repo_name
stringlengths
7
94
repo_path
stringlengths
4
237
repo_head_hexsha
stringlengths
40
40
content
stringlengths
10
680k
apis
stringlengths
2
680k
scmarquez/Hause-Price-Kaggle-Competition
analisis_de_variables.py
5fe32fed87a7bf2c6e5f41761ea1c4dd00761f21
# -*- coding: utf-8 -*- """ Created on Fri Dec 29 16:40:53 2017 @author: Sergio """ #Analisis de variables import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import ensemble, tree, linear_model from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import r2_score, mean_squared_error from sklearn.utils import shuffle import warnings #Ignorar los warnings warnings.filterwarnings('ignore') #Lectura de los datos #En train se guandan los datos con los que se entrenará al modelo train = pd.read_csv('train.csv') #En test se guarda el conjunto de datos para el test test = pd.read_csv('test.csv') #Primero hay que eliminar las varibles que tengan un número alto de valores perdidos #El número de valores perdidos de cada conjunto en cada variable NAs = pd.concat([train.isnull().sum()/1460, test.isnull().sum()/1459], axis=1, keys=['Train', 'Test']) #print(NAs) #Eliminar todas las variables que tengan más de un 0.2 de valores perdidos eliminar = [] nvars = 0 for index, row in NAs.iterrows(): print(index) print(row['Test']) if (row['Test'] > 0.2) or (row ['Train'] > 0.2): eliminar.append(index) #En la variable eliminar estan los nombres de las variables que deben ser directamente eliminadas #Dentro de las variables a eliminar encontramos que la variable de Alley NA no indica desconocido, es un posible valor más de los posibles a tomar #Esa variable debe seguir estando en nuestro conjunto print(eliminar) eliminar.remove('Alley') eliminar.remove('FireplaceQu')#Sucede lo mismo que con Alley train.drop(eliminar,axis=1, inplace=True) test.drop(eliminar,axis=1, inplace=True) """ Ahora es necesario un análisis más profundo de las variables. En primer lugar encontramos algunas variables que parecen tener una representación numérica, como por ejemplo 'MSSubClass' o 'OverallCond'. Al leer la documentación sobre que información aportan las variables encontramos que OverallCond aunque sea una variable aparentemente nominal expresa cosas que son medibles como la calidad, es decir muestra una puntuación entre 1 y 10 """ #Variables numéricas que deben ser transformadas a string test['MSSubClass'] = test['MSSubClass'].astype(str) train['MSSubClass'] = train['MSSubClass'].astype(str) test['YrSold'] = test['YrSold'].astype(str) train['YrSold'] = train['YrSold'].astype(str) #Variables categóricas que deben ser numéricas, ya que expresan puntuación #El lógico pensar que aumentar la puntuación en algo hace efecto directo en el precio final ExterQualvalues = {'ExterQual':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1}} ExterCondvalues = {'ExterCond':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1}} BsmQualvalues = {'BsmtQual':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1}} BsmCondvalues = {'BsmtCond':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1,}} HeatingQCvalues = {'HeatingQC':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1}} KitchenQualvalues = {'KitchenQual':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1}} FireplaceQuvalues = {'FireplaceQu':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1}} GarageCondvalues = {'GarageCond':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1}} GarageQualvalues = {'GarageQual':{'Ex':5,'Gd':4,'TA':3,'Fa':2,'Po':1}} PoolQCvalues = {'PoolQC':{'Ex':4,'Gd':3,'TA':2,'Fa':1}} #Reemplazar los valores en las tablas train.replace(ExterQualvalues,inplace=True) train.replace(ExterCondvalues,inplace=True) train.replace(BsmQualvalues,inplace=True) train.replace(BsmCondvalues,inplace=True) train.replace(HeatingQCvalues,inplace=True) train.replace(KitchenQualvalues,inplace=True) train.replace(FireplaceQuvalues,inplace=True) train.replace(GarageCondvalues,inplace=True) train.replace(GarageQualvalues,inplace=True) train.replace(PoolQCvalues,inplace=True) test.replace(ExterQualvalues,inplace=True) test.replace(ExterCondvalues,inplace=True) test.replace(BsmQualvalues,inplace=True) test.replace(BsmCondvalues,inplace=True) test.replace(HeatingQCvalues,inplace=True) test.replace(KitchenQualvalues,inplace=True) test.replace(FireplaceQuvalues,inplace=True) test.replace(GarageCondvalues,inplace=True) test.replace(GarageQualvalues,inplace=True) test.replace(PoolQCvalues,inplace=True) #Ahora tenemos todas las variables con un tipo de dato 'correcto' #Cuantas variables de cada tipo tenemos train_labels = train.pop('SalePrice') features = pd.concat([train, test], keys=['train', 'test']) enteras = features.dtypes[features.dtypes == 'int64'].index flotantes = features.dtypes[features.dtypes == 'float64'].index nominales = features.dtypes[features.dtypes == 'object'].index #Se pasa a formato lista para su uso ent = [] for var in enteras: ent.append(var) flot = [] for var in flotantes: flot.append(var) nom = [] for var in nominales: nom.append(var) numericas = ent+flot #Ahora es necesario rellenar los valores perdidos de cada variable. """En algunas de las variables que han sido transformadas a numéricas NAN no expresa que el dato no exista, sino que expresa puntuación 0""" features['BsmtQual'] = features['BsmtQual'].fillna(0) features['BsmtCond'] = features['BsmtCond'].fillna(0) features['FireplaceQu'] = features['FireplaceQu'].fillna(0) features['GarageQual'] = features['GarageQual'].fillna(0) features['GarageCond'] = features['GarageCond'].fillna(0) #El resto de variables pueden rellenarse con la media for var in numericas: if features[var].isnull().sum() > 0: features[var] = features[var].fillna(features[var].mean()) #El resto ce variables nomnales se rellenan con el valor más frecuente for var in nominales: if features[var].isnull().sum() > 0: features[var] = features[var].fillna(features[var].mode()[0]) """Una vez que la tabla de datos está en el formato correcto vamos a estudiar la correlación de las variables con el precio. Las variables que presenten una correlación baja se descartarán ya que lo único que van a hacer es hacer que nuestro modelo se impreciso. Si se imputan demasiadas variables perderemos información valiosa y el modelo volverá a ser impreciso. Sacando un Heatmap se puede ver la correlación de las variables""" #train_labels = np.log(train_labels)#La transformación logarítmica de los datos los aproxima a una distribución normal complete = features.loc['train']#Solo se usan las entradas de entrenamiento complete = pd.concat([complete,train_labels],axis=1)#Se adjunta la columna de precios de nuevo correlationPlot = complete.corr()#Mantiene la matriz de correlación en un DataFrame f,ax = plt.subplots(figsize=(12,9))#Configuración del tamaño de la imagen sns.heatmap(correlationPlot,vmax=.8,square=True)#Crea el heatmap con los valores de correlación plt.yticks(rotation=0)#cambia el eje de las etiquetas del gráfico para que se vean bien plt.xticks(rotation=90)#cambia el eje de las etiquetas del gráfico para que se vean bien plt.show()#Muestra el gráfico f.savefig('Heatmap.png')#Guarda el gráfico en un archivo """La matriz de correlación muestra la correlación entre dos variables de forma que los valores más claros muestran que dos variables tienen una correlación alta El siguiente paso del análisis es buscar que variables muestran una correlación alta entre sí y eliminar una de esas variables, ya que es información redundante y puede eliminarse. Otra manera de enfocar el problema es que usar dos variables correlacionadas puede ayudar a sofocar el efecto del ruido en una variable. En primer lugar es necesario descubrir que variables son las que determinan el precio de la vivienda usando la correlación. """ #Crear la lista de variables con correlación alta con el precio de la vivienda """Inciso: calcular la correlación antes de aplicar la escala logaritmica a los datos tiene sentido, pues el coeficiente de correlación de Pearson no varía con la escala y el origen. Además solo nos sirve para hacer una aproximación hacia que variables usar o no en el algoritmo. Después si será necesario hacer que las variables tengan una distribución normalizada. """ HighCorrelation = [] for index, row in correlationPlot.iterrows(): if (row['SalePrice'] >= 0.5) or (row ['SalePrice'] <= -0.5): HighCorrelation.append(index) print(row['SalePrice']) print("total de variables: "+str(len(HighCorrelation))) print(HighCorrelation) """Ahora hay que examniar las variables nominales que se tendrán en cuenta Para hacer este análisis se va a usar una gráfica que exprese la relación entre el precio y el valor de la vivienda.""" complete = features.loc['train'] complete = pd.concat([complete,train_labels],axis=1) malas = [#'MSSubClass', 'LandContour', 'LandSlope', #'RoofStyle', #'RoofMatl', 'Exterior2nd', #'Exterior1st', 'MasVnrType', 'BsmtExposure', 'Functional', 'YrSold'] ################################## #malas = ['Utilities', 'RoofMatl','Heating','Functional'] for var in malas: data = pd.concat([complete[var],complete['SalePrice']],axis=1) f,ax = plt.subplots(figsize=(12,9)) fig = sns.boxplot(x=var,y="SalePrice",data=data) fig.axis(ymin=0,ymax=800000) plt.xticks(rotation=90) f.savefig(str(var)+'_Price.png') """ aparentemente malas variables: LandContour LandScope RoofStyle RoofMatl Exterior2nd Exterior1st MasVnrType BsmtExposure Functional YrSold """ """Analisis con PCA"""
[((470, 503), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (493, 503), False, 'import warnings\n'), ((605, 629), 'pandas.read_csv', 'pd.read_csv', (['"""train.csv"""'], {}), "('train.csv')\n", (616, 629), True, 'import pandas as pd\n'), ((692, 715), 'pandas.read_csv', 'pd.read_csv', (['"""test.csv"""'], {}), "('test.csv')\n", (703, 715), True, 'import pandas as pd\n'), ((4424, 4472), 'pandas.concat', 'pd.concat', (['[train, test]'], {'keys': "['train', 'test']"}), "([train, test], keys=['train', 'test'])\n", (4433, 4472), True, 'import pandas as pd\n'), ((6417, 6460), 'pandas.concat', 'pd.concat', (['[complete, train_labels]'], {'axis': '(1)'}), '([complete, train_labels], axis=1)\n', (6426, 6460), True, 'import pandas as pd\n'), ((6596, 6625), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 9)'}), '(figsize=(12, 9))\n', (6608, 6625), True, 'import matplotlib.pyplot as plt\n'), ((6664, 6715), 'seaborn.heatmap', 'sns.heatmap', (['correlationPlot'], {'vmax': '(0.8)', 'square': '(True)'}), '(correlationPlot, vmax=0.8, square=True)\n', (6675, 6715), True, 'import seaborn as sns\n'), ((6761, 6783), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'rotation': '(0)'}), '(rotation=0)\n', (6771, 6783), True, 'import matplotlib.pyplot as plt\n'), ((6850, 6873), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (6860, 6873), True, 'import matplotlib.pyplot as plt\n'), ((6940, 6950), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6948, 6950), True, 'import matplotlib.pyplot as plt\n'), ((8632, 8675), 'pandas.concat', 'pd.concat', (['[complete, train_labels]'], {'axis': '(1)'}), '([complete, train_labels], axis=1)\n', (8641, 8675), True, 'import pandas as pd\n'), ((8982, 9039), 'pandas.concat', 'pd.concat', (["[complete[var], complete['SalePrice']]"], {'axis': '(1)'}), "([complete[var], complete['SalePrice']], axis=1)\n", (8991, 9039), True, 'import pandas as pd\n'), ((9047, 9076), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 9)'}), '(figsize=(12, 9))\n', (9059, 9076), True, 'import matplotlib.pyplot as plt\n'), ((9084, 9128), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': 'var', 'y': '"""SalePrice"""', 'data': 'data'}), "(x=var, y='SalePrice', data=data)\n", (9095, 9128), True, 'import seaborn as sns\n'), ((9160, 9183), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '(90)'}), '(rotation=90)\n', (9170, 9183), True, 'import matplotlib.pyplot as plt\n')]
mdatsev/prostgres
query-gen.py
3418258a8b832546ef4d5009867bf1cf79248b7b
import random import sys ntables = 100 ncols = 100 nrows = 10000 def printstderr(s): sys.stderr.write(s + '\n') sys.stderr.flush() def get_value(): return random.randint(-99999999, 99999999) for t in range(ntables): printstderr(f'{t}/{ntables}') print(f"create table x ({','.join(['x int'] * ncols)});") for r in range(nrows): print(f"insert into _last ({','.join(['x'] * ncols)}) values (", end='') for c in range(ncols): print(get_value(), end=('' if c==ncols-1 else ',')) print(');') # 10 min to generate # 3 min to process
[((89, 115), 'sys.stderr.write', 'sys.stderr.write', (["(s + '\\n')"], {}), "(s + '\\n')\n", (105, 115), False, 'import sys\n'), ((118, 136), 'sys.stderr.flush', 'sys.stderr.flush', ([], {}), '()\n', (134, 136), False, 'import sys\n'), ((164, 199), 'random.randint', 'random.randint', (['(-99999999)', '(99999999)'], {}), '(-99999999, 99999999)\n', (178, 199), False, 'import random\n')]
joshbenner/sensu-ansible-role
molecule/default/tests/test_default.py
ecc92ba3462d7edf50ad96ddda61080ba58c29f8
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_packages(host): package = host.package('sensu') assert package.is_installed assert '1.7.0' in package.version def test_dir_ownership(host): assert host.file('/opt/sensu').group == 'sensu' def test_main_config(host): f = host.file('/etc/sensu/config.json') assert f.exists assert f.is_file assert f.user == 'sensu' assert f.group == 'sensu' assert f.mode == 0o600 assert f.contains('rabbitmq') assert f.contains('check-cpu.rb') assert f.contains('"foo": "bar"') assert f.contains('example_subscription') assert f.contains('"zip": "zap"') assert not f.contains('subscription_to_be_overridden') def test_server_running(host): server = host.service('sensu-server') assert server.is_running assert server.is_enabled def test_api_running(host): api = host.service('sensu-api') assert api.is_running assert api.is_enabled def test_client_running(host): client = host.service('sensu-client') assert client.is_running assert client.is_enabled def test_api_listening(host): assert host.socket('tcp://0.0.0.0:4567').is_listening def test_plugin_installed(host): assert host.file('/opt/sensu/embedded/bin/check-memory.rb').exists # Tests extension install/enable def test_snmp_listening(host): assert host.socket('udp://0.0.0.0:1062').is_listening
[]
moepman/wgskex
wgskex/worker/netlink.py
7a931088b5910f8034ad5a1362777e08c47c42fe
import hashlib import logging import re from dataclasses import dataclass from datetime import datetime, timedelta from textwrap import wrap from typing import Dict, List from pyroute2 import IPRoute, NDB, WireGuard from wgskex.common.utils import mac2eui64 logger = logging.getLogger(__name__) # TODO make loglevel configurable logger.setLevel("DEBUG") @dataclass class WireGuardClient: public_key: str domain: str remove: bool @property def lladdr(self) -> str: m = hashlib.md5() m.update(self.public_key.encode("ascii") + b"\n") hashed_key = m.hexdigest() hash_as_list = wrap(hashed_key, 2) temp_mac = ":".join(["02"] + hash_as_list[:5]) lladdr = re.sub(r"/\d+$", "/128", mac2eui64(mac=temp_mac, prefix="fe80::/10")) return lladdr @property def vx_interface(self) -> str: return f"vx-{self.domain}" @property def wg_interface(self) -> str: return f"wg-{self.domain}" """WireGuardClient describes complete configuration for a specific WireGuard client Attributes: public_key: WireGuard Public key domain: Domain Name of the WireGuard peer lladdr: IPv6 lladdr of the WireGuard peer wg_interface: Name of the WireGuard interface this peer will use vx_interface: Name of the VXLAN interface we set a route for the lladdr to remove: Are we removing this peer or not? """ def wg_flush_stale_peers(domain: str) -> List[Dict]: stale_clients = find_stale_wireguard_clients("wg-" + domain) result = [] for stale_client in stale_clients: stale_wireguard_client = WireGuardClient( public_key=stale_client, domain=domain, remove=True, ) result.append(link_handler(stale_wireguard_client)) return result # pyroute2 stuff def link_handler(client: WireGuardClient) -> Dict[str, Dict]: results = {} results.update({"Wireguard": wireguard_handler(client)}) try: results.update({"Route": route_handler(client)}) except Exception as e: results.update({"Route": {"Exception": e}}) results.update({"Bridge FDB": bridge_fdb_handler(client)}) return results def bridge_fdb_handler(client: WireGuardClient) -> Dict: with IPRoute() as ip: return ip.fdb( "del" if client.remove else "append", # FIXME this list may be empty if the interface is not existing ifindex=ip.link_lookup(ifname=client.vx_interface)[0], lladdr="00:00:00:00:00:00", dst=re.sub(r"/\d+$", "", client.lladdr), nda_ifindex=ip.link_lookup(ifname=client.wg_interface)[0], ) def wireguard_handler(client: WireGuardClient) -> Dict: with WireGuard() as wg: wg_peer = { "public_key": client.public_key, "persistent_keepalive": 15, "allowed_ips": [client.lladdr], "remove": client.remove, } return wg.set(client.wg_interface, peer=wg_peer) def route_handler(client: WireGuardClient) -> Dict: with IPRoute() as ip: return ip.route( "del" if client.remove else "replace", dst=client.lladdr, oif=ip.link_lookup(ifname=client.wg_interface)[0], ) def find_wireguard_domains() -> List[str]: with NDB() as ndb: # ndb.interfaces[{"kind": "wireguard"}]] seems to trigger https://github.com/svinota/pyroute2/issues/737 iface_values = ndb.interfaces.values() interfaces = [iface.get("ifname", "") for iface in iface_values if iface.get("kind", "") == "wireguard"] result = [iface.removeprefix("wg-") for iface in interfaces if iface.startswith("wg-")] return result def find_stale_wireguard_clients(wg_interface: str) -> List[str]: with WireGuard() as wg: all_clients = [] infos = wg.info(wg_interface) for info in infos: clients = info.get_attr("WGDEVICE_A_PEERS") if clients is not None: all_clients.extend(clients) three_minutes_ago = (datetime.now() - timedelta(minutes=3)).timestamp() stale_clients = [ client.get_attr("WGPEER_A_PUBLIC_KEY").decode("utf-8") for client in all_clients # TODO add never connected peers to a list and remove them on next call if 0 < (client.get_attr("WGPEER_A_LAST_HANDSHAKE_TIME") or {}).get("tv_sec", int()) < three_minutes_ago ] return stale_clients
[((270, 297), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (287, 297), False, 'import logging\n'), ((502, 515), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (513, 515), False, 'import hashlib\n'), ((633, 652), 'textwrap.wrap', 'wrap', (['hashed_key', '(2)'], {}), '(hashed_key, 2)\n', (637, 652), False, 'from textwrap import wrap\n'), ((2307, 2316), 'pyroute2.IPRoute', 'IPRoute', ([], {}), '()\n', (2314, 2316), False, 'from pyroute2 import IPRoute, NDB, WireGuard\n'), ((2781, 2792), 'pyroute2.WireGuard', 'WireGuard', ([], {}), '()\n', (2790, 2792), False, 'from pyroute2 import IPRoute, NDB, WireGuard\n'), ((3118, 3127), 'pyroute2.IPRoute', 'IPRoute', ([], {}), '()\n', (3125, 3127), False, 'from pyroute2 import IPRoute, NDB, WireGuard\n'), ((3369, 3374), 'pyroute2.NDB', 'NDB', ([], {}), '()\n', (3372, 3374), False, 'from pyroute2 import IPRoute, NDB, WireGuard\n'), ((3853, 3864), 'pyroute2.WireGuard', 'WireGuard', ([], {}), '()\n', (3862, 3864), False, 'from pyroute2 import IPRoute, NDB, WireGuard\n'), ((751, 794), 'wgskex.common.utils.mac2eui64', 'mac2eui64', ([], {'mac': 'temp_mac', 'prefix': '"""fe80::/10"""'}), "(mac=temp_mac, prefix='fe80::/10')\n", (760, 794), False, 'from wgskex.common.utils import mac2eui64\n'), ((2596, 2631), 're.sub', 're.sub', (['"""/\\\\d+$"""', '""""""', 'client.lladdr'], {}), "('/\\\\d+$', '', client.lladdr)\n", (2602, 2631), False, 'import re\n'), ((4129, 4143), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4141, 4143), False, 'from datetime import datetime, timedelta\n'), ((4146, 4166), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(3)'}), '(minutes=3)\n', (4155, 4166), False, 'from datetime import datetime, timedelta\n')]
Ju99ernaut/super-fastapi
api/main.py
83c232bcaff1006d413a9945ced3ba398b673505
import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from routes import items import config from constants import * config.parse_args() app = FastAPI( title="API", description="API boilerplate", version="1.0.0", openapi_tags=API_TAGS_METADATA, ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(items.router) @app.get("/") async def root(): return { "docs": "api documentation at /docs or /redoc", } if __name__ == "__main__": uvicorn.run("main:app", host=config.CONFIG.host, port=int(config.CONFIG.port))
[((161, 180), 'config.parse_args', 'config.parse_args', ([], {}), '()\n', (178, 180), False, 'import config\n'), ((187, 291), 'fastapi.FastAPI', 'FastAPI', ([], {'title': '"""API"""', 'description': '"""API boilerplate"""', 'version': '"""1.0.0"""', 'openapi_tags': 'API_TAGS_METADATA'}), "(title='API', description='API boilerplate', version='1.0.0',\n openapi_tags=API_TAGS_METADATA)\n", (194, 291), False, 'from fastapi import FastAPI\n')]
vallka/djellifique
gellifinsta/models.py
fb84fba6be413f9d38276d89ae84aeaff761218f
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.html import mark_safe # Create your models here. class Gellifinsta(models.Model): class Meta: ordering = ['-taken_at_datetime'] shortcode = models.CharField(_("Shortcode"), max_length=20) taken_at_datetime = models.DateTimeField(_("taken at")) username = models.CharField(_("Username"), max_length=100) is_active = models.BooleanField(_("Active"),default=True) is_video = models.BooleanField(_("Video"),default=False) file_path = models.CharField(_("File Path"), max_length=500) url = models.CharField(_("URL"), max_length=500) created_dt = models.DateTimeField(_("Created Date/Time"), auto_now_add=True, null=True) updated_dt = models.DateTimeField(_("Updated Date/Time"), auto_now=True, null=True) caption = models.TextField(_("Caption"), blank=True, null=True) tags = models.TextField(_("Tags"), blank=True, null=True) def __str__(self): return self.shortcode + ':' + str(self.taken_at_datetime) def image_tag(self): return mark_safe('<img src="%s" width="250" />' % (self.url)) image_tag.short_description = 'Image' def tags_spaced(self): return self.tags.replace(',',' ') tags_spaced.short_description = 'Tags' class Products(models.Model): class Meta: ordering = ['name'] name = models.CharField(_("Name"), max_length=100, unique=True) is_active = models.BooleanField(_("Active"),default=True) def __str__(self): return self.name
[((279, 293), 'django.utils.translation.ugettext_lazy', '_', (['"""Shortcode"""'], {}), "('Shortcode')\n", (280, 293), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((355, 368), 'django.utils.translation.ugettext_lazy', '_', (['"""taken at"""'], {}), "('taken at')\n", (356, 368), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((402, 415), 'django.utils.translation.ugettext_lazy', '_', (['"""Username"""'], {}), "('Username')\n", (403, 415), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((469, 480), 'django.utils.translation.ugettext_lazy', '_', (['"""Active"""'], {}), "('Active')\n", (470, 480), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((530, 540), 'django.utils.translation.ugettext_lazy', '_', (['"""Video"""'], {}), "('Video')\n", (531, 540), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((589, 603), 'django.utils.translation.ugettext_lazy', '_', (['"""File Path"""'], {}), "('File Path')\n", (590, 603), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((648, 656), 'django.utils.translation.ugettext_lazy', '_', (['"""URL"""'], {}), "('URL')\n", (649, 656), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((712, 734), 'django.utils.translation.ugettext_lazy', '_', (['"""Created Date/Time"""'], {}), "('Created Date/Time')\n", (713, 734), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((804, 826), 'django.utils.translation.ugettext_lazy', '_', (['"""Updated Date/Time"""'], {}), "('Updated Date/Time')\n", (805, 826), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((885, 897), 'django.utils.translation.ugettext_lazy', '_', (['"""Caption"""'], {}), "('Caption')\n", (886, 897), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((950, 959), 'django.utils.translation.ugettext_lazy', '_', (['"""Tags"""'], {}), "('Tags')\n", (951, 959), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1115, 1168), 'django.utils.html.mark_safe', 'mark_safe', (['(\'<img src="%s" width="250" />\' % self.url)'], {}), '(\'<img src="%s" width="250" />\' % self.url)\n', (1124, 1168), False, 'from django.utils.html import mark_safe\n'), ((1431, 1440), 'django.utils.translation.ugettext_lazy', '_', (['"""Name"""'], {}), "('Name')\n", (1432, 1440), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1507, 1518), 'django.utils.translation.ugettext_lazy', '_', (['"""Active"""'], {}), "('Active')\n", (1508, 1518), True, 'from django.utils.translation import ugettext_lazy as _\n')]
wsqy/sacn_server
scanBase/migrations/0003_ipsection.py
e91a41a71b27926fbcfbe3f22bbb6bbc61b39461
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-16 13:35 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('scanBase', '0002_auto_20180116_1321'), ] operations = [ migrations.CreateModel( name='IPSection', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ip_section', models.CharField(blank=True, max_length=30, null=True, unique=True, verbose_name='ip段')), ('ip_start', models.GenericIPAddressField(blank=True, null=True, verbose_name='开始ip')), ('ip_end', models.GenericIPAddressField(blank=True, null=True, verbose_name='结束ip')), ('total', models.IntegerField(blank=True, null=True, verbose_name='总量')), ('deal_time', models.DateTimeField(blank=True, null=True, verbose_name='处理时间')), ('country', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scanBase.CountryInfo', verbose_name='所属国家')), ], options={ 'verbose_name_plural': 'ip段信息', 'verbose_name': 'ip段信息', }, ), ]
[((430, 523), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (446, 523), False, 'from django.db import migrations, models\n'), ((553, 644), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(30)', 'null': '(True)', 'unique': '(True)', 'verbose_name': '"""ip段"""'}), "(blank=True, max_length=30, null=True, unique=True,\n verbose_name='ip段')\n", (569, 644), False, 'from django.db import migrations, models\n'), ((672, 744), 'django.db.models.GenericIPAddressField', 'models.GenericIPAddressField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""开始ip"""'}), "(blank=True, null=True, verbose_name='开始ip')\n", (700, 744), False, 'from django.db import migrations, models\n'), ((774, 846), 'django.db.models.GenericIPAddressField', 'models.GenericIPAddressField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""结束ip"""'}), "(blank=True, null=True, verbose_name='结束ip')\n", (802, 846), False, 'from django.db import migrations, models\n'), ((875, 936), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""总量"""'}), "(blank=True, null=True, verbose_name='总量')\n", (894, 936), False, 'from django.db import migrations, models\n'), ((969, 1033), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""处理时间"""'}), "(blank=True, null=True, verbose_name='处理时间')\n", (989, 1033), False, 'from django.db import migrations, models\n'), ((1064, 1179), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""scanBase.CountryInfo"""', 'verbose_name': '"""所属国家"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'scanBase.CountryInfo', verbose_name='所属国家')\n", (1081, 1179), False, 'from django.db import migrations, models\n')]
LostCow/KLUE
sts/train.py
73b1b0526cf6b1b6f5ef535b9527d8abe6ca1a77
import argparse import numpy as np import os import torch from transformers import AutoTokenizer, AutoConfig, Trainer, TrainingArguments from model import RobertaForStsRegression from dataset import KlueStsWithSentenceMaskDataset from utils import read_json, seed_everything from metric import compute_metrics def main(args): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") config = AutoConfig.from_pretrained(args.model_name_or_path) config.num_labels = args.num_labels tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) train_file_path = os.path.join(args.data_dir, args.train_filename) valid_file_path = os.path.join(args.data_dir, args.valid_filename) train_json = read_json(train_file_path) valid_json = read_json(valid_file_path) train_dataset = KlueStsWithSentenceMaskDataset(train_json, tokenizer, 510) valid_dataset = KlueStsWithSentenceMaskDataset(train_json, tokenizer, 510) model = RobertaForStsRegression.from_pretrained( args.model_name_or_path, config=config ) model.to(device) training_args = TrainingArguments( output_dir=args.model_dir, save_total_limit=args.save_total_limit, save_steps=args.save_steps, num_train_epochs=args.num_train_epochs, learning_rate=args.learning_rate, per_device_train_batch_size=args.batch_size, per_device_eval_batch_size=64, gradient_accumulation_steps=args.gradient_accumulation_steps, weight_decay=args.weight_decay, logging_dir="./logs", logging_steps=args.save_steps, evaluation_strategy=args.evaluation_strategy, metric_for_best_model="pearsonr", fp16=True, fp16_opt_level="O1", eval_steps=args.save_steps, load_best_model_at_end=True, ) trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=valid_dataset, compute_metrics=compute_metrics, ) trainer.train() model.save_pretrained(args.model_dir) tokenizer.save_pretrained(args.model_dir) if __name__ == "__main__": parser = argparse.ArgumentParser() # data_arg parser.add_argument("--data_dir", type=str, default="./data") parser.add_argument("--model_dir", type=str, default="./model") parser.add_argument("--output_dir", type=str, default="./output") parser.add_argument("--model_name_or_path", type=str, default="klue/roberta-large") parser.add_argument( "--train_filename", type=str, default="klue-sts-v1.1_train.json" ) parser.add_argument("--valid_filename", type=str, default="klue-sts-v1.1_dev.json") # train_arg parser.add_argument("--num_labels", type=int, default=1) parser.add_argument("--seed", type=int, default=15) parser.add_argument("--num_train_epochs", type=int, default=5) parser.add_argument("--batch_size", type=int, default=64) parser.add_argument("--learning_rate", type=float, default=5e-5) parser.add_argument("--gradient_accumulation_steps", type=int, default=1) parser.add_argument("--weight_decay", type=float, default=0.01) # eval_arg parser.add_argument("--evaluation_strategy", type=str, default="steps") parser.add_argument("--save_steps", type=int, default=250) parser.add_argument("--eval_steps", type=int, default=250) parser.add_argument("--save_total_limit", type=int, default=2) args = parser.parse_args() main(args)
[((419, 470), 'transformers.AutoConfig.from_pretrained', 'AutoConfig.from_pretrained', (['args.model_name_or_path'], {}), '(args.model_name_or_path)\n', (445, 470), False, 'from transformers import AutoTokenizer, AutoConfig, Trainer, TrainingArguments\n'), ((527, 581), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['args.model_name_or_path'], {}), '(args.model_name_or_path)\n', (556, 581), False, 'from transformers import AutoTokenizer, AutoConfig, Trainer, TrainingArguments\n'), ((605, 653), 'os.path.join', 'os.path.join', (['args.data_dir', 'args.train_filename'], {}), '(args.data_dir, args.train_filename)\n', (617, 653), False, 'import os\n'), ((676, 724), 'os.path.join', 'os.path.join', (['args.data_dir', 'args.valid_filename'], {}), '(args.data_dir, args.valid_filename)\n', (688, 724), False, 'import os\n'), ((743, 769), 'utils.read_json', 'read_json', (['train_file_path'], {}), '(train_file_path)\n', (752, 769), False, 'from utils import read_json, seed_everything\n'), ((787, 813), 'utils.read_json', 'read_json', (['valid_file_path'], {}), '(valid_file_path)\n', (796, 813), False, 'from utils import read_json, seed_everything\n'), ((835, 893), 'dataset.KlueStsWithSentenceMaskDataset', 'KlueStsWithSentenceMaskDataset', (['train_json', 'tokenizer', '(510)'], {}), '(train_json, tokenizer, 510)\n', (865, 893), False, 'from dataset import KlueStsWithSentenceMaskDataset\n'), ((914, 972), 'dataset.KlueStsWithSentenceMaskDataset', 'KlueStsWithSentenceMaskDataset', (['train_json', 'tokenizer', '(510)'], {}), '(train_json, tokenizer, 510)\n', (944, 972), False, 'from dataset import KlueStsWithSentenceMaskDataset\n'), ((986, 1065), 'model.RobertaForStsRegression.from_pretrained', 'RobertaForStsRegression.from_pretrained', (['args.model_name_or_path'], {'config': 'config'}), '(args.model_name_or_path, config=config)\n', (1025, 1065), False, 'from model import RobertaForStsRegression\n'), ((1122, 1736), 'transformers.TrainingArguments', 'TrainingArguments', ([], {'output_dir': 'args.model_dir', 'save_total_limit': 'args.save_total_limit', 'save_steps': 'args.save_steps', 'num_train_epochs': 'args.num_train_epochs', 'learning_rate': 'args.learning_rate', 'per_device_train_batch_size': 'args.batch_size', 'per_device_eval_batch_size': '(64)', 'gradient_accumulation_steps': 'args.gradient_accumulation_steps', 'weight_decay': 'args.weight_decay', 'logging_dir': '"""./logs"""', 'logging_steps': 'args.save_steps', 'evaluation_strategy': 'args.evaluation_strategy', 'metric_for_best_model': '"""pearsonr"""', 'fp16': '(True)', 'fp16_opt_level': '"""O1"""', 'eval_steps': 'args.save_steps', 'load_best_model_at_end': '(True)'}), "(output_dir=args.model_dir, save_total_limit=args.\n save_total_limit, save_steps=args.save_steps, num_train_epochs=args.\n num_train_epochs, learning_rate=args.learning_rate,\n per_device_train_batch_size=args.batch_size, per_device_eval_batch_size\n =64, gradient_accumulation_steps=args.gradient_accumulation_steps,\n weight_decay=args.weight_decay, logging_dir='./logs', logging_steps=\n args.save_steps, evaluation_strategy=args.evaluation_strategy,\n metric_for_best_model='pearsonr', fp16=True, fp16_opt_level='O1',\n eval_steps=args.save_steps, load_best_model_at_end=True)\n", (1139, 1736), False, 'from transformers import AutoTokenizer, AutoConfig, Trainer, TrainingArguments\n'), ((1859, 1993), 'transformers.Trainer', 'Trainer', ([], {'model': 'model', 'args': 'training_args', 'train_dataset': 'train_dataset', 'eval_dataset': 'valid_dataset', 'compute_metrics': 'compute_metrics'}), '(model=model, args=training_args, train_dataset=train_dataset,\n eval_dataset=valid_dataset, compute_metrics=compute_metrics)\n', (1866, 1993), False, 'from transformers import AutoTokenizer, AutoConfig, Trainer, TrainingArguments\n'), ((2187, 2212), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2210, 2212), False, 'import argparse\n'), ((368, 393), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (391, 393), False, 'import torch\n')]
walkr/nanoservice
test/test_base_client.py
e2098986b1baa5f283167ae487d14f3c6c21961a
import unittest from nanoservice import Responder from nanoservice import Requester class BaseTestCase(unittest.TestCase): def setUp(self): addr = 'inproc://test' self.client = Requester(addr) self.service = Responder(addr) self.service.register('divide', lambda x, y: x / y) self.service.register('echo', lambda x: x) def tearDown(self): self.client.socket.close() self.service.socket.close() class TestClient(BaseTestCase): def test_build_payload(self): payload = self.client.build_payload('echo', 'My Name') method, args, ref = payload self.assertTrue(method == 'echo') self.assertTrue(len(payload) == 3) def test_encoder(self): data = {'name': 'Joe Doe'} encoded = self.client.encode(data) decoded = self.client.decode(encoded) self.assertEqual(data, decoded) def test_call_wo_receive(self): # Requester side ops method, args = 'echo', 'hello world' payload = self.client.build_payload(method, args) self.client.socket.send(self.client.encode(payload)) # Responder side ops method, args, ref = self.service.receive() self.assertEqual(method, 'echo') self.assertEqual(args, 'hello world') self.assertEqual(ref, payload[2]) def test_basic_socket_operation(self): msg = 'abc' self.client.socket.send(msg) res = self.service.socket.recv().decode('utf-8') self.assertEqual(msg, res) def test_timeout(self): c = Requester('inproc://timeout', timeouts=(1, 1)) c.socket.send('hello') self.assertRaises(Exception, c.socket.recv) if __name__ == '__main__': unittest.main()
[((1744, 1759), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1757, 1759), False, 'import unittest\n'), ((201, 216), 'nanoservice.Requester', 'Requester', (['addr'], {}), '(addr)\n', (210, 216), False, 'from nanoservice import Requester\n'), ((240, 255), 'nanoservice.Responder', 'Responder', (['addr'], {}), '(addr)\n', (249, 255), False, 'from nanoservice import Responder\n'), ((1582, 1628), 'nanoservice.Requester', 'Requester', (['"""inproc://timeout"""'], {'timeouts': '(1, 1)'}), "('inproc://timeout', timeouts=(1, 1))\n", (1591, 1628), False, 'from nanoservice import Requester\n')]
chidioguejiofor/airtech-api
airtech_api/flight/models.py
45d77da0cc4230dd3cb7ab4cbb5168a9239850f5
from airtech_api.utils.auditable_model import AuditableBaseModel from django.db import models # Create your models here. class Flight(AuditableBaseModel): class Meta: db_table = 'Flight' capacity = models.IntegerField(null=False) location = models.TextField(null=False) destination = models.TextField(null=False) schedule = models.DateTimeField(null=False) current_price = models.IntegerField() type = models.CharField( choices=(('local', 'local'), ('international', 'international')), max_length=13, )
[((217, 248), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(False)'}), '(null=False)\n', (236, 248), False, 'from django.db import models\n'), ((264, 292), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(False)'}), '(null=False)\n', (280, 292), False, 'from django.db import models\n'), ((311, 339), 'django.db.models.TextField', 'models.TextField', ([], {'null': '(False)'}), '(null=False)\n', (327, 339), False, 'from django.db import models\n'), ((355, 387), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'null': '(False)'}), '(null=False)\n', (375, 387), False, 'from django.db import models\n'), ((408, 429), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (427, 429), False, 'from django.db import models\n'), ((442, 543), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "(('local', 'local'), ('international', 'international'))", 'max_length': '(13)'}), "(choices=(('local', 'local'), ('international',\n 'international')), max_length=13)\n", (458, 543), False, 'from django.db import models\n')]
kaka-lin/autonomous-driving-notes
Sensor Fusion and Tracking/Kalman Filters/Gaussian/gaussian.py
6c1b29752d6deb679637766b6cea5c6fe5b72319
import numpy as np import matplotlib.pyplot as plt def gaussian(x, mean, std): std2 = np.power(std, 2) return (1 / np.sqrt(2* np.pi * std2)) * np.exp(-.5 * (x - mean)**2 / std2) if __name__ == "__main__": gauss_1 = gaussian(10, 8, 2) # 0.12098536225957168 gauss_2 = gaussian(10, 10, 2) # 0.19947114020071635 print("Gauss(10, 8, 2): {}".format(gauss_1)) print("Gauss(10, 10, 2): {}".format(gauss_2)) # 標準高斯分佈 mean = 0 variance = 1 std = np.sqrt(variance) # Plot between -10 and 10 with .001 steps. x = np.arange(-5, 5, 0.001) gauss = [] for i in x: gauss.append(gaussian(i, mean, std)) gauss = np.array(gauss) plt.plot(x, gauss) plt.show()
[((92, 108), 'numpy.power', 'np.power', (['std', '(2)'], {}), '(std, 2)\n', (100, 108), True, 'import numpy as np\n'), ((482, 499), 'numpy.sqrt', 'np.sqrt', (['variance'], {}), '(variance)\n', (489, 499), True, 'import numpy as np\n'), ((556, 579), 'numpy.arange', 'np.arange', (['(-5)', '(5)', '(0.001)'], {}), '(-5, 5, 0.001)\n', (565, 579), True, 'import numpy as np\n'), ((668, 683), 'numpy.array', 'np.array', (['gauss'], {}), '(gauss)\n', (676, 683), True, 'import numpy as np\n'), ((689, 707), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'gauss'], {}), '(x, gauss)\n', (697, 707), True, 'import matplotlib.pyplot as plt\n'), ((712, 722), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (720, 722), True, 'import matplotlib.pyplot as plt\n'), ((153, 190), 'numpy.exp', 'np.exp', (['(-0.5 * (x - mean) ** 2 / std2)'], {}), '(-0.5 * (x - mean) ** 2 / std2)\n', (159, 190), True, 'import numpy as np\n'), ((125, 150), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi * std2)'], {}), '(2 * np.pi * std2)\n', (132, 150), True, 'import numpy as np\n')]
fazillatheef/lsbasi
part19/test_interpreter.py
07e1a14516156a21ebe2d82e0bae4bba5ad73dd6
import unittest class LexerTestCase(unittest.TestCase): def makeLexer(self, text): from spi import Lexer lexer = Lexer(text) return lexer def test_tokens(self): from spi import TokenType records = ( ('234', TokenType.INTEGER_CONST, 234), ('3.14', TokenType.REAL_CONST, 3.14), ('*', TokenType.MUL, '*'), ('DIV', TokenType.INTEGER_DIV, 'DIV'), ('/', TokenType.FLOAT_DIV, '/'), ('+', TokenType.PLUS, '+'), ('-', TokenType.MINUS, '-'), ('(', TokenType.LPAREN, '('), (')', TokenType.RPAREN, ')'), (':=', TokenType.ASSIGN, ':='), ('.', TokenType.DOT, '.'), ('number', TokenType.ID, 'number'), (';', TokenType.SEMI, ';'), ('BEGIN', TokenType.BEGIN, 'BEGIN'), ('END', TokenType.END, 'END'), ('PROCEDURE', TokenType.PROCEDURE, 'PROCEDURE'), ) for text, tok_type, tok_val in records: lexer = self.makeLexer(text) token = lexer.get_next_token() self.assertEqual(token.type, tok_type) self.assertEqual(token.value, tok_val) def test_lexer_exception(self): from spi import LexerError lexer = self.makeLexer('<') with self.assertRaises(LexerError): lexer.get_next_token() class ParserTestCase(unittest.TestCase): def makeParser(self, text): from spi import Lexer, Parser lexer = Lexer(text) parser = Parser(lexer) return parser def test_expression_invalid_syntax_01(self): from spi import ParserError, ErrorCode parser = self.makeParser( """ PROGRAM Test; VAR a : INTEGER; BEGIN a := 10 * ; {Invalid syntax} END. """ ) with self.assertRaises(ParserError) as cm: parser.parse() the_exception = cm.exception self.assertEqual(the_exception.error_code, ErrorCode.UNEXPECTED_TOKEN) self.assertEqual(the_exception.token.value, ';') self.assertEqual(the_exception.token.lineno, 6) def test_expression_invalid_syntax_02(self): from spi import ParserError, ErrorCode parser = self.makeParser( """ PROGRAM Test; VAR a : INTEGER; BEGIN a := 1 (1 + 2); {Invalid syntax} END. """ ) with self.assertRaises(ParserError) as cm: parser.parse() the_exception = cm.exception self.assertEqual(the_exception.error_code, ErrorCode.UNEXPECTED_TOKEN) self.assertEqual(the_exception.token.value, '(') self.assertEqual(the_exception.token.lineno, 6) def test_maximum_one_VAR_block_is_allowed(self): from spi import ParserError, ErrorCode # zero VARs parser = self.makeParser( """ PROGRAM Test; BEGIN END. """ ) parser.parse() # one VAR parser = self.makeParser( """ PROGRAM Test; VAR a : INTEGER; BEGIN END. """ ) parser.parse() parser = self.makeParser( """ PROGRAM Test; VAR a : INTEGER; VAR b : INTEGER; BEGIN a := 5; b := a + 10; END. """ ) with self.assertRaises(ParserError) as cm: parser.parse() the_exception = cm.exception self.assertEqual(the_exception.error_code, ErrorCode.UNEXPECTED_TOKEN) self.assertEqual(the_exception.token.value, 'VAR') self.assertEqual(the_exception.token.lineno, 5) # second VAR class SemanticAnalyzerTestCase(unittest.TestCase): def runSemanticAnalyzer(self, text): from spi import Lexer, Parser, SemanticAnalyzer lexer = Lexer(text) parser = Parser(lexer) tree = parser.parse() semantic_analyzer = SemanticAnalyzer() semantic_analyzer.visit(tree) return semantic_analyzer def test_semantic_duplicate_id_error(self): from spi import SemanticError, ErrorCode with self.assertRaises(SemanticError) as cm: self.runSemanticAnalyzer( """ PROGRAM Test; VAR a : INTEGER; a : REAL; {Duplicate identifier} BEGIN a := 5; END. """ ) the_exception = cm.exception self.assertEqual(the_exception.error_code, ErrorCode.DUPLICATE_ID) self.assertEqual(the_exception.token.value, 'a') self.assertEqual(the_exception.token.lineno, 5) def test_semantic_id_not_found_error(self): from spi import SemanticError, ErrorCode with self.assertRaises(SemanticError) as cm: self.runSemanticAnalyzer( """ PROGRAM Test; VAR a : INTEGER; BEGIN a := 5 + b; END. """ ) the_exception = cm.exception self.assertEqual(the_exception.error_code, ErrorCode.ID_NOT_FOUND) self.assertEqual(the_exception.token.value, 'b') class TestCallStack: def __init__(self): self._records = [] def push(self, ar): self._records.append(ar) def pop(self): # do nothing pass def peek(self): return self._records[-1] class InterpreterTestCase(unittest.TestCase): def makeInterpreter(self, text): from spi import Lexer, Parser, SemanticAnalyzer, Interpreter lexer = Lexer(text) parser = Parser(lexer) tree = parser.parse() semantic_analyzer = SemanticAnalyzer() semantic_analyzer.visit(tree) interpreter = Interpreter(tree) interpreter.call_stack = TestCallStack() return interpreter def test_integer_arithmetic_expressions(self): for expr, result in ( ('3', 3), ('2 + 7 * 4', 30), ('7 - 8 DIV 4', 5), ('14 + 2 * 3 - 6 DIV 2', 17), ('7 + 3 * (10 DIV (12 DIV (3 + 1) - 1))', 22), ('7 + 3 * (10 DIV (12 DIV (3 + 1) - 1)) DIV (2 + 3) - 5 - 3 + (8)', 10), ('7 + (((3 + 2)))', 12), ('- 3', -3), ('+ 3', 3), ('5 - - - + - 3', 8), ('5 - - - + - (3 + 4) - +2', 10), ): interpreter = self.makeInterpreter( """PROGRAM Test; VAR a : INTEGER; BEGIN a := %s END. """ % expr ) interpreter.interpret() ar = interpreter.call_stack.peek() self.assertEqual(ar['a'], result) def test_float_arithmetic_expressions(self): for expr, result in ( ('3.14', 3.14), ('2.14 + 7 * 4', 30.14), ('7.14 - 8 / 4', 5.14), ): interpreter = self.makeInterpreter( """PROGRAM Test; VAR a : REAL; BEGIN a := %s END. """ % expr ) interpreter.interpret() ar = interpreter.call_stack.peek() self.assertEqual(ar['a'], result) def test_procedure_call(self): text = """\ program Main; procedure Alpha(a : integer; b : integer); var x : integer; begin x := (a + b ) * 2; end; begin { Main } Alpha(3 + 5, 7); end. { Main } """ interpreter = self.makeInterpreter(text) interpreter.interpret() ar = interpreter.call_stack.peek() self.assertEqual(ar['a'], 8) self.assertEqual(ar['b'], 7) self.assertEqual(ar['x'], 30) self.assertEqual(ar.nesting_level, 2) def test_program(self): text = """\ PROGRAM Part12; VAR number : INTEGER; a, b : INTEGER; y : REAL; PROCEDURE P1; VAR a : REAL; k : INTEGER; PROCEDURE P2; VAR a, z : INTEGER; BEGIN {P2} z := 777; END; {P2} BEGIN {P1} END; {P1} BEGIN {Part12} number := 2; a := number ; b := 10 * a + 10 * number DIV 4; y := 20 / 7 + 3.14 END. {Part12} """ interpreter = self.makeInterpreter(text) interpreter.interpret() ar = interpreter.call_stack.peek() self.assertEqual(len(ar.members.keys()), 4) self.assertEqual(ar['number'], 2) self.assertEqual(ar['a'], 2) self.assertEqual(ar['b'], 25) self.assertAlmostEqual(ar['y'], float(20) / 7 + 3.14) # 5.9971... if __name__ == '__main__': unittest.main()
[((9013, 9028), 'unittest.main', 'unittest.main', ([], {}), '()\n', (9026, 9028), False, 'import unittest\n'), ((135, 146), 'spi.Lexer', 'Lexer', (['text'], {}), '(text)\n', (140, 146), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((1535, 1546), 'spi.Lexer', 'Lexer', (['text'], {}), '(text)\n', (1540, 1546), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((1564, 1577), 'spi.Parser', 'Parser', (['lexer'], {}), '(lexer)\n', (1570, 1577), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((4138, 4149), 'spi.Lexer', 'Lexer', (['text'], {}), '(text)\n', (4143, 4149), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((4167, 4180), 'spi.Parser', 'Parser', (['lexer'], {}), '(lexer)\n', (4173, 4180), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((4240, 4258), 'spi.SemanticAnalyzer', 'SemanticAnalyzer', ([], {}), '()\n', (4256, 4258), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((5916, 5927), 'spi.Lexer', 'Lexer', (['text'], {}), '(text)\n', (5921, 5927), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((5945, 5958), 'spi.Parser', 'Parser', (['lexer'], {}), '(lexer)\n', (5951, 5958), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((6018, 6036), 'spi.SemanticAnalyzer', 'SemanticAnalyzer', ([], {}), '()\n', (6034, 6036), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n'), ((6098, 6115), 'spi.Interpreter', 'Interpreter', (['tree'], {}), '(tree)\n', (6109, 6115), False, 'from spi import Lexer, Parser, SemanticAnalyzer, Interpreter\n')]
Ferlern/Arctic-Tundra
bot_components/configurator.py
407b8c38c31f6c930df662e87ced527b9fd26c61
import json from typing import TypedDict from .bot_emoji import AdditionalEmoji class Warn(TypedDict): text: str mute_time: int ban: bool class PersonalVoice(TypedDict): categoty: int price: int slot_price: int bitrate_price: int class System(TypedDict): token: str initial_extensions: list[str] class ExperienceSystem(TypedDict): experience_channel: int cooldown: int minimal_message_length: int experience_per_message: list[int] roles: dict[str, int] coins_per_level_up: int class AutoTranslation(TypedDict): channels: list lang: str class Config(TypedDict): guild: int token: str prefixes: list[str] commands_channels: list[int] mute_role: int suggestions_channel: int moderators_roles: list[int] warns_system: list[Warn] coin: str daily: int marry_price: int personal_voice: PersonalVoice experience_system: ExperienceSystem auto_translation: AutoTranslation additional_emoji: AdditionalEmoji class Configurator: def __init__(self) -> None: self.system: System self.config: Config def dump(self): with open("./bot_components/config.json", "w") as write_file: to_dump = [self.system, self.config] json.dump(to_dump, write_file, indent=4) def load(self): with open("./bot_components/config.json", "r") as write_file: data = json.load(write_file) self.system = System(data[0]) self.config = Config(data[1]) def reload(self): self.dump() self.load() configurator = Configurator() configurator.load()
[((1303, 1343), 'json.dump', 'json.dump', (['to_dump', 'write_file'], {'indent': '(4)'}), '(to_dump, write_file, indent=4)\n', (1312, 1343), False, 'import json\n'), ((1454, 1475), 'json.load', 'json.load', (['write_file'], {}), '(write_file)\n', (1463, 1475), False, 'import json\n')]
ihash5/reinforcement-learning
recnn/utils/plot.py
c72e9db33c6ed6abd34e9f48012189369b7cd5d0
from scipy.spatial import distance from scipy import ndimage import matplotlib.pyplot as plt import torch from scipy import stats import numpy as np def pairwise_distances_fig(embs): embs = embs.detach().cpu().numpy() similarity_matrix_cos = distance.cdist(embs, embs, 'cosine') similarity_matrix_euc = distance.cdist(embs, embs, 'euclidean') fig = plt.figure(figsize=(16,10)) ax = fig.add_subplot(121) cax = ax.matshow(similarity_matrix_cos) fig.colorbar(cax) ax.set_title('Cosine') ax.axis('off') ax = fig.add_subplot(122) cax = ax.matshow(similarity_matrix_euc) fig.colorbar(cax) ax.set_title('Euclidian') ax.axis('off') fig.suptitle('Action pairwise distances') plt.close() return fig def pairwise_distances(embs): fig = pairwise_distances_fig(embs) fig.show() def smooth(scalars, weight): # Weight between 0 and 1 last = scalars[0] # First value in the plot (first timestep) smoothed = list() for point in scalars: smoothed_val = last * weight + (1 - weight) * point # Calculate smoothed value smoothed.append(smoothed_val) # Save it last = smoothed_val # Anchor the last smoothed value return smoothed def smooth_gauss(arr, var): return ndimage.gaussian_filter1d(arr, var) class Plotter: def __init__(self, loss, style): self.loss = loss self.style = style self.smoothing = lambda x: smooth_gauss(x, 4) def set_smoothing_func(self, f): self.smoothing = f def plot_loss(self): for row in self.style: fig, axes = plt.subplots(1, len(row), figsize=(16, 6)) if len(row) == 1: axes = [axes] for col in range(len(row)): key = row[col] axes[col].set_title(key) axes[col].plot(self.loss['train']['step'], self.smoothing(self.loss['train'][key]), 'b-', label='train') axes[col].plot(self.loss['test']['step'], self.loss['test'][key], 'r-.', label='test') plt.legend() plt.show() def log_loss(self, key, item, test=False): kind = 'train' if test: kind = 'test' self.loss[kind][key].append(item) def log_losses(self, losses, test=False): for key, val in losses.items(): self.log_loss(key, val, test) @staticmethod def kde_reconstruction_error(ad, gen_actions, true_actions, device=torch.device('cpu')): def rec_score(actions): return ad.rec_error(torch.tensor(actions).to(device).float()).detach().cpu().numpy() true_scores = rec_score(true_actions) gen_scores = rec_score(gen_actions) true_kernel = stats.gaussian_kde(true_scores) gen_kernel = stats.gaussian_kde(gen_scores) x = np.linspace(0, 1000, 100) probs_true = true_kernel(x) probs_gen = gen_kernel(x) fig = plt.figure(figsize=(16, 10)) ax = fig.add_subplot(111) ax.plot(x, probs_true, '-b', label='true dist') ax.plot(x, probs_gen, '-r', label='generated dist') ax.legend() return fig @staticmethod def plot_kde_reconstruction_error(*args, **kwargs): fig = Plotter.kde_reconstruction_error(*args, **kwargs) fig.show()
[((252, 288), 'scipy.spatial.distance.cdist', 'distance.cdist', (['embs', 'embs', '"""cosine"""'], {}), "(embs, embs, 'cosine')\n", (266, 288), False, 'from scipy.spatial import distance\n'), ((317, 356), 'scipy.spatial.distance.cdist', 'distance.cdist', (['embs', 'embs', '"""euclidean"""'], {}), "(embs, embs, 'euclidean')\n", (331, 356), False, 'from scipy.spatial import distance\n'), ((368, 396), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 10)'}), '(figsize=(16, 10))\n', (378, 396), True, 'import matplotlib.pyplot as plt\n'), ((736, 747), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (745, 747), True, 'import matplotlib.pyplot as plt\n'), ((1335, 1370), 'scipy.ndimage.gaussian_filter1d', 'ndimage.gaussian_filter1d', (['arr', 'var'], {}), '(arr, var)\n', (1360, 1370), False, 'from scipy import ndimage\n'), ((2257, 2267), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2265, 2267), True, 'import matplotlib.pyplot as plt\n'), ((2643, 2662), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2655, 2662), False, 'import torch\n'), ((2909, 2940), 'scipy.stats.gaussian_kde', 'stats.gaussian_kde', (['true_scores'], {}), '(true_scores)\n', (2927, 2940), False, 'from scipy import stats\n'), ((2962, 2992), 'scipy.stats.gaussian_kde', 'stats.gaussian_kde', (['gen_scores'], {}), '(gen_scores)\n', (2980, 2992), False, 'from scipy import stats\n'), ((3006, 3031), 'numpy.linspace', 'np.linspace', (['(0)', '(1000)', '(100)'], {}), '(0, 1000, 100)\n', (3017, 3031), True, 'import numpy as np\n'), ((3116, 3144), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 10)'}), '(figsize=(16, 10))\n', (3126, 3144), True, 'import matplotlib.pyplot as plt\n'), ((2236, 2248), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2246, 2248), True, 'import matplotlib.pyplot as plt\n'), ((2730, 2751), 'torch.tensor', 'torch.tensor', (['actions'], {}), '(actions)\n', (2742, 2751), False, 'import torch\n')]
pazzy-stack/twilio
tests/integration/insights/v1/call/test_metric.py
d3b9b9f1b17b9de89b2528e8d2ffd33edf9676e0
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from tests import IntegrationTestCase from tests.holodeck import Request from twilio.base.exceptions import TwilioException from twilio.http.response import Response class MetricTestCase(IntegrationTestCase): def test_list_request(self): self.holodeck.mock(Response(500, '')) with self.assertRaises(TwilioException): self.client.insights.v1.calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .metrics.list() self.holodeck.assert_has_request(Request( 'get', 'https://insights.twilio.com/v1/Voice/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Metrics', )) def test_read_response(self): self.holodeck.mock(Response( 200, ''' { "meta": { "page": 0, "page_size": 50, "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?PageSize=50&Page=0", "previous_page_url": null, "next_page_url": null, "key": "metrics", "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?PageSize=50&Page=0" }, "metrics": [ { "timestamp": "2019-10-07T22:32:06Z", "call_sid": "CA7569efe0253644fa4a88aa97beca3310", "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9", "edge": "sdk_edge", "direction": "both", "sdk_edge": { "interval": { "packets_received": 50, "packets_lost": 0, "audio_in": { "value": 81.0 }, "audio_out": { "value": 5237.0 }, "jitter": { "value": 9 }, "mos": { "value": 4.39 }, "rtt": { "value": 81 } }, "cumulative": { "bytes_received": 547788, "bytes_sent": 329425, "packets_received": 3900, "packets_lost": 0, "packets_sent": 3934 } }, "client_edge": null, "carrier_edge": null, "sip_edge": null, "gateway": null, "client": null } ] } ''' )) actual = self.client.insights.v1.calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .metrics.list() self.assertIsNotNone(actual) def test_read_full_response(self): self.holodeck.mock(Response( 200, ''' { "meta": { "page": 10, "page_size": 5, "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=0", "previous_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=9&PageToken=DP10", "next_page_url": null, "key": "metrics", "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=10" }, "metrics": [ { "timestamp": "2019-10-07T22:32:06Z", "call_sid": "CA7569efe0253644fa4a88aa97beca3310", "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9", "edge": "sdk_edge", "direction": "both", "sdk_edge": { "interval": { "packets_received": 50, "packets_lost": 0, "audio_in": { "value": 81.0 }, "audio_out": { "value": 5237.0 }, "jitter": { "value": 9 }, "mos": { "value": 4.39 }, "rtt": { "value": 81 } }, "cumulative": { "bytes_received": 547788, "bytes_sent": 329425, "packets_received": 3900, "packets_lost": 0, "packets_sent": 3934 } }, "client_edge": null, "carrier_edge": null, "sip_edge": null, "gateway": null, "client": null } ] } ''' )) actual = self.client.insights.v1.calls(sid="CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \ .metrics.list() self.assertIsNotNone(actual)
[((393, 410), 'twilio.http.response.Response', 'Response', (['(500)', '""""""'], {}), "(500, '')\n", (401, 410), False, 'from twilio.http.response import Response\n'), ((641, 747), 'tests.holodeck.Request', 'Request', (['"""get"""', '"""https://insights.twilio.com/v1/Voice/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Metrics"""'], {}), "('get',\n 'https://insights.twilio.com/v1/Voice/CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Metrics'\n )\n", (648, 747), False, 'from tests.holodeck import Request\n'), ((837, 3255), 'twilio.http.response.Response', 'Response', (['(200)', '"""\n {\n "meta": {\n "page": 0,\n "page_size": 50,\n "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?PageSize=50&Page=0",\n "previous_page_url": null,\n "next_page_url": null,\n "key": "metrics",\n "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?PageSize=50&Page=0"\n },\n "metrics": [\n {\n "timestamp": "2019-10-07T22:32:06Z",\n "call_sid": "CA7569efe0253644fa4a88aa97beca3310",\n "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9",\n "edge": "sdk_edge",\n "direction": "both",\n "sdk_edge": {\n "interval": {\n "packets_received": 50,\n "packets_lost": 0,\n "audio_in": {\n "value": 81.0\n },\n "audio_out": {\n "value": 5237.0\n },\n "jitter": {\n "value": 9\n },\n "mos": {\n "value": 4.39\n },\n "rtt": {\n "value": 81\n }\n },\n "cumulative": {\n "bytes_received": 547788,\n "bytes_sent": 329425,\n "packets_received": 3900,\n "packets_lost": 0,\n "packets_sent": 3934\n }\n },\n "client_edge": null,\n "carrier_edge": null,\n "sip_edge": null,\n "gateway": null,\n "client": null\n }\n ]\n }\n """'], {}), '(200,\n """\n {\n "meta": {\n "page": 0,\n "page_size": 50,\n "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?PageSize=50&Page=0",\n "previous_page_url": null,\n "next_page_url": null,\n "key": "metrics",\n "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?PageSize=50&Page=0"\n },\n "metrics": [\n {\n "timestamp": "2019-10-07T22:32:06Z",\n "call_sid": "CA7569efe0253644fa4a88aa97beca3310",\n "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9",\n "edge": "sdk_edge",\n "direction": "both",\n "sdk_edge": {\n "interval": {\n "packets_received": 50,\n "packets_lost": 0,\n "audio_in": {\n "value": 81.0\n },\n "audio_out": {\n "value": 5237.0\n },\n "jitter": {\n "value": 9\n },\n "mos": {\n "value": 4.39\n },\n "rtt": {\n "value": 81\n }\n },\n "cumulative": {\n "bytes_received": 547788,\n "bytes_sent": 329425,\n "packets_received": 3900,\n "packets_lost": 0,\n "packets_sent": 3934\n }\n },\n "client_edge": null,\n "carrier_edge": null,\n "sip_edge": null,\n "gateway": null,\n "client": null\n }\n ]\n }\n """\n )\n', (845, 3255), False, 'from twilio.http.response import Response\n'), ((3535, 6149), 'twilio.http.response.Response', 'Response', (['(200)', '"""\n {\n "meta": {\n "page": 10,\n "page_size": 5,\n "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=0",\n "previous_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=9&PageToken=DP10",\n "next_page_url": null,\n "key": "metrics",\n "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=10"\n },\n "metrics": [\n {\n "timestamp": "2019-10-07T22:32:06Z",\n "call_sid": "CA7569efe0253644fa4a88aa97beca3310",\n "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9",\n "edge": "sdk_edge",\n "direction": "both",\n "sdk_edge": {\n "interval": {\n "packets_received": 50,\n "packets_lost": 0,\n "audio_in": {\n "value": 81.0\n },\n "audio_out": {\n "value": 5237.0\n },\n "jitter": {\n "value": 9\n },\n "mos": {\n "value": 4.39\n },\n "rtt": {\n "value": 81\n }\n },\n "cumulative": {\n "bytes_received": 547788,\n "bytes_sent": 329425,\n "packets_received": 3900,\n "packets_lost": 0,\n "packets_sent": 3934\n }\n },\n "client_edge": null,\n "carrier_edge": null,\n "sip_edge": null,\n "gateway": null,\n "client": null\n }\n ]\n }\n """'], {}), '(200,\n """\n {\n "meta": {\n "page": 10,\n "page_size": 5,\n "first_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=0",\n "previous_page_url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=9&PageToken=DP10",\n "next_page_url": null,\n "key": "metrics",\n "url": "https://insights.twilio.com/v1/Voice/CAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Metrics?Direction=both&Edge=sdk_edge&PageSize=5&Page=10"\n },\n "metrics": [\n {\n "timestamp": "2019-10-07T22:32:06Z",\n "call_sid": "CA7569efe0253644fa4a88aa97beca3310",\n "account_sid": "AC998c10b68cbfda9f67277f7d8f4439c9",\n "edge": "sdk_edge",\n "direction": "both",\n "sdk_edge": {\n "interval": {\n "packets_received": 50,\n "packets_lost": 0,\n "audio_in": {\n "value": 81.0\n },\n "audio_out": {\n "value": 5237.0\n },\n "jitter": {\n "value": 9\n },\n "mos": {\n "value": 4.39\n },\n "rtt": {\n "value": 81\n }\n },\n "cumulative": {\n "bytes_received": 547788,\n "bytes_sent": 329425,\n "packets_received": 3900,\n "packets_lost": 0,\n "packets_sent": 3934\n }\n },\n "client_edge": null,\n "carrier_edge": null,\n "sip_edge": null,\n "gateway": null,\n "client": null\n }\n ]\n }\n """\n )\n', (3543, 6149), False, 'from twilio.http.response import Response\n')]
essepuntato/comp-think
2017-2018/lecture-notes/python/02-algorithms_listing_8_contains_word.py
3dac317bda0eb7650adc4a92c1ccb8a4ce87a3a6
def contains_word(first_word, second_word, bibliographic_entry): contains_first_word = first_word in bibliographic_entry contains_second_word = second_word in bibliographic_entry if contains_first_word and contains_second_word: return 2 elif contains_first_word or contains_second_word: return 1 else: return 0 if __name__ == "__main__": bibliographic_entry = "Peroni, S., Osborne, F., Di Iorio, A., Nuzzolese, A. G., Poggi, F., Vitali, F., " \ "Motta, E. (2017). Research Articles in Simplified HTML: a Web-first format for " \ "HTML-based scholarly articles. PeerJ Computer Science 3: e132. e2513. " \ "DOI: https://doi.org/10.7717/peerj-cs.132" print(contains_word("Peroni", "Osborne", bibliographic_entry)) print(contains_word("Peroni", "Asprino", bibliographic_entry)) print(contains_word("Reforgiato", "Osborne", bibliographic_entry)) print(contains_word("Reforgiato", "Asprino", bibliographic_entry))
[]
ivaivalous/ivodb
backend/user/scripter.py
e9b0969225fdb725d35a2ecfab21f87d1d9b2a00
#!/usr/bin/env python import responses from selenium import webdriver # This file contains/references the default JS # used to provide functions dealing with input/output SCRIPT_RUNNER = "runner.html" ENCODING = 'utf-8' PAGE_LOAD_TIMEOUT = 5 PAGE_LOAD_TIMEOUT_MS = PAGE_LOAD_TIMEOUT * 1000 capabilities = webdriver.DesiredCapabilities.PHANTOMJS capabilities["phantomjs.page.settings.resourceTimeout"] = PAGE_LOAD_TIMEOUT_MS capabilities["phantomjs.page.settings.loadImages"] = False SCRIPT_TEMPLATE = """ window.requestData = {{method:"{0}", headers:{1}, data:"{2}", params:{3}}}; window.method = requestData.method; window.headers = requestData.headers; window.data = requestData.data; window.params = requestData.params; window.logs = []; window.log = function(message) {{ window.logs.push({{ "time": (new Date).getTime(), "message": message }}) }}; """ GET_LOGS_SCRIPT = 'return window.logs;' class Scripter: def __init__(self): self.driver = webdriver.PhantomJS(desired_capabilities=capabilities) self.driver.implicitly_wait(PAGE_LOAD_TIMEOUT) self.driver.set_page_load_timeout(PAGE_LOAD_TIMEOUT) def run(self, request, script_body, input_params): self.driver.get(SCRIPT_RUNNER) self.driver.execute_script( Scripter.build_runner_script(request, input_params)) try: response = self.execute_user_script(script_body) logs = self.driver.execute_script(GET_LOGS_SCRIPT) return response.encode(ENCODING), logs except: return responses.get_invalid_request(), [] def execute_user_script(self, script_body): """Execute a user-contributed script.""" return self.driver.execute_script(script_body) @staticmethod def build_runner_script(request, input_params): # Build JS related to having access to input # and request data. return SCRIPT_TEMPLATE.format( request.method, Scripter.build_headers_map(request.headers), request.get_data().encode(ENCODING), Scripter.build_params_map(input_params.encode(ENCODING))) @staticmethod def build_params_map(input_params): # input_params looks like "test=aaa&test2=jjj" couples = input_params.split("&") params_map = {} for couple in couples: c = couple.split("=") key = c[0] value = c[1] if len(c) > 1 else "" params_map[key] = value return params_map @staticmethod def build_headers_map(headers): headers_map = {} for key, value in headers: if 'jwt=' in value: continue headers_map[key] = value.encode(ENCODING) return headers_map
[((1038, 1092), 'selenium.webdriver.PhantomJS', 'webdriver.PhantomJS', ([], {'desired_capabilities': 'capabilities'}), '(desired_capabilities=capabilities)\n', (1057, 1092), False, 'from selenium import webdriver\n'), ((1637, 1668), 'responses.get_invalid_request', 'responses.get_invalid_request', ([], {}), '()\n', (1666, 1668), False, 'import responses\n')]
luhouxiang/byrobot
bwtougu/api/names.py
e110e7865965a344d2b61cb925c959cee1387758
#!/usr/bin/env python # -*- coding: utf-8 -*- VALID_HISTORY_FIELDS = [ 'datetime', 'open', 'close', 'high', 'low', 'total_turnover', 'volume', 'acc_net_value', 'discount_rate', 'unit_net_value', 'limit_up', 'limit_down', 'open_interest', 'basis_spread', 'settlement', 'prev_settlement' ] VALID_GET_PRICE_FIELDS = [ 'OpeningPx', 'ClosingPx', 'HighPx', 'LowPx', 'TotalTurnover', 'TotalVolumeTraded', 'AccNetValue', 'UnitNetValue', 'DiscountRate', 'SettlPx', 'PrevSettlPx', 'OpenInterest', 'BasisSpread', 'HighLimitPx', 'LowLimitPx' ] VALID_TENORS = [ '0S', '1M', '2M', '3M', '6M', '9M', '1Y', '2Y', '3Y', '4Y', '5Y', '6Y', '7Y', '8Y', '9Y', '10Y', '15Y', '20Y', '30Y', '40Y', '50Y' ] VALID_INSTRUMENT_TYPES = [ 'CS', 'Future', 'INDX', 'ETF', 'LOF', 'SF', 'FenjiA', 'FenjiB', 'FenjiMu', 'Stock', 'Fund', 'Index' ] VALID_XUEQIU_FIELDS = [ 'new_comments', 'total_comments', 'new_followers', 'total_followers', 'sell_actions', 'buy_actions', ] VALID_MARGIN_FIELDS = [ 'margin_balance', 'buy_on_margin_value', 'short_sell_quantity', 'margin_repayment', 'short_balance_quantity', 'short_repayment_quantity', 'short_balance', 'total_balance' ] VALID_SHARE_FIELDS = [ 'total', 'circulation_a', 'management_circulation', 'non_circulation_a', 'total_a' ] VALID_TURNOVER_FIELDS = ( 'today', 'week', 'month', 'three_month', 'six_month', 'year', 'current_year', 'total', )
[]
dveni/causal-text-embeddings
src/PeerRead/data_cleaning/process_PeerRead_abstracts.py
82104f3fb6fd540cf98cb4ca0fd5b5d1fb5f757a
""" Simple pre-processing for PeerRead papers. Takes in JSON formatted data from ScienceParse and outputs a tfrecord Reference example: https://github.com/tensorlayer/tensorlayer/blob/9528da50dfcaf9f0f81fba9453e488a1e6c8ee8f/examples/data_process/tutorial_tfrecord3.py """ import argparse import glob import os import random import io import json from dateutil.parser import parse as parse_date import tensorflow as tf import bert.tokenization as tokenization from PeerRead.ScienceParse.Paper import Paper from PeerRead.ScienceParse.ScienceParseReader import ScienceParseReader from PeerRead.data_cleaning.PeerRead_hand_features import get_PeerRead_hand_features rng = random.Random(0) def process_json_paper(paper_json_filename, scienceparse_dir, tokenizer): paper = Paper.from_json(paper_json_filename) paper.SCIENCEPARSE = ScienceParseReader.read_science_parse(paper.ID, paper.TITLE, paper.ABSTRACT, scienceparse_dir) # tokenize PeerRead features try: title_tokens = tokenizer.tokenize(paper.TITLE) except ValueError: # missing titles are quite common sciparse print("Missing title for " + paper_json_filename) title_tokens = None abstract_tokens = tokenizer.tokenize(paper.ABSTRACT) text_features = {'title': title_tokens, 'abstract': abstract_tokens} context_features = {'authors': paper.AUTHORS, 'accepted': paper.ACCEPTED, 'name': paper.ID} # add hand crafted features from PeerRead pr_hand_features = get_PeerRead_hand_features(paper) context_features.update(pr_hand_features) return text_features, context_features def bert_process_sentence(example_tokens, max_seq_length, tokenizer): """ Tokenization and pre-processing of text as expected by Bert Parameters ---------- example_tokens max_seq_length tokenizer Returns ------- """ # Account for [CLS] and [SEP] with "- 2" if len(example_tokens) > max_seq_length - 2: example_tokens = example_tokens[0:(max_seq_length - 2)] # The convention in BERT for single sequences is: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. (vv: Not relevant for us) # For classification tasks, the first vector (corresponding to [CLS]) is # used as as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. # vv: segment_ids seem to be the same as type_ids tokens = [] segment_ids = [] tokens.append("[CLS]") segment_ids.append(0) for token in example_tokens: tokens.append(token) segment_ids.append(0) tokens.append("[SEP]") segment_ids.append(0) input_ids = tokenizer.convert_tokens_to_ids(tokens) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. input_mask = [1] * len(input_ids) # Zero-pad up to the sequence length. while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length return input_ids, input_mask, segment_ids def paper_to_bert_Example(text_features, context_features, max_seq_length, tokenizer): """ Parses the input paper into a tf.Example as expected by Bert Note: the docs for tensorflow Example are awful ¯\_(ツ)_/¯ """ abstract_features = {} abstract_tokens, abstract_padding_mask, _ = \ bert_process_sentence(text_features['abstract'], max_seq_length, tokenizer) abstract_features["token_ids"] = _int64_feature(abstract_tokens) abstract_features["token_mask"] = _int64_feature(abstract_padding_mask) # abstract_features["segment_ids"] = create_int_feature(feature.segment_ids) TODO: ommission may cause bugs # abstract_features["label_ids"] = _int64_feature([feature.label_id]) # non-sequential features tf_context_features, tf_context_features_types = _dict_of_nonlist_numerical_to_tf_features(context_features) features = {**tf_context_features, **abstract_features} tf_example = tf.train.Example(features=tf.train.Features(feature=features)) return tf_example def _int64_feature(value): """Wrapper for inserting an int64 Feature into a SequenceExample proto, e.g, An integer label. """ if isinstance(value, list): return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) else: return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _float_feature(value): """Wrapper for inserting a float Feature into a SequenceExample proto, e.g, An integer label. """ if isinstance(value, list): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) else: return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) def _bytes_feature(value): """Wrapper for inserting a bytes Feature into a SequenceExample proto, e.g, an image in byte """ # return tf.train.Feature(bytes_list=tf.train.BytesList(value=[str(value)])) return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _dict_of_nonlist_numerical_to_tf_features(my_dict): """ Strip out non-numerical features Returns tf_features_dict: a dictionary suitable for passing to tf.train.example tf_types_dict: a dictionary of the tf types of previous dict """ tf_types_dict = {} tf_features_dict = {} for k, v in my_dict.items(): if isinstance(v, int) or isinstance(v, bool): tf_features_dict[k] = _int64_feature(v) tf_types_dict[k] = tf.int64 elif isinstance(v, float): tf_features_dict[k] = _float_feature(v) tf_types_dict[k] = tf.float32 else: pass return tf_features_dict, tf_types_dict venues = {'acl': 1, 'conll': 2, 'iclr': 3, 'nips': 4, 'icml': 5, 'emnlp': 6, 'aaai': 7, 'hlt-naacl': 8, 'arxiv': 0} def _venues(venue_name): if venue_name.lower() in venues: return venues[venue_name.lower()] else: return -1 def _arxiv_subject(subjects): subject = subjects[0] if 'lg' in subject.lower(): return 0 elif 'cl' in subject.lower(): return 1 elif 'ai' in subject.lower(): return 2 else: raise Exception("arxiv subject not recognized") def clean_PeerRead_dataset(review_json_dir, parsedpdf_json_dir, venue, year, out_dir, out_file, max_abs_len, tokenizer, default_accept=1, is_arxiv = False): if not os.path.exists(out_dir): os.makedirs(out_dir) print('Reading reviews from...', review_json_dir) paper_json_filenames = sorted(glob.glob('{}/*.json'.format(review_json_dir))) with tf.python_io.TFRecordWriter(out_dir + "/" + out_file) as writer: for idx, paper_json_filename in enumerate(paper_json_filenames): text_features, context_features = process_json_paper(paper_json_filename, parsedpdf_json_dir, tokenizer) if context_features['accepted'] is None: # missing for conferences other than ICLR (we only see accepts) context_features['accepted'] = default_accept many_split = rng.randint(0, 100) # useful for easy data splitting later # other context features arxiv = -1 if is_arxiv: with io.open(paper_json_filename) as json_file: loaded = json.load(json_file) year = parse_date(loaded['DATE_OF_SUBMISSION']).year venue = _venues(loaded['conference']) arxiv = _arxiv_subject([loaded['SUBJECTS']]) extra_context = {'id': idx, 'venue': venue, 'year': year, 'many_split': many_split, 'arxiv': arxiv} context_features.update(extra_context) # turn it into a tf.data example paper_ex = paper_to_bert_Example(text_features, context_features, max_seq_length=max_abs_len, tokenizer=tokenizer) writer.write(paper_ex.SerializeToString()) def main(): parser = argparse.ArgumentParser() parser.add_argument('--review-json-dir', type=str, default='../dat/PeerRead/arxiv.all/all/reviews') parser.add_argument('--parsedpdf-json-dir', type=str, default='../dat/PeerRead/arxiv.all/all/parsed_pdfs') parser.add_argument('--out-dir', type=str, default='../dat/PeerRead/proc') parser.add_argument('--out-file', type=str, default='arxiv-all.tf_record') parser.add_argument('--vocab-file', type=str, default='../../bert/pre-trained/uncased_L-12_H-768_A-12/vocab.txt') parser.add_argument('--max-abs-len', type=int, default=250) parser.add_argument('--venue', type=int, default=0) parser.add_argument('--year', type=int, default=2017) args = parser.parse_args() tokenizer = tokenization.FullTokenizer( vocab_file=args.vocab_file, do_lower_case=True) clean_PeerRead_dataset(args.review_json_dir, args.parsedpdf_json_dir, args.venue, args.year, args.out_dir, args.out_file, args.max_abs_len, tokenizer, is_arxiv=True) if __name__ == "__main__": main()
[((676, 692), 'random.Random', 'random.Random', (['(0)'], {}), '(0)\n', (689, 692), False, 'import random\n'), ((781, 817), 'PeerRead.ScienceParse.Paper.Paper.from_json', 'Paper.from_json', (['paper_json_filename'], {}), '(paper_json_filename)\n', (796, 817), False, 'from PeerRead.ScienceParse.Paper import Paper\n'), ((843, 941), 'PeerRead.ScienceParse.ScienceParseReader.ScienceParseReader.read_science_parse', 'ScienceParseReader.read_science_parse', (['paper.ID', 'paper.TITLE', 'paper.ABSTRACT', 'scienceparse_dir'], {}), '(paper.ID, paper.TITLE, paper.ABSTRACT,\n scienceparse_dir)\n', (880, 941), False, 'from PeerRead.ScienceParse.ScienceParseReader import ScienceParseReader\n'), ((1620, 1653), 'PeerRead.data_cleaning.PeerRead_hand_features.get_PeerRead_hand_features', 'get_PeerRead_hand_features', (['paper'], {}), '(paper)\n', (1646, 1653), False, 'from PeerRead.data_cleaning.PeerRead_hand_features import get_PeerRead_hand_features\n'), ((8708, 8733), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (8731, 8733), False, 'import argparse\n'), ((9454, 9528), 'bert.tokenization.FullTokenizer', 'tokenization.FullTokenizer', ([], {'vocab_file': 'args.vocab_file', 'do_lower_case': '(True)'}), '(vocab_file=args.vocab_file, do_lower_case=True)\n', (9480, 9528), True, 'import bert.tokenization as tokenization\n'), ((7108, 7131), 'os.path.exists', 'os.path.exists', (['out_dir'], {}), '(out_dir)\n', (7122, 7131), False, 'import os\n'), ((7141, 7161), 'os.makedirs', 'os.makedirs', (['out_dir'], {}), '(out_dir)\n', (7152, 7161), False, 'import os\n'), ((7309, 7362), 'tensorflow.python_io.TFRecordWriter', 'tf.python_io.TFRecordWriter', (["(out_dir + '/' + out_file)"], {}), "(out_dir + '/' + out_file)\n", (7336, 7362), True, 'import tensorflow as tf\n'), ((4469, 4504), 'tensorflow.train.Features', 'tf.train.Features', ([], {'feature': 'features'}), '(feature=features)\n', (4486, 4504), True, 'import tensorflow as tf\n'), ((5458, 5491), 'tensorflow.train.BytesList', 'tf.train.BytesList', ([], {'value': '[value]'}), '(value=[value])\n', (5476, 5491), True, 'import tensorflow as tf\n'), ((4744, 4775), 'tensorflow.train.Int64List', 'tf.train.Int64List', ([], {'value': 'value'}), '(value=value)\n', (4762, 4775), True, 'import tensorflow as tf\n'), ((4830, 4863), 'tensorflow.train.Int64List', 'tf.train.Int64List', ([], {'value': '[value]'}), '(value=[value])\n', (4848, 4863), True, 'import tensorflow as tf\n'), ((5079, 5110), 'tensorflow.train.FloatList', 'tf.train.FloatList', ([], {'value': 'value'}), '(value=value)\n', (5097, 5110), True, 'import tensorflow as tf\n'), ((5165, 5198), 'tensorflow.train.FloatList', 'tf.train.FloatList', ([], {'value': '[value]'}), '(value=[value])\n', (5183, 5198), True, 'import tensorflow as tf\n'), ((7938, 7966), 'io.open', 'io.open', (['paper_json_filename'], {}), '(paper_json_filename)\n', (7945, 7966), False, 'import io\n'), ((8010, 8030), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (8019, 8030), False, 'import json\n'), ((8054, 8094), 'dateutil.parser.parse', 'parse_date', (["loaded['DATE_OF_SUBMISSION']"], {}), "(loaded['DATE_OF_SUBMISSION'])\n", (8064, 8094), True, 'from dateutil.parser import parse as parse_date\n')]
An7ar35/python-app-skeleton-structure
app/packageB/__init__.py
9060411bd32840c6510ad8fe18dcdc097c07b511
__all__=['module1']
[]
ZakDoesGaming/OregonTrail
lib/shop.py
90cab35536ac5c6ba9e772ac5c29c914017c9c23
from pygame import Surface, font from copy import copy from random import randint, choice import string from lib.transactionButton import TransactionButton SHOP_PREFIX = ["archer", "baker", "fisher", "miller", "rancher", "robber"] SHOP_SUFFIX = ["cave", "creek", "desert", "farm", "field", "forest", "hill", "lake", "mountain", "pass", "valley", "woods"] class Shop(): def __init__(self, name, inventory, priceModifier, groupInventory, groupMoney, itemPrices, position, blitPosition, money, resourcePath): self.yValue = 40 self.groupInventory = groupInventory self.groupMoney = groupMoney self.priceModifier = priceModifier self.itemPrices = itemPrices self.inventory = inventory self.position = position self.blitPosition = blitPosition self.resourcePath = resourcePath self.buyButtonList = [] self.sellButtonList = [] self.xPos = (-self.position * 40) + 1280 self.shopSurface = Surface((500, 300)).convert() self.sepLine = Surface((self.shopSurface.get_width(), 10)).convert() self.sepLine.fill((0, 0, 0)) self.invContainer = Surface((self.shopSurface.get_width() - 20, self.shopSurface.get_height() / 2 - 35)).convert() self.invContainer.fill((255, 255, 255)) self.titleFont = font.Font("res/fonts/west.ttf", 17) self.textFont = font.Font("res/fonts/west.ttf", 15) if (name == ""): self.name = (choice(SHOP_PREFIX) + "'s " + choice(SHOP_SUFFIX)).capitalize() else: self.name = name if (self.inventory == {}): inventoryRandom = copy(self.groupInventory) for key in list(inventoryRandom.keys()): inventoryRandom[key] = randint(0, 10) inventoryRandom["Food"] *= 20 self.inventory = inventoryRandom if (money is None): self.money = randint(200, 500) else: self.name = name self.render() def get_surface(self): self.render() return self.shopSurface def update(self, groupInv, groupMoney): self.groupInventory = groupInv self.groupMoney = groupMoney self.render() def move(self, moveValue): self.xPos += (2 * moveValue) self.render() def render(self): self.yValue = 40 self.shopSurface.fill((133, 94, 66)) self.shopSurface.blit(self.titleFont.render(self.name + " - $" + str(self.money), 1, (0, 0, 255)), (10, 5)) self.shopSurface.blit(self.invContainer, (10, 25)) self.shopSurface.blit(self.invContainer, (10, self.shopSurface.get_height() / 2 + 30)) self.shopSurface.blit(self.textFont.render("Inventory", 1, (255, 0, 0)), (10, 25)) self.shopSurface.blit(self.textFont.render("Amount", 1, (255, 0, 0)), (130, 25)) self.shopSurface.blit(self.textFont.render("Price", 1, (255, 0, 0)), (200, 25)) for key in list(self.inventory.keys()): self.shopSurface.blit(self.textFont.render(key + ":", 1, (0, 0, 0)), (10, self.yValue)) self.shopSurface.blit(self.textFont.render(str(self.inventory[key]), 1, (0, 0, 0)), (150, self.yValue)) self.shopSurface.blit(self.textFont.render("$"+str(self.itemPrices[key] * self.priceModifier), 1, (0, 0, 0)), (200, self.yValue)) if (len(self.buyButtonList) < len(self.inventory.keys())): buttonPos = tuple(map(sum, zip(self.blitPosition, (250, self.yValue)))) self.buyButtonList.append(TransactionButton(transaction = "buy", item = key, imagePosition = (250, self.yValue), rectPosition = buttonPos, resourcePath = self.resourcePath)) self.yValue += 30 for button in self.buyButtonList: self.shopSurface.blit(button.image, button.imagePosition) self.shopSurface.blit(self.sepLine, (0, float(self.shopSurface.get_height()) / 2)) self.shopSurface.blit(self.titleFont.render("You - $" + str(self.groupMoney), 1, (0, 0, 255)), (10, float(self.shopSurface.get_height()) / 2 + 10)) self.shopSurface.blit(self.titleFont.render("Inventory", 1, (255, 0, 0)), (10, float(self.shopSurface.get_height()) / 2 + 30)) self.shopSurface.blit(self.titleFont.render("Amount", 1, (255, 0, 0)), (130, float(self.shopSurface.get_height()) / 2 + 30)) self.shopSurface.blit(self.titleFont.render("Price", 1, (255, 0, 0)), (200, float(self.shopSurface.get_height()) / 2 + 30)) self.yValue = (float(self.shopSurface.get_height()) / 2) + 45 for key in list(self.groupInventory.keys()): self.shopSurface.blit(self.textFont.render(key + ":", 1, (0, 0, 0)), (10, self.yValue)) self.shopSurface.blit(self.textFont.render(str(self.groupInventory[key]), 1, (0, 0, 0)), (150, self.yValue)) self.shopSurface.blit(self.textFont.render("$" + str(self.itemPrices[key] * self.priceModifier), 1, (0, 0, 0)), (200, self.yValue)) if (len(self.sellButtonList) < len(self.inventory.keys())): buttonPos = tuple(map(sum, zip(self.blitPosition, (250, self.yValue)))) self.sellButtonList.append(TransactionButton(transaction = "sell", item = key, imagePosition = (250, self.yValue), rectPosition = buttonPos, resourcePath = self.resourcePath)) self.yValue += 30 for button in self.sellButtonList: self.shopSurface.blit(button.image, button.imagePosition)
[((1236, 1271), 'pygame.font.Font', 'font.Font', (['"""res/fonts/west.ttf"""', '(17)'], {}), "('res/fonts/west.ttf', 17)\n", (1245, 1271), False, 'from pygame import Surface, font\n'), ((1290, 1325), 'pygame.font.Font', 'font.Font', (['"""res/fonts/west.ttf"""', '(15)'], {}), "('res/fonts/west.ttf', 15)\n", (1299, 1325), False, 'from pygame import Surface, font\n'), ((1510, 1535), 'copy.copy', 'copy', (['self.groupInventory'], {}), '(self.groupInventory)\n', (1514, 1535), False, 'from copy import copy\n'), ((1738, 1755), 'random.randint', 'randint', (['(200)', '(500)'], {}), '(200, 500)\n', (1745, 1755), False, 'from random import randint, choice\n'), ((913, 932), 'pygame.Surface', 'Surface', (['(500, 300)'], {}), '((500, 300))\n', (920, 932), False, 'from pygame import Surface, font\n'), ((1607, 1621), 'random.randint', 'randint', (['(0)', '(10)'], {}), '(0, 10)\n', (1614, 1621), False, 'from random import randint, choice\n'), ((3230, 3371), 'lib.transactionButton.TransactionButton', 'TransactionButton', ([], {'transaction': '"""buy"""', 'item': 'key', 'imagePosition': '(250, self.yValue)', 'rectPosition': 'buttonPos', 'resourcePath': 'self.resourcePath'}), "(transaction='buy', item=key, imagePosition=(250, self.\n yValue), rectPosition=buttonPos, resourcePath=self.resourcePath)\n", (3247, 3371), False, 'from lib.transactionButton import TransactionButton\n'), ((4905, 5047), 'lib.transactionButton.TransactionButton', 'TransactionButton', ([], {'transaction': '"""sell"""', 'item': 'key', 'imagePosition': '(250, self.yValue)', 'rectPosition': 'buttonPos', 'resourcePath': 'self.resourcePath'}), "(transaction='sell', item=key, imagePosition=(250, self.\n yValue), rectPosition=buttonPos, resourcePath=self.resourcePath)\n", (4922, 5047), False, 'from lib.transactionButton import TransactionButton\n'), ((1394, 1413), 'random.choice', 'choice', (['SHOP_SUFFIX'], {}), '(SHOP_SUFFIX)\n', (1400, 1413), False, 'from random import randint, choice\n'), ((1364, 1383), 'random.choice', 'choice', (['SHOP_PREFIX'], {}), '(SHOP_PREFIX)\n', (1370, 1383), False, 'from random import randint, choice\n')]
ajmal017/amp
core/dataflow/test/test_runners.py
8de7e3b88be87605ec3bad03c139ac64eb460e5c
import logging import numpy as np import core.dataflow as dtf import helpers.unit_test as hut _LOG = logging.getLogger(__name__) class TestRollingFitPredictDagRunner(hut.TestCase): def test1(self) -> None: """ Test the DagRunner using `ArmaReturnsBuilder` """ dag_builder = dtf.ArmaReturnsBuilder() config = dag_builder.get_config_template() dag_builder.get_dag(config) # dag_runner = dtf.RollingFitPredictDagRunner( config=config, dag_builder=dag_builder, start="2010-01-04 09:30", end="2010-01-04 15:30", retraining_freq="H", retraining_lookback=4, ) result_bundles = list(dag_runner.fit_predict()) np.testing.assert_equal(len(result_bundles), 2) class TestIncrementalDagRunner(hut.TestCase): def test1(self) -> None: """ Test the DagRunner using `ArmaReturnsBuilder` """ dag_builder = dtf.ArmaReturnsBuilder() config = dag_builder.get_config_template() # Create DAG and generate fit state. dag = dag_builder.get_dag(config) dag.run_leq_node("rets/clip", "fit") fit_state = dtf.get_fit_state(dag) # dag_runner = dtf.IncrementalDagRunner( config=config, dag_builder=dag_builder, start="2010-01-04 15:30", end="2010-01-04 15:45", freq="5T", fit_state=fit_state, ) result_bundles = list(dag_runner.predict()) self.assertEqual(len(result_bundles), 4) # Check that dataframe results of `col` do not retroactively change # over successive prediction steps (which would suggest future # peeking). col = "vwap_ret_0_vol_2_hat" for rb_i, rb_i_next in zip(result_bundles[:-1], result_bundles[1:]): srs_i = rb_i.result_df[col] srs_i_next = rb_i_next.result_df[col] self.assertTrue(srs_i.compare(srs_i_next[:-1]).empty)
[((104, 131), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (121, 131), False, 'import logging\n'), ((316, 340), 'core.dataflow.ArmaReturnsBuilder', 'dtf.ArmaReturnsBuilder', ([], {}), '()\n', (338, 340), True, 'import core.dataflow as dtf\n'), ((459, 631), 'core.dataflow.RollingFitPredictDagRunner', 'dtf.RollingFitPredictDagRunner', ([], {'config': 'config', 'dag_builder': 'dag_builder', 'start': '"""2010-01-04 09:30"""', 'end': '"""2010-01-04 15:30"""', 'retraining_freq': '"""H"""', 'retraining_lookback': '(4)'}), "(config=config, dag_builder=dag_builder,\n start='2010-01-04 09:30', end='2010-01-04 15:30', retraining_freq='H',\n retraining_lookback=4)\n", (489, 631), True, 'import core.dataflow as dtf\n'), ((997, 1021), 'core.dataflow.ArmaReturnsBuilder', 'dtf.ArmaReturnsBuilder', ([], {}), '()\n', (1019, 1021), True, 'import core.dataflow as dtf\n'), ((1225, 1247), 'core.dataflow.get_fit_state', 'dtf.get_fit_state', (['dag'], {}), '(dag)\n', (1242, 1247), True, 'import core.dataflow as dtf\n'), ((1279, 1430), 'core.dataflow.IncrementalDagRunner', 'dtf.IncrementalDagRunner', ([], {'config': 'config', 'dag_builder': 'dag_builder', 'start': '"""2010-01-04 15:30"""', 'end': '"""2010-01-04 15:45"""', 'freq': '"""5T"""', 'fit_state': 'fit_state'}), "(config=config, dag_builder=dag_builder, start=\n '2010-01-04 15:30', end='2010-01-04 15:45', freq='5T', fit_state=fit_state)\n", (1303, 1430), True, 'import core.dataflow as dtf\n')]
hmnk-1967/OCR-Python-Project-CS-BUIC
Main Project/Main_Program.py
28c72d9913a25655f6183a7b960e527a0432c8e1
import tkinter.messagebox from tkinter import * import tkinter as tk from tkinter import filedialog import numpy import pytesseract #Python wrapper for Google-owned OCR engine known by the name of Tesseract. import cv2 from PIL import Image, ImageTk import os root = tk.Tk() root.title("Object Character Recognizer") root.geometry("1280x720") test_image = None def browse_image(): fin = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select Image File", filetypes=(("PNG Files", "*.png"), ("JPG Files", "*.jpg"), ("All Files", "*.*"))) global test_image image = Image.open(fin) test_image = image img = ImageTk.PhotoImage(image.resize((650, 400))) lb = tk.Label(image=img) lb.place(x=25, y=50) root.mainloop() def use_ocr_default(): try: global test_image messge = None #OEM stands for OCR Engine Mode and PSM stands for Page Segmentation Mode. #OEM defines what kind of OCR engine is to be used (this defines the dataset that would be used to cross-match #the available data with the testing data). #PSM defines how Tesseract will treat the image that supposedly contains characters and how it will extract the #data from the image. tess = pytesseract.image_to_string(test_image, config='-l eng --oem 1 --psm 3') label = Label(messge, text='Result:') label.place(x=850, y=320) display_message = Text(messge, width=46, height=15) display_message.insert(END, str(tess)) display_message.config(state=DISABLED) display_message.delete(0, END) display_message.place(x=890, y=330) except: #Print a error message when the user inputs an incompatible image. tkinter.messagebox.showinfo('Something\'s Wrong!', 'Your picture may not contain English characters or you may have not selected a picture. Please select a picture with detectable English characters.') def use_ocr_handwriting(): try: global test_image opencv_img = numpy.array(test_image) opencv_img = opencv_img[:, :, ::-1].copy() #This line is used to convert RGB PIL image file to BGR cv2 image file. blurred_img = cv2.medianBlur(opencv_img, 5) gray_img = cv2.cvtColor(blurred_img, cv2.COLOR_BGR2GRAY) thresh, binary = cv2.threshold(gray_img, 122, 255, cv2.THRESH_BINARY) messge = None tess = pytesseract.image_to_string(binary, config='-l eng --oem 1 --psm 3') label = Label(messge, text='Result:') label.place(x=850, y=320) display_message = Text(messge, width=46, height=15) display_message.insert(END, str(tess)) display_message.config(state=DISABLED) display_message.delete(0, END) display_message.place(x=890, y=330) except: tkinter.messagebox.showinfo('Something\'s Wrong!', 'Your picture may not contain English characters or you may have not selected a picture. Please select a picture with detectable English characters.') def use_ocr_singletext(): try: global test_image messge = None tess = pytesseract.image_to_string(test_image, config='-l eng --oem 1 --psm 7') label = Label(messge, text='Result:') label.place(x=850, y=320) display_message = Text(messge, width=46, height=15) display_message.insert(END, str(tess)) display_message.config(state=DISABLED) display_message.delete(0, END) display_message.place(x=890, y=330) except: tkinter.messagebox.showinfo('Something\'s Wrong!', 'Your picture may not contain English characters or you may have not selected a picture. Please select a picture with detectable English characters.') w = tk.LabelFrame(root, text="Image:", width=768, height=600) w.place(x=20, y=10) w.pack_propagate(0) w1 = tk.LabelFrame(root, text="Extracted Text:", width=500, height=310) w1.place(x=800, y=300) w2 = tk.LabelFrame(root, text="Operations:", width=350, height=280) w2.place(x=800, y=10) btn1 = tk.Button(w2, text="Load Image", padx=40, pady=10, command=browse_image) btn1.place(x=22, y=20) btn1 = tk.Button(w2, text="Run Handwritten OCR", padx=40, pady=10, command=use_ocr_handwriting) btn1.place(x=22, y=80) btn1 = tk.Button(w2, text="Run Default OCR", padx=40, pady=10, command=use_ocr_default) btn1.place(x=22, y=140) btn1 = tk.Button(w2, text="Run Single Text OCR", padx=40, pady=10, command=use_ocr_singletext) btn1.place(x=22, y=200) root.mainloop()
[((268, 275), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (273, 275), True, 'import tkinter as tk\n'), ((3726, 3783), 'tkinter.LabelFrame', 'tk.LabelFrame', (['root'], {'text': '"""Image:"""', 'width': '(768)', 'height': '(600)'}), "(root, text='Image:', width=768, height=600)\n", (3739, 3783), True, 'import tkinter as tk\n'), ((3829, 3895), 'tkinter.LabelFrame', 'tk.LabelFrame', (['root'], {'text': '"""Extracted Text:"""', 'width': '(500)', 'height': '(310)'}), "(root, text='Extracted Text:', width=500, height=310)\n", (3842, 3895), True, 'import tkinter as tk\n'), ((3924, 3986), 'tkinter.LabelFrame', 'tk.LabelFrame', (['root'], {'text': '"""Operations:"""', 'width': '(350)', 'height': '(280)'}), "(root, text='Operations:', width=350, height=280)\n", (3937, 3986), True, 'import tkinter as tk\n'), ((4016, 4088), 'tkinter.Button', 'tk.Button', (['w2'], {'text': '"""Load Image"""', 'padx': '(40)', 'pady': '(10)', 'command': 'browse_image'}), "(w2, text='Load Image', padx=40, pady=10, command=browse_image)\n", (4025, 4088), True, 'import tkinter as tk\n'), ((4119, 4212), 'tkinter.Button', 'tk.Button', (['w2'], {'text': '"""Run Handwritten OCR"""', 'padx': '(40)', 'pady': '(10)', 'command': 'use_ocr_handwriting'}), "(w2, text='Run Handwritten OCR', padx=40, pady=10, command=\n use_ocr_handwriting)\n", (4128, 4212), True, 'import tkinter as tk\n'), ((4238, 4323), 'tkinter.Button', 'tk.Button', (['w2'], {'text': '"""Run Default OCR"""', 'padx': '(40)', 'pady': '(10)', 'command': 'use_ocr_default'}), "(w2, text='Run Default OCR', padx=40, pady=10, command=use_ocr_default\n )\n", (4247, 4323), True, 'import tkinter as tk\n'), ((4350, 4442), 'tkinter.Button', 'tk.Button', (['w2'], {'text': '"""Run Single Text OCR"""', 'padx': '(40)', 'pady': '(10)', 'command': 'use_ocr_singletext'}), "(w2, text='Run Single Text OCR', padx=40, pady=10, command=\n use_ocr_singletext)\n", (4359, 4442), True, 'import tkinter as tk\n'), ((589, 604), 'PIL.Image.open', 'Image.open', (['fin'], {}), '(fin)\n', (599, 604), False, 'from PIL import Image, ImageTk\n'), ((692, 711), 'tkinter.Label', 'tk.Label', ([], {'image': 'img'}), '(image=img)\n', (700, 711), True, 'import tkinter as tk\n'), ((1257, 1329), 'pytesseract.image_to_string', 'pytesseract.image_to_string', (['test_image'], {'config': '"""-l eng --oem 1 --psm 3"""'}), "(test_image, config='-l eng --oem 1 --psm 3')\n", (1284, 1329), False, 'import pytesseract\n'), ((2021, 2044), 'numpy.array', 'numpy.array', (['test_image'], {}), '(test_image)\n', (2032, 2044), False, 'import numpy\n'), ((2190, 2219), 'cv2.medianBlur', 'cv2.medianBlur', (['opencv_img', '(5)'], {}), '(opencv_img, 5)\n', (2204, 2219), False, 'import cv2\n'), ((2239, 2284), 'cv2.cvtColor', 'cv2.cvtColor', (['blurred_img', 'cv2.COLOR_BGR2GRAY'], {}), '(blurred_img, cv2.COLOR_BGR2GRAY)\n', (2251, 2284), False, 'import cv2\n'), ((2310, 2362), 'cv2.threshold', 'cv2.threshold', (['gray_img', '(122)', '(255)', 'cv2.THRESH_BINARY'], {}), '(gray_img, 122, 255, cv2.THRESH_BINARY)\n', (2323, 2362), False, 'import cv2\n'), ((2400, 2468), 'pytesseract.image_to_string', 'pytesseract.image_to_string', (['binary'], {'config': '"""-l eng --oem 1 --psm 3"""'}), "(binary, config='-l eng --oem 1 --psm 3')\n", (2427, 2468), False, 'import pytesseract\n'), ((3108, 3180), 'pytesseract.image_to_string', 'pytesseract.image_to_string', (['test_image'], {'config': '"""-l eng --oem 1 --psm 7"""'}), "(test_image, config='-l eng --oem 1 --psm 7')\n", (3135, 3180), False, 'import pytesseract\n'), ((432, 443), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (441, 443), False, 'import os\n')]
wainshine/tensorflow
third_party/nasm/workspace.bzl
dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d
"""loads the nasm library, used by TF.""" load("//third_party:repo.bzl", "tf_http_archive") def repo(): tf_http_archive( name = "nasm", urls = [ "https://storage.googleapis.com/mirror.tensorflow.org/www.nasm.us/pub/nasm/releasebuilds/2.13.03/nasm-2.13.03.tar.bz2", "http://pkgs.fedoraproject.org/repo/pkgs/nasm/nasm-2.13.03.tar.bz2/sha512/d7a6b4cee8dfd603d8d4c976e5287b5cc542fa0b466ff989b743276a6e28114e64289bf02a7819eca63142a5278aa6eed57773007e5f589e15768e6456a8919d/nasm-2.13.03.tar.bz2", "http://www.nasm.us/pub/nasm/releasebuilds/2.13.03/nasm-2.13.03.tar.bz2", ], sha256 = "63ec86477ad3f0f6292325fd89e1d93aea2e2fd490070863f17d48f7cd387011", strip_prefix = "nasm-2.13.03", build_file = "//third_party/nasm:nasm.BUILD", system_build_file = "//third_party/nasm:BUILD.system", )
[]
wence-/libCEED
python/tests/test-1-vector.py
c785ad36304ed34c5edefb75cf1a0fe5445db17b
# Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at # the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights # reserved. See files LICENSE and NOTICE for details. # # This file is part of CEED, a collection of benchmarks, miniapps, software # libraries and APIs for efficient high-order finite element and spectral # element discretizations for exascale applications. For more information and # source code availability see http://github.com/ceed. # # The CEED research is supported by the Exascale Computing Project 17-SC-20-SC, # a collaborative effort of two U.S. Department of Energy organizations (Office # of Science and the National Nuclear Security Administration) responsible for # the planning and preparation of a capable exascale ecosystem, including # software, applications, hardware, advanced system engineering and early # testbed platforms, in support of the nation's exascale computing imperative. # @file # Test Ceed Vector functionality import os import libceed import numpy as np import check TOL = libceed.EPSILON * 256 # ------------------------------------------------------------------------------- # Utility # ------------------------------------------------------------------------------- def check_values(ceed, x, value): with x.array_read() as b: for i in range(len(b)): assert b[i] == value # ------------------------------------------------------------------------------- # Test creation, setting, reading, restoring, and destroying of a vector # ------------------------------------------------------------------------------- def test_100(ceed_resource): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) a = np.arange(10, 10 + n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.USE_POINTER) with x.array_read() as b: for i in range(n): assert b[i] == 10 + i # ------------------------------------------------------------------------------- # Test setValue # ------------------------------------------------------------------------------- def test_101(ceed_resource): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) value = 1 a = np.arange(10, 10 + n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.USE_POINTER) with x.array() as b: for i in range(len(b)): assert b[i] == 10 + i x.set_value(3.0) check_values(ceed, x, 3.0) del x x = ceed.Vector(n) # Set value before setting or getting the array x.set_value(5.0) check_values(ceed, x, 5.0) # ------------------------------------------------------------------------------- # Test getArrayRead state counter # ------------------------------------------------------------------------------- def test_102(ceed_resource): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) x.set_value(0) # Two read accesses should not generate an error a = x.get_array_read() b = x.get_array_read() x.restore_array_read() x.restore_array_read() # ------------------------------------------------------------------------------- # Test setting one vector from array of another vector # ------------------------------------------------------------------------------- def test_103(ceed_resource): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) y = ceed.Vector(n) a = np.arange(10, 10 + n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.USE_POINTER) with x.array() as x_array: y.set_array(x_array, cmode=libceed.USE_POINTER) with y.array_read() as y_array: for i in range(n): assert y_array[i] == 10 + i # ------------------------------------------------------------------------------- # Test getArray to modify array # ------------------------------------------------------------------------------- def test_104(ceed_resource): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) a = np.zeros(n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.USE_POINTER) with x.array() as b: b[3] = -3.14 if libceed.lib.CEED_SCALAR_TYPE == libceed.SCALAR_FP32: assert a[3] == np.float32(-3.14) else: assert a[3] == -3.14 # ------------------------------------------------------------------------------- # Test creation, setting, reading, restoring, and destroying of a vector using # CEED_MEM_DEVICE # ------------------------------------------------------------------------------- def test_105(ceed_resource): # Skip test for non-GPU backend if 'gpu' in ceed_resource: ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) y = ceed.Vector(n) a = np.arange(10, 10 + n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.USE_POINTER) arr = x.get_array_read(memtype=libceed.MEM_DEVICE) y.set_array(arr, memtype=libceed.MEM_DEVICE) x.restore_array_read() with y.array_read() as b: for i in range(n): assert b[i] == 10 + i # ------------------------------------------------------------------------------- # Test view # ------------------------------------------------------------------------------- def test_107(ceed_resource, capsys): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) a = np.arange(10, 10 + n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.USE_POINTER) print(x) stdout, stderr, ref_stdout = check.output(capsys) assert not stderr assert stdout == ref_stdout # ------------------------------------------------------------------------------- # Test norms # ------------------------------------------------------------------------------- def test_108(ceed_resource, capsys): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) a = np.arange(0, n, dtype=ceed.scalar_type()) for i in range(n): if (i % 2 == 0): a[i] *= -1 x.set_array(a, cmode=libceed.USE_POINTER) norm = x.norm(normtype=libceed.NORM_1) assert abs(norm - 45.) < TOL norm = x.norm() assert abs(norm - np.sqrt(285.)) < TOL norm = x.norm(normtype=libceed.NORM_MAX) assert abs(norm - 9.) < TOL # ------------------------------------------------------------------------------- # Test taking the reciprocal of a vector # ------------------------------------------------------------------------------- def test_119(ceed_resource): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) a = np.arange(10, 10 + n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.USE_POINTER) x.reciprocal() with x.array_read() as b: for i in range(n): assert abs(b[i] - 1. / (10 + i)) < TOL # ------------------------------------------------------------------------------- # Test AXPY # ------------------------------------------------------------------------------- def test_121(ceed_resource, capsys): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) y = ceed.Vector(n) a = np.arange(10, 10 + n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.COPY_VALUES) y.set_array(a, cmode=libceed.COPY_VALUES) y.axpy(-0.5, x) with y.array() as b: assert np.allclose(.5 * a, b) # ------------------------------------------------------------------------------- # Test pointwise multiplication # ------------------------------------------------------------------------------- def test_122(ceed_resource, capsys): ceed = libceed.Ceed(ceed_resource) n = 10 w = ceed.Vector(n) x = ceed.Vector(n) y = ceed.Vector(n) a = np.arange(0, n, dtype=ceed.scalar_type()) w.set_array(a, cmode=libceed.COPY_VALUES) x.set_array(a, cmode=libceed.COPY_VALUES) y.set_array(a, cmode=libceed.COPY_VALUES) w.pointwise_mult(x, y) with w.array() as b: for i in range(len(b)): assert abs(b[i] - i * i) < 1e-14 w.pointwise_mult(w, y) with w.array() as b: for i in range(len(b)): assert abs(b[i] - i * i * i) < 1e-14 w.pointwise_mult(x, w) with w.array() as b: for i in range(len(b)): assert abs(b[i] - i * i * i * i) < 1e-14 y.pointwise_mult(y, y) with y.array() as b: for i in range(len(b)): assert abs(b[i] - i * i) < 1e-14 # ------------------------------------------------------------------------------- # Test Scale # ------------------------------------------------------------------------------- def test_123(ceed_resource, capsys): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) a = np.arange(10, 10 + n, dtype=ceed.scalar_type()) x.set_array(a, cmode=libceed.COPY_VALUES) x.scale(-0.5) with x.array() as b: assert np.allclose(-.5 * a, b) # ------------------------------------------------------------------------------- # Test getArrayWrite to modify array # ------------------------------------------------------------------------------- def test_124(ceed_resource): ceed = libceed.Ceed(ceed_resource) n = 10 x = ceed.Vector(n) with x.array_write() as a: for i in range(len(a)): a[i] = 3 * i with x.array_read() as a: for i in range(len(a)): assert a[i] == 3 * i # ------------------------------------------------------------------------------- # Test modification of reshaped array # ------------------------------------------------------------------------------- def test_199(ceed_resource): """Modification of reshaped array""" ceed = libceed.Ceed(ceed_resource) vec = ceed.Vector(12) vec.set_value(0.0) with vec.array(4, 3) as x: x[...] = np.eye(4, 3) with vec.array_read(3, 4) as x: assert np.all(x == np.eye(4, 3).reshape(3, 4)) # -------------------------------------------------------------------------------
[((1674, 1701), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (1686, 1701), False, 'import libceed\n'), ((2155, 2182), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (2167, 2182), False, 'import libceed\n'), ((2857, 2884), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (2869, 2884), False, 'import libceed\n'), ((3364, 3391), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (3376, 3391), False, 'import libceed\n'), ((3985, 4012), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (3997, 4012), False, 'import libceed\n'), ((5390, 5417), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (5402, 5417), False, 'import libceed\n'), ((5604, 5624), 'check.output', 'check.output', (['capsys'], {}), '(capsys)\n', (5616, 5624), False, 'import check\n'), ((5907, 5934), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (5919, 5934), False, 'import libceed\n'), ((6608, 6635), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (6620, 6635), False, 'import libceed\n'), ((7129, 7156), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (7141, 7156), False, 'import libceed\n'), ((7695, 7722), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (7707, 7722), False, 'import libceed\n'), ((8753, 8780), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (8765, 8780), False, 'import libceed\n'), ((9246, 9273), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (9258, 9273), False, 'import libceed\n'), ((9781, 9808), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (9793, 9808), False, 'import libceed\n'), ((4706, 4733), 'libceed.Ceed', 'libceed.Ceed', (['ceed_resource'], {}), '(ceed_resource)\n', (4718, 4733), False, 'import libceed\n'), ((7425, 7448), 'numpy.allclose', 'np.allclose', (['(0.5 * a)', 'b'], {}), '(0.5 * a, b)\n', (7436, 7448), True, 'import numpy as np\n'), ((8978, 9002), 'numpy.allclose', 'np.allclose', (['(-0.5 * a)', 'b'], {}), '(-0.5 * a, b)\n', (8989, 9002), True, 'import numpy as np\n'), ((9907, 9919), 'numpy.eye', 'np.eye', (['(4)', '(3)'], {}), '(4, 3)\n', (9913, 9919), True, 'import numpy as np\n'), ((4272, 4289), 'numpy.float32', 'np.float32', (['(-3.14)'], {}), '(-3.14)\n', (4282, 4289), True, 'import numpy as np\n'), ((6260, 6274), 'numpy.sqrt', 'np.sqrt', (['(285.0)'], {}), '(285.0)\n', (6267, 6274), True, 'import numpy as np\n'), ((9984, 9996), 'numpy.eye', 'np.eye', (['(4)', '(3)'], {}), '(4, 3)\n', (9990, 9996), True, 'import numpy as np\n')]
aperezpredictia/ESMValCore
esmvalcore/cmor/_fixes/cmip6/cesm2.py
d5bf3f459ff3a43e780d75d57b63b88b6cc8c4f2
"""Fixes for CESM2 model.""" from ..fix import Fix from ..shared import (add_scalar_depth_coord, add_scalar_height_coord, add_scalar_typeland_coord, add_scalar_typesea_coord) class Fgco2(Fix): """Fixes for fgco2.""" def fix_metadata(self, cubes): """Add depth (0m) coordinate. Parameters ---------- cube : iris.cube.CubeList Returns ------- iris.cube.Cube """ cube = self.get_cube_from_list(cubes) add_scalar_depth_coord(cube) return cubes class Tas(Fix): """Fixes for tas.""" def fix_metadata(self, cubes): """Add height (2m) coordinate. Parameters ---------- cube : iris.cube.CubeList Returns ------- iris.cube.Cube """ cube = self.get_cube_from_list(cubes) add_scalar_height_coord(cube) return cubes class Sftlf(Fix): """Fixes for sftlf.""" def fix_metadata(self, cubes): """Add typeland coordinate. Parameters ---------- cube : iris.cube.CubeList Returns ------- iris.cube.Cube """ cube = self.get_cube_from_list(cubes) add_scalar_typeland_coord(cube) return cubes class Sftof(Fix): """Fixes for sftof.""" def fix_metadata(self, cubes): """Add typesea coordinate. Parameters ---------- cube : iris.cube.CubeList Returns ------- iris.cube.Cube """ cube = self.get_cube_from_list(cubes) add_scalar_typesea_coord(cube) return cubes
[]
vitay/YouTubeFacesDB
examples/GenerateSubset.py
e7225e8d775ad64889fbee57a4452a25573a0360
from YouTubeFacesDB import generate_ytf_database ############################################################################### # Create the dataset ############################################################################### generate_ytf_database( directory= '../data',#'/scratch/vitay/Datasets/YouTubeFaces', # Location of the YTF dataset filename='ytfdb.h5', # Name of the HDF5 file to write to labels=10, # Number of labels to randomly select max_number=-1, # Maximum number of images to use size=(100, 100), # Size of the images color=False, # Black and white bw_first=True, # Final shape is (1, w, h) cropped=True # The original images are cropped to the faces )
[((231, 383), 'YouTubeFacesDB.generate_ytf_database', 'generate_ytf_database', ([], {'directory': '"""../data"""', 'filename': '"""ytfdb.h5"""', 'labels': '(10)', 'max_number': '(-1)', 'size': '(100, 100)', 'color': '(False)', 'bw_first': '(True)', 'cropped': '(True)'}), "(directory='../data', filename='ytfdb.h5', labels=10,\n max_number=-1, size=(100, 100), color=False, bw_first=True, cropped=True)\n", (252, 383), False, 'from YouTubeFacesDB import generate_ytf_database\n')]
opennode/nodeconductor-assembly-waldur
src/waldur_mastermind/billing/tests/test_price_current.py
cad9966389dc9b52b13d2301940c99cf4b243900
from freezegun import freeze_time from rest_framework import test from waldur_mastermind.billing.tests.utils import get_financial_report_url from waldur_mastermind.invoices import models as invoice_models from waldur_mastermind.invoices.tests import factories as invoice_factories from waldur_mastermind.invoices.tests import fixtures as invoice_fixtures @freeze_time('2017-01-10') class PriceCurrentTest(test.APITransactionTestCase): def setUp(self): self.fixture = invoice_fixtures.InvoiceFixture() invoice_factories.InvoiceItemFactory( invoice=self.fixture.invoice, project=self.fixture.project, unit=invoice_models.InvoiceItem.Units.PER_MONTH, unit_price=100, quantity=1, ) invoice_factories.InvoiceItemFactory( invoice=self.fixture.invoice, project=self.fixture.project, unit=invoice_models.InvoiceItem.Units.PER_DAY, unit_price=3, quantity=31, ) def test_current_price(self): self.client.force_authenticate(self.fixture.staff) url = get_financial_report_url(self.fixture.project.customer) response = self.client.get(url) self.assertEqual(response.status_code, 200) data = response.json() self.assertEqual(data['billing_price_estimate']['current'], 100 + 9 * 3) diff = ( data['billing_price_estimate']['total'] - data['billing_price_estimate']['current'] ) self.assertEqual(diff, 22 * 3)
[((359, 384), 'freezegun.freeze_time', 'freeze_time', (['"""2017-01-10"""'], {}), "('2017-01-10')\n", (370, 384), False, 'from freezegun import freeze_time\n'), ((482, 515), 'waldur_mastermind.invoices.tests.fixtures.InvoiceFixture', 'invoice_fixtures.InvoiceFixture', ([], {}), '()\n', (513, 515), True, 'from waldur_mastermind.invoices.tests import fixtures as invoice_fixtures\n'), ((525, 707), 'waldur_mastermind.invoices.tests.factories.InvoiceItemFactory', 'invoice_factories.InvoiceItemFactory', ([], {'invoice': 'self.fixture.invoice', 'project': 'self.fixture.project', 'unit': 'invoice_models.InvoiceItem.Units.PER_MONTH', 'unit_price': '(100)', 'quantity': '(1)'}), '(invoice=self.fixture.invoice, project=\n self.fixture.project, unit=invoice_models.InvoiceItem.Units.PER_MONTH,\n unit_price=100, quantity=1)\n', (561, 707), True, 'from waldur_mastermind.invoices.tests import factories as invoice_factories\n'), ((778, 957), 'waldur_mastermind.invoices.tests.factories.InvoiceItemFactory', 'invoice_factories.InvoiceItemFactory', ([], {'invoice': 'self.fixture.invoice', 'project': 'self.fixture.project', 'unit': 'invoice_models.InvoiceItem.Units.PER_DAY', 'unit_price': '(3)', 'quantity': '(31)'}), '(invoice=self.fixture.invoice, project=\n self.fixture.project, unit=invoice_models.InvoiceItem.Units.PER_DAY,\n unit_price=3, quantity=31)\n', (814, 957), True, 'from waldur_mastermind.invoices.tests import factories as invoice_factories\n'), ((1128, 1183), 'waldur_mastermind.billing.tests.utils.get_financial_report_url', 'get_financial_report_url', (['self.fixture.project.customer'], {}), '(self.fixture.project.customer)\n', (1152, 1183), False, 'from waldur_mastermind.billing.tests.utils import get_financial_report_url\n')]
ejfitzgerald/agents-aea
tests/test_cli/test_utils/test_utils.py
6411fcba8af2cdf55a3005939ae8129df92e8c3e
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ------------------------------------------------------------------------------ """This test module contains the tests for aea.cli.utils module.""" from builtins import FileNotFoundError from typing import cast from unittest import TestCase, mock from click import BadParameter, ClickException from jsonschema import ValidationError from yaml import YAMLError from aea.cli.utils.click_utils import AEAJsonPathType, PublicIdParameter from aea.cli.utils.config import ( _init_cli_config, get_or_create_cli_config, update_cli_config, ) from aea.cli.utils.context import Context from aea.cli.utils.decorators import _validate_config_consistency, clean_after from aea.cli.utils.formatting import format_items from aea.cli.utils.generic import is_readme_present from aea.cli.utils.package_utils import ( find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name, ) from tests.conftest import FETCHAI from tests.test_cli.tools_for_testing import ( ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest, ) AUTHOR = "author" class FormatItemsTestCase(TestCase): """Test case for format_items method.""" def testformat_items_positive(self): """Test format_items positive result.""" items = [ { "public_id": "author/name:version", "name": "obj-name", "description": "Some description", "author": "author", "version": "1.0", } ] result = format_items(items) expected_result = ( "------------------------------\n" "Public ID: author/name:version\n" "Name: obj-name\n" "Description: Some description\n" "Author: author\n" "Version: 1.0\n" "------------------------------\n" ) self.assertEqual(result, expected_result) @mock.patch("aea.cli.utils.package_utils.os.path.join", return_value="some-path") class TryGetItemSourcePathTestCase(TestCase): """Test case for try_get_item_source_path method.""" @mock.patch("aea.cli.utils.package_utils.os.path.exists", return_value=True) def test_get_item_source_path_positive(self, exists_mock, join_mock): """Test for get_item_source_path positive result.""" result = try_get_item_source_path("cwd", AUTHOR, "skills", "skill-name") expected_result = "some-path" self.assertEqual(result, expected_result) join_mock.assert_called_once_with("cwd", AUTHOR, "skills", "skill-name") exists_mock.assert_called_once_with("some-path") result = try_get_item_source_path("cwd", None, "skills", "skill-name") self.assertEqual(result, expected_result) @mock.patch("aea.cli.utils.package_utils.os.path.exists", return_value=False) def test_get_item_source_path_not_exists(self, exists_mock, join_mock): """Test for get_item_source_path item already exists.""" with self.assertRaises(ClickException): try_get_item_source_path("cwd", AUTHOR, "skills", "skill-name") @mock.patch("aea.cli.utils.package_utils.os.path.join", return_value="some-path") class TryGetItemTargetPathTestCase(TestCase): """Test case for try_get_item_target_path method.""" @mock.patch("aea.cli.utils.package_utils.os.path.exists", return_value=False) def test_get_item_target_path_positive(self, exists_mock, join_mock): """Test for get_item_source_path positive result.""" result = try_get_item_target_path("packages", AUTHOR, "skills", "skill-name") expected_result = "some-path" self.assertEqual(result, expected_result) join_mock.assert_called_once_with("packages", AUTHOR, "skills", "skill-name") exists_mock.assert_called_once_with("some-path") @mock.patch("aea.cli.utils.package_utils.os.path.exists", return_value=True) def test_get_item_target_path_already_exists(self, exists_mock, join_mock): """Test for get_item_target_path item already exists.""" with self.assertRaises(ClickException): try_get_item_target_path("skills", AUTHOR, "skill-name", "packages_path") class PublicIdParameterTestCase(TestCase): """Test case for PublicIdParameter class.""" def test_get_metavar_positive(self): """Test for get_metavar positive result.""" result = PublicIdParameter.get_metavar("obj", "param") expected_result = "PUBLIC_ID" self.assertEqual(result, expected_result) @mock.patch("aea.cli.utils.config.os.path.dirname", return_value="dir-name") @mock.patch("aea.cli.utils.config.os.path.exists", return_value=False) @mock.patch("aea.cli.utils.config.os.makedirs") @mock.patch("builtins.open") class InitConfigFolderTestCase(TestCase): """Test case for _init_cli_config method.""" def test_init_cli_config_positive( self, open_mock, makedirs_mock, exists_mock, dirname_mock ): """Test for _init_cli_config method positive result.""" _init_cli_config() dirname_mock.assert_called_once() exists_mock.assert_called_once_with("dir-name") makedirs_mock.assert_called_once_with("dir-name") @mock.patch("aea.cli.utils.config.get_or_create_cli_config") @mock.patch("aea.cli.utils.generic.yaml.dump") @mock.patch("builtins.open", mock.mock_open()) class UpdateCLIConfigTestCase(TestCase): """Test case for update_cli_config method.""" def testupdate_cli_config_positive(self, dump_mock, icf_mock): """Test for update_cli_config method positive result.""" update_cli_config({"some": "config"}) icf_mock.assert_called_once() dump_mock.assert_called_once() def _raise_yamlerror(*args): raise YAMLError() def _raise_file_not_found_error(*args): raise FileNotFoundError() @mock.patch("builtins.open", mock.mock_open()) class GetOrCreateCLIConfigTestCase(TestCase): """Test case for read_cli_config method.""" @mock.patch( "aea.cli.utils.generic.yaml.safe_load", return_value={"correct": "output"} ) def testget_or_create_cli_config_positive(self, safe_load_mock): """Test for get_or_create_cli_config method positive result.""" result = get_or_create_cli_config() expected_result = {"correct": "output"} self.assertEqual(result, expected_result) safe_load_mock.assert_called_once() @mock.patch("aea.cli.utils.generic.yaml.safe_load", _raise_yamlerror) def testget_or_create_cli_config_bad_yaml(self): """Test for rget_or_create_cli_config method bad yaml behavior.""" with self.assertRaises(ClickException): get_or_create_cli_config() class CleanAfterTestCase(TestCase): """Test case for clean_after decorator method.""" @mock.patch("aea.cli.utils.decorators.os.path.exists", return_value=True) @mock.patch("aea.cli.utils.decorators._cast_ctx", lambda x: x) @mock.patch("aea.cli.utils.decorators.shutil.rmtree") def test_clean_after_positive(self, rmtree_mock, *mocks): """Test clean_after decorator method for positive result.""" @clean_after def func(click_context): ctx = cast(Context, click_context.obj) ctx.clean_paths.append("clean/path") raise ClickException("Message") with self.assertRaises(ClickException): func(ContextMock()) rmtree_mock.assert_called_once_with("clean/path") @mock.patch("aea.cli.utils.package_utils.click.echo", raise_stoptest) class ValidateAuthorNameTestCase(TestCase): """Test case for validate_author_name method.""" @mock.patch( "aea.cli.utils.package_utils.click.prompt", return_value="correct_author" ) def test_validate_author_name_positive(self, prompt_mock): """Test validate_author_name for positive result.""" author = "valid_author" result = validate_author_name(author=author) self.assertEqual(result, author) result = validate_author_name() self.assertEqual(result, "correct_author") prompt_mock.assert_called_once() @mock.patch( "aea.cli.utils.package_utils.click.prompt", return_value="inv@l1d_@uth&r" ) def test_validate_author_name_negative(self, prompt_mock): """Test validate_author_name for negative result.""" with self.assertRaises(StopTest): validate_author_name() prompt_mock.return_value = "skills" with self.assertRaises(StopTest): validate_author_name() class ValidatePackageNameTestCase(TestCase): """Test case for validate_package_name method.""" def test_validate_package_name_positive(self): """Test validate_package_name for positive result.""" validate_package_name("correct_name") def test_validate_package_name_negative(self): """Test validate_package_name for negative result.""" with self.assertRaises(BadParameter): validate_package_name("incorrect-name") def _raise_validation_error(*args, **kwargs): raise ValidationError("Message.") class FindItemLocallyTestCase(TestCase): """Test case for find_item_locally method.""" @mock.patch("aea.cli.utils.package_utils.Path.exists", return_value=True) @mock.patch( "aea.cli.utils.package_utils.ConfigLoader.from_configuration_type", _raise_validation_error, ) def test_find_item_locally_bad_config(self, *mocks): """Test find_item_locally for bad config result.""" public_id = PublicIdMock.from_str("fetchai/echo:0.5.0") with self.assertRaises(ClickException) as cm: find_item_locally(ContextMock(), "skill", public_id) self.assertIn("configuration file not valid", cm.exception.message) @mock.patch("aea.cli.utils.package_utils.Path.exists", return_value=True) @mock.patch("aea.cli.utils.package_utils.Path.open", mock.mock_open()) @mock.patch( "aea.cli.utils.package_utils.ConfigLoader.from_configuration_type", return_value=ConfigLoaderMock(), ) def test_find_item_locally_cant_find(self, from_conftype_mock, *mocks): """Test find_item_locally for can't find result.""" public_id = PublicIdMock.from_str("fetchai/echo:0.5.0") with self.assertRaises(ClickException) as cm: find_item_locally(ContextMock(), "skill", public_id) self.assertEqual( cm.exception.message, "Cannot find skill with author and version specified." ) class FindItemInDistributionTestCase(TestCase): """Test case for find_item_in_distribution method.""" @mock.patch("aea.cli.utils.package_utils.Path.exists", return_value=True) @mock.patch( "aea.cli.utils.package_utils.ConfigLoader.from_configuration_type", _raise_validation_error, ) def testfind_item_in_distribution_bad_config(self, *mocks): """Test find_item_in_distribution for bad config result.""" public_id = PublicIdMock.from_str("fetchai/echo:0.5.0") with self.assertRaises(ClickException) as cm: find_item_in_distribution(ContextMock(), "skill", public_id) self.assertIn("configuration file not valid", cm.exception.message) @mock.patch("aea.cli.utils.package_utils.Path.exists", return_value=False) def testfind_item_in_distribution_not_found(self, *mocks): """Test find_item_in_distribution for not found result.""" public_id = PublicIdMock.from_str("fetchai/echo:0.5.0") with self.assertRaises(ClickException) as cm: find_item_in_distribution(ContextMock(), "skill", public_id) self.assertIn("Cannot find skill", cm.exception.message) @mock.patch("aea.cli.utils.package_utils.Path.exists", return_value=True) @mock.patch("aea.cli.utils.package_utils.Path.open", mock.mock_open()) @mock.patch( "aea.cli.utils.package_utils.ConfigLoader.from_configuration_type", return_value=ConfigLoaderMock(), ) def testfind_item_in_distribution_cant_find(self, from_conftype_mock, *mocks): """Test find_item_locally for can't find result.""" public_id = PublicIdMock.from_str("fetchai/echo:0.5.0") with self.assertRaises(ClickException) as cm: find_item_in_distribution(ContextMock(), "skill", public_id) self.assertEqual( cm.exception.message, "Cannot find skill with author and version specified." ) class ValidateConfigConsistencyTestCase(TestCase): """Test case for _validate_config_consistency method.""" @mock.patch("aea.cli.utils.config.Path.exists", _raise_validation_error) def test__validate_config_consistency_cant_find(self, *mocks): """Test _validate_config_consistency can't find result""" with self.assertRaises(ValueError) as cm: _validate_config_consistency(ContextMock(protocols=["some"])) self.assertIn("Cannot find", str(cm.exception)) @mock.patch( "aea.cli.utils.package_utils._compute_fingerprint", return_value={"correct": "fingerprint"}, ) class IsFingerprintCorrectTestCase(TestCase): """Test case for adding skill with invalid fingerprint.""" def test_is_fingerprint_correct_positive(self, *mocks): """Test is_fingerprint_correct method for positive result.""" item_config = mock.Mock() item_config.fingerprint = {"correct": "fingerprint"} item_config.fingerprint_ignore_patterns = [] result = is_fingerprint_correct("package_path", item_config) self.assertTrue(result) def test_is_fingerprint_correct_negative(self, *mocks): """Test is_fingerprint_correct method for negative result.""" item_config = mock.Mock() item_config.fingerprint = {"incorrect": "fingerprint"} item_config.fingerprint_ignore_patterns = [] package_path = "package_dir" result = is_fingerprint_correct(package_path, item_config) self.assertFalse(result) @mock.patch("aea.cli.config.click.ParamType") class AEAJsonPathTypeTestCase(TestCase): """Test case for AEAJsonPathType class.""" @mock.patch("aea.cli.utils.click_utils.Path.exists", return_value=True) def test_convert_root_vendor_positive(self, *mocks): """Test for convert method with root "vendor" positive result.""" value = "vendor.author.protocols.package_name.attribute_name" ctx_mock = ContextMock() ctx_mock.obj = mock.Mock() ctx_mock.obj.set_config = mock.Mock() obj = AEAJsonPathType() obj.convert(value, "param", ctx_mock) @mock.patch("aea.cli.utils.click_utils.Path.exists", return_value=False) def test_convert_root_vendor_path_not_exists(self, *mocks): """Test for convert method with root "vendor" path not exists.""" value = "vendor.author.protocols.package_name.attribute_name" obj = AEAJsonPathType() with self.assertRaises(BadParameter): obj.convert(value, "param", "ctx") @mock.patch("aea.cli.utils.package_utils.LedgerApis", mock.MagicMock()) class TryGetBalanceTestCase(TestCase): """Test case for try_get_balance method.""" def test_try_get_balance_positive(self): """Test for try_get_balance method positive result.""" agent_config = mock.Mock() agent_config.default_ledger_config = FETCHAI wallet_mock = mock.Mock() wallet_mock.addresses = {FETCHAI: "some-adress"} try_get_balance(agent_config, wallet_mock, FETCHAI) @mock.patch("aea.cli.utils.generic.os.path.exists", return_value=True) class IsReadmePresentTestCase(TestCase): """Test case for is_readme_present method.""" def test_is_readme_present_positive(self, *mocks): """Test is_readme_present for positive result.""" self.assertTrue(is_readme_present("readme/path"))
[((2790, 2875), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.os.path.join"""'], {'return_value': '"""some-path"""'}), "('aea.cli.utils.package_utils.os.path.join', return_value='some-path'\n )\n", (2800, 2875), False, 'from unittest import TestCase, mock\n'), ((3979, 4064), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.os.path.join"""'], {'return_value': '"""some-path"""'}), "('aea.cli.utils.package_utils.os.path.join', return_value='some-path'\n )\n", (3989, 4064), False, 'from unittest import TestCase, mock\n'), ((5401, 5476), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.config.os.path.dirname"""'], {'return_value': '"""dir-name"""'}), "('aea.cli.utils.config.os.path.dirname', return_value='dir-name')\n", (5411, 5476), False, 'from unittest import TestCase, mock\n'), ((5478, 5547), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.config.os.path.exists"""'], {'return_value': '(False)'}), "('aea.cli.utils.config.os.path.exists', return_value=False)\n", (5488, 5547), False, 'from unittest import TestCase, mock\n'), ((5549, 5595), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.config.os.makedirs"""'], {}), "('aea.cli.utils.config.os.makedirs')\n", (5559, 5595), False, 'from unittest import TestCase, mock\n'), ((5597, 5624), 'unittest.mock.patch', 'mock.patch', (['"""builtins.open"""'], {}), "('builtins.open')\n", (5607, 5624), False, 'from unittest import TestCase, mock\n'), ((6079, 6138), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.config.get_or_create_cli_config"""'], {}), "('aea.cli.utils.config.get_or_create_cli_config')\n", (6089, 6138), False, 'from unittest import TestCase, mock\n'), ((6140, 6185), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.generic.yaml.dump"""'], {}), "('aea.cli.utils.generic.yaml.dump')\n", (6150, 6185), False, 'from unittest import TestCase, mock\n'), ((8344, 8412), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.click.echo"""', 'raise_stoptest'], {}), "('aea.cli.utils.package_utils.click.echo', raise_stoptest)\n", (8354, 8412), False, 'from unittest import TestCase, mock\n'), ((13856, 13964), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils._compute_fingerprint"""'], {'return_value': "{'correct': 'fingerprint'}"}), "('aea.cli.utils.package_utils._compute_fingerprint', return_value\n ={'correct': 'fingerprint'})\n", (13866, 13964), False, 'from unittest import TestCase, mock\n'), ((14881, 14925), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.config.click.ParamType"""'], {}), "('aea.cli.config.click.ParamType')\n", (14891, 14925), False, 'from unittest import TestCase, mock\n'), ((16408, 16477), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.generic.os.path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.generic.os.path.exists', return_value=True)\n", (16418, 16477), False, 'from unittest import TestCase, mock\n'), ((2980, 3055), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.os.path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.package_utils.os.path.exists', return_value=True)\n", (2990, 3055), False, 'from unittest import TestCase, mock\n'), ((3634, 3710), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.os.path.exists"""'], {'return_value': '(False)'}), "('aea.cli.utils.package_utils.os.path.exists', return_value=False)\n", (3644, 3710), False, 'from unittest import TestCase, mock\n'), ((4169, 4245), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.os.path.exists"""'], {'return_value': '(False)'}), "('aea.cli.utils.package_utils.os.path.exists', return_value=False)\n", (4179, 4245), False, 'from unittest import TestCase, mock\n'), ((4704, 4779), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.os.path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.package_utils.os.path.exists', return_value=True)\n", (4714, 4779), False, 'from unittest import TestCase, mock\n'), ((6215, 6231), 'unittest.mock.mock_open', 'mock.mock_open', ([], {}), '()\n', (6229, 6231), False, 'from unittest import TestCase, mock\n'), ((6621, 6632), 'yaml.YAMLError', 'YAMLError', ([], {}), '()\n', (6630, 6632), False, 'from yaml import YAMLError\n'), ((6685, 6704), 'builtins.FileNotFoundError', 'FileNotFoundError', ([], {}), '()\n', (6702, 6704), False, 'from builtins import FileNotFoundError\n'), ((6854, 6944), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.generic.yaml.safe_load"""'], {'return_value': "{'correct': 'output'}"}), "('aea.cli.utils.generic.yaml.safe_load', return_value={'correct':\n 'output'})\n", (6864, 6944), False, 'from unittest import TestCase, mock\n'), ((7288, 7356), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.generic.yaml.safe_load"""', '_raise_yamlerror'], {}), "('aea.cli.utils.generic.yaml.safe_load', _raise_yamlerror)\n", (7298, 7356), False, 'from unittest import TestCase, mock\n'), ((6736, 6752), 'unittest.mock.mock_open', 'mock.mock_open', ([], {}), '()\n', (6750, 6752), False, 'from unittest import TestCase, mock\n'), ((7670, 7742), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.decorators.os.path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.decorators.os.path.exists', return_value=True)\n", (7680, 7742), False, 'from unittest import TestCase, mock\n'), ((7748, 7809), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.decorators._cast_ctx"""', '(lambda x: x)'], {}), "('aea.cli.utils.decorators._cast_ctx', lambda x: x)\n", (7758, 7809), False, 'from unittest import TestCase, mock\n'), ((7815, 7867), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.decorators.shutil.rmtree"""'], {}), "('aea.cli.utils.decorators.shutil.rmtree')\n", (7825, 7867), False, 'from unittest import TestCase, mock\n'), ((8516, 8606), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.click.prompt"""'], {'return_value': '"""correct_author"""'}), "('aea.cli.utils.package_utils.click.prompt', return_value=\n 'correct_author')\n", (8526, 8606), False, 'from unittest import TestCase, mock\n'), ((9005, 9095), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.click.prompt"""'], {'return_value': '"""inv@l1d_@uth&r"""'}), "('aea.cli.utils.package_utils.click.prompt', return_value=\n 'inv@l1d_@uth&r')\n", (9015, 9095), False, 'from unittest import TestCase, mock\n'), ((9959, 9986), 'jsonschema.ValidationError', 'ValidationError', (['"""Message."""'], {}), "('Message.')\n", (9974, 9986), False, 'from jsonschema import ValidationError\n'), ((10086, 10158), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.Path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.package_utils.Path.exists', return_value=True)\n", (10096, 10158), False, 'from unittest import TestCase, mock\n'), ((10164, 10271), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.ConfigLoader.from_configuration_type"""', '_raise_validation_error'], {}), "('aea.cli.utils.package_utils.ConfigLoader.from_configuration_type',\n _raise_validation_error)\n", (10174, 10271), False, 'from unittest import TestCase, mock\n'), ((10674, 10746), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.Path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.package_utils.Path.exists', return_value=True)\n", (10684, 10746), False, 'from unittest import TestCase, mock\n'), ((11521, 11593), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.Path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.package_utils.Path.exists', return_value=True)\n", (11531, 11593), False, 'from unittest import TestCase, mock\n'), ((11599, 11706), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.ConfigLoader.from_configuration_type"""', '_raise_validation_error'], {}), "('aea.cli.utils.package_utils.ConfigLoader.from_configuration_type',\n _raise_validation_error)\n", (11609, 11706), False, 'from unittest import TestCase, mock\n'), ((12132, 12205), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.Path.exists"""'], {'return_value': '(False)'}), "('aea.cli.utils.package_utils.Path.exists', return_value=False)\n", (12142, 12205), False, 'from unittest import TestCase, mock\n'), ((12599, 12671), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.package_utils.Path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.package_utils.Path.exists', return_value=True)\n", (12609, 12671), False, 'from unittest import TestCase, mock\n'), ((13467, 13538), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.config.Path.exists"""', '_raise_validation_error'], {}), "('aea.cli.utils.config.Path.exists', _raise_validation_error)\n", (13477, 13538), False, 'from unittest import TestCase, mock\n'), ((15020, 15090), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.click_utils.Path.exists"""'], {'return_value': '(True)'}), "('aea.cli.utils.click_utils.Path.exists', return_value=True)\n", (15030, 15090), False, 'from unittest import TestCase, mock\n'), ((15490, 15561), 'unittest.mock.patch', 'mock.patch', (['"""aea.cli.utils.click_utils.Path.exists"""'], {'return_value': '(False)'}), "('aea.cli.utils.click_utils.Path.exists', return_value=False)\n", (15500, 15561), False, 'from unittest import TestCase, mock\n'), ((15951, 15967), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (15965, 15967), False, 'from unittest import TestCase, mock\n'), ((2401, 2420), 'aea.cli.utils.formatting.format_items', 'format_items', (['items'], {}), '(items)\n', (2413, 2420), False, 'from aea.cli.utils.formatting import format_items\n'), ((3208, 3271), 'aea.cli.utils.package_utils.try_get_item_source_path', 'try_get_item_source_path', (['"""cwd"""', 'AUTHOR', '"""skills"""', '"""skill-name"""'], {}), "('cwd', AUTHOR, 'skills', 'skill-name')\n", (3232, 3271), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((3516, 3577), 'aea.cli.utils.package_utils.try_get_item_source_path', 'try_get_item_source_path', (['"""cwd"""', 'None', '"""skills"""', '"""skill-name"""'], {}), "('cwd', None, 'skills', 'skill-name')\n", (3540, 3577), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((4398, 4466), 'aea.cli.utils.package_utils.try_get_item_target_path', 'try_get_item_target_path', (['"""packages"""', 'AUTHOR', '"""skills"""', '"""skill-name"""'], {}), "('packages', AUTHOR, 'skills', 'skill-name')\n", (4422, 4466), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((5264, 5309), 'aea.cli.utils.click_utils.PublicIdParameter.get_metavar', 'PublicIdParameter.get_metavar', (['"""obj"""', '"""param"""'], {}), "('obj', 'param')\n", (5293, 5309), False, 'from aea.cli.utils.click_utils import AEAJsonPathType, PublicIdParameter\n'), ((5901, 5919), 'aea.cli.utils.config._init_cli_config', '_init_cli_config', ([], {}), '()\n', (5917, 5919), False, 'from aea.cli.utils.config import _init_cli_config, get_or_create_cli_config, update_cli_config\n'), ((6465, 6502), 'aea.cli.utils.config.update_cli_config', 'update_cli_config', (["{'some': 'config'}"], {}), "({'some': 'config'})\n", (6482, 6502), False, 'from aea.cli.utils.config import _init_cli_config, get_or_create_cli_config, update_cli_config\n'), ((7113, 7139), 'aea.cli.utils.config.get_or_create_cli_config', 'get_or_create_cli_config', ([], {}), '()\n', (7137, 7139), False, 'from aea.cli.utils.config import _init_cli_config, get_or_create_cli_config, update_cli_config\n'), ((8789, 8824), 'aea.cli.utils.package_utils.validate_author_name', 'validate_author_name', ([], {'author': 'author'}), '(author=author)\n', (8809, 8824), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((8884, 8906), 'aea.cli.utils.package_utils.validate_author_name', 'validate_author_name', ([], {}), '()\n', (8904, 8906), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((9651, 9688), 'aea.cli.utils.package_utils.validate_package_name', 'validate_package_name', (['"""correct_name"""'], {}), "('correct_name')\n", (9672, 9688), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((10428, 10471), 'tests.test_cli.tools_for_testing.PublicIdMock.from_str', 'PublicIdMock.from_str', (['"""fetchai/echo:0.5.0"""'], {}), "('fetchai/echo:0.5.0')\n", (10449, 10471), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((11118, 11161), 'tests.test_cli.tools_for_testing.PublicIdMock.from_str', 'PublicIdMock.from_str', (['"""fetchai/echo:0.5.0"""'], {}), "('fetchai/echo:0.5.0')\n", (11139, 11161), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((10804, 10820), 'unittest.mock.mock_open', 'mock.mock_open', ([], {}), '()\n', (10818, 10820), False, 'from unittest import TestCase, mock\n'), ((11878, 11921), 'tests.test_cli.tools_for_testing.PublicIdMock.from_str', 'PublicIdMock.from_str', (['"""fetchai/echo:0.5.0"""'], {}), "('fetchai/echo:0.5.0')\n", (11899, 11921), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((12356, 12399), 'tests.test_cli.tools_for_testing.PublicIdMock.from_str', 'PublicIdMock.from_str', (['"""fetchai/echo:0.5.0"""'], {}), "('fetchai/echo:0.5.0')\n", (12377, 12399), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((13050, 13093), 'tests.test_cli.tools_for_testing.PublicIdMock.from_str', 'PublicIdMock.from_str', (['"""fetchai/echo:0.5.0"""'], {}), "('fetchai/echo:0.5.0')\n", (13071, 13093), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((12729, 12745), 'unittest.mock.mock_open', 'mock.mock_open', ([], {}), '()\n', (12743, 12745), False, 'from unittest import TestCase, mock\n'), ((14233, 14244), 'unittest.mock.Mock', 'mock.Mock', ([], {}), '()\n', (14242, 14244), False, 'from unittest import TestCase, mock\n'), ((14376, 14427), 'aea.cli.utils.package_utils.is_fingerprint_correct', 'is_fingerprint_correct', (['"""package_path"""', 'item_config'], {}), "('package_path', item_config)\n", (14398, 14427), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((14613, 14624), 'unittest.mock.Mock', 'mock.Mock', ([], {}), '()\n', (14622, 14624), False, 'from unittest import TestCase, mock\n'), ((14795, 14844), 'aea.cli.utils.package_utils.is_fingerprint_correct', 'is_fingerprint_correct', (['package_path', 'item_config'], {}), '(package_path, item_config)\n', (14817, 14844), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((15311, 15324), 'tests.test_cli.tools_for_testing.ContextMock', 'ContextMock', ([], {}), '()\n', (15322, 15324), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((15348, 15359), 'unittest.mock.Mock', 'mock.Mock', ([], {}), '()\n', (15357, 15359), False, 'from unittest import TestCase, mock\n'), ((15394, 15405), 'unittest.mock.Mock', 'mock.Mock', ([], {}), '()\n', (15403, 15405), False, 'from unittest import TestCase, mock\n'), ((15420, 15437), 'aea.cli.utils.click_utils.AEAJsonPathType', 'AEAJsonPathType', ([], {}), '()\n', (15435, 15437), False, 'from aea.cli.utils.click_utils import AEAJsonPathType, PublicIdParameter\n'), ((15784, 15801), 'aea.cli.utils.click_utils.AEAJsonPathType', 'AEAJsonPathType', ([], {}), '()\n', (15799, 15801), False, 'from aea.cli.utils.click_utils import AEAJsonPathType, PublicIdParameter\n'), ((16188, 16199), 'unittest.mock.Mock', 'mock.Mock', ([], {}), '()\n', (16197, 16199), False, 'from unittest import TestCase, mock\n'), ((16276, 16287), 'unittest.mock.Mock', 'mock.Mock', ([], {}), '()\n', (16285, 16287), False, 'from unittest import TestCase, mock\n'), ((16353, 16404), 'aea.cli.utils.package_utils.try_get_balance', 'try_get_balance', (['agent_config', 'wallet_mock', 'FETCHAI'], {}), '(agent_config, wallet_mock, FETCHAI)\n', (16368, 16404), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((3912, 3975), 'aea.cli.utils.package_utils.try_get_item_source_path', 'try_get_item_source_path', (['"""cwd"""', 'AUTHOR', '"""skills"""', '"""skill-name"""'], {}), "('cwd', AUTHOR, 'skills', 'skill-name')\n", (3936, 3975), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((4985, 5058), 'aea.cli.utils.package_utils.try_get_item_target_path', 'try_get_item_target_path', (['"""skills"""', 'AUTHOR', '"""skill-name"""', '"""packages_path"""'], {}), "('skills', AUTHOR, 'skill-name', 'packages_path')\n", (5009, 5058), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((7545, 7571), 'aea.cli.utils.config.get_or_create_cli_config', 'get_or_create_cli_config', ([], {}), '()\n', (7569, 7571), False, 'from aea.cli.utils.config import _init_cli_config, get_or_create_cli_config, update_cli_config\n'), ((8072, 8104), 'typing.cast', 'cast', (['Context', 'click_context.obj'], {}), '(Context, click_context.obj)\n', (8076, 8104), False, 'from typing import cast\n'), ((8172, 8197), 'click.ClickException', 'ClickException', (['"""Message"""'], {}), "('Message')\n", (8186, 8197), False, 'from click import BadParameter, ClickException\n'), ((9283, 9305), 'aea.cli.utils.package_utils.validate_author_name', 'validate_author_name', ([], {}), '()\n', (9303, 9305), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((9405, 9427), 'aea.cli.utils.package_utils.validate_author_name', 'validate_author_name', ([], {}), '()\n', (9425, 9427), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((9861, 9900), 'aea.cli.utils.package_utils.validate_package_name', 'validate_package_name', (['"""incorrect-name"""'], {}), "('incorrect-name')\n", (9882, 9900), False, 'from aea.cli.utils.package_utils import find_item_in_distribution, find_item_locally, is_fingerprint_correct, try_get_balance, try_get_item_source_path, try_get_item_target_path, validate_author_name, validate_package_name\n'), ((10936, 10954), 'tests.test_cli.tools_for_testing.ConfigLoaderMock', 'ConfigLoaderMock', ([], {}), '()\n', (10952, 10954), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((12861, 12879), 'tests.test_cli.tools_for_testing.ConfigLoaderMock', 'ConfigLoaderMock', ([], {}), '()\n', (12877, 12879), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((16707, 16739), 'aea.cli.utils.generic.is_readme_present', 'is_readme_present', (['"""readme/path"""'], {}), "('readme/path')\n", (16724, 16739), False, 'from aea.cli.utils.generic import is_readme_present\n'), ((8264, 8277), 'tests.test_cli.tools_for_testing.ContextMock', 'ContextMock', ([], {}), '()\n', (8275, 8277), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((10556, 10569), 'tests.test_cli.tools_for_testing.ContextMock', 'ContextMock', ([], {}), '()\n', (10567, 10569), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((11246, 11259), 'tests.test_cli.tools_for_testing.ContextMock', 'ContextMock', ([], {}), '()\n', (11257, 11259), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((12014, 12027), 'tests.test_cli.tools_for_testing.ContextMock', 'ContextMock', ([], {}), '()\n', (12025, 12027), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((12492, 12505), 'tests.test_cli.tools_for_testing.ContextMock', 'ContextMock', ([], {}), '()\n', (12503, 12505), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((13186, 13199), 'tests.test_cli.tools_for_testing.ContextMock', 'ContextMock', ([], {}), '()\n', (13197, 13199), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n'), ((13763, 13794), 'tests.test_cli.tools_for_testing.ContextMock', 'ContextMock', ([], {'protocols': "['some']"}), "(protocols=['some'])\n", (13774, 13794), False, 'from tests.test_cli.tools_for_testing import ConfigLoaderMock, ContextMock, PublicIdMock, StopTest, raise_stoptest\n')]
SanjarbekSaminjonov/musofirlar.backend
api/flat/urls.py
23b09e90cc4e3d153063ad1768b5ae1c18ff866d
from django.urls import path from . import views urlpatterns = [ path('', views.FlatListAPIView.as_view()), path('create/', views.FlatCreateAPIView.as_view()), path('<int:pk>/', views.FlatDetailAPIView.as_view()), path('<int:pk>/update/', views.FlatUpdateAPIView.as_view()), path('<int:pk>/delete/', views.FlatDeleteAPIView.as_view()), ]
[]
hsky77/hyssop
hyssop_aiohttp/component/__init__.py
4ab1e82f9e2592de56589c7426a037564bef49a6
# Copyright (C) 2020-Present the hyssop authors and contributors. # # This module is part of hyssop and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php ''' File created: January 1st 2021 Modified By: hsky77 Last Updated: January 7th 2021 15:30:08 pm ''' from hyssop.project.component import ComponentTypes from .aio_client import AioClientComponent class AioHttpComponentTypes(ComponentTypes): AioClient = ('aioclient', 'aio_client', 'AioClientComponent')
[]
tGhattas/IMP-seamless-cloning
run_clone.py
2c81e0bd9bc99955afe06ec4eea187a5a42761e3
import cv2 import getopt import sys from gui import MaskPainter, MaskMover from clone import seamless_cloning, shepards_seamless_cloning from utils import read_image, plt from os import path def usage(): print( "Usage: python run_clone.py [options] \n\n\ Options: \n\ \t-h\t Flag to specify a brief help message and exits..\n\ \t-s\t(Required) Specify a source image.\n\ \t-t\t(Required) Specify a target image.\n\ \t-m\t(Optional) Specify a mask image with the object in white and other part in black, ignore this option if you plan to draw it later.\n\ \t-x\t(Optional) Flag to specify a mode, either 'possion' or 'shepard'. default is possion.\n\ \t-v\t(Optional) Flag to specify grad field of source only or both in case of Possion solver is used. default is source only.") if __name__ == '__main__': # parse command line arguments args = {} try: opts, _ = getopt.getopt(sys.argv[1:], "vxhs:t:m:p:") except getopt.GetoptError as err: # print help information and exit: print(err) # will print something like "option -a not recognized" print("See help: run_clone.py -h") exit(2) for o, a in opts: if o in ("-h"): usage() exit() elif o in ("-s"): args["source"] = a elif o in ("-t"): args["target"] = a elif o in ("-m"): args["mask"] = a elif o in ("-x"): args["mode"] = a.lower() elif o in ("-v"): args["gradient_field_source_only"] = a else: continue # if ("source" not in args) or ("target" not in args): usage() exit() # # set default mode to Possion solver mode = "poisson" if ("mode" not in args) else args["mode"] gradient_field_source_only = ("gradient_field_source_only" not in args) source = read_image(args["source"], 2) target = read_image(args["target"], 2) if source is None or target is None: print('Source or target image not exist.') exit() if source.shape[0] > target.shape[0] or source.shape[1] > target.shape[1]: print('Source image cannot be larger than target image.') exit() # draw the mask mask_path = "" if "mask" not in args: print('Please highlight the object to disapparate.\n') mp = MaskPainter(args["source"]) mask_path = mp.paint_mask() else: mask_path = args["mask"] # adjust mask position for target image print('Please move the object to desired location to apparate.\n') mm = MaskMover(args["target"], mask_path) offset_x, offset_y, target_mask_path = mm.move_mask() # blend print('Blending ...') target_mask = read_image(target_mask_path, 1) offset = offset_x, offset_y cloning_tool = seamless_cloning if mode == "poisson" else shepards_seamless_cloning kwargs = {"gradient_field_source_only": gradient_field_source_only} if mode == "poisson" else {} blend_result = cloning_tool(source, target, target_mask, offset, **kwargs) cv2.imwrite(path.join(path.dirname(args["source"]), 'target_result.png'), blend_result) plt.figure("Result"), plt.imshow(blend_result), plt.show() print('Done.\n') ''' running example: - Possion based solver: python run_clone.py -s external/blend-1.jpg -t external/main-1.jpg python run_clone.py -s external/source3.jpg -t external/target3.jpg -v - Shepard's interpolation: python run_clone.py -s external/blend-1.jpg -t external/main-1.jpg -x python run_clone.py -s external/source3.jpg -t external/target3.jpg -x '''
[((1937, 1966), 'utils.read_image', 'read_image', (["args['source']", '(2)'], {}), "(args['source'], 2)\n", (1947, 1966), False, 'from utils import read_image, plt\n'), ((1980, 2009), 'utils.read_image', 'read_image', (["args['target']", '(2)'], {}), "(args['target'], 2)\n", (1990, 2009), False, 'from utils import read_image, plt\n'), ((2654, 2690), 'gui.MaskMover', 'MaskMover', (["args['target']", 'mask_path'], {}), "(args['target'], mask_path)\n", (2663, 2690), False, 'from gui import MaskPainter, MaskMover\n'), ((2806, 2837), 'utils.read_image', 'read_image', (['target_mask_path', '(1)'], {}), '(target_mask_path, 1)\n', (2816, 2837), False, 'from utils import read_image, plt\n'), ((954, 996), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:]', '"""vxhs:t:m:p:"""'], {}), "(sys.argv[1:], 'vxhs:t:m:p:')\n", (967, 996), False, 'import getopt\n'), ((2422, 2449), 'gui.MaskPainter', 'MaskPainter', (["args['source']"], {}), "(args['source'])\n", (2433, 2449), False, 'from gui import MaskPainter, MaskMover\n'), ((3252, 3272), 'utils.plt.figure', 'plt.figure', (['"""Result"""'], {}), "('Result')\n", (3262, 3272), False, 'from utils import read_image, plt\n'), ((3274, 3298), 'utils.plt.imshow', 'plt.imshow', (['blend_result'], {}), '(blend_result)\n', (3284, 3298), False, 'from utils import read_image, plt\n'), ((3300, 3310), 'utils.plt.show', 'plt.show', ([], {}), '()\n', (3308, 3310), False, 'from utils import read_image, plt\n'), ((3166, 3194), 'os.path.dirname', 'path.dirname', (["args['source']"], {}), "(args['source'])\n", (3178, 3194), False, 'from os import path\n')]
Punkweb/punkweb-boards
punkweb_boards/rest/serializers.py
8934d15fbff2a3ce9191fdb19d58d029eb55ef16
from rest_framework import serializers from punkweb_boards.conf.settings import SHOUTBOX_DISABLED_TAGS from punkweb_boards.models import ( BoardProfile, Category, Subcategory, Thread, Post, Conversation, Message, Report, Shout, ) class BoardProfileSerializer(serializers.ModelSerializer): post_count = serializers.ReadOnlyField() can_shout = serializers.ReadOnlyField() rendered_username = serializers.ReadOnlyField() rendered_rank = serializers.ReadOnlyField() class Meta: model = BoardProfile fields = "__all__" class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category exclude = ("auth_req",) class SubcategorySerializer(serializers.ModelSerializer): last_thread = serializers.ReadOnlyField(source="last_thread.id") last_thread_title = serializers.ReadOnlyField(source="last_thread.title") last_thread_created = serializers.ReadOnlyField( source="last_thread.created" ) last_thread_user = serializers.ReadOnlyField( source="last_thread.user.profile.rendered_username" ) parent_name = serializers.ReadOnlyField(source="parent.name") thread_count = serializers.ReadOnlyField() post_count = serializers.ReadOnlyField() can_post = serializers.SerializerMethodField() def get_can_post(self, obj): return obj.can_post(self.context.get("request").user) class Meta: model = Subcategory exclude = ("auth_req",) class ThreadSerializer(serializers.ModelSerializer): last_post = serializers.ReadOnlyField(source="last_post.id") last_post_created = serializers.ReadOnlyField(source="last_post.created") last_post_username = serializers.ReadOnlyField( source="last_post.user.username" ) last_post_rendered_username = serializers.ReadOnlyField( source="last_post.user.profile.rendered_username" ) user_username = serializers.ReadOnlyField(source="user.username") user_rendered_username = serializers.ReadOnlyField( source="user.profile.rendered_username" ) user_image = serializers.ReadOnlyField(source="user.profile.avatar") user_post_count = serializers.ReadOnlyField( source="user.profile.post_count" ) user_join_date = serializers.ReadOnlyField(source="user.created") flagged = serializers.ReadOnlyField(source="reported") posts_count = serializers.ReadOnlyField() can_edit = serializers.SerializerMethodField() def get_can_edit(self, obj): return obj.can_edit(self.context.get("request").user) class Meta: model = Thread fields = "__all__" read_only_fields = ( "pinned", "closed", "user", "upvoted_by", "downvoted_by", ) class PostSerializer(serializers.ModelSerializer): flagged = serializers.ReadOnlyField(source="reported") can_edit = serializers.SerializerMethodField() def get_can_edit(self, obj): return obj.can_edit(self.context.get("request").user) class Meta: model = Post fields = "__all__" read_only_fields = ("user", "upvoted_by", "downvoted_by") class ConversationSerializer(serializers.ModelSerializer): last_message = serializers.ReadOnlyField(source="last_message.id") last_message_title = serializers.ReadOnlyField(source="last_message.title") last_message_created = serializers.ReadOnlyField( source="last_message.created" ) last_message_user = serializers.ReadOnlyField( source="last_message.user.profile.rendered_username" ) message_count = serializers.ReadOnlyField() class Meta: model = Conversation fields = "__all__" read_only_fields = ("unread_by",) class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = "__all__" read_only_fields = ("user",) class ShoutSerializer(serializers.ModelSerializer): username = serializers.ReadOnlyField(source="user.username") rendered_username = serializers.ReadOnlyField( source="user.profile.rendered_username" ) class Meta: model = Shout fields = ( "id", "user", "username", "rendered_username", "content", "_content_rendered", "created", "modified", ) read_only_fields = ("user",) def create(self, validated_data): for key in SHOUTBOX_DISABLED_TAGS: key_tag = "[{}]".format(key).lower() if ( key_tag[: len(key_tag) - 1] in validated_data.get("content").lower() ): raise serializers.ValidationError( { "notAllowed": "{} is not allowed in the shoutbox".format( key_tag ) } ) return Shout.objects.create(**validated_data)
[((344, 371), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (369, 371), False, 'from rest_framework import serializers\n'), ((388, 415), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (413, 415), False, 'from rest_framework import serializers\n'), ((440, 467), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (465, 467), False, 'from rest_framework import serializers\n'), ((488, 515), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (513, 515), False, 'from rest_framework import serializers\n'), ((797, 847), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_thread.id"""'}), "(source='last_thread.id')\n", (822, 847), False, 'from rest_framework import serializers\n'), ((872, 925), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_thread.title"""'}), "(source='last_thread.title')\n", (897, 925), False, 'from rest_framework import serializers\n'), ((952, 1007), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_thread.created"""'}), "(source='last_thread.created')\n", (977, 1007), False, 'from rest_framework import serializers\n'), ((1045, 1123), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_thread.user.profile.rendered_username"""'}), "(source='last_thread.user.profile.rendered_username')\n", (1070, 1123), False, 'from rest_framework import serializers\n'), ((1156, 1203), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""parent.name"""'}), "(source='parent.name')\n", (1181, 1203), False, 'from rest_framework import serializers\n'), ((1223, 1250), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (1248, 1250), False, 'from rest_framework import serializers\n'), ((1268, 1295), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (1293, 1295), False, 'from rest_framework import serializers\n'), ((1311, 1346), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (1344, 1346), False, 'from rest_framework import serializers\n'), ((1591, 1639), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_post.id"""'}), "(source='last_post.id')\n", (1616, 1639), False, 'from rest_framework import serializers\n'), ((1664, 1717), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_post.created"""'}), "(source='last_post.created')\n", (1689, 1717), False, 'from rest_framework import serializers\n'), ((1743, 1802), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_post.user.username"""'}), "(source='last_post.user.username')\n", (1768, 1802), False, 'from rest_framework import serializers\n'), ((1851, 1927), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_post.user.profile.rendered_username"""'}), "(source='last_post.user.profile.rendered_username')\n", (1876, 1927), False, 'from rest_framework import serializers\n'), ((1962, 2011), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""user.username"""'}), "(source='user.username')\n", (1987, 2011), False, 'from rest_framework import serializers\n'), ((2041, 2107), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""user.profile.rendered_username"""'}), "(source='user.profile.rendered_username')\n", (2066, 2107), False, 'from rest_framework import serializers\n'), ((2139, 2194), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""user.profile.avatar"""'}), "(source='user.profile.avatar')\n", (2164, 2194), False, 'from rest_framework import serializers\n'), ((2217, 2276), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""user.profile.post_count"""'}), "(source='user.profile.post_count')\n", (2242, 2276), False, 'from rest_framework import serializers\n'), ((2312, 2360), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""user.created"""'}), "(source='user.created')\n", (2337, 2360), False, 'from rest_framework import serializers\n'), ((2375, 2419), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""reported"""'}), "(source='reported')\n", (2400, 2419), False, 'from rest_framework import serializers\n'), ((2438, 2465), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (2463, 2465), False, 'from rest_framework import serializers\n'), ((2481, 2516), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (2514, 2516), False, 'from rest_framework import serializers\n'), ((2904, 2948), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""reported"""'}), "(source='reported')\n", (2929, 2948), False, 'from rest_framework import serializers\n'), ((2964, 2999), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (2997, 2999), False, 'from rest_framework import serializers\n'), ((3307, 3358), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_message.id"""'}), "(source='last_message.id')\n", (3332, 3358), False, 'from rest_framework import serializers\n'), ((3384, 3438), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_message.title"""'}), "(source='last_message.title')\n", (3409, 3438), False, 'from rest_framework import serializers\n'), ((3466, 3522), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_message.created"""'}), "(source='last_message.created')\n", (3491, 3522), False, 'from rest_framework import serializers\n'), ((3561, 3640), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""last_message.user.profile.rendered_username"""'}), "(source='last_message.user.profile.rendered_username')\n", (3586, 3640), False, 'from rest_framework import serializers\n'), ((3675, 3702), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (3700, 3702), False, 'from rest_framework import serializers\n'), ((4047, 4096), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""user.username"""'}), "(source='user.username')\n", (4072, 4096), False, 'from rest_framework import serializers\n'), ((4121, 4187), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {'source': '"""user.profile.rendered_username"""'}), "(source='user.profile.rendered_username')\n", (4146, 4187), False, 'from rest_framework import serializers\n'), ((5042, 5080), 'punkweb_boards.models.Shout.objects.create', 'Shout.objects.create', ([], {}), '(**validated_data)\n', (5062, 5080), False, 'from punkweb_boards.models import BoardProfile, Category, Subcategory, Thread, Post, Conversation, Message, Report, Shout\n')]
ulise/hetida-designer
runtime/components/Statistic/moving_minimum_time.py
a6be8eb45abf950d5498e3ca756ea1d2e46b5c00
from hetdesrun.component.registration import register from hetdesrun.datatypes import DataType import pandas as pd import numpy as np # ***** DO NOT EDIT LINES BELOW ***** # These lines may be overwritten if input/output changes. @register( inputs={"data": DataType.Any, "t": DataType.String}, outputs={"movmin": DataType.Any}, ) def main(*, data, t): """entrypoint function for this component Usage example: >>> main( ... data = pd.Series( ... { ... "2019-08-01T15:20:00": 4.0, ... "2019-08-01T15:20:01": 5.0, ... "2019-08-01T15:20:05": 1.0, ... "2019-08-01T15:20:09": 9.0, ... } ... ), ... t = "4s" ... )["movmin"] 2019-08-01 15:20:00 4.0 2019-08-01 15:20:01 4.0 2019-08-01 15:20:05 1.0 2019-08-01 15:20:09 9.0 dtype: float64 """ # ***** DO NOT EDIT LINES ABOVE ***** # write your code here. try: data.index = pd.to_datetime(data.index) except (ValueError, TypeError): raise TypeError("indices of data must be datetime") data_sort = data.sort_index().dropna() try: return {"movmin": data_sort.rolling(t).min()} except (ValueError): raise ValueError(f"t could not be parsed as frequency: {t}")
[((233, 333), 'hetdesrun.component.registration.register', 'register', ([], {'inputs': "{'data': DataType.Any, 't': DataType.String}", 'outputs': "{'movmin': DataType.Any}"}), "(inputs={'data': DataType.Any, 't': DataType.String}, outputs={\n 'movmin': DataType.Any})\n", (241, 333), False, 'from hetdesrun.component.registration import register\n'), ((1002, 1028), 'pandas.to_datetime', 'pd.to_datetime', (['data.index'], {}), '(data.index)\n', (1016, 1028), True, 'import pandas as pd\n')]
MikhailNakhatovich/rooms_painting
painter.py
51b92797c867d4bb1c8d42a58785c0f4dacd4075
import cv2 import ezdxf import numpy as np def draw_hatch(img, entity, color, mask): for poly_path in entity.paths.paths: # print(poly_path.path_type_flags) polygon = np.array([vertex[:-1] for vertex in poly_path.vertices]).astype(int) if poly_path.path_type_flags & 1 == 1: cv2.fillPoly(img, [polygon], color) cv2.fillPoly(mask, [polygon], (255, 255, 255)) else: cv2.fillPoly(img, [polygon], (255, 255, 255)) return color def draw_line(img, entity, color, mask): p1 = entity.dxf.start[:-1] p2 = entity.dxf.end[:-1] cv2.line(img, (int(p1[0]), int(p1[1])), (int(p2[0]), int(p2[1])), color, 1) cv2.line(mask, (int(p1[0]), int(p1[1])), (int(p2[0]), int(p2[1])), (255, 255, 255), 2) return color def draw_lwpolyline(img, entity, color, mask): polyline = [] a = np.array(entity.lwpoints.values).astype(int) while len(a) > 0: polyline.append((a[0], a[1])) a = a[5:] cv2.polylines(img, [np.array(polyline)], entity.closed, color, 1) cv2.polylines(mask, [np.array(polyline)], entity.closed, (255, 255, 255), 2) return color def draw_arc(img, entity, color, mask): s = entity.dxf.start_angle * np.pi / 180 e = entity.dxf.end_angle * np.pi / 180 if s > e: s -= 2 * np.pi d = (e - s) / (int((e - s) * 180 / np.pi) + 1) r = entity.dxf.radius cx, cy = entity.dxf.center.xyz[:-1] angles = np.arange(s, e + d / 2, d) x = cx + r * np.cos(angles) y = cy + r * np.sin(angles) points = np.column_stack((x, y)).astype(int) cv2.polylines(img, [points], abs(s - e) < 1e-9, color, 1) cv2.polylines(mask, [points], abs(s - e) < 1e-9, (255, 255, 255), 2) return color def draw_circle(img, entity, color, mask): r = entity.dxf.radius cx, cy = entity.dxf.center.xyz[:-1] cv2.circle(img, (int(cx), int(cy)), int(r), color, 1) cv2.circle(mask, (int(cx), int(cy)), int(r), (255, 255, 255), -1) return color def draw_ellipse(img, entity, color, mask): cx, cy = entity.dxf.center.xyz[:-1] ma = entity.dxf.major_axis.magnitude angle = entity.dxf.major_axis.angle_deg mi = ma * entity.dxf.ratio s = entity.dxf.start_param * 180 / np.pi e = entity.dxf.end_param * 180 / np.pi if entity.dxf.extrusion.z == -1: s = 360 - s e = 360 - e cv2.ellipse(img, (int(cx), int(cy)), (int(ma), int(mi)), angle, s, e, color, 1) cv2.ellipse(mask, (int(cx), int(cy)), (int(ma), int(mi)), angle, s, e, (255, 255, 255), 1) return color def draw_point(img, entity, color, mask): cx, cy = entity.dxf.location.xyz[:-1] cv2.circle(img, (int(cx), int(cy)), 0, color, 1) cv2.circle(mask, (int(cx), int(cy)), 0, (255, 255, 255), -1) return color draw_map = { 'HATCH': draw_hatch, 'LINE': draw_line, 'LWPOLYLINE': draw_lwpolyline, 'ARC': draw_arc, 'CIRCLE': draw_circle, 'ELLIPSE': draw_ellipse, 'POINT': draw_point, } def paint(in_path, out_path, config): doc = ezdxf.readfile(in_path) extmax, extmin = doc.header['$EXTMAX'], doc.header['$EXTMIN'] xmin, ymin = np.floor(extmin[:-1]).astype(int) xmax, ymax = np.ceil(extmax[:-1]).astype(int) img = np.ones((ymax + ymin, xmax + xmin, 3), np.uint8) * 255 mask = np.zeros_like(img) msp = doc.modelspace() layers = config.get('layers', {}) colors = config.get('colors', {}) # print(doc.layers.entries.keys()) for layer_name, names in layers.items(): color = tuple(colors.get(layer_name, [0, 0, 0])) for name in names: if name not in doc.layers: continue entities = msp.query('*[layer=="%s"]' % name) tmp = np.zeros((ymax + ymin, xmax + xmin), np.uint8) for entity in entities: if entity.DXFTYPE in draw_map: draw_map[entity.DXFTYPE](img, entity, color, tmp) else: print("%s: %s" % (name, entity.DXFTYPE)) contours, hierarchy = cv2.findContours(tmp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(mask, contours, -1, color, -1) res, img_png = cv2.imencode('.png', cv2.flip(img, 0)) res, mask_png = cv2.imencode('.png', cv2.flip(mask, 0)) with open(out_path, 'wb') as f: f.write(img_png.tobytes()) with open(out_path[:-4] + "_mask.png", 'wb') as f: f.write(mask_png.tobytes())
[((1455, 1481), 'numpy.arange', 'np.arange', (['s', '(e + d / 2)', 'd'], {}), '(s, e + d / 2, d)\n', (1464, 1481), True, 'import numpy as np\n'), ((3039, 3062), 'ezdxf.readfile', 'ezdxf.readfile', (['in_path'], {}), '(in_path)\n', (3053, 3062), False, 'import ezdxf\n'), ((3306, 3324), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (3319, 3324), True, 'import numpy as np\n'), ((3240, 3288), 'numpy.ones', 'np.ones', (['(ymax + ymin, xmax + xmin, 3)', 'np.uint8'], {}), '((ymax + ymin, xmax + xmin, 3), np.uint8)\n', (3247, 3288), True, 'import numpy as np\n'), ((4220, 4236), 'cv2.flip', 'cv2.flip', (['img', '(0)'], {}), '(img, 0)\n', (4228, 4236), False, 'import cv2\n'), ((4279, 4296), 'cv2.flip', 'cv2.flip', (['mask', '(0)'], {}), '(mask, 0)\n', (4287, 4296), False, 'import cv2\n'), ((317, 352), 'cv2.fillPoly', 'cv2.fillPoly', (['img', '[polygon]', 'color'], {}), '(img, [polygon], color)\n', (329, 352), False, 'import cv2\n'), ((365, 411), 'cv2.fillPoly', 'cv2.fillPoly', (['mask', '[polygon]', '(255, 255, 255)'], {}), '(mask, [polygon], (255, 255, 255))\n', (377, 411), False, 'import cv2\n'), ((438, 483), 'cv2.fillPoly', 'cv2.fillPoly', (['img', '[polygon]', '(255, 255, 255)'], {}), '(img, [polygon], (255, 255, 255))\n', (450, 483), False, 'import cv2\n'), ((867, 899), 'numpy.array', 'np.array', (['entity.lwpoints.values'], {}), '(entity.lwpoints.values)\n', (875, 899), True, 'import numpy as np\n'), ((1014, 1032), 'numpy.array', 'np.array', (['polyline'], {}), '(polyline)\n', (1022, 1032), True, 'import numpy as np\n'), ((1085, 1103), 'numpy.array', 'np.array', (['polyline'], {}), '(polyline)\n', (1093, 1103), True, 'import numpy as np\n'), ((1499, 1513), 'numpy.cos', 'np.cos', (['angles'], {}), '(angles)\n', (1505, 1513), True, 'import numpy as np\n'), ((1531, 1545), 'numpy.sin', 'np.sin', (['angles'], {}), '(angles)\n', (1537, 1545), True, 'import numpy as np\n'), ((1559, 1582), 'numpy.column_stack', 'np.column_stack', (['(x, y)'], {}), '((x, y))\n', (1574, 1582), True, 'import numpy as np\n'), ((3146, 3167), 'numpy.floor', 'np.floor', (['extmin[:-1]'], {}), '(extmin[:-1])\n', (3154, 3167), True, 'import numpy as np\n'), ((3197, 3217), 'numpy.ceil', 'np.ceil', (['extmax[:-1]'], {}), '(extmax[:-1])\n', (3204, 3217), True, 'import numpy as np\n'), ((3736, 3782), 'numpy.zeros', 'np.zeros', (['(ymax + ymin, xmax + xmin)', 'np.uint8'], {}), '((ymax + ymin, xmax + xmin), np.uint8)\n', (3744, 3782), True, 'import numpy as np\n'), ((4053, 4118), 'cv2.findContours', 'cv2.findContours', (['tmp', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(tmp, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (4069, 4118), False, 'import cv2\n'), ((4131, 4178), 'cv2.drawContours', 'cv2.drawContours', (['mask', 'contours', '(-1)', 'color', '(-1)'], {}), '(mask, contours, -1, color, -1)\n', (4147, 4178), False, 'import cv2\n'), ((189, 245), 'numpy.array', 'np.array', (['[vertex[:-1] for vertex in poly_path.vertices]'], {}), '([vertex[:-1] for vertex in poly_path.vertices])\n', (197, 245), True, 'import numpy as np\n')]
vascoalramos/misago-deployment
misago/misago/users/serializers/auth.py
20226072138403108046c0afad9d99eb4163cedc
from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework import serializers from ...acl.useracl import serialize_user_acl from .user import UserSerializer User = get_user_model() __all__ = ["AuthenticatedUserSerializer", "AnonymousUserSerializer"] class AuthFlags: def get_is_authenticated(self, obj): return bool(obj.is_authenticated) def get_is_anonymous(self, obj): return bool(obj.is_anonymous) class AuthenticatedUserSerializer(UserSerializer, AuthFlags): email = serializers.SerializerMethodField() is_authenticated = serializers.SerializerMethodField() is_anonymous = serializers.SerializerMethodField() class Meta: model = User fields = UserSerializer.Meta.fields + [ "has_usable_password", "is_hiding_presence", "limits_private_thread_invites_to", "unread_private_threads", "subscribe_to_started_threads", "subscribe_to_replied_threads", "is_authenticated", "is_anonymous", ] def get_acl(self, obj): acl = self.context.get("acl") if acl: return serialize_user_acl(acl) return {} def get_email(self, obj): return obj.email def get_api(self, obj): return { "avatar": reverse("misago:api:user-avatar", kwargs={"pk": obj.pk}), "data_downloads": reverse( "misago:api:user-data-downloads", kwargs={"pk": obj.pk} ), "details": reverse("misago:api:user-details", kwargs={"pk": obj.pk}), "change_email": reverse( "misago:api:user-change-email", kwargs={"pk": obj.pk} ), "change_password": reverse( "misago:api:user-change-password", kwargs={"pk": obj.pk} ), "edit_details": reverse( "misago:api:user-edit-details", kwargs={"pk": obj.pk} ), "options": reverse("misago:api:user-forum-options", kwargs={"pk": obj.pk}), "request_data_download": reverse( "misago:api:user-request-data-download", kwargs={"pk": obj.pk} ), "username": reverse("misago:api:user-username", kwargs={"pk": obj.pk}), "delete": reverse( "misago:api:user-delete-own-account", kwargs={"pk": obj.pk} ), } AuthenticatedUserSerializer = AuthenticatedUserSerializer.exclude_fields( "is_avatar_locked", "is_blocked", "is_followed", "is_signature_locked", "meta", "signature", "status", ) class AnonymousUserSerializer(serializers.Serializer, AuthFlags): id = serializers.ReadOnlyField() acl = serializers.SerializerMethodField() is_authenticated = serializers.SerializerMethodField() is_anonymous = serializers.SerializerMethodField() def get_acl(self, obj): acl = self.context.get("acl") if acl: return serialize_user_acl(acl) return {}
[((206, 222), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (220, 222), False, 'from django.contrib.auth import get_user_model\n'), ((547, 582), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (580, 582), False, 'from rest_framework import serializers\n'), ((606, 641), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (639, 641), False, 'from rest_framework import serializers\n'), ((661, 696), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (694, 696), False, 'from rest_framework import serializers\n'), ((2732, 2759), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (2757, 2759), False, 'from rest_framework import serializers\n'), ((2770, 2805), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (2803, 2805), False, 'from rest_framework import serializers\n'), ((2829, 2864), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (2862, 2864), False, 'from rest_framework import serializers\n'), ((2884, 2919), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (2917, 2919), False, 'from rest_framework import serializers\n'), ((1364, 1420), 'django.urls.reverse', 'reverse', (['"""misago:api:user-avatar"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-avatar', kwargs={'pk': obj.pk})\n", (1371, 1420), False, 'from django.urls import reverse\n'), ((1452, 1516), 'django.urls.reverse', 'reverse', (['"""misago:api:user-data-downloads"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-data-downloads', kwargs={'pk': obj.pk})\n", (1459, 1516), False, 'from django.urls import reverse\n'), ((1571, 1628), 'django.urls.reverse', 'reverse', (['"""misago:api:user-details"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-details', kwargs={'pk': obj.pk})\n", (1578, 1628), False, 'from django.urls import reverse\n'), ((1658, 1720), 'django.urls.reverse', 'reverse', (['"""misago:api:user-change-email"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-change-email', kwargs={'pk': obj.pk})\n", (1665, 1720), False, 'from django.urls import reverse\n'), ((1783, 1848), 'django.urls.reverse', 'reverse', (['"""misago:api:user-change-password"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-change-password', kwargs={'pk': obj.pk})\n", (1790, 1848), False, 'from django.urls import reverse\n'), ((1908, 1970), 'django.urls.reverse', 'reverse', (['"""misago:api:user-edit-details"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-edit-details', kwargs={'pk': obj.pk})\n", (1915, 1970), False, 'from django.urls import reverse\n'), ((2025, 2088), 'django.urls.reverse', 'reverse', (['"""misago:api:user-forum-options"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-forum-options', kwargs={'pk': obj.pk})\n", (2032, 2088), False, 'from django.urls import reverse\n'), ((2127, 2198), 'django.urls.reverse', 'reverse', (['"""misago:api:user-request-data-download"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-request-data-download', kwargs={'pk': obj.pk})\n", (2134, 2198), False, 'from django.urls import reverse\n'), ((2254, 2312), 'django.urls.reverse', 'reverse', (['"""misago:api:user-username"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-username', kwargs={'pk': obj.pk})\n", (2261, 2312), False, 'from django.urls import reverse\n'), ((2336, 2404), 'django.urls.reverse', 'reverse', (['"""misago:api:user-delete-own-account"""'], {'kwargs': "{'pk': obj.pk}"}), "('misago:api:user-delete-own-account', kwargs={'pk': obj.pk})\n", (2343, 2404), False, 'from django.urls import reverse\n')]
mohammadanarul/Ecommerce-Django-YT
shop/models.py
afecc8f41693925619b81986d979706c64175360
from ctypes.wintypes import CHAR from distutils.command.upload import upload from random import choice from telnetlib import STATUS from unicodedata import category from django.db import models from ckeditor.fields import RichTextField from taggit.managers import TaggableManager # Create your models here. from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class MPTTMeta: order_insertion_by = ['name'] class Brand(models.Model): name = models.CharField(max_length=50) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Product(models.Model): STATUS_CHOICES = ( ('NONE', 'NONE'), ('NEW', 'NEW'), ('SALE', 'SALE'), ('HOT', 'HOT'), ) title = models.CharField(max_length=50) price = models.DecimalField(max_digits=5, decimal_places=2) short_description = RichTextField() tags = TaggableManager() description = RichTextField() specification = RichTextField() image = models.ImageField(upload_to='product/') category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) stack = models.IntegerField(default=5) status = models.CharField(max_length=5, choices=STATUS_CHOICES, default='NONE') is_fetured = models.BooleanField(default=False) is_special = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class ProductImages(models.Model): category = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to='products/')
[((397, 441), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'unique': '(True)'}), '(max_length=50, unique=True)\n', (413, 441), False, 'from django.db import models\n'), ((455, 555), 'mptt.models.TreeForeignKey', 'TreeForeignKey', (['"""self"""'], {'on_delete': 'models.CASCADE', 'null': '(True)', 'blank': '(True)', 'related_name': '"""children"""'}), "('self', on_delete=models.CASCADE, null=True, blank=True,\n related_name='children')\n", (469, 555), False, 'from mptt.models import MPTTModel, TreeForeignKey\n'), ((568, 601), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (587, 601), False, 'from django.db import models\n'), ((620, 659), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (640, 659), False, 'from django.db import models\n'), ((678, 713), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (698, 713), False, 'from django.db import models\n'), ((812, 843), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (828, 843), False, 'from django.db import models\n'), ((860, 893), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (879, 893), False, 'from django.db import models\n'), ((912, 951), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (932, 951), False, 'from django.db import models\n'), ((970, 1005), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (990, 1005), False, 'from django.db import models\n'), ((1178, 1209), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (1194, 1209), False, 'from django.db import models\n'), ((1222, 1273), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(5)', 'decimal_places': '(2)'}), '(max_digits=5, decimal_places=2)\n', (1241, 1273), False, 'from django.db import models\n'), ((1298, 1313), 'ckeditor.fields.RichTextField', 'RichTextField', ([], {}), '()\n', (1311, 1313), False, 'from ckeditor.fields import RichTextField\n'), ((1325, 1342), 'taggit.managers.TaggableManager', 'TaggableManager', ([], {}), '()\n', (1340, 1342), False, 'from taggit.managers import TaggableManager\n'), ((1361, 1376), 'ckeditor.fields.RichTextField', 'RichTextField', ([], {}), '()\n', (1374, 1376), False, 'from ckeditor.fields import RichTextField\n'), ((1397, 1412), 'ckeditor.fields.RichTextField', 'RichTextField', ([], {}), '()\n', (1410, 1412), False, 'from ckeditor.fields import RichTextField\n'), ((1425, 1464), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""product/"""'}), "(upload_to='product/')\n", (1442, 1464), False, 'from django.db import models\n'), ((1480, 1533), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Category'], {'on_delete': 'models.CASCADE'}), '(Category, on_delete=models.CASCADE)\n', (1497, 1533), False, 'from django.db import models\n'), ((1546, 1596), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Brand'], {'on_delete': 'models.CASCADE'}), '(Brand, on_delete=models.CASCADE)\n', (1563, 1596), False, 'from django.db import models\n'), ((1609, 1639), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(5)'}), '(default=5)\n', (1628, 1639), False, 'from django.db import models\n'), ((1653, 1723), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(5)', 'choices': 'STATUS_CHOICES', 'default': '"""NONE"""'}), "(max_length=5, choices=STATUS_CHOICES, default='NONE')\n", (1669, 1723), False, 'from django.db import models\n'), ((1742, 1776), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (1761, 1776), False, 'from django.db import models\n'), ((1795, 1829), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (1814, 1829), False, 'from django.db import models\n'), ((1846, 1879), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (1865, 1879), False, 'from django.db import models\n'), ((1898, 1937), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (1918, 1937), False, 'from django.db import models\n'), ((1956, 1991), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (1976, 1991), False, 'from django.db import models\n'), ((2043, 2118), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Product'], {'on_delete': 'models.CASCADE', 'related_name': '"""images"""'}), "(Product, on_delete=models.CASCADE, related_name='images')\n", (2060, 2118), False, 'from django.db import models\n'), ((2131, 2171), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""products/"""'}), "(upload_to='products/')\n", (2148, 2171), False, 'from django.db import models\n')]
deeuu/supriya
supriya/patterns/NoteEvent.py
14fcb5316eccb4dafbe498932ceff56e1abb9d27
import uuid import supriya.commands import supriya.realtime from supriya.patterns.Event import Event class NoteEvent(Event): ### CLASS VARIABLES ### __slots__ = () ### INITIALIZER ### def __init__( self, add_action=None, delta=None, duration=None, is_stop=True, synthdef=None, target_node=None, uuid=None, **settings, ): if add_action is not None: add_action = supriya.AddAction.from_expr(add_action) Event.__init__( self, add_action=add_action, delta=delta, duration=duration, is_stop=bool(is_stop), synthdef=synthdef, target_node=target_node, uuid=uuid, **settings, ) ### PRIVATE METHODS ### def _perform_nonrealtime(self, session, uuids, offset, maximum_offset=None): import supriya.assets.synthdefs settings = self.settings.copy() # Do not mutate in place. synthdef = self.get("synthdef", supriya.assets.synthdefs.default) synthdef = synthdef or supriya.assets.synthdefs.default synth_uuid = self.get("uuid", uuid.uuid4()) is_stop = self.get("is_stop") duration = self.get("duration") if duration is None: duration = 1 if "duration" in settings: duration = settings.pop("duration") dictionaries = self._expand( settings, synthdef, uuids, realtime=False, synth_parameters_only=True ) if synth_uuid not in uuids: # Begin a Pbind or Pmono synth target_node = self["target_node"] if isinstance(target_node, uuid.UUID) and target_node in uuids: target_node = uuids[target_node] prototype = (supriya.nonrealtime.Session, supriya.nonrealtime.Node) if not isinstance(target_node, prototype): target_node = session synths = [] with session.at(offset): for dictionary in dictionaries: synth = target_node.add_synth( add_action=self["add_action"], duration=duration, synthdef=synthdef, **dictionary, ) synths.append(synth) if not is_stop: uuids[synth_uuid] = tuple(synths) else: # Extend and make settings on a Pmono synth synths = uuids[synth_uuid] stop_offset = offset + duration for synth, dictionary in zip(synths, dictionaries): duration = stop_offset - synth.start_offset synth.set_duration(duration) with session.at(offset): for key, value in dictionary.items(): synth[key] = value return offset + max(self.delta, self.get("duration", 0)) def _perform_realtime(self, index=0, server=None, timestamp=0, uuids=None): import supriya.assets.synthdefs import supriya.patterns synth_uuid = self.get("uuid") or uuid.uuid4() synthdef = self.get("synthdef", supriya.assets.synthdefs.default) synthdef = synthdef or supriya.assets.synthdefs.default is_stop = self.get("is_stop") duration = self["duration"] if duration is None: duration = 1 dictionaries = self._expand(self.settings, synthdef, uuids) first_visit = False if synth_uuid not in uuids: first_visit = True node_ids = { server.node_id_allocator.allocate_node_id(): None for _ in range(len(dictionaries)) } uuids[synth_uuid] = node_ids start_product = self._build_start_bundle( dictionaries, first_visit, index, synth_uuid, synthdef, timestamp, uuids ) if self.get("duration"): if is_stop: stop_product = self._build_stop_bundle( index, synth_uuid, synthdef, timestamp, uuids ) else: stop_product = supriya.patterns.EventProduct( event=None, index=index, is_stop=True, requests=(), timestamp=timestamp + duration, uuid=None, ) return [start_product, stop_product] else: uuids.pop(synth_uuid) return [start_product] def _build_start_bundle( self, dictionaries, first_visit, index, synth_uuid, synthdef, timestamp, uuids ): import supriya.patterns requests = [] node_ids = uuids[synth_uuid] if first_visit: for node_id, dictionary in zip(node_ids, dictionaries): add_action = dictionary.pop("add_action") target_node = dictionary.pop("target_node") if target_node is None: target_node = 1 synth_kwargs = { key: value for key, value in dictionary.items() if key in synthdef.parameter_names } request = supriya.commands.SynthNewRequest( add_action=add_action, node_id=node_id, synthdef=synthdef, target_node_id=target_node, **synth_kwargs, ) requests.append(request) synth = supriya.realtime.Synth(synthdef) node_ids[node_id] = synth else: for node_id, dictionary in zip(node_ids, dictionaries): synth_kwargs = { key: value for key, value in dictionary.items() if key in synthdef.parameter_names } request = supriya.commands.NodeSetRequest( node_id=node_id, **synth_kwargs ) requests.append(request) event_product = supriya.patterns.EventProduct( event=self, index=index, is_stop=False, requests=requests, timestamp=timestamp, uuid=synth_uuid, ) return event_product def _build_stop_bundle(self, index, synth_uuid, synthdef, timestamp, uuids): import supriya.patterns import supriya.synthdefs duration = self["duration"] if duration is None: duration = 1 requests = [] timestamp = timestamp + duration node_ids = sorted(uuids[synth_uuid]) if synthdef.has_gate: for node_id in node_ids: request = supriya.commands.NodeSetRequest(node_id=node_id, gate=0) requests.append(request) elif any(x >= supriya.DoneAction.FREE_SYNTH for x in synthdef.done_actions): pass else: request = supriya.commands.NodeFreeRequest(node_ids=node_ids) requests.append(request) event_product = supriya.patterns.EventProduct( event=self, index=index, is_stop=True, requests=requests, timestamp=timestamp, uuid=synth_uuid, ) return event_product
[((1208, 1220), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1218, 1220), False, 'import uuid\n'), ((3193, 3205), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (3203, 3205), False, 'import uuid\n')]
ApacheAA/LastSeen
emoji_utils.py
1fe675b3ee3072d56e9fe094d1d80e1f7d876215
# unicode digit emojis # digits from '0' to '9' zero_digit_code = zd = 48 # excluded digits excl_digits = [2, 4, 5, 7] # unicode digit keycap udkc = '\U0000fe0f\U000020e3' hours_0_9 = [chr(i) + udkc for i in range(zd, zd + 10) if i - zd not in excl_digits] # number '10' emoji hours_0_9.append('\U0001f51f') # custom emojis from '11' to '23' hours_11_23 = [str(i) for i in range(11, 24)] vote = ('PLUS', 'MINUS') edit = '\U0001F4DD'
[]
Sniper970119/ExampleForTransformers
TFBertForMaskedLM/main.py
3348525957c38b2a45898d4f4652879933503b25
# -*- coding:utf-8 -*- """ ┏┛ ┻━━━━━┛ ┻┓ ┃       ┃ ┃   ━   ┃ ┃ ┳┛  ┗┳ ┃ ┃       ┃ ┃   ┻   ┃ ┃       ┃ ┗━┓   ┏━━━┛ ┃   ┃ 神兽保佑 ┃   ┃ 代码无BUG! ┃   ┗━━━━━━━━━┓ ┃CREATE BY SNIPER┣┓ ┃     ┏┛ ┗━┓ ┓ ┏━━━┳ ┓ ┏━┛ ┃ ┫ ┫ ┃ ┫ ┫ ┗━┻━┛ ┗━┻━┛ """ import tensorflow as tf import numpy as np for gpu in tf.config.experimental.list_physical_devices('GPU'): tf.config.experimental.set_memory_growth(gpu, True) from transformers import BertTokenizer, TFBertForMaskedLM tokenizer = BertTokenizer.from_pretrained('bert-base-cased') model = TFBertForMaskedLM.from_pretrained('bert-base-cased', return_dict=True) inputs = tokenizer("The capital of France is [MASK].", return_tensors="tf") outputs = model(inputs) logits = outputs.logits output = np.argmax(logits[0][6]) o1 = tokenizer.decode(int(output)) inputs = tokenizer("The capital of [MASK] is BeiJing.", return_tensors="tf") outputs = model(inputs) logits = outputs.logits output = np.argmax(logits[0][4]) o2 = tokenizer.decode(int(output)) print()
[((421, 472), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (465, 472), True, 'import tensorflow as tf\n'), ((602, 650), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-cased"""'], {}), "('bert-base-cased')\n", (631, 650), False, 'from transformers import BertTokenizer, TFBertForMaskedLM\n'), ((660, 730), 'transformers.TFBertForMaskedLM.from_pretrained', 'TFBertForMaskedLM.from_pretrained', (['"""bert-base-cased"""'], {'return_dict': '(True)'}), "('bert-base-cased', return_dict=True)\n", (693, 730), False, 'from transformers import BertTokenizer, TFBertForMaskedLM\n'), ((867, 890), 'numpy.argmax', 'np.argmax', (['logits[0][6]'], {}), '(logits[0][6])\n', (876, 890), True, 'import numpy as np\n'), ((1063, 1086), 'numpy.argmax', 'np.argmax', (['logits[0][4]'], {}), '(logits[0][4])\n', (1072, 1086), True, 'import numpy as np\n'), ((478, 529), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['gpu', '(True)'], {}), '(gpu, True)\n', (518, 529), True, 'import tensorflow as tf\n')]
gcastellan0s/mirariapp
mirari/TCS/migrations/0042_auto_20190726_0145.py
24a9db06d10f96c894d817ef7ccfeec2a25788b7
# Generated by Django 2.0.5 on 2019-07-26 06:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('TCS', '0041_auto_20190726_0030'), ] operations = [ migrations.AlterModelOptions( name='modelo', options={'default_permissions': [], 'ordering': ['-id'], 'permissions': [('Can_View__Modelo', 'Ve modelos'), ('Can_Create__Modelo', 'Crea modelos'), ('Can_Update__Modelo', 'Modifica modelos'), ('Can_Delete__Modelo', 'Elimina modelos'), ('Can_Change__ModelTCS', 'Modifica modelos de equipo')], 'verbose_name': 'Modelo', 'verbose_name_plural': 'Modelos'}, ), ]
[((223, 645), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""modelo"""', 'options': "{'default_permissions': [], 'ordering': ['-id'], 'permissions': [(\n 'Can_View__Modelo', 'Ve modelos'), ('Can_Create__Modelo',\n 'Crea modelos'), ('Can_Update__Modelo', 'Modifica modelos'), (\n 'Can_Delete__Modelo', 'Elimina modelos'), ('Can_Change__ModelTCS',\n 'Modifica modelos de equipo')], 'verbose_name': 'Modelo',\n 'verbose_name_plural': 'Modelos'}"}), "(name='modelo', options={'default_permissions':\n [], 'ordering': ['-id'], 'permissions': [('Can_View__Modelo',\n 'Ve modelos'), ('Can_Create__Modelo', 'Crea modelos'), (\n 'Can_Update__Modelo', 'Modifica modelos'), ('Can_Delete__Modelo',\n 'Elimina modelos'), ('Can_Change__ModelTCS',\n 'Modifica modelos de equipo')], 'verbose_name': 'Modelo',\n 'verbose_name_plural': 'Modelos'})\n", (251, 645), False, 'from django.db import migrations\n')]
belltailjp/kornia
kornia/geometry/calibration/undistort.py
cfa3b6823d55e276893847f1c3f06ddf108c606a
import torch from kornia.geometry.linalg import transform_points from kornia.geometry.transform import remap from kornia.utils import create_meshgrid from .distort import distort_points, tilt_projection # Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384 def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) -> torch.Tensor: r"""Compensate for lens distortion a set of 2D image points. Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`, tangential :math:`(p_1, p_2)`, thin prism :math:`(s_1, s_2, s_3, s_4)`, and tilt :math:`(\tau_x, \tau_y)` distortion models are considered in this function. Args: points: Input image points with shape :math:`(*, N, 2)`. K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`. dist: Distortion coefficients :math:`(k_1,k_2,p_1,p_2[,k_3[,k_4,k_5,k_6[,s_1,s_2,s_3,s_4[,\tau_x,\tau_y]]]])`. This is a vector with 4, 5, 8, 12 or 14 elements with shape :math:`(*, n)`. Returns: Undistorted 2D points with shape :math:`(*, N, 2)`. Example: >>> _ = torch.manual_seed(0) >>> x = torch.rand(1, 4, 2) >>> K = torch.eye(3)[None] >>> dist = torch.rand(1, 4) >>> undistort_points(x, K, dist) tensor([[[-0.1513, -0.1165], [ 0.0711, 0.1100], [-0.0697, 0.0228], [-0.1843, -0.1606]]]) """ if points.dim() < 2 and points.shape[-1] != 2: raise ValueError(f'points shape is invalid. Got {points.shape}.') if K.shape[-2:] != (3, 3): raise ValueError(f'K matrix shape is invalid. Got {K.shape}.') if dist.shape[-1] not in [4, 5, 8, 12, 14]: raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}") # Adding zeros to obtain vector with 14 coeffs. if dist.shape[-1] < 14: dist = torch.nn.functional.pad(dist, [0, 14 - dist.shape[-1]]) # Convert 2D points from pixels to normalized camera coordinates cx: torch.Tensor = K[..., 0:1, 2] # princial point in x (Bx1) cy: torch.Tensor = K[..., 1:2, 2] # princial point in y (Bx1) fx: torch.Tensor = K[..., 0:1, 0] # focal in x (Bx1) fy: torch.Tensor = K[..., 1:2, 1] # focal in y (Bx1) # This is equivalent to K^-1 [u,v,1]^T x: torch.Tensor = (points[..., 0] - cx) / fx # (BxN - Bx1)/Bx1 -> BxN y: torch.Tensor = (points[..., 1] - cy) / fy # (BxN - Bx1)/Bx1 -> BxN # Compensate for tilt distortion if torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0): inv_tilt = tilt_projection(dist[..., 12], dist[..., 13], True) # Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1]) x, y = transform_points(inv_tilt, torch.stack([x, y], dim=-1)).unbind(-1) # Iteratively undistort points x0, y0 = x, y for _ in range(5): r2 = x * x + y * y inv_rad_poly = (1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r2 * r2 + dist[..., 7:8] * r2 ** 3) / ( 1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r2 * r2 + dist[..., 4:5] * r2 ** 3 ) deltaX = ( 2 * dist[..., 2:3] * x * y + dist[..., 3:4] * (r2 + 2 * x * x) + dist[..., 8:9] * r2 + dist[..., 9:10] * r2 * r2 ) deltaY = ( dist[..., 2:3] * (r2 + 2 * y * y) + 2 * dist[..., 3:4] * x * y + dist[..., 10:11] * r2 + dist[..., 11:12] * r2 * r2 ) x = (x0 - deltaX) * inv_rad_poly y = (y0 - deltaY) * inv_rad_poly # Convert points from normalized camera coordinates to pixel coordinates x = fx * x + cx y = fy * y + cy return torch.stack([x, y], -1) # Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L287 def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) -> torch.Tensor: r"""Compensate an image for lens distortion. Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`, tangential :math:`(p_1, p_2)`, thin prism :math:`(s_1, s_2, s_3, s_4)`, and tilt :math:`(\tau_x, \tau_y)` distortion models are considered in this function. Args: image: Input image with shape :math:`(*, C, H, W)`. K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`. dist: Distortion coefficients :math:`(k_1,k_2,p_1,p_2[,k_3[,k_4,k_5,k_6[,s_1,s_2,s_3,s_4[,\tau_x,\tau_y]]]])`. This is a vector with 4, 5, 8, 12 or 14 elements with shape :math:`(*, n)`. Returns: Undistorted image with shape :math:`(*, C, H, W)`. Example: >>> img = torch.rand(1, 3, 5, 5) >>> K = torch.eye(3)[None] >>> dist_coeff = torch.rand(4) >>> out = undistort_image(img, K, dist_coeff) >>> out.shape torch.Size([1, 3, 5, 5]) """ if len(image.shape) < 2: raise ValueError(f"Image shape is invalid. Got: {image.shape}.") if K.shape[-2:] != (3, 3): raise ValueError(f'K matrix shape is invalid. Got {K.shape}.') if dist.shape[-1] not in [4, 5, 8, 12, 14]: raise ValueError(f'Invalid number of distortion coefficients. Got {dist.shape[-1]}.') if not image.is_floating_point(): raise ValueError(f'Invalid input image data type. Input should be float. Got {image.dtype}.') B, _, rows, cols = image.shape # Create point coordinates for each pixel of the image xy_grid: torch.Tensor = create_meshgrid(rows, cols, False, image.device, image.dtype) pts = xy_grid.reshape(-1, 2) # (rows*cols)x2 matrix of pixel coordinates # Distort points and define maps ptsd: torch.Tensor = distort_points(pts, K, dist) # Bx(rows*cols)x2 mapx: torch.Tensor = ptsd[..., 0].reshape(B, rows, cols) # B x rows x cols, float mapy: torch.Tensor = ptsd[..., 1].reshape(B, rows, cols) # B x rows x cols, float # Remap image to undistort out = remap(image, mapx, mapy, align_corners=True) return out
[((3764, 3787), 'torch.stack', 'torch.stack', (['[x, y]', '(-1)'], {}), '([x, y], -1)\n', (3775, 3787), False, 'import torch\n'), ((5543, 5604), 'kornia.utils.create_meshgrid', 'create_meshgrid', (['rows', 'cols', '(False)', 'image.device', 'image.dtype'], {}), '(rows, cols, False, image.device, image.dtype)\n', (5558, 5604), False, 'from kornia.utils import create_meshgrid\n'), ((6010, 6054), 'kornia.geometry.transform.remap', 'remap', (['image', 'mapx', 'mapy'], {'align_corners': '(True)'}), '(image, mapx, mapy, align_corners=True)\n', (6015, 6054), False, 'from kornia.geometry.transform import remap\n'), ((1947, 2002), 'torch.nn.functional.pad', 'torch.nn.functional.pad', (['dist', '[0, 14 - dist.shape[-1]]'], {}), '(dist, [0, 14 - dist.shape[-1]])\n', (1970, 2002), False, 'import torch\n'), ((2561, 2590), 'torch.any', 'torch.any', (['(dist[..., 12] != 0)'], {}), '(dist[..., 12] != 0)\n', (2570, 2590), False, 'import torch\n'), ((2594, 2623), 'torch.any', 'torch.any', (['(dist[..., 13] != 0)'], {}), '(dist[..., 13] != 0)\n', (2603, 2623), False, 'import torch\n'), ((2816, 2843), 'torch.stack', 'torch.stack', (['[x, y]'], {'dim': '(-1)'}), '([x, y], dim=-1)\n', (2827, 2843), False, 'import torch\n')]
o-Ian/Practice-Python
Tests/Aula_7a.py
1e4b2d0788e70006096a53a7cf038db3148ba4b7
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) print('A soma é: {}!' .format(n1+n2)) print('A subtração entre {} e {} é {}!' .format(n1, n2, n1-n2)) print('A multiplicação desses valores é {}!' .format(n1 * n2)) print('A divisão entre {} e {} é {:.3}' .format(n1, n2, n1/n2)) print('A divisão sem restos é {}!' .format(n1//n2), end = ' ') print('O resto dessa divisão é {}' .format(n1 % n2))
[]
shuvro-zz/manubot
manubot/cite/tests/test_citekey_api.py
9023b7fbfa0b235c14a4d702516bc0cd6d3101ed
"""Tests API-level functions in manubot.cite. Both functions are found in citekey.py""" import pytest from manubot.cite import citekey_to_csl_item, standardize_citekey @pytest.mark.parametrize( "citekey,expected", [ ("doi:10.5061/DRYAD.q447c/1", "doi:10.5061/dryad.q447c/1"), ("doi:10.5061/dryad.q447c/1", "doi:10.5061/dryad.q447c/1"), ("doi:10/b6vnmd", "doi:10.1016/s0933-3657(96)00367-3"), ("doi:10/B6VNMD", "doi:10.1016/s0933-3657(96)00367-3"), ( "doi:10/xxxxxxxxxxxxxYY", "doi:10/xxxxxxxxxxxxxyy", ), # passthrough non-existent shortDOI ("pmid:24159271", "pmid:24159271"), ("isbn:1339919885", "isbn:9781339919881"), ("isbn:1-339-91988-5", "isbn:9781339919881"), ("isbn:978-0-387-95069-3", "isbn:9780387950693"), ("isbn:9780387950938", "isbn:9780387950938"), ("isbn:1-55860-510-X", "isbn:9781558605107"), ("isbn:1-55860-510-x", "isbn:9781558605107"), ], ) def test_standardize_citekey(citekey, expected): """ Standardize identifiers based on their source """ output = standardize_citekey(citekey) assert output == expected @pytest.mark.xfail(reason="https://twitter.com/dhimmel/status/950443969313419264") def test_citekey_to_csl_item_doi_datacite(): citekey = "doi:10.7287/peerj.preprints.3100v1" csl_item = citekey_to_csl_item(citekey) assert csl_item["id"] == "11cb5HXoY" assert csl_item["URL"] == "https://doi.org/10.7287/peerj.preprints.3100v1" assert csl_item["DOI"] == "10.7287/peerj.preprints.3100v1" assert csl_item["type"] == "report" assert ( csl_item["title"] == "Sci-Hub provides access to nearly all scholarly literature" ) authors = csl_item["author"] assert authors[0]["family"] == "Himmelstein" assert authors[-1]["family"] == "Greene" def test_citekey_to_csl_item_arxiv(): citekey = "arxiv:cond-mat/0703470v2" csl_item = citekey_to_csl_item(citekey) assert csl_item["id"] == "ES92tcdg" assert csl_item["URL"] == "https://arxiv.org/abs/cond-mat/0703470v2" assert csl_item["number"] == "cond-mat/0703470v2" assert csl_item["version"] == "2" assert csl_item["type"] == "report" assert csl_item["container-title"] == "arXiv" assert csl_item["title"] == "Portraits of Complex Networks" authors = csl_item["author"] assert authors[0]["literal"] == "J. P. Bagrow" assert csl_item["DOI"] == "10.1209/0295-5075/81/68004" def test_citekey_to_csl_item_pmc(): """ https://api.ncbi.nlm.nih.gov/lit/ctxp/v1/pmc/?format=csl&id=3041534 """ citekey = f"pmcid:PMC3041534" csl_item = citekey_to_csl_item(citekey) assert csl_item["id"] == "RoOhUFKU" assert csl_item["URL"] == "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3041534/" assert csl_item["container-title-short"] == "Summit Transl Bioinform" assert ( csl_item["title"] == "Secondary Use of EHR: Data Quality Issues and Informatics Opportunities" ) authors = csl_item["author"] assert authors[0]["family"] == "Botsis" assert csl_item["PMID"] == "21347133" assert csl_item["PMCID"] == "PMC3041534" assert "generated by Manubot" in csl_item["note"] assert "standard_id: pmcid:PMC3041534" in csl_item["note"] def test_citekey_to_csl_item_pubmed_1(): """ Generated from XML returned by https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=21347133&rettype=full """ citekey = "pmid:21347133" csl_item = citekey_to_csl_item(citekey) assert csl_item["id"] == "y9ONtSZ9" assert csl_item["type"] == "article-journal" assert csl_item["URL"] == "https://www.ncbi.nlm.nih.gov/pubmed/21347133" assert csl_item["container-title"] == "Summit on translational bioinformatics" assert ( csl_item["title"] == "Secondary Use of EHR: Data Quality Issues and Informatics Opportunities." ) assert csl_item["issued"]["date-parts"] == [[2010, 3, 1]] authors = csl_item["author"] assert authors[0]["given"] == "Taxiarchis" assert authors[0]["family"] == "Botsis" assert csl_item["PMID"] == "21347133" assert csl_item["PMCID"] == "PMC3041534" def test_citekey_to_csl_item_pubmed_2(): """ Generated from XML returned by https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=27094199&rettype=full """ citekey = "pmid:27094199" csl_item = citekey_to_csl_item(citekey) print(csl_item) assert csl_item["id"] == "alaFV9OY" assert csl_item["type"] == "article-journal" assert csl_item["URL"] == "https://www.ncbi.nlm.nih.gov/pubmed/27094199" assert csl_item["container-title"] == "Circulation. Cardiovascular genetics" assert csl_item["container-title-short"] == "Circ Cardiovasc Genet" assert csl_item["page"] == "179-84" assert ( csl_item["title"] == "Genetic Association-Guided Analysis of Gene Networks for the Study of Complex Traits." ) assert csl_item["issued"]["date-parts"] == [[2016, 4]] authors = csl_item["author"] assert authors[0]["given"] == "Casey S" assert authors[0]["family"] == "Greene" assert csl_item["PMID"] == "27094199" assert csl_item["DOI"] == "10.1161/circgenetics.115.001181" def test_citekey_to_csl_item_pubmed_with_numeric_month(): """ Generated from XML returned by https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=29028984&rettype=full See https://github.com/manubot/manubot/issues/69 """ citekey = "pmid:29028984" csl_item = citekey_to_csl_item(citekey) print(csl_item) assert csl_item["issued"]["date-parts"] == [[2018, 3, 15]] def test_citekey_to_csl_item_pubmed_book(): """ Extracting CSL metadata from books in PubMed is not supported. Logic not implemented to parse XML returned by https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=29227604&rettype=full """ with pytest.raises(NotImplementedError): citekey_to_csl_item("pmid:29227604") def test_citekey_to_csl_item_isbn(): csl_item = citekey_to_csl_item("isbn:9780387950693") assert csl_item["type"] == "book" assert csl_item["title"] == "Complex analysis"
[((173, 854), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""citekey,expected"""', "[('doi:10.5061/DRYAD.q447c/1', 'doi:10.5061/dryad.q447c/1'), (\n 'doi:10.5061/dryad.q447c/1', 'doi:10.5061/dryad.q447c/1'), (\n 'doi:10/b6vnmd', 'doi:10.1016/s0933-3657(96)00367-3'), ('doi:10/B6VNMD',\n 'doi:10.1016/s0933-3657(96)00367-3'), ('doi:10/xxxxxxxxxxxxxYY',\n 'doi:10/xxxxxxxxxxxxxyy'), ('pmid:24159271', 'pmid:24159271'), (\n 'isbn:1339919885', 'isbn:9781339919881'), ('isbn:1-339-91988-5',\n 'isbn:9781339919881'), ('isbn:978-0-387-95069-3', 'isbn:9780387950693'),\n ('isbn:9780387950938', 'isbn:9780387950938'), ('isbn:1-55860-510-X',\n 'isbn:9781558605107'), ('isbn:1-55860-510-x', 'isbn:9781558605107')]"], {}), "('citekey,expected', [('doi:10.5061/DRYAD.q447c/1',\n 'doi:10.5061/dryad.q447c/1'), ('doi:10.5061/dryad.q447c/1',\n 'doi:10.5061/dryad.q447c/1'), ('doi:10/b6vnmd',\n 'doi:10.1016/s0933-3657(96)00367-3'), ('doi:10/B6VNMD',\n 'doi:10.1016/s0933-3657(96)00367-3'), ('doi:10/xxxxxxxxxxxxxYY',\n 'doi:10/xxxxxxxxxxxxxyy'), ('pmid:24159271', 'pmid:24159271'), (\n 'isbn:1339919885', 'isbn:9781339919881'), ('isbn:1-339-91988-5',\n 'isbn:9781339919881'), ('isbn:978-0-387-95069-3', 'isbn:9780387950693'),\n ('isbn:9780387950938', 'isbn:9780387950938'), ('isbn:1-55860-510-X',\n 'isbn:9781558605107'), ('isbn:1-55860-510-x', 'isbn:9781558605107')])\n", (196, 854), False, 'import pytest\n'), ((1194, 1280), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""https://twitter.com/dhimmel/status/950443969313419264"""'}), "(reason=\n 'https://twitter.com/dhimmel/status/950443969313419264')\n", (1211, 1280), False, 'import pytest\n'), ((1132, 1160), 'manubot.cite.standardize_citekey', 'standardize_citekey', (['citekey'], {}), '(citekey)\n', (1151, 1160), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n'), ((1387, 1415), 'manubot.cite.citekey_to_csl_item', 'citekey_to_csl_item', (['citekey'], {}), '(citekey)\n', (1406, 1415), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n'), ((1979, 2007), 'manubot.cite.citekey_to_csl_item', 'citekey_to_csl_item', (['citekey'], {}), '(citekey)\n', (1998, 2007), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n'), ((2685, 2713), 'manubot.cite.citekey_to_csl_item', 'citekey_to_csl_item', (['citekey'], {}), '(citekey)\n', (2704, 2713), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n'), ((3561, 3589), 'manubot.cite.citekey_to_csl_item', 'citekey_to_csl_item', (['citekey'], {}), '(citekey)\n', (3580, 3589), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n'), ((4479, 4507), 'manubot.cite.citekey_to_csl_item', 'citekey_to_csl_item', (['citekey'], {}), '(citekey)\n', (4498, 4507), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n'), ((5624, 5652), 'manubot.cite.citekey_to_csl_item', 'citekey_to_csl_item', (['citekey'], {}), '(citekey)\n', (5643, 5652), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n'), ((6157, 6198), 'manubot.cite.citekey_to_csl_item', 'citekey_to_csl_item', (['"""isbn:9780387950693"""'], {}), "('isbn:9780387950693')\n", (6176, 6198), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n'), ((6022, 6056), 'pytest.raises', 'pytest.raises', (['NotImplementedError'], {}), '(NotImplementedError)\n', (6035, 6056), False, 'import pytest\n'), ((6066, 6102), 'manubot.cite.citekey_to_csl_item', 'citekey_to_csl_item', (['"""pmid:29227604"""'], {}), "('pmid:29227604')\n", (6085, 6102), False, 'from manubot.cite import citekey_to_csl_item, standardize_citekey\n')]
hmaarrfk/vispy
vispy/io/datasets.py
7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2
# -*- coding: utf-8 -*- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from os import path as op from ..util import load_data_file # This is the package data dir, not the dir for config, etc. DATA_DIR = op.join(op.dirname(__file__), '_data') def load_iris(): """Load the iris dataset Returns ------- iris : NpzFile data['data'] : a (150, 4) NumPy array with the iris' features data['group'] : a (150,) NumPy array with the iris' group """ return np.load(load_data_file('iris/iris.npz', force_download='2014-09-04')) def load_crate(): """Load an image of a crate Returns ------- crate : array 256x256x3 crate image. """ return np.load(load_data_file('orig/crate.npz'))['crate'] def pack_unit(value): """Packs float values between [0,1] into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """ pack = np.zeros(value.shape + (4,), dtype=np.ubyte) for i in range(4): value, pack[..., i] = np.modf(value * 256.) return pack def pack_ieee(value): """Packs float ieee binary representation into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """ return np.fromstring(value.tobytes(), np.ubyte).reshape((value.shape + (4,))) def load_spatial_filters(packed=True): """Load spatial-filters kernel Parameters ---------- packed : bool Whether or not the data should be in "packed" representation for use in GLSL code. Returns ------- kernel : array 16x1024x4 (packed float in rgba) or 16x1024 (unpacked float) 16 interpolation kernel with length 1024 each. names : tuple of strings Respective interpolation names, plus "Nearest" which does not require a filter but can still be used """ names = ("Bilinear", "Hanning", "Hamming", "Hermite", "Kaiser", "Quadric", "Bicubic", "CatRom", "Mitchell", "Spline16", "Spline36", "Gaussian", "Bessel", "Sinc", "Lanczos", "Blackman", "Nearest") kernel = np.load(op.join(DATA_DIR, 'spatial-filters.npy')) if packed: # convert the kernel to a packed representation kernel = pack_unit(kernel) return kernel, names
[((321, 341), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (331, 341), True, 'from os import path as op\n'), ((1080, 1124), 'numpy.zeros', 'np.zeros', (['(value.shape + (4,))'], {'dtype': 'np.ubyte'}), '(value.shape + (4,), dtype=np.ubyte)\n', (1088, 1124), True, 'import numpy as np\n'), ((1178, 1200), 'numpy.modf', 'np.modf', (['(value * 256.0)'], {}), '(value * 256.0)\n', (1185, 1200), True, 'import numpy as np\n'), ((2315, 2355), 'os.path.join', 'op.join', (['DATA_DIR', '"""spatial-filters.npy"""'], {}), "(DATA_DIR, 'spatial-filters.npy')\n", (2322, 2355), True, 'from os import path as op\n')]
jehung/universal_portfolio
universal_portfolio/knapsack.py
de731a6166ff057c8d6f3f73f80f9aca151805fa
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np np.random.seed(1335) # for reproducibility np.set_printoptions(precision=5, suppress=True, linewidth=150) import os import pandas as pd import backtest as twp from matplotlib import pyplot as plt from sklearn import metrics, preprocessing from talib.abstract import * from sklearn.externals import joblib import quandl import random, timeit from sklearn import preprocessing from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.layers.recurrent import LSTM from keras.optimizers import RMSprop, Adam ''' Name: The Self Learning Quant, Example 3 Author: Daniel Zakrisson Created: 30/03/2016 Copyright: (c) Daniel Zakrisson 2016 Licence: BSD Requirements: Numpy Pandas MatplotLib scikit-learn TA-Lib, instructions at https://mrjbq7.github.io/ta-lib/install.html Keras, https://keras.io/ Quandl, https://www.quandl.com/tools/python backtest.py from the TWP library. Download backtest.py and put in the same folder /plt create a subfolder in the same directory where plot files will be saved ''' def get_ticker(x): return x.split('/')[-1].split('.')[0] def read_file(file, test=None): scaler = preprocessing.MinMaxScaler() d = pd.read_csv(file).set_index('Date') d.fillna(0, inplace=True) ticker = get_ticker(file) d['ticker'] = ticker d.rename(columns={'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Adj Close': 'adj_close', 'Volume (BTC)': 'volume'}, inplace=True) x_train = d.iloc[:-100, ] x_test = d.iloc[-100:, ] if test: return x_test, ticker else: return x_train, ticker # Initialize first state, all items are placed deterministically def init_state(file, test): d, ticker = read_file(file, test=test) xdata = pd.DataFrame() scaler = preprocessing.StandardScaler() xdata['adj_close'] = d['adj_close'] # .values xdata['diff'] = xdata['adj_close'].diff(periods=1) xdata['diff'].fillna(0, inplace=True) xdata['sma15'] = SMA(d, timeperiod=15) xdata['sma60'] = SMA(d, timeperiod=60) xdata['rsi'] = RSI(d, timeperiod=14) xdata['atr'] = ATR(d, timeperiod=14) xdata.fillna(0, inplace=True) # --- Preprocess data # xdata = np.column_stack((close, diff, sma15, close - sma15, sma15 - sma60, rsi, atr)) xdata = pd.DataFrame(scaler.fit_transform(xdata), columns=xdata.columns) xdata['ticker'] = ticker pivot_columns = xdata.columns[0:-1] pivot = xdata.pivot_table(index=d.index, columns='ticker', values=pivot_columns) # Make a pivot table from the data pivot.columns = [s1 + '-' + s2 for (s1, s2) in pivot.columns.tolist()] return pivot def all_init_data(test=False): filepath = 'util/stock_dfs/' all = [] scaler = preprocessing.StandardScaler() for f in os.listdir(filepath): datapath = os.path.join(filepath, f) if datapath.endswith('.csv'): # print(datapath) Res = init_state(datapath, test=test) all.append(Res) all = pd.concat(all, axis=1) all.fillna(0, inplace=True) closecol = [col for col in all.columns if 'adj_close' in col] close = all[closecol].values # xdata = np.column_stack((close, diff, sma15, close-sma15, sma15-sma60, rsi, atr)) xdata = np.vstack(all.values) xdata = np.nan_to_num(xdata) if test == False: scaler = preprocessing.StandardScaler() xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1) joblib.dump(scaler, 'data/scaler.pkl') else: scaler = joblib.load('data/scaler.pkl') xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1) state = xdata[0:1, 0:1, :] return state, xdata, close # Take Action def take_action(state, xdata, action, signal, time_step): # this should generate a list of trade signals that at evaluation time are fed to the backtester # the backtester should get a list of trade signals and a list of price data for the assett # make necessary adjustments to state and then return it time_step += 1 # if the current iteration is the last state ("terminal state") then set terminal_state to 1 if time_step + 1 == xdata.shape[0]: state = xdata[time_step - 1:time_step, 0:1, :] terminal_state = 1 signal.loc[time_step] = 0 return state, time_step, signal, terminal_state # move the market data window one step forward state = xdata[time_step - 1:time_step, 0:1, :] # take action if action == 1: signal.loc[time_step] = 100 elif action == 2: signal.loc[time_step] = -100 else: signal.loc[time_step] = 0 # print(state) terminal_state = 0 # print(signal) return state, time_step, signal, terminal_state # Get Reward, the reward is returned at the end of an episode def get_reward(new_state, time_step, action, xdata, signal, terminal_state, eval=False, epoch=0): reward = 0 signal.fillna(value=0, inplace=True) if eval == False: try: bt = twp.Backtest(pd.Series(data=[x[0] for x in xdata[time_step - 2:time_step]], index=signal[time_step - 2:time_step].index.values), signal[time_step - 2:time_step], signalType='shares') reward = np.max((bt.data['price'].iloc[-1] - bt.data['price'].iloc[-2]) * bt.data['shares'].iloc[-1]) except: pass if terminal_state == 1 and eval == True: bt = twp.Backtest(pd.Series(data=[x[0] for x in xdata], index=signal.index.values), signal, signalType='shares') reward = bt.pnl.iloc[-1] plt.figure(figsize=(9, 16)) bt.plotTrades() plt.axvline(x=400, color='black', linestyle='--') plt.text(250, 400, 'training data') plt.text(450, 400, 'test data') plt.suptitle(str(epoch)) plt.savefig('plt/' + 'knapsack_' + str(epoch) + '.png') plt.close('all') ''' # save a figure of the test set plt.figure(figsize=(10, 25)) for i in range(xdata.T.shape[0]): #frame = pd.concat(btFrame, axis=1) bt = twp.Backtest(pd.Series(data=[x for x in xdata.T[i]], index=signal.index.values), signal, signalType='shares') reward += np.max(bt.pnl.iloc[-1]) bt.plotTrades() #plt.axvline(x=400, color='black', linestyle='--') #plt.text(250, 400, 'training data') #plt.text(450, 400, 'test data') #plt.suptitle(str(epoch)) plt.savefig('plt/' + 'knapsack_' + str(epoch) + '.png', bbox_inches='tight', pad_inches=1, dpi=72) plt.close('all') ''' # print(time_step, terminal_state, eval, reward) return reward def evaluate_Q(eval_data, eval_model, epoch=0): # This function is used to evaluate the performance of the system each epoch, without the influence of epsilon and random actions signal = pd.Series(index=np.arange(len(eval_data))) state, xdata, price_data = all_init_data() status = 1 terminal_state = 0 time_step = 1 while (status == 1): # We start in state S qval = eval_model.predict(state, batch_size=batch_size) action = (np.argmax(qval)) # Take action, observe new state S' new_state, time_step, signal, terminal_state = take_action(state, xdata, action, signal, time_step) # Observe reward eval_reward = get_reward(new_state, time_step, action, price_data, signal, terminal_state, eval=True, epoch=epoch) state = new_state if terminal_state == 1: # terminal state status = 0 return eval_reward if __name__ == "__main__": # This neural network is the the Q-function, run it like this: # model.predict(state.reshape(1,64), batch_size=1) batch_size = 7 num_features = 2544 epochs = 3 gamma = 0.95 # since the reward can be several time steps away, make gamma high epsilon = 1 batchSize = 100 buffer = 200 replay = [] learning_progress = [] model = Sequential() model.add(LSTM(64, input_shape=(1, num_features), return_sequences=True, stateful=False)) model.add(Dropout(0.5)) model.add(LSTM(64, input_shape=(1, num_features), return_sequences=False, stateful=False)) model.add(Dropout(0.5)) model.add(Dense(4, init='lecun_uniform')) model.add(Activation('linear')) # linear output so we can have range of real-valued outputs rms = RMSprop() adam = Adam() model.compile(loss='mse', optimizer=adam) start_time = timeit.default_timer() # read_convert_data(symbol='XBTEUR') #run once to read indata, resample and convert to pickle astate, xdata, aprice_data = all_init_data() bstate, test_data, test_price_data = all_init_data(test=True) ''' bstate, test_data, test_price_data = all_init_data(test=True) print(astate.shape) print(bstate.shape) print(xdata.shape) print(test_data.shape) print(price_data.shape) print(test_price_data.shape) ''' # stores tuples of (S, A, R, S') h = 0 # signal = pd.Series(index=market_data.index) signal = pd.Series(index=np.arange(len(xdata))) for i in range(epochs): if i == epochs - 1: # the last epoch, use test data set state, xdata, price_data = all_init_data() else: state, xdata, price_data = all_init_data(test=True) status = 1 terminal_state = 0 time_step = 5 # while game still in progress while (status == 1): # We are in state S # Let's run our Q function on S to get Q values for all possible actions print('epoch ' + str(i)) qval = model.predict(state, batch_size=batch_size) if (random.random() < epsilon): # choose random action action = np.random.randint(0, 4) # assumes 4 different actions else: # choose best action from Q(s,a) values action = (np.argmax(qval)) # Take action, observe new state S' new_state, time_step, signal, terminal_state = take_action(state, xdata, action, signal, time_step) # Observe reward reward = get_reward(new_state, time_step, action, price_data, signal, terminal_state) print('new_state', new_state) print('reward', reward) # Experience replay storage if (len(replay) < buffer): # if buffer not filled, add to it replay.append((state, action, reward, new_state)) # print(time_step, reward, terminal_state) else: # if buffer full, overwrite old values if (h < (buffer - 1)): h += 1 else: h = 0 replay[h] = (state, action, reward, new_state) # randomly sample our experience replay memory minibatch = random.sample(replay, batchSize) X_train = [] y_train = [] for memory in minibatch: # Get max_Q(S',a) old_state, action, reward, new_state = memory old_qval = model.predict(old_state, batch_size=batch_size) newQ = model.predict(new_state, batch_size=batch_size) maxQ = np.max(newQ) y = np.zeros((1, 4)) y[:] = old_qval[:] if terminal_state == 0: # non-terminal state update = (reward + (gamma * maxQ)) else: # terminal state update = reward # print('rewardbase', reward) # print('update', update) y[0][action] = update # print(time_step, reward, terminal_state) X_train.append(old_state) y_train.append(y.reshape(4, )) X_train = np.squeeze(np.array(X_train), axis=(1)) y_train = np.array(y_train) model.fit(X_train, y_train, batch_size=batchSize, epochs=100, verbose=0) state = new_state if terminal_state == 1: # if reached terminal state, update epoch status status = 0 eval_reward = evaluate_Q(test_data, model, i) # eval_reward = value_iter(test_data, epsilon, epochs) learning_progress.append(eval_reward) print("Epoch #: %s Reward: %f Epsilon: %f" % (i, eval_reward, epsilon)) # learning_progress.append((reward)) if epsilon > 0.1: # decrement epsilon over time epsilon -= (1.0 / epochs) elapsed = np.round(timeit.default_timer() - start_time, decimals=2) print("Completed in %f" % (elapsed,)) bt = twp.Backtest(pd.Series(data=[x[0] for x in test_price_data]), signal, signalType='shares') bt.data['delta'] = bt.data['shares'].diff().fillna(0) print(bt.data) bt.data.to_csv('plt/knapsack_data.csv') unique, counts = np.unique(filter(lambda v: v == v, signal.values), return_counts=True) print(np.asarray((unique, counts)).T) plt.figure() plt.subplot(3, 1, 1) bt.plotTrades() plt.subplot(3, 1, 2) bt.pnl.plot(style='x-') plt.subplot(3, 1, 3) plt.plot(learning_progress) print('to plot', learning_progress) plt.savefig('plt/knapsack_summary' + '.png', bbox_inches='tight', pad_inches=1, dpi=72) plt.show()
[((82, 102), 'numpy.random.seed', 'np.random.seed', (['(1335)'], {}), '(1335)\n', (96, 102), True, 'import numpy as np\n'), ((126, 188), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(5)', 'suppress': '(True)', 'linewidth': '(150)'}), '(precision=5, suppress=True, linewidth=150)\n', (145, 188), True, 'import numpy as np\n'), ((1264, 1292), 'sklearn.preprocessing.MinMaxScaler', 'preprocessing.MinMaxScaler', ([], {}), '()\n', (1290, 1292), False, 'from sklearn import preprocessing\n'), ((1904, 1918), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1916, 1918), True, 'import pandas as pd\n'), ((1932, 1962), 'sklearn.preprocessing.StandardScaler', 'preprocessing.StandardScaler', ([], {}), '()\n', (1960, 1962), False, 'from sklearn import preprocessing\n'), ((2885, 2915), 'sklearn.preprocessing.StandardScaler', 'preprocessing.StandardScaler', ([], {}), '()\n', (2913, 2915), False, 'from sklearn import preprocessing\n'), ((2929, 2949), 'os.listdir', 'os.listdir', (['filepath'], {}), '(filepath)\n', (2939, 2949), False, 'import os\n'), ((3152, 3174), 'pandas.concat', 'pd.concat', (['all'], {'axis': '(1)'}), '(all, axis=1)\n', (3161, 3174), True, 'import pandas as pd\n'), ((3408, 3429), 'numpy.vstack', 'np.vstack', (['all.values'], {}), '(all.values)\n', (3417, 3429), True, 'import numpy as np\n'), ((3442, 3462), 'numpy.nan_to_num', 'np.nan_to_num', (['xdata'], {}), '(xdata)\n', (3455, 3462), True, 'import numpy as np\n'), ((8173, 8185), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (8183, 8185), False, 'from keras.models import Sequential\n'), ((8701, 8710), 'keras.optimizers.RMSprop', 'RMSprop', ([], {}), '()\n', (8708, 8710), False, 'from keras.optimizers import RMSprop, Adam\n'), ((8722, 8728), 'keras.optimizers.Adam', 'Adam', ([], {}), '()\n', (8726, 8728), False, 'from keras.optimizers import RMSprop, Adam\n'), ((8793, 8815), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (8813, 8815), False, 'import random, timeit\n'), ((13413, 13425), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13423, 13425), True, 'from matplotlib import pyplot as plt\n'), ((13430, 13450), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(1)', '(1)'], {}), '(3, 1, 1)\n', (13441, 13450), True, 'from matplotlib import pyplot as plt\n'), ((13475, 13495), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(1)', '(2)'], {}), '(3, 1, 2)\n', (13486, 13495), True, 'from matplotlib import pyplot as plt\n'), ((13528, 13548), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(1)', '(3)'], {}), '(3, 1, 3)\n', (13539, 13548), True, 'from matplotlib import pyplot as plt\n'), ((13553, 13580), 'matplotlib.pyplot.plot', 'plt.plot', (['learning_progress'], {}), '(learning_progress)\n', (13561, 13580), True, 'from matplotlib import pyplot as plt\n'), ((13626, 13717), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('plt/knapsack_summary' + '.png')"], {'bbox_inches': '"""tight"""', 'pad_inches': '(1)', 'dpi': '(72)'}), "('plt/knapsack_summary' + '.png', bbox_inches='tight',\n pad_inches=1, dpi=72)\n", (13637, 13717), True, 'from matplotlib import pyplot as plt\n'), ((13718, 13728), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13726, 13728), True, 'from matplotlib import pyplot as plt\n'), ((2970, 2995), 'os.path.join', 'os.path.join', (['filepath', 'f'], {}), '(filepath, f)\n', (2982, 2995), False, 'import os\n'), ((3502, 3532), 'sklearn.preprocessing.StandardScaler', 'preprocessing.StandardScaler', ([], {}), '()\n', (3530, 3532), False, 'from sklearn import preprocessing\n'), ((3609, 3647), 'sklearn.externals.joblib.dump', 'joblib.dump', (['scaler', '"""data/scaler.pkl"""'], {}), "(scaler, 'data/scaler.pkl')\n", (3620, 3647), False, 'from sklearn.externals import joblib\n'), ((3675, 3705), 'sklearn.externals.joblib.load', 'joblib.load', (['"""data/scaler.pkl"""'], {}), "('data/scaler.pkl')\n", (3686, 3705), False, 'from sklearn.externals import joblib\n'), ((5729, 5756), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 16)'}), '(figsize=(9, 16))\n', (5739, 5756), True, 'from matplotlib import pyplot as plt\n'), ((5789, 5838), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(400)', 'color': '"""black"""', 'linestyle': '"""--"""'}), "(x=400, color='black', linestyle='--')\n", (5800, 5838), True, 'from matplotlib import pyplot as plt\n'), ((5847, 5882), 'matplotlib.pyplot.text', 'plt.text', (['(250)', '(400)', '"""training data"""'], {}), "(250, 400, 'training data')\n", (5855, 5882), True, 'from matplotlib import pyplot as plt\n'), ((5891, 5922), 'matplotlib.pyplot.text', 'plt.text', (['(450)', '(400)', '"""test data"""'], {}), "(450, 400, 'test data')\n", (5899, 5922), True, 'from matplotlib import pyplot as plt\n'), ((6028, 6044), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (6037, 6044), True, 'from matplotlib import pyplot as plt\n'), ((7297, 7312), 'numpy.argmax', 'np.argmax', (['qval'], {}), '(qval)\n', (7306, 7312), True, 'import numpy as np\n'), ((8200, 8278), 'keras.layers.recurrent.LSTM', 'LSTM', (['(64)'], {'input_shape': '(1, num_features)', 'return_sequences': '(True)', 'stateful': '(False)'}), '(64, input_shape=(1, num_features), return_sequences=True, stateful=False)\n', (8204, 8278), False, 'from keras.layers.recurrent import LSTM\n'), ((8351, 8363), 'keras.layers.core.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (8358, 8363), False, 'from keras.layers.core import Dense, Dropout, Activation\n'), ((8380, 8459), 'keras.layers.recurrent.LSTM', 'LSTM', (['(64)'], {'input_shape': '(1, num_features)', 'return_sequences': '(False)', 'stateful': '(False)'}), '(64, input_shape=(1, num_features), return_sequences=False, stateful=False)\n', (8384, 8459), False, 'from keras.layers.recurrent import LSTM\n'), ((8532, 8544), 'keras.layers.core.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (8539, 8544), False, 'from keras.layers.core import Dense, Dropout, Activation\n'), ((8561, 8591), 'keras.layers.core.Dense', 'Dense', (['(4)'], {'init': '"""lecun_uniform"""'}), "(4, init='lecun_uniform')\n", (8566, 8591), False, 'from keras.layers.core import Dense, Dropout, Activation\n'), ((8607, 8627), 'keras.layers.core.Activation', 'Activation', (['"""linear"""'], {}), "('linear')\n", (8617, 8627), False, 'from keras.layers.core import Dense, Dropout, Activation\n'), ((13073, 13120), 'pandas.Series', 'pd.Series', ([], {'data': '[x[0] for x in test_price_data]'}), '(data=[x[0] for x in test_price_data])\n', (13082, 13120), True, 'import pandas as pd\n'), ((1301, 1318), 'pandas.read_csv', 'pd.read_csv', (['file'], {}), '(file)\n', (1312, 1318), True, 'import pandas as pd\n'), ((5396, 5493), 'numpy.max', 'np.max', (["((bt.data['price'].iloc[-1] - bt.data['price'].iloc[-2]) * bt.data['shares'\n ].iloc[-1])"], {}), "((bt.data['price'].iloc[-1] - bt.data['price'].iloc[-2]) * bt.data[\n 'shares'].iloc[-1])\n", (5402, 5493), True, 'import numpy as np\n'), ((5593, 5657), 'pandas.Series', 'pd.Series', ([], {'data': '[x[0] for x in xdata]', 'index': 'signal.index.values'}), '(data=[x[0] for x in xdata], index=signal.index.values)\n', (5602, 5657), True, 'import pandas as pd\n'), ((12959, 12981), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (12979, 12981), False, 'import random, timeit\n'), ((13376, 13404), 'numpy.asarray', 'np.asarray', (['(unique, counts)'], {}), '((unique, counts))\n', (13386, 13404), True, 'import numpy as np\n'), ((5179, 5298), 'pandas.Series', 'pd.Series', ([], {'data': '[x[0] for x in xdata[time_step - 2:time_step]]', 'index': 'signal[time_step - 2:time_step].index.values'}), '(data=[x[0] for x in xdata[time_step - 2:time_step]], index=signal\n [time_step - 2:time_step].index.values)\n', (5188, 5298), True, 'import pandas as pd\n'), ((10017, 10032), 'random.random', 'random.random', ([], {}), '()\n', (10030, 10032), False, 'import random, timeit\n'), ((10094, 10117), 'numpy.random.randint', 'np.random.randint', (['(0)', '(4)'], {}), '(0, 4)\n', (10111, 10117), True, 'import numpy as np\n'), ((10234, 10249), 'numpy.argmax', 'np.argmax', (['qval'], {}), '(qval)\n', (10243, 10249), True, 'import numpy as np\n'), ((11183, 11215), 'random.sample', 'random.sample', (['replay', 'batchSize'], {}), '(replay, batchSize)\n', (11196, 11215), False, 'import random, timeit\n'), ((12294, 12311), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (12302, 12311), True, 'import numpy as np\n'), ((11600, 11612), 'numpy.max', 'np.max', (['newQ'], {}), '(newQ)\n', (11606, 11612), True, 'import numpy as np\n'), ((11637, 11653), 'numpy.zeros', 'np.zeros', (['(1, 4)'], {}), '((1, 4))\n', (11645, 11653), True, 'import numpy as np\n'), ((12239, 12256), 'numpy.array', 'np.array', (['X_train'], {}), '(X_train)\n', (12247, 12256), True, 'import numpy as np\n')]
bask0/q10hybrid
experiments/experiment_01.py
9b18af9dd382c65dd667139f97e7da0241091a2c
import pytorch_lightning as pl import optuna import xarray as xr from pytorch_lightning.callbacks.early_stopping import EarlyStopping from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint import os import shutil from argparse import ArgumentParser from datetime import datetime from project.fluxdata import FluxData from models.hybrid import Q10Model # Hardcoded `Trainer` args. Note that these cannot be passed via cli. TRAINER_ARGS = dict( max_epochs=100, log_every_n_steps=1, weights_summary=None ) class Objective(object): def __init__(self, args): self.args = args def __call__(self, trial: optuna.trial.Trial) -> float: q10_init = trial.suggest_float('q10_init', 0.0001, 1000.) seed = trial.suggest_int('seed', 0, 999999999999) use_ta = trial.suggest_categorical('use_ta', [True, False]) dropout = trial.suggest_float('dropout', 0.0, 1.0) if use_ta: features = ['sw_pot', 'dsw_pot', 'ta'] else: features = ['sw_pot', 'dsw_pot'] pl.seed_everything(seed) # Further variables used in the hybrid model. physical = ['ta'] # Target (multiple targets not possible currently). targets = ['reco'] # Find variables that are only needed in physical model but not in NN. physical_exclusive = [v for v in physical if v not in features] # ------------ # data # ------------ ds = xr.open_dataset(self.args.data_path) fluxdata = FluxData( ds, features=features + physical_exclusive, targets=targets, context_size=1, train_time=slice('2003-01-01', '2006-12-31'), valid_time=slice('2007-01-01', '2007-12-31'), test_time=slice('2008-01-01', '2008-12-31'), batch_size=self.args.batch_size, data_loader_kwargs={'num_workers': 4}) train_loader = fluxdata.train_dataloader() val_loader = fluxdata.val_dataloader() test_loader = fluxdata.test_dataloader() # Create empty xr.Dataset, will be used by the model to save predictions every epoch. max_epochs = TRAINER_ARGS['max_epochs'] ds_pred = fluxdata.target_xr('valid', varnames=['reco', 'rb'], num_epochs=max_epochs) # ------------ # model # ------------ model = Q10Model( features=features, targets=targets, norm=fluxdata._norm, ds=ds_pred, q10_init=q10_init, hidden_dim=self.args.hidden_dim, num_layers=self.args.num_layers, learning_rate=self.args.learning_rate, dropout=dropout, weight_decay=self.args.weight_decay, num_steps=len(train_loader) * max_epochs) # ------------ # training # ------------ trainer = pl.Trainer.from_argparse_args( self.args, default_root_dir=self.args.log_dir, **TRAINER_ARGS, callbacks=[ EarlyStopping( monitor='valid_loss', patience=10, min_delta=0.00001), ModelCheckpoint( filename='{epoch}-{val_loss:.2f}', save_top_k=1, verbose=False, monitor='valid_loss', mode='min', prefix=model.__class__.__name__) ]) trainer.fit(model, train_loader, val_loader) # ------------ # testing # ------------ # trainer.test(test_dataloaders=test_loader) # ------------ # save results # ------------ # Store predictions. ds = fluxdata.add_scalar_record(model.ds, varname='q10', x=model.q10_history) trial.set_user_attr('q10', ds.q10[-1].item()) # Add some attributes that are required for analysis. ds.attrs = { 'created': datetime.now().strftime("%Y-%m-%d %H:%M:%S"), 'author': '[email protected]', 'q10_init': q10_init, 'dropout': dropout, 'use_ta': int(use_ta), 'loss': trainer.callback_metrics['valid_loss'].item() } ds = ds.isel(epoch=slice(0, trainer.current_epoch + 1)) # Save data. save_dir = os.path.join(model.logger.log_dir, 'predictions.nc') print(f'Saving predictions to: {save_dir}') ds.to_netcdf(save_dir) return trainer.callback_metrics['valid_loss'].item() @staticmethod def add_project_specific_args(parent_parser: ArgumentParser) -> ArgumentParser: parser = ArgumentParser(parents=[parent_parser], add_help=False) parser.add_argument( '--batch_size', default=240, type=int) parser.add_argument( '--data_path', default='./data/Synthetic4BookChap.nc', type=str) parser.add_argument( '--log_dir', default='./logs/experiment_01/', type=str) return parser def main(parser: ArgumentParser = None, **kwargs): """Use kwargs to overload argparse args.""" # ------------ # args # ------------ if parser is None: parser = ArgumentParser() parser = Objective.add_project_specific_args(parser) parser = pl.Trainer.add_argparse_args(parser) parser = Q10Model.add_model_specific_args(parser) parser.add_argument('--create_study', action='store_true', help='create new study (deletes old) and exits') parser.add_argument('--single_seed', action='store_true', help='use only one seed instead of (1, ..., 10).') args = parser.parse_args() globargs = TRAINER_ARGS.copy() globargs.update(kwargs) for k, v in globargs.items(): setattr(args, k, v) # ------------ # study setup # ------------ search_space = { 'q10_init': [0.5, 1.5, 2.5], 'seed': [0] if args.single_seed else [i for i in range(10)], 'dropout': [0.0, 0.2, 0.4, 0.6], 'use_ta': [True, False] } sql_file = os.path.abspath(os.path.join(args.log_dir, "optuna.db")) sql_path = f'sqlite:///{sql_file}' if args.create_study | (not os.path.isfile(sql_file)): if os.path.isdir(args.log_dir): shutil.rmtree(args.log_dir) os.makedirs(args.log_dir, exist_ok=True) study = optuna.create_study( study_name="q10hybrid", storage=sql_path, sampler=optuna.samplers.GridSampler(search_space), direction='minimize', load_if_exists=False) if args.create_study: return None if not os.path.isdir(args.log_dir): os.makedirs(args.log_dir) # ------------ # run study # ------------ n_trials = 1 for _, v in search_space.items(): n_trials *= len(v) study = optuna.load_study( study_name="q10hybrid", storage=sql_path, sampler=optuna.samplers.GridSampler(search_space)) study.optimize(Objective(args), n_trials=n_trials) if __name__ == '__main__': main()
[((5383, 5419), 'pytorch_lightning.Trainer.add_argparse_args', 'pl.Trainer.add_argparse_args', (['parser'], {}), '(parser)\n', (5411, 5419), True, 'import pytorch_lightning as pl\n'), ((5433, 5473), 'models.hybrid.Q10Model.add_model_specific_args', 'Q10Model.add_model_specific_args', (['parser'], {}), '(parser)\n', (5465, 5473), False, 'from models.hybrid import Q10Model\n'), ((1071, 1095), 'pytorch_lightning.seed_everything', 'pl.seed_everything', (['seed'], {}), '(seed)\n', (1089, 1095), True, 'import pytorch_lightning as pl\n'), ((1492, 1528), 'xarray.open_dataset', 'xr.open_dataset', (['self.args.data_path'], {}), '(self.args.data_path)\n', (1507, 1528), True, 'import xarray as xr\n'), ((4425, 4477), 'os.path.join', 'os.path.join', (['model.logger.log_dir', '"""predictions.nc"""'], {}), "(model.logger.log_dir, 'predictions.nc')\n", (4437, 4477), False, 'import os\n'), ((4743, 4798), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'parents': '[parent_parser]', 'add_help': '(False)'}), '(parents=[parent_parser], add_help=False)\n', (4757, 4798), False, 'from argparse import ArgumentParser\n'), ((5295, 5311), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (5309, 5311), False, 'from argparse import ArgumentParser\n'), ((6152, 6191), 'os.path.join', 'os.path.join', (['args.log_dir', '"""optuna.db"""'], {}), "(args.log_dir, 'optuna.db')\n", (6164, 6191), False, 'import os\n'), ((6303, 6330), 'os.path.isdir', 'os.path.isdir', (['args.log_dir'], {}), '(args.log_dir)\n', (6316, 6330), False, 'import os\n'), ((6380, 6420), 'os.makedirs', 'os.makedirs', (['args.log_dir'], {'exist_ok': '(True)'}), '(args.log_dir, exist_ok=True)\n', (6391, 6420), False, 'import os\n'), ((6722, 6749), 'os.path.isdir', 'os.path.isdir', (['args.log_dir'], {}), '(args.log_dir)\n', (6735, 6749), False, 'import os\n'), ((6759, 6784), 'os.makedirs', 'os.makedirs', (['args.log_dir'], {}), '(args.log_dir)\n', (6770, 6784), False, 'import os\n'), ((6265, 6289), 'os.path.isfile', 'os.path.isfile', (['sql_file'], {}), '(sql_file)\n', (6279, 6289), False, 'import os\n'), ((6344, 6371), 'shutil.rmtree', 'shutil.rmtree', (['args.log_dir'], {}), '(args.log_dir)\n', (6357, 6371), False, 'import shutil\n'), ((7027, 7068), 'optuna.samplers.GridSampler', 'optuna.samplers.GridSampler', (['search_space'], {}), '(search_space)\n', (7054, 7068), False, 'import optuna\n'), ((6544, 6585), 'optuna.samplers.GridSampler', 'optuna.samplers.GridSampler', (['search_space'], {}), '(search_space)\n', (6571, 6585), False, 'import optuna\n'), ((3102, 3167), 'pytorch_lightning.callbacks.early_stopping.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""valid_loss"""', 'patience': '(10)', 'min_delta': '(1e-05)'}), "(monitor='valid_loss', patience=10, min_delta=1e-05)\n", (3115, 3167), False, 'from pytorch_lightning.callbacks.early_stopping import EarlyStopping\n'), ((3248, 3399), 'pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint', 'ModelCheckpoint', ([], {'filename': '"""{epoch}-{val_loss:.2f}"""', 'save_top_k': '(1)', 'verbose': '(False)', 'monitor': '"""valid_loss"""', 'mode': '"""min"""', 'prefix': 'model.__class__.__name__'}), "(filename='{epoch}-{val_loss:.2f}', save_top_k=1, verbose=\n False, monitor='valid_loss', mode='min', prefix=model.__class__.__name__)\n", (3263, 3399), False, 'from pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint\n'), ((4048, 4062), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4060, 4062), False, 'from datetime import datetime\n')]
warifp/InstagramPostAndDelete
main.py
d22577325eccf42e629cef076ab43f7788587bc4
#! @@Author : WAHYU ARIF PURNOMO #! @@Create : 18 Januari 2019 #! @@Modify : 19 Januari 2019 #! Gambar dari reddit. #! Gunakan VPN karena DNS situs reddit sudah di blokir dari negara Indonesia. import os import json import requests import progressbar from PIL import Image from lxml import html from time import sleep from ImageDeleter import delete_png from InstagramAPI import InstagramAPI InstagramAPI = InstagramAPI(input("Username: "), input("Password: ")) while True: if (InstagramAPI.login()): break else: for x in range(300): os.system('cls') print(300-x) sleep(1) global useable useable = [] os.system('pause') def get_image(): print("Memulai mendapatkan gambar ..") json_raw = requests.get('https://www.reddit.com/r/me_irl/new/.json', headers = {'User-agent': 'Image_Testing_V3'}).json() json_data = json_raw['data'] json_children = json_data['children'] for x in range(len(json_children)): json_current = json_children[x] json_current_data = json_current['data'] json_current_url = json_current_data['url'] if "https://i.redd.it/" not in json_current_url: pass else: if json_current_url not in useable: useable.append(json_current_url) download() else: pass def download(): print("Memulai download ..") global filename new_filename = "" filename = useable[-1] filename = filename.replace("https://i.redd.it/", "") print(filename) f = open(filename, 'wb') f.write(requests.get(useable[-1]).content) f.close() if (filename[-3] + filename[-2] + filename[-1]) != 'jpg': im = Image.open(filename) for x in range(len(filename)-3): new_filename = new_filename + filename[x] im = im.convert("RGB") im.save("edit" + new_filename + 'jpg') new_filename = "edit" + new_filename + "jpg" print(new_filename) else: new_filename = filename upload(new_filename) def delete_image(bad_file): print("Memulai menghapus gambar ..") if (bad_file[0] + bad_file[1] + bad_file[2] + bad_file[3]) == "edit": png_bad_file = '' for x in range(len(bad_file)-3): png_bad_file = png_bad_file + bad_file[x] png_bad_file = png_bad_file + "png" try: os.remove(png_bad_file) except Exception as e: pass os.remove(bad_file) delete_png() print("Selesai.") wait() def upload(file): print("Memulai upload ..") caption = "" InstagramAPI.uploadPhoto(file, caption=caption) delete_image(file) def wait(): for i in progressbar.progressbar(range(1800)): sleep(1) while True: get_image() print("Gambar sukses di upload.") sleep(5) os.system('pause')
[((663, 681), 'os.system', 'os.system', (['"""pause"""'], {}), "('pause')\n", (672, 681), False, 'import os\n'), ((484, 504), 'InstagramAPI.InstagramAPI.login', 'InstagramAPI.login', ([], {}), '()\n', (502, 504), False, 'from InstagramAPI import InstagramAPI\n'), ((2490, 2509), 'os.remove', 'os.remove', (['bad_file'], {}), '(bad_file)\n', (2499, 2509), False, 'import os\n'), ((2514, 2526), 'ImageDeleter.delete_png', 'delete_png', ([], {}), '()\n', (2524, 2526), False, 'from ImageDeleter import delete_png\n'), ((2631, 2678), 'InstagramAPI.InstagramAPI.uploadPhoto', 'InstagramAPI.uploadPhoto', (['file'], {'caption': 'caption'}), '(file, caption=caption)\n', (2655, 2678), False, 'from InstagramAPI import InstagramAPI\n'), ((2854, 2862), 'time.sleep', 'sleep', (['(5)'], {}), '(5)\n', (2859, 2862), False, 'from time import sleep\n'), ((2867, 2885), 'os.system', 'os.system', (['"""pause"""'], {}), "('pause')\n", (2876, 2885), False, 'import os\n'), ((1738, 1758), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (1748, 1758), False, 'from PIL import Image\n'), ((2774, 2782), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (2779, 2782), False, 'from time import sleep\n'), ((572, 588), 'os.system', 'os.system', (['"""cls"""'], {}), "('cls')\n", (581, 588), False, 'import os\n'), ((626, 634), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (631, 634), False, 'from time import sleep\n'), ((758, 864), 'requests.get', 'requests.get', (['"""https://www.reddit.com/r/me_irl/new/.json"""'], {'headers': "{'User-agent': 'Image_Testing_V3'}"}), "('https://www.reddit.com/r/me_irl/new/.json', headers={\n 'User-agent': 'Image_Testing_V3'})\n", (770, 864), False, 'import requests\n'), ((1614, 1639), 'requests.get', 'requests.get', (['useable[-1]'], {}), '(useable[-1])\n', (1626, 1639), False, 'import requests\n'), ((2414, 2437), 'os.remove', 'os.remove', (['png_bad_file'], {}), '(png_bad_file)\n', (2423, 2437), False, 'import os\n')]
maximilionus/pyspectator-x
pyspectator/collection.py
1265f1f39e7ca0534f9e6ffcd7087f2ebced3397
from collections import MutableMapping, Container from datetime import datetime, timedelta from pyvalid import accepts class LimitedTimeTable(MutableMapping, Container): def __init__(self, time_span): self.__storage = dict() self.__time_span = None self.time_span = time_span @property def time_span(self): return self.__time_span @time_span.setter @accepts(object, timedelta) def time_span(self, value): self.__time_span = value @property def oldest(self): value = None if self.__len__() > 0: value = min(self.__storage.keys()) return value @property def newest(self): value = None if self.__len__() > 0: value = max(self.__storage.keys()) return value def oldest_keys(self, size): for key in self.__get_slice(0, size): yield key def oldest_values(self, size): for key in self.oldest_keys(size): yield self.__storage.get(key) def oldest_items(self, size): for key in self.oldest_keys(size): yield (key, self.__storage.get(key)) def newest_keys(self, size): for key in self.__get_slice(-size, None): yield key def newest_values(self, size): for key in self.newest_keys(size): yield self.__storage.get(key) def newest_items(self, size): for key in self.newest_keys(size): yield (key, self.__storage.get(key)) def __get_slice(self, start, end): keys = sorted(self.keys()) return keys[start:end] def __getitem__(self, item): return self.__storage.__getitem__(item) @accepts(object, datetime, object) def __setitem__(self, key, value): now = datetime.now() if key > now: raise ValueError('Can\'t set item from future!') oldest = self.oldest if (oldest is not None) and (oldest != key): longest_time_span = now - oldest # Item is too old for current timetable if longest_time_span >= self.time_span: self.__delitem__(oldest) return self.__storage.__setitem__(key, value) def __delitem__(self, key): return self.__storage.__delitem__(key) def __len__(self): return self.__storage.__len__() def __iter__(self): return self.__storage.__iter__() def __contains__(self, item): return self.__storage.__contains__(item) __all__ = ['LimitedTimeTable']
[((407, 433), 'pyvalid.accepts', 'accepts', (['object', 'timedelta'], {}), '(object, timedelta)\n', (414, 433), False, 'from pyvalid import accepts\n'), ((1711, 1744), 'pyvalid.accepts', 'accepts', (['object', 'datetime', 'object'], {}), '(object, datetime, object)\n', (1718, 1744), False, 'from pyvalid import accepts\n'), ((1798, 1812), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1810, 1812), False, 'from datetime import datetime, timedelta\n')]
AndySamoil/Elite_Code
keyboardrow.py
7dc3b7b1b8688c932474f8a10fd2637fd2918bdd
def findWords(self, words: List[str]) -> List[str]: ''' sets and iterate through sets ''' every = [set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")] ans = [] for word in words: l = len(word) for sett in every: count = 0 for let in word: if let.lower() in sett: count += 1 if count == l: ans.append(word) return ans
[]
xli1110/LC
DFS_Backtracking/31. Next Permutation.py
3c18b8809c5a21a62903060eef659654e0595036
class Solution: def __init__(self): self.res = [] self.path = [] def arr_to_num(self, arr): s = "" for x in arr: s += str(x) return int(s) def find_position(self, nums): for i in range(len(self.res)): if self.res[i] == nums: if i == len(self.res) - 1: return 0 # we need the check below for duplicate elements in nums # run nums = [1, 5, 1] and see the case next_num = self.arr_to_num(self.res[i + 1]) if next_num > self.arr_to_num(nums): return i + 1 raise Exception("The permutation function has something wrong, please debug it.") def DFS(self, arr): if not arr: self.res.append(self.path[:]) return for i in range(len(arr)): self.path.append(arr[i]) self.DFS(arr[:i] + arr[i + 1:]) self.path.pop() def nextPermutation(self, nums: [int]) -> None: """ Do not return anything, modify nums in-place instead. """ if not nums: raise Exception("Empty Array") # all permutations # note that we need to SORT the array at first arr = nums[:] arr.sort() self.DFS(arr) # find position position = self.find_position(nums) # in-place replacement for i in range(len(nums)): nums[i] = self.res[position][i] if __name__ == "__main__": sol = Solution() # nums = [2, 1, 3] nums = [1, 5, 1] sol.nextPermutation(nums) print(sol.res)
[]
konradotto/TS
plugin/DataExport/extend.py
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
#!/usr/bin/python # Copyright (C) 2015 Ion Torrent Systems, Inc. All Rights Reserved import subprocess import re pluginName = 'DataExport' pluginDir = "" networkFS = ["nfs", "cifs"] localFS = ["ext4", "ext3", "xfs", "ntfs", "exfat", "vboxsf"] supportedFS = ",".join(localFS + networkFS) def test(bucket): return bucket def runProcess(exe): p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return iter(p.stdout.readline, b'') def runProcessAndReturnLastLine(exe): p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return p.stdout.readlines()[-1] def backupDevices(bucket): devices = "" cmd = "mount -l -t " + supportedFS for line in runProcess(cmd.split()): line_arr = line.split() folder = line_arr[2] fstype = line_arr[4] perms = line_arr[5] if perms.find('w') != -1: use = True if fstype in localFS: m = re.match('^(/media|/mnt)', folder) if not m: use = False if use: cmd2 = "df -h %s " % folder df = runProcessAndReturnLastLine(cmd2.split()) avail = df.split()[2] devices = devices + "<OPTION VALUE=\"" + folder + "\">" + folder + " (" + avail + " free, " + fstype + ")</option>" return devices
[((359, 430), 'subprocess.Popen', 'subprocess.Popen', (['exe'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), '(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n', (375, 430), False, 'import subprocess\n'), ((519, 590), 'subprocess.Popen', 'subprocess.Popen', (['exe'], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), '(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n', (535, 590), False, 'import subprocess\n'), ((982, 1016), 're.match', 're.match', (['"""^(/media|/mnt)"""', 'folder'], {}), "('^(/media|/mnt)', folder)\n", (990, 1016), False, 'import re\n')]
PaulAustin/sb7-pgz
boids/biods_object.py
fca3e50132b9d1894fb348b2082e83ce7b937b19
# Ported from JavaSript version to Python and Pygame Zero # Designed to work well with mu-editor environment. # # The original Javascript version wasdonw by Ben Eater # at https://github.com/beneater/boids (MIT License) # No endorsement implied. # # Complex numbers are are used as vectors to integrate x and y positions and velocities # MIT licesense (details in parent directory) import random import time HEIGHT = 500 # window height WIDTH = 900 # window width MARGIN = 150 # disstance to start avoid edge NUM_BOIDS = 75 VISUAL_RANGE = 70 # radius of influence for most algoriths SPEED_LIMIT_UPPER = 13 # boids canonly fly so fast. SPEED_LIMIT_LOWER = 3 # boid will fall if flying too slow SPEED_INIT = 20 # range for random velocity MIN_DISTANCE = 10 # the distance to stay away from other boids AVOID_FACTOR = 0.05 # % location change if too close CENTERING_FACTOR = 0.050 # % location change to pull to center MATCHING_FACTOR = 0.015 # % velocity change if close MARGIN_FACTOR = 0.25+0.0j # rate of turning away from edge HISTORY_LENGTH = 30 BACK_COLOR = (0, 0, 90) BOID_COLOR = (255, 128, 128) BOID_SIZE = 8 TRAIL_COLOR = (255, 255, 64) g_boids = [] class Boid: def __init__(boid) : boid.loc = complex( (random.randint(0, WIDTH)), (random.randint(0, HEIGHT))) boid.vel = complex( (random.randint(-SPEED_INIT, SPEED_INIT)), (random.randint(-SPEED_INIT, SPEED_INIT))) boid.history = [] def keep_within_bounds(boid) : # Constrain a boid to within the window. If it gets too close to an edge, # nudge it back in and reverse its direction. if (boid.loc.real < MARGIN): boid.vel += MARGIN_FACTOR * 1.0 if (boid.loc.real > WIDTH - MARGIN) : boid.vel += MARGIN_FACTOR * -1.0 if (boid.loc.imag < MARGIN) : boid.vel += MARGIN_FACTOR * 1.0j if (boid.loc.imag > HEIGHT - MARGIN) : boid.vel += MARGIN_FACTOR * -1.0j def fly_towards_center(boid): # Find the center of mass of the other boids and # adjust velocity slightly to point towards the # center of mass. center = 0+0j num_neighbors = 0 for other_boid in g_boids : if abs(boid.loc - other_boid.loc) < VISUAL_RANGE : center += other_boid.loc num_neighbors += 1 if num_neighbors > 0 : center = center / num_neighbors boid.loc += (center - boid.loc) * CENTERING_FACTOR def avoid_others(boid): # Move away from other boids that are too close to avoid colliding move = 0+0j for other_boid in g_boids : if not (other_boid is boid) : if abs(boid.loc - other_boid.loc) < MIN_DISTANCE : move += boid.loc - other_boid.loc boid.vel += move * AVOID_FACTOR def match_velocity(boid): # Find the average velocity (speed and direction) # of the other boids and adjust velocity slightly to match. avg_vel = 0+0j num_neighbors = 0 for otherBoid in g_boids: if abs(boid.loc - otherBoid.loc) < VISUAL_RANGE : avg_vel += otherBoid.vel num_neighbors += 1 if num_neighbors > 0: avg_vel /= num_neighbors boid.vel += (avg_vel - boid.vel) * MATCHING_FACTOR def limit_speed(boid): # Speed will naturally vary in flocking behavior, # but real animals can't go arbitrarily fast (or slow) speed = abs(boid.vel) if (speed > SPEED_LIMIT_UPPER) : boid.vel = boid.vel / speed * SPEED_LIMIT_UPPER if (speed < SPEED_LIMIT_LOWER) : boid.vel = boid.vel / speed * SPEED_LIMIT_LOWER return def draw(boid): screen.draw.filled_circle((boid.loc.real, boid.loc.imag), BOID_SIZE, BOID_COLOR) tail = boid.loc + boid.vel * -1.8 screen.draw.line( (boid.loc.real, boid.loc.imag), (tail.real, tail.imag), BOID_COLOR) def draw_trail(boid): pt_from = (boid.loc.real, boid.loc.imag) for p in boid.history: pt_to = (p.real, p.imag) screen.draw.line(pt_from, pt_to, TRAIL_COLOR) pt_from = pt_to def draw(): screen.fill(BACK_COLOR) if keyboard.space: for boid in g_boids: boid.draw_trail() for boid in g_boids: boid.draw() screen.draw.text("space:tails r:restart", (20, 20)) def update(): for boid in g_boids: # Apply rules boid.fly_towards_center() boid.avoid_others() boid.match_velocity() boid.limit_speed() boid.keep_within_bounds() # Update the position based on the current velocity boid.loc += boid.vel boid.history.insert(0, boid.loc) boid.history = boid.history[:HISTORY_LENGTH] def init(): global g_boids g_boids = [Boid() for _ in range(NUM_BOIDS)] def on_key_down(key, mod, unicode): if (key == keys.R): init() init()
[((1349, 1373), 'random.randint', 'random.randint', (['(0)', 'WIDTH'], {}), '(0, WIDTH)\n', (1363, 1373), False, 'import random\n'), ((1389, 1414), 'random.randint', 'random.randint', (['(0)', 'HEIGHT'], {}), '(0, HEIGHT)\n', (1403, 1414), False, 'import random\n'), ((1458, 1497), 'random.randint', 'random.randint', (['(-SPEED_INIT)', 'SPEED_INIT'], {}), '(-SPEED_INIT, SPEED_INIT)\n', (1472, 1497), False, 'import random\n'), ((1513, 1552), 'random.randint', 'random.randint', (['(-SPEED_INIT)', 'SPEED_INIT'], {}), '(-SPEED_INIT, SPEED_INIT)\n', (1527, 1552), False, 'import random\n')]
UpOut/UpOutDF
upoutdf/types/recurring/yearly.py
5d2f87884565d98b77e25c6a26af7dbea266be76
# coding: utf-8 import pytz from dateutil.relativedelta import relativedelta from .base import BaseRecurring from upoutdf.occurences import OccurenceBlock, OccurenceGroup from upoutdf.constants import YEARLY_TYPE class YearlyType(BaseRecurring): year_day = None required_attributes = [ 'every', 'timezone', 'starting_time', 'lasting_seconds', 'type', 'starting_date' ] def increment_by(self): return relativedelta(years=+self.every) def _snap_datetime(self,datetime,yearday): if datetime is None: return None snapper = self.snapping_class(self.timezone) return snapper.snap_to_year_day(datetime,yearday) def _canonicalize_date(self,date): if not date.tzinfo: date = date.replace(tzinfo=pytz.utc) if date.tzinfo != self.timezone: date = self.timezone.normalize(date.astimezone(self.timezone)) return date def canonicalize(self): canonical = "every %s year" % self.every if self.year_day is not None: canonical = "%s day %s" % ( canonical, self.year_day ) #(starting <datetimestring>) (ending <datetimestring>) if not self.starting_date_infinite: starting_date = self._canonicalize_date(self.starting_date) canonical = "%s starting %s" % ( canonical, starting_date.strftime("_%m/%d/%Y") ) if not self.ending_date_infinite: ending_date = self._canonicalize_date(self.ending_date) canonical = "%s ending %s" % ( canonical, ending_date.strftime("_%m/%d/%Y") ) if self.repeating_count is not None: canonical = "%s repeating %s times" % ( canonical, self.repeating_count ) starting_time = self._canonicalize_date(self.starting_time) canonical = "%s at %s" % ( canonical, starting_time.strftime("%-I:%M%p") ) canonical = "%s lasting %s seconds in %s" % ( canonical, self.lasting_seconds, str(self.timezone) ) return canonical def occurences(self): if not self.verify_parsed(): raise RuntimeError("Please call parse before calling occurences") ending = self.ending_date repeating_count = self.repeating_count ending_date_infinite = self.ending_date_infinite if repeating_count is not None: ending_date_infinite = False if ending is not None: ending = self._set_start_time(ending) ending = self._strip_microseconds(ending) occurence_start = self.starting_date if self.year_day is not None: try: occurence_start = self._snap_datetime(self.starting_date,self.year_day) except ValueError: #If we had a problem, try the next year occurence_start = self._snap_datetime( self.starting_date+relativedelta(years=+1), self.year_day ) occurence_start = self._set_start_time(occurence_start) occurence_start = self._strip_microseconds(occurence_start) occurence_block = OccurenceBlock( starting_date=occurence_start, ending_date=None, starting_date_infinite=self.starting_date_infinite, ending_date_infinite=ending_date_infinite, typeobj=self ) repeated = 1 occurence_end = None #While we're before the end date (if we have it) #And we're before the max repetetions (if we have it) while ((ending is None or occurence_start <= ending) and (repeating_count is None or repeated <= repeating_count)): occurence_end = self._get_end_datetime(occurence_start) occurence_end = self._strip_microseconds(occurence_end) occurence_block.add_occurence(occurence_start,occurence_end) occurence_start = self._increment_occurence(occurence_start) occurence_start = self._strip_microseconds(occurence_start) repeated+=1 occurence_block.ending_date = occurence_end #We always return a OccurenceGroup, even if just 1 return OccurenceGroup(blocks=[occurence_block]) def _parse_type(self,tokens): if tokens[0] == 'day': tokens = self._step_tokens(tokens) try: self.year_day = int(tokens[0]) except ValueError: raise ValueError("Invalid year day") tokens = self._step_tokens(tokens) self.type = YEARLY_TYPE return tokens
[((478, 510), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(+self.every)'}), '(years=+self.every)\n', (491, 510), False, 'from dateutil.relativedelta import relativedelta\n'), ((3441, 3621), 'upoutdf.occurences.OccurenceBlock', 'OccurenceBlock', ([], {'starting_date': 'occurence_start', 'ending_date': 'None', 'starting_date_infinite': 'self.starting_date_infinite', 'ending_date_infinite': 'ending_date_infinite', 'typeobj': 'self'}), '(starting_date=occurence_start, ending_date=None,\n starting_date_infinite=self.starting_date_infinite,\n ending_date_infinite=ending_date_infinite, typeobj=self)\n', (3455, 3621), False, 'from upoutdf.occurences import OccurenceBlock, OccurenceGroup\n'), ((4516, 4556), 'upoutdf.occurences.OccurenceGroup', 'OccurenceGroup', ([], {'blocks': '[occurence_block]'}), '(blocks=[occurence_block])\n', (4530, 4556), False, 'from upoutdf.occurences import OccurenceBlock, OccurenceGroup\n'), ((3204, 3227), 'dateutil.relativedelta.relativedelta', 'relativedelta', ([], {'years': '(+1)'}), '(years=+1)\n', (3217, 3227), False, 'from dateutil.relativedelta import relativedelta\n')]
dbinetti/captable
project/urls.py
29769b2b99a3185fda241b3087ccbe621f8c97a2
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView urlpatterns = patterns( '', url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^about/$', TemplateView.as_view(template_name='about.html'), name='about'), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^', include('apps.captable.urls',)), ) urlpatterns += staticfiles_urlpatterns()
[((86, 106), 'django.contrib.admin.autodiscover', 'admin.autodiscover', ([], {}), '()\n', (104, 106), False, 'from django.contrib import admin\n'), ((599, 624), 'django.contrib.staticfiles.urls.staticfiles_urlpatterns', 'staticfiles_urlpatterns', ([], {}), '()\n', (622, 624), False, 'from django.contrib.staticfiles.urls import staticfiles_urlpatterns\n'), ((271, 318), 'django.views.generic.TemplateView.as_view', 'TemplateView.as_view', ([], {'template_name': '"""home.html"""'}), "(template_name='home.html')\n", (291, 318), False, 'from django.views.generic import TemplateView\n'), ((355, 403), 'django.views.generic.TemplateView.as_view', 'TemplateView.as_view', ([], {'template_name': '"""about.html"""'}), "(template_name='about.html')\n", (375, 403), False, 'from django.views.generic import TemplateView\n'), ((444, 484), 'django.conf.urls.include', 'include', (['"""django.contrib.admindocs.urls"""'], {}), "('django.contrib.admindocs.urls')\n", (451, 484), False, 'from django.conf.urls import patterns, include, url\n'), ((507, 531), 'django.conf.urls.include', 'include', (['admin.site.urls'], {}), '(admin.site.urls)\n', (514, 531), False, 'from django.conf.urls import patterns, include, url\n'), ((548, 577), 'django.conf.urls.include', 'include', (['"""apps.captable.urls"""'], {}), "('apps.captable.urls')\n", (555, 577), False, 'from django.conf.urls import patterns, include, url\n')]
marjanhs/procon20
common/evaluators/bert_emotion_evaluator.py
c49ad38a77e58fd84ff0409cc9f5081c6de0bf0b
import warnings import numpy as np import torch import torch.nn.functional as F from sklearn import metrics from torch.utils.data import DataLoader, SequentialSampler, TensorDataset from tqdm import tqdm from datasets.bert_processors.abstract_processor import convert_examples_to_features_with_emotion, \ convert_examples_to_hierarchical_features from utils.preprocessing import pad_input_matrix from utils.tokenization import BertTokenizer from utils.emotion import Emotion # Suppress warnings from sklearn.metrics warnings.filterwarnings('ignore') class BertEvaluator(object): def __init__(self, model, processor, args, split='dev'): self.args = args self.model = model self.processor = processor self.tokenizer = BertTokenizer.from_pretrained(args.model, is_lowercase=args.is_lowercase) self.emotioner = Emotion(args.nrc_path, args.max_em_len, args.emotion_filters) if split == 'test': self.eval_examples = self.processor.get_test_examples(args.data_dir, args.test_name) elif split == 'dev': self.eval_examples = self.processor.get_dev_examples(args.data_dir, args.dev_name) else: self.eval_examples = self.processor.get_any_examples(args.data_dir, split) def get_scores(self, silent=False, return_indices=False): all_indices = [] if self.args.is_hierarchical: eval_features = convert_examples_to_hierarchical_features( self.eval_examples, self.args.max_seq_length, self.tokenizer) else: eval_features = convert_examples_to_features_with_emotion( self.eval_examples, self.args.max_seq_length, self.tokenizer, self.emotioner) unpadded_input_ids = [f.input_ids for f in eval_features] unpadded_input_mask = [f.input_mask for f in eval_features] unpadded_segment_ids = [f.segment_ids for f in eval_features] unpadded_emotion_scores = [f.sentiment_scores for f in eval_features] if self.args.is_hierarchical: pad_input_matrix(unpadded_input_ids, self.args.max_doc_length) pad_input_matrix(unpadded_input_mask, self.args.max_doc_length) pad_input_matrix(unpadded_segment_ids, self.args.max_doc_length) padded_input_ids = torch.tensor(unpadded_input_ids, dtype=torch.long) padded_input_mask = torch.tensor(unpadded_input_mask, dtype=torch.long) padded_segment_ids = torch.tensor(unpadded_segment_ids, dtype=torch.long) padded_emotion_ids = torch.tensor(unpadded_emotion_scores, dtype=torch.long) label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long) eval_data = TensorDataset(padded_input_ids, padded_input_mask, padded_segment_ids, padded_emotion_ids, label_ids) eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=self.args.batch_size) self.model.eval() total_loss = 0 nb_eval_steps, nb_eval_examples = 0, 0 predicted_labels, target_labels = list(), list() for input_ids, input_mask, segment_ids, emotion_ids, label_ids in tqdm(eval_dataloader, desc="Evaluating", disable=silent): input_ids = input_ids.to(self.args.device) input_mask = input_mask.to(self.args.device) segment_ids = segment_ids.to(self.args.device) emotion_ids = emotion_ids.to(self.args.device) label_ids = label_ids.to(self.args.device) with torch.no_grad(): if return_indices: outs = self.model(input_ids, segment_ids, input_mask, emotion_ids=emotion_ids, return_indices=return_indices) else: outs = self.model(input_ids, segment_ids, input_mask, emotion_ids=emotion_ids) if isinstance(outs, tuple): outs, _ = outs if return_indices: logits, indices = outs all_indices.extend(indices.cpu().detach().numpy()) else: logits = outs if self.args.is_multilabel: predicted_labels.extend(F.sigmoid(logits).round().long().cpu().detach().numpy()) target_labels.extend(label_ids.cpu().detach().numpy()) loss = F.binary_cross_entropy_with_logits(logits, label_ids.float(), size_average=False) average, average_mac = 'micro', 'macro' else: predicted_labels.extend(torch.argmax(logits, dim=1).cpu().detach().numpy()) target_labels.extend(torch.argmax(label_ids, dim=1).cpu().detach().numpy()) loss = F.cross_entropy(logits, torch.argmax(label_ids, dim=1)) average, average_mac = 'binary', 'binary' if self.args.n_gpu > 1: loss = loss.mean() if self.args.gradient_accumulation_steps > 1: loss = loss / self.args.gradient_accumulation_steps total_loss += loss.item() nb_eval_examples += input_ids.size(0) nb_eval_steps += 1 predicted_labels, target_labels = np.array(predicted_labels), np.array(target_labels) accuracy = metrics.accuracy_score(target_labels, predicted_labels) precision = metrics.precision_score(target_labels, predicted_labels, average=average) recall = metrics.recall_score(target_labels, predicted_labels, average=average) avg_loss = total_loss / nb_eval_steps hamming_loss = metrics.hamming_loss(target_labels, predicted_labels) jaccard_score = metrics.jaccard_score(target_labels, predicted_labels, average=average) f1_micro = metrics.f1_score(target_labels, predicted_labels, average=average) f1_macro = metrics.f1_score(target_labels, predicted_labels, average=average_mac) if return_indices: return [accuracy, precision, recall, f1_micro, avg_loss, f1_macro, hamming_loss, jaccard_score, predicted_labels, target_labels, all_indices],\ ['accuracy', 'precision', 'recall', 'f1_micro', 'avg_loss', 'f1_macro', 'hamming_loss', 'jaccard', 'predicted_labels', 'target_labels', 'all_indices'] else: return [accuracy, precision, recall, f1_micro, avg_loss, f1_macro, hamming_loss, jaccard_score, predicted_labels, target_labels],\ ['accuracy', 'precision', 'recall', 'f1_micro', 'avg_loss', 'f1_macro', 'hamming_loss', 'jaccard', 'predicted_labels', 'target_labels'] def get_bert_layers(self, silent=False, last_bert_layers=-1): if self.args.is_hierarchical: eval_features = convert_examples_to_hierarchical_features( self.eval_examples, self.args.max_seq_length, self.tokenizer) else: eval_features = convert_examples_to_features_with_emotion( self.eval_examples, self.args.max_seq_length, self.tokenizer, self.emotioner) unpadded_input_ids = [f.input_ids for f in eval_features] unpadded_input_mask = [f.input_mask for f in eval_features] unpadded_segment_ids = [f.segment_ids for f in eval_features] unpadded_emotion_ids = [f.emotioniment_scores for f in eval_features] if self.args.is_hierarchical: pad_input_matrix(unpadded_input_ids, self.args.max_doc_length) pad_input_matrix(unpadded_input_mask, self.args.max_doc_length) pad_input_matrix(unpadded_segment_ids, self.args.max_doc_length) padded_input_ids = torch.tensor(unpadded_input_ids, dtype=torch.long) padded_input_mask = torch.tensor(unpadded_input_mask, dtype=torch.long) padded_segment_ids = torch.tensor(unpadded_segment_ids, dtype=torch.long) padded_emotion_ids = torch.tensor(unpadded_emotion_ids, dtype=torch.long) label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long) eval_data = TensorDataset(padded_input_ids, padded_input_mask, padded_segment_ids, padded_emotion_ids, label_ids) eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=self.args.batch_size) self.model.eval() bert_layers_l, label_ids_l = [], [] for input_ids, input_mask, segment_ids, emotion_ids, label_ids in tqdm(eval_dataloader, desc="Evaluating", disable=silent): input_ids = input_ids.to(self.args.device) input_mask = input_mask.to(self.args.device) segment_ids = segment_ids.to(self.args.device) emotion_ids = emotion_ids.to(self.args.device) label_ids = label_ids.to(self.args.device) with torch.no_grad(): bert_layers = self.model.get_bert_embedding(input_ids, segment_ids, input_mask, emotion_ids=emotion_ids, last_bert_layers=last_bert_layers) label_ids = torch.argmax(label_ids, dim=1).cpu().detach().numpy() bert_layers_l.extend(bert_layers) label_ids_l.extend(label_ids) bert_layers_l = torch.stack(bert_layers_l, dim=0) return bert_layers_l, label_ids_l
[((539, 572), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (562, 572), False, 'import warnings\n'), ((785, 858), 'utils.tokenization.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['args.model'], {'is_lowercase': 'args.is_lowercase'}), '(args.model, is_lowercase=args.is_lowercase)\n', (814, 858), False, 'from utils.tokenization import BertTokenizer\n'), ((885, 946), 'utils.emotion.Emotion', 'Emotion', (['args.nrc_path', 'args.max_em_len', 'args.emotion_filters'], {}), '(args.nrc_path, args.max_em_len, args.emotion_filters)\n', (892, 946), False, 'from utils.emotion import Emotion\n'), ((2358, 2408), 'torch.tensor', 'torch.tensor', (['unpadded_input_ids'], {'dtype': 'torch.long'}), '(unpadded_input_ids, dtype=torch.long)\n', (2370, 2408), False, 'import torch\n'), ((2438, 2489), 'torch.tensor', 'torch.tensor', (['unpadded_input_mask'], {'dtype': 'torch.long'}), '(unpadded_input_mask, dtype=torch.long)\n', (2450, 2489), False, 'import torch\n'), ((2520, 2572), 'torch.tensor', 'torch.tensor', (['unpadded_segment_ids'], {'dtype': 'torch.long'}), '(unpadded_segment_ids, dtype=torch.long)\n', (2532, 2572), False, 'import torch\n'), ((2603, 2658), 'torch.tensor', 'torch.tensor', (['unpadded_emotion_scores'], {'dtype': 'torch.long'}), '(unpadded_emotion_scores, dtype=torch.long)\n', (2615, 2658), False, 'import torch\n'), ((2680, 2747), 'torch.tensor', 'torch.tensor', (['[f.label_id for f in eval_features]'], {'dtype': 'torch.long'}), '([f.label_id for f in eval_features], dtype=torch.long)\n', (2692, 2747), False, 'import torch\n'), ((2771, 2876), 'torch.utils.data.TensorDataset', 'TensorDataset', (['padded_input_ids', 'padded_input_mask', 'padded_segment_ids', 'padded_emotion_ids', 'label_ids'], {}), '(padded_input_ids, padded_input_mask, padded_segment_ids,\n padded_emotion_ids, label_ids)\n', (2784, 2876), False, 'from torch.utils.data import DataLoader, SequentialSampler, TensorDataset\n'), ((2897, 2925), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['eval_data'], {}), '(eval_data)\n', (2914, 2925), False, 'from torch.utils.data import DataLoader, SequentialSampler, TensorDataset\n'), ((2953, 3029), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_data'], {'sampler': 'eval_sampler', 'batch_size': 'self.args.batch_size'}), '(eval_data, sampler=eval_sampler, batch_size=self.args.batch_size)\n', (2963, 3029), False, 'from torch.utils.data import DataLoader, SequentialSampler, TensorDataset\n'), ((3268, 3324), 'tqdm.tqdm', 'tqdm', (['eval_dataloader'], {'desc': '"""Evaluating"""', 'disable': 'silent'}), "(eval_dataloader, desc='Evaluating', disable=silent)\n", (3272, 3324), False, 'from tqdm import tqdm\n'), ((5390, 5445), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['target_labels', 'predicted_labels'], {}), '(target_labels, predicted_labels)\n', (5412, 5445), False, 'from sklearn import metrics\n'), ((5467, 5540), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['target_labels', 'predicted_labels'], {'average': 'average'}), '(target_labels, predicted_labels, average=average)\n', (5490, 5540), False, 'from sklearn import metrics\n'), ((5559, 5629), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['target_labels', 'predicted_labels'], {'average': 'average'}), '(target_labels, predicted_labels, average=average)\n', (5579, 5629), False, 'from sklearn import metrics\n'), ((5703, 5756), 'sklearn.metrics.hamming_loss', 'metrics.hamming_loss', (['target_labels', 'predicted_labels'], {}), '(target_labels, predicted_labels)\n', (5723, 5756), False, 'from sklearn import metrics\n'), ((5782, 5853), 'sklearn.metrics.jaccard_score', 'metrics.jaccard_score', (['target_labels', 'predicted_labels'], {'average': 'average'}), '(target_labels, predicted_labels, average=average)\n', (5803, 5853), False, 'from sklearn import metrics\n'), ((5874, 5940), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['target_labels', 'predicted_labels'], {'average': 'average'}), '(target_labels, predicted_labels, average=average)\n', (5890, 5940), False, 'from sklearn import metrics\n'), ((5961, 6031), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['target_labels', 'predicted_labels'], {'average': 'average_mac'}), '(target_labels, predicted_labels, average=average_mac)\n', (5977, 6031), False, 'from sklearn import metrics\n'), ((7734, 7784), 'torch.tensor', 'torch.tensor', (['unpadded_input_ids'], {'dtype': 'torch.long'}), '(unpadded_input_ids, dtype=torch.long)\n', (7746, 7784), False, 'import torch\n'), ((7814, 7865), 'torch.tensor', 'torch.tensor', (['unpadded_input_mask'], {'dtype': 'torch.long'}), '(unpadded_input_mask, dtype=torch.long)\n', (7826, 7865), False, 'import torch\n'), ((7896, 7948), 'torch.tensor', 'torch.tensor', (['unpadded_segment_ids'], {'dtype': 'torch.long'}), '(unpadded_segment_ids, dtype=torch.long)\n', (7908, 7948), False, 'import torch\n'), ((7979, 8031), 'torch.tensor', 'torch.tensor', (['unpadded_emotion_ids'], {'dtype': 'torch.long'}), '(unpadded_emotion_ids, dtype=torch.long)\n', (7991, 8031), False, 'import torch\n'), ((8053, 8120), 'torch.tensor', 'torch.tensor', (['[f.label_id for f in eval_features]'], {'dtype': 'torch.long'}), '([f.label_id for f in eval_features], dtype=torch.long)\n', (8065, 8120), False, 'import torch\n'), ((8144, 8249), 'torch.utils.data.TensorDataset', 'TensorDataset', (['padded_input_ids', 'padded_input_mask', 'padded_segment_ids', 'padded_emotion_ids', 'label_ids'], {}), '(padded_input_ids, padded_input_mask, padded_segment_ids,\n padded_emotion_ids, label_ids)\n', (8157, 8249), False, 'from torch.utils.data import DataLoader, SequentialSampler, TensorDataset\n'), ((8270, 8298), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['eval_data'], {}), '(eval_data)\n', (8287, 8298), False, 'from torch.utils.data import DataLoader, SequentialSampler, TensorDataset\n'), ((8326, 8402), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_data'], {'sampler': 'eval_sampler', 'batch_size': 'self.args.batch_size'}), '(eval_data, sampler=eval_sampler, batch_size=self.args.batch_size)\n', (8336, 8402), False, 'from torch.utils.data import DataLoader, SequentialSampler, TensorDataset\n'), ((8556, 8612), 'tqdm.tqdm', 'tqdm', (['eval_dataloader'], {'desc': '"""Evaluating"""', 'disable': 'silent'}), "(eval_dataloader, desc='Evaluating', disable=silent)\n", (8560, 8612), False, 'from tqdm import tqdm\n'), ((9304, 9337), 'torch.stack', 'torch.stack', (['bert_layers_l'], {'dim': '(0)'}), '(bert_layers_l, dim=0)\n', (9315, 9337), False, 'import torch\n'), ((1462, 1570), 'datasets.bert_processors.abstract_processor.convert_examples_to_hierarchical_features', 'convert_examples_to_hierarchical_features', (['self.eval_examples', 'self.args.max_seq_length', 'self.tokenizer'], {}), '(self.eval_examples, self.args.\n max_seq_length, self.tokenizer)\n', (1503, 1570), False, 'from datasets.bert_processors.abstract_processor import convert_examples_to_features_with_emotion, convert_examples_to_hierarchical_features\n'), ((1628, 1752), 'datasets.bert_processors.abstract_processor.convert_examples_to_features_with_emotion', 'convert_examples_to_features_with_emotion', (['self.eval_examples', 'self.args.max_seq_length', 'self.tokenizer', 'self.emotioner'], {}), '(self.eval_examples, self.args.\n max_seq_length, self.tokenizer, self.emotioner)\n', (1669, 1752), False, 'from datasets.bert_processors.abstract_processor import convert_examples_to_features_with_emotion, convert_examples_to_hierarchical_features\n'), ((2110, 2172), 'utils.preprocessing.pad_input_matrix', 'pad_input_matrix', (['unpadded_input_ids', 'self.args.max_doc_length'], {}), '(unpadded_input_ids, self.args.max_doc_length)\n', (2126, 2172), False, 'from utils.preprocessing import pad_input_matrix\n'), ((2186, 2249), 'utils.preprocessing.pad_input_matrix', 'pad_input_matrix', (['unpadded_input_mask', 'self.args.max_doc_length'], {}), '(unpadded_input_mask, self.args.max_doc_length)\n', (2202, 2249), False, 'from utils.preprocessing import pad_input_matrix\n'), ((2263, 2327), 'utils.preprocessing.pad_input_matrix', 'pad_input_matrix', (['unpadded_segment_ids', 'self.args.max_doc_length'], {}), '(unpadded_segment_ids, self.args.max_doc_length)\n', (2279, 2327), False, 'from utils.preprocessing import pad_input_matrix\n'), ((5318, 5344), 'numpy.array', 'np.array', (['predicted_labels'], {}), '(predicted_labels)\n', (5326, 5344), True, 'import numpy as np\n'), ((5346, 5369), 'numpy.array', 'np.array', (['target_labels'], {}), '(target_labels)\n', (5354, 5369), True, 'import numpy as np\n'), ((6838, 6946), 'datasets.bert_processors.abstract_processor.convert_examples_to_hierarchical_features', 'convert_examples_to_hierarchical_features', (['self.eval_examples', 'self.args.max_seq_length', 'self.tokenizer'], {}), '(self.eval_examples, self.args.\n max_seq_length, self.tokenizer)\n', (6879, 6946), False, 'from datasets.bert_processors.abstract_processor import convert_examples_to_features_with_emotion, convert_examples_to_hierarchical_features\n'), ((7004, 7128), 'datasets.bert_processors.abstract_processor.convert_examples_to_features_with_emotion', 'convert_examples_to_features_with_emotion', (['self.eval_examples', 'self.args.max_seq_length', 'self.tokenizer', 'self.emotioner'], {}), '(self.eval_examples, self.args.\n max_seq_length, self.tokenizer, self.emotioner)\n', (7045, 7128), False, 'from datasets.bert_processors.abstract_processor import convert_examples_to_features_with_emotion, convert_examples_to_hierarchical_features\n'), ((7486, 7548), 'utils.preprocessing.pad_input_matrix', 'pad_input_matrix', (['unpadded_input_ids', 'self.args.max_doc_length'], {}), '(unpadded_input_ids, self.args.max_doc_length)\n', (7502, 7548), False, 'from utils.preprocessing import pad_input_matrix\n'), ((7562, 7625), 'utils.preprocessing.pad_input_matrix', 'pad_input_matrix', (['unpadded_input_mask', 'self.args.max_doc_length'], {}), '(unpadded_input_mask, self.args.max_doc_length)\n', (7578, 7625), False, 'from utils.preprocessing import pad_input_matrix\n'), ((7639, 7703), 'utils.preprocessing.pad_input_matrix', 'pad_input_matrix', (['unpadded_segment_ids', 'self.args.max_doc_length'], {}), '(unpadded_segment_ids, self.args.max_doc_length)\n', (7655, 7703), False, 'from utils.preprocessing import pad_input_matrix\n'), ((3636, 3651), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3649, 3651), False, 'import torch\n'), ((8924, 8939), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8937, 8939), False, 'import torch\n'), ((4855, 4885), 'torch.argmax', 'torch.argmax', (['label_ids'], {'dim': '(1)'}), '(label_ids, dim=1)\n', (4867, 4885), False, 'import torch\n'), ((9127, 9157), 'torch.argmax', 'torch.argmax', (['label_ids'], {'dim': '(1)'}), '(label_ids, dim=1)\n', (9139, 9157), False, 'import torch\n'), ((4662, 4689), 'torch.argmax', 'torch.argmax', (['logits'], {'dim': '(1)'}), '(logits, dim=1)\n', (4674, 4689), False, 'import torch\n'), ((4752, 4782), 'torch.argmax', 'torch.argmax', (['label_ids'], {'dim': '(1)'}), '(label_ids, dim=1)\n', (4764, 4782), False, 'import torch\n'), ((4308, 4325), 'torch.nn.functional.sigmoid', 'F.sigmoid', (['logits'], {}), '(logits)\n', (4317, 4325), True, 'import torch.nn.functional as F\n')]
andrearosasco/DistilledReplay
model/mlp1.py
2a4efa88d22b9afc7016f07549114688f346dbe8
import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self, config): super(Model, self).__init__() self.drop = nn.Dropout(config['dropout']) self.fc1 = nn.Linear(784, 2000) self.fc2 = nn.Linear(2000, 2000) self.fc3 = nn.Linear(2000, 2000) self.fc4 = nn.Linear(2000, 2000) self.fc5 = nn.Linear(2000, 10) def forward(self, x): # 784 -> 2000 x = F.relu(self.drop(self.fc1(x))) # 2000 -> 2000 x = F.relu(self.drop(self.fc2(x))) # 2000 -> 2000 x = F.relu(self.drop(self.fc3(x))) # 2000 -> 2000 x = F.relu(self.drop(self.fc4(x))) # 2000 -> 100 x = self.fc5(x) return x
[((177, 206), 'torch.nn.Dropout', 'nn.Dropout', (["config['dropout']"], {}), "(config['dropout'])\n", (187, 206), True, 'import torch.nn as nn\n'), ((229, 249), 'torch.nn.Linear', 'nn.Linear', (['(784)', '(2000)'], {}), '(784, 2000)\n', (238, 249), True, 'import torch.nn as nn\n'), ((270, 291), 'torch.nn.Linear', 'nn.Linear', (['(2000)', '(2000)'], {}), '(2000, 2000)\n', (279, 291), True, 'import torch.nn as nn\n'), ((312, 333), 'torch.nn.Linear', 'nn.Linear', (['(2000)', '(2000)'], {}), '(2000, 2000)\n', (321, 333), True, 'import torch.nn as nn\n'), ((354, 375), 'torch.nn.Linear', 'nn.Linear', (['(2000)', '(2000)'], {}), '(2000, 2000)\n', (363, 375), True, 'import torch.nn as nn\n'), ((396, 415), 'torch.nn.Linear', 'nn.Linear', (['(2000)', '(10)'], {}), '(2000, 10)\n', (405, 415), True, 'import torch.nn as nn\n')]
aslafy-z/netbox
netbox/ipam/managers.py
a5512dd4c46c005df8752fc330c1382ac22b31ea
from django.db import models from ipam.lookups import Host, Inet class IPAddressManager(models.Manager): def get_queryset(self): """ By default, PostgreSQL will order INETs with shorter (larger) prefix lengths ahead of those with longer (smaller) masks. This makes no sense when ordering IPs, which should be ordered solely by family and host address. We can use HOST() to extract just the host portion of the address (ignoring its mask), but we must then re-cast this value to INET() so that records will be ordered properly. We are essentially re-casting each IP address as a /32 or /128. """ qs = super().get_queryset() return qs.order_by(Inet(Host('address')))
[((727, 742), 'ipam.lookups.Host', 'Host', (['"""address"""'], {}), "('address')\n", (731, 742), False, 'from ipam.lookups import Host, Inet\n')]
VArdulov/learning-kis
train.py
2637f08d5e8027a22feff17064be45ea51f738e5
#!/usr/bin/env python # coding: utf-8 """ Learning Koopman Invariant Subspace (c) Naoya Takeishi, 2017. [email protected] """ import numpy as np np.random.seed(1234567890) from argparse import ArgumentParser from os import path import time from lkis import TimeSeriesBatchMaker, KoopmanInvariantSubspaceLearner from losses import combined_loss from torch import device, save, manual_seed from torch.optim import SGD import matplotlib.pyplot as plt import seaborn as sns # -- Parse arguments t = time.time() parser = ArgumentParser(description='Learning Koopman Invariant Subspace (Now with PyTorch!)') parser.add_argument("--name", "-n", type=str, default=f"lkis-{int(time.time())}", help="name of experiment") parser.add_argument("--data-path", type=str, default="./train.npy", help="time-series data to model") parser.add_argument("--epochs", "-e", type=int, default=1000, help="number of epochs to train for") parser.add_argument("--num-batches", "-b", type=int, default=1, help="how many batchs for break the data up into") parser.add_argument("--gpu", action="store_true", default=False, help="use a GPU or no") parser.add_argument("--intermediate-observable", "-i", type=int, default=-1, help="intermediate dimensional observation space") parser.add_argument("--save-model", "-m", action="store_true", default=False, help="whether or not you want the model saved to $name$.torch.mdl") parser.add_argument("--save-training-plot", "-p", action="store_true", default=False, help="where to save plotting") parser.add_argument("--max-lag", "-l", type=int, default=-1, help="maximum_lag") parser.add_argument("--state-space", "-s", type=int, default=1, help="dimensionality of the underlying state space") parser.add_argument("--alpha", "-a", type=float, default=1.0, help="value to score the reconstruction loss by") parser.add_argument("--learning-rate", "-r", type=float, default=0.001, help="Optimizer learning rate") parser.add_argument("--validation-data-path", "-v", type=str, default="") #ToDo: Implement parser.add_argument("--dmd", action="store_true", default=False, help="Execute and save the DMD on the training set") if __name__ == "__main__": # grab the command line arguments cli_args = parser.parse_args() manual_seed(216) # find and load the training data data_path = cli_args.data_path print(f"Loading training data from {data_path}") data_train = np.load(data_path) if len(data_train.shape) == 1: data_train = data_train.reshape(-1, 1) print(f"Loaded a dataset with dimension: {data_train.shape}") validate = cli_args.validation_data_path != "" data_val = None if validate: data_path = cli_args.validation_data_path print(f"Loading validation data from {data_path}") data_val = np.load(data_path) # process the delay either set by the user or is set to one 10th of the data delay = cli_args.max_lag if cli_args.max_lag > 0 else (data_train.shape[0] // 10) # based on the number of batches, delay, and size of the data compute the samples per batch samples_per_batch = (data_train.shape[0] - delay) // cli_args.num_batches # construct the data preparer batch_iterator = TimeSeriesBatchMaker( y=data_train, batch_size=samples_per_batch, max_lag=delay ) if validate: val_batch_iterator = TimeSeriesBatchMaker( y=data_val, max_lag=delay ) # construct the end-to-end model lkis = KoopmanInvariantSubspaceLearner( observable_dim=data_train.shape[1], latent_dim=cli_args.state_space, intermediate_observable=cli_args.intermediate_observable, delay=delay ) if cli_args.gpu: device = device("cuda") # initialize the optimizer optimizer = SGD(lkis.parameters(), lr=cli_args.learning_rate) losses = [] val_losses = [] for epoch in range(cli_args.epochs): loss = 0 for b in range(cli_args.num_batches): optimizer.zero_grad() time_delayed_ys, y_true = next(batch_iterator) if cli_args.gpu: time_delayed_ys.to(device) y_true.to(device) g_pred, y_pred = lkis(time_delayed_ys) g_0 = g_pred[:-1] g_1 = g_pred[1:] batch_loss = combined_loss(y_pred=y_pred, y_true=y_true, g_0=g_0, g_1=g_1) batch_loss.backward() optimizer.step() loss += batch_loss.item() # display the epoch training loss print(f"epoch : {epoch + 1}/{cli_args.epochs}, loss = {loss:.6f}") losses.append(loss) if validate: y_time_delayed_val, y_true = next(val_batch_iterator) if cli_args.gpu: y_time_delayed_val.to(device) y_true.to(device) g_pred, y_pred = lkis(y_time_delayed_val) g_0 = g_pred[:-1] g_1 = g_pred[1:] batch_loss = combined_loss(y_pred=y_pred, y_true=y_true, g_0=g_0, g_1=g_1) val_loss = batch_loss.item() print(f"\tval-loss = {val_loss:.6f}") val_losses.append(val_loss) if cli_args.save_model: save(lkis, f"{cli_args.name}.torch.mdl") if cli_args.save_training_plot: sns.lineplot(x=list(range(cli_args.epochs)), y=losses, label="training loss") if validate: sns.lineplot(x=list(range(cli_args.epochs)), y=val_losses, label="validation loss") plt.xlabel("Epochs") plt.ylabel("Combined Reconstruction and DMD Loss") plt.title(f"Training Loss for {cli_args.name}") plt.savefig(f"{cli_args.name}-training-loss.png")
[((162, 188), 'numpy.random.seed', 'np.random.seed', (['(1234567890)'], {}), '(1234567890)\n', (176, 188), True, 'import numpy as np\n'), ((516, 527), 'time.time', 'time.time', ([], {}), '()\n', (525, 527), False, 'import time\n'), ((537, 627), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Learning Koopman Invariant Subspace (Now with PyTorch!)"""'}), "(description=\n 'Learning Koopman Invariant Subspace (Now with PyTorch!)')\n", (551, 627), False, 'from argparse import ArgumentParser\n'), ((2258, 2274), 'torch.manual_seed', 'manual_seed', (['(216)'], {}), '(216)\n', (2269, 2274), False, 'from torch import device, save, manual_seed\n'), ((2419, 2437), 'numpy.load', 'np.load', (['data_path'], {}), '(data_path)\n', (2426, 2437), True, 'import numpy as np\n'), ((3220, 3299), 'lkis.TimeSeriesBatchMaker', 'TimeSeriesBatchMaker', ([], {'y': 'data_train', 'batch_size': 'samples_per_batch', 'max_lag': 'delay'}), '(y=data_train, batch_size=samples_per_batch, max_lag=delay)\n', (3240, 3299), False, 'from lkis import TimeSeriesBatchMaker, KoopmanInvariantSubspaceLearner\n'), ((3507, 3687), 'lkis.KoopmanInvariantSubspaceLearner', 'KoopmanInvariantSubspaceLearner', ([], {'observable_dim': 'data_train.shape[1]', 'latent_dim': 'cli_args.state_space', 'intermediate_observable': 'cli_args.intermediate_observable', 'delay': 'delay'}), '(observable_dim=data_train.shape[1],\n latent_dim=cli_args.state_space, intermediate_observable=cli_args.\n intermediate_observable, delay=delay)\n', (3538, 3687), False, 'from lkis import TimeSeriesBatchMaker, KoopmanInvariantSubspaceLearner\n'), ((2802, 2820), 'numpy.load', 'np.load', (['data_path'], {}), '(data_path)\n', (2809, 2820), True, 'import numpy as np\n'), ((3376, 3423), 'lkis.TimeSeriesBatchMaker', 'TimeSeriesBatchMaker', ([], {'y': 'data_val', 'max_lag': 'delay'}), '(y=data_val, max_lag=delay)\n', (3396, 3423), False, 'from lkis import TimeSeriesBatchMaker, KoopmanInvariantSubspaceLearner\n'), ((3756, 3770), 'torch.device', 'device', (['"""cuda"""'], {}), "('cuda')\n", (3762, 3770), False, 'from torch import device, save, manual_seed\n'), ((5226, 5266), 'torch.save', 'save', (['lkis', 'f"""{cli_args.name}.torch.mdl"""'], {}), "(lkis, f'{cli_args.name}.torch.mdl')\n", (5230, 5266), False, 'from torch import device, save, manual_seed\n'), ((5515, 5535), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (5525, 5535), True, 'import matplotlib.pyplot as plt\n'), ((5544, 5594), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Combined Reconstruction and DMD Loss"""'], {}), "('Combined Reconstruction and DMD Loss')\n", (5554, 5594), True, 'import matplotlib.pyplot as plt\n'), ((5603, 5650), 'matplotlib.pyplot.title', 'plt.title', (['f"""Training Loss for {cli_args.name}"""'], {}), "(f'Training Loss for {cli_args.name}')\n", (5612, 5650), True, 'import matplotlib.pyplot as plt\n'), ((5659, 5708), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""{cli_args.name}-training-loss.png"""'], {}), "(f'{cli_args.name}-training-loss.png')\n", (5670, 5708), True, 'import matplotlib.pyplot as plt\n'), ((4346, 4407), 'losses.combined_loss', 'combined_loss', ([], {'y_pred': 'y_pred', 'y_true': 'y_true', 'g_0': 'g_0', 'g_1': 'g_1'}), '(y_pred=y_pred, y_true=y_true, g_0=g_0, g_1=g_1)\n', (4359, 4407), False, 'from losses import combined_loss\n'), ((4995, 5056), 'losses.combined_loss', 'combined_loss', ([], {'y_pred': 'y_pred', 'y_true': 'y_true', 'g_0': 'g_0', 'g_1': 'g_1'}), '(y_pred=y_pred, y_true=y_true, g_0=g_0, g_1=g_1)\n', (5008, 5056), False, 'from losses import combined_loss\n'), ((689, 700), 'time.time', 'time.time', ([], {}), '()\n', (698, 700), False, 'import time\n')]
KenWoo/Algorithm
Algorithms/Easy/1200. Minimum Absolute Difference/answer.py
4012a2f0a099a502df1e5df2e39faa75fe6463e8
from typing import List class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() res = [] min_diff = arr[1] - arr[0] res.append([arr[0], arr[1]]) for i in range(1, len(arr)-1): diff = arr[i+1]-arr[i] if diff < min_diff: min_diff = diff res.clear() res.append([arr[i], arr[i+1]]) elif diff == min_diff: res.append([arr[i], arr[i+1]]) return res if __name__ == "__main__": s = Solution() result = s.minimumAbsDifference([3, 8, -10, 23, 19, -4, -14, 27]) print(result)
[]
VijayStroup/Physics_Problem_Solver_Basic
resources/physequations.py
fc6944475ed8bcfe91bbd207734c3f9aee31e0fe
import math def close(expected, actual, maxerror): '''checks to see if the actual number is within expected +- maxerror.''' low = expected - maxerror high = expected + maxerror if actual >= low and actual <= high: return True else: return False def grav_potential_energy(mass, height, gravity=9.81): '''calculate potential energy given mass and height. Mass in kilograms and height in meters.''' gp_energy = mass * height * gravity return gp_energy def kin_energy(mass, velocity): '''calculate kinetic energy given mass and velocity. Mass in kilograms and velocity in meters per second.''' k_energy = .5 * mass * velocity ** 2 return k_energy def work_energy(force, displacement, angle): '''calculate work energy given force, displancement, and angle. Force in newtons, displacement in meters, angle in degrees.''' anglerad = math.radians(angle) cos = math.cos(anglerad) w_energy = force * displacement * cos return w_energy '''============================================================================= Tests =============================================================================''' if __name__ == '__main__': def check(funcname, args, expected, ans, maxerror): if not close(expected, ans, maxerror): print(f'{funcname}({args}) = {ans} should = {expected}') print(close(10, 11.1, 1)) print(close(100, 100.001, .01)) print(close(-10, -11.01, 1)) print(close(84756, 84300.2, 500.5)) #gravitional potential energy tests ans = grav_potential_energy(3.00, 7.00) check('grav_potential_energy', '3.00, 7.00', 206.01, ans, 0.00000000000000000000000001) ans = grav_potential_energy(2.00, 5.00) check('grav_potential_energy', '2.00, 5.00', 98.1, ans, 0.01) #kinetic energy tests ans = kin_energy(2, 6.55) check('kin_energy', '2, 6.55', 42.90, ans, 0.01) ans = kin_energy(5.65, 10) check('kin_energy', '5.65, 10', 282.5, ans, 0.1) #work energy tests ans = work_energy(500, 10, 0) check('work_energy', '500, 10, 0', 5000.0, ans, 0.1) ans = work_energy(150, 50, 45) check('work_energy', '150, 50, 45', 5303.30, ans, 0.01)
[((859, 878), 'math.radians', 'math.radians', (['angle'], {}), '(angle)\n', (871, 878), False, 'import math\n'), ((886, 904), 'math.cos', 'math.cos', (['anglerad'], {}), '(anglerad)\n', (894, 904), False, 'import math\n')]
andycon/PyMVPA
mvpa2/tests/test_erdataset.py
67f7ee68012e3a1128168c583d6c83303b7a2c27
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyMVPA package for the # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## '''Tests for the event-related dataset''' from mvpa2.testing import * from mvpa2.datasets import dataset_wizard from mvpa2.mappers.flatten import FlattenMapper from mvpa2.mappers.boxcar import BoxcarMapper from mvpa2.mappers.fx import FxMapper from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, \ extract_boxcar_event_samples from mvpa2.datasets.sources import load_example_fmri_dataset from mvpa2.mappers.zscore import zscore def test_erdataset(): # 3 chunks, 5 targets, blocks of 5 samples each nchunks = 3 ntargets = 5 blocklength = 5 nfeatures = 10 targets = np.tile(np.repeat(range(ntargets), blocklength), nchunks) chunks = np.repeat(np.arange(nchunks), ntargets * blocklength) samples = np.repeat( np.arange(nchunks * ntargets * blocklength), nfeatures).reshape(-1, nfeatures) ds = dataset_wizard(samples, targets=targets, chunks=chunks) # check if events are determined properly evs = find_events(targets=ds.sa.targets, chunks=ds.sa.chunks) for ev in evs: assert_equal(ev['duration'], blocklength) assert_equal(ntargets * nchunks, len(evs)) for t in range(ntargets): assert_equal(len([ev for ev in evs if ev['targets'] == t]), nchunks) # now turn `ds` into an eventreleated dataset erds = eventrelated_dataset(ds, evs) # the only unprefixed sample attributes are assert_equal(sorted([a for a in ds.sa if not a.startswith('event')]), ['chunks', 'targets']) # samples as expected? assert_array_equal(erds.samples[0], np.repeat(np.arange(blocklength), nfeatures)) # that should also be the temporal feature offset assert_array_equal(erds.samples[0], erds.fa.event_offsetidx) assert_array_equal(erds.sa.event_onsetidx, np.arange(0,71,5)) # finally we should see two mappers assert_equal(len(erds.a.mapper), 2) assert_true(isinstance(erds.a.mapper[0], BoxcarMapper)) assert_true(isinstance(erds.a.mapper[1], FlattenMapper)) # check alternative event mapper # this one does temporal compression by averaging erds_compress = eventrelated_dataset( ds, evs, event_mapper=FxMapper('features', np.mean)) assert_equal(len(erds), len(erds_compress)) assert_array_equal(erds_compress.samples[:,0], np.arange(2,73,5)) # # now check the same dataset with event descretization tr = 2.5 ds.sa['time'] = np.arange(nchunks * ntargets * blocklength) * tr evs = [{'onset': 4.9, 'duration': 6.2}] # doesn't work without conversion assert_raises(ValueError, eventrelated_dataset, ds, evs) erds = eventrelated_dataset(ds, evs, time_attr='time') assert_equal(len(erds), 1) assert_array_equal(erds.samples[0], np.repeat(np.arange(1,5), nfeatures)) assert_array_equal(erds.sa.orig_onset, [evs[0]['onset']]) assert_array_equal(erds.sa.orig_duration, [evs[0]['duration']]) assert_array_almost_equal(erds.sa.orig_offset, [2.4]) assert_array_equal(erds.sa.time, [np.arange(2.5, 11, 2.5)]) # now with closest match erds = eventrelated_dataset(ds, evs, time_attr='time', match='closest') expected_nsamples = 3 assert_equal(len(erds), 1) assert_array_equal(erds.samples[0], np.repeat(np.arange(2,2+expected_nsamples), nfeatures)) assert_array_equal(erds.sa.orig_onset, [evs[0]['onset']]) assert_array_equal(erds.sa.orig_duration, [evs[0]['duration']]) assert_array_almost_equal(erds.sa.orig_offset, [-0.1]) assert_array_equal(erds.sa.time, [np.arange(5.0, 11, 2.5)]) # now test the way back results = np.arange(erds.nfeatures) assert_array_equal(erds.a.mapper.reverse1(results), results.reshape(expected_nsamples, nfeatures)) # what about multiple results? nresults = 5 results = dataset_wizard([results] * nresults) # and let's have an attribute to make it more difficult results.sa['myattr'] = np.arange(5) rds = erds.a.mapper.reverse(results) assert_array_equal(rds, results.samples.reshape(nresults * expected_nsamples, nfeatures)) assert_array_equal(rds.sa.myattr, np.repeat(results.sa.myattr, expected_nsamples)) evs = [dict(onset=12, duration=2), dict(onset=70, duration=3)] evds = extract_boxcar_event_samples(ds, evs) # it goes for the max of all durations assert_equal(evds.shape, (len(evs), 3 * ds.nfeatures)) # overide duration evds = extract_boxcar_event_samples(ds, evs, event_duration=1) assert_equal(evds.shape, (len(evs), 1 * ds.nfeatures)) assert_equal(np.unique(evds.samples[1]), 70) # overide onset evds = extract_boxcar_event_samples(ds, evs, event_offset=2) assert_equal(evds.shape, (len(evs), 3 * ds.nfeatures)) assert_equal(np.unique(evds.samples[1,:10]), 72) # overide both evds = extract_boxcar_event_samples(ds, evs, event_offset=-2, event_duration=1) assert_equal(evds.shape, (len(evs), 1 * ds.nfeatures)) assert_equal(np.unique(evds.samples[1]), 68) def test_hrf_modeling(): skip_if_no_external('nibabel') skip_if_no_external('nipy') # ATM relies on NiPy's GLM implementation ds = load_example_fmri_dataset('25mm', literal=True) # TODO: simulate short dataset with known properties and use it # for testing events = find_events(targets=ds.sa.targets, chunks=ds.sa.chunks) tr = ds.a.imghdr['pixdim'][4] for ev in events: for a in ('onset', 'duration'): ev[a] = ev[a] * tr evds = eventrelated_dataset(ds, events, time_attr='time_coords', condition_attr='targets', design_kwargs=dict(drift_model='blank'), glmfit_kwargs=dict(model='ols'), model='hrf') # same voxels assert_equal(ds.nfeatures, evds.nfeatures) assert_array_equal(ds.fa.voxel_indices, evds.fa.voxel_indices) # one sample for each condition, plus constant assert_equal(sorted(ds.sa['targets'].unique), sorted(evds.sa.targets)) assert_equal(evds.a.add_regs.sa.regressor_names[0], 'constant') # with centered data zscore(ds) evds_demean = eventrelated_dataset(ds, events, time_attr='time_coords', condition_attr='targets', design_kwargs=dict(drift_model='blank'), glmfit_kwargs=dict(model='ols'), model='hrf') # after demeaning the constant should consume a lot less assert(evds.a.add_regs[0].samples.mean() > evds_demean.a.add_regs[0].samples.mean()) # from eyeballing the sensitivity example -- would be better to test this on # the tutorial data assert(evds_demean[evds.sa.targets == 'shoe'].samples.max() \ > evds_demean[evds.sa.targets == 'bottle'].samples.max()) # HRF models assert('regressors' in evds.sa) assert('regressors' in evds.a.add_regs.sa) assert_equal(evds.sa.regressors.shape[1], len(ds)) # custom regressors evds_regrs = eventrelated_dataset(ds, events, time_attr='time_coords', condition_attr='targets', regr_attrs=['time_indices'], design_kwargs=dict(drift_model='blank'), glmfit_kwargs=dict(model='ols'), model='hrf') # verify that nothing screwed up time_coords assert_equal(ds.sa.time_coords[0], 0) assert_equal(len(evds_regrs), len(evds)) # one more output sample in .a.add_regs assert_equal(len(evds_regrs.a.add_regs) - 1, len(evds.a.add_regs)) # comes last before constant assert_equal('time_indices', evds_regrs.a.add_regs.sa.regressor_names[-2]) # order of main regressors is unchanged assert_array_equal(evds.sa.targets, evds_regrs.sa.targets) # custom regressors from external sources evds_regrs = eventrelated_dataset(ds, events, time_attr='time_coords', condition_attr='targets', regr_attrs=['time_coords'], design_kwargs=dict(drift_model='blank', add_regs=np.linspace(1, -1, len(ds))[None].T, add_reg_names=['negative_trend']), glmfit_kwargs=dict(model='ols'), model='hrf') assert_equal(len(evds_regrs), len(evds)) # But we got one more in additional regressors assert_equal(len(evds_regrs.a.add_regs) - 2, len(evds.a.add_regs)) # comes last before constant assert_array_equal(['negative_trend', 'time_coords', 'constant'], evds_regrs.a.add_regs.sa.regressor_names) # order is otherwise unchanged assert_array_equal(evds.sa.targets, evds_regrs.sa.targets) # HRF models with estimating per each chunk assert_equal(ds.sa.time_coords[0], 0) evds_regrs = eventrelated_dataset(ds, events, time_attr='time_coords', condition_attr=['targets', 'chunks'], regr_attrs=['time_indices'], design_kwargs=dict(drift_model='blank'), glmfit_kwargs=dict(model='ols'), model='hrf') assert_true('add_regs' in evds_regrs.a) assert_true('time_indices' in evds_regrs.a.add_regs.sa.regressor_names) assert_equal(len(ds.UC) * len(ds.UT), len(evds_regrs)) assert_equal(len(evds_regrs.UC) * len(evds_regrs.UT), len(evds_regrs)) from mvpa2.mappers.fx import mean_group_sample evds_regrs_meaned = mean_group_sample(['targets'])(evds_regrs) assert_array_equal(evds_regrs_meaned.T, evds.T) # targets should be the same #corr = np.corrcoef(np.vstack((evds.samples, evds_regrs_meaned))) #import pydb; pydb.debugger() #pass #i = 1
[((1272, 1327), 'mvpa2.datasets.dataset_wizard', 'dataset_wizard', (['samples'], {'targets': 'targets', 'chunks': 'chunks'}), '(samples, targets=targets, chunks=chunks)\n', (1286, 1327), False, 'from mvpa2.datasets import dataset_wizard\n'), ((1384, 1439), 'mvpa2.datasets.eventrelated.find_events', 'find_events', ([], {'targets': 'ds.sa.targets', 'chunks': 'ds.sa.chunks'}), '(targets=ds.sa.targets, chunks=ds.sa.chunks)\n', (1395, 1439), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((1745, 1774), 'mvpa2.datasets.eventrelated.eventrelated_dataset', 'eventrelated_dataset', (['ds', 'evs'], {}), '(ds, evs)\n', (1765, 1774), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((3089, 3136), 'mvpa2.datasets.eventrelated.eventrelated_dataset', 'eventrelated_dataset', (['ds', 'evs'], {'time_attr': '"""time"""'}), "(ds, evs, time_attr='time')\n", (3109, 3136), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((3538, 3602), 'mvpa2.datasets.eventrelated.eventrelated_dataset', 'eventrelated_dataset', (['ds', 'evs'], {'time_attr': '"""time"""', 'match': '"""closest"""'}), "(ds, evs, time_attr='time', match='closest')\n", (3558, 3602), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((4324, 4360), 'mvpa2.datasets.dataset_wizard', 'dataset_wizard', (['([results] * nresults)'], {}), '([results] * nresults)\n', (4338, 4360), False, 'from mvpa2.datasets import dataset_wizard\n'), ((4878, 4915), 'mvpa2.datasets.eventrelated.extract_boxcar_event_samples', 'extract_boxcar_event_samples', (['ds', 'evs'], {}), '(ds, evs)\n', (4906, 4915), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((5052, 5107), 'mvpa2.datasets.eventrelated.extract_boxcar_event_samples', 'extract_boxcar_event_samples', (['ds', 'evs'], {'event_duration': '(1)'}), '(ds, evs, event_duration=1)\n', (5080, 5107), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((5247, 5300), 'mvpa2.datasets.eventrelated.extract_boxcar_event_samples', 'extract_boxcar_event_samples', (['ds', 'evs'], {'event_offset': '(2)'}), '(ds, evs, event_offset=2)\n', (5275, 5300), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((5443, 5515), 'mvpa2.datasets.eventrelated.extract_boxcar_event_samples', 'extract_boxcar_event_samples', (['ds', 'evs'], {'event_offset': '(-2)', 'event_duration': '(1)'}), '(ds, evs, event_offset=-2, event_duration=1)\n', (5471, 5515), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((5808, 5855), 'mvpa2.datasets.sources.load_example_fmri_dataset', 'load_example_fmri_dataset', (['"""25mm"""'], {'literal': '(True)'}), "('25mm', literal=True)\n", (5833, 5855), False, 'from mvpa2.datasets.sources import load_example_fmri_dataset\n'), ((5955, 6010), 'mvpa2.datasets.eventrelated.find_events', 'find_events', ([], {'targets': 'ds.sa.targets', 'chunks': 'ds.sa.chunks'}), '(targets=ds.sa.targets, chunks=ds.sa.chunks)\n', (5966, 6010), False, 'from mvpa2.datasets.eventrelated import find_events, eventrelated_dataset, extract_boxcar_event_samples\n'), ((6803, 6813), 'mvpa2.mappers.zscore.zscore', 'zscore', (['ds'], {}), '(ds)\n', (6809, 6813), False, 'from mvpa2.mappers.zscore import zscore\n'), ((10408, 10438), 'mvpa2.mappers.fx.mean_group_sample', 'mean_group_sample', (["['targets']"], {}), "(['targets'])\n", (10425, 10438), False, 'from mvpa2.mappers.fx import mean_group_sample\n'), ((2639, 2668), 'mvpa2.mappers.fx.FxMapper', 'FxMapper', (['"""features"""', 'np.mean'], {}), "('features', np.mean)\n", (2647, 2668), False, 'from mvpa2.mappers.fx import FxMapper\n')]
aksr-aashish/FIREXUSERBOT
userbot/plugins/delfp.py
dff0b7bf028cb27779626ce523402346cc990402
from telethon.tl.functions.photos import DeletePhotosRequest, GetUserPhotosRequest from telethon.tl.types import InputPhoto from userbot.cmdhelp import CmdHelp from userbot.utils import admin_cmd, edit_or_reply, sudo_cmd CmdHelp("delfp").add_command("delpfp", None, "delete ur currnt profile picture").add() @borg.on(admin_cmd(pattern="delpfp ?(.*)")) @borg.on(sudo_cmd(pattern="delpfp ?(.*)", allow_sudo=True)) async def remove_profilepic(delpfp): """For .delpfp command, delete your current profile picture in Telegram.""" group = delpfp.text[8:] if group == "all": lim = 0 elif group.isdigit(): lim = int(group) else: lim = 1 pfplist = await delpfp.client( GetUserPhotosRequest(user_id=delpfp.from_id, offset=0, max_id=0, limit=lim) ) input_photos = [InputPhoto( id=sep.id, access_hash=sep.access_hash, file_reference=sep.file_reference, ) for sep in pfplist.photos] await delpfp.client(DeletePhotosRequest(id=input_photos)) await edit_or_reply( delpfp, f"`Successfully deleted {len(input_photos)} profile picture(s).`" )
[((321, 354), 'userbot.utils.admin_cmd', 'admin_cmd', ([], {'pattern': '"""delpfp ?(.*)"""'}), "(pattern='delpfp ?(.*)')\n", (330, 354), False, 'from userbot.utils import admin_cmd, edit_or_reply, sudo_cmd\n'), ((365, 414), 'userbot.utils.sudo_cmd', 'sudo_cmd', ([], {'pattern': '"""delpfp ?(.*)"""', 'allow_sudo': '(True)'}), "(pattern='delpfp ?(.*)', allow_sudo=True)\n", (373, 414), False, 'from userbot.utils import admin_cmd, edit_or_reply, sudo_cmd\n'), ((823, 913), 'telethon.tl.types.InputPhoto', 'InputPhoto', ([], {'id': 'sep.id', 'access_hash': 'sep.access_hash', 'file_reference': 'sep.file_reference'}), '(id=sep.id, access_hash=sep.access_hash, file_reference=sep.\n file_reference)\n', (833, 913), False, 'from telethon.tl.types import InputPhoto\n'), ((721, 796), 'telethon.tl.functions.photos.GetUserPhotosRequest', 'GetUserPhotosRequest', ([], {'user_id': 'delpfp.from_id', 'offset': '(0)', 'max_id': '(0)', 'limit': 'lim'}), '(user_id=delpfp.from_id, offset=0, max_id=0, limit=lim)\n', (741, 796), False, 'from telethon.tl.functions.photos import DeletePhotosRequest, GetUserPhotosRequest\n'), ((1023, 1059), 'telethon.tl.functions.photos.DeletePhotosRequest', 'DeletePhotosRequest', ([], {'id': 'input_photos'}), '(id=input_photos)\n', (1042, 1059), False, 'from telethon.tl.functions.photos import DeletePhotosRequest, GetUserPhotosRequest\n'), ((223, 239), 'userbot.cmdhelp.CmdHelp', 'CmdHelp', (['"""delfp"""'], {}), "('delfp')\n", (230, 239), False, 'from userbot.cmdhelp import CmdHelp\n')]
pplonski/automlbenchmark
amlb/benchmarks/file.py
f49ddfa2583643173296ed8ab45a8c14c62a6987
import logging import os from typing import List, Tuple, Optional from amlb.utils import config_load, Namespace log = logging.getLogger(__name__) def _find_local_benchmark_definition(name: str, benchmark_definition_dirs: List[str]) -> str: # 'name' should be either a full path to the benchmark, # or a filename (without extension) in the benchmark directory. if os.path.exists(name): return name for bd in benchmark_definition_dirs: bf = os.path.join(bd, f"{name}.yaml") if os.path.exists(bf): # We don't account for duplicate definitions (yet). return bf # should we support s3 and check for s3 path before raising error? raise ValueError(f"Incorrect benchmark name or path `{name}`, name not available in {benchmark_definition_dirs}.") def load_file_benchmark(name: str, benchmark_definition_dirs: List[str]) -> Tuple[str, Optional[str], List[Namespace]]: """ Loads benchmark from a local file. """ benchmark_file = _find_local_benchmark_definition(name, benchmark_definition_dirs) log.info("Loading benchmark definitions from %s.", benchmark_file) tasks = config_load(benchmark_file) benchmark_name, _ = os.path.splitext(os.path.basename(benchmark_file)) return benchmark_name, benchmark_file, tasks
[((120, 147), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (137, 147), False, 'import logging\n'), ((379, 399), 'os.path.exists', 'os.path.exists', (['name'], {}), '(name)\n', (393, 399), False, 'import os\n'), ((1156, 1183), 'amlb.utils.config_load', 'config_load', (['benchmark_file'], {}), '(benchmark_file)\n', (1167, 1183), False, 'from amlb.utils import config_load, Namespace\n'), ((476, 508), 'os.path.join', 'os.path.join', (['bd', 'f"""{name}.yaml"""'], {}), "(bd, f'{name}.yaml')\n", (488, 508), False, 'import os\n'), ((520, 538), 'os.path.exists', 'os.path.exists', (['bf'], {}), '(bf)\n', (534, 538), False, 'import os\n'), ((1225, 1257), 'os.path.basename', 'os.path.basename', (['benchmark_file'], {}), '(benchmark_file)\n', (1241, 1257), False, 'import os\n')]
eyesoft/pybuspro
pybuspro/devices/control.py
9a178117be2db40ef1399cc60afdc18e251682bc
from ..core.telegram import Telegram from ..helpers.enums import OperateCode class _Control: def __init__(self, buspro): self._buspro = buspro self.subnet_id = None self.device_id = None @staticmethod def build_telegram_from_control(control): if control is None: return None if type(control) == _SingleChannelControl: operate_code = OperateCode.SingleChannelControl payload = [control.channel_number, control.channel_level, control.running_time_minutes, control.running_time_seconds] elif type(control) == _SceneControl: operate_code = OperateCode.SceneControl payload = [control.area_number, control.scene_number] elif type(control) == _ReadStatusOfChannels: operate_code = OperateCode.ReadStatusOfChannels payload = [] elif type(control) == _GenericControl: operate_code = control.operate_code payload = control.payload elif type(control) == _UniversalSwitch: operate_code = OperateCode.UniversalSwitchControl payload = [control.switch_number, control.switch_status.value] elif type(control) == _ReadStatusOfUniversalSwitch: operate_code = OperateCode.ReadStatusOfUniversalSwitch payload = [control.switch_number] elif type(control) == _ReadSensorStatus: operate_code = OperateCode.ReadSensorStatus payload = [] elif type(control) == _ReadSensorsInOneStatus: operate_code = OperateCode.ReadSensorsInOneStatus payload = [] elif type(control) == _ReadFloorHeatingStatus: operate_code = OperateCode.ReadFloorHeatingStatus payload = [] elif type(control) == _ReadDryContactStatus: operate_code = OperateCode.ReadDryContactStatus payload = [1, control.switch_number] elif type(control) == _ControlFloorHeatingStatus: operate_code = OperateCode.ControlFloorHeatingStatus payload = [control.temperature_type, control.status, control.mode, control.normal_temperature, control.day_temperature, control.night_temperature, control.away_temperature] else: return None telegram = Telegram() telegram.target_address = (control.subnet_id, control.device_id) telegram.operate_code = operate_code telegram.payload = payload return telegram @property def telegram(self): return self.build_telegram_from_control(self) async def send(self): telegram = self.telegram # if telegram.target_address[1] == 100: # print("==== {}".format(str(telegram))) await self._buspro.network_interface.send_telegram(telegram) class _GenericControl(_Control): def __init__(self, buspro): super().__init__(buspro) self.payload = None self.operate_code = None class _SingleChannelControl(_Control): def __init__(self, buspro): super().__init__(buspro) self.channel_number = None self.channel_level = None self.running_time_minutes = None self.running_time_seconds = None class _SceneControl(_Control): def __init__(self, buspro): super().__init__(buspro) self.area_number = None self.scene_number = None class _ReadStatusOfChannels(_Control): def __init__(self, buspro): super().__init__(buspro) # no more properties class _UniversalSwitch(_Control): def __init__(self, buspro): super().__init__(buspro) self.switch_number = None self.switch_status = None class _ReadStatusOfUniversalSwitch(_Control): def __init__(self, buspro): super().__init__(buspro) self.switch_number = None class _ReadSensorStatus(_Control): def __init__(self, buspro): super().__init__(buspro) # no more properties class _ReadSensorsInOneStatus(_Control): def __init__(self, buspro): super().__init__(buspro) # no more properties class _ReadFloorHeatingStatus(_Control): def __init__(self, buspro): super().__init__(buspro) # no more properties class _ControlFloorHeatingStatus(_Control): def __init__(self, buspro): super().__init__(buspro) self.temperature_type = None self.status = None self.mode = None self.normal_temperature = None self.day_temperature = None self.night_temperature = None self.away_temperature = None class _ReadDryContactStatus(_Control): def __init__(self, buspro): super().__init__(buspro) self.switch_number = None
[]
eunchong/infra
appengine/chrome_infra_console_loadtest/main.py
ce3728559112bfb3e8b32137eada517aec6d22f9
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import endpoints import random import webapp2 from apiclient import discovery from google.appengine.ext import ndb from oauth2client.client import GoogleCredentials from protorpc import messages from protorpc import message_types from protorpc import remote from components import auth CONFIG_DATASTORE_KEY = "CONFIG_DATASTORE_KEY" API_NAME = 'consoleapp' API_VERSION = 'v1' DISCOVERY_URL = '%s/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest' class FieldParamsModel(ndb.Model): field_key = ndb.StringProperty() values = ndb.StringProperty(repeated=True) class MetricModel(ndb.Model): name = ndb.StringProperty(default="") minimum = ndb.FloatProperty(default=0) maximum = ndb.FloatProperty(default=100) class ParamsModel(ndb.Model): time = ndb.FloatProperty(default=10) freq = ndb.FloatProperty(default=1) url = ndb.StringProperty() params = ndb.LocalStructuredProperty(FieldParamsModel, repeated=True) metrics = ndb.LocalStructuredProperty(MetricModel, repeated=True) class Field(messages.Message): key = messages.StringField(1) value = messages.StringField(2) class Point(messages.Message): time = messages.FloatField(1) value = messages.FloatField(2) class FieldParams(messages.Message): field_key = messages.StringField(1) values = messages.StringField(2, repeated=True) class Metric(messages.Message): name = messages.StringField(1) minimum = messages.FloatField(2) maximum = messages.FloatField(3) class Params(messages.Message): time = messages.FloatField(1) freq = messages.FloatField(2) url = messages.StringField(3) params = messages.MessageField(FieldParams, 4, repeated=True) metrics = messages.MessageField(Metric, 5, repeated=True) class TimeSeries(messages.Message): points = messages.MessageField(Point, 1, repeated=True) fields = messages.MessageField(Field, 2, repeated=True) metric = messages.StringField(3) class DataPacket(messages.Message): timeseries = messages.MessageField(TimeSeries, 1, repeated=True) @auth.endpoints_api(name='consoleapp', version='v1') class LoadTestApi(remote.Service): """A testing endpoint that receives timeseries data.""" @auth.endpoints_method(DataPacket, message_types.VoidMessage, name='timeseries.update') @auth.require(lambda: auth.is_group_member('metric-generators')) def timeseries_update(self, request): logging.debug('Datapacket length is %d', len(request.timeseries)) return message_types.VoidMessage() @auth.endpoints_api(name='ui', version='v1') class UIApi(remote.Service): """API for the loadtest configuration UI.""" @auth.endpoints_method(message_types.VoidMessage, Params, name='ui.get') @auth.require(lambda: auth.is_group_member('metric-generators')) def UI_get(self, _request): data = ParamsModel.get_or_insert(CONFIG_DATASTORE_KEY) params = [FieldParams(field_key=field.field_key, values=field.values) for field in data.params] metrics = [Metric(name=metric.name, minimum=metric.minimum, maximum=metric.maximum) for metric in data.metrics] return Params(time=data.time, freq=data.freq, url=data.url, params=params, metrics=metrics) @auth.endpoints_method(Params, message_types.VoidMessage, name='ui.set') @auth.require(lambda: auth.is_group_member('metric-generators')) def UI_set(self, request): logging.debug('Got %s', request) data = ParamsModel.get_or_insert(CONFIG_DATASTORE_KEY) data.time = request.time data.freq = request.freq data.url = request.url data.params = [FieldParamsModel(field_key=field.field_key, values=field.values) for field in request.params] data.metrics = [MetricModel(name=metric.name, minimum=metric.minimum, maximum=metric.maximum) for metric in request.metrics] data.put() return message_types.VoidMessage() def field_generator(dataparams, index, fields): if index == len(dataparams): return [fields] else: key = dataparams[index].field_key return sum((field_generator( dataparams, index+1, fields+[{'key': key, 'value': value}]) for value in dataparams[index].values), []) class CronHandler(webapp2.RequestHandler): def get(self): data = ParamsModel.get_or_insert(CONFIG_DATASTORE_KEY) metric_ranges = {} for metric in data.metrics: metric_ranges[metric.name] = (metric.minimum,metric.maximum) datapacket = {'timeseries': []} logging.debug('There are %d metrics', len(metric_ranges)) fieldlist = field_generator(data.params, 0, []) for metric in metric_ranges: for fields in fieldlist: points = [] for x in xrange(0, int(data.time), int(data.freq)): points.append({'time': x, 'value': random.uniform(*metric_ranges[metric])}) timeseries = {'points': points, 'fields': fields, 'metric': metric} datapacket['timeseries'].append(timeseries) logging.info('Send data to %s', data.url) discovery_url = DISCOVERY_URL % data.url credentials = GoogleCredentials.get_application_default() service = discovery.build(API_NAME, API_VERSION, discoveryServiceUrl=discovery_url, credentials=credentials) _response = service.timeseries().update(body=datapacket).execute() backend_handlers = [ ('/cron', CronHandler) ] WEBAPP = webapp2.WSGIApplication(backend_handlers, debug=True) APPLICATION = endpoints.api_server([LoadTestApi, UIApi])
[((2190, 2241), 'components.auth.endpoints_api', 'auth.endpoints_api', ([], {'name': '"""consoleapp"""', 'version': '"""v1"""'}), "(name='consoleapp', version='v1')\n", (2208, 2241), False, 'from components import auth\n'), ((2670, 2713), 'components.auth.endpoints_api', 'auth.endpoints_api', ([], {'name': '"""ui"""', 'version': '"""v1"""'}), "(name='ui', version='v1')\n", (2688, 2713), False, 'from components import auth\n'), ((5849, 5902), 'webapp2.WSGIApplication', 'webapp2.WSGIApplication', (['backend_handlers'], {'debug': '(True)'}), '(backend_handlers, debug=True)\n', (5872, 5902), False, 'import webapp2\n'), ((5918, 5960), 'endpoints.api_server', 'endpoints.api_server', (['[LoadTestApi, UIApi]'], {}), '([LoadTestApi, UIApi])\n', (5938, 5960), False, 'import endpoints\n'), ((678, 698), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {}), '()\n', (696, 698), False, 'from google.appengine.ext import ndb\n'), ((710, 743), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {'repeated': '(True)'}), '(repeated=True)\n', (728, 743), False, 'from google.appengine.ext import ndb\n'), ((785, 815), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {'default': '""""""'}), "(default='')\n", (803, 815), False, 'from google.appengine.ext import ndb\n'), ((828, 856), 'google.appengine.ext.ndb.FloatProperty', 'ndb.FloatProperty', ([], {'default': '(0)'}), '(default=0)\n', (845, 856), False, 'from google.appengine.ext import ndb\n'), ((869, 899), 'google.appengine.ext.ndb.FloatProperty', 'ndb.FloatProperty', ([], {'default': '(100)'}), '(default=100)\n', (886, 899), False, 'from google.appengine.ext import ndb\n'), ((941, 970), 'google.appengine.ext.ndb.FloatProperty', 'ndb.FloatProperty', ([], {'default': '(10)'}), '(default=10)\n', (958, 970), False, 'from google.appengine.ext import ndb\n'), ((980, 1008), 'google.appengine.ext.ndb.FloatProperty', 'ndb.FloatProperty', ([], {'default': '(1)'}), '(default=1)\n', (997, 1008), False, 'from google.appengine.ext import ndb\n'), ((1017, 1037), 'google.appengine.ext.ndb.StringProperty', 'ndb.StringProperty', ([], {}), '()\n', (1035, 1037), False, 'from google.appengine.ext import ndb\n'), ((1049, 1109), 'google.appengine.ext.ndb.LocalStructuredProperty', 'ndb.LocalStructuredProperty', (['FieldParamsModel'], {'repeated': '(True)'}), '(FieldParamsModel, repeated=True)\n', (1076, 1109), False, 'from google.appengine.ext import ndb\n'), ((1122, 1177), 'google.appengine.ext.ndb.LocalStructuredProperty', 'ndb.LocalStructuredProperty', (['MetricModel'], {'repeated': '(True)'}), '(MetricModel, repeated=True)\n', (1149, 1177), False, 'from google.appengine.ext import ndb\n'), ((1219, 1242), 'protorpc.messages.StringField', 'messages.StringField', (['(1)'], {}), '(1)\n', (1239, 1242), False, 'from protorpc import messages\n'), ((1253, 1276), 'protorpc.messages.StringField', 'messages.StringField', (['(2)'], {}), '(2)\n', (1273, 1276), False, 'from protorpc import messages\n'), ((1319, 1341), 'protorpc.messages.FloatField', 'messages.FloatField', (['(1)'], {}), '(1)\n', (1338, 1341), False, 'from protorpc import messages\n'), ((1352, 1374), 'protorpc.messages.FloatField', 'messages.FloatField', (['(2)'], {}), '(2)\n', (1371, 1374), False, 'from protorpc import messages\n'), ((1428, 1451), 'protorpc.messages.StringField', 'messages.StringField', (['(1)'], {}), '(1)\n', (1448, 1451), False, 'from protorpc import messages\n'), ((1463, 1501), 'protorpc.messages.StringField', 'messages.StringField', (['(2)'], {'repeated': '(True)'}), '(2, repeated=True)\n', (1483, 1501), False, 'from protorpc import messages\n'), ((1545, 1568), 'protorpc.messages.StringField', 'messages.StringField', (['(1)'], {}), '(1)\n', (1565, 1568), False, 'from protorpc import messages\n'), ((1581, 1603), 'protorpc.messages.FloatField', 'messages.FloatField', (['(2)'], {}), '(2)\n', (1600, 1603), False, 'from protorpc import messages\n'), ((1616, 1638), 'protorpc.messages.FloatField', 'messages.FloatField', (['(3)'], {}), '(3)\n', (1635, 1638), False, 'from protorpc import messages\n'), ((1682, 1704), 'protorpc.messages.FloatField', 'messages.FloatField', (['(1)'], {}), '(1)\n', (1701, 1704), False, 'from protorpc import messages\n'), ((1714, 1736), 'protorpc.messages.FloatField', 'messages.FloatField', (['(2)'], {}), '(2)\n', (1733, 1736), False, 'from protorpc import messages\n'), ((1745, 1768), 'protorpc.messages.StringField', 'messages.StringField', (['(3)'], {}), '(3)\n', (1765, 1768), False, 'from protorpc import messages\n'), ((1780, 1832), 'protorpc.messages.MessageField', 'messages.MessageField', (['FieldParams', '(4)'], {'repeated': '(True)'}), '(FieldParams, 4, repeated=True)\n', (1801, 1832), False, 'from protorpc import messages\n'), ((1845, 1892), 'protorpc.messages.MessageField', 'messages.MessageField', (['Metric', '(5)'], {'repeated': '(True)'}), '(Metric, 5, repeated=True)\n', (1866, 1892), False, 'from protorpc import messages\n'), ((1942, 1988), 'protorpc.messages.MessageField', 'messages.MessageField', (['Point', '(1)'], {'repeated': '(True)'}), '(Point, 1, repeated=True)\n', (1963, 1988), False, 'from protorpc import messages\n'), ((2000, 2046), 'protorpc.messages.MessageField', 'messages.MessageField', (['Field', '(2)'], {'repeated': '(True)'}), '(Field, 2, repeated=True)\n', (2021, 2046), False, 'from protorpc import messages\n'), ((2058, 2081), 'protorpc.messages.StringField', 'messages.StringField', (['(3)'], {}), '(3)\n', (2078, 2081), False, 'from protorpc import messages\n'), ((2135, 2186), 'protorpc.messages.MessageField', 'messages.MessageField', (['TimeSeries', '(1)'], {'repeated': '(True)'}), '(TimeSeries, 1, repeated=True)\n', (2156, 2186), False, 'from protorpc import messages\n'), ((2339, 2430), 'components.auth.endpoints_method', 'auth.endpoints_method', (['DataPacket', 'message_types.VoidMessage'], {'name': '"""timeseries.update"""'}), "(DataPacket, message_types.VoidMessage, name=\n 'timeseries.update')\n", (2360, 2430), False, 'from components import auth\n'), ((2794, 2865), 'components.auth.endpoints_method', 'auth.endpoints_method', (['message_types.VoidMessage', 'Params'], {'name': '"""ui.get"""'}), "(message_types.VoidMessage, Params, name='ui.get')\n", (2815, 2865), False, 'from components import auth\n'), ((3453, 3524), 'components.auth.endpoints_method', 'auth.endpoints_method', (['Params', 'message_types.VoidMessage'], {'name': '"""ui.set"""'}), "(Params, message_types.VoidMessage, name='ui.set')\n", (3474, 3524), False, 'from components import auth\n'), ((2639, 2666), 'protorpc.message_types.VoidMessage', 'message_types.VoidMessage', ([], {}), '()\n', (2664, 2666), False, 'from protorpc import message_types\n'), ((3650, 3682), 'logging.debug', 'logging.debug', (['"""Got %s"""', 'request'], {}), "('Got %s', request)\n", (3663, 3682), False, 'import logging\n'), ((4236, 4263), 'protorpc.message_types.VoidMessage', 'message_types.VoidMessage', ([], {}), '()\n', (4261, 4263), False, 'from protorpc import message_types\n'), ((5395, 5436), 'logging.info', 'logging.info', (['"""Send data to %s"""', 'data.url'], {}), "('Send data to %s', data.url)\n", (5407, 5436), False, 'import logging\n'), ((5500, 5543), 'oauth2client.client.GoogleCredentials.get_application_default', 'GoogleCredentials.get_application_default', ([], {}), '()\n', (5541, 5543), False, 'from oauth2client.client import GoogleCredentials\n'), ((5558, 5660), 'apiclient.discovery.build', 'discovery.build', (['API_NAME', 'API_VERSION'], {'discoveryServiceUrl': 'discovery_url', 'credentials': 'credentials'}), '(API_NAME, API_VERSION, discoveryServiceUrl=discovery_url,\n credentials=credentials)\n', (5573, 5660), False, 'from apiclient import discovery\n'), ((2475, 2516), 'components.auth.is_group_member', 'auth.is_group_member', (['"""metric-generators"""'], {}), "('metric-generators')\n", (2495, 2516), False, 'from components import auth\n'), ((2915, 2956), 'components.auth.is_group_member', 'auth.is_group_member', (['"""metric-generators"""'], {}), "('metric-generators')\n", (2935, 2956), False, 'from components import auth\n'), ((3574, 3615), 'components.auth.is_group_member', 'auth.is_group_member', (['"""metric-generators"""'], {}), "('metric-generators')\n", (3594, 3615), False, 'from components import auth\n'), ((5178, 5216), 'random.uniform', 'random.uniform', (['*metric_ranges[metric]'], {}), '(*metric_ranges[metric])\n', (5192, 5216), False, 'import random\n')]
usnistgov/dioptra
src/mitre/securingai/restapi/task_plugin/controller.py
08a08e96c27787915bafc75a483431333e2c70ca
# This Software (Dioptra) is being made available as a public service by the # National Institute of Standards and Technology (NIST), an Agency of the United # States Department of Commerce. This software was developed in part by employees of # NIST and in part by NIST contractors. Copyright in portions of this software that # were developed by NIST contractors has been licensed or assigned to NIST. Pursuant # to Title 17 United States Code Section 105, works of NIST employees are not # subject to copyright protection in the United States. However, NIST may hold # international copyright in software created by its employees and domestic # copyright (or licensing rights) in portions of software that were assigned or # licensed to NIST. To the extent that NIST holds copyright in this software, it is # being made available under the Creative Commons Attribution 4.0 International # license (CC BY 4.0). The disclaimers of the CC BY 4.0 license apply to all parts # of the software developed or licensed by NIST. # # ACCESS THE FULL CC BY 4.0 LICENSE HERE: # https://creativecommons.org/licenses/by/4.0/legalcode """The module defining the task plugin endpoints.""" import uuid from typing import List, Optional import structlog from flask import current_app, jsonify from flask.wrappers import Response from flask_accepts import accepts, responds from flask_restx import Namespace, Resource from injector import inject from structlog.stdlib import BoundLogger from mitre.securingai.restapi.utils import as_api_parser from .errors import TaskPluginDoesNotExistError, TaskPluginUploadError from .model import TaskPlugin, TaskPluginUploadForm, TaskPluginUploadFormData from .schema import TaskPluginSchema, TaskPluginUploadSchema from .service import TaskPluginService LOGGER: BoundLogger = structlog.stdlib.get_logger() api: Namespace = Namespace( "TaskPlugin", description="Task plugin registry operations", ) @api.route("/") class TaskPluginResource(Resource): """Shows a list of all task plugins, and lets you POST to upload new ones.""" @inject def __init__(self, *args, task_plugin_service: TaskPluginService, **kwargs) -> None: self._task_plugin_service = task_plugin_service super().__init__(*args, **kwargs) @responds(schema=TaskPluginSchema(many=True), api=api) def get(self) -> List[TaskPlugin]: """Gets a list of all registered task plugins.""" log: BoundLogger = LOGGER.new( request_id=str(uuid.uuid4()), resource="taskPlugin", request_type="GET" ) log.info("Request received") return self._task_plugin_service.get_all( bucket=current_app.config["AI_PLUGINS_BUCKET"], log=log ) @api.expect(as_api_parser(api, TaskPluginUploadSchema)) @accepts(TaskPluginUploadSchema, api=api) @responds(schema=TaskPluginSchema, api=api) def post(self) -> TaskPlugin: """Registers a new task plugin uploaded via the task plugin upload form.""" log: BoundLogger = LOGGER.new( request_id=str(uuid.uuid4()), resource="taskPlugin", request_type="POST" ) task_plugin_upload_form: TaskPluginUploadForm = TaskPluginUploadForm() log.info("Request received") if not task_plugin_upload_form.validate_on_submit(): log.error("Form validation failed") raise TaskPluginUploadError log.info("Form validation successful") task_plugin_upload_form_data: TaskPluginUploadFormData = ( self._task_plugin_service.extract_data_from_form( task_plugin_upload_form=task_plugin_upload_form, log=log ) ) return self._task_plugin_service.create( task_plugin_upload_form_data=task_plugin_upload_form_data, bucket=current_app.config["AI_PLUGINS_BUCKET"], log=log, ) @api.route("/securingai_builtins") class TaskPluginBuiltinsCollectionResource(Resource): """Shows a list of all builtin task plugins.""" @inject def __init__(self, *args, task_plugin_service: TaskPluginService, **kwargs) -> None: self._task_plugin_service = task_plugin_service super().__init__(*args, **kwargs) @responds(schema=TaskPluginSchema(many=True), api=api) def get(self) -> List[TaskPlugin]: """Gets a list of all available builtin task plugins.""" log: BoundLogger = LOGGER.new( request_id=str(uuid.uuid4()), resource="taskPluginBuiltinCollection", request_type="GET", ) log.info("Request received") return self._task_plugin_service.get_all_in_collection( collection="securingai_builtins", bucket=current_app.config["AI_PLUGINS_BUCKET"], log=log, ) @api.route("/securingai_builtins/<string:taskPluginName>") @api.param( "taskPluginName", "A unique string identifying a task plugin package within securingai_builtins " "collection.", ) class TaskPluginBuiltinCollectionNameResource(Resource): """Shows a single builtin task plugin package.""" @inject def __init__(self, *args, task_plugin_service: TaskPluginService, **kwargs) -> None: self._task_plugin_service = task_plugin_service super().__init__(*args, **kwargs) @responds(schema=TaskPluginSchema, api=api) def get(self, taskPluginName: str) -> TaskPlugin: """Gets a builtin task plugin by its unique name.""" log: BoundLogger = LOGGER.new( request_id=str(uuid.uuid4()), resource="taskPluginBuiltinCollectionName", request_type="GET", ) log.info("Request received") task_plugin: Optional[ TaskPlugin ] = self._task_plugin_service.get_by_name_in_collection( collection="securingai_builtins", task_plugin_name=taskPluginName, bucket=current_app.config["AI_PLUGINS_BUCKET"], log=log, ) if task_plugin is None: log.error( "TaskPlugin not found", task_plugin_name=taskPluginName, collection="securingai_builtins", ) raise TaskPluginDoesNotExistError return task_plugin @api.route("/securingai_custom") class TaskPluginCustomCollectionResource(Resource): """Shows a list of all custom task plugins.""" @inject def __init__(self, *args, task_plugin_service: TaskPluginService, **kwargs) -> None: self._task_plugin_service = task_plugin_service super().__init__(*args, **kwargs) @responds(schema=TaskPluginSchema(many=True), api=api) def get(self) -> List[TaskPlugin]: """Gets a list of all registered custom task plugins.""" log: BoundLogger = LOGGER.new( request_id=str(uuid.uuid4()), resource="taskPluginCustomCollection", request_type="GET", ) log.info("Request received") return self._task_plugin_service.get_all_in_collection( collection="securingai_custom", bucket=current_app.config["AI_PLUGINS_BUCKET"], log=log, ) @api.route("/securingai_custom/<string:taskPluginName>") @api.param( "taskPluginName", "A unique string identifying a task plugin package within securingai_custom " "collection.", ) class TaskPluginCustomCollectionNameResource(Resource): """Shows a single custom task plugin package and lets you delete it.""" @inject def __init__(self, *args, task_plugin_service: TaskPluginService, **kwargs) -> None: self._task_plugin_service = task_plugin_service super().__init__(*args, **kwargs) @responds(schema=TaskPluginSchema, api=api) def get(self, taskPluginName: str) -> TaskPlugin: """Gets a custom task plugin by its unique name.""" log: BoundLogger = LOGGER.new( request_id=str(uuid.uuid4()), resource="taskPluginCustomCollectionName", request_type="GET", ) log.info("Request received") task_plugin: Optional[ TaskPlugin ] = self._task_plugin_service.get_by_name_in_collection( collection="securingai_custom", task_plugin_name=taskPluginName, bucket=current_app.config["AI_PLUGINS_BUCKET"], log=log, ) if task_plugin is None: log.error( "TaskPlugin not found", task_plugin_name=taskPluginName, collection="securingai_custom", ) raise TaskPluginDoesNotExistError return task_plugin def delete(self, taskPluginName: str) -> Response: """Deletes a custom task plugin by its unique name.""" log: BoundLogger = LOGGER.new( request_id=str(uuid.uuid4()), resource="taskPluginCustomCollectionName", task_plugin_name=taskPluginName, request_type="DELETE", ) log.info("Request received") task_plugins: List[TaskPlugin] = self._task_plugin_service.delete( collection="securingai_custom", task_plugin_name=taskPluginName, bucket=current_app.config["AI_PLUGINS_BUCKET"], log=log, ) name: List[str] = [x.task_plugin_name for x in task_plugins] return jsonify( # type: ignore dict(status="Success", collection="securingai_custom", taskPluginName=name) )
[((1802, 1831), 'structlog.stdlib.get_logger', 'structlog.stdlib.get_logger', ([], {}), '()\n', (1829, 1831), False, 'import structlog\n'), ((1850, 1920), 'flask_restx.Namespace', 'Namespace', (['"""TaskPlugin"""'], {'description': '"""Task plugin registry operations"""'}), "('TaskPlugin', description='Task plugin registry operations')\n", (1859, 1920), False, 'from flask_restx import Namespace, Resource\n'), ((2789, 2829), 'flask_accepts.accepts', 'accepts', (['TaskPluginUploadSchema'], {'api': 'api'}), '(TaskPluginUploadSchema, api=api)\n', (2796, 2829), False, 'from flask_accepts import accepts, responds\n'), ((2835, 2877), 'flask_accepts.responds', 'responds', ([], {'schema': 'TaskPluginSchema', 'api': 'api'}), '(schema=TaskPluginSchema, api=api)\n', (2843, 2877), False, 'from flask_accepts import accepts, responds\n'), ((5319, 5361), 'flask_accepts.responds', 'responds', ([], {'schema': 'TaskPluginSchema', 'api': 'api'}), '(schema=TaskPluginSchema, api=api)\n', (5327, 5361), False, 'from flask_accepts import accepts, responds\n'), ((7724, 7766), 'flask_accepts.responds', 'responds', ([], {'schema': 'TaskPluginSchema', 'api': 'api'}), '(schema=TaskPluginSchema, api=api)\n', (7732, 7766), False, 'from flask_accepts import accepts, responds\n'), ((2740, 2782), 'mitre.securingai.restapi.utils.as_api_parser', 'as_api_parser', (['api', 'TaskPluginUploadSchema'], {}), '(api, TaskPluginUploadSchema)\n', (2753, 2782), False, 'from mitre.securingai.restapi.utils import as_api_parser\n'), ((2491, 2503), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (2501, 2503), False, 'import uuid\n'), ((3062, 3074), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (3072, 3074), False, 'import uuid\n'), ((4455, 4467), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (4465, 4467), False, 'import uuid\n'), ((5543, 5555), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (5553, 5555), False, 'import uuid\n'), ((6846, 6858), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (6856, 6858), False, 'import uuid\n'), ((7947, 7959), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (7957, 7959), False, 'import uuid\n'), ((8862, 8874), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (8872, 8874), False, 'import uuid\n')]
mjmaenpaa/dulwich
dulwich/tests/test_lru_cache.py
d13a0375f4cc3099ff1c6edacda97f317c28f67a
# Copyright (C) 2006, 2008 Canonical Ltd # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache # License, Version 2.0. # """Tests for the lru_cache module.""" from dulwich import ( lru_cache, ) from dulwich.tests import ( TestCase, ) class TestLRUCache(TestCase): """Test that LRU cache properly keeps track of entries.""" def test_cache_size(self): cache = lru_cache.LRUCache(max_cache=10) self.assertEqual(10, cache.cache_size()) cache = lru_cache.LRUCache(max_cache=256) self.assertEqual(256, cache.cache_size()) cache.resize(512) self.assertEqual(512, cache.cache_size()) def test_missing(self): cache = lru_cache.LRUCache(max_cache=10) self.assertFalse('foo' in cache) self.assertRaises(KeyError, cache.__getitem__, 'foo') cache['foo'] = 'bar' self.assertEqual('bar', cache['foo']) self.assertTrue('foo' in cache) self.assertFalse('bar' in cache) def test_map_None(self): # Make sure that we can properly map None as a key. cache = lru_cache.LRUCache(max_cache=10) self.assertFalse(None in cache) cache[None] = 1 self.assertEqual(1, cache[None]) cache[None] = 2 self.assertEqual(2, cache[None]) # Test the various code paths of __getitem__, to make sure that we can # handle when None is the key for the LRU and the MRU cache[1] = 3 cache[None] = 1 cache[None] cache[1] cache[None] self.assertEqual([None, 1], [n.key for n in cache._walk_lru()]) def test_add__null_key(self): cache = lru_cache.LRUCache(max_cache=10) self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1) def test_overflow(self): """Adding extra entries will pop out old ones.""" cache = lru_cache.LRUCache(max_cache=1, after_cleanup_count=1) cache['foo'] = 'bar' # With a max cache of 1, adding 'baz' should pop out 'foo' cache['baz'] = 'biz' self.assertFalse('foo' in cache) self.assertTrue('baz' in cache) self.assertEqual('biz', cache['baz']) def test_by_usage(self): """Accessing entries bumps them up in priority.""" cache = lru_cache.LRUCache(max_cache=2) cache['baz'] = 'biz' cache['foo'] = 'bar' self.assertEqual('biz', cache['baz']) # This must kick out 'foo' because it was the last accessed cache['nub'] = 'in' self.assertFalse('foo' in cache) def test_cleanup(self): """Test that we can use a cleanup function.""" cleanup_called = [] def cleanup_func(key, val): cleanup_called.append((key, val)) cache = lru_cache.LRUCache(max_cache=2, after_cleanup_count=2) cache.add('baz', '1', cleanup=cleanup_func) cache.add('foo', '2', cleanup=cleanup_func) cache.add('biz', '3', cleanup=cleanup_func) self.assertEqual([('baz', '1')], cleanup_called) # 'foo' is now most recent, so final cleanup will call it last cache['foo'] cache.clear() self.assertEqual([('baz', '1'), ('biz', '3'), ('foo', '2')], cleanup_called) def test_cleanup_on_replace(self): """Replacing an object should cleanup the old value.""" cleanup_called = [] def cleanup_func(key, val): cleanup_called.append((key, val)) cache = lru_cache.LRUCache(max_cache=2) cache.add(1, 10, cleanup=cleanup_func) cache.add(2, 20, cleanup=cleanup_func) cache.add(2, 25, cleanup=cleanup_func) self.assertEqual([(2, 20)], cleanup_called) self.assertEqual(25, cache[2]) # Even __setitem__ should make sure cleanup() is called cache[2] = 26 self.assertEqual([(2, 20), (2, 25)], cleanup_called) def test_len(self): cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10) cache[1] = 10 cache[2] = 20 cache[3] = 30 cache[4] = 40 self.assertEqual(4, len(cache)) cache[5] = 50 cache[6] = 60 cache[7] = 70 cache[8] = 80 self.assertEqual(8, len(cache)) cache[1] = 15 # replacement self.assertEqual(8, len(cache)) cache[9] = 90 cache[10] = 100 cache[11] = 110 # We hit the max self.assertEqual(10, len(cache)) self.assertEqual([11, 10, 9, 1, 8, 7, 6, 5, 4, 3], [n.key for n in cache._walk_lru()]) def test_cleanup_shrinks_to_after_clean_count(self): cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=3) cache.add(1, 10) cache.add(2, 20) cache.add(3, 25) cache.add(4, 30) cache.add(5, 35) self.assertEqual(5, len(cache)) # This will bump us over the max, which causes us to shrink down to # after_cleanup_cache size cache.add(6, 40) self.assertEqual(3, len(cache)) def test_after_cleanup_larger_than_max(self): cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=10) self.assertEqual(5, cache._after_cleanup_count) def test_after_cleanup_none(self): cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=None) # By default _after_cleanup_size is 80% of the normal size self.assertEqual(4, cache._after_cleanup_count) def test_cleanup_2(self): cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2) # Add these in order cache.add(1, 10) cache.add(2, 20) cache.add(3, 25) cache.add(4, 30) cache.add(5, 35) self.assertEqual(5, len(cache)) # Force a compaction cache.cleanup() self.assertEqual(2, len(cache)) def test_preserve_last_access_order(self): cache = lru_cache.LRUCache(max_cache=5) # Add these in order cache.add(1, 10) cache.add(2, 20) cache.add(3, 25) cache.add(4, 30) cache.add(5, 35) self.assertEqual([5, 4, 3, 2, 1], [n.key for n in cache._walk_lru()]) # Now access some randomly cache[2] cache[5] cache[3] cache[2] self.assertEqual([2, 3, 5, 4, 1], [n.key for n in cache._walk_lru()]) def test_get(self): cache = lru_cache.LRUCache(max_cache=5) cache.add(1, 10) cache.add(2, 20) self.assertEqual(20, cache.get(2)) self.assertEqual(None, cache.get(3)) obj = object() self.assertTrue(obj is cache.get(3, obj)) self.assertEqual([2, 1], [n.key for n in cache._walk_lru()]) self.assertEqual(10, cache.get(1)) self.assertEqual([1, 2], [n.key for n in cache._walk_lru()]) def test_keys(self): cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5) cache[1] = 2 cache[2] = 3 cache[3] = 4 self.assertEqual([1, 2, 3], sorted(cache.keys())) cache[4] = 5 cache[5] = 6 cache[6] = 7 self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys())) def test_resize_smaller(self): cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4) cache[1] = 2 cache[2] = 3 cache[3] = 4 cache[4] = 5 cache[5] = 6 self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys())) cache[6] = 7 self.assertEqual([3, 4, 5, 6], sorted(cache.keys())) # Now resize to something smaller, which triggers a cleanup cache.resize(max_cache=3, after_cleanup_count=2) self.assertEqual([5, 6], sorted(cache.keys())) # Adding something will use the new size cache[7] = 8 self.assertEqual([5, 6, 7], sorted(cache.keys())) cache[8] = 9 self.assertEqual([7, 8], sorted(cache.keys())) def test_resize_larger(self): cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4) cache[1] = 2 cache[2] = 3 cache[3] = 4 cache[4] = 5 cache[5] = 6 self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys())) cache[6] = 7 self.assertEqual([3, 4, 5, 6], sorted(cache.keys())) cache.resize(max_cache=8, after_cleanup_count=6) self.assertEqual([3, 4, 5, 6], sorted(cache.keys())) cache[7] = 8 cache[8] = 9 cache[9] = 10 cache[10] = 11 self.assertEqual([3, 4, 5, 6, 7, 8, 9, 10], sorted(cache.keys())) cache[11] = 12 # triggers cleanup back to new after_cleanup_count self.assertEqual([6, 7, 8, 9, 10, 11], sorted(cache.keys())) class TestLRUSizeCache(TestCase): def test_basic_init(self): cache = lru_cache.LRUSizeCache() self.assertEqual(2048, cache._max_cache) self.assertEqual(int(cache._max_size*0.8), cache._after_cleanup_size) self.assertEqual(0, cache._value_size) def test_add__null_key(self): cache = lru_cache.LRUSizeCache() self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1) def test_add_tracks_size(self): cache = lru_cache.LRUSizeCache() self.assertEqual(0, cache._value_size) cache.add('my key', 'my value text') self.assertEqual(13, cache._value_size) def test_remove_tracks_size(self): cache = lru_cache.LRUSizeCache() self.assertEqual(0, cache._value_size) cache.add('my key', 'my value text') self.assertEqual(13, cache._value_size) node = cache._cache['my key'] cache._remove_node(node) self.assertEqual(0, cache._value_size) def test_no_add_over_size(self): """Adding a large value may not be cached at all.""" cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5) self.assertEqual(0, cache._value_size) self.assertEqual({}, cache.items()) cache.add('test', 'key') self.assertEqual(3, cache._value_size) self.assertEqual({'test': 'key'}, cache.items()) cache.add('test2', 'key that is too big') self.assertEqual(3, cache._value_size) self.assertEqual({'test':'key'}, cache.items()) # If we would add a key, only to cleanup and remove all cached entries, # then obviously that value should not be stored cache.add('test3', 'bigkey') self.assertEqual(3, cache._value_size) self.assertEqual({'test':'key'}, cache.items()) cache.add('test4', 'bikey') self.assertEqual(3, cache._value_size) self.assertEqual({'test':'key'}, cache.items()) def test_no_add_over_size_cleanup(self): """If a large value is not cached, we will call cleanup right away.""" cleanup_calls = [] def cleanup(key, value): cleanup_calls.append((key, value)) cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5) self.assertEqual(0, cache._value_size) self.assertEqual({}, cache.items()) cache.add('test', 'key that is too big', cleanup=cleanup) # key was not added self.assertEqual(0, cache._value_size) self.assertEqual({}, cache.items()) # and cleanup was called self.assertEqual([('test', 'key that is too big')], cleanup_calls) def test_adding_clears_cache_based_on_size(self): """The cache is cleared in LRU order until small enough""" cache = lru_cache.LRUSizeCache(max_size=20) cache.add('key1', 'value') # 5 chars cache.add('key2', 'value2') # 6 chars cache.add('key3', 'value23') # 7 chars self.assertEqual(5+6+7, cache._value_size) cache['key2'] # reference key2 so it gets a newer reference time cache.add('key4', 'value234') # 8 chars, over limit # We have to remove 2 keys to get back under limit self.assertEqual(6+8, cache._value_size) self.assertEqual({'key2':'value2', 'key4':'value234'}, cache.items()) def test_adding_clears_to_after_cleanup_size(self): cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10) cache.add('key1', 'value') # 5 chars cache.add('key2', 'value2') # 6 chars cache.add('key3', 'value23') # 7 chars self.assertEqual(5+6+7, cache._value_size) cache['key2'] # reference key2 so it gets a newer reference time cache.add('key4', 'value234') # 8 chars, over limit # We have to remove 3 keys to get back under limit self.assertEqual(8, cache._value_size) self.assertEqual({'key4':'value234'}, cache.items()) def test_custom_sizes(self): def size_of_list(lst): return sum(len(x) for x in lst) cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10, compute_size=size_of_list) cache.add('key1', ['val', 'ue']) # 5 chars cache.add('key2', ['val', 'ue2']) # 6 chars cache.add('key3', ['val', 'ue23']) # 7 chars self.assertEqual(5+6+7, cache._value_size) cache['key2'] # reference key2 so it gets a newer reference time cache.add('key4', ['value', '234']) # 8 chars, over limit # We have to remove 3 keys to get back under limit self.assertEqual(8, cache._value_size) self.assertEqual({'key4':['value', '234']}, cache.items()) def test_cleanup(self): cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10) # Add these in order cache.add('key1', 'value') # 5 chars cache.add('key2', 'value2') # 6 chars cache.add('key3', 'value23') # 7 chars self.assertEqual(5+6+7, cache._value_size) cache.cleanup() # Only the most recent fits after cleaning up self.assertEqual(7, cache._value_size) def test_keys(self): cache = lru_cache.LRUSizeCache(max_size=10) cache[1] = 'a' cache[2] = 'b' cache[3] = 'cdef' self.assertEqual([1, 2, 3], sorted(cache.keys())) def test_resize_smaller(self): cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9) cache[1] = 'abc' cache[2] = 'def' cache[3] = 'ghi' cache[4] = 'jkl' # Triggers a cleanup self.assertEqual([2, 3, 4], sorted(cache.keys())) # Resize should also cleanup again cache.resize(max_size=6, after_cleanup_size=4) self.assertEqual([4], sorted(cache.keys())) # Adding should use the new max size cache[5] = 'mno' self.assertEqual([4, 5], sorted(cache.keys())) cache[6] = 'pqr' self.assertEqual([6], sorted(cache.keys())) def test_resize_larger(self): cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9) cache[1] = 'abc' cache[2] = 'def' cache[3] = 'ghi' cache[4] = 'jkl' # Triggers a cleanup self.assertEqual([2, 3, 4], sorted(cache.keys())) cache.resize(max_size=15, after_cleanup_size=12) self.assertEqual([2, 3, 4], sorted(cache.keys())) cache[5] = 'mno' cache[6] = 'pqr' self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys())) cache[7] = 'stu' self.assertEqual([4, 5, 6, 7], sorted(cache.keys()))
[((1169, 1201), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(10)'}), '(max_cache=10)\n', (1187, 1201), False, 'from dulwich import lru_cache\n'), ((1268, 1301), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(256)'}), '(max_cache=256)\n', (1286, 1301), False, 'from dulwich import lru_cache\n'), ((1474, 1506), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(10)'}), '(max_cache=10)\n', (1492, 1506), False, 'from dulwich import lru_cache\n'), ((1874, 1906), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(10)'}), '(max_cache=10)\n', (1892, 1906), False, 'from dulwich import lru_cache\n'), ((2443, 2475), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(10)'}), '(max_cache=10)\n', (2461, 2475), False, 'from dulwich import lru_cache\n'), ((2653, 2707), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(1)', 'after_cleanup_count': '(1)'}), '(max_cache=1, after_cleanup_count=1)\n', (2671, 2707), False, 'from dulwich import lru_cache\n'), ((3068, 3099), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(2)'}), '(max_cache=2)\n', (3086, 3099), False, 'from dulwich import lru_cache\n'), ((3556, 3610), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(2)', 'after_cleanup_count': '(2)'}), '(max_cache=2, after_cleanup_count=2)\n', (3574, 3610), False, 'from dulwich import lru_cache\n'), ((4282, 4313), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(2)'}), '(max_cache=2)\n', (4300, 4313), False, 'from dulwich import lru_cache\n'), ((4736, 4792), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(10)', 'after_cleanup_count': '(10)'}), '(max_cache=10, after_cleanup_count=10)\n', (4754, 4792), False, 'from dulwich import lru_cache\n'), ((5463, 5517), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)', 'after_cleanup_count': '(3)'}), '(max_cache=5, after_cleanup_count=3)\n', (5481, 5517), False, 'from dulwich import lru_cache\n'), ((5928, 5983), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)', 'after_cleanup_count': '(10)'}), '(max_cache=5, after_cleanup_count=10)\n', (5946, 5983), False, 'from dulwich import lru_cache\n'), ((6096, 6153), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)', 'after_cleanup_count': 'None'}), '(max_cache=5, after_cleanup_count=None)\n', (6114, 6153), False, 'from dulwich import lru_cache\n'), ((6324, 6378), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)', 'after_cleanup_count': '(2)'}), '(max_cache=5, after_cleanup_count=2)\n', (6342, 6378), False, 'from dulwich import lru_cache\n'), ((6732, 6763), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)'}), '(max_cache=5)\n', (6750, 6763), False, 'from dulwich import lru_cache\n'), ((7221, 7252), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)'}), '(max_cache=5)\n', (7239, 7252), False, 'from dulwich import lru_cache\n'), ((7688, 7742), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)', 'after_cleanup_count': '(5)'}), '(max_cache=5, after_cleanup_count=5)\n', (7706, 7742), False, 'from dulwich import lru_cache\n'), ((8044, 8098), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)', 'after_cleanup_count': '(4)'}), '(max_cache=5, after_cleanup_count=4)\n', (8062, 8098), False, 'from dulwich import lru_cache\n'), ((8785, 8839), 'dulwich.lru_cache.LRUCache', 'lru_cache.LRUCache', ([], {'max_cache': '(5)', 'after_cleanup_count': '(4)'}), '(max_cache=5, after_cleanup_count=4)\n', (8803, 8839), False, 'from dulwich import lru_cache\n'), ((9597, 9621), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {}), '()\n', (9619, 9621), False, 'from dulwich import lru_cache\n'), ((9847, 9871), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {}), '()\n', (9869, 9871), False, 'from dulwich import lru_cache\n'), ((9998, 10022), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {}), '()\n', (10020, 10022), False, 'from dulwich import lru_cache\n'), ((10219, 10243), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {}), '()\n', (10241, 10243), False, 'from dulwich import lru_cache\n'), ((10617, 10674), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(10)', 'after_cleanup_size': '(5)'}), '(max_size=10, after_cleanup_size=5)\n', (10639, 10674), False, 'from dulwich import lru_cache\n'), ((11722, 11779), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(10)', 'after_cleanup_size': '(5)'}), '(max_size=10, after_cleanup_size=5)\n', (11744, 11779), False, 'from dulwich import lru_cache\n'), ((12302, 12337), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(20)'}), '(max_size=20)\n', (12324, 12337), False, 'from dulwich import lru_cache\n'), ((12944, 13002), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(20)', 'after_cleanup_size': '(10)'}), '(max_size=20, after_cleanup_size=10)\n', (12966, 13002), False, 'from dulwich import lru_cache\n'), ((13617, 13707), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(20)', 'after_cleanup_size': '(10)', 'compute_size': 'size_of_list'}), '(max_size=20, after_cleanup_size=10, compute_size=\n size_of_list)\n', (13639, 13707), False, 'from dulwich import lru_cache\n'), ((14307, 14365), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(20)', 'after_cleanup_size': '(10)'}), '(max_size=20, after_cleanup_size=10)\n', (14329, 14365), False, 'from dulwich import lru_cache\n'), ((14753, 14788), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(10)'}), '(max_size=10)\n', (14775, 14788), False, 'from dulwich import lru_cache\n'), ((14972, 15029), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(10)', 'after_cleanup_size': '(9)'}), '(max_size=10, after_cleanup_size=9)\n', (14994, 15029), False, 'from dulwich import lru_cache\n'), ((15620, 15677), 'dulwich.lru_cache.LRUSizeCache', 'lru_cache.LRUSizeCache', ([], {'max_size': '(10)', 'after_cleanup_size': '(9)'}), '(max_size=10, after_cleanup_size=9)\n', (15642, 15677), False, 'from dulwich import lru_cache\n')]
pedrotari7/advent_of_code
py/2016/5B.py
98d5bc8d903435624a019a5702f5421d7b4ef8c8
import md5 (i,count) = (0,0) password = ['']*8 while 1: key = 'reyedfim' + str(i) md = md5.new(key).hexdigest() if md[:5] == '00000': index = int(md[5],16) if index < len(password) and password[index]=='': password[index] = md[6] count += 1 if count == 8: break i+=1 print ''.join(password)
[]
lsica-scopely/mgear4
release/scripts/mgear/shifter_epic_components/EPIC_foot_01/__init__.py
28ed5d66370a9516da05d93d447bfc15f4c0c9f4
import pymel.core as pm import ast from pymel.core import datatypes from mgear.shifter import component from mgear.core import node, applyop, vector from mgear.core import attribute, transform, primitive class Component(component.Main): """Shifter component Class""" # ===================================================== # OBJECTS # ===================================================== def addObjects(self): """Add all the objects needed to create the component.""" # joint Description Names jd_names = ast.literal_eval( self.settings["jointNamesDescription_custom"] ) jdn_ball = jd_names[0] self.up_axis = pm.upAxis(q=True, axis=True) self.div_count = len(self.guide.apos) - 5 plane = [self.guide.apos[0], self.guide.apos[-4], self.guide.apos[-3]] self.normal = self.getNormalFromPos(plane) self.binormal = self.getBiNormalFromPos(plane) # Heel --------------------------------------------- # bank pivot t = transform.getTransformLookingAt( self.guide.pos["heel"], self.guide.apos[-4], self.normal, "xz", self.negate, ) t = transform.setMatrixPosition(t, self.guide.pos["inpivot"]) self.in_npo = primitive.addTransform( self.root, self.getName("in_npo"), t ) self.in_piv = primitive.addTransform( self.in_npo, self.getName("in_piv"), t ) t = transform.setMatrixPosition(t, self.guide.pos["outpivot"]) self.out_piv = primitive.addTransform( self.in_piv, self.getName("out_piv"), t ) # heel t = transform.getTransformLookingAt( self.guide.pos["heel"], self.guide.apos[-4], self.normal, "xz", self.negate, ) self.heel_loc = primitive.addTransform( self.out_piv, self.getName("heel_loc"), t ) attribute.setRotOrder(self.heel_loc, "YZX") self.heel_ctl = self.addCtl( self.heel_loc, "heel_ctl", t, self.color_ik, "sphere", w=self.size * 0.1, tp=self.parentCtlTag, ) attribute.setKeyableAttributes(self.heel_ctl, self.r_params) # Tip ---------------------------------------------- if self.up_axis == "y": v = datatypes.Vector( self.guide.apos[-5].x, self.guide.pos["heel"].y, self.guide.apos[-5].z, ) else: v = datatypes.Vector( self.guide.apos[-5].x, self.guide.apos[-5].y, self.guide.pos["heel"].z, ) t = transform.setMatrixPosition(t, v) self.tip_ctl = self.addCtl( self.heel_ctl, "tip_ctl", t, self.color_ik, "circle", w=self.size, tp=self.heel_ctl, ) attribute.setKeyableAttributes(self.tip_ctl, self.r_params) # Roll --------------------------------------------- if self.settings["useRollCtl"]: t = transform.getTransformLookingAt( self.guide.pos["heel"], self.guide.apos[-4], self.normal, "xz", self.negate, ) t = transform.setMatrixPosition(t, self.guide.pos["root"]) self.roll_np = primitive.addTransform( self.root, self.getName("roll_npo"), t ) self.roll_ctl = self.addCtl( self.roll_np, "roll_ctl", t, self.color_ik, "cylinder", w=self.size * 0.5, h=self.size * 0.5, ro=datatypes.Vector(3.1415 * 0.5, 0, 0), tp=self.tip_ctl, ) attribute.setKeyableAttributes(self.roll_ctl, ["rx", "rz"]) # Backward Controlers ------------------------------ bk_pos = self.guide.apos[1:-3] bk_pos.reverse() parent = self.tip_ctl self.bk_ctl = [] self.bk_loc = [] self.previousTag = self.tip_ctl for i, pos in enumerate(bk_pos): if i == 0: t = transform.getTransform(self.heel_ctl) t = transform.setMatrixPosition(t, pos) else: direction = bk_pos[i - 1] t = transform.getTransformLookingAt( pos, direction, self.normal, "xz", self.negate ) bk_loc = primitive.addTransform( parent, self.getName("bk%s_loc" % i), t ) bk_ctl = self.addCtl( bk_loc, "bk%s_ctl" % i, t, self.color_ik, "sphere", w=self.size * 0.15, tp=self.previousTag, ) attribute.setKeyableAttributes(bk_ctl, self.r_params) self.previousTag = bk_ctl self.bk_loc.append(bk_loc) self.bk_ctl.append(bk_ctl) parent = bk_ctl # FK Reference ------------------------------------ self.fk_ref = primitive.addTransformFromPos( self.bk_ctl[-1], self.getName("fk_ref"), self.guide.apos[0] ) self.fk_npo = primitive.addTransform( self.fk_ref, self.getName("fk0_npo"), transform.getTransform(self.bk_ctl[-1]), ) # Forward Controlers ------------------------------ self.fk_ctl = [] self.fk_loc = [] parent = self.fk_npo self.previousTag = self.tip_ctl for i, bk_ctl in enumerate(reversed(self.bk_ctl[1:])): if i == len(self.bk_ctl) - 2: t = transform.getTransform(self.tip_ctl) v = transform.getTranslation(bk_ctl) t = transform.setMatrixPosition(t, v) else: t = transform.getTransform(bk_ctl) dist = vector.getDistance( self.guide.apos[i + 1], self.guide.apos[i + 2] ) fk_loc = primitive.addTransform( parent, self.getName("fk%s_loc" % i), t ) po_vec = datatypes.Vector(dist * 0.5 * self.n_factor, 0, 0) fk_ctl = self.addCtl( fk_loc, "fk%s_ctl" % i, t, self.color_fk, "cube", w=dist, h=self.size * 0.5, d=self.size * 0.5, po=po_vec, tp=self.previousTag, ) self.previousTag = fk_ctl attribute.setKeyableAttributes(fk_ctl) if i: name = jdn_ball + str(i) else: name = jdn_ball self.jnt_pos.append([fk_ctl, name]) parent = fk_ctl self.fk_ctl.append(fk_ctl) self.fk_loc.append(fk_loc) # ===================================================== # ATTRIBUTES # ===================================================== def addAttributes(self): """Create the anim and setupr rig attributes for the component""" # Anim ------------------------------------------- # Roll Angles if not self.settings["useRollCtl"]: self.roll_att = self.addAnimParam( "roll", "Roll", "double", 0, -180, 180 ) self.bank_att = self.addAnimParam( "bank", "Bank", "double", 0, -180, 180 ) self.angles_att = [ self.addAnimParam("angle_%s" % i, "Angle %s" % i, "double", -20) for i in range(self.div_count) ] # Setup ------------------------------------------ self.blend_att = self.addSetupParam( "blend", "Fk/Ik Blend", "double", 1, 0, 1 ) # ===================================================== # OPERATORS # ===================================================== def addOperators(self): """Create operators and set the relations for the component rig Apply operators, constraints, expressions to the hierarchy. In order to keep the code clean and easier to debug, we shouldn't create any new object in this method. """ # Visibilities ------------------------------------- try: # ik if self.settings["useRollCtl"]: for shp in self.roll_ctl.getShapes(): pm.connectAttr(self.blend_att, shp.attr("visibility")) for bk_ctl in self.bk_ctl: for shp in bk_ctl.getShapes(): pm.connectAttr(self.blend_att, shp.attr("visibility")) for shp in self.heel_ctl.getShapes(): pm.connectAttr(self.blend_att, shp.attr("visibility")) for shp in self.tip_ctl.getShapes(): pm.connectAttr(self.blend_att, shp.attr("visibility")) except RuntimeError: pm.displayInfo("Visibility already connect") # Roll / Bank -------------------------------------- if self.settings["useRollCtl"]: # Using the controler self.roll_att = self.roll_ctl.attr("rz") self.bank_att = self.roll_ctl.attr("rx") clamp_node = node.createClampNode( [self.roll_att, self.bank_att, self.bank_att], [0, -180, 0], [180, 0, 180], ) inAdd_nod = node.createAddNode( clamp_node.outputB, pm.getAttr(self.in_piv.attr("rx")) * self.n_factor, ) pm.connectAttr(clamp_node.outputR, self.heel_loc.attr("rz")) pm.connectAttr(clamp_node.outputG, self.out_piv.attr("rx")) pm.connectAttr(inAdd_nod.output, self.in_piv.attr("rx")) # Reverse Controler offset ------------------------- angle_outputs = node.createAddNodeMulti(self.angles_att) for i, bk_loc in enumerate(reversed(self.bk_loc)): if i == 0: # First inpu = self.roll_att min_input = self.angles_att[i] elif i == len(self.angles_att): # Last sub_nod = node.createSubNode( self.roll_att, angle_outputs[i - 1] ) inpu = sub_nod.output min_input = -360 else: # Others sub_nod = node.createSubNode( self.roll_att, angle_outputs[i - 1] ) inpu = sub_nod.output min_input = self.angles_att[i] clamp_node = node.createClampNode(inpu, min_input, 0) add_node = node.createAddNode( clamp_node.outputR, bk_loc.getAttr("rz") ) pm.connectAttr(add_node.output, bk_loc.attr("rz")) # Reverse compensation ----------------------------- for i, fk_loc in enumerate(self.fk_loc): bk_ctl = self.bk_ctl[-i - 1] bk_loc = self.bk_loc[-i - 1] fk_ctl = self.fk_ctl[i] # Inverse Rotorder o_node = applyop.gear_inverseRotorder_op(bk_ctl, fk_ctl) pm.connectAttr(o_node.output, bk_loc.attr("ro")) pm.connectAttr(fk_ctl.attr("ro"), fk_loc.attr("ro")) attribute.lockAttribute(bk_ctl, "ro") # Compensate the backward rotation # ik addx_node = node.createAddNode( bk_ctl.attr("rx"), bk_loc.attr("rx") ) addy_node = node.createAddNode( bk_ctl.attr("ry"), bk_loc.attr("ry") ) addz_node = node.createAddNode( bk_ctl.attr("rz"), bk_loc.attr("rz") ) addz_node = node.createAddNode( addz_node.output, -bk_loc.getAttr("rz") - fk_loc.getAttr("rz") ) neg_node = node.createMulNode( [addx_node.output, addy_node.output, addz_node.output], [-1, -1, -1], ) add_node = node.createAddNode( neg_node.outputY.get() * -1, neg_node.outputY ) ik_outputs = [neg_node.outputX, add_node.output, neg_node.outputZ] # fk fk_outputs = [0, 0, fk_loc.getAttr("rz")] # blend blend_node = node.createBlendNode( ik_outputs, fk_outputs, self.blend_att ) pm.connectAttr(blend_node.output, fk_loc.attr("rotate")) return # ===================================================== # CONNECTOR # ===================================================== def setRelation(self): """Set the relation beetween object from guide to rig""" self.relatives["root"] = self.fk_ctl[0] self.relatives["heel"] = self.fk_ctl[0] self.relatives["inpivot"] = self.fk_ctl[0] self.relatives["outpivot"] = self.fk_ctl[0] self.controlRelatives["root"] = self.fk_ctl[0] self.controlRelatives["heel"] = self.fk_ctl[0] self.controlRelatives["inpivot"] = self.fk_ctl[0] self.controlRelatives["outpivot"] = self.fk_ctl[0] self.jointRelatives["root"] = 0 self.jointRelatives["heel"] = 0 self.jointRelatives["inpivot"] = 0 self.jointRelatives["outpivot"] = 0 for i in range(self.div_count): self.relatives["%s_loc" % i] = self.fk_ctl[i] self.jointRelatives["%s_loc" % i] = i if self.div_count > 0: self.relatives["%s_loc" % self.div_count] = self.fk_ctl[-1] self.jointRelatives["%s_loc" % self.div_count] = self.div_count - 1 def addConnection(self): """Add more connection definition to the set""" self.connections["EPIC_leg_01"] = self.connect_leg_2jnt_01 self.connections["leg_2jnt_01"] = self.connect_leg_2jnt_01 self.connections["leg_ms_2jnt_01"] = self.connect_leg_ms_2jnt_01 self.connections["leg_3jnt_01"] = self.connect_leg_3jnt_01 def connect_leg_2jnt_01(self): """Connector for leg 2jnt""" # If the parent component hasn't been generated we skip the connection if self.parent_comp is None: return pm.connectAttr(self.parent_comp.blend_att, self.blend_att) pm.parent(self.root, self.parent_comp.ik_ctl) pm.parent(self.parent_comp.ik_ref, self.bk_ctl[-1]) pm.parentConstraint( self.parent_comp.tws2_rot, self.fk_ref, maintainOffset=True ) return def connect_leg_ms_2jnt_01(self): """Connector for leg ms 2jnt""" # If the parent component hasn't been generated we skip the connection if self.parent_comp is None: return pm.connectAttr(self.parent_comp.blend_att, self.blend_att) pm.parent(self.root, self.parent_comp.ik_ctl) pm.parent(self.parent_comp.ik_ref, self.bk_ctl[-1]) pm.parentConstraint( self.parent_comp.tws3_rot, self.fk_ref, maintainOffset=True ) cns = pm.scaleConstraint( self.parent_comp.fk_ref, self.parent_comp.ik_ref, self.fk_ref, wal=True, ) bc_node = pm.createNode("blendColors") pm.connectAttr( bc_node.outputB, cns + ".%sW0" % self.parent_comp.fk_ref ) pm.connectAttr( bc_node.outputR, cns + ".%sW1" % self.parent_comp.ik_ref ) pm.connectAttr(self.parent_comp.blend_att, bc_node.blender) return def connect_leg_3jnt_01(self): """Connector for leg 3jnt""" # If the parent component hasn't been generated we skip the connection if self.parent_comp is None: return pm.connectAttr(self.parent_comp.blend_att, self.blend_att) pm.parent(self.root, self.parent_comp.ik_ctl) pm.parent(self.parent_comp.ik_ref, self.bk_ctl[-1]) pm.parent(self.parent_comp.ik2b_ikCtl_ref, self.bk_ctl[-1]) pm.parentConstraint( self.parent_comp.tws3_rot, self.fk_ref, maintainOffset=True ) return
[((556, 619), 'ast.literal_eval', 'ast.literal_eval', (["self.settings['jointNamesDescription_custom']"], {}), "(self.settings['jointNamesDescription_custom'])\n", (572, 619), False, 'import ast\n'), ((697, 725), 'pymel.core.upAxis', 'pm.upAxis', ([], {'q': '(True)', 'axis': '(True)'}), '(q=True, axis=True)\n', (706, 725), True, 'import pymel.core as pm\n'), ((1059, 1171), 'mgear.core.transform.getTransformLookingAt', 'transform.getTransformLookingAt', (["self.guide.pos['heel']", 'self.guide.apos[-4]', 'self.normal', '"""xz"""', 'self.negate'], {}), "(self.guide.pos['heel'], self.guide.apos[-4],\n self.normal, 'xz', self.negate)\n", (1090, 1171), False, 'from mgear.core import attribute, transform, primitive\n'), ((1252, 1309), 'mgear.core.transform.setMatrixPosition', 'transform.setMatrixPosition', (['t', "self.guide.pos['inpivot']"], {}), "(t, self.guide.pos['inpivot'])\n", (1279, 1309), False, 'from mgear.core import attribute, transform, primitive\n'), ((1537, 1595), 'mgear.core.transform.setMatrixPosition', 'transform.setMatrixPosition', (['t', "self.guide.pos['outpivot']"], {}), "(t, self.guide.pos['outpivot'])\n", (1564, 1595), False, 'from mgear.core import attribute, transform, primitive\n'), ((1734, 1846), 'mgear.core.transform.getTransformLookingAt', 'transform.getTransformLookingAt', (["self.guide.pos['heel']", 'self.guide.apos[-4]', 'self.normal', '"""xz"""', 'self.negate'], {}), "(self.guide.pos['heel'], self.guide.apos[-4],\n self.normal, 'xz', self.negate)\n", (1765, 1846), False, 'from mgear.core import attribute, transform, primitive\n'), ((2036, 2079), 'mgear.core.attribute.setRotOrder', 'attribute.setRotOrder', (['self.heel_loc', '"""YZX"""'], {}), "(self.heel_loc, 'YZX')\n", (2057, 2079), False, 'from mgear.core import attribute, transform, primitive\n'), ((2316, 2376), 'mgear.core.attribute.setKeyableAttributes', 'attribute.setKeyableAttributes', (['self.heel_ctl', 'self.r_params'], {}), '(self.heel_ctl, self.r_params)\n', (2346, 2376), False, 'from mgear.core import attribute, transform, primitive\n'), ((2833, 2866), 'mgear.core.transform.setMatrixPosition', 'transform.setMatrixPosition', (['t', 'v'], {}), '(t, v)\n', (2860, 2866), False, 'from mgear.core import attribute, transform, primitive\n'), ((3090, 3149), 'mgear.core.attribute.setKeyableAttributes', 'attribute.setKeyableAttributes', (['self.tip_ctl', 'self.r_params'], {}), '(self.tip_ctl, self.r_params)\n', (3120, 3149), False, 'from mgear.core import attribute, transform, primitive\n'), ((9544, 9645), 'mgear.core.node.createClampNode', 'node.createClampNode', (['[self.roll_att, self.bank_att, self.bank_att]', '[0, -180, 0]', '[180, 0, 180]'], {}), '([self.roll_att, self.bank_att, self.bank_att], [0, -\n 180, 0], [180, 0, 180])\n', (9564, 9645), False, 'from mgear.core import node, applyop, vector\n'), ((10124, 10164), 'mgear.core.node.createAddNodeMulti', 'node.createAddNodeMulti', (['self.angles_att'], {}), '(self.angles_att)\n', (10147, 10164), False, 'from mgear.core import node, applyop, vector\n'), ((14495, 14553), 'pymel.core.connectAttr', 'pm.connectAttr', (['self.parent_comp.blend_att', 'self.blend_att'], {}), '(self.parent_comp.blend_att, self.blend_att)\n', (14509, 14553), True, 'import pymel.core as pm\n'), ((14562, 14607), 'pymel.core.parent', 'pm.parent', (['self.root', 'self.parent_comp.ik_ctl'], {}), '(self.root, self.parent_comp.ik_ctl)\n', (14571, 14607), True, 'import pymel.core as pm\n'), ((14616, 14667), 'pymel.core.parent', 'pm.parent', (['self.parent_comp.ik_ref', 'self.bk_ctl[-1]'], {}), '(self.parent_comp.ik_ref, self.bk_ctl[-1])\n', (14625, 14667), True, 'import pymel.core as pm\n'), ((14676, 14761), 'pymel.core.parentConstraint', 'pm.parentConstraint', (['self.parent_comp.tws2_rot', 'self.fk_ref'], {'maintainOffset': '(True)'}), '(self.parent_comp.tws2_rot, self.fk_ref, maintainOffset=True\n )\n', (14695, 14761), True, 'import pymel.core as pm\n'), ((15019, 15077), 'pymel.core.connectAttr', 'pm.connectAttr', (['self.parent_comp.blend_att', 'self.blend_att'], {}), '(self.parent_comp.blend_att, self.blend_att)\n', (15033, 15077), True, 'import pymel.core as pm\n'), ((15086, 15131), 'pymel.core.parent', 'pm.parent', (['self.root', 'self.parent_comp.ik_ctl'], {}), '(self.root, self.parent_comp.ik_ctl)\n', (15095, 15131), True, 'import pymel.core as pm\n'), ((15140, 15191), 'pymel.core.parent', 'pm.parent', (['self.parent_comp.ik_ref', 'self.bk_ctl[-1]'], {}), '(self.parent_comp.ik_ref, self.bk_ctl[-1])\n', (15149, 15191), True, 'import pymel.core as pm\n'), ((15200, 15285), 'pymel.core.parentConstraint', 'pm.parentConstraint', (['self.parent_comp.tws3_rot', 'self.fk_ref'], {'maintainOffset': '(True)'}), '(self.parent_comp.tws3_rot, self.fk_ref, maintainOffset=True\n )\n', (15219, 15285), True, 'import pymel.core as pm\n'), ((15317, 15413), 'pymel.core.scaleConstraint', 'pm.scaleConstraint', (['self.parent_comp.fk_ref', 'self.parent_comp.ik_ref', 'self.fk_ref'], {'wal': '(True)'}), '(self.parent_comp.fk_ref, self.parent_comp.ik_ref, self.\n fk_ref, wal=True)\n', (15335, 15413), True, 'import pymel.core as pm\n'), ((15486, 15514), 'pymel.core.createNode', 'pm.createNode', (['"""blendColors"""'], {}), "('blendColors')\n", (15499, 15514), True, 'import pymel.core as pm\n'), ((15523, 15595), 'pymel.core.connectAttr', 'pm.connectAttr', (['bc_node.outputB', "(cns + '.%sW0' % self.parent_comp.fk_ref)"], {}), "(bc_node.outputB, cns + '.%sW0' % self.parent_comp.fk_ref)\n", (15537, 15595), True, 'import pymel.core as pm\n'), ((15626, 15698), 'pymel.core.connectAttr', 'pm.connectAttr', (['bc_node.outputR', "(cns + '.%sW1' % self.parent_comp.ik_ref)"], {}), "(bc_node.outputR, cns + '.%sW1' % self.parent_comp.ik_ref)\n", (15640, 15698), True, 'import pymel.core as pm\n'), ((15729, 15788), 'pymel.core.connectAttr', 'pm.connectAttr', (['self.parent_comp.blend_att', 'bc_node.blender'], {}), '(self.parent_comp.blend_att, bc_node.blender)\n', (15743, 15788), True, 'import pymel.core as pm\n'), ((16023, 16081), 'pymel.core.connectAttr', 'pm.connectAttr', (['self.parent_comp.blend_att', 'self.blend_att'], {}), '(self.parent_comp.blend_att, self.blend_att)\n', (16037, 16081), True, 'import pymel.core as pm\n'), ((16090, 16135), 'pymel.core.parent', 'pm.parent', (['self.root', 'self.parent_comp.ik_ctl'], {}), '(self.root, self.parent_comp.ik_ctl)\n', (16099, 16135), True, 'import pymel.core as pm\n'), ((16144, 16195), 'pymel.core.parent', 'pm.parent', (['self.parent_comp.ik_ref', 'self.bk_ctl[-1]'], {}), '(self.parent_comp.ik_ref, self.bk_ctl[-1])\n', (16153, 16195), True, 'import pymel.core as pm\n'), ((16204, 16263), 'pymel.core.parent', 'pm.parent', (['self.parent_comp.ik2b_ikCtl_ref', 'self.bk_ctl[-1]'], {}), '(self.parent_comp.ik2b_ikCtl_ref, self.bk_ctl[-1])\n', (16213, 16263), True, 'import pymel.core as pm\n'), ((16272, 16357), 'pymel.core.parentConstraint', 'pm.parentConstraint', (['self.parent_comp.tws3_rot', 'self.fk_ref'], {'maintainOffset': '(True)'}), '(self.parent_comp.tws3_rot, self.fk_ref, maintainOffset=True\n )\n', (16291, 16357), True, 'import pymel.core as pm\n'), ((2487, 2580), 'pymel.core.datatypes.Vector', 'datatypes.Vector', (['self.guide.apos[-5].x', "self.guide.pos['heel'].y", 'self.guide.apos[-5].z'], {}), "(self.guide.apos[-5].x, self.guide.pos['heel'].y, self.\n guide.apos[-5].z)\n", (2503, 2580), False, 'from pymel.core import datatypes\n'), ((2669, 2762), 'pymel.core.datatypes.Vector', 'datatypes.Vector', (['self.guide.apos[-5].x', 'self.guide.apos[-5].y', "self.guide.pos['heel'].z"], {}), "(self.guide.apos[-5].x, self.guide.apos[-5].y, self.guide.\n pos['heel'].z)\n", (2685, 2762), False, 'from pymel.core import datatypes\n'), ((3268, 3380), 'mgear.core.transform.getTransformLookingAt', 'transform.getTransformLookingAt', (["self.guide.pos['heel']", 'self.guide.apos[-4]', 'self.normal', '"""xz"""', 'self.negate'], {}), "(self.guide.pos['heel'], self.guide.apos[-4],\n self.normal, 'xz', self.negate)\n", (3299, 3380), False, 'from mgear.core import attribute, transform, primitive\n'), ((3488, 3542), 'mgear.core.transform.setMatrixPosition', 'transform.setMatrixPosition', (['t', "self.guide.pos['root']"], {}), "(t, self.guide.pos['root'])\n", (3515, 3542), False, 'from mgear.core import attribute, transform, primitive\n'), ((4029, 4088), 'mgear.core.attribute.setKeyableAttributes', 'attribute.setKeyableAttributes', (['self.roll_ctl', "['rx', 'rz']"], {}), "(self.roll_ctl, ['rx', 'rz'])\n", (4059, 4088), False, 'from mgear.core import attribute, transform, primitive\n'), ((5093, 5146), 'mgear.core.attribute.setKeyableAttributes', 'attribute.setKeyableAttributes', (['bk_ctl', 'self.r_params'], {}), '(bk_ctl, self.r_params)\n', (5123, 5146), False, 'from mgear.core import attribute, transform, primitive\n'), ((5608, 5647), 'mgear.core.transform.getTransform', 'transform.getTransform', (['self.bk_ctl[-1]'], {}), '(self.bk_ctl[-1])\n', (5630, 5647), False, 'from mgear.core import attribute, transform, primitive\n'), ((6196, 6262), 'mgear.core.vector.getDistance', 'vector.getDistance', (['self.guide.apos[i + 1]', 'self.guide.apos[i + 2]'], {}), '(self.guide.apos[i + 1], self.guide.apos[i + 2])\n', (6214, 6262), False, 'from mgear.core import node, applyop, vector\n'), ((6431, 6481), 'pymel.core.datatypes.Vector', 'datatypes.Vector', (['(dist * 0.5 * self.n_factor)', '(0)', '(0)'], {}), '(dist * 0.5 * self.n_factor, 0, 0)\n', (6447, 6481), False, 'from pymel.core import datatypes\n'), ((6869, 6907), 'mgear.core.attribute.setKeyableAttributes', 'attribute.setKeyableAttributes', (['fk_ctl'], {}), '(fk_ctl)\n', (6899, 6907), False, 'from mgear.core import attribute, transform, primitive\n'), ((10845, 10885), 'mgear.core.node.createClampNode', 'node.createClampNode', (['inpu', 'min_input', '(0)'], {}), '(inpu, min_input, 0)\n', (10865, 10885), False, 'from mgear.core import node, applyop, vector\n'), ((11347, 11394), 'mgear.core.applyop.gear_inverseRotorder_op', 'applyop.gear_inverseRotorder_op', (['bk_ctl', 'fk_ctl'], {}), '(bk_ctl, fk_ctl)\n', (11378, 11394), False, 'from mgear.core import node, applyop, vector\n'), ((11533, 11570), 'mgear.core.attribute.lockAttribute', 'attribute.lockAttribute', (['bk_ctl', '"""ro"""'], {}), "(bk_ctl, 'ro')\n", (11556, 11570), False, 'from mgear.core import attribute, transform, primitive\n'), ((12130, 12222), 'mgear.core.node.createMulNode', 'node.createMulNode', (['[addx_node.output, addy_node.output, addz_node.output]', '[-1, -1, -1]'], {}), '([addx_node.output, addy_node.output, addz_node.output],\n [-1, -1, -1])\n', (12148, 12222), False, 'from mgear.core import node, applyop, vector\n'), ((12582, 12642), 'mgear.core.node.createBlendNode', 'node.createBlendNode', (['ik_outputs', 'fk_outputs', 'self.blend_att'], {}), '(ik_outputs, fk_outputs, self.blend_att)\n', (12602, 12642), False, 'from mgear.core import node, applyop, vector\n'), ((4420, 4457), 'mgear.core.transform.getTransform', 'transform.getTransform', (['self.heel_ctl'], {}), '(self.heel_ctl)\n', (4442, 4457), False, 'from mgear.core import attribute, transform, primitive\n'), ((4478, 4513), 'mgear.core.transform.setMatrixPosition', 'transform.setMatrixPosition', (['t', 'pos'], {}), '(t, pos)\n', (4505, 4513), False, 'from mgear.core import attribute, transform, primitive\n'), ((4594, 4673), 'mgear.core.transform.getTransformLookingAt', 'transform.getTransformLookingAt', (['pos', 'direction', 'self.normal', '"""xz"""', 'self.negate'], {}), "(pos, direction, self.normal, 'xz', self.negate)\n", (4625, 4673), False, 'from mgear.core import attribute, transform, primitive\n'), ((5964, 6000), 'mgear.core.transform.getTransform', 'transform.getTransform', (['self.tip_ctl'], {}), '(self.tip_ctl)\n', (5986, 6000), False, 'from mgear.core import attribute, transform, primitive\n'), ((6021, 6053), 'mgear.core.transform.getTranslation', 'transform.getTranslation', (['bk_ctl'], {}), '(bk_ctl)\n', (6045, 6053), False, 'from mgear.core import attribute, transform, primitive\n'), ((6074, 6107), 'mgear.core.transform.setMatrixPosition', 'transform.setMatrixPosition', (['t', 'v'], {}), '(t, v)\n', (6101, 6107), False, 'from mgear.core import attribute, transform, primitive\n'), ((6146, 6176), 'mgear.core.transform.getTransform', 'transform.getTransform', (['bk_ctl'], {}), '(bk_ctl)\n', (6168, 6176), False, 'from mgear.core import attribute, transform, primitive\n'), ((9246, 9290), 'pymel.core.displayInfo', 'pm.displayInfo', (['"""Visibility already connect"""'], {}), "('Visibility already connect')\n", (9260, 9290), True, 'import pymel.core as pm\n'), ((3931, 3967), 'pymel.core.datatypes.Vector', 'datatypes.Vector', (['(3.1415 * 0.5)', '(0)', '(0)'], {}), '(3.1415 * 0.5, 0, 0)\n', (3947, 3967), False, 'from pymel.core import datatypes\n'), ((10420, 10475), 'mgear.core.node.createSubNode', 'node.createSubNode', (['self.roll_att', 'angle_outputs[i - 1]'], {}), '(self.roll_att, angle_outputs[i - 1])\n', (10438, 10475), False, 'from mgear.core import node, applyop, vector\n'), ((10640, 10695), 'mgear.core.node.createSubNode', 'node.createSubNode', (['self.roll_att', 'angle_outputs[i - 1]'], {}), '(self.roll_att, angle_outputs[i - 1])\n', (10658, 10695), False, 'from mgear.core import node, applyop, vector\n')]
Engerrs/ckan.org
streams/blog/migrations/0012_auto_20200928_1212.py
a5a9b63b0ca16cb5aa4f709f7a264b8f6c265158
# Generated by Django 3.1.1 on 2020-09-28 12:12 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0011_blogpostpage_featured'), ] operations = [ migrations.RemoveField( model_name='blogpostpage', name='date', ), migrations.AddField( model_name='blogpostpage', name='created', field=models.DateTimeField(blank=True, default=datetime.datetime.now), ), ]
[((251, 313), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""blogpostpage"""', 'name': '"""date"""'}), "(model_name='blogpostpage', name='date')\n", (273, 313), False, 'from django.db import migrations, models\n'), ((464, 527), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'default': 'datetime.datetime.now'}), '(blank=True, default=datetime.datetime.now)\n', (484, 527), False, 'from django.db import migrations, models\n')]
rafaelpezzuto/opac
opac/webapp/main/views.py
9b54202350e262a27cb9cb756a892185b288df24
# coding: utf-8 import logging import requests import mimetypes from io import BytesIO from urllib.parse import urlparse from datetime import datetime, timedelta from collections import OrderedDict from flask_babelex import gettext as _ from flask import ( render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response, ) from werkzeug.contrib.atom import AtomFeed from urllib.parse import urljoin from legendarium.formatter import descriptive_short_format from . import main from webapp import babel from webapp import cache from webapp import controllers from webapp.choices import STUDY_AREAS from webapp.utils import utils from webapp.utils.caching import cache_key_with_lang, cache_key_with_lang_with_qs from webapp import forms from webapp.config.lang_names import display_original_lang_name from opac_schema.v1.models import Journal, Issue, Article, Collection from lxml import etree from packtools import HTMLGenerator logger = logging.getLogger(__name__) JOURNAL_UNPUBLISH = _("O periódico está indisponível por motivo de: ") ISSUE_UNPUBLISH = _("O número está indisponível por motivo de: ") ARTICLE_UNPUBLISH = _("O artigo está indisponível por motivo de: ") IAHX_LANGS = dict( p='pt', e='es', i='en', ) def url_external(endpoint, **kwargs): url = url_for(endpoint, **kwargs) return urljoin(request.url_root, url) class RetryableError(Exception): """Erro recuperável sem que seja necessário modificar o estado dos dados na parte cliente, e.g., timeouts, erros advindos de particionamento de rede etc. """ class NonRetryableError(Exception): """Erro do qual não pode ser recuperado sem modificar o estado dos dados na parte cliente, e.g., recurso solicitado não exite, URI inválida etc. """ def fetch_data(url: str, timeout: float = 2) -> bytes: try: response = requests.get(url, timeout=timeout) except (requests.ConnectionError, requests.Timeout) as exc: raise RetryableError(exc) from exc except (requests.InvalidSchema, requests.MissingSchema, requests.InvalidURL) as exc: raise NonRetryableError(exc) from exc else: try: response.raise_for_status() except requests.HTTPError as exc: if 400 <= exc.response.status_code < 500: raise NonRetryableError(exc) from exc elif 500 <= exc.response.status_code < 600: raise RetryableError(exc) from exc else: raise return response.content @main.before_app_request def add_collection_to_g(): if not hasattr(g, 'collection'): try: collection = controllers.get_current_collection() setattr(g, 'collection', collection) except Exception: # discutir o que fazer aqui setattr(g, 'collection', {}) @main.after_request def add_header(response): response.headers['x-content-type-options'] = 'nosniff' return response @main.after_request def add_language_code(response): language = session.get('lang', get_locale()) response.set_cookie('language', language) return response @main.before_app_request def add_forms_to_g(): setattr(g, 'email_share', forms.EmailShareForm()) setattr(g, 'email_contact', forms.ContactForm()) setattr(g, 'error', forms.ErrorForm()) @main.before_app_request def add_scielo_org_config_to_g(): language = session.get('lang', get_locale()) scielo_org_links = { key: url[language] for key, url in current_app.config.get('SCIELO_ORG_URIS', {}).items() } setattr(g, 'scielo_org', scielo_org_links) @babel.localeselector def get_locale(): langs = current_app.config.get('LANGUAGES') lang_from_headers = request.accept_languages.best_match(list(langs.keys())) if 'lang' not in list(session.keys()): session['lang'] = lang_from_headers if not lang_from_headers and not session['lang']: # Caso não seja possível detectar o idioma e não tenhamos a chave lang # no seção, fixamos o idioma padrão. session['lang'] = current_app.config.get('BABEL_DEFAULT_LOCALE') return session['lang'] @main.route('/set_locale/<string:lang_code>/') def set_locale(lang_code): langs = current_app.config.get('LANGUAGES') if lang_code not in list(langs.keys()): abort(400, _('Código de idioma inválido')) referrer = request.referrer hash = request.args.get('hash') if hash: referrer += "#" + hash # salvar o lang code na sessão session['lang'] = lang_code return redirect(referrer) def get_lang_from_session(): """ Tenta retornar o idioma da seção, caso não consiga retorna BABEL_DEFAULT_LOCALE. """ try: return session['lang'] except KeyError: return current_app.config.get('BABEL_DEFAULT_LOCALE') @main.route('/') @cache.cached(key_prefix=cache_key_with_lang) def index(): language = session.get('lang', get_locale()) news = controllers.get_latest_news_by_lang(language) tweets = controllers.get_collection_tweets() press_releases = controllers.get_press_releases({'language': language}) urls = { 'downloads': '{0}/w/accesses?collection={1}'.format( current_app.config['METRICS_URL'], current_app.config['OPAC_COLLECTION']), 'references': '{0}/w/publication/size?collection={1}'.format( current_app.config['METRICS_URL'], current_app.config['OPAC_COLLECTION']), 'other': '{0}/?collection={1}'.format( current_app.config['METRICS_URL'], current_app.config['OPAC_COLLECTION']) } if ( g.collection is not None and isinstance(g.collection, Collection) and g.collection.metrics is not None and current_app.config['USE_HOME_METRICS'] ): g.collection.metrics.total_journal = Journal.objects.filter( is_public=True, current_status="current" ).count() g.collection.metrics.total_article = Article.objects.filter( is_public=True ).count() context = { 'news': news, 'urls': urls, 'tweets': tweets, 'press_releases': press_releases, } return render_template("collection/index.html", **context) # ##################################Collection################################### @main.route('/journals/alpha') @cache.cached(key_prefix=cache_key_with_lang) def collection_list(): allowed_filters = ["current", "no-current", ""] query_filter = request.args.get("status", "") if not query_filter in allowed_filters: query_filter = "" journals_list = [ controllers.get_journal_json_data(journal) for journal in controllers.get_journals(query_filter=query_filter) ] return render_template("collection/list_journal.html", **{'journals_list': journals_list, 'query_filter': query_filter}) @main.route("/journals/thematic") @cache.cached(key_prefix=cache_key_with_lang) def collection_list_thematic(): allowed_query_filters = ["current", "no-current", ""] allowed_thematic_filters = ["areas", "wos", "publisher"] thematic_table = { "areas": "study_areas", "wos": "subject_categories", "publisher": "publisher_name", } query_filter = request.args.get("status", "") title_query = request.args.get("query", "") thematic_filter = request.args.get("filter", "areas") if not query_filter in allowed_query_filters: query_filter = "" if not thematic_filter in allowed_thematic_filters: thematic_filter = "areas" lang = get_lang_from_session()[:2].lower() objects = controllers.get_journals_grouped_by( thematic_table[thematic_filter], title_query, query_filter=query_filter, lang=lang, ) return render_template( "collection/list_thematic.html", **{"objects": objects, "query_filter": query_filter, "filter": thematic_filter} ) @main.route('/journals/feed/') @cache.cached(key_prefix=cache_key_with_lang) def collection_list_feed(): language = session.get('lang', get_locale()) collection = controllers.get_current_collection() title = 'SciELO - %s - %s' % (collection.name, _('Últimos periódicos inseridos na coleção')) subtitle = _('10 últimos periódicos inseridos na coleção %s' % collection.name) feed = AtomFeed(title, subtitle=subtitle, feed_url=request.url, url=request.url_root) journals = controllers.get_journals_paginated( title_query='', page=1, order_by='-created', per_page=10) if not journals.items: feed.add('Nenhum periódico encontrado', url=request.url, updated=datetime.now()) for journal in journals.items: issues = controllers.get_issues_by_jid(journal.jid, is_public=True) last_issue = issues[0] if issues else None articles = [] if last_issue: articles = controllers.get_articles_by_iid(last_issue.iid, is_public=True) result_dict = OrderedDict() for article in articles: section = article.get_section_by_lang(language[:2]) result_dict.setdefault(section, []) result_dict[section].append(article) context = { 'journal': journal, 'articles': result_dict, 'language': language, 'last_issue': last_issue } feed.add(journal.title, render_template("collection/list_feed_content.html", **context), content_type='html', author=journal.publisher_name, url=url_external('main.journal_detail', url_seg=journal.url_segment), updated=journal.updated, published=journal.created) return feed.get_response() @main.route("/about/", methods=['GET']) @main.route('/about/<string:slug_name>', methods=['GET']) @cache.cached(key_prefix=cache_key_with_lang_with_qs) def about_collection(slug_name=None): language = session.get('lang', get_locale()) context = {} page = None if slug_name: # caso seja uma página page = controllers.get_page_by_slug_name(slug_name, language) if not page: abort(404, _('Página não encontrada')) context['page'] = page else: # caso não seja uma página é uma lista pages = controllers.get_pages_by_lang(language) context['pages'] = pages return render_template("collection/about.html", **context) # ###################################Journal##################################### @main.route('/scielo.php/') @cache.cached(key_prefix=cache_key_with_lang_with_qs) def router_legacy(): script_php = request.args.get('script', None) pid = request.args.get('pid', None) tlng = request.args.get('tlng', None) allowed_scripts = [ 'sci_serial', 'sci_issuetoc', 'sci_arttext', 'sci_abstract', 'sci_issues', 'sci_pdf' ] if (script_php is not None) and (script_php in allowed_scripts) and not pid: # se tem pelo menos um param: pid ou script_php abort(400, _(u'Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)) elif script_php and pid: if script_php == 'sci_serial': # pid = issn journal = controllers.get_journal_by_issn(pid) if not journal: abort(404, _('Periódico não encontrado')) if not journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason)) return redirect(url_for('main.journal_detail', url_seg=journal.url_segment), code=301) elif script_php == 'sci_issuetoc': issue = controllers.get_issue_by_pid(pid) if not issue: abort(404, _('Número não encontrado')) if not issue.is_public: abort(404, ISSUE_UNPUBLISH + _(issue.unpublish_reason)) if not issue.journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(issue.journal.unpublish_reason)) if issue.url_segment and "ahead" in issue.url_segment: return redirect( url_for('main.aop_toc', url_seg=url_seg), code=301) return redirect( url_for( "main.issue_toc", url_seg=issue.journal.url_segment, url_seg_issue=issue.url_segment), 301 ) elif script_php == 'sci_arttext' or script_php == 'sci_abstract': article = controllers.get_article_by_pid_v2(pid) if not article: abort(404, _('Artigo não encontrado')) # 'abstract' or None (not False, porque False converterá a string 'False') part = (script_php == 'sci_abstract' and 'abstract') or None if tlng not in article.languages: tlng = article.original_language return redirect(url_for('main.article_detail_v3', url_seg=article.journal.url_segment, article_pid_v3=article.aid, part=part, lang=tlng), code=301) elif script_php == 'sci_issues': journal = controllers.get_journal_by_issn(pid) if not journal: abort(404, _('Periódico não encontrado')) if not journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason)) return redirect(url_for('main.issue_grid', url_seg=journal.url_segment), 301) elif script_php == 'sci_pdf': # accesso ao pdf do artigo: article = controllers.get_article_by_pid_v2(pid) if not article: abort(404, _('Artigo não encontrado')) return redirect( url_for( 'main.article_detail_v3', url_seg=article.journal.url_segment, article_pid_v3=article.aid, format='pdf', ), code=301 ) else: abort(400, _(u'Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)) else: return redirect('/') @main.route('/<string:journal_seg>') @main.route('/journal/<string:journal_seg>') def journal_detail_legacy_url(journal_seg): return redirect(url_for('main.journal_detail', url_seg=journal_seg), code=301) @main.route('/j/<string:url_seg>/') @cache.cached(key_prefix=cache_key_with_lang) def journal_detail(url_seg): journal = controllers.get_journal_by_url_seg(url_seg) if not journal: abort(404, _('Periódico não encontrado')) if not journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason)) utils.fix_journal_last_issue(journal) # todo: ajustar para que seja só noticias relacionadas ao periódico language = session.get('lang', get_locale()) news = controllers.get_latest_news_by_lang(language) # Press releases press_releases = controllers.get_press_releases({ 'journal': journal, 'language': language}) # Lista de seções # Mantendo sempre o idioma inglês para as seções na página incial do periódico if journal.last_issue and journal.current_status == "current": sections = [section for section in journal.last_issue.sections if section.language == 'en'] recent_articles = controllers.get_recent_articles_of_issue(journal.last_issue.iid, is_public=True) else: sections = [] recent_articles = [] latest_issue = journal.last_issue if latest_issue: latest_issue_legend = descriptive_short_format( title=journal.title, short_title=journal.short_title, pubdate=str(latest_issue.year), volume=latest_issue.volume, number=latest_issue.number, suppl=latest_issue.suppl_text, language=language[:2].lower()) else: latest_issue_legend = '' journal_metrics = controllers.get_journal_metrics(journal) context = { 'journal': journal, 'press_releases': press_releases, 'recent_articles': recent_articles, 'journal_study_areas': [ STUDY_AREAS.get(study_area.upper()) for study_area in journal.study_areas ], # o primiero item da lista é o último número. # condicional para verificar se issues contém itens 'last_issue': latest_issue, 'latest_issue_legend': latest_issue_legend, 'sections': sections if sections else None, 'news': news, 'journal_metrics': journal_metrics } return render_template("journal/detail.html", **context) @main.route('/journal/<string:url_seg>/feed/') @cache.cached(key_prefix=cache_key_with_lang) def journal_feed(url_seg): journal = controllers.get_journal_by_url_seg(url_seg) if not journal: abort(404, _('Periódico não encontrado')) if not journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason)) issues = controllers.get_issues_by_jid(journal.jid, is_public=True) last_issue = issues[0] if issues else None articles = controllers.get_articles_by_iid(last_issue.iid, is_public=True) feed = AtomFeed(journal.title, feed_url=request.url, url=request.url_root, subtitle=utils.get_label_issue(last_issue)) feed_language = session.get('lang', get_locale()) feed_language = feed_language[:2].lower() for article in articles: # ######### TODO: Revisar ######### article_lang = feed_language if feed_language not in article.languages: article_lang = article.original_language feed.add(article.title or _('Artigo sem título'), render_template("issue/feed_content.html", article=article), content_type='html', id=article.doi or article.pid, author=article.authors, url=url_external('main.article_detail_v3', url_seg=journal.url_segment, article_pid_v3=article.aid, lang=article_lang), updated=journal.updated, published=journal.created) return feed.get_response() @main.route("/journal/<string:url_seg>/about/", methods=['GET']) @cache.cached(key_prefix=cache_key_with_lang) def about_journal(url_seg): language = session.get('lang', get_locale()) journal = controllers.get_journal_by_url_seg(url_seg) if not journal: abort(404, _('Periódico não encontrado')) if not journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason)) latest_issue = utils.fix_journal_last_issue(journal) if latest_issue: latest_issue_legend = descriptive_short_format( title=journal.title, short_title=journal.short_title, pubdate=str(latest_issue.year), volume=latest_issue.volume, number=latest_issue.number, suppl=latest_issue.suppl_text, language=language[:2].lower()) else: latest_issue_legend = None page = controllers.get_page_by_journal_acron_lang(journal.acronym, language) context = { 'journal': journal, 'latest_issue_legend': latest_issue_legend, 'last_issue': latest_issue, 'journal_study_areas': [ STUDY_AREAS.get(study_area.upper()) for study_area in journal.study_areas ], } if page: context['content'] = page.content if page.updated_at: context['page_updated_at'] = page.updated_at return render_template("journal/about.html", **context) @main.route("/journals/search/alpha/ajax/", methods=['GET', ]) @cache.cached(key_prefix=cache_key_with_lang_with_qs) def journals_search_alpha_ajax(): if not request.is_xhr: abort(400, _('Requisição inválida. Deve ser por ajax')) query = request.args.get('query', '', type=str) query_filter = request.args.get('query_filter', '', type=str) page = request.args.get('page', 1, type=int) lang = get_lang_from_session()[:2].lower() response_data = controllers.get_alpha_list_from_paginated_journals( title_query=query, query_filter=query_filter, page=page, lang=lang) return jsonify(response_data) @main.route("/journals/search/group/by/filter/ajax/", methods=['GET']) @cache.cached(key_prefix=cache_key_with_lang_with_qs) def journals_search_by_theme_ajax(): if not request.is_xhr: abort(400, _('Requisição inválida. Deve ser por ajax')) query = request.args.get('query', '', type=str) query_filter = request.args.get('query_filter', '', type=str) filter = request.args.get('filter', 'areas', type=str) lang = get_lang_from_session()[:2].lower() if filter == 'areas': objects = controllers.get_journals_grouped_by('study_areas', query, query_filter=query_filter, lang=lang) elif filter == 'wos': objects = controllers.get_journals_grouped_by('subject_categories', query, query_filter=query_filter, lang=lang) elif filter == 'publisher': objects = controllers.get_journals_grouped_by('publisher_name', query, query_filter=query_filter, lang=lang) else: return jsonify({ 'error': 401, 'message': _('Parámetro "filter" é inválido, deve ser "areas", "wos" ou "publisher".') }) return jsonify(objects) @main.route("/journals/download/<string:list_type>/<string:extension>/", methods=['GET', ]) @cache.cached(key_prefix=cache_key_with_lang_with_qs) def download_journal_list(list_type, extension): if extension.lower() not in ['csv', 'xls']: abort(401, _('Parámetro "extension" é inválido, deve ser "csv" ou "xls".')) elif list_type.lower() not in ['alpha', 'areas', 'wos', 'publisher']: abort(401, _('Parámetro "list_type" é inválido, deve ser: "alpha", "areas", "wos" ou "publisher".')) else: if extension.lower() == 'xls': mimetype = 'application/vnd.ms-excel' else: mimetype = 'text/csv' query = request.args.get('query', '', type=str) data = controllers.get_journal_generator_for_csv(list_type=list_type, title_query=query, extension=extension.lower()) timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') filename = 'journals_%s_%s.%s' % (list_type, timestamp, extension) response = Response(data, mimetype=mimetype) response.headers['Content-Disposition'] = 'attachment; filename=%s' % filename return response @main.route("/<string:url_seg>/contact", methods=['POST']) def contact(url_seg): if not request.is_xhr: abort(403, _('Requisição inválida, deve ser ajax.')) if utils.is_recaptcha_valid(request): form = forms.ContactForm(request.form) journal = controllers.get_journal_by_url_seg(url_seg) if not journal.enable_contact: abort(403, _('Periódico não permite envio de email.')) recipients = journal.editor_email if form.validate(): sent, message = controllers.send_email_contact(recipients, form.data['name'], form.data['your_email'], form.data['message']) return jsonify({'sent': sent, 'message': str(message), 'fields': [key for key in form.data.keys()]}) else: return jsonify({'sent': False, 'message': form.errors, 'fields': [key for key in form.data.keys()]}) else: abort(400, _('Requisição inválida, captcha inválido.')) @main.route("/form_contact/<string:url_seg>/", methods=['GET']) def form_contact(url_seg): journal = controllers.get_journal_by_url_seg(url_seg) if not journal: abort(404, _('Periódico não encontrado')) context = { 'journal': journal } return render_template("journal/includes/contact_form.html", **context) # ###################################Issue####################################### @main.route('/grid/<string:url_seg>/') def issue_grid_legacy(url_seg): return redirect(url_for('main.issue_grid', url_seg=url_seg), 301) @main.route('/j/<string:url_seg>/grid') @cache.cached(key_prefix=cache_key_with_lang) def issue_grid(url_seg): journal = controllers.get_journal_by_url_seg(url_seg) if not journal: abort(404, _('Periódico não encontrado')) if not journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason)) # idioma da sessão language = session.get('lang', get_locale()) # A ordenação padrão da função ``get_issues_by_jid``: "-year", "-volume", "-order" issues_data = controllers.get_issues_for_grid_by_jid(journal.id, is_public=True) latest_issue = issues_data['last_issue'] if latest_issue: latest_issue_legend = descriptive_short_format( title=journal.title, short_title=journal.short_title, pubdate=str(latest_issue.year), volume=latest_issue.volume, number=latest_issue.number, suppl=latest_issue.suppl_text, language=language[:2].lower()) else: latest_issue_legend = None context = { 'journal': journal, 'last_issue': issues_data['last_issue'], 'latest_issue_legend': latest_issue_legend, 'volume_issue': issues_data['volume_issue'], 'ahead': issues_data['ahead'], 'result_dict': issues_data['ordered_for_grid'], 'journal_study_areas': [ STUDY_AREAS.get(study_area.upper()) for study_area in journal.study_areas ], } return render_template("issue/grid.html", **context) @main.route('/toc/<string:url_seg>/<string:url_seg_issue>/') def issue_toc_legacy(url_seg, url_seg_issue): if url_seg_issue and "ahead" in url_seg_issue: return redirect(url_for('main.aop_toc', url_seg=url_seg), code=301) return redirect( url_for('main.issue_toc', url_seg=url_seg, url_seg_issue=url_seg_issue), code=301) @main.route('/j/<string:url_seg>/i/<string:url_seg_issue>/') @cache.cached(key_prefix=cache_key_with_lang_with_qs) def issue_toc(url_seg, url_seg_issue): section_filter = None goto = request.args.get("goto", None, type=str) if goto not in ("previous", "next"): goto = None if goto in (None, "next") and "ahead" in url_seg_issue: # redireciona para `aop_toc` return redirect(url_for('main.aop_toc', url_seg=url_seg), code=301) # idioma da sessão language = session.get('lang', get_locale()) if current_app.config["FILTER_SECTION_ENABLE"]: # seção dos documentos, se selecionada section_filter = request.args.get('section', '', type=str).upper() # obtém o issue issue = controllers.get_issue_by_url_seg(url_seg, url_seg_issue) if not issue: abort(404, _('Número não encontrado')) if not issue.is_public: abort(404, ISSUE_UNPUBLISH + _(issue.unpublish_reason)) # obtém o journal journal = issue.journal if not journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason)) # completa url_segment do last_issue utils.fix_journal_last_issue(journal) # goto_next_or_previous_issue (redireciona) goto_url = goto_next_or_previous_issue( issue, request.args.get('goto', None, type=str)) if goto_url: return redirect(goto_url, code=301) # obtém os documentos articles = controllers.get_articles_by_iid(issue.iid, is_public=True) if articles: # obtém TODAS as seções dos documentos deste sumário sections = sorted({a.section.upper() for a in articles if a.section}) else: # obtém as seções dos documentos deste sumário sections = [] if current_app.config["FILTER_SECTION_ENABLE"] and section_filter != '': # obtém somente os documentos da seção selecionada articles = [a for a in articles if a.section.upper() == section_filter] # obtém PDF e TEXT de cada documento has_math_content = False for article in articles: article_text_languages = [doc['lang'] for doc in article.htmls] article_pdf_languages = [(doc['lang'], doc['url']) for doc in article.pdfs] setattr(article, "article_text_languages", article_text_languages) setattr(article, "article_pdf_languages", article_pdf_languages) if 'mml:' in article.title: has_math_content = True # obtém a legenda bibliográfica issue_bibliographic_strip = descriptive_short_format( title=journal.title, short_title=journal.short_title, pubdate=str(issue.year), volume=issue.volume, number=issue.number, suppl=issue.suppl_text, language=language[:2].lower()) context = { 'this_page_url': url_for( 'main.issue_toc', url_seg=url_seg, url_seg_issue=url_seg_issue), 'has_math_content': has_math_content, 'journal': journal, 'issue': issue, 'issue_bibliographic_strip': issue_bibliographic_strip, 'articles': articles, 'sections': sections, 'section_filter': section_filter, 'journal_study_areas': [ STUDY_AREAS.get(study_area.upper()) for study_area in journal.study_areas ], 'last_issue': journal.last_issue } return render_template("issue/toc.html", **context) def goto_next_or_previous_issue(current_issue, goto_param): if goto_param not in ["next", "previous"]: return None all_issues = list( controllers.get_issues_by_jid(current_issue.journal.id, is_public=True)) if goto_param == "next": selected_issue = utils.get_next_issue(all_issues, current_issue) elif goto_param == "previous": selected_issue = utils.get_prev_issue(all_issues, current_issue) if selected_issue in (None, current_issue): # nao precisa redirecionar return None try: url_seg_issue = selected_issue.url_segment except AttributeError: return None else: return url_for('main.issue_toc', url_seg=selected_issue.journal.url_segment, url_seg_issue=url_seg_issue) def get_next_or_previous_issue(current_issue, goto_param): if goto_param not in ["next", "previous"]: return current_issue all_issues = list( controllers.get_issues_by_jid(current_issue.journal.id, is_public=True)) if goto_param == "next": return utils.get_next_issue(all_issues, current_issue) return utils.get_prev_issue(all_issues, current_issue) @main.route('/j/<string:url_seg>/aop') @cache.cached(key_prefix=cache_key_with_lang_with_qs) def aop_toc(url_seg): section_filter = request.args.get('section', '', type=str).upper() aop_issues = controllers.get_aop_issues(url_seg) or [] if not aop_issues: abort(404, _('Artigos ahead of print não encontrados')) goto = request.args.get("goto", None, type=str) if goto == "previous": url = goto_next_or_previous_issue(aop_issues[-1], goto) if url: redirect(url, code=301) journal = aop_issues[0].journal if not journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason)) utils.fix_journal_last_issue(journal) articles = [] for aop_issue in aop_issues: _articles = controllers.get_articles_by_iid( aop_issue.iid, is_public=True) if _articles: articles.extend(_articles) if not articles: abort(404, _('Artigos ahead of print não encontrados')) sections = sorted({a.section.upper() for a in articles if a.section}) if section_filter != '': articles = [a for a in articles if a.section.upper() == section_filter] for article in articles: article_text_languages = [doc['lang'] for doc in article.htmls] article_pdf_languages = [(doc['lang'], doc['url']) for doc in article.pdfs] setattr(article, "article_text_languages", article_text_languages) setattr(article, "article_pdf_languages", article_pdf_languages) context = { 'this_page_url': url_for("main.aop_toc", url_seg=url_seg), 'journal': journal, 'issue': aop_issues[0], 'issue_bibliographic_strip': "ahead of print", 'articles': articles, 'sections': sections, 'section_filter': section_filter, 'journal_study_areas': [ STUDY_AREAS.get(study_area.upper()) for study_area in journal.study_areas ], # o primeiro item da lista é o último número. 'last_issue': journal.last_issue } return render_template("issue/toc.html", **context) @main.route('/feed/<string:url_seg>/<string:url_seg_issue>/') @cache.cached(key_prefix=cache_key_with_lang) def issue_feed(url_seg, url_seg_issue): issue = controllers.get_issue_by_url_seg(url_seg, url_seg_issue) if not issue: abort(404, _('Número não encontrado')) if not issue.is_public: abort(404, ISSUE_UNPUBLISH + _(issue.unpublish_reason)) if not issue.journal.is_public: abort(404, JOURNAL_UNPUBLISH + _(issue.journal.unpublish_reason)) journal = issue.journal articles = controllers.get_articles_by_iid(issue.iid, is_public=True) feed = AtomFeed(journal.title or "", feed_url=request.url, url=request.url_root, subtitle=utils.get_label_issue(issue)) feed_language = session.get('lang', get_locale()) for article in articles: # ######### TODO: Revisar ######### article_lang = feed_language if feed_language not in article.languages: article_lang = article.original_language feed.add(article.title or 'Unknow title', render_template("issue/feed_content.html", article=article), content_type='html', author=article.authors, id=article.doi or article.pid, url=url_external('main.article_detail_v3', url_seg=journal.url_segment, article_pid_v3=article.aid, lang=article_lang), updated=journal.updated, published=journal.created) return feed.get_response() # ##################################Article###################################### @main.route('/article/<regex("S\d{4}-\d{3}[0-9xX][0-2][0-9]{3}\d{4}\d{5}"):pid>/') @cache.cached(key_prefix=cache_key_with_lang) def article_detail_pid(pid): article = controllers.get_article_by_pid(pid) if not article: article = controllers.get_article_by_oap_pid(pid) if not article: abort(404, _('Artigo não encontrado')) return redirect(url_for('main.article_detail_v3', url_seg=article.journal.acronym, article_pid_v3=article.aid)) def render_html_from_xml(article, lang, gs_abstract=False): logger.debug("Get XML: %s", article.xml) if current_app.config["SSM_XML_URL_REWRITE"]: result = fetch_data(use_ssm_url(article.xml)) else: result = fetch_data(article.xml) xml = etree.parse(BytesIO(result)) generator = HTMLGenerator.parse( xml, valid_only=False, gs_abstract=gs_abstract, output_style="website") return generator.generate(lang), generator.languages def render_html_from_html(article, lang): html_url = [html for html in article.htmls if html['lang'] == lang] try: html_url = html_url[0]['url'] except IndexError: raise ValueError('Artigo não encontrado') from None result = fetch_data(use_ssm_url(html_url)) html = result.decode('utf8') text_languages = [html['lang'] for html in article.htmls] return html, text_languages def render_html_abstract(article, lang): abstract_text = '' for abstract in article.abstracts: if abstract['language'] == lang: abstract_text = abstract["text"] break return abstract_text, article.abstract_languages def render_html(article, lang, gs_abstract=False): if article.xml: return render_html_from_xml(article, lang, gs_abstract) elif article.htmls: if gs_abstract: return render_html_abstract(article, lang) return render_html_from_html(article, lang) else: # TODO: Corrigir os teste que esperam ter o atributo ``htmls`` # O ideal seria levantar um ValueError. return '', [] # TODO: Remover assim que o valor Article.xml estiver consistente na base de # dados def use_ssm_url(url): """Normaliza a string `url` de acordo com os valores das diretivas de configuração OPAC_SSM_SCHEME, OPAC_SSM_DOMAIN e OPAC_SSM_PORT. A normalização busca obter uma URL absoluta em função de uma relativa, ou uma absoluta em função de uma absoluta, mas com as partes *scheme* e *authority* trocadas pelas definidas nas diretivas citadas anteriormente. Este código deve ser removido assim que o valor de Article.xml estiver consistente, i.e., todos os registros possuirem apenas URLs absolutas. """ if url.startswith("http"): parsed_url = urlparse(url) return current_app.config["SSM_BASE_URI"] + parsed_url.path else: return current_app.config["SSM_BASE_URI"] + url @main.route('/article/<string:url_seg>/<string:url_seg_issue>/<string:url_seg_article>/') @main.route('/article/<string:url_seg>/<string:url_seg_issue>/<string:url_seg_article>/<regex("(?:\w{2})"):lang_code>/') @main.route('/article/<string:url_seg>/<string:url_seg_issue>/<regex("(.*)"):url_seg_article>/') @main.route('/article/<string:url_seg>/<string:url_seg_issue>/<regex("(.*)"):url_seg_article>/<regex("(?:\w{2})"):lang_code>/') @cache.cached(key_prefix=cache_key_with_lang) def article_detail(url_seg, url_seg_issue, url_seg_article, lang_code=''): issue = controllers.get_issue_by_url_seg(url_seg, url_seg_issue) if not issue: abort(404, _('Issue não encontrado')) article = controllers.get_article_by_issue_article_seg(issue.iid, url_seg_article) if article is None: article = controllers.get_article_by_aop_url_segs( issue.journal, url_seg_issue, url_seg_article ) if article is None: abort(404, _('Artigo não encontrado')) req_params = { "url_seg": article.journal.acronym, "article_pid_v3": article.aid, } if lang_code: req_params["lang"] = lang_code return redirect(url_for('main.article_detail_v3', **req_params)) @main.route('/j/<string:url_seg>/a/<string:article_pid_v3>/') @main.route('/j/<string:url_seg>/a/<string:article_pid_v3>/<string:part>/') @cache.cached(key_prefix=cache_key_with_lang) def article_detail_v3(url_seg, article_pid_v3, part=None): qs_lang = request.args.get('lang', type=str) or None qs_goto = request.args.get('goto', type=str) or None qs_stop = request.args.get('stop', type=str) or None qs_format = request.args.get('format', 'html', type=str) gs_abstract = (part == "abstract") if part and not gs_abstract: abort(404, _("Não existe '{}'. No seu lugar use '{}'" ).format(part, 'abstract')) try: qs_lang, article = controllers.get_article( article_pid_v3, url_seg, qs_lang, gs_abstract, qs_goto) if qs_goto: return redirect( url_for( 'main.article_detail_v3', url_seg=url_seg, article_pid_v3=article.aid, part=part, format=qs_format, lang=qs_lang, stop=getattr(article, 'stop', None), ), code=301 ) except (controllers.PreviousOrNextArticleNotFoundError) as e: if gs_abstract: abort(404, _('Resumo inexistente')) abort(404, _('Artigo inexistente')) except (controllers.ArticleNotFoundError, controllers.ArticleJournalNotFoundError): abort(404, _('Artigo não encontrado')) except controllers.ArticleLangNotFoundError: return redirect( url_for( 'main.article_detail_v3', url_seg=url_seg, article_pid_v3=article_pid_v3, format=qs_format, ), code=301 ) except controllers.ArticleAbstractNotFoundError: abort(404, _('Recurso não encontrado')) except controllers.ArticleIsNotPublishedError as e: abort(404, "{}{}".format(ARTICLE_UNPUBLISH, e)) except controllers.IssueIsNotPublishedError as e: abort(404, "{}{}".format(ISSUE_UNPUBLISH, e)) except controllers.JournalIsNotPublishedError as e: abort(404, "{}{}".format(JOURNAL_UNPUBLISH, e)) except ValueError as e: abort(404, str(e)) def _handle_html(): citation_pdf_url = None for pdf_data in article.pdfs: if pdf_data.get("lang") == qs_lang: citation_pdf_url = url_for( 'main.article_detail_v3', url_seg=article.journal.url_segment, article_pid_v3=article_pid_v3, lang=qs_lang, format="pdf", ) break website = request.url if website: parsed_url = urlparse(request.url) if current_app.config["FORCE_USE_HTTPS_GOOGLE_TAGS"]: website = "{}://{}".format('https', parsed_url.netloc) else: website = "{}://{}".format(parsed_url.scheme, parsed_url.netloc) if citation_pdf_url: citation_pdf_url = "{}{}".format(website, citation_pdf_url) try: html, text_languages = render_html(article, qs_lang, gs_abstract) except (ValueError, NonRetryableError): abort(404, _('HTML do Artigo não encontrado ou indisponível')) except RetryableError: abort(500, _('Erro inesperado')) text_versions = sorted( [ ( lang, display_original_lang_name(lang), url_for( 'main.article_detail_v3', url_seg=article.journal.url_segment, article_pid_v3=article_pid_v3, lang=lang ) ) for lang in text_languages ] ) citation_xml_url = "{}{}".format( website, url_for( 'main.article_detail_v3', url_seg=article.journal.url_segment, article_pid_v3=article_pid_v3, format="xml", lang=article.original_language, ) ) context = { 'next_article': qs_stop != 'next', 'previous_article': qs_stop != 'previous', 'article': article, 'journal': article.journal, 'issue': article.issue, 'html': html, 'citation_pdf_url': citation_pdf_url, 'citation_xml_url': citation_xml_url, 'article_lang': qs_lang, 'text_versions': text_versions, 'related_links': controllers.related_links(article), 'gs_abstract': gs_abstract, 'part': part, } return render_template("article/detail.html", **context) def _handle_pdf(): if not article.pdfs: abort(404, _('PDF do Artigo não encontrado')) pdf_info = [pdf for pdf in article.pdfs if pdf['lang'] == qs_lang] if len(pdf_info) != 1: abort(404, _('PDF do Artigo não encontrado')) try: pdf_url = pdf_info[0]['url'] except (IndexError, KeyError, ValueError, TypeError): abort(404, _('PDF do Artigo não encontrado')) if pdf_url: return get_pdf_content(pdf_url) raise abort(404, _('Recurso do Artigo não encontrado. Caminho inválido!')) def _handle_xml(): if current_app.config["SSM_XML_URL_REWRITE"]: result = fetch_data(use_ssm_url(article.xml)) else: result = fetch_data(article.xml) response = make_response(result) response.headers['Content-Type'] = 'application/xml' return response if 'html' == qs_format: return _handle_html() elif 'pdf' == qs_format: return _handle_pdf() elif 'xml' == qs_format: return _handle_xml() else: abort(400, _('Formato não suportado')) @main.route('/readcube/epdf/') @main.route('/readcube/epdf.php') @cache.cached(key_prefix=cache_key_with_lang_with_qs) def article_epdf(): doi = request.args.get('doi', None, type=str) pid = request.args.get('pid', None, type=str) pdf_path = request.args.get('pdf_path', None, type=str) lang = request.args.get('lang', None, type=str) if not all([doi, pid, pdf_path, lang]): abort(400, _('Parâmetros insuficientes para obter o EPDF do artigo')) else: context = { 'doi': doi, 'pid': pid, 'pdf_path': pdf_path, 'lang': lang, } return render_template("article/epdf.html", **context) def get_pdf_content(url): logger.debug("Get PDF: %s", url) if current_app.config["SSM_ARTICLE_ASSETS_OR_RENDITIONS_URL_REWRITE"]: url = use_ssm_url(url) try: response = fetch_data(url) except NonRetryableError: abort(404, _('PDF não encontrado')) except RetryableError: abort(500, _('Erro inesperado')) else: mimetype, __ = mimetypes.guess_type(url) return Response(response, mimetype=mimetype) @cache.cached(key_prefix=cache_key_with_lang_with_qs) def get_content_from_ssm(resource_ssm_media_path): resource_ssm_full_url = current_app.config['SSM_BASE_URI'] + resource_ssm_media_path url = resource_ssm_full_url.strip() mimetype, __ = mimetypes.guess_type(url) try: ssm_response = fetch_data(url) except NonRetryableError: abort(404, _('Recurso não encontrado')) except RetryableError: abort(500, _('Erro inesperado')) else: return Response(ssm_response, mimetype=mimetype) @main.route('/media/assets/<regex("(.*)"):relative_media_path>') @cache.cached(key_prefix=cache_key_with_lang) def media_assets_proxy(relative_media_path): resource_ssm_path = '{ssm_media_path}{resource_path}'.format( ssm_media_path=current_app.config['SSM_MEDIA_PATH'], resource_path=relative_media_path) return get_content_from_ssm(resource_ssm_path) @main.route('/article/ssm/content/raw/') @cache.cached(key_prefix=cache_key_with_lang_with_qs) def article_ssm_content_raw(): resource_ssm_path = request.args.get('resource_ssm_path', None) if not resource_ssm_path: raise abort(404, _('Recurso do Artigo não encontrado. Caminho inválido!')) else: return get_content_from_ssm(resource_ssm_path) @main.route('/pdf/<string:url_seg>/<string:url_seg_issue>/<string:url_seg_article>') @main.route('/pdf/<string:url_seg>/<string:url_seg_issue>/<string:url_seg_article>/<regex("(?:\w{2})"):lang_code>') @main.route('/pdf/<string:url_seg>/<string:url_seg_issue>/<regex("(.*)"):url_seg_article>') @main.route('/pdf/<string:url_seg>/<string:url_seg_issue>/<regex("(.*)"):url_seg_article>/<regex("(?:\w{2})"):lang_code>') @cache.cached(key_prefix=cache_key_with_lang) def article_detail_pdf(url_seg, url_seg_issue, url_seg_article, lang_code=''): """ Padrões esperados: `/pdf/csc/2021.v26suppl1/2557-2558` `/pdf/csc/2021.v26suppl1/2557-2558/en` """ if not lang_code and "." not in url_seg_issue: return router_legacy_pdf(url_seg, url_seg_issue, url_seg_article) issue = controllers.get_issue_by_url_seg(url_seg, url_seg_issue) if not issue: abort(404, _('Issue não encontrado')) article = controllers.get_article_by_issue_article_seg(issue.iid, url_seg_article) if not article: abort(404, _('Artigo não encontrado')) req_params = { 'url_seg': article.journal.url_segment, 'article_pid_v3': article.aid, 'format': 'pdf', } if lang_code: req_params['lang'] = lang_code return redirect(url_for('main.article_detail_v3', **req_params), code=301) @main.route('/pdf/<string:journal_acron>/<string:issue_info>/<string:pdf_filename>.pdf') @cache.cached(key_prefix=cache_key_with_lang_with_qs) def router_legacy_pdf(journal_acron, issue_info, pdf_filename): pdf_filename = '%s.pdf' % pdf_filename journal = controllers.get_journal_by_url_seg(journal_acron) if not journal: abort(404, _('Este PDF não existe em http://www.scielo.br. Consulte http://search.scielo.org')) article = controllers.get_article_by_pdf_filename( journal_acron, issue_info, pdf_filename) if not article: abort(404, _('PDF do artigo não foi encontrado')) return redirect( url_for( 'main.article_detail_v3', url_seg=article.journal.url_segment, article_pid_v3=article.aid, format='pdf', lang=article._pdf_lang, ), code=301 ) @main.route('/cgi-bin/fbpe/<string:text_or_abstract>/') @cache.cached(key_prefix=cache_key_with_lang_with_qs) def router_legacy_article(text_or_abstract): pid = request.args.get('pid', None) lng = request.args.get('lng', None) if not (text_or_abstract in ['fbtext', 'fbabs'] and pid): # se tem pid abort(400, _('Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)) article = controllers.get_article_by_pid_v1(pid) if not article: abort(404, _('Artigo não encontrado')) return redirect( url_for( 'main.article_detail_v3', url_seg=article.journal.url_segment, article_pid_v3=article.aid, ), code=301 ) # ###############################E-mail share################################## @main.route("/email_share_ajax/", methods=['POST']) def email_share_ajax(): if not request.is_xhr: abort(400, _('Requisição inválida.')) form = forms.EmailShareForm(request.form) if form.validate(): recipients = [email.strip() for email in form.data['recipients'].split(';') if email.strip() != ''] sent, message = controllers.send_email_share(form.data['your_email'], recipients, form.data['share_url'], form.data['subject'], form.data['comment']) return jsonify({'sent': sent, 'message': str(message), 'fields': [key for key in form.data.keys()]}) else: return jsonify({'sent': False, 'message': form.errors, 'fields': [key for key in form.data.keys()]}) @main.route("/form_mail/", methods=['GET']) def email_form(): context = {'url': request.args.get('url')} return render_template("email/email_form.html", **context) @main.route("/email_error_ajax/", methods=['POST']) def email_error_ajax(): if not request.is_xhr: abort(400, _('Requisição inválida.')) form = forms.ErrorForm(request.form) if form.validate(): recipients = [email.strip() for email in current_app.config.get('EMAIL_ACCOUNTS_RECEIVE_ERRORS') if email.strip() != ''] sent, message = controllers.send_email_error(form.data['name'], form.data['your_email'], recipients, form.data['url'], form.data['error_type'], form.data['message'], form.data['page_title']) return jsonify({'sent': sent, 'message': str(message), 'fields': [key for key in form.data.keys()]}) else: return jsonify({'sent': False, 'message': form.errors, 'fields': [key for key in form.data.keys()]}) @main.route("/error_mail/", methods=['GET']) def error_form(): context = {'url': request.args.get('url')} return render_template("includes/error_form.html", **context) # ###############################Others######################################## @main.route("/media/<path:filename>/", methods=['GET']) @cache.cached(key_prefix=cache_key_with_lang) def download_file_by_filename(filename): media_root = current_app.config['MEDIA_ROOT'] return send_from_directory(media_root, filename) @main.route("/img/scielo.gif", methods=['GET']) def full_text_image(): return send_from_directory('static', 'img/full_text_scielo_img.gif') @main.route("/robots.txt", methods=['GET']) def get_robots_txt_file(): return send_from_directory('static', 'robots.txt') @main.route("/revistas/<path:journal_seg>/<string:page>.htm", methods=['GET']) def router_legacy_info_pages(journal_seg, page): """ Essa view function realiza o redirecionamento das URLs antigas para as novas URLs. Mantém um dicionário como uma tabela relacionamento entre o nome das páginas que pode ser: Página âncora [iaboutj.htm, eaboutj.htm, paboutj.htm] -> #about [iedboard.htm, eedboard.htm, pedboard.htm] -> #editors [iinstruc.htm einstruc.htm, pinstruc.htm]-> #instructions isubscrp.htm -> Sem âncora """ page_anchor = { 'iaboutj': '#about', 'eaboutj': '#about', 'paboutj': '#about', 'eedboard': '#editors', 'iedboard': '#editors', 'pedboard': '#editors', 'iinstruc': '#instructions', 'pinstruc': '#instructions', 'einstruc': '#instructions' } return redirect('%s%s' % (url_for('main.about_journal', url_seg=journal_seg), page_anchor.get(page, '')), code=301) @main.route("/api/v1/counter_dict", methods=['GET']) def router_counter_dicts(): """ Essa view function retorna um dicionário, em formato JSON, que mapeia PIDs a insumos necessários para o funcionamento das aplicações Matomo & COUNTER & SUSHI. """ end_date = request.args.get('end_date', '', type=str) try: end_date = datetime.strptime(end_date, '%Y-%m-%d') except ValueError: end_date = datetime.now() begin_date = end_date - timedelta(days=30) page = request.args.get('page', type=int) if not page: page = 1 limit = request.args.get('limit', type=int) if not limit or limit > 100 or limit < 0: limit = 100 results = {'dictionary_date': end_date, 'end_date': end_date.strftime('%Y-%m-%d %H-%M-%S'), 'begin_date': begin_date.strftime('%Y-%m-%d %H-%M-%S'), 'documents': {}, 'collection': current_app.config['OPAC_COLLECTION']} articles = controllers.get_articles_by_date_range(begin_date, end_date, page, limit) for a in articles.items: results['documents'].update(get_article_counter_data(a)) results['total'] = articles.total results['pages'] = articles.pages results['limit'] = articles.per_page results['page'] = articles.page return jsonify(results) def get_article_counter_data(article): return { article.aid: { "journal_acronym": article.journal.acronym, "pid": article.pid if article.pid else '', "aop_pid": article.aop_pid if article.aop_pid else '', "pid_v1": article.scielo_pids.get('v1', ''), "pid_v2": article.scielo_pids.get('v2', ''), "pid_v3": article.scielo_pids.get('v3', ''), "publication_date": article.publication_date, "default_language": article.original_language, "create": article.created, "update": article.updated } } @main.route('/cgi-bin/wxis.exe/iah/') def author_production(): # http://www.scielo.br/cgi-bin/wxis.exe/iah/ # ?IsisScript=iah/iah.xis&base=article%5Edlibrary&format=iso.pft& # lang=p&nextAction=lnk& # indexSearch=AU&exprSearch=MEIERHOFFER,+LILIAN+KOZSLOWSKI # -> # //search.scielo.org/?lang=pt&q=au:MEIERHOFFER,+LILIAN+KOZSLOWSKI search_url = current_app.config.get('URL_SEARCH') if not search_url: abort(404, "URL_SEARCH: {}".format(_('Página não encontrada'))) qs_exprSearch = request.args.get('exprSearch', type=str) or '' qs_indexSearch = request.args.get('indexSearch', type=str) or '' qs_lang = request.args.get('lang', type=str) or '' _lang = IAHX_LANGS.get(qs_lang) or '' _lang = _lang and "lang={}".format(_lang) _expr = "{}{}".format( qs_indexSearch == "AU" and "au:" or '', qs_exprSearch) _expr = _expr and "q={}".format(_expr.replace(" ", "+")) _and = _lang and _expr and "&" or '' _question_mark = (_lang or _expr) and "?" or "" if search_url.startswith("//"): protocol = "https:" elif search_url.startswith("http"): protocol = "" else: protocol = "https://" url = "{}{}{}{}{}{}".format( protocol, search_url, _question_mark, _lang, _and, _expr) return redirect(url, code=301)
[((1059, 1086), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1076, 1086), False, 'import logging\n'), ((1108, 1158), 'flask_babelex.gettext', '_', (['"""O periódico está indisponível por motivo de: """'], {}), "('O periódico está indisponível por motivo de: ')\n", (1109, 1158), True, 'from flask_babelex import gettext as _\n'), ((1177, 1224), 'flask_babelex.gettext', '_', (['"""O número está indisponível por motivo de: """'], {}), "('O número está indisponível por motivo de: ')\n", (1178, 1224), True, 'from flask_babelex import gettext as _\n'), ((1245, 1292), 'flask_babelex.gettext', '_', (['"""O artigo está indisponível por motivo de: """'], {}), "('O artigo está indisponível por motivo de: ')\n", (1246, 1292), True, 'from flask_babelex import gettext as _\n'), ((4989, 5033), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (5001, 5033), False, 'from webapp import cache\n'), ((6539, 6583), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (6551, 6583), False, 'from webapp import cache\n'), ((7125, 7169), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (7137, 7169), False, 'from webapp import cache\n'), ((8201, 8245), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (8213, 8245), False, 'from webapp import cache\n'), ((10219, 10271), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (10231, 10271), False, 'from webapp import cache\n'), ((10940, 10992), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (10952, 10992), False, 'from webapp import cache\n'), ((14994, 15038), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (15006, 15038), False, 'from webapp import cache\n'), ((17256, 17300), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (17268, 17300), False, 'from webapp import cache\n'), ((18945, 18989), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (18957, 18989), False, 'from webapp import cache\n'), ((20336, 20388), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (20348, 20388), False, 'from webapp import cache\n'), ((21076, 21128), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (21088, 21128), False, 'from webapp import cache\n'), ((22214, 22266), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (22226, 22266), False, 'from webapp import cache\n'), ((25187, 25231), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (25199, 25231), False, 'from webapp import cache\n'), ((27079, 27131), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (27091, 27131), False, 'from webapp import cache\n'), ((31711, 31763), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (31723, 31763), False, 'from webapp import cache\n'), ((33858, 33902), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (33870, 33902), False, 'from webapp import cache\n'), ((35622, 35666), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (35634, 35666), False, 'from webapp import cache\n'), ((38986, 39030), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (38998, 39030), False, 'from webapp import cache\n'), ((39934, 39978), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (39946, 39978), False, 'from webapp import cache\n'), ((46053, 46105), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (46065, 46105), False, 'from webapp import cache\n'), ((47144, 47196), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (47156, 47196), False, 'from webapp import cache\n'), ((47753, 47797), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (47765, 47797), False, 'from webapp import cache\n'), ((48108, 48160), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (48120, 48160), False, 'from webapp import cache\n'), ((48857, 48901), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (48869, 48901), False, 'from webapp import cache\n'), ((49892, 49944), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (49904, 49944), False, 'from webapp import cache\n'), ((50746, 50798), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang_with_qs'}), '(key_prefix=cache_key_with_lang_with_qs)\n', (50758, 50798), False, 'from webapp import cache\n'), ((54118, 54162), 'webapp.cache.cached', 'cache.cached', ([], {'key_prefix': 'cache_key_with_lang'}), '(key_prefix=cache_key_with_lang)\n', (54130, 54162), False, 'from webapp import cache\n'), ((1401, 1428), 'flask.url_for', 'url_for', (['endpoint'], {}), '(endpoint, **kwargs)\n', (1408, 1428), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((1440, 1470), 'urllib.parse.urljoin', 'urljoin', (['request.url_root', 'url'], {}), '(request.url_root, url)\n', (1447, 1470), False, 'from urllib.parse import urljoin\n'), ((3795, 3830), 'flask.current_app.config.get', 'current_app.config.get', (['"""LANGUAGES"""'], {}), "('LANGUAGES')\n", (3817, 3830), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((4367, 4402), 'flask.current_app.config.get', 'current_app.config.get', (['"""LANGUAGES"""'], {}), "('LANGUAGES')\n", (4389, 4402), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((4543, 4567), 'flask.request.args.get', 'request.args.get', (['"""hash"""'], {}), "('hash')\n", (4559, 4567), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((4691, 4709), 'flask.redirect', 'redirect', (['referrer'], {}), '(referrer)\n', (4699, 4709), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((5107, 5152), 'webapp.controllers.get_latest_news_by_lang', 'controllers.get_latest_news_by_lang', (['language'], {}), '(language)\n', (5142, 5152), False, 'from webapp import controllers\n'), ((5167, 5202), 'webapp.controllers.get_collection_tweets', 'controllers.get_collection_tweets', ([], {}), '()\n', (5200, 5202), False, 'from webapp import controllers\n'), ((5224, 5278), 'webapp.controllers.get_press_releases', 'controllers.get_press_releases', (["{'language': language}"], {}), "({'language': language})\n", (5254, 5278), False, 'from webapp import controllers\n'), ((6369, 6420), 'flask.render_template', 'render_template', (['"""collection/index.html"""'], {}), "('collection/index.html', **context)\n", (6384, 6420), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((6678, 6708), 'flask.request.args.get', 'request.args.get', (['"""status"""', '""""""'], {}), "('status', '')\n", (6694, 6708), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((6947, 7064), 'flask.render_template', 'render_template', (['"""collection/list_journal.html"""'], {}), "('collection/list_journal.html', **{'journals_list':\n journals_list, 'query_filter': query_filter})\n", (6962, 7064), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((7477, 7507), 'flask.request.args.get', 'request.args.get', (['"""status"""', '""""""'], {}), "('status', '')\n", (7493, 7507), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((7526, 7555), 'flask.request.args.get', 'request.args.get', (['"""query"""', '""""""'], {}), "('query', '')\n", (7542, 7555), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((7578, 7613), 'flask.request.args.get', 'request.args.get', (['"""filter"""', '"""areas"""'], {}), "('filter', 'areas')\n", (7594, 7613), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((7844, 7967), 'webapp.controllers.get_journals_grouped_by', 'controllers.get_journals_grouped_by', (['thematic_table[thematic_filter]', 'title_query'], {'query_filter': 'query_filter', 'lang': 'lang'}), '(thematic_table[thematic_filter],\n title_query, query_filter=query_filter, lang=lang)\n', (7879, 7967), False, 'from webapp import controllers\n'), ((8015, 8148), 'flask.render_template', 'render_template', (['"""collection/list_thematic.html"""'], {}), "('collection/list_thematic.html', **{'objects': objects,\n 'query_filter': query_filter, 'filter': thematic_filter})\n", (8030, 8148), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((8340, 8376), 'webapp.controllers.get_current_collection', 'controllers.get_current_collection', ([], {}), '()\n', (8374, 8376), False, 'from webapp import controllers\n'), ((8490, 8558), 'flask_babelex.gettext', '_', (["('10 últimos periódicos inseridos na coleção %s' % collection.name)"], {}), "('10 últimos periódicos inseridos na coleção %s' % collection.name)\n", (8491, 8558), True, 'from flask_babelex import gettext as _\n'), ((8571, 8649), 'werkzeug.contrib.atom.AtomFeed', 'AtomFeed', (['title'], {'subtitle': 'subtitle', 'feed_url': 'request.url', 'url': 'request.url_root'}), '(title, subtitle=subtitle, feed_url=request.url, url=request.url_root)\n', (8579, 8649), False, 'from werkzeug.contrib.atom import AtomFeed\n'), ((8706, 8803), 'webapp.controllers.get_journals_paginated', 'controllers.get_journals_paginated', ([], {'title_query': '""""""', 'page': '(1)', 'order_by': '"""-created"""', 'per_page': '(10)'}), "(title_query='', page=1, order_by=\n '-created', per_page=10)\n", (8740, 8803), False, 'from webapp import controllers\n'), ((10773, 10824), 'flask.render_template', 'render_template', (['"""collection/about.html"""'], {}), "('collection/about.html', **context)\n", (10788, 10824), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((11032, 11064), 'flask.request.args.get', 'request.args.get', (['"""script"""', 'None'], {}), "('script', None)\n", (11048, 11064), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((11075, 11104), 'flask.request.args.get', 'request.args.get', (['"""pid"""', 'None'], {}), "('pid', None)\n", (11091, 11104), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((11116, 11146), 'flask.request.args.get', 'request.args.get', (['"""tlng"""', 'None'], {}), "('tlng', None)\n", (11132, 11146), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((15082, 15125), 'webapp.controllers.get_journal_by_url_seg', 'controllers.get_journal_by_url_seg', (['url_seg'], {}), '(url_seg)\n', (15116, 15125), False, 'from webapp import controllers\n'), ((15301, 15338), 'webapp.utils.utils.fix_journal_last_issue', 'utils.fix_journal_last_issue', (['journal'], {}), '(journal)\n', (15329, 15338), False, 'from webapp.utils import utils\n'), ((15472, 15517), 'webapp.controllers.get_latest_news_by_lang', 'controllers.get_latest_news_by_lang', (['language'], {}), '(language)\n', (15507, 15517), False, 'from webapp import controllers\n'), ((15561, 15635), 'webapp.controllers.get_press_releases', 'controllers.get_press_releases', (["{'journal': journal, 'language': language}"], {}), "({'journal': journal, 'language': language})\n", (15591, 15635), False, 'from webapp import controllers\n'), ((16517, 16557), 'webapp.controllers.get_journal_metrics', 'controllers.get_journal_metrics', (['journal'], {}), '(journal)\n', (16548, 16557), False, 'from webapp import controllers\n'), ((17156, 17205), 'flask.render_template', 'render_template', (['"""journal/detail.html"""'], {}), "('journal/detail.html', **context)\n", (17171, 17205), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((17342, 17385), 'webapp.controllers.get_journal_by_url_seg', 'controllers.get_journal_by_url_seg', (['url_seg'], {}), '(url_seg)\n', (17376, 17385), False, 'from webapp import controllers\n'), ((17570, 17628), 'webapp.controllers.get_issues_by_jid', 'controllers.get_issues_by_jid', (['journal.jid'], {'is_public': '(True)'}), '(journal.jid, is_public=True)\n', (17599, 17628), False, 'from webapp import controllers\n'), ((17691, 17754), 'webapp.controllers.get_articles_by_iid', 'controllers.get_articles_by_iid', (['last_issue.iid'], {'is_public': '(True)'}), '(last_issue.iid, is_public=True)\n', (17722, 17754), False, 'from webapp import controllers\n'), ((19082, 19125), 'webapp.controllers.get_journal_by_url_seg', 'controllers.get_journal_by_url_seg', (['url_seg'], {}), '(url_seg)\n', (19116, 19125), False, 'from webapp import controllers\n'), ((19316, 19353), 'webapp.utils.utils.fix_journal_last_issue', 'utils.fix_journal_last_issue', (['journal'], {}), '(journal)\n', (19344, 19353), False, 'from webapp.utils import utils\n'), ((19729, 19798), 'webapp.controllers.get_page_by_journal_acron_lang', 'controllers.get_page_by_journal_acron_lang', (['journal.acronym', 'language'], {}), '(journal.acronym, language)\n', (19771, 19798), False, 'from webapp import controllers\n'), ((20221, 20269), 'flask.render_template', 'render_template', (['"""journal/about.html"""'], {}), "('journal/about.html', **context)\n", (20236, 20269), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((20528, 20567), 'flask.request.args.get', 'request.args.get', (['"""query"""', '""""""'], {'type': 'str'}), "('query', '', type=str)\n", (20544, 20567), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((20587, 20633), 'flask.request.args.get', 'request.args.get', (['"""query_filter"""', '""""""'], {'type': 'str'}), "('query_filter', '', type=str)\n", (20603, 20633), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((20645, 20682), 'flask.request.args.get', 'request.args.get', (['"""page"""', '(1)'], {'type': 'int'}), "('page', 1, type=int)\n", (20661, 20682), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((20751, 20873), 'webapp.controllers.get_alpha_list_from_paginated_journals', 'controllers.get_alpha_list_from_paginated_journals', ([], {'title_query': 'query', 'query_filter': 'query_filter', 'page': 'page', 'lang': 'lang'}), '(title_query=query,\n query_filter=query_filter, page=page, lang=lang)\n', (20801, 20873), False, 'from webapp import controllers\n'), ((20979, 21001), 'flask.jsonify', 'jsonify', (['response_data'], {}), '(response_data)\n', (20986, 21001), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((21271, 21310), 'flask.request.args.get', 'request.args.get', (['"""query"""', '""""""'], {'type': 'str'}), "('query', '', type=str)\n", (21287, 21310), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((21330, 21376), 'flask.request.args.get', 'request.args.get', (['"""query_filter"""', '""""""'], {'type': 'str'}), "('query_filter', '', type=str)\n", (21346, 21376), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((21390, 21435), 'flask.request.args.get', 'request.args.get', (['"""filter"""', '"""areas"""'], {'type': 'str'}), "('filter', 'areas', type=str)\n", (21406, 21435), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((22102, 22118), 'flask.jsonify', 'jsonify', (['objects'], {}), '(objects)\n', (22109, 22118), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((23558, 23591), 'webapp.utils.utils.is_recaptcha_valid', 'utils.is_recaptcha_valid', (['request'], {}), '(request)\n', (23582, 23591), False, 'from webapp.utils import utils\n'), ((24677, 24720), 'webapp.controllers.get_journal_by_url_seg', 'controllers.get_journal_by_url_seg', (['url_seg'], {}), '(url_seg)\n', (24711, 24720), False, 'from webapp import controllers\n'), ((24852, 24916), 'flask.render_template', 'render_template', (['"""journal/includes/contact_form.html"""'], {}), "('journal/includes/contact_form.html', **context)\n", (24867, 24916), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((25271, 25314), 'webapp.controllers.get_journal_by_url_seg', 'controllers.get_journal_by_url_seg', (['url_seg'], {}), '(url_seg)\n', (25305, 25314), False, 'from webapp import controllers\n'), ((25664, 25730), 'webapp.controllers.get_issues_for_grid_by_jid', 'controllers.get_issues_for_grid_by_jid', (['journal.id'], {'is_public': '(True)'}), '(journal.id, is_public=True)\n', (25702, 25730), False, 'from webapp import controllers\n'), ((26580, 26625), 'flask.render_template', 'render_template', (['"""issue/grid.html"""'], {}), "('issue/grid.html', **context)\n", (26595, 26625), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((27208, 27248), 'flask.request.args.get', 'request.args.get', (['"""goto"""', 'None'], {'type': 'str'}), "('goto', None, type=str)\n", (27224, 27248), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((27765, 27821), 'webapp.controllers.get_issue_by_url_seg', 'controllers.get_issue_by_url_seg', (['url_seg', 'url_seg_issue'], {}), '(url_seg, url_seg_issue)\n', (27797, 27821), False, 'from webapp import controllers\n'), ((28174, 28211), 'webapp.utils.utils.fix_journal_last_issue', 'utils.fix_journal_last_issue', (['journal'], {}), '(journal)\n', (28202, 28211), False, 'from webapp.utils import utils\n'), ((28465, 28523), 'webapp.controllers.get_articles_by_iid', 'controllers.get_articles_by_iid', (['issue.iid'], {'is_public': '(True)'}), '(issue.iid, is_public=True)\n', (28496, 28523), False, 'from webapp import controllers\n'), ((30407, 30451), 'flask.render_template', 'render_template', (['"""issue/toc.html"""'], {}), "('issue/toc.html', **context)\n", (30422, 30451), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((31621, 31668), 'webapp.utils.utils.get_prev_issue', 'utils.get_prev_issue', (['all_issues', 'current_issue'], {}), '(all_issues, current_issue)\n', (31641, 31668), False, 'from webapp.utils import utils\n'), ((32017, 32057), 'flask.request.args.get', 'request.args.get', (['"""goto"""', 'None'], {'type': 'str'}), "('goto', None, type=str)\n", (32033, 32057), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((32341, 32378), 'webapp.utils.utils.fix_journal_last_issue', 'utils.fix_journal_last_issue', (['journal'], {}), '(journal)\n', (32369, 32378), False, 'from webapp.utils import utils\n'), ((33748, 33792), 'flask.render_template', 'render_template', (['"""issue/toc.html"""'], {}), "('issue/toc.html', **context)\n", (33763, 33792), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((33955, 34011), 'webapp.controllers.get_issue_by_url_seg', 'controllers.get_issue_by_url_seg', (['url_seg', 'url_seg_issue'], {}), '(url_seg, url_seg_issue)\n', (33987, 34011), False, 'from webapp import controllers\n'), ((34326, 34384), 'webapp.controllers.get_articles_by_iid', 'controllers.get_articles_by_iid', (['issue.iid'], {'is_public': '(True)'}), '(issue.iid, is_public=True)\n', (34357, 34384), False, 'from webapp import controllers\n'), ((35711, 35746), 'webapp.controllers.get_article_by_pid', 'controllers.get_article_by_pid', (['pid'], {}), '(pid)\n', (35741, 35746), False, 'from webapp import controllers\n'), ((36387, 36482), 'packtools.HTMLGenerator.parse', 'HTMLGenerator.parse', (['xml'], {'valid_only': '(False)', 'gs_abstract': 'gs_abstract', 'output_style': '"""website"""'}), "(xml, valid_only=False, gs_abstract=gs_abstract,\n output_style='website')\n", (36406, 36482), False, 'from packtools import HTMLGenerator\n'), ((39118, 39174), 'webapp.controllers.get_issue_by_url_seg', 'controllers.get_issue_by_url_seg', (['url_seg', 'url_seg_issue'], {}), '(url_seg, url_seg_issue)\n', (39150, 39174), False, 'from webapp import controllers\n'), ((39254, 39326), 'webapp.controllers.get_article_by_issue_article_seg', 'controllers.get_article_by_issue_article_seg', (['issue.iid', 'url_seg_article'], {}), '(issue.iid, url_seg_article)\n', (39298, 39326), False, 'from webapp import controllers\n'), ((40225, 40269), 'flask.request.args.get', 'request.args.get', (['"""format"""', '"""html"""'], {'type': 'str'}), "('format', 'html', type=str)\n", (40241, 40269), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((46136, 46175), 'flask.request.args.get', 'request.args.get', (['"""doi"""', 'None'], {'type': 'str'}), "('doi', None, type=str)\n", (46152, 46175), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((46186, 46225), 'flask.request.args.get', 'request.args.get', (['"""pid"""', 'None'], {'type': 'str'}), "('pid', None, type=str)\n", (46202, 46225), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((46241, 46285), 'flask.request.args.get', 'request.args.get', (['"""pdf_path"""', 'None'], {'type': 'str'}), "('pdf_path', None, type=str)\n", (46257, 46285), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((46297, 46337), 'flask.request.args.get', 'request.args.get', (['"""lang"""', 'None'], {'type': 'str'}), "('lang', None, type=str)\n", (46313, 46337), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((47397, 47422), 'mimetypes.guess_type', 'mimetypes.guess_type', (['url'], {}), '(url)\n', (47417, 47422), False, 'import mimetypes\n'), ((48216, 48259), 'flask.request.args.get', 'request.args.get', (['"""resource_ssm_path"""', 'None'], {}), "('resource_ssm_path', None)\n", (48232, 48259), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((49249, 49305), 'webapp.controllers.get_issue_by_url_seg', 'controllers.get_issue_by_url_seg', (['url_seg', 'url_seg_issue'], {}), '(url_seg, url_seg_issue)\n', (49281, 49305), False, 'from webapp import controllers\n'), ((49385, 49457), 'webapp.controllers.get_article_by_issue_article_seg', 'controllers.get_article_by_issue_article_seg', (['issue.iid', 'url_seg_article'], {}), '(issue.iid, url_seg_article)\n', (49429, 49457), False, 'from webapp import controllers\n'), ((50067, 50116), 'webapp.controllers.get_journal_by_url_seg', 'controllers.get_journal_by_url_seg', (['journal_acron'], {}), '(journal_acron)\n', (50101, 50116), False, 'from webapp import controllers\n'), ((50257, 50342), 'webapp.controllers.get_article_by_pdf_filename', 'controllers.get_article_by_pdf_filename', (['journal_acron', 'issue_info', 'pdf_filename'], {}), '(journal_acron, issue_info, pdf_filename\n )\n', (50296, 50342), False, 'from webapp import controllers\n'), ((50854, 50883), 'flask.request.args.get', 'request.args.get', (['"""pid"""', 'None'], {}), "('pid', None)\n", (50870, 50883), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((50894, 50923), 'flask.request.args.get', 'request.args.get', (['"""lng"""', 'None'], {}), "('lng', None)\n", (50910, 50923), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((51111, 51149), 'webapp.controllers.get_article_by_pid_v1', 'controllers.get_article_by_pid_v1', (['pid'], {}), '(pid)\n', (51144, 51149), False, 'from webapp import controllers\n'), ((51663, 51697), 'webapp.forms.EmailShareForm', 'forms.EmailShareForm', (['request.form'], {}), '(request.form)\n', (51683, 51697), False, 'from webapp import forms\n'), ((52602, 52653), 'flask.render_template', 'render_template', (['"""email/email_form.html"""'], {}), "('email/email_form.html', **context)\n", (52617, 52653), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((52818, 52847), 'webapp.forms.ErrorForm', 'forms.ErrorForm', (['request.form'], {}), '(request.form)\n', (52833, 52847), False, 'from webapp import forms\n'), ((53922, 53976), 'flask.render_template', 'render_template', (['"""includes/error_form.html"""'], {}), "('includes/error_form.html', **context)\n", (53937, 53976), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((54265, 54306), 'flask.send_from_directory', 'send_from_directory', (['media_root', 'filename'], {}), '(media_root, filename)\n', (54284, 54306), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((54391, 54452), 'flask.send_from_directory', 'send_from_directory', (['"""static"""', '"""img/full_text_scielo_img.gif"""'], {}), "('static', 'img/full_text_scielo_img.gif')\n", (54410, 54452), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((54537, 54580), 'flask.send_from_directory', 'send_from_directory', (['"""static"""', '"""robots.txt"""'], {}), "('static', 'robots.txt')\n", (54556, 54580), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((55907, 55949), 'flask.request.args.get', 'request.args.get', (['"""end_date"""', '""""""'], {'type': 'str'}), "('end_date', '', type=str)\n", (55923, 55949), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((56134, 56168), 'flask.request.args.get', 'request.args.get', (['"""page"""'], {'type': 'int'}), "('page', type=int)\n", (56150, 56168), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((56216, 56251), 'flask.request.args.get', 'request.args.get', (['"""limit"""'], {'type': 'int'}), "('limit', type=int)\n", (56232, 56251), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((56617, 56690), 'webapp.controllers.get_articles_by_date_range', 'controllers.get_articles_by_date_range', (['begin_date', 'end_date', 'page', 'limit'], {}), '(begin_date, end_date, page, limit)\n', (56655, 56690), False, 'from webapp import controllers\n'), ((56951, 56967), 'flask.jsonify', 'jsonify', (['results'], {}), '(results)\n', (56958, 56967), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((57978, 58014), 'flask.current_app.config.get', 'current_app.config.get', (['"""URL_SEARCH"""'], {}), "('URL_SEARCH')\n", (58000, 58014), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((58915, 58938), 'flask.redirect', 'redirect', (['url'], {'code': '(301)'}), '(url, code=301)\n', (58923, 58938), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((1964, 1998), 'requests.get', 'requests.get', (['url'], {'timeout': 'timeout'}), '(url, timeout=timeout)\n', (1976, 1998), False, 'import requests\n'), ((3328, 3350), 'webapp.forms.EmailShareForm', 'forms.EmailShareForm', ([], {}), '()\n', (3348, 3350), False, 'from webapp import forms\n'), ((3384, 3403), 'webapp.forms.ContactForm', 'forms.ContactForm', ([], {}), '()\n', (3401, 3403), False, 'from webapp import forms\n'), ((3429, 3446), 'webapp.forms.ErrorForm', 'forms.ErrorForm', ([], {}), '()\n', (3444, 3446), False, 'from webapp import forms\n'), ((4204, 4250), 'flask.current_app.config.get', 'current_app.config.get', (['"""BABEL_DEFAULT_LOCALE"""'], {}), "('BABEL_DEFAULT_LOCALE')\n", (4226, 4250), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((6811, 6853), 'webapp.controllers.get_journal_json_data', 'controllers.get_journal_json_data', (['journal'], {}), '(journal)\n', (6844, 6853), False, 'from webapp import controllers\n'), ((9012, 9070), 'webapp.controllers.get_issues_by_jid', 'controllers.get_issues_by_jid', (['journal.jid'], {'is_public': '(True)'}), '(journal.jid, is_public=True)\n', (9041, 9070), False, 'from webapp import controllers\n'), ((9333, 9346), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (9344, 9346), False, 'from collections import OrderedDict\n'), ((10457, 10511), 'webapp.controllers.get_page_by_slug_name', 'controllers.get_page_by_slug_name', (['slug_name', 'language'], {}), '(slug_name, language)\n', (10490, 10511), False, 'from webapp import controllers\n'), ((10688, 10727), 'webapp.controllers.get_pages_by_lang', 'controllers.get_pages_by_lang', (['language'], {}), '(language)\n', (10717, 10727), False, 'from webapp import controllers\n'), ((14864, 14915), 'flask.url_for', 'url_for', (['"""main.journal_detail"""'], {'url_seg': 'journal_seg'}), "('main.journal_detail', url_seg=journal_seg)\n", (14871, 14915), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((15952, 16037), 'webapp.controllers.get_recent_articles_of_issue', 'controllers.get_recent_articles_of_issue', (['journal.last_issue.iid'], {'is_public': '(True)'}), '(journal.last_issue.iid, is_public=True\n )\n', (15992, 16037), False, 'from webapp import controllers\n'), ((21528, 21628), 'webapp.controllers.get_journals_grouped_by', 'controllers.get_journals_grouped_by', (['"""study_areas"""', 'query'], {'query_filter': 'query_filter', 'lang': 'lang'}), "('study_areas', query, query_filter=\n query_filter, lang=lang)\n", (21563, 21628), False, 'from webapp import controllers\n'), ((23609, 23640), 'webapp.forms.ContactForm', 'forms.ContactForm', (['request.form'], {}), '(request.form)\n', (23626, 23640), False, 'from webapp import forms\n'), ((23660, 23703), 'webapp.controllers.get_journal_by_url_seg', 'controllers.get_journal_by_url_seg', (['url_seg'], {}), '(url_seg)\n', (23694, 23703), False, 'from webapp import controllers\n'), ((25094, 25137), 'flask.url_for', 'url_for', (['"""main.issue_grid"""'], {'url_seg': 'url_seg'}), "('main.issue_grid', url_seg=url_seg)\n", (25101, 25137), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((26892, 26963), 'flask.url_for', 'url_for', (['"""main.issue_toc"""'], {'url_seg': 'url_seg', 'url_seg_issue': 'url_seg_issue'}), "('main.issue_toc', url_seg=url_seg, url_seg_issue=url_seg_issue)\n", (26899, 26963), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((28320, 28360), 'flask.request.args.get', 'request.args.get', (['"""goto"""', 'None'], {'type': 'str'}), "('goto', None, type=str)\n", (28336, 28360), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((28394, 28422), 'flask.redirect', 'redirect', (['goto_url'], {'code': '(301)'}), '(goto_url, code=301)\n', (28402, 28422), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((29797, 29868), 'flask.url_for', 'url_for', (['"""main.issue_toc"""'], {'url_seg': 'url_seg', 'url_seg_issue': 'url_seg_issue'}), "('main.issue_toc', url_seg=url_seg, url_seg_issue=url_seg_issue)\n", (29804, 29868), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((30613, 30684), 'webapp.controllers.get_issues_by_jid', 'controllers.get_issues_by_jid', (['current_issue.journal.id'], {'is_public': '(True)'}), '(current_issue.journal.id, is_public=True)\n', (30642, 30684), False, 'from webapp import controllers\n'), ((30740, 30787), 'webapp.utils.utils.get_next_issue', 'utils.get_next_issue', (['all_issues', 'current_issue'], {}), '(all_issues, current_issue)\n', (30760, 30787), False, 'from webapp.utils import utils\n'), ((31131, 31233), 'flask.url_for', 'url_for', (['"""main.issue_toc"""'], {'url_seg': 'selected_issue.journal.url_segment', 'url_seg_issue': 'url_seg_issue'}), "('main.issue_toc', url_seg=selected_issue.journal.url_segment,\n url_seg_issue=url_seg_issue)\n", (31138, 31233), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((31445, 31516), 'webapp.controllers.get_issues_by_jid', 'controllers.get_issues_by_jid', (['current_issue.journal.id'], {'is_public': '(True)'}), '(current_issue.journal.id, is_public=True)\n', (31474, 31516), False, 'from webapp import controllers\n'), ((31562, 31609), 'webapp.utils.utils.get_next_issue', 'utils.get_next_issue', (['all_issues', 'current_issue'], {}), '(all_issues, current_issue)\n', (31582, 31609), False, 'from webapp.utils import utils\n'), ((31876, 31911), 'webapp.controllers.get_aop_issues', 'controllers.get_aop_issues', (['url_seg'], {}), '(url_seg)\n', (31902, 31911), False, 'from webapp import controllers\n'), ((32451, 32513), 'webapp.controllers.get_articles_by_iid', 'controllers.get_articles_by_iid', (['aop_issue.iid'], {'is_public': '(True)'}), '(aop_issue.iid, is_public=True)\n', (32482, 32513), False, 'from webapp import controllers\n'), ((33234, 33274), 'flask.url_for', 'url_for', (['"""main.aop_toc"""'], {'url_seg': 'url_seg'}), "('main.aop_toc', url_seg=url_seg)\n", (33241, 33274), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((35786, 35825), 'webapp.controllers.get_article_by_oap_pid', 'controllers.get_article_by_oap_pid', (['pid'], {}), '(pid)\n', (35820, 35825), False, 'from webapp import controllers\n'), ((35915, 36013), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'article.journal.acronym', 'article_pid_v3': 'article.aid'}), "('main.article_detail_v3', url_seg=article.journal.acronym,\n article_pid_v3=article.aid)\n", (35922, 36013), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((36353, 36368), 'io.BytesIO', 'BytesIO', (['result'], {}), '(result)\n', (36360, 36368), False, 'from io import BytesIO\n'), ((38399, 38412), 'urllib.parse.urlparse', 'urlparse', (['url'], {}), '(url)\n', (38407, 38412), False, 'from urllib.parse import urlparse\n'), ((39369, 39459), 'webapp.controllers.get_article_by_aop_url_segs', 'controllers.get_article_by_aop_url_segs', (['issue.journal', 'url_seg_issue', 'url_seg_article'], {}), '(issue.journal, url_seg_issue,\n url_seg_article)\n', (39408, 39459), False, 'from webapp import controllers\n'), ((39744, 39791), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {}), "('main.article_detail_v3', **req_params)\n", (39751, 39791), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((40052, 40086), 'flask.request.args.get', 'request.args.get', (['"""lang"""'], {'type': 'str'}), "('lang', type=str)\n", (40068, 40086), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((40109, 40143), 'flask.request.args.get', 'request.args.get', (['"""goto"""'], {'type': 'str'}), "('goto', type=str)\n", (40125, 40143), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((40166, 40200), 'flask.request.args.get', 'request.args.get', (['"""stop"""'], {'type': 'str'}), "('stop', type=str)\n", (40182, 40200), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((40501, 40580), 'webapp.controllers.get_article', 'controllers.get_article', (['article_pid_v3', 'url_seg', 'qs_lang', 'gs_abstract', 'qs_goto'], {}), '(article_pid_v3, url_seg, qs_lang, gs_abstract, qs_goto)\n', (40524, 40580), False, 'from webapp import controllers\n'), ((44783, 44832), 'flask.render_template', 'render_template', (['"""article/detail.html"""'], {}), "('article/detail.html', **context)\n", (44798, 44832), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((45646, 45667), 'flask.make_response', 'make_response', (['result'], {}), '(result)\n', (45659, 45667), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((46624, 46671), 'flask.render_template', 'render_template', (['"""article/epdf.html"""'], {}), "('article/epdf.html', **context)\n", (46639, 46671), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((47062, 47087), 'mimetypes.guess_type', 'mimetypes.guess_type', (['url'], {}), '(url)\n', (47082, 47087), False, 'import mimetypes\n'), ((47103, 47140), 'flask.Response', 'Response', (['response'], {'mimetype': 'mimetype'}), '(response, mimetype=mimetype)\n', (47111, 47140), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((47643, 47684), 'flask.Response', 'Response', (['ssm_response'], {'mimetype': 'mimetype'}), '(ssm_response, mimetype=mimetype)\n', (47651, 47684), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((49741, 49788), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {}), "('main.article_detail_v3', **req_params)\n", (49748, 49788), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((50456, 50596), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'article.journal.url_segment', 'article_pid_v3': 'article.aid', 'format': '"""pdf"""', 'lang': 'article._pdf_lang'}), "('main.article_detail_v3', url_seg=article.journal.url_segment,\n article_pid_v3=article.aid, format='pdf', lang=article._pdf_lang)\n", (50463, 50596), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((51247, 51349), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'article.journal.url_segment', 'article_pid_v3': 'article.aid'}), "('main.article_detail_v3', url_seg=article.journal.url_segment,\n article_pid_v3=article.aid)\n", (51254, 51349), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((51856, 51994), 'webapp.controllers.send_email_share', 'controllers.send_email_share', (["form.data['your_email']", 'recipients', "form.data['share_url']", "form.data['subject']", "form.data['comment']"], {}), "(form.data['your_email'], recipients, form.data\n ['share_url'], form.data['subject'], form.data['comment'])\n", (51884, 51994), False, 'from webapp import controllers\n'), ((52566, 52589), 'flask.request.args.get', 'request.args.get', (['"""url"""'], {}), "('url')\n", (52582, 52589), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((53028, 53211), 'webapp.controllers.send_email_error', 'controllers.send_email_error', (["form.data['name']", "form.data['your_email']", 'recipients', "form.data['url']", "form.data['error_type']", "form.data['message']", "form.data['page_title']"], {}), "(form.data['name'], form.data['your_email'],\n recipients, form.data['url'], form.data['error_type'], form.data[\n 'message'], form.data['page_title'])\n", (53056, 53211), False, 'from webapp import controllers\n'), ((53886, 53909), 'flask.request.args.get', 'request.args.get', (['"""url"""'], {}), "('url')\n", (53902, 53909), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((55978, 56017), 'datetime.datetime.strptime', 'datetime.strptime', (['end_date', '"""%Y-%m-%d"""'], {}), "(end_date, '%Y-%m-%d')\n", (55995, 56017), False, 'from datetime import datetime, timedelta\n'), ((56103, 56121), 'datetime.timedelta', 'timedelta', ([], {'days': '(30)'}), '(days=30)\n', (56112, 56121), False, 'from datetime import datetime, timedelta\n'), ((58131, 58171), 'flask.request.args.get', 'request.args.get', (['"""exprSearch"""'], {'type': 'str'}), "('exprSearch', type=str)\n", (58147, 58171), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((58199, 58240), 'flask.request.args.get', 'request.args.get', (['"""indexSearch"""'], {'type': 'str'}), "('indexSearch', type=str)\n", (58215, 58240), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((58261, 58295), 'flask.request.args.get', 'request.args.get', (['"""lang"""'], {'type': 'str'}), "('lang', type=str)\n", (58277, 58295), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((2760, 2796), 'webapp.controllers.get_current_collection', 'controllers.get_current_collection', ([], {}), '()\n', (2794, 2796), False, 'from webapp import controllers\n'), ((3938, 3952), 'flask.session.keys', 'session.keys', ([], {}), '()\n', (3950, 3952), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((4467, 4497), 'flask_babelex.gettext', '_', (['"""Código de idioma inválido"""'], {}), "('Código de idioma inválido')\n", (4468, 4497), True, 'from flask_babelex import gettext as _\n'), ((4922, 4968), 'flask.current_app.config.get', 'current_app.config.get', (['"""BABEL_DEFAULT_LOCALE"""'], {}), "('BABEL_DEFAULT_LOCALE')\n", (4944, 4968), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((6877, 6928), 'webapp.controllers.get_journals', 'controllers.get_journals', ([], {'query_filter': 'query_filter'}), '(query_filter=query_filter)\n', (6901, 6928), False, 'from webapp import controllers\n'), ((8429, 8473), 'flask_babelex.gettext', '_', (['"""Últimos periódicos inseridos na coleção"""'], {}), "('Últimos periódicos inseridos na coleção')\n", (8430, 8473), True, 'from flask_babelex import gettext as _\n'), ((9191, 9254), 'webapp.controllers.get_articles_by_iid', 'controllers.get_articles_by_iid', (['last_issue.iid'], {'is_public': '(True)'}), '(last_issue.iid, is_public=True)\n', (9222, 9254), False, 'from webapp import controllers\n'), ((9762, 9825), 'flask.render_template', 'render_template', (['"""collection/list_feed_content.html"""'], {}), "('collection/list_feed_content.html', **context)\n", (9777, 9825), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((11426, 11495), 'flask_babelex.gettext', '_', (["(u'Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)"], {}), "(u'Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)\n", (11427, 11495), True, 'from flask_babelex import gettext as _\n'), ((14702, 14715), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (14710, 14715), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((15166, 15195), 'flask_babelex.gettext', '_', (['"""Periódico não encontrado"""'], {}), "('Periódico não encontrado')\n", (15167, 15195), True, 'from flask_babelex import gettext as _\n'), ((17426, 17455), 'flask_babelex.gettext', '_', (['"""Periódico não encontrado"""'], {}), "('Periódico não encontrado')\n", (17427, 17455), True, 'from flask_babelex import gettext as _\n'), ((17904, 17937), 'webapp.utils.utils.get_label_issue', 'utils.get_label_issue', (['last_issue'], {}), '(last_issue)\n', (17925, 17937), False, 'from webapp.utils import utils\n'), ((18332, 18391), 'flask.render_template', 'render_template', (['"""issue/feed_content.html"""'], {'article': 'article'}), "('issue/feed_content.html', article=article)\n", (18347, 18391), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((19166, 19195), 'flask_babelex.gettext', '_', (['"""Periódico não encontrado"""'], {}), "('Periódico não encontrado')\n", (19167, 19195), True, 'from flask_babelex import gettext as _\n'), ((20470, 20513), 'flask_babelex.gettext', '_', (['"""Requisição inválida. Deve ser por ajax"""'], {}), "('Requisição inválida. Deve ser por ajax')\n", (20471, 20513), True, 'from flask_babelex import gettext as _\n'), ((21213, 21256), 'flask_babelex.gettext', '_', (['"""Requisição inválida. Deve ser por ajax"""'], {}), "('Requisição inválida. Deve ser por ajax')\n", (21214, 21256), True, 'from flask_babelex import gettext as _\n'), ((21668, 21774), 'webapp.controllers.get_journals_grouped_by', 'controllers.get_journals_grouped_by', (['"""subject_categories"""', 'query'], {'query_filter': 'query_filter', 'lang': 'lang'}), "('subject_categories', query,\n query_filter=query_filter, lang=lang)\n", (21703, 21774), False, 'from webapp import controllers\n'), ((22383, 22446), 'flask_babelex.gettext', '_', (['"""Parámetro "extension" é inválido, deve ser "csv" ou "xls"."""'], {}), '(\'Parámetro "extension" é inválido, deve ser "csv" ou "xls".\')\n', (22384, 22446), True, 'from flask_babelex import gettext as _\n'), ((22794, 22833), 'flask.request.args.get', 'request.args.get', (['"""query"""', '""""""'], {'type': 'str'}), "('query', '', type=str)\n", (22810, 22833), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((23233, 23266), 'flask.Response', 'Response', (['data'], {'mimetype': 'mimetype'}), '(data, mimetype=mimetype)\n', (23241, 23266), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((23508, 23548), 'flask_babelex.gettext', '_', (['"""Requisição inválida, deve ser ajax."""'], {}), "('Requisição inválida, deve ser ajax.')\n", (23509, 23548), True, 'from flask_babelex import gettext as _\n'), ((23911, 24024), 'webapp.controllers.send_email_contact', 'controllers.send_email_contact', (['recipients', "form.data['name']", "form.data['your_email']", "form.data['message']"], {}), "(recipients, form.data['name'], form.data[\n 'your_email'], form.data['message'])\n", (23941, 24024), False, 'from webapp import controllers\n'), ((24525, 24568), 'flask_babelex.gettext', '_', (['"""Requisição inválida, captcha inválido."""'], {}), "('Requisição inválida, captcha inválido.')\n", (24526, 24568), True, 'from flask_babelex import gettext as _\n'), ((24760, 24789), 'flask_babelex.gettext', '_', (['"""Periódico não encontrado"""'], {}), "('Periódico não encontrado')\n", (24761, 24789), True, 'from flask_babelex import gettext as _\n'), ((25355, 25384), 'flask_babelex.gettext', '_', (['"""Periódico não encontrado"""'], {}), "('Periódico não encontrado')\n", (25356, 25384), True, 'from flask_babelex import gettext as _\n'), ((26810, 26850), 'flask.url_for', 'url_for', (['"""main.aop_toc"""'], {'url_seg': 'url_seg'}), "('main.aop_toc', url_seg=url_seg)\n", (26817, 26850), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((27432, 27472), 'flask.url_for', 'url_for', (['"""main.aop_toc"""'], {'url_seg': 'url_seg'}), "('main.aop_toc', url_seg=url_seg)\n", (27439, 27472), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((27859, 27885), 'flask_babelex.gettext', '_', (['"""Número não encontrado"""'], {}), "('Número não encontrado')\n", (27860, 27885), True, 'from flask_babelex import gettext as _\n'), ((30848, 30895), 'webapp.utils.utils.get_prev_issue', 'utils.get_prev_issue', (['all_issues', 'current_issue'], {}), '(all_issues, current_issue)\n', (30868, 30895), False, 'from webapp.utils import utils\n'), ((31808, 31849), 'flask.request.args.get', 'request.args.get', (['"""section"""', '""""""'], {'type': 'str'}), "('section', '', type=str)\n", (31824, 31849), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((31960, 32003), 'flask_babelex.gettext', '_', (['"""Artigos ahead of print não encontrados"""'], {}), "('Artigos ahead of print não encontrados')\n", (31961, 32003), True, 'from flask_babelex import gettext as _\n'), ((32177, 32200), 'flask.redirect', 'redirect', (['url'], {'code': '(301)'}), '(url, code=301)\n', (32185, 32200), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((32628, 32671), 'flask_babelex.gettext', '_', (['"""Artigos ahead of print não encontrados"""'], {}), "('Artigos ahead of print não encontrados')\n", (32629, 32671), True, 'from flask_babelex import gettext as _\n'), ((34050, 34076), 'flask_babelex.gettext', '_', (['"""Número não encontrado"""'], {}), "('Número não encontrado')\n", (34051, 34076), True, 'from flask_babelex import gettext as _\n'), ((34540, 34568), 'webapp.utils.utils.get_label_issue', 'utils.get_label_issue', (['issue'], {}), '(issue)\n', (34561, 34568), False, 'from webapp.utils import utils\n'), ((34908, 34967), 'flask.render_template', 'render_template', (['"""issue/feed_content.html"""'], {'article': 'article'}), "('issue/feed_content.html', article=article)\n", (34923, 34967), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((35866, 35892), 'flask_babelex.gettext', '_', (['"""Artigo não encontrado"""'], {}), "('Artigo não encontrado')\n", (35867, 35892), True, 'from flask_babelex import gettext as _\n'), ((39212, 39237), 'flask_babelex.gettext', '_', (['"""Issue não encontrado"""'], {}), "('Issue não encontrado')\n", (39213, 39237), True, 'from flask_babelex import gettext as _\n'), ((39521, 39547), 'flask_babelex.gettext', '_', (['"""Artigo não encontrado"""'], {}), "('Artigo não encontrado')\n", (39522, 39547), True, 'from flask_babelex import gettext as _\n'), ((42694, 42715), 'urllib.parse.urlparse', 'urlparse', (['request.url'], {}), '(request.url)\n', (42702, 42715), False, 'from urllib.parse import urlparse\n'), ((43937, 44093), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'article.journal.url_segment', 'article_pid_v3': 'article_pid_v3', 'format': '"""xml"""', 'lang': 'article.original_language'}), "('main.article_detail_v3', url_seg=article.journal.url_segment,\n article_pid_v3=article_pid_v3, format='xml', lang=article.original_language\n )\n", (43944, 44093), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((44656, 44690), 'webapp.controllers.related_links', 'controllers.related_links', (['article'], {}), '(article)\n', (44681, 44690), False, 'from webapp import controllers\n'), ((45374, 45430), 'flask_babelex.gettext', '_', (['"""Recurso do Artigo não encontrado. Caminho inválido!"""'], {}), "('Recurso do Artigo não encontrado. Caminho inválido!')\n", (45375, 45430), True, 'from flask_babelex import gettext as _\n'), ((46402, 46459), 'flask_babelex.gettext', '_', (['"""Parâmetros insuficientes para obter o EPDF do artigo"""'], {}), "('Parâmetros insuficientes para obter o EPDF do artigo')\n", (46403, 46459), True, 'from flask_babelex import gettext as _\n'), ((48315, 48371), 'flask_babelex.gettext', '_', (['"""Recurso do Artigo não encontrado. Caminho inválido!"""'], {}), "('Recurso do Artigo não encontrado. Caminho inválido!')\n", (48316, 48371), True, 'from flask_babelex import gettext as _\n'), ((49343, 49368), 'flask_babelex.gettext', '_', (['"""Issue não encontrado"""'], {}), "('Issue não encontrado')\n", (49344, 49368), True, 'from flask_babelex import gettext as _\n'), ((49497, 49523), 'flask_babelex.gettext', '_', (['"""Artigo não encontrado"""'], {}), "('Artigo não encontrado')\n", (49498, 49523), True, 'from flask_babelex import gettext as _\n'), ((50157, 50245), 'flask_babelex.gettext', '_', (['"""Este PDF não existe em http://www.scielo.br. Consulte http://search.scielo.org"""'], {}), "('Este PDF não existe em http://www.scielo.br. Consulte http://search.scielo.org'\n )\n", (50158, 50245), True, 'from flask_babelex import gettext as _\n'), ((50387, 50424), 'flask_babelex.gettext', '_', (['"""PDF do artigo não foi encontrado"""'], {}), "('PDF do artigo não foi encontrado')\n", (50388, 50424), True, 'from flask_babelex import gettext as _\n'), ((51026, 51094), 'flask_babelex.gettext', '_', (["('Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)"], {}), "('Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)\n", (51027, 51094), True, 'from flask_babelex import gettext as _\n'), ((51189, 51215), 'flask_babelex.gettext', '_', (['"""Artigo não encontrado"""'], {}), "('Artigo não encontrado')\n", (51190, 51215), True, 'from flask_babelex import gettext as _\n'), ((51624, 51649), 'flask_babelex.gettext', '_', (['"""Requisição inválida."""'], {}), "('Requisição inválida.')\n", (51625, 51649), True, 'from flask_babelex import gettext as _\n'), ((52779, 52804), 'flask_babelex.gettext', '_', (['"""Requisição inválida."""'], {}), "('Requisição inválida.')\n", (52780, 52804), True, 'from flask_babelex import gettext as _\n'), ((56060, 56074), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (56072, 56074), False, 'from datetime import datetime, timedelta\n'), ((6013, 6077), 'opac_schema.v1.models.Journal.objects.filter', 'Journal.objects.filter', ([], {'is_public': '(True)', 'current_status': '"""current"""'}), "(is_public=True, current_status='current')\n", (6035, 6077), False, 'from opac_schema.v1.models import Journal, Issue, Article, Collection\n'), ((6153, 6191), 'opac_schema.v1.models.Article.objects.filter', 'Article.objects.filter', ([], {'is_public': '(True)'}), '(is_public=True)\n', (6175, 6191), False, 'from opac_schema.v1.models import Journal, Issue, Article, Collection\n'), ((8943, 8957), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8955, 8957), False, 'from datetime import datetime, timedelta\n'), ((10556, 10582), 'flask_babelex.gettext', '_', (['"""Página não encontrada"""'], {}), "('Página não encontrada')\n", (10557, 10582), True, 'from flask_babelex import gettext as _\n'), ((11613, 11649), 'webapp.controllers.get_journal_by_issn', 'controllers.get_journal_by_issn', (['pid'], {}), '(pid)\n', (11644, 11649), False, 'from webapp import controllers\n'), ((15267, 15294), 'flask_babelex.gettext', '_', (['journal.unpublish_reason'], {}), '(journal.unpublish_reason)\n', (15268, 15294), True, 'from flask_babelex import gettext as _\n'), ((17527, 17554), 'flask_babelex.gettext', '_', (['journal.unpublish_reason'], {}), '(journal.unpublish_reason)\n', (17528, 17554), True, 'from flask_babelex import gettext as _\n'), ((18291, 18313), 'flask_babelex.gettext', '_', (['"""Artigo sem título"""'], {}), "('Artigo sem título')\n", (18292, 18313), True, 'from flask_babelex import gettext as _\n'), ((19267, 19294), 'flask_babelex.gettext', '_', (['journal.unpublish_reason'], {}), '(journal.unpublish_reason)\n', (19268, 19294), True, 'from flask_babelex import gettext as _\n'), ((21821, 21924), 'webapp.controllers.get_journals_grouped_by', 'controllers.get_journals_grouped_by', (['"""publisher_name"""', 'query'], {'query_filter': 'query_filter', 'lang': 'lang'}), "('publisher_name', query, query_filter=\n query_filter, lang=lang)\n", (21856, 21924), False, 'from webapp import controllers\n'), ((22541, 22634), 'flask_babelex.gettext', '_', (['"""Parámetro "list_type" é inválido, deve ser: "alpha", "areas", "wos" ou "publisher"."""'], {}), '(\'Parámetro "list_type" é inválido, deve ser: "alpha", "areas", "wos" ou "publisher".\'\n )\n', (22542, 22634), True, 'from flask_babelex import gettext as _\n'), ((23767, 23809), 'flask_babelex.gettext', '_', (['"""Periódico não permite envio de email."""'], {}), "('Periódico não permite envio de email.')\n", (23768, 23809), True, 'from flask_babelex import gettext as _\n'), ((25456, 25483), 'flask_babelex.gettext', '_', (['journal.unpublish_reason'], {}), '(journal.unpublish_reason)\n', (25457, 25483), True, 'from flask_babelex import gettext as _\n'), ((27682, 27723), 'flask.request.args.get', 'request.args.get', (['"""section"""', '""""""'], {'type': 'str'}), "('section', '', type=str)\n", (27698, 27723), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((27952, 27977), 'flask_babelex.gettext', '_', (['issue.unpublish_reason'], {}), '(issue.unpublish_reason)\n', (27953, 27977), True, 'from flask_babelex import gettext as _\n'), ((28099, 28126), 'flask_babelex.gettext', '_', (['journal.unpublish_reason'], {}), '(journal.unpublish_reason)\n', (28100, 28126), True, 'from flask_babelex import gettext as _\n'), ((32307, 32334), 'flask_babelex.gettext', '_', (['journal.unpublish_reason'], {}), '(journal.unpublish_reason)\n', (32308, 32334), True, 'from flask_babelex import gettext as _\n'), ((34144, 34169), 'flask_babelex.gettext', '_', (['issue.unpublish_reason'], {}), '(issue.unpublish_reason)\n', (34145, 34169), True, 'from flask_babelex import gettext as _\n'), ((34247, 34280), 'flask_babelex.gettext', '_', (['issue.journal.unpublish_reason'], {}), '(issue.journal.unpublish_reason)\n', (34248, 34280), True, 'from flask_babelex import gettext as _\n'), ((41174, 41197), 'flask_babelex.gettext', '_', (['"""Artigo inexistente"""'], {}), "('Artigo inexistente')\n", (41175, 41197), True, 'from flask_babelex import gettext as _\n'), ((41318, 41344), 'flask_babelex.gettext', '_', (['"""Artigo não encontrado"""'], {}), "('Artigo não encontrado')\n", (41319, 41344), True, 'from flask_babelex import gettext as _\n'), ((41432, 41536), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'url_seg', 'article_pid_v3': 'article_pid_v3', 'format': 'qs_format'}), "('main.article_detail_v3', url_seg=url_seg, article_pid_v3=\n article_pid_v3, format=qs_format)\n", (41439, 41536), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((41715, 41742), 'flask_babelex.gettext', '_', (['"""Recurso não encontrado"""'], {}), "('Recurso não encontrado')\n", (41716, 41742), True, 'from flask_babelex import gettext as _\n'), ((42310, 42443), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'article.journal.url_segment', 'article_pid_v3': 'article_pid_v3', 'lang': 'qs_lang', 'format': '"""pdf"""'}), "('main.article_detail_v3', url_seg=article.journal.url_segment,\n article_pid_v3=article_pid_v3, lang=qs_lang, format='pdf')\n", (42317, 42443), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((44909, 44942), 'flask_babelex.gettext', '_', (['"""PDF do Artigo não encontrado"""'], {}), "('PDF do Artigo não encontrado')\n", (44910, 44942), True, 'from flask_babelex import gettext as _\n'), ((45074, 45107), 'flask_babelex.gettext', '_', (['"""PDF do Artigo não encontrado"""'], {}), "('PDF do Artigo não encontrado')\n", (45075, 45107), True, 'from flask_babelex import gettext as _\n'), ((46936, 46959), 'flask_babelex.gettext', '_', (['"""PDF não encontrado"""'], {}), "('PDF não encontrado')\n", (46937, 46959), True, 'from flask_babelex import gettext as _\n'), ((47007, 47027), 'flask_babelex.gettext', '_', (['"""Erro inesperado"""'], {}), "('Erro inesperado')\n", (47008, 47027), True, 'from flask_babelex import gettext as _\n'), ((47521, 47548), 'flask_babelex.gettext', '_', (['"""Recurso não encontrado"""'], {}), "('Recurso não encontrado')\n", (47522, 47548), True, 'from flask_babelex import gettext as _\n'), ((47596, 47616), 'flask_babelex.gettext', '_', (['"""Erro inesperado"""'], {}), "('Erro inesperado')\n", (47597, 47616), True, 'from flask_babelex import gettext as _\n'), ((52923, 52978), 'flask.current_app.config.get', 'current_app.config.get', (['"""EMAIL_ACCOUNTS_RECEIVE_ERRORS"""'], {}), "('EMAIL_ACCOUNTS_RECEIVE_ERRORS')\n", (52945, 52978), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((55498, 55548), 'flask.url_for', 'url_for', (['"""main.about_journal"""'], {'url_seg': 'journal_seg'}), "('main.about_journal', url_seg=journal_seg)\n", (55505, 55548), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((58081, 58107), 'flask_babelex.gettext', '_', (['"""Página não encontrada"""'], {}), "('Página não encontrada')\n", (58082, 58107), True, 'from flask_babelex import gettext as _\n'), ((3634, 3679), 'flask.current_app.config.get', 'current_app.config.get', (['"""SCIELO_ORG_URIS"""', '{}'], {}), "('SCIELO_ORG_URIS', {})\n", (3656, 3679), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((11881, 11940), 'flask.url_for', 'url_for', (['"""main.journal_detail"""'], {'url_seg': 'journal.url_segment'}), "('main.journal_detail', url_seg=journal.url_segment)\n", (11888, 11940), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((12045, 12078), 'webapp.controllers.get_issue_by_pid', 'controllers.get_issue_by_pid', (['pid'], {}), '(pid)\n', (12073, 12078), False, 'from webapp import controllers\n'), ((23094, 23108), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (23106, 23108), False, 'from datetime import datetime, timedelta\n'), ((40377, 40420), 'flask_babelex.gettext', '_', (['"""Não existe \'{}\'. No seu lugar use \'{}\'"""'], {}), '("Não existe \'{}\'. No seu lugar use \'{}\'")\n', (40378, 40420), True, 'from flask_babelex import gettext as _\n'), ((41130, 41153), 'flask_babelex.gettext', '_', (['"""Resumo inexistente"""'], {}), "('Resumo inexistente')\n", (41131, 41153), True, 'from flask_babelex import gettext as _\n'), ((43215, 43265), 'flask_babelex.gettext', '_', (['"""HTML do Artigo não encontrado ou indisponível"""'], {}), "('HTML do Artigo não encontrado ou indisponível')\n", (43216, 43265), True, 'from flask_babelex import gettext as _\n'), ((43321, 43341), 'flask_babelex.gettext', '_', (['"""Erro inesperado"""'], {}), "('Erro inesperado')\n", (43322, 43341), True, 'from flask_babelex import gettext as _\n'), ((43466, 43498), 'webapp.config.lang_names.display_original_lang_name', 'display_original_lang_name', (['lang'], {}), '(lang)\n', (43492, 43498), False, 'from webapp.config.lang_names import display_original_lang_name\n'), ((43523, 43639), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'article.journal.url_segment', 'article_pid_v3': 'article_pid_v3', 'lang': 'lang'}), "('main.article_detail_v3', url_seg=article.journal.url_segment,\n article_pid_v3=article_pid_v3, lang=lang)\n", (43530, 43639), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((45249, 45282), 'flask_babelex.gettext', '_', (['"""PDF do Artigo não encontrado"""'], {}), "('PDF do Artigo não encontrado')\n", (45250, 45282), True, 'from flask_babelex import gettext as _\n'), ((45957, 45983), 'flask_babelex.gettext', '_', (['"""Formato não suportado"""'], {}), "('Formato não suportado')\n", (45958, 45983), True, 'from flask_babelex import gettext as _\n'), ((11706, 11735), 'flask_babelex.gettext', '_', (['"""Periódico não encontrado"""'], {}), "('Periódico não encontrado')\n", (11707, 11735), True, 'from flask_babelex import gettext as _\n'), ((12616, 12714), 'flask.url_for', 'url_for', (['"""main.issue_toc"""'], {'url_seg': 'issue.journal.url_segment', 'url_seg_issue': 'issue.url_segment'}), "('main.issue_toc', url_seg=issue.journal.url_segment, url_seg_issue=\n issue.url_segment)\n", (12623, 12714), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((12903, 12941), 'webapp.controllers.get_article_by_pid_v2', 'controllers.get_article_by_pid_v2', (['pid'], {}), '(pid)\n', (12936, 12941), False, 'from webapp import controllers\n'), ((22004, 22079), 'flask_babelex.gettext', '_', (['"""Parámetro "filter" é inválido, deve ser "areas", "wos" ou "publisher"."""'], {}), '(\'Parámetro "filter" é inválido, deve ser "areas", "wos" ou "publisher".\')\n', (22005, 22079), True, 'from flask_babelex import gettext as _\n'), ((11823, 11850), 'flask_babelex.gettext', '_', (['journal.unpublish_reason'], {}), '(journal.unpublish_reason)\n', (11824, 11850), True, 'from flask_babelex import gettext as _\n'), ((12133, 12159), 'flask_babelex.gettext', '_', (['"""Número não encontrado"""'], {}), "('Número não encontrado')\n", (12134, 12159), True, 'from flask_babelex import gettext as _\n'), ((12518, 12558), 'flask.url_for', 'url_for', (['"""main.aop_toc"""'], {'url_seg': 'url_seg'}), "('main.aop_toc', url_seg=url_seg)\n", (12525, 12558), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((13311, 13435), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'article.journal.url_segment', 'article_pid_v3': 'article.aid', 'part': 'part', 'lang': 'tlng'}), "('main.article_detail_v3', url_seg=article.journal.url_segment,\n article_pid_v3=article.aid, part=part, lang=tlng)\n", (13318, 13435), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((13680, 13716), 'webapp.controllers.get_journal_by_issn', 'controllers.get_journal_by_issn', (['pid'], {}), '(pid)\n', (13711, 13716), False, 'from webapp import controllers\n'), ((12243, 12268), 'flask_babelex.gettext', '_', (['issue.unpublish_reason'], {}), '(issue.unpublish_reason)\n', (12244, 12268), True, 'from flask_babelex import gettext as _\n'), ((12362, 12395), 'flask_babelex.gettext', '_', (['issue.journal.unpublish_reason'], {}), '(issue.journal.unpublish_reason)\n', (12363, 12395), True, 'from flask_babelex import gettext as _\n'), ((12997, 13023), 'flask_babelex.gettext', '_', (['"""Artigo não encontrado"""'], {}), "('Artigo não encontrado')\n", (12998, 13023), True, 'from flask_babelex import gettext as _\n'), ((13948, 14003), 'flask.url_for', 'url_for', (['"""main.issue_grid"""'], {'url_seg': 'journal.url_segment'}), "('main.issue_grid', url_seg=journal.url_segment)\n", (13955, 14003), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((14147, 14185), 'webapp.controllers.get_article_by_pid_v2', 'controllers.get_article_by_pid_v2', (['pid'], {}), '(pid)\n', (14180, 14185), False, 'from webapp import controllers\n'), ((13773, 13802), 'flask_babelex.gettext', '_', (['"""Periódico não encontrado"""'], {}), "('Periódico não encontrado')\n", (13774, 13802), True, 'from flask_babelex import gettext as _\n'), ((14315, 14431), 'flask.url_for', 'url_for', (['"""main.article_detail_v3"""'], {'url_seg': 'article.journal.url_segment', 'article_pid_v3': 'article.aid', 'format': '"""pdf"""'}), "('main.article_detail_v3', url_seg=article.journal.url_segment,\n article_pid_v3=article.aid, format='pdf')\n", (14322, 14431), False, 'from flask import render_template, abort, current_app, request, session, redirect, jsonify, url_for, Response, send_from_directory, g, make_response\n'), ((14605, 14674), 'flask_babelex.gettext', '_', (["(u'Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)"], {}), "(u'Requsição inválida ao tentar acessar o artigo com pid: %s' % pid)\n", (14606, 14674), True, 'from flask_babelex import gettext as _\n'), ((13890, 13917), 'flask_babelex.gettext', '_', (['journal.unpublish_reason'], {}), '(journal.unpublish_reason)\n', (13891, 13917), True, 'from flask_babelex import gettext as _\n'), ((14241, 14267), 'flask_babelex.gettext', '_', (['"""Artigo não encontrado"""'], {}), "('Artigo não encontrado')\n", (14242, 14267), True, 'from flask_babelex import gettext as _\n')]
CodeXfull/Pandas
create_read_write_1/Writing/to_csv.py
08b0adc28eedba47f6eb8303ba6a36a37ababb92
""" Converter um DataFrame para CSV """ import pandas as pd dataset = pd.DataFrame({'Frutas': ["Abacaxi", "Mamão"], "Nomes": ["Éverton", "Márcia"]}, index=["Linha 1", "Linha 2"]) dataset.to_csv("dataset.csv")
[((71, 184), 'pandas.DataFrame', 'pd.DataFrame', (["{'Frutas': ['Abacaxi', 'Mamão'], 'Nomes': ['Éverton', 'Márcia']}"], {'index': "['Linha 1', 'Linha 2']"}), "({'Frutas': ['Abacaxi', 'Mamão'], 'Nomes': ['Éverton', 'Márcia'\n ]}, index=['Linha 1', 'Linha 2'])\n", (83, 184), True, 'import pandas as pd\n')]
13rilliant/Python-CMS
venv/Lib/site-packages/pygsheets/client.py
56c4f3f1cbdd81020aa690ab92d0e26d042458c1
# -*- coding: utf-8 -*-. import re import warnings import os import logging from pygsheets.drive import DriveAPIWrapper from pygsheets.sheet import SheetAPIWrapper from pygsheets.spreadsheet import Spreadsheet from pygsheets.exceptions import SpreadsheetNotFound, NoValidUrlKeyFound from pygsheets.custom_types import ValueRenderOption, DateTimeRenderOption from google_auth_httplib2 import AuthorizedHttp GOOGLE_SHEET_CELL_UPDATES_LIMIT = 50000 _url_key_re_v1 = re.compile(r'key=([^&#]+)') _url_key_re_v2 = re.compile(r"/spreadsheets/d/([a-zA-Z0-9-_]+)") _email_patttern = re.compile(r"\"?([-a-zA-Z0-9.`?{}]+@[-a-zA-Z0-9.]+\.\w+)\"?") # _domain_pattern = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE) _deprecated_keyword_mapping = { 'parent_id': 'folder', } class Client(object): """Create or access Google spreadsheets. Exposes members to create new spreadsheets or open existing ones. Use `authorize` to instantiate an instance of this class. >>> import pygsheets >>> c = pygsheets.authorize() The sheet API service object is stored in the sheet property and the drive API service object in the drive property. >>> c.sheet.get('<SPREADSHEET ID>') >>> c.drive.delete('<FILE ID>') :param credentials: The credentials object returned by google-auth or google-auth-oauthlib. :param retries: (Optional) Number of times to retry a connection before raising a TimeOut error. Default: 3 :param http: The underlying HTTP object to use to make requests. If not specified, a :class:`httplib2.Http` instance will be constructed. """ spreadsheet_cls = Spreadsheet def __init__(self, credentials, retries=3, http=None): self.oauth = credentials self.logger = logging.getLogger(__name__) http = AuthorizedHttp(credentials, http=http) data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") self.sheet = SheetAPIWrapper(http, data_path, retries=retries) self.drive = DriveAPIWrapper(http, data_path) @property def teamDriveId(self): """ Enable team drive support Deprecated: use client.drive.enable_team_drive(team_drive_id=?) """ return self.drive.team_drive_id @teamDriveId.setter def teamDriveId(self, value): warnings.warn("Depricated please use drive.enable_team_drive") self.drive.enable_team_drive(value) def spreadsheet_ids(self, query=None): """Get a list of all spreadsheet ids present in the Google Drive or TeamDrive accessed.""" return [x['id'] for x in self.drive.spreadsheet_metadata(query)] def spreadsheet_titles(self, query=None): """Get a list of all spreadsheet titles present in the Google Drive or TeamDrive accessed.""" return [x['name'] for x in self.drive.spreadsheet_metadata(query)] def create(self, title, template=None, folder=None, **kwargs): """Create a new spreadsheet. The title will always be set to the given value (even overwriting the templates title). The template can either be a `spreadsheet resource <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#resource-spreadsheet>`_ or an instance of :class:`~pygsheets.Spreadsheet`. In both cases undefined values will be ignored. :param title: Title of the new spreadsheet. :param template: A template to create the new spreadsheet from. :param folder: The Id of the folder this sheet will be stored in. :param kwargs: Standard parameters (see reference for details). :return: :class:`~pygsheets.Spreadsheet` """ result = self.sheet.create(title, template=template, **kwargs) if folder: self.drive.move_file(result['spreadsheetId'], old_folder=self.drive.spreadsheet_metadata(query="name = '" + title + "'")[0]['parents'][0], new_folder=folder) return self.spreadsheet_cls(self, jsonsheet=result) def open(self, title): """Open a spreadsheet by title. In a case where there are several sheets with the same title, the first one found is returned. >>> import pygsheets >>> c = pygsheets.authorize() >>> c.open('TestSheet') :param title: A title of a spreadsheet. :returns: :class:`~pygsheets.Spreadsheet` :raises pygsheets.SpreadsheetNotFound: No spreadsheet with the given title was found. """ try: spreadsheet = list(filter(lambda x: x['name'] == title, self.drive.spreadsheet_metadata()))[0] return self.open_by_key(spreadsheet['id']) except (KeyError, IndexError): raise SpreadsheetNotFound('Could not find a spreadsheet with title %s.' % title) def open_by_key(self, key): """Open a spreadsheet by key. >>> import pygsheets >>> c = pygsheets.authorize() >>> c.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') :param key: The key of a spreadsheet. (can be found in the sheet URL) :returns: :class:`~pygsheets.Spreadsheet` :raises pygsheets.SpreadsheetNotFound: The given spreadsheet ID was not found. """ response = self.sheet.get(key, fields='properties,sheets/properties,spreadsheetId,namedRanges', includeGridData=False) return self.spreadsheet_cls(self, response) def open_by_url(self, url): """Open a spreadsheet by URL. >>> import pygsheets >>> c = pygsheets.authorize() >>> c.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl') :param url: URL of a spreadsheet as it appears in a browser. :returns: :class:`~pygsheets.Spreadsheet` :raises pygsheets.SpreadsheetNotFound: No spreadsheet was found with the given URL. """ m1 = _url_key_re_v1.search(url) if m1: return self.open_by_key(m1.group(1)) else: m2 = _url_key_re_v2.search(url) if m2: return self.open_by_key(m2.group(1)) else: raise NoValidUrlKeyFound def open_all(self, query=''): """Opens all available spreadsheets. Result can be filtered when specifying the query parameter. On the details on how to form the query: `Reference <https://developers.google.com/drive/v3/web/search-parameters>`_ :param query: (Optional) Can be used to filter the returned metadata. :returns: A list of :class:`~pygsheets.Spreadsheet`. """ return [self.open_by_key(key) for key in self.spreadsheet_ids(query=query)] def open_as_json(self, key): """Return a json representation of the spreadsheet. See `Reference <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#Spreadsheet>`__ for details. """ return self.sheet.get(key, fields='properties,sheets/properties,sheets/protectedRanges,' 'spreadsheetId,namedRanges', includeGridData=False) def get_range(self, spreadsheet_id, value_range, major_dimension='ROWS', value_render_option=ValueRenderOption.FORMATTED_VALUE, date_time_render_option=DateTimeRenderOption.SERIAL_NUMBER): """Returns a range of values from a spreadsheet. The caller must specify the spreadsheet ID and a range. Reference: `request <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`__ :param spreadsheet_id: The ID of the spreadsheet to retrieve data from. :param value_range: The A1 notation of the values to retrieve. :param major_dimension: The major dimension that results should use. For example, if the spreadsheet data is: A1=1,B1=2,A2=3,B2=4, then requesting range=A1:B2,majorDimension=ROWS will return [[1,2],[3,4]], whereas requesting range=A1:B2,majorDimension=COLUMNS will return [[1,3],[2,4]]. :param value_render_option: How values should be represented in the output. The default render option is `ValueRenderOption.FORMATTED_VALUE`. :param date_time_render_option: How dates, times, and durations should be represented in the output. This is ignored if `valueRenderOption` is `FORMATTED_VALUE`. The default dateTime render option is [`DateTimeRenderOption.SERIAL_NUMBER`]. :return: An array of arrays with the values fetched. Returns an empty array if no values were fetched. Values are dynamically typed as int, float or string. """ result = self.sheet.values_get(spreadsheet_id, value_range, major_dimension, value_render_option, date_time_render_option) try: return result['values'] except KeyError: return [['']]
[((468, 494), 're.compile', 're.compile', (['"""key=([^&#]+)"""'], {}), "('key=([^&#]+)')\n", (478, 494), False, 'import re\n'), ((513, 559), 're.compile', 're.compile', (['"""/spreadsheets/d/([a-zA-Z0-9-_]+)"""'], {}), "('/spreadsheets/d/([a-zA-Z0-9-_]+)')\n", (523, 559), False, 'import re\n'), ((579, 643), 're.compile', 're.compile', (['"""\\\\"?([-a-zA-Z0-9.`?{}]+@[-a-zA-Z0-9.]+\\\\.\\\\w+)\\\\"?"""'], {}), '(\'\\\\"?([-a-zA-Z0-9.`?{}]+@[-a-zA-Z0-9.]+\\\\.\\\\w+)\\\\"?\')\n', (589, 643), False, 'import re\n'), ((1868, 1895), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1885, 1895), False, 'import logging\n'), ((1912, 1950), 'google_auth_httplib2.AuthorizedHttp', 'AuthorizedHttp', (['credentials'], {'http': 'http'}), '(credentials, http=http)\n', (1926, 1950), False, 'from google_auth_httplib2 import AuthorizedHttp\n'), ((2058, 2107), 'pygsheets.sheet.SheetAPIWrapper', 'SheetAPIWrapper', (['http', 'data_path'], {'retries': 'retries'}), '(http, data_path, retries=retries)\n', (2073, 2107), False, 'from pygsheets.sheet import SheetAPIWrapper\n'), ((2129, 2161), 'pygsheets.drive.DriveAPIWrapper', 'DriveAPIWrapper', (['http', 'data_path'], {}), '(http, data_path)\n', (2144, 2161), False, 'from pygsheets.drive import DriveAPIWrapper\n'), ((2438, 2501), 'warnings.warn', 'warnings.warn', (['"""Depricated please use drive.enable_team_drive"""'], {}), "('Depricated please use drive.enable_team_drive')\n", (2451, 2501), False, 'import warnings\n'), ((2000, 2025), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (2015, 2025), False, 'import os\n'), ((4955, 5029), 'pygsheets.exceptions.SpreadsheetNotFound', 'SpreadsheetNotFound', (["('Could not find a spreadsheet with title %s.' % title)"], {}), "('Could not find a spreadsheet with title %s.' % title)\n", (4974, 5029), False, 'from pygsheets.exceptions import SpreadsheetNotFound, NoValidUrlKeyFound\n')]
NatalyAristova/Training_python
model/group_contact.py
e95a2b9e25238285d705a880fd94d73f173c3a31
from sys import maxsize class Group_contact: def __init__(self,firstname=None, middlename=None, lastname=None, nickname=None, title=None, company=None, address=None, home=None, mobile=None, work=None, fax=None, email=None, email2=None, email3=None, byear=None, address2=None, phone2=None, notes=None, all_phones_from_home_page=None, id=None, all_emails_from_home_page=None): self.firstname=firstname self.middlename=middlename self.lastname=lastname self.nickname=nickname self.title=title self.company=company self.address=address self.home=home self.mobile=mobile self.work=work self.fax=fax self.email=email self.email2 = email2 self.email3 = email3 self.byear=byear self.address2=address2 self.phone2=phone2 self.notes=notes self.id = id self.all_phones_from_home_page=all_phones_from_home_page self.all_emails_from_home_page = all_emails_from_home_page def __repr__(self): return "%s:%s:%s:%s:%s:%s" % (self.id, self.lastname, self.firstname, self.middlename, self.nickname, self.title) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and (self.lastname, self.firstname) == (other.lastname, other.firstname) def id_or_max(self): if self.id: return int(self.id) else: return maxsize
[]
membranepotential/mendeley-python-sdk
test/manual/documents/test_iter_documents.py
0336f0164f4d409309e813cbd0140011b5b2ff8f
from itertools import islice from test import get_user_session, cassette from test.resources.documents import delete_all_documents, create_document def test_should_iterate_through_documents(): session = get_user_session() delete_all_documents() with cassette('fixtures/resources/documents/iter_documents/iterate_through_documents.yaml'): create_document(session, 'title 1') create_document(session, 'title 2') create_document(session, 'title 3') docs = list(islice(session.documents.iter(page_size=2), 3)) assert len(docs) == 3 assert docs[0].title == 'title 1' assert docs[1].title == 'title 2' assert docs[2].title == 'title 3'
[((210, 228), 'test.get_user_session', 'get_user_session', ([], {}), '()\n', (226, 228), False, 'from test import get_user_session, cassette\n'), ((233, 255), 'test.resources.documents.delete_all_documents', 'delete_all_documents', ([], {}), '()\n', (253, 255), False, 'from test.resources.documents import delete_all_documents, create_document\n'), ((266, 362), 'test.cassette', 'cassette', (['"""fixtures/resources/documents/iter_documents/iterate_through_documents.yaml"""'], {}), "(\n 'fixtures/resources/documents/iter_documents/iterate_through_documents.yaml'\n )\n", (274, 362), False, 'from test import get_user_session, cassette\n'), ((362, 397), 'test.resources.documents.create_document', 'create_document', (['session', '"""title 1"""'], {}), "(session, 'title 1')\n", (377, 397), False, 'from test.resources.documents import delete_all_documents, create_document\n'), ((406, 441), 'test.resources.documents.create_document', 'create_document', (['session', '"""title 2"""'], {}), "(session, 'title 2')\n", (421, 441), False, 'from test.resources.documents import delete_all_documents, create_document\n'), ((450, 485), 'test.resources.documents.create_document', 'create_document', (['session', '"""title 3"""'], {}), "(session, 'title 3')\n", (465, 485), False, 'from test.resources.documents import delete_all_documents, create_document\n')]
cbsudux/minimal-hand
demo.py
893c252e7e818a9a96b279023ea8a78a88fb0a4d
import argparse import cv2 import keyboard import numpy as np import open3d as o3d import os import pygame from transforms3d.axangles import axangle2mat import config from hand_mesh import HandMesh from kinematics import mpii_to_mano from utils import OneEuroFilter, imresize from wrappers import ModelPipeline from utils import * def video_to_images(vid_file, img_folder=None, return_info=False): if img_folder is None: img_folder = osp.join('/tmp', osp.basename(vid_file).replace('.', '_')) os.makedirs(img_folder, exist_ok=True) command = ['ffmpeg', '-i', vid_file, '-f', 'image2', '-v', 'error', f'{img_folder}/%06d.png'] print(f'Running \"{" ".join(command)}\"') subprocess.call(command) print(f'Images saved to \"{img_folder}\"') img_shape = cv2.imread(osp.join(img_folder, '000001.png')).shape if return_info: return img_folder, len(os.listdir(img_folder)), img_shape else: return img_folder def run(args): ############ output visualization ############ # view_mat = axangle2mat([1, 0, 0], np.pi) # align different coordinate systems # window_size = 1080 # hand_mesh = HandMesh(config.HAND_MESH_MODEL_PATH) # mesh = o3d.geometry.TriangleMesh() # mesh.triangles = o3d.utility.Vector3iVector(hand_mesh.faces) # mesh.vertices = \ # o3d.utility.Vector3dVector(np.matmul(view_mat, hand_mesh.verts.T).T * 1000) # mesh.compute_vertex_normals() # viewer = o3d.visualization.Visualizer() # viewer.create_window( # width=window_size + 1, height=window_size + 1, # window_name='Minimal Hand - output' # ) # viewer.add_geometry(mesh) # view_control = viewer.get_view_control() # cam_params = view_control.convert_to_pinhole_camera_parameters() # extrinsic = cam_params.extrinsic.copy() # extrinsic[0:3, 3] = 0 # cam_params.extrinsic = extrinsic # cam_params.intrinsic.set_intrinsics( # window_size + 1, window_size + 1, config.CAM_FX, config.CAM_FY, # window_size // 2, window_size // 2 # ) # view_control.convert_from_pinhole_camera_parameters(cam_params) # view_control.set_constant_z_far(1000) # render_option = viewer.get_render_option() # render_option.load_from_json('./render_option.json') # viewer.update_renderer() # ############ input visualization ############ # pygame.init() # display = pygame.display.set_mode((window_size, window_size)) # pygame.display.set_caption('Minimal Hand - input') # ############ misc ############ # mesh_smoother = OneEuroFilter(4.0, 0.0) # clock = pygame.time.Clock() ############ Move all of above code to local to render ########### video_file = args.vid_file if not os.path.isfile(video_file): exit(f'Input video \"{video_file}\" does not exist!') output_path = os.path.join(args.output_folder, os.path.basename(video_file).replace('.mp4', '')) os.makedirs(output_path, exist_ok=True) image_folder, num_frames, img_shape = video_to_images(video_file, return_info=True) print(f'Input video number of frames {num_frames}') orig_height, orig_width = img_shape[:2] # total_time = time.time() import pdb; pdb.set_trace() image_file_names = [ osp.join(image_folder, x) for x in os.listdir(image_folder) if x.endswith('.png') or x.endswith('.jpg') ] model = ModelPipeline() for i in image_file_names: # What do all these conditions check for? frame_large = x if frame_large is None: continue if frame_large.shape[0] > frame_large.shape[1]: margin = int((frame_large.shape[0] - frame_large.shape[1]) / 2) frame_large = frame_large[margin:-margin] else: margin = int((frame_large.shape[1] - frame_large.shape[0]) / 2) frame_large = frame_large[:, margin:-margin] frame_large = np.flip(frame_large, axis=1).copy() # why? Camera flip? frame = imresize(frame_large, (128, 128)) # needed ######## Golden lines, run this here ######### _, theta_mpii = model.process(frame) theta_mano = mpii_to_mano(theta_mpii) ######## Save theta_mano and pass as input to local ######## v = hand_mesh.set_abs_quat(theta_mano) v *= 2 # for better visualization v = v * 1000 + np.array([0, 0, 400]) v = mesh_smoother.process(v) mesh.triangles = o3d.utility.Vector3iVector(hand_mesh.faces) mesh.vertices = o3d.utility.Vector3dVector(np.matmul(view_mat, v.T).T) mesh.paint_uniform_color(config.HAND_COLOR) mesh.compute_triangle_normals() mesh.compute_vertex_normals() # for some version of open3d you may need `viewer.update_geometry(mesh)` viewer.update_geometry() viewer.poll_events() display.blit( pygame.surfarray.make_surface( np.transpose( imresize(frame_large, (window_size, window_size) ), (1, 0, 2)) ), (0, 0) ) pygame.display.update() if keyboard.is_pressed("esc"): break clock.tick(30) # What's this do? If it adds delay remove it if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--vid_file', type=str, help='input video path or youtube link') args = parser.parse_args() run(args)
[((513, 551), 'os.makedirs', 'os.makedirs', (['img_folder'], {'exist_ok': '(True)'}), '(img_folder, exist_ok=True)\n', (524, 551), False, 'import os\n'), ((2995, 3034), 'os.makedirs', 'os.makedirs', (['output_path'], {'exist_ok': '(True)'}), '(output_path, exist_ok=True)\n', (3006, 3034), False, 'import os\n'), ((3273, 3288), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (3286, 3288), False, 'import pdb\n'), ((3478, 3493), 'wrappers.ModelPipeline', 'ModelPipeline', ([], {}), '()\n', (3491, 3493), False, 'from wrappers import ModelPipeline\n'), ((5366, 5391), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5389, 5391), False, 'import argparse\n'), ((2799, 2825), 'os.path.isfile', 'os.path.isfile', (['video_file'], {}), '(video_file)\n', (2813, 2825), False, 'import os\n'), ((4081, 4114), 'utils.imresize', 'imresize', (['frame_large', '(128, 128)'], {}), '(frame_large, (128, 128))\n', (4089, 4114), False, 'from utils import OneEuroFilter, imresize\n'), ((4248, 4272), 'kinematics.mpii_to_mano', 'mpii_to_mano', (['theta_mpii'], {}), '(theta_mpii)\n', (4260, 4272), False, 'from kinematics import mpii_to_mano\n'), ((4541, 4584), 'open3d.utility.Vector3iVector', 'o3d.utility.Vector3iVector', (['hand_mesh.faces'], {}), '(hand_mesh.faces)\n', (4567, 4584), True, 'import open3d as o3d\n'), ((5173, 5196), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (5194, 5196), False, 'import pygame\n'), ((5209, 5235), 'keyboard.is_pressed', 'keyboard.is_pressed', (['"""esc"""'], {}), "('esc')\n", (5228, 5235), False, 'import keyboard\n'), ((3374, 3398), 'os.listdir', 'os.listdir', (['image_folder'], {}), '(image_folder)\n', (3384, 3398), False, 'import os\n'), ((4456, 4477), 'numpy.array', 'np.array', (['[0, 0, 400]'], {}), '([0, 0, 400])\n', (4464, 4477), True, 'import numpy as np\n'), ((955, 977), 'os.listdir', 'os.listdir', (['img_folder'], {}), '(img_folder)\n', (965, 977), False, 'import os\n'), ((2941, 2969), 'os.path.basename', 'os.path.basename', (['video_file'], {}), '(video_file)\n', (2957, 2969), False, 'import os\n'), ((4009, 4037), 'numpy.flip', 'np.flip', (['frame_large'], {'axis': '(1)'}), '(frame_large, axis=1)\n', (4016, 4037), True, 'import numpy as np\n'), ((4636, 4660), 'numpy.matmul', 'np.matmul', (['view_mat', 'v.T'], {}), '(view_mat, v.T)\n', (4645, 4660), True, 'import numpy as np\n'), ((5046, 5095), 'utils.imresize', 'imresize', (['frame_large', '(window_size, window_size)'], {}), '(frame_large, (window_size, window_size))\n', (5054, 5095), False, 'from utils import OneEuroFilter, imresize\n')]
incuna/incuna-groups
test_project/settings.py
148c181faf66fe73792cb2c5bbf5500ba61aa22d
import os import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] ROOT_URLCONF = 'groups.tests.urls' STATIC_URL = '/static/' SECRET_KEY = 'krc34ji^-fd-=+r6e%p!0u0k9h$9!q*_#l=6)74h#o(jrxsx4p' PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',) DATABASES = { 'default': dj_database_url.config(default='postgres://localhost/groups') } DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage' INSTALLED_APPS = ( 'groups', 'crispy_forms', 'pagination', 'polymorphic', # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'groups', 'tests', 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.request', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] CRISPY_TEMPLATE_PACK = 'bootstrap3' TEST_RUNNER = 'test_project.test_runner.Runner'
[((366, 427), 'dj_database_url.config', 'dj_database_url.config', ([], {'default': '"""postgres://localhost/groups"""'}), "(default='postgres://localhost/groups')\n", (388, 427), False, 'import dj_database_url\n'), ((79, 104), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (94, 104), False, 'import os\n'), ((1165, 1219), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""groups"""', '"""tests"""', '"""templates"""'], {}), "(BASE_DIR, 'groups', 'tests', 'templates')\n", (1177, 1219), False, 'import os\n')]
cclauss/akismet
tests/test_akismet.py
7b65bc163d6947a3013d01bf9accf1bc6c0781ca
import datetime import os import sys import unittest from unittest import mock import akismet class AkismetTests(unittest.TestCase): api_key = os.getenv("TEST_AKISMET_API_KEY") blog_url = os.getenv("TEST_AKISMET_BLOG_URL") api_key_env_var = "PYTHON_AKISMET_API_KEY" blog_url_env_var = "PYTHON_AKISMET_BLOG_URL" def setUp(self): self.api = akismet.Akismet(key=self.api_key, blog_url=self.blog_url) class AkismetConfigurationTests(AkismetTests): """ Tests configuration of the Akismet class. """ def test_config_from_args(self): """ Configuring via explicit arguments succeeds. """ api = akismet.Akismet(key=self.api_key, blog_url=self.blog_url) self.assertEqual(self.api_key, api.api_key) self.assertEqual(self.blog_url, api.blog_url) def test_bad_config_args(self): """ Configuring with bad arguments fails. """ with self.assertRaises(akismet.APIKeyError): akismet.Akismet(key="invalid", blog_url="http://invalid") def test_config_from_env(self): """ Configuring via environment variables succeeds. """ try: os.environ[self.api_key_env_var] = self.api_key os.environ[self.blog_url_env_var] = self.blog_url api = akismet.Akismet(key=None, blog_url=None) self.assertEqual(self.api_key, api.api_key) self.assertEqual(self.blog_url, api.blog_url) api = akismet.Akismet() self.assertEqual(self.api_key, api.api_key) self.assertEqual(self.blog_url, api.blog_url) finally: os.environ[self.api_key_env_var] = "" os.environ[self.blog_url_env_var] = "" def test_bad_config_env(self): """ Configuring with bad environment variables fails. """ try: os.environ[self.api_key_env_var] = "invalid" os.environ[self.blog_url_env_var] = "http://invalid" with self.assertRaises(akismet.APIKeyError): akismet.Akismet() finally: os.environ[self.api_key_env_var] = "" os.environ[self.blog_url_env_var] = "" def test_bad_url(self): """ Configuring with a bad URL fails. """ bad_urls = ( "example.com", "ftp://example.com", "www.example.com", "http//example.com", "https//example.com", ) for url in bad_urls: with self.assertRaises(akismet.ConfigurationError): akismet.Akismet(key=self.api_key, blog_url=url) def test_missing_config(self): """ Instantiating without any configuration fails. """ with self.assertRaises(akismet.ConfigurationError): akismet.Akismet(key=None, blog_url=None) with self.assertRaises(akismet.ConfigurationError): akismet.Akismet() def test_user_agent(self): """ The Akismet class creates the correct user-agent string. """ api = akismet.Akismet(key=self.api_key, blog_url=self.blog_url) expected_agent = "Python/{} | akismet.py/{}".format( "{}.{}".format(*sys.version_info[:2]), akismet.__version__ ) self.assertEqual(expected_agent, api.user_agent_header["User-Agent"]) class AkismetAPITests(AkismetTests): """ Tests implementation of the Akismet API. """ base_kwargs = { "user_ip": "127.0.0.1", "user_agent": "Mozilla", # Always send this when testing; Akismet recognizes it as a # test query and does not train/learn from it. "is_test": 1, } def test_verify_key_valid(self): """ The verify_key operation succeeds with a valid key and URL. """ self.assertTrue(akismet.Akismet.verify_key(self.api_key, self.blog_url)) def test_verify_key_invalid(self): """ The verify_key operation fails with an invalid key and URL. """ self.assertFalse(akismet.Akismet.verify_key("invalid", "http://invalid")) def test_comment_check_spam(self): """ The comment_check method correctly identifies spam. """ check_kwargs = { # Akismet guarantees this will be classified spam. "comment_author": "viagra-test-123", **self.base_kwargs, } self.assertTrue(self.api.comment_check(**check_kwargs)) def test_comment_check_not_spam(self): """ The comment_check method correctly identifies non-spam. """ check_kwargs = { # Akismet guarantees this will not be classified spam. "user_role": "administrator", **self.base_kwargs, } self.assertFalse(self.api.comment_check(**check_kwargs)) def test_submit_spam(self): """ The submit_spam method succeeds. """ spam_kwargs = { "comment_type": "comment", "comment_author": "viagra-test-123", "comment_content": "viagra-test-123", **self.base_kwargs, } self.assertTrue(self.api.submit_spam(**spam_kwargs)) def test_submit_ham(self): """ The submit_ham method succeeds. """ ham_kwargs = { "comment_type": "comment", "comment_author": "Legitimate Author", "comment_content": "This is a legitimate comment.", "user_role": "administrator", **self.base_kwargs, } self.assertTrue(self.api.submit_ham(**ham_kwargs)) def test_unexpected_verify_key_response(self): """ Unexpected verify_key API responses are correctly handled. """ post_mock = mock.MagicMock() with mock.patch("requests.post", post_mock): with self.assertRaises(akismet.ProtocolError): akismet.Akismet.verify_key(self.api_key, self.blog_url) def test_unexpected_comment_check_response(self): """ Unexpected comment_check API responses are correctly handled. """ post_mock = mock.MagicMock() with mock.patch("requests.post", post_mock): with self.assertRaises(akismet.ProtocolError): check_kwargs = {"comment_author": "viagra-test-123", **self.base_kwargs} self.api.comment_check(**check_kwargs) def test_unexpected_submit_spam_response(self): """ Unexpected submit_spam API responses are correctly handled. """ post_mock = mock.MagicMock() with mock.patch("requests.post", post_mock): with self.assertRaises(akismet.ProtocolError): spam_kwargs = { "comment_type": "comment", "comment_author": "viagra-test-123", "comment_content": "viagra-test-123", **self.base_kwargs, } self.api.submit_spam(**spam_kwargs) def test_unexpected_submit_ham_response(self): """ Unexpected submit_ham API responses are correctly handled. """ post_mock = mock.MagicMock() with mock.patch("requests.post", post_mock): with self.assertRaises(akismet.ProtocolError): ham_kwargs = { "comment_type": "comment", "comment_author": "Legitimate Author", "comment_content": "This is a legitimate comment.", "user_role": "administrator", **self.base_kwargs, } self.api.submit_ham(**ham_kwargs) class AkismetRequestTests(AkismetTests): """ Tests the requests constructed by the Akismet class. """ def _get_mock(self, text): """ Create a mock for requests.post() returning expected text. """ post_mock = mock.MagicMock() post_mock.return_value.text = text return post_mock def _mock_request(self, method, endpoint, text, method_kwargs): """ Issue a mocked request and verify requests.post() was called with the correct arguments. """ method_kwargs.update(user_ip="127.0.0.1", user_agent="Mozilla", is_test=1) expected_kwargs = {"blog": self.blog_url, **method_kwargs} post_mock = self._get_mock(text) with mock.patch("requests.post", post_mock): getattr(self.api, method)(**method_kwargs) post_mock.assert_called_with( endpoint.format(self.api_key), data=expected_kwargs, headers=akismet.Akismet.user_agent_header, ) def test_verify_key(self): """ The request issued by verify_key() is correct. """ post_mock = self._get_mock("valid") with mock.patch("requests.post", post_mock): akismet.Akismet.verify_key(self.api_key, self.blog_url) post_mock.assert_called_with( akismet.Akismet.VERIFY_KEY_URL, data={"key": self.api_key, "blog": self.blog_url}, headers=akismet.Akismet.user_agent_header, ) def test_comment_check(self): """ The request issued by comment_check() is correct. """ self._mock_request( "comment_check", akismet.Akismet.COMMENT_CHECK_URL, "true", {"comment_author": "viagra-test-123"}, ) def test_submit_spam(self): """ The request issued by submit_spam() is correct. """ self._mock_request( "submit_spam", akismet.Akismet.SUBMIT_SPAM_URL, akismet.Akismet.SUBMIT_SUCCESS_RESPONSE, {"comment_content": "Bad comment", "comment_author": "viagra-test-123"}, ) def test_submit_ham(self): """ The request issued by submit_ham() is correct. """ self._mock_request( "submit_ham", akismet.Akismet.SUBMIT_HAM_URL, akismet.Akismet.SUBMIT_SUCCESS_RESPONSE, { "comment_content": "Good comment", "comment_author": "Legitimate commenter", }, ) def test_full_kwargs(self): """ All optional Akismet arguments are correctly passed through. """ modified_timestamp = datetime.datetime.now() posted_timestamp = modified_timestamp - datetime.timedelta(seconds=30) full_kwargs = { "referrer": "http://www.example.com/", "permalink": "http://www.example.com/#comment123", "comment_type": "comment", "comment_author": "Legitimate Author", "comment_author_email": "[email protected]", "comment_author_url": "http://www.example.com/", "comment_content": "This is a fine comment.", "comment_date_gmt": posted_timestamp.isoformat(), "comment_post_modified_gmt": modified_timestamp.isoformat(), "blog_lang": "en_us", "blog_charset": "utf-8", "user_role": "administrator", "recheck_reason": "edit", } self._mock_request( "comment_check", akismet.Akismet.COMMENT_CHECK_URL, "false", full_kwargs ) def test_unknown_kwargs(self): """ Unknown Akismet arguments are correctly rejected. """ bad_kwargs = {"bad_arg": "bad_val"} with self.assertRaises(akismet.UnknownArgumentError): self._mock_request( "comment_check", akismet.Akismet.COMMENT_CHECK_URL, "false", bad_kwargs )
[((150, 183), 'os.getenv', 'os.getenv', (['"""TEST_AKISMET_API_KEY"""'], {}), "('TEST_AKISMET_API_KEY')\n", (159, 183), False, 'import os\n'), ((199, 233), 'os.getenv', 'os.getenv', (['"""TEST_AKISMET_BLOG_URL"""'], {}), "('TEST_AKISMET_BLOG_URL')\n", (208, 233), False, 'import os\n'), ((372, 429), 'akismet.Akismet', 'akismet.Akismet', ([], {'key': 'self.api_key', 'blog_url': 'self.blog_url'}), '(key=self.api_key, blog_url=self.blog_url)\n', (387, 429), False, 'import akismet\n'), ((672, 729), 'akismet.Akismet', 'akismet.Akismet', ([], {'key': 'self.api_key', 'blog_url': 'self.blog_url'}), '(key=self.api_key, blog_url=self.blog_url)\n', (687, 729), False, 'import akismet\n'), ((3123, 3180), 'akismet.Akismet', 'akismet.Akismet', ([], {'key': 'self.api_key', 'blog_url': 'self.blog_url'}), '(key=self.api_key, blog_url=self.blog_url)\n', (3138, 3180), False, 'import akismet\n'), ((5853, 5869), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (5867, 5869), False, 'from unittest import mock\n'), ((6224, 6240), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (6238, 6240), False, 'from unittest import mock\n'), ((6663, 6679), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (6677, 6679), False, 'from unittest import mock\n'), ((7260, 7276), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (7274, 7276), False, 'from unittest import mock\n'), ((8017, 8033), 'unittest.mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (8031, 8033), False, 'from unittest import mock\n'), ((10539, 10562), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (10560, 10562), False, 'import datetime\n'), ((1009, 1066), 'akismet.Akismet', 'akismet.Akismet', ([], {'key': '"""invalid"""', 'blog_url': '"""http://invalid"""'}), "(key='invalid', blog_url='http://invalid')\n", (1024, 1066), False, 'import akismet\n'), ((1339, 1379), 'akismet.Akismet', 'akismet.Akismet', ([], {'key': 'None', 'blog_url': 'None'}), '(key=None, blog_url=None)\n', (1354, 1379), False, 'import akismet\n'), ((1513, 1530), 'akismet.Akismet', 'akismet.Akismet', ([], {}), '()\n', (1528, 1530), False, 'import akismet\n'), ((2856, 2896), 'akismet.Akismet', 'akismet.Akismet', ([], {'key': 'None', 'blog_url': 'None'}), '(key=None, blog_url=None)\n', (2871, 2896), False, 'import akismet\n'), ((2969, 2986), 'akismet.Akismet', 'akismet.Akismet', ([], {}), '()\n', (2984, 2986), False, 'import akismet\n'), ((3894, 3949), 'akismet.Akismet.verify_key', 'akismet.Akismet.verify_key', (['self.api_key', 'self.blog_url'], {}), '(self.api_key, self.blog_url)\n', (3920, 3949), False, 'import akismet\n'), ((4109, 4164), 'akismet.Akismet.verify_key', 'akismet.Akismet.verify_key', (['"""invalid"""', '"""http://invalid"""'], {}), "('invalid', 'http://invalid')\n", (4135, 4164), False, 'import akismet\n'), ((5883, 5921), 'unittest.mock.patch', 'mock.patch', (['"""requests.post"""', 'post_mock'], {}), "('requests.post', post_mock)\n", (5893, 5921), False, 'from unittest import mock\n'), ((6254, 6292), 'unittest.mock.patch', 'mock.patch', (['"""requests.post"""', 'post_mock'], {}), "('requests.post', post_mock)\n", (6264, 6292), False, 'from unittest import mock\n'), ((6693, 6731), 'unittest.mock.patch', 'mock.patch', (['"""requests.post"""', 'post_mock'], {}), "('requests.post', post_mock)\n", (6703, 6731), False, 'from unittest import mock\n'), ((7290, 7328), 'unittest.mock.patch', 'mock.patch', (['"""requests.post"""', 'post_mock'], {}), "('requests.post', post_mock)\n", (7300, 7328), False, 'from unittest import mock\n'), ((8505, 8543), 'unittest.mock.patch', 'mock.patch', (['"""requests.post"""', 'post_mock'], {}), "('requests.post', post_mock)\n", (8515, 8543), False, 'from unittest import mock\n'), ((8969, 9007), 'unittest.mock.patch', 'mock.patch', (['"""requests.post"""', 'post_mock'], {}), "('requests.post', post_mock)\n", (8979, 9007), False, 'from unittest import mock\n'), ((9021, 9076), 'akismet.Akismet.verify_key', 'akismet.Akismet.verify_key', (['self.api_key', 'self.blog_url'], {}), '(self.api_key, self.blog_url)\n', (9047, 9076), False, 'import akismet\n'), ((10611, 10641), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': '(30)'}), '(seconds=30)\n', (10629, 10641), False, 'import datetime\n'), ((2090, 2107), 'akismet.Akismet', 'akismet.Akismet', ([], {}), '()\n', (2105, 2107), False, 'import akismet\n'), ((2620, 2667), 'akismet.Akismet', 'akismet.Akismet', ([], {'key': 'self.api_key', 'blog_url': 'url'}), '(key=self.api_key, blog_url=url)\n', (2635, 2667), False, 'import akismet\n'), ((5998, 6053), 'akismet.Akismet.verify_key', 'akismet.Akismet.verify_key', (['self.api_key', 'self.blog_url'], {}), '(self.api_key, self.blog_url)\n', (6024, 6053), False, 'import akismet\n')]
gaurvigoyal/lifting_events_to_3d_hpe
experimenting/dataset/datamodule.py
66d27eb7534f81a95d9f68e17cc534ef2a2c9b1c
import pytorch_lightning as pl from torch.utils.data import DataLoader, Dataset from .core import BaseCore from .factory import BaseDataFactory class DataModule(pl.LightningDataModule): def __init__( self, dataset_factory: BaseDataFactory, core: BaseCore, aug_train_config, aug_test_config, batch_size: int, num_workers: int, train_val_split: float = 0.8, ): super().__init__() self.core = core self.batch_size = batch_size self.num_workers = num_workers self.dataset_factory = dataset_factory self.aug_train_config = aug_train_config self.aug_test_config = aug_test_config self.train_val_split = train_val_split def prepare_data(self, *args, **kwargs): pass def setup(self, stage=None): self.dataset_factory.set_dataset_core(self.core) ( self.train_indexes, self.val_indexes, self.test_indexes, ) = self.dataset_factory.get_train_test_split(self.train_val_split) self.train_dataset = self.dataset_factory.get_dataset( self.train_indexes, self.aug_train_config ) self.val_dataset = self.dataset_factory.get_dataset( self.val_indexes, self.aug_test_config ) self.test_dataset = self.dataset_factory.get_dataset( self.test_indexes, self.aug_test_config ) def train_dataloader(self): return get_dataloader(self.train_dataset, self.batch_size, self.num_workers) def val_dataloader(self): return get_dataloader( self.val_dataset, self.batch_size, shuffle=False, num_workers=self.num_workers, ) def test_dataloader(self): return get_dataloader( self.test_dataset, self.batch_size, shuffle=False, num_workers=self.num_workers, ) def test_frames_only_dataloader(self): return get_dataloader( self.dataset_factory.get_frame_only_dataset( self.test_indexes, self.aug_test_config ), self.batch_size, shuffle=False, num_workers=self.num_workers, ) def get_dataloader( dataset: Dataset, batch_size: int, num_workers: int = 12, shuffle=True ) -> DataLoader: loader = DataLoader( dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=True, ) return loader
[((2414, 2520), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': 'batch_size', 'shuffle': 'shuffle', 'num_workers': 'num_workers', 'pin_memory': '(True)'}), '(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=\n num_workers, pin_memory=True)\n', (2424, 2520), False, 'from torch.utils.data import DataLoader, Dataset\n')]
giulianoiorio/PeTar
sevn-interface/SEVN/resources/SEVN_walkthrough/running_folder/analysis_3_pandas.py
f6a849552b3d8e47c5e08fe90fed05bf38bc407d
import pandas as pd import matplotlib.pyplot as plt import numpy as np #Load file dt=pd.read_csv("sevn_output/output_0.csv") #Give a look to the columns print(dt.columns) #Consider only the final states dt=dt.drop_duplicates(["ID","name"], keep='last') #Load evolved file dte=pd.read_csv("sevn_output/evolved_0.dat",sep='\s+') #Give a look to the columns print(dte.columns) dte=dte.rename(columns={'#ID': 'ID','Mass_0':"Mzams_0", 'Mass_1':"Mzams_1"}) #After change print(dte.columns) #Join the two dataset dt = dt.merge(dte, on=["ID","name"], how="inner", suffixes=("","_ini") ) # - on: column(s, can be a list of columns) to match during the merge of the two tables. The colum(s) has(have) to be present in both the tables # - how: type of join to use, see documentation here and the next slide # - suffixes: columns with the same name in the two tables (not used in on) will be renamed adding these suffixes. #Give a look to the columns print(dt.columns) #Create filter indexes idx0 = (dt.RemnantType_0==6) idx1 = (dt.RemnantType_1==6) idxb0 = idx0 & dt.Semimajor.notnull() idxb1 = idx1 & dt.Semimajor.notnull() idxm0 = idxb0 & (dt.GWtime + dt.BWorldtime <= 14000) idxm1 = idxb1 & (dt.GWtime + dt.BWorldtime <= 14000) #Filter and join masses AllBH = pd.concat([dt[idx0].Mass_0,dt[idx1].Mass_1]) BoundBH = pd.concat([dt[idxb0].Mass_0,dt[idxb1].Mass_1]) MergingBH = pd.concat([dt[idxm0].Mass_0,dt[idxm1].Mass_1]) #Filter and join initial masses AllBHzams = pd.concat([dt[idx0].Mzams_0,dt[idx1].Mzams_1]) BoundBHzams = pd.concat([dt[idxb0].Mzams_0,dt[idxb1].Mzams_1]) MergingBHzams = pd.concat([dt[idxm0].Mzams_0,dt[idxm1].Mzams_1]) #Filter and join initial semimajor axis AllBHa = pd.concat([dt[idx0].a,dt[idx1].a]) BoundBHa = pd.concat([dt[idxb0].a,dt[idxb1].a]) MergingBHa = pd.concat([dt[idxm0].a,dt[idxm1].a]) #Plot plt.figure(figsize=(10,5)) plt.subplot(1,2,1) plt.scatter(AllBHzams,AllBH,zorder=1,edgecolor="k",s=30,label="All") plt.scatter(BoundBHzams,BoundBH,zorder=2,edgecolor="k",s=30, label="Bound") plt.scatter(MergingBHzams,MergingBH,zorder=3,edgecolor="k",s=30, label="Merging") plt.plot(np.linspace(0,140),np.linspace(0,140),ls="dashed",c="gray") plt.xscale("log") plt.yscale("log") plt.ylabel("BH mass [M$_\odot$]",fontsize=18) plt.xlabel("$M\mathrm{zams}$ [M$_\odot$]",fontsize=18) plt.gca().tick_params(axis='both', which='major', labelsize=18) plt.legend(fontsize=16) plt.subplot(1,2,2) plt.scatter(AllBHa,AllBH,zorder=1,edgecolor="k",s=30,label="All") plt.scatter(BoundBHa,BoundBH,zorder=2,edgecolor="k",s=30,label="Bound") plt.scatter(MergingBHa,MergingBH,zorder=3,edgecolor="k",s=30,label="Merging") plt.xscale("log") plt.yscale("log") plt.xlabel("Semimajor initial [R$_\odot$]",fontsize=18) plt.ylabel("BH mass [M$_\odot$]",fontsize=18) plt.gca().tick_params(axis='both', which='major', labelsize=18) plt.tight_layout() plt.savefig("analysis3.png") plt.show()
[((86, 125), 'pandas.read_csv', 'pd.read_csv', (['"""sevn_output/output_0.csv"""'], {}), "('sevn_output/output_0.csv')\n", (97, 125), True, 'import pandas as pd\n'), ((278, 330), 'pandas.read_csv', 'pd.read_csv', (['"""sevn_output/evolved_0.dat"""'], {'sep': '"""\\\\s+"""'}), "('sevn_output/evolved_0.dat', sep='\\\\s+')\n", (289, 330), True, 'import pandas as pd\n'), ((1264, 1309), 'pandas.concat', 'pd.concat', (['[dt[idx0].Mass_0, dt[idx1].Mass_1]'], {}), '([dt[idx0].Mass_0, dt[idx1].Mass_1])\n', (1273, 1309), True, 'import pandas as pd\n'), ((1319, 1366), 'pandas.concat', 'pd.concat', (['[dt[idxb0].Mass_0, dt[idxb1].Mass_1]'], {}), '([dt[idxb0].Mass_0, dt[idxb1].Mass_1])\n', (1328, 1366), True, 'import pandas as pd\n'), ((1378, 1425), 'pandas.concat', 'pd.concat', (['[dt[idxm0].Mass_0, dt[idxm1].Mass_1]'], {}), '([dt[idxm0].Mass_0, dt[idxm1].Mass_1])\n', (1387, 1425), True, 'import pandas as pd\n'), ((1470, 1517), 'pandas.concat', 'pd.concat', (['[dt[idx0].Mzams_0, dt[idx1].Mzams_1]'], {}), '([dt[idx0].Mzams_0, dt[idx1].Mzams_1])\n', (1479, 1517), True, 'import pandas as pd\n'), ((1531, 1580), 'pandas.concat', 'pd.concat', (['[dt[idxb0].Mzams_0, dt[idxb1].Mzams_1]'], {}), '([dt[idxb0].Mzams_0, dt[idxb1].Mzams_1])\n', (1540, 1580), True, 'import pandas as pd\n'), ((1596, 1645), 'pandas.concat', 'pd.concat', (['[dt[idxm0].Mzams_0, dt[idxm1].Mzams_1]'], {}), '([dt[idxm0].Mzams_0, dt[idxm1].Mzams_1])\n', (1605, 1645), True, 'import pandas as pd\n'), ((1695, 1730), 'pandas.concat', 'pd.concat', (['[dt[idx0].a, dt[idx1].a]'], {}), '([dt[idx0].a, dt[idx1].a])\n', (1704, 1730), True, 'import pandas as pd\n'), ((1741, 1778), 'pandas.concat', 'pd.concat', (['[dt[idxb0].a, dt[idxb1].a]'], {}), '([dt[idxb0].a, dt[idxb1].a])\n', (1750, 1778), True, 'import pandas as pd\n'), ((1791, 1828), 'pandas.concat', 'pd.concat', (['[dt[idxm0].a, dt[idxm1].a]'], {}), '([dt[idxm0].a, dt[idxm1].a])\n', (1800, 1828), True, 'import pandas as pd\n'), ((1836, 1863), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (1846, 1863), True, 'import matplotlib.pyplot as plt\n'), ((1864, 1884), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (1875, 1884), True, 'import matplotlib.pyplot as plt\n'), ((1883, 1956), 'matplotlib.pyplot.scatter', 'plt.scatter', (['AllBHzams', 'AllBH'], {'zorder': '(1)', 'edgecolor': '"""k"""', 's': '(30)', 'label': '"""All"""'}), "(AllBHzams, AllBH, zorder=1, edgecolor='k', s=30, label='All')\n", (1894, 1956), True, 'import matplotlib.pyplot as plt\n'), ((1952, 2031), 'matplotlib.pyplot.scatter', 'plt.scatter', (['BoundBHzams', 'BoundBH'], {'zorder': '(2)', 'edgecolor': '"""k"""', 's': '(30)', 'label': '"""Bound"""'}), "(BoundBHzams, BoundBH, zorder=2, edgecolor='k', s=30, label='Bound')\n", (1963, 2031), True, 'import matplotlib.pyplot as plt\n'), ((2028, 2118), 'matplotlib.pyplot.scatter', 'plt.scatter', (['MergingBHzams', 'MergingBH'], {'zorder': '(3)', 'edgecolor': '"""k"""', 's': '(30)', 'label': '"""Merging"""'}), "(MergingBHzams, MergingBH, zorder=3, edgecolor='k', s=30, label=\n 'Merging')\n", (2039, 2118), True, 'import matplotlib.pyplot as plt\n'), ((2179, 2196), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (2189, 2196), True, 'import matplotlib.pyplot as plt\n'), ((2197, 2214), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (2207, 2214), True, 'import matplotlib.pyplot as plt\n'), ((2215, 2262), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""BH mass [M$_\\\\odot$]"""'], {'fontsize': '(18)'}), "('BH mass [M$_\\\\odot$]', fontsize=18)\n", (2225, 2262), True, 'import matplotlib.pyplot as plt\n'), ((2261, 2319), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$M\\\\mathrm{zams}$ [M$_\\\\odot$]"""'], {'fontsize': '(18)'}), "('$M\\\\mathrm{zams}$ [M$_\\\\odot$]', fontsize=18)\n", (2271, 2319), True, 'import matplotlib.pyplot as plt\n'), ((2381, 2404), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(16)'}), '(fontsize=16)\n', (2391, 2404), True, 'import matplotlib.pyplot as plt\n'), ((2406, 2426), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (2417, 2426), True, 'import matplotlib.pyplot as plt\n'), ((2425, 2495), 'matplotlib.pyplot.scatter', 'plt.scatter', (['AllBHa', 'AllBH'], {'zorder': '(1)', 'edgecolor': '"""k"""', 's': '(30)', 'label': '"""All"""'}), "(AllBHa, AllBH, zorder=1, edgecolor='k', s=30, label='All')\n", (2436, 2495), True, 'import matplotlib.pyplot as plt\n'), ((2491, 2567), 'matplotlib.pyplot.scatter', 'plt.scatter', (['BoundBHa', 'BoundBH'], {'zorder': '(2)', 'edgecolor': '"""k"""', 's': '(30)', 'label': '"""Bound"""'}), "(BoundBHa, BoundBH, zorder=2, edgecolor='k', s=30, label='Bound')\n", (2502, 2567), True, 'import matplotlib.pyplot as plt\n'), ((2563, 2650), 'matplotlib.pyplot.scatter', 'plt.scatter', (['MergingBHa', 'MergingBH'], {'zorder': '(3)', 'edgecolor': '"""k"""', 's': '(30)', 'label': '"""Merging"""'}), "(MergingBHa, MergingBH, zorder=3, edgecolor='k', s=30, label=\n 'Merging')\n", (2574, 2650), True, 'import matplotlib.pyplot as plt\n'), ((2641, 2658), 'matplotlib.pyplot.xscale', 'plt.xscale', (['"""log"""'], {}), "('log')\n", (2651, 2658), True, 'import matplotlib.pyplot as plt\n'), ((2659, 2676), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (2669, 2676), True, 'import matplotlib.pyplot as plt\n'), ((2677, 2735), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Semimajor initial [R$_\\\\odot$]"""'], {'fontsize': '(18)'}), "('Semimajor initial [R$_\\\\odot$]', fontsize=18)\n", (2687, 2735), True, 'import matplotlib.pyplot as plt\n'), ((2734, 2781), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""BH mass [M$_\\\\odot$]"""'], {'fontsize': '(18)'}), "('BH mass [M$_\\\\odot$]', fontsize=18)\n", (2744, 2781), True, 'import matplotlib.pyplot as plt\n'), ((2847, 2865), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2863, 2865), True, 'import matplotlib.pyplot as plt\n'), ((2866, 2894), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""analysis3.png"""'], {}), "('analysis3.png')\n", (2877, 2894), True, 'import matplotlib.pyplot as plt\n'), ((2895, 2905), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2903, 2905), True, 'import matplotlib.pyplot as plt\n'), ((2119, 2138), 'numpy.linspace', 'np.linspace', (['(0)', '(140)'], {}), '(0, 140)\n', (2130, 2138), True, 'import numpy as np\n'), ((2138, 2157), 'numpy.linspace', 'np.linspace', (['(0)', '(140)'], {}), '(0, 140)\n', (2149, 2157), True, 'import numpy as np\n'), ((2317, 2326), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2324, 2326), True, 'import matplotlib.pyplot as plt\n'), ((2780, 2789), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2787, 2789), True, 'import matplotlib.pyplot as plt\n')]
VladimirLazor/Lohika
apps/tg_bot/apps.py
a36407feeb2e3ade4f8c689030f343d88ff47a92
from django.apps import AppConfig class TgBotConfig(AppConfig): name = 'apps.tg_bot'
[]
rikeshtailor/Office365-REST-Python-Client
office365/sharepoint/portal/group_site_manager.py
ca7bfa1b22212137bb4e984c0457632163e89a43
from office365.runtime.client_object import ClientObject from office365.runtime.client_result import ClientResult from office365.runtime.http.http_method import HttpMethod from office365.runtime.queries.service_operation_query import ServiceOperationQuery from office365.runtime.resource_path import ResourcePath from office365.sharepoint.portal.group_creation_params import GroupCreationInformation from office365.sharepoint.portal.group_site_info import GroupSiteInfo class GroupSiteManager(ClientObject): def __init__(self, context): super(GroupSiteManager, self).__init__(context, ResourcePath("GroupSiteManager"), None) def create_group_ex(self, display_name, alias, is_public, optional_params=None): """ Create a modern site :param str display_name: :param str alias: :param bool is_public: :param office365.sharepoint.portal.group_creation_params.GroupCreationParams or None optional_params: """ payload = GroupCreationInformation(display_name, alias, is_public, optional_params) result = ClientResult(self.context, GroupSiteInfo()) qry = ServiceOperationQuery(self, "CreateGroupEx", None, payload, None, result) self.context.add_query(qry) return result def delete(self, site_url): """ Deletes a SharePoint Team site :type site_url: str """ payload = { "siteUrl": site_url } qry = ServiceOperationQuery(self, "Delete", None, payload) self.context.add_query(qry) return self def get_status(self, group_id): """Get the status of a SharePoint site :type group_id: str """ result = ClientResult(self.context, GroupSiteInfo()) qry = ServiceOperationQuery(self, "GetSiteStatus", None, {'groupId': group_id}, None, result) self.context.add_query(qry) def _construct_status_request(request): request.method = HttpMethod.Get request.url += "?groupId='{0}'".format(group_id) self.context.before_execute(_construct_status_request) return result
[((997, 1070), 'office365.sharepoint.portal.group_creation_params.GroupCreationInformation', 'GroupCreationInformation', (['display_name', 'alias', 'is_public', 'optional_params'], {}), '(display_name, alias, is_public, optional_params)\n', (1021, 1070), False, 'from office365.sharepoint.portal.group_creation_params import GroupCreationInformation\n'), ((1146, 1219), 'office365.runtime.queries.service_operation_query.ServiceOperationQuery', 'ServiceOperationQuery', (['self', '"""CreateGroupEx"""', 'None', 'payload', 'None', 'result'], {}), "(self, 'CreateGroupEx', None, payload, None, result)\n", (1167, 1219), False, 'from office365.runtime.queries.service_operation_query import ServiceOperationQuery\n'), ((1479, 1531), 'office365.runtime.queries.service_operation_query.ServiceOperationQuery', 'ServiceOperationQuery', (['self', '"""Delete"""', 'None', 'payload'], {}), "(self, 'Delete', None, payload)\n", (1500, 1531), False, 'from office365.runtime.queries.service_operation_query import ServiceOperationQuery\n'), ((1788, 1879), 'office365.runtime.queries.service_operation_query.ServiceOperationQuery', 'ServiceOperationQuery', (['self', '"""GetSiteStatus"""', 'None', "{'groupId': group_id}", 'None', 'result'], {}), "(self, 'GetSiteStatus', None, {'groupId': group_id},\n None, result)\n", (1809, 1879), False, 'from office365.runtime.queries.service_operation_query import ServiceOperationQuery\n'), ((599, 631), 'office365.runtime.resource_path.ResourcePath', 'ResourcePath', (['"""GroupSiteManager"""'], {}), "('GroupSiteManager')\n", (611, 631), False, 'from office365.runtime.resource_path import ResourcePath\n'), ((1115, 1130), 'office365.sharepoint.portal.group_site_info.GroupSiteInfo', 'GroupSiteInfo', ([], {}), '()\n', (1128, 1130), False, 'from office365.sharepoint.portal.group_site_info import GroupSiteInfo\n'), ((1757, 1772), 'office365.sharepoint.portal.group_site_info.GroupSiteInfo', 'GroupSiteInfo', ([], {}), '()\n', (1770, 1772), False, 'from office365.sharepoint.portal.group_site_info import GroupSiteInfo\n')]
smok-serwis/cython
tests/errors/e_tuple_args_T692.py
e551a3a348888bd89d4aad809916709a634af1fb
# ticket: 692 # mode: error def func((a, b)): return a + b _ERRORS = u""" 4:9: Missing argument name 5:11: undeclared name not builtin: a 5:15: undeclared name not builtin: b """
[]
Ladvien/esp32_upython_env
ble.py
8b0feab940efd3feff16220473e1b5b27d679a56
import bluetooth import time bt = bluetooth.BLE() # singleton bt.active(True) # activate BT stack UART_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E') UART_TX = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,) UART_RX = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_WRITE,) UART_SERVICE = (UART_UUID, (UART_TX, UART_RX,),) SERVICES = (UART_SERVICE,) ( (tx, rx,), ) = bt.gatts_register_services(SERVICES) bt.gap_advertise(100)
[((34, 49), 'bluetooth.BLE', 'bluetooth.BLE', ([], {}), '()\n', (47, 49), False, 'import bluetooth\n'), ((149, 203), 'bluetooth.UUID', 'bluetooth.UUID', (['"""6E400001-B5A3-F393-E0A9-E50E24DCCA9E"""'], {}), "('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')\n", (163, 203), False, 'import bluetooth\n'), ((215, 269), 'bluetooth.UUID', 'bluetooth.UUID', (['"""6E400003-B5A3-F393-E0A9-E50E24DCCA9E"""'], {}), "('6E400003-B5A3-F393-E0A9-E50E24DCCA9E')\n", (229, 269), False, 'import bluetooth\n'), ((328, 382), 'bluetooth.UUID', 'bluetooth.UUID', (['"""6E400002-B5A3-F393-E0A9-E50E24DCCA9E"""'], {}), "('6E400002-B5A3-F393-E0A9-E50E24DCCA9E')\n", (342, 382), False, 'import bluetooth\n')]
luxbe/sledo
examples/custom-generator/customer.py
26aa2b59b11ea115afc25bb407602578cb342170
from random import randint from sledo.generate.field_generators.base import FieldGenerator values = ("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Germany", "Greece", "Hungary", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia", "Slovenia", "Spain", "Sweden", "United States", "Japan", "United Kingdom", "Bangladesh", "Argentina", "China") count = len(values) - 1 class CustomerAddressGenerator(FieldGenerator): def generate(self, **_): return values[randint(0, count)]
[((933, 950), 'random.randint', 'randint', (['(0)', 'count'], {}), '(0, count)\n', (940, 950), False, 'from random import randint\n')]
crawftv/CRAwTO
status-uncertain/baseline_model.py
8c6fdb93ed963cbddfe967b041e8beb578d1e94d
#!/usr/bin/env python3 from sklearn.metrics import r2_score import numpy as np class BaselineModel(object): def get_params(self): return None def predict(self, X): return np.ones_like(X.index.values) * self._y_pred def score(self, X, y): y_true = y y_pred = np.ones_like(y_true) * self._y_pred return r2_score(y_true, y_pred) class BaselineClassificationPrediction(BaselineModel): def fit( self, X, y, ): self.y_pred = y.mode() return self def predict( self, X, ): return self.y_pred class BaselineRegressionPrediction(BaselineModel): def fit(self, X, y): self._y_pred = y.median() return self
[((357, 381), 'sklearn.metrics.r2_score', 'r2_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (365, 381), False, 'from sklearn.metrics import r2_score\n'), ((198, 226), 'numpy.ones_like', 'np.ones_like', (['X.index.values'], {}), '(X.index.values)\n', (210, 226), True, 'import numpy as np\n'), ((306, 326), 'numpy.ones_like', 'np.ones_like', (['y_true'], {}), '(y_true)\n', (318, 326), True, 'import numpy as np\n')]
ecalder6/MT-HW2
aligner/grow_diag_final.py
1356aeb374a6e4d0b0ae819684bf314039948c56
import optparse import sys def make_set(data, s, e_vocab, f_vocab, aligned, reverse): for pair in data.split(): cur = pair.split('-') if reverse: e_vocab.add(int(cur[1])) f_vocab.add(int(cur[0])) aligned.add(int(cur[0])) s.add((int(cur[1]), int(cur[0]))) else: e_vocab.add(int(cur[0])) f_vocab.add(int(cur[1])) aligned.add(int(cur[0])) s.add((int(cur[0]), int(cur[1]))) def grow_diag_final_and(e2f_data, f2e_data): directions = [(-1,0),(0,-1),(1,0),(0,1),(-1,-1),(-1,1),(1,-1),(1,1)] for (i, (e2f, f2e)) in enumerate(zip(open(e2f_data), open(f2e_data))): e2f_set, f2e_set, e_vocab, f_vocab, e_aligned, f_aligned = set(), set(), set(), set(), set(), set() make_set(e2f, e2f_set, e_vocab, f_vocab, e_aligned, False) make_set(f2e, f2e_set, e_vocab, f_vocab, f_aligned, True) alignment = e2f_set & f2e_set union_alignment = e2f_set | f2e_set grow_diag(e_vocab, f_vocab, e_aligned, f_aligned, alignment, union_alignment, directions) final(e_vocab, f_vocab, e_aligned, f_aligned, alignment, union_alignment, True) for e, f in alignment: sys.stdout.write("%i-%i " % (e,f)) sys.stdout.write("\n") def grow_diag(e_vocab, f_vocab, e_alignment, f_alignment, alignment, union_alignment, directions): prev_len = 0 while prev_len != len(alignment): prev_len = len(alignment) for e in e_vocab: for f in f_vocab: if (e, f) in alignment: for d in directions: en, fn = e + d[0], f + d[1] if (en not in e_alignment or fn not in f_alignment) and (en, fn) in union_alignment: alignment.add((en, fn)) e_alignment.add(en) f_alignment.add(fn) def final(e_vocab, f_vocab, e_alignment, f_alignment, alignment, union_alignment, final_and): for e in e_vocab: for f in f_vocab: c = False if final_and: c = e not in e_alignment and f not in f_alignment else: c = e not in e_alignment or f not in f_alignment if c and (e, f) in union_alignment: alignment.add((e, f)) e_alignment.add(e) f_alignment.add(f) def main(): optparser = optparse.OptionParser() optparser.add_option("-d", "--data", dest="train", default="data/alignment", help="Data filename prefix (default=data)") optparser.add_option("-e", "--e2f", dest="e2f", default="ef", help="Suffix of English to French filename (default=ef)") optparser.add_option("-f", "--f2e", dest="f2e", default="fe", help="Suffix of French to English filename (default=fe)") optparser.add_option("-a", "--final_and", dest="final_and", action="store_true", help="Whether to use Final-And version of the algorithm") (opts, args) = optparser.parse_args() e2f_data = "%s.%s" % (opts.train, opts.e2f) f2e_data = "%s.%s" % (opts.train, opts.f2e) grow_diag_final_and(e2f_data, f2e_data) if __name__ == "__main__": main()
[((2468, 2491), 'optparse.OptionParser', 'optparse.OptionParser', ([], {}), '()\n', (2489, 2491), False, 'import optparse\n'), ((1285, 1307), 'sys.stdout.write', 'sys.stdout.write', (['"""\n"""'], {}), "('\\n')\n", (1301, 1307), False, 'import sys\n'), ((1242, 1277), 'sys.stdout.write', 'sys.stdout.write', (["('%i-%i ' % (e, f))"], {}), "('%i-%i ' % (e, f))\n", (1258, 1277), False, 'import sys\n')]
Transcranial-Solutions/t-bears
tests/test_tbears_db.py
4712b8bb425814c444ee75f3220a31df934982aa
# -*- coding: utf-8 -*- # Copyright 2017-2018 ICON Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import unittest from tbears.block_manager.tbears_db import TbearsDB DIRECTORY_PATH = os.path.abspath((os.path.dirname(__file__))) DB_PATH = os.path.join(DIRECTORY_PATH, './.tbears_db') class TestTBearsDB(unittest.TestCase): def setUp(self): self.TBEARS_DB = TbearsDB(TbearsDB.make_db(DB_PATH)) self.test_key = b'test_key' self.test_value = b'test_value' def tearDown(self): self.TBEARS_DB.close() shutil.rmtree(DB_PATH) def test_put_and_get(self): # Put and get self.TBEARS_DB.put(self.test_key, self.test_value) ret = self.TBEARS_DB.get(self.test_key) self.assertEqual(ret, self.test_value) # overwrite overwrite_value = b'test_value_overwrite' self.TBEARS_DB.put(self.test_key, overwrite_value) ret = self.TBEARS_DB.get(self.test_key) self.assertEqual(ret, overwrite_value) # get invalid key ret = self.TBEARS_DB.get(b'invalid_key') self.assertIsNone(ret) # put invalid type self.assertRaises(TypeError, self.TBEARS_DB.put, 'test_key', self.test_value) self.assertRaises(TypeError, self.TBEARS_DB.put, self.test_key, 123) def test_delete(self): self.TBEARS_DB.put(self.test_key, self.test_value) ret = self.TBEARS_DB.get(self.test_key) self.assertEqual(ret, self.test_value) self.TBEARS_DB.delete(self.test_key) ret = self.TBEARS_DB.get(self.test_key) self.assertIsNone(ret) def test_iterator(self): self.TBEARS_DB.put(b'key1', b'value1') self.TBEARS_DB.put(b'key2', b'value2') self.TBEARS_DB.put(b'key3', b'value3') self.TBEARS_DB.put(b'key4', b'value4') i = 1 for _, actual_value in self.TBEARS_DB.iterator(): expected_value = ('value' + str(i)).encode() self.assertEqual(expected_value, actual_value) i += 1
[((771, 815), 'os.path.join', 'os.path.join', (['DIRECTORY_PATH', '"""./.tbears_db"""'], {}), "(DIRECTORY_PATH, './.tbears_db')\n", (783, 815), False, 'import os\n'), ((733, 758), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (748, 758), False, 'import os\n'), ((1080, 1102), 'shutil.rmtree', 'shutil.rmtree', (['DB_PATH'], {}), '(DB_PATH)\n', (1093, 1102), False, 'import shutil\n'), ((913, 938), 'tbears.block_manager.tbears_db.TbearsDB.make_db', 'TbearsDB.make_db', (['DB_PATH'], {}), '(DB_PATH)\n', (929, 938), False, 'from tbears.block_manager.tbears_db import TbearsDB\n')]
pierky/exabgp
src/exabgp/bgp/message/update/attribute/bgpls/link/mplsmask.py
34be537ae5906c0830b31da1152ae63108ccf911
# encoding: utf-8 """ mplsmask.py Created by Evelio Vila on 2016-12-01. Copyright (c) 2014-2017 Exa Networks. All rights reserved. """ from exabgp.bgp.message.notification import Notify from exabgp.bgp.message.update.attribute.bgpls.linkstate import LinkState from exabgp.bgp.message.update.attribute.bgpls.linkstate import FlagLS # 0 1 2 3 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | Type | Length | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # |L|R| Reserved | # +-+-+-+-+-+-+-+-+ # https://tools.ietf.org/html/rfc7752#section-3.3.2.2 MPLS Protocol Mask # # +------------+------------------------------------------+-----------+ # | Bit | Description | Reference | # +------------+------------------------------------------+-----------+ # | 'L' | Label Distribution Protocol (LDP) | [RFC5036] | # | 'R' | Extension to RSVP for LSP Tunnels | [RFC3209] | # | | (RSVP-TE) | | # | 'Reserved' | Reserved for future use | | # +------------+------------------------------------------+-----------+ # RFC 7752 3.3.2.2. MPLS Protocol Mask TLV @LinkState.register() class MplsMask(FlagLS): REPR = 'MPLS Protocol mask' JSON = 'mpls-mask' TLV = 1094 FLAGS = ['LDP', 'RSVP-TE', 'RSV', 'RSV', 'RSV', 'RSV', 'RSV', 'RSV'] LEN = 1
[((1458, 1478), 'exabgp.bgp.message.update.attribute.bgpls.linkstate.LinkState.register', 'LinkState.register', ([], {}), '()\n', (1476, 1478), False, 'from exabgp.bgp.message.update.attribute.bgpls.linkstate import LinkState\n')]
hsorby/scaffoldmaker
tests/test_cecum.py
5e3b4531665dbc465b53acc1662f8d9bbb9dc1e1
import unittest from opencmiss.utils.zinc.finiteelement import evaluateFieldNodesetRange from opencmiss.utils.zinc.general import ChangeManager from opencmiss.zinc.context import Context from opencmiss.zinc.element import Element from opencmiss.zinc.field import Field from opencmiss.zinc.result import RESULT_OK from scaffoldmaker.meshtypes.meshtype_3d_cecum1 import MeshType_3d_cecum1 from scaffoldmaker.utils.zinc_utils import createFaceMeshGroupExteriorOnFace from testutils import assertAlmostEqualList class CecumScaffoldTestCase(unittest.TestCase): def test_cecum1(self): """ Test creation of cecum scaffold. """ parameterSetNames = MeshType_3d_cecum1.getParameterSetNames() self.assertEqual(parameterSetNames, ["Default", "Pig 1"]) options = MeshType_3d_cecum1.getDefaultOptions("Pig 1") self.assertEqual(30, len(options)) self.assertEqual(5, options.get("Number of segments")) self.assertEqual(2, options.get("Number of elements around tenia coli")) self.assertEqual(8, options.get("Number of elements along segment")) self.assertEqual(1, options.get("Number of elements through wall")) self.assertEqual(35.0, options.get("Start inner radius")) self.assertEqual(3.0, options.get("Start inner radius derivative")) self.assertEqual(38.0, options.get("End inner radius")) self.assertEqual(3.0, options.get("End inner radius derivative")) self.assertEqual(0.5, options.get("Corner inner radius factor")) self.assertEqual(0.25, options.get("Haustrum inner radius factor")) self.assertEqual(4.0, options.get("Segment length mid derivative factor")) self.assertEqual(3, options.get("Number of tenia coli")) self.assertEqual(5.0, options.get("Start tenia coli width")) self.assertEqual(0.0, options.get("End tenia coli width derivative")) self.assertEqual(2.0, options.get("Wall thickness")) ostiumOptions = options['Ileocecal junction'] ostiumSettings = ostiumOptions.getScaffoldSettings() self.assertEqual(1, ostiumSettings.get("Number of vessels")) self.assertEqual(8, ostiumSettings.get("Number of elements around ostium")) self.assertEqual(1, ostiumSettings.get("Number of elements through wall")) self.assertEqual(20.0, ostiumSettings.get("Ostium diameter")) self.assertEqual(10.0, ostiumSettings.get("Vessel inner diameter")) self.assertEqual(60, options.get("Ileocecal junction angular position degrees")) self.assertEqual(0.5, options.get("Ileocecal junction position along factor")) context = Context("Test") region = context.getDefaultRegion() self.assertTrue(region.isValid()) annotationGroups = MeshType_3d_cecum1.generateBaseMesh(region, options) self.assertEqual(2, len(annotationGroups)) fieldmodule = region.getFieldmodule() self.assertEqual(RESULT_OK, fieldmodule.defineAllFaces()) mesh3d = fieldmodule.findMeshByDimension(3) self.assertEqual(1492, mesh3d.getSize()) mesh2d = fieldmodule.findMeshByDimension(2) self.assertEqual(5617, mesh2d.getSize()) mesh1d = fieldmodule.findMeshByDimension(1) self.assertEqual(6767, mesh1d.getSize()) nodes = fieldmodule.findNodesetByFieldDomainType(Field.DOMAIN_TYPE_NODES) self.assertEqual(2642, nodes.getSize()) datapoints = fieldmodule.findNodesetByFieldDomainType(Field.DOMAIN_TYPE_DATAPOINTS) self.assertEqual(0, datapoints.getSize()) coordinates = fieldmodule.findFieldByName("coordinates").castFiniteElement() self.assertTrue(coordinates.isValid()) minimums, maximums = evaluateFieldNodesetRange(coordinates, nodes) assertAlmostEqualList(self, minimums, [-49.01658984455258, -46.89686037622053, -2.343256155753525], 1.0E-6) assertAlmostEqualList(self, maximums, [42.18085849205387, 54.89264119402881, 180.0], 1.0E-6) with ChangeManager(fieldmodule): one = fieldmodule.createFieldConstant(1.0) faceMeshGroup = createFaceMeshGroupExteriorOnFace(fieldmodule, Element.FACE_TYPE_XI3_1) surfaceAreaField = fieldmodule.createFieldMeshIntegral(one, coordinates, faceMeshGroup) surfaceAreaField.setNumbersOfPoints(4) volumeField = fieldmodule.createFieldMeshIntegral(one, coordinates, mesh3d) volumeField.setNumbersOfPoints(3) fieldcache = fieldmodule.createFieldcache() result, surfaceArea = surfaceAreaField.evaluateReal(fieldcache, 1) self.assertEqual(result, RESULT_OK) self.assertAlmostEqual(surfaceArea, 65960.20655074248, delta=1.0E-6) result, volume = volumeField.evaluateReal(fieldcache, 1) self.assertEqual(result, RESULT_OK) self.assertAlmostEqual(volume, 127905.28250502056, delta=1.0E-6) if __name__ == "__main__": unittest.main()
[((4961, 4976), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4974, 4976), False, 'import unittest\n'), ((681, 722), 'scaffoldmaker.meshtypes.meshtype_3d_cecum1.MeshType_3d_cecum1.getParameterSetNames', 'MeshType_3d_cecum1.getParameterSetNames', ([], {}), '()\n', (720, 722), False, 'from scaffoldmaker.meshtypes.meshtype_3d_cecum1 import MeshType_3d_cecum1\n'), ((807, 852), 'scaffoldmaker.meshtypes.meshtype_3d_cecum1.MeshType_3d_cecum1.getDefaultOptions', 'MeshType_3d_cecum1.getDefaultOptions', (['"""Pig 1"""'], {}), "('Pig 1')\n", (843, 852), False, 'from scaffoldmaker.meshtypes.meshtype_3d_cecum1 import MeshType_3d_cecum1\n'), ((2670, 2685), 'opencmiss.zinc.context.Context', 'Context', (['"""Test"""'], {}), "('Test')\n", (2677, 2685), False, 'from opencmiss.zinc.context import Context\n'), ((2799, 2851), 'scaffoldmaker.meshtypes.meshtype_3d_cecum1.MeshType_3d_cecum1.generateBaseMesh', 'MeshType_3d_cecum1.generateBaseMesh', (['region', 'options'], {}), '(region, options)\n', (2834, 2851), False, 'from scaffoldmaker.meshtypes.meshtype_3d_cecum1 import MeshType_3d_cecum1\n'), ((3753, 3798), 'opencmiss.utils.zinc.finiteelement.evaluateFieldNodesetRange', 'evaluateFieldNodesetRange', (['coordinates', 'nodes'], {}), '(coordinates, nodes)\n', (3778, 3798), False, 'from opencmiss.utils.zinc.finiteelement import evaluateFieldNodesetRange\n'), ((3807, 3918), 'testutils.assertAlmostEqualList', 'assertAlmostEqualList', (['self', 'minimums', '[-49.01658984455258, -46.89686037622053, -2.343256155753525]', '(1e-06)'], {}), '(self, minimums, [-49.01658984455258, -\n 46.89686037622053, -2.343256155753525], 1e-06)\n', (3828, 3918), False, 'from testutils import assertAlmostEqualList\n'), ((3923, 4018), 'testutils.assertAlmostEqualList', 'assertAlmostEqualList', (['self', 'maximums', '[42.18085849205387, 54.89264119402881, 180.0]', '(1e-06)'], {}), '(self, maximums, [42.18085849205387, 54.89264119402881,\n 180.0], 1e-06)\n', (3944, 4018), False, 'from testutils import assertAlmostEqualList\n'), ((4030, 4056), 'opencmiss.utils.zinc.general.ChangeManager', 'ChangeManager', (['fieldmodule'], {}), '(fieldmodule)\n', (4043, 4056), False, 'from opencmiss.utils.zinc.general import ChangeManager\n'), ((4141, 4212), 'scaffoldmaker.utils.zinc_utils.createFaceMeshGroupExteriorOnFace', 'createFaceMeshGroupExteriorOnFace', (['fieldmodule', 'Element.FACE_TYPE_XI3_1'], {}), '(fieldmodule, Element.FACE_TYPE_XI3_1)\n', (4174, 4212), False, 'from scaffoldmaker.utils.zinc_utils import createFaceMeshGroupExteriorOnFace\n')]
jm66/pyvmomi-community-samples
samples/destroy_vm.py
5ca4a50b767500e07b9bce9fba70240bfa963a4e
#!/usr/bin/env python # Copyright 2015 Michael Rice <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import atexit from pyVim import connect from pyVmomi import vim from tools import cli from tools import tasks def setup_args(): """Adds additional ARGS to allow the vm name or uuid to be set. """ parser = cli.build_arg_parser() # using j here because -u is used for user parser.add_argument('-j', '--uuid', help='BIOS UUID of the VirtualMachine you want ' 'to destroy.') parser.add_argument('-n', '--name', help='DNS Name of the VirtualMachine you want to ' 'destroy.') parser.add_argument('-i', '--ip', help='IP Address of the VirtualMachine you want to ' 'destroy') parser.add_argument('-v', '--vm', help='VM name of the VirtualMachine you want ' 'to destroy.') my_args = parser.parse_args() return cli.prompt_for_password(my_args) def get_obj(content, vimtype, name): """Create contrainer view and search for object in it""" obj = None container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for c in container.view: if name: if c.name == name: obj = c break else: obj = c break container.Destroy() return obj ARGS = setup_args() SI = None try: SI = connect.SmartConnectNoSSL(host=ARGS.host, user=ARGS.user, pwd=ARGS.password, port=ARGS.port) atexit.register(connect.Disconnect, SI) except (IOError, vim.fault.InvalidLogin): pass if not SI: raise SystemExit("Unable to connect to host with supplied credentials.") VM = None if ARGS.vm: VM = get_obj(SI.content, [vim.VirtualMachine], ARGS.vm) elif ARGS.uuid: VM = SI.content.searchIndex.FindByUuid(None, ARGS.uuid, True, False) elif ARGS.name: VM = SI.content.searchIndex.FindByDnsName(None, ARGS.name, True) elif ARGS.ip: VM = SI.content.searchIndex.FindByIp(None, ARGS.ip, True) if VM is None: raise SystemExit( "Unable to locate VirtualMachine. Arguments given: " "vm - {0} , uuid - {1} , name - {2} , ip - {3}" .format(ARGS.vm, ARGS.uuid, ARGS.name, ARGS.ip) ) print("Found: {0}".format(VM.name)) print("The current powerState is: {0}".format(VM.runtime.powerState)) if format(VM.runtime.powerState) == "poweredOn": print("Attempting to power off {0}".format(VM.name)) TASK = VM.PowerOffVM_Task() tasks.wait_for_tasks(SI, [TASK]) print("{0}".format(TASK.info.state)) print("Destroying VM from vSphere.") TASK = VM.Destroy_Task() tasks.wait_for_tasks(SI, [TASK]) print("Done.")
[((3610, 3642), 'tools.tasks.wait_for_tasks', 'tasks.wait_for_tasks', (['SI', '[TASK]'], {}), '(SI, [TASK])\n', (3630, 3642), False, 'from tools import tasks\n'), ((909, 931), 'tools.cli.build_arg_parser', 'cli.build_arg_parser', ([], {}), '()\n', (929, 931), False, 'from tools import cli\n'), ((1647, 1679), 'tools.cli.prompt_for_password', 'cli.prompt_for_password', (['my_args'], {}), '(my_args)\n', (1670, 1679), False, 'from tools import cli\n'), ((2156, 2252), 'pyVim.connect.SmartConnectNoSSL', 'connect.SmartConnectNoSSL', ([], {'host': 'ARGS.host', 'user': 'ARGS.user', 'pwd': 'ARGS.password', 'port': 'ARGS.port'}), '(host=ARGS.host, user=ARGS.user, pwd=ARGS.password,\n port=ARGS.port)\n', (2181, 2252), False, 'from pyVim import connect\n'), ((2358, 2397), 'atexit.register', 'atexit.register', (['connect.Disconnect', 'SI'], {}), '(connect.Disconnect, SI)\n', (2373, 2397), False, 'import atexit\n'), ((3473, 3505), 'tools.tasks.wait_for_tasks', 'tasks.wait_for_tasks', (['SI', '[TASK]'], {}), '(SI, [TASK])\n', (3493, 3505), False, 'from tools import tasks\n')]
1000monkeys/MastermindRedux
helpers/Screen.py
6b07a341ecbf2ea325949a49c84218cc3632cd33
import sys class Screen: def __init__(self) -> None: pass def handle_events(self, events): for event in events: if event.type == self.pygame.QUIT: sys.exit() def draw(self, screen): pass
[((201, 211), 'sys.exit', 'sys.exit', ([], {}), '()\n', (209, 211), False, 'import sys\n')]
chris-han/ailab
VirtualStage/BackgroundMatting/fixed_threshold.py
b77d90f9089fa8003095843aa5de718fe73965a7
import os def fixed_split(videos, thresholds, mask_suffix, overlap=0, background_path="/"): # crop target background video frames backgrounds = [os.path.join(background_path, f[:-4]) for f in os.listdir(background_path) if f.endswith(".mp4")] print(f"Splitting {len(backgrounds)} target background videos vertically by a fixed threshold") for i, background in enumerate(backgrounds): if i >= (len(thresholds)) or not thresholds[i]: continue try: os.makedirs(background + "_up") os.makedirs(background + "_dw") except FileExistsError: continue threshold = int(thresholds[i]) iup_region = f"iw:{threshold + overlap}:0:0" idw_region = f"iw:ih-{threshold + overlap}:0:{threshold - overlap}" cmd=( f"ffmpeg -i \"{os.path.join(background, '%04d_img.png')}\" " f'-filter:v "crop={iup_region}" ' f"\"{os.path.join(background+'_up', '%04d_img.png')}\"" " > split_background_logs.txt 2>&1" ) code = os.system( cmd ) if code != 0: exit(code) code = os.system( f"ffmpeg -i \"{os.path.join(background, '%04d_img.png')}\" " f'-filter:v "crop={idw_region}" ' f"\"{os.path.join(background+'_dw', '%04d_img.png')}\"" " > split_background_logs.txt 2>&1" ) if code != 0: exit(code) print(f"Splitting {len(videos)} videos vertically by a fixed threshold") for i, video in enumerate(videos): if i >= (len(thresholds)) or not thresholds[i]: continue try: os.makedirs(video + "_up") os.makedirs(video + "_dw") except FileExistsError: continue threshold = int(thresholds[i]) iup_region = f"iw:{threshold + overlap}:0:0" idw_region = f"iw:ih-{threshold + overlap}:0:{threshold - overlap}" # crop target background single image cmd = ( f"ffmpeg -y -i \"{video+'.png'}\" " f'-filter:v \"crop={iup_region}\" ' f"\"{video+'_up.png'}\"" " > split_logs.txt 2>&1" ) code = os.system( cmd ) if code != 0: exit(code) code = os.system( f"ffmpeg -y -i \"{video+'.png'}\" " f'-filter:v "crop={idw_region}" ' f"\"{video+'_dw.png'}\"" " > split_logs.txt 2>&1" ) if code != 0: exit(code) # crop color images cmd=( f"ffmpeg -i \"{os.path.join(video, '%04d_img.png')}\" " f'-filter:v "crop={iup_region}" ' f"\"{os.path.join(video+'_up', '%04d_img.png')}\"" " > split_logs.txt 2>&1" ) code = os.system( cmd ) if code != 0: exit(code) code = os.system( f"ffmpeg -i \"{os.path.join(video, '%04d_img.png')}\" " f'-filter:v "crop={idw_region}" ' f"\"{os.path.join(video+'_dw', '%04d_img.png')}\"" " > split_logs.txt 2>&1" ) if code != 0: exit(code) # crop mask images code = os.system( f"ffmpeg -i \"{os.path.join(video, '%04d')}{mask_suffix}.png\" " f'-filter:v "crop={iup_region}" ' f"\"{os.path.join(video+'_up', '%04d')}{mask_suffix}.png\"" " > split_logs.txt 2>&1" ) if code != 0: exit(code) code = os.system( f"ffmpeg -i \"{os.path.join(video, '%04d')}{mask_suffix}.png\" " f'-filter:v "crop={idw_region}" ' f"\"{os.path.join(video+'_dw', '%04d')}{mask_suffix}.png\"" " > split_logs.txt 2>&1" ) if code != 0: exit(code) print(f" Splitted {video} ({i+1}/{len(videos)})") def fixed_merge(videos, factors, output_dir, suffix, outputs_list, overlap=0): print(f"Reconstructing {len(videos)} output images") for i, video in enumerate(videos): if i < (len(factors)) and factors[i]: # video split, merging out_path = os.path.join(output_dir, os.path.basename(video)).replace( "\\", "/" ) try: os.makedirs(out_path + suffix) except FileExistsError: continue outpup = (out_path + "_up" + suffix).replace("\\", "/") outpdw = (out_path + "_dw" + suffix).replace("\\", "/") for o in outputs_list: code = os.system( f"ffmpeg -i \"{outpup}/%04d_{o}.png\" -i \"{outpdw}/%04d_{o}.png\" " f'-filter_complex "[0:0]crop=iw:ih-{overlap}:0:0[v0];' f"[1:0]crop=iw:ih-{overlap}:0:{overlap}[v1];" f'[v0][v1]vstack" ' f"\"{out_path + suffix}/%04d_{o}.png\" -hide_banner" " > merge_logs.txt" ) if code != 0: exit(code) print(f" Merged {video} ({i+1}/{len(videos)})")
[((157, 194), 'os.path.join', 'os.path.join', (['background_path', 'f[:-4]'], {}), '(background_path, f[:-4])\n', (169, 194), False, 'import os\n'), ((1089, 1103), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (1098, 1103), False, 'import os\n'), ((2253, 2267), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2262, 2267), False, 'import os\n'), ((2350, 2483), 'os.system', 'os.system', (['f"""ffmpeg -y -i "{video + \'.png\'}" -filter:v "crop={idw_region}" "{video + \'_dw.png\'}" > split_logs.txt 2>&1"""'], {}), '(\n f\'ffmpeg -y -i "{video + \\\'.png\\\'}" -filter:v "crop={idw_region}" "{video + \\\'_dw.png\\\'}" > split_logs.txt 2>&1\'\n )\n', (2359, 2483), False, 'import os\n'), ((2867, 2881), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2876, 2881), False, 'import os\n'), ((204, 231), 'os.listdir', 'os.listdir', (['background_path'], {}), '(background_path)\n', (214, 231), False, 'import os\n'), ((508, 539), 'os.makedirs', 'os.makedirs', (["(background + '_up')"], {}), "(background + '_up')\n", (519, 539), False, 'import os\n'), ((552, 583), 'os.makedirs', 'os.makedirs', (["(background + '_dw')"], {}), "(background + '_dw')\n", (563, 583), False, 'import os\n'), ((1707, 1733), 'os.makedirs', 'os.makedirs', (["(video + '_up')"], {}), "(video + '_up')\n", (1718, 1733), False, 'import os\n'), ((1746, 1772), 'os.makedirs', 'os.makedirs', (["(video + '_dw')"], {}), "(video + '_dw')\n", (1757, 1772), False, 'import os\n'), ((856, 896), 'os.path.join', 'os.path.join', (['background', '"""%04d_img.png"""'], {}), "(background, '%04d_img.png')\n", (868, 896), False, 'import os\n'), ((842, 890), 'os.path.join', 'os.path.join', (["(background + '_up')", '"""%04d_img.png"""'], {}), "(background + '_up', '%04d_img.png')\n", (854, 890), False, 'import os\n'), ((2655, 2690), 'os.path.join', 'os.path.join', (['video', '"""%04d_img.png"""'], {}), "(video, '%04d_img.png')\n", (2667, 2690), False, 'import os\n'), ((2641, 2684), 'os.path.join', 'os.path.join', (["(video + '_up')", '"""%04d_img.png"""'], {}), "(video + '_up', '%04d_img.png')\n", (2653, 2684), False, 'import os\n'), ((4371, 4401), 'os.makedirs', 'os.makedirs', (['(out_path + suffix)'], {}), '(out_path + suffix)\n', (4382, 4401), False, 'import os\n'), ((4659, 4917), 'os.system', 'os.system', (['f"""ffmpeg -i "{outpup}/%04d_{o}.png" -i "{outpdw}/%04d_{o}.png" -filter_complex "[0:0]crop=iw:ih-{overlap}:0:0[v0];[1:0]crop=iw:ih-{overlap}:0:{overlap}[v1];[v0][v1]vstack" "{out_path + suffix}/%04d_{o}.png" -hide_banner > merge_logs.txt"""'], {}), '(\n f\'ffmpeg -i "{outpup}/%04d_{o}.png" -i "{outpdw}/%04d_{o}.png" -filter_complex "[0:0]crop=iw:ih-{overlap}:0:0[v0];[1:0]crop=iw:ih-{overlap}:0:{overlap}[v1];[v0][v1]vstack" "{out_path + suffix}/%04d_{o}.png" -hide_banner > merge_logs.txt\'\n )\n', (4668, 4917), False, 'import os\n'), ((1224, 1264), 'os.path.join', 'os.path.join', (['background', '"""%04d_img.png"""'], {}), "(background, '%04d_img.png')\n", (1236, 1264), False, 'import os\n'), ((1210, 1258), 'os.path.join', 'os.path.join', (["(background + '_dw')", '"""%04d_img.png"""'], {}), "(background + '_dw', '%04d_img.png')\n", (1222, 1258), False, 'import os\n'), ((3002, 3037), 'os.path.join', 'os.path.join', (['video', '"""%04d_img.png"""'], {}), "(video, '%04d_img.png')\n", (3014, 3037), False, 'import os\n'), ((2988, 3031), 'os.path.join', 'os.path.join', (["(video + '_dw')", '"""%04d_img.png"""'], {}), "(video + '_dw', '%04d_img.png')\n", (3000, 3031), False, 'import os\n'), ((3325, 3352), 'os.path.join', 'os.path.join', (['video', '"""%04d"""'], {}), "(video, '%04d')\n", (3337, 3352), False, 'import os\n'), ((3311, 3346), 'os.path.join', 'os.path.join', (["(video + '_up')", '"""%04d"""'], {}), "(video + '_up', '%04d')\n", (3323, 3346), False, 'import os\n'), ((3638, 3665), 'os.path.join', 'os.path.join', (['video', '"""%04d"""'], {}), "(video, '%04d')\n", (3650, 3665), False, 'import os\n'), ((3624, 3659), 'os.path.join', 'os.path.join', (["(video + '_dw')", '"""%04d"""'], {}), "(video + '_dw', '%04d')\n", (3636, 3659), False, 'import os\n'), ((4263, 4286), 'os.path.basename', 'os.path.basename', (['video'], {}), '(video)\n', (4279, 4286), False, 'import os\n')]
veredsil/hn2016_falwa
hn2016_falwa/utilities.py
53035ac838860dd8a8d85619f16cc9785dee8655
import numpy as np from math import pi,exp def static_stability(height,area,theta,s_et=None,n_et=None): """ The function "static_stability" computes the vertical gradient (z-derivative) of hemispheric-averaged potential temperature, i.e. d\tilde{theta}/dz in the def- inition of QGPV in eq.(3) of Huang and Nakamura (2016), by central differencing. At the boundary, the static stability is estimated by forward/backward differen- cing involving two adjacent z-grid points: i.e. stat_n[0] = (t0_n[1]-t0_n[0])/(height[1]-height[0]) stat_n[-1] = (t0_n[-2]-t0_n[-1])/(height[-2]-height[-1]) Please make inquiries and report issues via Github: https://github.com/csyhuang/hn2016_falwa/issues Parameters ---------- height : sequence or array_like Array of z-coordinate [in meters] with dimension = (kmax), equally spaced area : ndarray Two-dimension numpy array specifying differential areal element of each grid point; dimension = (nlat, nlon). theta : ndarray Matrix of potential temperature [K] with dimension (kmax,nlat,nlon) or (kmax,nlat) s_et : int, optional Index of the latitude that defines the boundary of the Southern hemispheric domain; initialized as nlat/2 if not input n_et : int, optional Index of the latitude that defines the boundary of the Southern hemispheric domain; initialized as nlat/2 if not input Returns ------- t0_n : sequence or array_like Area-weighted average of potential temperature (\tilde{\theta} in HN16) in the Northern hemispheric domain with dimension = (kmax) t0_s : sequence or array_like Area-weighted average of potential temperature (\tilde{\theta} in HN16) in the Southern hemispheric domain with dimension = (kmax) stat_n : sequence or array_like Static stability (d\tilde{\theta}/dz in HN16) in the Northern hemispheric domain with dimension = (kmax) stat_s : sequence or array_like Static stability (d\tilde{\theta}/dz in HN16) in the Southern hemispheric domain with dimension = (kmax) """ nlat = theta.shape[1] if s_et==None: s_et = nlat//2 if n_et==None: n_et = nlat//2 stat_n = np.zeros(theta.shape[0]) stat_s = np.zeros(theta.shape[0]) if theta.ndim==3: zonal_mean = np.mean(theta,axis=-1) elif theta.ndim==2: zonal_mean = theta if area.ndim==2: area_zonal_mean = np.mean(area,axis=-1) elif area.ndim==1: area_zonal_mean = area csm_n_et = np.sum(area_zonal_mean[-n_et:]) csm_s_et = np.sum(area_zonal_mean[:s_et]) t0_n = np.sum(zonal_mean[:,-n_et:]*area_zonal_mean[np.newaxis,-n_et:],axis=-1)/csm_n_et t0_s = np.sum(zonal_mean[:,:s_et]*area_zonal_mean[np.newaxis,:s_et],axis=-1)/csm_s_et stat_n[1:-1] = (t0_n[2:]-t0_n[:-2])/(height[2:]-height[:-2]) stat_s[1:-1] = (t0_s[2:]-t0_s[:-2])/(height[2:]-height[:-2]) stat_n[0] = (t0_n[1]-t0_n[0])/(height[1]-height[0]) stat_n[-1] = (t0_n[-2]-t0_n[-1])/(height[-2]-height[-1]) stat_s[0] = (t0_s[1]-t0_s[0])/(height[1]-height[0]) stat_s[-1] = (t0_s[-2]-t0_s[-1])/(height[-2]-height[-1]) return t0_n,t0_s,stat_n,stat_s def compute_qgpv_givenvort(omega,nlat,nlon,kmax,unih,ylat,avort,potential_temp, t0_cn,t0_cs,stat_cn,stat_cs,nlat_s=None,scale_height=7000.): """ The function "compute_qgpv_givenvort" computes the quasi-geostrophic potential vorticity based on the absolute vorticity, potential temperature and static stability given. Please make inquiries and report issues via Github: https://github.com/csyhuang/hn2016_falwa/issues Parameters ---------- omega : float, optional Rotation rate of the planet. nlat : int Latitudinal dimension of the latitude grid. nlon : int Longitudinal dimension of the longitude grid. kmax : int Vertical dimension of the height grid. unih : sequence or array_like Numpy array of height in [meters]; dimension = (kmax) ylat : sequence or array_like Numpy array of latitudes in [degrees]; dimension = (nlat) avort : ndarray Three-dimension numpy array of absolute vorticity (i.e. relative vorticity + 2*Omega*sin(lat)) in [1/s]; dimension = (kmax x nlat x nlon) potential_temp : ndarray Three-dimension numpy array of potential temperature in [K]; dimension = (kmax x nlat x nlon) t0_cn : sequence or array_like Area-weighted average of potential temperature (\tilde{\theta} in HN16) in the Northern hemispheric domain with dimension = (kmax) t0_cs : sequence or array_like Area-weighted average of potential temperature (\tilde{\theta} in HN16) in the Southern hemispheric domain with dimension = (kmax) stat_cn : sequence or array_like Static stability (d\tilde{\theta}/dz in HN16) in the Northern hemispheric domain with dimension = (kmax) stat_cs : sequence or array_like Static stability (d\tilde{\theta}/dz in HN16) in the Southern hemispheric domain with dimension = (kmax) scale_height : float Scale height of the atmosphere in [m] with default value 7000. Returns ------- QGPV : ndarray Three-dimension numpy array of quasi-geostrophic potential vorticity; dimension = (kmax x nlat x nlon) dzdiv : ndarray Three-dimension numpy array of the stretching term in QGPV; dimension = (kmax x nlat x nlon) """ if nlat_s==None: nlat_s=nlat//2 clat = np.cos(ylat*pi/180.) clat = np.abs(clat) # Just to avoid the negative value at poles # --- Next, calculate PV --- av2 = np.empty_like(potential_temp) # dv/d(lon) av3 = np.empty_like(potential_temp) # du/d(lat) qgpv = np.empty_like(potential_temp) # av1+av2+av3+dzdiv av1 = np.ones((kmax,nlat,nlon)) * 2*omega*np.sin(ylat[np.newaxis,:,np.newaxis]*pi/180.) # Calculate the z-divergence term zdiv = np.empty_like(potential_temp) dzdiv = np.empty_like(potential_temp) for kk in range(kmax): # This is more efficient zdiv[kk,:nlat_s,:] = exp(-unih[kk]/scale_height)*(potential_temp[kk,:nlat_s,:]-t0_cs[kk])/stat_cs[kk] zdiv[kk,-nlat_s:,:] = exp(-unih[kk]/scale_height)*(potential_temp[kk,-nlat_s:,:]-t0_cn[kk])/stat_cn[kk] dzdiv[1:kmax-1,:,:] = np.exp(unih[1:kmax-1,np.newaxis,np.newaxis]/scale_height)* \ (zdiv[2:kmax,:,:]-zdiv[0:kmax-2,:,:]) \ /(unih[2:kmax,np.newaxis,np.newaxis]-unih[0:kmax-2,np.newaxis,np.newaxis]) dzdiv[0,:,:] = exp(unih[0]/scale_height)*(zdiv[1,:,:]-zdiv[0,:,:])/ \ (unih[1,np.newaxis,np.newaxis]-unih[0,np.newaxis,np.newaxis]) dzdiv[kmax-1,:,:] = exp(unih[kmax-1]/scale_height)*(zdiv[kmax-1,:,:]-zdiv[kmax-2,:,:])/ \ (unih[kmax-1,np.newaxis,np.newaxis]-unih[kmax-2,np.newaxis,np.newaxis]) qgpv = avort+dzdiv * av1 return qgpv, dzdiv
[((2300, 2324), 'numpy.zeros', 'np.zeros', (['theta.shape[0]'], {}), '(theta.shape[0])\n', (2308, 2324), True, 'import numpy as np\n'), ((2338, 2362), 'numpy.zeros', 'np.zeros', (['theta.shape[0]'], {}), '(theta.shape[0])\n', (2346, 2362), True, 'import numpy as np\n'), ((2621, 2652), 'numpy.sum', 'np.sum', (['area_zonal_mean[-n_et:]'], {}), '(area_zonal_mean[-n_et:])\n', (2627, 2652), True, 'import numpy as np\n'), ((2668, 2698), 'numpy.sum', 'np.sum', (['area_zonal_mean[:s_et]'], {}), '(area_zonal_mean[:s_et])\n', (2674, 2698), True, 'import numpy as np\n'), ((5689, 5714), 'numpy.cos', 'np.cos', (['(ylat * pi / 180.0)'], {}), '(ylat * pi / 180.0)\n', (5695, 5714), True, 'import numpy as np\n'), ((5721, 5733), 'numpy.abs', 'np.abs', (['clat'], {}), '(clat)\n', (5727, 5733), True, 'import numpy as np\n'), ((5822, 5851), 'numpy.empty_like', 'np.empty_like', (['potential_temp'], {}), '(potential_temp)\n', (5835, 5851), True, 'import numpy as np\n'), ((5874, 5903), 'numpy.empty_like', 'np.empty_like', (['potential_temp'], {}), '(potential_temp)\n', (5887, 5903), True, 'import numpy as np\n'), ((5927, 5956), 'numpy.empty_like', 'np.empty_like', (['potential_temp'], {}), '(potential_temp)\n', (5940, 5956), True, 'import numpy as np\n'), ((6120, 6149), 'numpy.empty_like', 'np.empty_like', (['potential_temp'], {}), '(potential_temp)\n', (6133, 6149), True, 'import numpy as np\n'), ((6162, 6191), 'numpy.empty_like', 'np.empty_like', (['potential_temp'], {}), '(potential_temp)\n', (6175, 6191), True, 'import numpy as np\n'), ((2407, 2430), 'numpy.mean', 'np.mean', (['theta'], {'axis': '(-1)'}), '(theta, axis=-1)\n', (2414, 2430), True, 'import numpy as np\n'), ((2529, 2551), 'numpy.mean', 'np.mean', (['area'], {'axis': '(-1)'}), '(area, axis=-1)\n', (2536, 2551), True, 'import numpy as np\n'), ((2711, 2789), 'numpy.sum', 'np.sum', (['(zonal_mean[:, -n_et:] * area_zonal_mean[(np.newaxis), -n_et:])'], {'axis': '(-1)'}), '(zonal_mean[:, -n_et:] * area_zonal_mean[(np.newaxis), -n_et:], axis=-1)\n', (2717, 2789), True, 'import numpy as np\n'), ((2803, 2879), 'numpy.sum', 'np.sum', (['(zonal_mean[:, :s_et] * area_zonal_mean[(np.newaxis), :s_et])'], {'axis': '(-1)'}), '(zonal_mean[:, :s_et] * area_zonal_mean[(np.newaxis), :s_et], axis=-1)\n', (2809, 2879), True, 'import numpy as np\n'), ((6024, 6080), 'numpy.sin', 'np.sin', (['(ylat[(np.newaxis), :, (np.newaxis)] * pi / 180.0)'], {}), '(ylat[(np.newaxis), :, (np.newaxis)] * pi / 180.0)\n', (6030, 6080), True, 'import numpy as np\n'), ((6493, 6560), 'numpy.exp', 'np.exp', (['(unih[1:kmax - 1, (np.newaxis), (np.newaxis)] / scale_height)'], {}), '(unih[1:kmax - 1, (np.newaxis), (np.newaxis)] / scale_height)\n', (6499, 6560), True, 'import numpy as np\n'), ((6697, 6724), 'math.exp', 'exp', (['(unih[0] / scale_height)'], {}), '(unih[0] / scale_height)\n', (6700, 6724), False, 'from math import pi, exp\n'), ((6842, 6876), 'math.exp', 'exp', (['(unih[kmax - 1] / scale_height)'], {}), '(unih[kmax - 1] / scale_height)\n', (6845, 6876), False, 'from math import pi, exp\n'), ((5988, 6015), 'numpy.ones', 'np.ones', (['(kmax, nlat, nlon)'], {}), '((kmax, nlat, nlon))\n', (5995, 6015), True, 'import numpy as np\n'), ((6273, 6302), 'math.exp', 'exp', (['(-unih[kk] / scale_height)'], {}), '(-unih[kk] / scale_height)\n', (6276, 6302), False, 'from math import pi, exp\n'), ((6384, 6413), 'math.exp', 'exp', (['(-unih[kk] / scale_height)'], {}), '(-unih[kk] / scale_height)\n', (6387, 6413), False, 'from math import pi, exp\n')]
JennyLawrance/azure-cli
src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/_params.py
cb9ca4b694110806b31803a95f9f315b2fde6410
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from argcomplete.completers import FilesCompleter from knack.arguments import CLIArgumentType from azure.cli.core.commands.parameters import (get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag) from azure.mgmt.iothub.models.iot_hub_client_enums import IotHubSku from azure.mgmt.iothubprovisioningservices.models.iot_dps_client_enums import (IotDpsSku, AllocationPolicy, AccessRightsDescription) from .custom import KeyType, SimpleAccessRights from ._validators import validate_policy_permissions from ._completers import get_device_id_completion_list hub_name_type = CLIArgumentType( completer=get_resource_name_completion_list('Microsoft.Devices/IotHubs'), help='IoT Hub name.') dps_name_type = CLIArgumentType( options_list=['--dps-name'], completer=get_resource_name_completion_list('Microsoft.Devices/ProvisioningServices'), help='IoT Provisioning Service name') def load_arguments(self, _): # pylint: disable=too-many-statements # Arguments for IoT DPS with self.argument_context('iot dps') as c: c.argument('dps_name', dps_name_type, options_list=['--name', '-n'], id_part='name') with self.argument_context('iot dps create') as c: c.argument('location', get_location_type(self.cli_ctx), help='Location of your IoT Provisioning Service. Default is the location of target resource group.') c.argument('sku', arg_type=get_enum_type(IotDpsSku), help='Pricing tier for the IoT provisioning service.') c.argument('unit', help='Units in your IoT Provisioning Service.', type=int) for subgroup in ['access-policy', 'linked-hub', 'certificate']: with self.argument_context('iot dps {}'.format(subgroup)) as c: c.argument('dps_name', options_list=['--dps-name'], id_part=None) with self.argument_context('iot dps access-policy') as c: c.argument('access_policy_name', options_list=['--access-policy-name', '--name', '-n'], help='A friendly name for DPS access policy.') with self.argument_context('iot dps access-policy create') as c: c.argument('rights', options_list=['--rights', '-r'], nargs='+', arg_type=get_enum_type(AccessRightsDescription), help='Access rights for the IoT provisioning service. Use space-separated list for multiple rights.') c.argument('primary_key', help='Primary SAS key value.') c.argument('secondary_key', help='Secondary SAS key value.') with self.argument_context('iot dps access-policy update') as c: c.argument('rights', options_list=['--rights', '-r'], nargs='+', arg_type=get_enum_type(AccessRightsDescription), help='Access rights for the IoT provisioning service. Use space-separated list for multiple rights.') c.argument('primary_key', help='Primary SAS key value.') c.argument('secondary_key', help='Secondary SAS key value.') with self.argument_context('iot dps linked-hub') as c: c.argument('linked_hub', options_list=['--linked-hub'], help='Host name of linked IoT Hub.') with self.argument_context('iot dps linked-hub create') as c: c.argument('connection_string', help='Connection string of the IoT hub.') c.argument('location', get_location_type(self.cli_ctx), help='Location of the IoT hub.') c.argument('apply_allocation_policy', help='A boolean indicating whether to apply allocation policy to the IoT hub.', arg_type=get_three_state_flag()) c.argument('allocation_weight', help='Allocation weight of the IoT hub.') with self.argument_context('iot dps linked-hub update') as c: c.argument('apply_allocation_policy', help='A boolean indicating whether to apply allocation policy to the Iot hub.', arg_type=get_three_state_flag()) c.argument('allocation_weight', help='Allocation weight of the IoT hub.') with self.argument_context('iot dps allocation-policy update') as c: c.argument('allocation_policy', options_list=['--policy', '-p'], arg_type=get_enum_type(AllocationPolicy), help='Allocation policy for the IoT provisioning service.') with self.argument_context('iot dps certificate') as c: c.argument('certificate_path', options_list=['--path', '-p'], type=file_type, completer=FilesCompleter([".cer", ".pem"]), help='The path to the file containing the certificate.') c.argument('certificate_name', options_list=['--certificate-name', '--name', '-n'], help='A friendly name for the certificate.') c.argument('etag', options_list=['--etag', '-e'], help='Entity Tag (etag) of the object.') # Arguments for IoT Hub with self.argument_context('iot') as c: c.argument('device_id', options_list=['--device-id', '-d'], help='Device Id.', completer=get_device_id_completion_list) with self.argument_context('iot hub') as c: c.argument('hub_name', hub_name_type, options_list=['--name', '-n'], id_part='name') c.argument('etag', options_list=['--etag', '-e'], help='Entity Tag (etag) of the object.') for subgroup in ['consumer-group', 'policy', 'job', 'certificate']: with self.argument_context('iot hub {}'.format(subgroup)) as c: c.argument('hub_name', options_list=['--hub-name']) with self.argument_context('iot device') as c: c.argument('hub_name', hub_name_type) with self.argument_context('iot hub certificate') as c: c.argument('certificate_path', options_list=['--path', '-p'], type=file_type, completer=FilesCompleter([".cer", ".pem"]), help='The path to the file containing the certificate.') c.argument('certificate_name', options_list=['--name', '-n'], help='A friendly name for the certificate.') with self.argument_context('iot hub consumer-group') as c: c.argument('consumer_group_name', options_list=['--name', '-n'], id_part='child_name_2', help='Event hub consumer group name.') c.argument('event_hub_name', id_part='child_name_1', help='Event hub endpoint name.') with self.argument_context('iot hub policy') as c: c.argument('policy_name', options_list=['--name', '-n'], id_part='child_name_1', help='Shared access policy name.') permission_values = ', '.join([x.value for x in SimpleAccessRights]) c.argument('permissions', nargs='*', validator=validate_policy_permissions, type=str.lower, help='Permissions of shared access policy. Use space-separated list for multiple permissions. ' 'Possible values: {}'.format(permission_values)) with self.argument_context('iot hub job') as c: c.argument('job_id', id_part='child_name_1', help='Job Id.') with self.argument_context('iot hub create') as c: c.argument('hub_name', completer=None) c.argument('location', get_location_type(self.cli_ctx), help='Location of your IoT Hub. Default is the location of target resource group.') c.argument('sku', arg_type=get_enum_type(IotHubSku), help='Pricing tier for Azure IoT Hub. Default value is F1, which is free. ' 'Note that only one free IoT hub instance is allowed in each ' 'subscription. Exception will be thrown if free instances exceed one.') c.argument('unit', help='Units in your IoT Hub.', type=int) c.argument('partition_count', help='The number of partitions for device-to-cloud messages.', type=int) with self.argument_context('iot hub show-connection-string') as c: c.argument('policy_name', help='Shared access policy to use.') c.argument('key_type', arg_type=get_enum_type(KeyType), options_list=['--key'], help='The key to use.') with self.argument_context('iot device create') as c: c.argument('device_id', completer=None) with self.argument_context('iot device create', arg_group='X.509 Certificate') as c: c.argument('x509', action='store_true', help='Use X.509 certificate for device authentication.') c.argument('primary_thumbprint', help='Primary X.509 certificate thumbprint to authenticate device.') c.argument('secondary_thumbprint', help='Secondary X.509 certificate thumbprint to authenticate device.') c.argument('valid_days', type=int, help='Number of days the generated self-signed X.509 certificate should be ' 'valid for. Default validity is 365 days.') c.argument('output_dir', help='Output directory for generated self-signed X.509 certificate. ' 'Default is current working directory.') with self.argument_context('iot device list') as c: c.argument('top', help='Maximum number of device identities to return.', type=int) with self.argument_context('iot device delete') as c: c.argument('etag', help='ETag of the target device. It is used for the purpose of optimistic ' 'concurrency. Delete operation will be performed only if the specified ' 'ETag matches the value maintained by the server, indicating that the ' 'device identity has not been modified since it was retrieved. Default ' 'value is set to wildcard character (*) to force an unconditional ' 'delete.') with self.argument_context('iot device show-connection-string') as c: c.argument('top', type=int, help='Maximum number of connection strings to return.') c.argument('key_type', arg_type=get_enum_type(KeyType), options_list=['--key'], help='The key to use.') with self.argument_context('iot device message') as c: c.argument('lock_token', help='Message lock token.') with self.argument_context('iot device message send', arg_group='Messaging') as c: c.argument('data', help='Device-to-cloud message body.') c.argument('message_id', help='Device-to-cloud message Id.') c.argument('correlation_id', help='Device-to-cloud message correlation Id.') c.argument('user_id', help='Device-to-cloud message user Id.') with self.argument_context('iot device message receive') as c: c.argument('lock_timeout', type=int, help='In case a message returned to this call, this specifies the amount of ' 'time in seconds, the message will be invisible to other receive calls.') with self.argument_context('iot device export') as c: c.argument('blob_container_uri', help='Blob Shared Access Signature URI with write access to a blob container.' 'This is used to output the status of the job and the results.') c.argument('include_keys', action='store_true', help='If set, keys are exported normally. Otherwise, keys are set to null in ' 'export output.') with self.argument_context('iot device import') as c: c.argument('input_blob_container_uri', help='Blob Shared Access Signature URI with read access to a blob container.' 'This blob contains the operations to be performed on the identity ' 'registry ') c.argument('output_blob_container_uri', help='Blob Shared Access Signature URI with write access to a blob container.' 'This is used to output the status of the job and the results.')
[((1348, 1410), 'azure.cli.core.commands.parameters.get_resource_name_completion_list', 'get_resource_name_completion_list', (['"""Microsoft.Devices/IotHubs"""'], {}), "('Microsoft.Devices/IotHubs')\n", (1381, 1410), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((1519, 1594), 'azure.cli.core.commands.parameters.get_resource_name_completion_list', 'get_resource_name_completion_list', (['"""Microsoft.Devices/ProvisioningServices"""'], {}), "('Microsoft.Devices/ProvisioningServices')\n", (1552, 1594), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((1964, 1995), 'azure.cli.core.commands.parameters.get_location_type', 'get_location_type', (['self.cli_ctx'], {}), '(self.cli_ctx)\n', (1981, 1995), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((4054, 4085), 'azure.cli.core.commands.parameters.get_location_type', 'get_location_type', (['self.cli_ctx'], {}), '(self.cli_ctx)\n', (4071, 4085), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((7837, 7868), 'azure.cli.core.commands.parameters.get_location_type', 'get_location_type', (['self.cli_ctx'], {}), '(self.cli_ctx)\n', (7854, 7868), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((2152, 2176), 'azure.cli.core.commands.parameters.get_enum_type', 'get_enum_type', (['IotDpsSku'], {}), '(IotDpsSku)\n', (2165, 2176), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((2952, 2990), 'azure.cli.core.commands.parameters.get_enum_type', 'get_enum_type', (['AccessRightsDescription'], {}), '(AccessRightsDescription)\n', (2965, 2990), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((3418, 3456), 'azure.cli.core.commands.parameters.get_enum_type', 'get_enum_type', (['AccessRightsDescription'], {}), '(AccessRightsDescription)\n', (3431, 3456), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((4312, 4334), 'azure.cli.core.commands.parameters.get_three_state_flag', 'get_three_state_flag', ([], {}), '()\n', (4332, 4334), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((4658, 4680), 'azure.cli.core.commands.parameters.get_three_state_flag', 'get_three_state_flag', ([], {}), '()\n', (4678, 4680), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((4920, 4951), 'azure.cli.core.commands.parameters.get_enum_type', 'get_enum_type', (['AllocationPolicy'], {}), '(AllocationPolicy)\n', (4933, 4951), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((5208, 5240), 'argcomplete.completers.FilesCompleter', 'FilesCompleter', (["['.cer', '.pem']"], {}), "(['.cer', '.pem'])\n", (5222, 5240), False, 'from argcomplete.completers import FilesCompleter\n'), ((6498, 6530), 'argcomplete.completers.FilesCompleter', 'FilesCompleter', (["['.cer', '.pem']"], {}), "(['.cer', '.pem'])\n", (6512, 6530), False, 'from argcomplete.completers import FilesCompleter\n'), ((8008, 8032), 'azure.cli.core.commands.parameters.get_enum_type', 'get_enum_type', (['IotHubSku'], {}), '(IotHubSku)\n', (8021, 8032), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((8674, 8696), 'azure.cli.core.commands.parameters.get_enum_type', 'get_enum_type', (['KeyType'], {}), '(KeyType)\n', (8687, 8696), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n'), ((10640, 10662), 'azure.cli.core.commands.parameters.get_enum_type', 'get_enum_type', (['KeyType'], {}), '(KeyType)\n', (10653, 10662), False, 'from azure.cli.core.commands.parameters import get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag\n')]
nhsconnect/prm-practice-migration-dashboard
metrics-calculator/tests/integration/test_s3.py
40c8760f409834d05bde4fb015aa5f8765acaa82
import boto3 import gzip from moto import mock_s3 import pytest import os from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist from tests.builders.file import build_gzip_csv @pytest.fixture(scope='function') def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ['AWS_ACCESS_KEY_ID'] = 'testing' os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing' os.environ['AWS_SECURITY_TOKEN'] = 'testing' os.environ['AWS_SESSION_TOKEN'] = 'testing' os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' @pytest.fixture(scope='function') def s3(aws_credentials): with mock_s3(): yield boto3.resource('s3', region_name='us-east-1') @mock_s3 def test_read_object_s3_returns_object_content(s3): bucket = s3.create_bucket(Bucket="test_bucket") s3_object = bucket.Object("test_object.csv.gz") gzipped_content = build_gzip_csv( header=["id", "message", "comment"], rows=[["123", "A message", "A comment"], [ "321", "Another message", "Another comment"]], ) s3_object.put( Body=gzipped_content ) expected = "id,message,comment\n123,A message,A comment\n321,Another message,Another comment" csv_stream = read_object_s3(s3, "s3://test_bucket/test_object.csv.gz") with gzip.open(csv_stream, mode="rt") as f: actual = f.read() assert actual == expected @mock_s3 def test_write_object_s3_writes_object_content(s3): s3.create_bucket(Bucket="test_bucket") json_string = b'{"fruit": "mango"}' write_object_s3(s3, "s3://test_bucket/test_object.json", json_string) s3_object_response = s3.Object("test_bucket", "test_object.json").get() assert s3_object_response["Body"].read() == json_string @mock_s3 def test_write_object_s3_writes_object_content_with_metadata(s3): s3.create_bucket(Bucket="test_bucket") json_string = b'{"fruit": "mango"}' metadata = { "start_date": "start-date", "end_date": "end-date" } write_object_s3(s3, "s3://test_bucket/test_object.json", json_string, metadata) s3_object_response = s3.Object("test_bucket", "test_object.json").get() assert s3_object_response["Metadata"] == metadata @mock_s3 def test_objects_exist_returns_true_when_all_objects_exist(s3): s3.create_bucket(Bucket="test_bucket") object_one = "object-one" object_two = "object-two" write_object_s3(s3, f"s3://test_bucket/{object_one}", 'object-one-content') write_object_s3(s3, f"s3://test_bucket/{object_two}", 'object-two-content') result = objects_exist(s3, "test_bucket", [object_one, object_two]) assert result @mock_s3 def test_objects_exist_returns_false_when_only_one_object_exists(s3): s3.create_bucket(Bucket="test_bucket") object_one = "object-one" object_two = "object-two" write_object_s3(s3, f"s3://test_bucket/{object_one}", 'object-one-content') result = objects_exist(s3, "test_bucket", [object_one, object_two]) assert not result @mock_s3 def test_objects_exist_returns_false_when_no_objects_exist(s3): s3.create_bucket(Bucket="test_bucket") object_one = "object-one" object_two = "object-two" result = objects_exist(s3, "test_bucket", [object_one, object_two]) assert not result
[((198, 230), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (212, 230), False, 'import pytest\n'), ((548, 580), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (562, 580), False, 'import pytest\n'), ((875, 1019), 'tests.builders.file.build_gzip_csv', 'build_gzip_csv', ([], {'header': "['id', 'message', 'comment']", 'rows': "[['123', 'A message', 'A comment'], ['321', 'Another message',\n 'Another comment']]"}), "(header=['id', 'message', 'comment'], rows=[['123',\n 'A message', 'A comment'], ['321', 'Another message', 'Another comment']])\n", (889, 1019), False, 'from tests.builders.file import build_gzip_csv\n'), ((1223, 1280), 'chalicelib.s3.read_object_s3', 'read_object_s3', (['s3', '"""s3://test_bucket/test_object.csv.gz"""'], {}), "(s3, 's3://test_bucket/test_object.csv.gz')\n", (1237, 1280), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((1538, 1607), 'chalicelib.s3.write_object_s3', 'write_object_s3', (['s3', '"""s3://test_bucket/test_object.json"""', 'json_string'], {}), "(s3, 's3://test_bucket/test_object.json', json_string)\n", (1553, 1607), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((2000, 2079), 'chalicelib.s3.write_object_s3', 'write_object_s3', (['s3', '"""s3://test_bucket/test_object.json"""', 'json_string', 'metadata'], {}), "(s3, 's3://test_bucket/test_object.json', json_string, metadata)\n", (2015, 2079), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((2395, 2470), 'chalicelib.s3.write_object_s3', 'write_object_s3', (['s3', 'f"""s3://test_bucket/{object_one}"""', '"""object-one-content"""'], {}), "(s3, f's3://test_bucket/{object_one}', 'object-one-content')\n", (2410, 2470), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((2475, 2550), 'chalicelib.s3.write_object_s3', 'write_object_s3', (['s3', 'f"""s3://test_bucket/{object_two}"""', '"""object-two-content"""'], {}), "(s3, f's3://test_bucket/{object_two}', 'object-two-content')\n", (2490, 2550), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((2565, 2623), 'chalicelib.s3.objects_exist', 'objects_exist', (['s3', '"""test_bucket"""', '[object_one, object_two]'], {}), "(s3, 'test_bucket', [object_one, object_two])\n", (2578, 2623), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((2833, 2908), 'chalicelib.s3.write_object_s3', 'write_object_s3', (['s3', 'f"""s3://test_bucket/{object_one}"""', '"""object-one-content"""'], {}), "(s3, f's3://test_bucket/{object_one}', 'object-one-content')\n", (2848, 2908), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((2923, 2981), 'chalicelib.s3.objects_exist', 'objects_exist', (['s3', '"""test_bucket"""', '[object_one, object_two]'], {}), "(s3, 'test_bucket', [object_one, object_two])\n", (2936, 2981), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((3198, 3256), 'chalicelib.s3.objects_exist', 'objects_exist', (['s3', '"""test_bucket"""', '[object_one, object_two]'], {}), "(s3, 'test_bucket', [object_one, object_two])\n", (3211, 3256), False, 'from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist\n'), ((615, 624), 'moto.mock_s3', 'mock_s3', ([], {}), '()\n', (622, 624), False, 'from moto import mock_s3\n'), ((1291, 1323), 'gzip.open', 'gzip.open', (['csv_stream'], {'mode': '"""rt"""'}), "(csv_stream, mode='rt')\n", (1300, 1323), False, 'import gzip\n'), ((640, 685), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {'region_name': '"""us-east-1"""'}), "('s3', region_name='us-east-1')\n", (654, 685), False, 'import boto3\n')]
kaldap/image-analogies
image_analogy/losses/patch_matcher.py
0867aedfae7dfc0d27c42805a3d07f7b9eb7eaa2
import numpy as np import scipy.interpolate import scipy.ndimage from sklearn.feature_extraction.image import extract_patches_2d, reconstruct_from_patches_2d def _calc_patch_grid_dims(shape, patch_size, patch_stride): x_w, x_h, x_c = shape num_rows = 1 + (x_h - patch_size) // patch_stride num_cols = 1 + (x_w - patch_size) // patch_stride return num_rows, num_cols def make_patch_grid(x, patch_size, patch_stride=1): '''x shape: (num_channels, rows, cols)''' x = x.transpose(2, 1, 0) patches = extract_patches_2d(x, (patch_size, patch_size)) x_w, x_h, x_c = x.shape num_rows, num_cols = _calc_patch_grid_dims(x.shape, patch_size, patch_stride) patches = patches.reshape((num_rows, num_cols, patch_size, patch_size, x_c)) patches = patches.transpose((0, 1, 4, 2, 3)) #patches = np.rollaxis(patches, -1, 2) return patches def combine_patches_grid(in_patches, out_shape): '''Reconstruct an image from these `patches` input shape: (rows, cols, channels, patch_row, patch_col) ''' num_rows, num_cols = in_patches.shape[:2] num_channels = in_patches.shape[-3] patch_size = in_patches.shape[-1] num_patches = num_rows * num_cols in_patches = np.reshape(in_patches, (num_patches, num_channels, patch_size, patch_size)) # (patches, channels, pr, pc) in_patches = np.transpose(in_patches, (0, 2, 3, 1)) # (patches, p, p, channels) recon = reconstruct_from_patches_2d(in_patches, out_shape) return recon.transpose(2, 1, 0).astype(np.float32) class PatchMatcher(object): '''A matcher of image patches inspired by the PatchMatch algorithm. image shape: (width, height, channels) ''' def __init__(self, input_shape, target_img, patch_size=1, patch_stride=1, jump_size=0.5, num_propagation_steps=5, num_random_steps=5, random_max_radius=1.0, random_scale=0.5): self.input_shape = input_shape self.patch_size = patch_size self.patch_stride = patch_stride self.jump_size = jump_size self.num_propagation_steps = num_propagation_steps self.num_random_steps = num_random_steps self.random_max_radius = random_max_radius self.random_scale = random_scale self.num_input_rows, self.num_input_cols = _calc_patch_grid_dims(input_shape, patch_size, patch_stride) self.target_patches = make_patch_grid(target_img, patch_size) self.target_patches_normed = self.normalize_patches(self.target_patches) self.coords = np.random.uniform(0.0, 1.0, # TODO: switch to pixels (2, self.num_input_rows, self.num_input_cols))# * [[[self.num_input_rows]],[[self.num_input_cols]]] self.similarity = np.zeros(input_shape[:2:-1], dtype=np.float32) self.min_propagration_row = 1.0 / self.num_input_rows self.min_propagration_col = 1.0 / self.num_input_cols self.delta_row = np.array([[[self.min_propagration_row]], [[0.0]]]) self.delta_col = np.array([[[0.0]], [[self.min_propagration_col]]]) def update(self, input_img, reverse_propagation=False): input_patches = self.get_patches_for(input_img) self.update_with_patches(self.normalize_patches(input_patches), reverse_propagation=reverse_propagation) def update_with_patches(self, input_patches, reverse_propagation=False): self._propagate(input_patches, reverse_propagation=reverse_propagation) self._random_update(input_patches) def get_patches_for(self, img): return make_patch_grid(img, self.patch_size); def normalize_patches(self, patches): norm = np.sqrt(np.sum(np.square(patches), axis=(2, 3, 4), keepdims=True)) return patches / norm def _propagate(self, input_patches, reverse_propagation=False): if reverse_propagation: roll_direction = 1 else: roll_direction = -1 sign = float(roll_direction) for step_i in range(self.num_propagation_steps): new_coords = self.clip_coords(np.roll(self.coords, roll_direction, 1) + self.delta_row * sign) coords_row, similarity_row = self.eval_state(new_coords, input_patches) new_coords = self.clip_coords(np.roll(self.coords, roll_direction, 2) + self.delta_col * sign) coords_col, similarity_col = self.eval_state(new_coords, input_patches) self.coords, self.similarity = self.take_best(coords_row, similarity_row, coords_col, similarity_col) def _random_update(self, input_patches): for alpha in range(1, self.num_random_steps + 1): # NOTE this should actually stop when the move is < 1 new_coords = self.clip_coords(self.coords + np.random.uniform(-self.random_max_radius, self.random_max_radius, self.coords.shape) * self.random_scale ** alpha) self.coords, self.similarity = self.eval_state(new_coords, input_patches) def eval_state(self, new_coords, input_patches): new_similarity = self.patch_similarity(input_patches, new_coords) delta_similarity = new_similarity - self.similarity coords = np.where(delta_similarity > 0, new_coords, self.coords) best_similarity = np.where(delta_similarity > 0, new_similarity, self.similarity) return coords, best_similarity def take_best(self, coords_a, similarity_a, coords_b, similarity_b): delta_similarity = similarity_a - similarity_b best_coords = np.where(delta_similarity > 0, coords_a, coords_b) best_similarity = np.where(delta_similarity > 0, similarity_a, similarity_b) return best_coords, best_similarity def patch_similarity(self, source, coords): '''Check the similarity of the patches specified in coords.''' target_vals = self.lookup_coords(self.target_patches_normed, coords) err = source * target_vals return np.sum(err, axis=(2, 3, 4)) def clip_coords(self, coords): # TODO: should this all be in pixel space? coords = np.clip(coords, 0.0, 1.0) return coords def lookup_coords(self, x, coords): x_shape = np.expand_dims(np.expand_dims(x.shape, -1), -1) i_coords = np.round(coords * (x_shape[:2] - 1)).astype('int32') return x[i_coords[0], i_coords[1]] def get_reconstruction(self, patches=None, combined=None): if combined is not None: patches = make_patch_grid(combined, self.patch_size) if patches is None: patches = self.target_patches patches = self.lookup_coords(patches, self.coords) recon = combine_patches_grid(patches, self.input_shape) return recon def scale(self, new_shape, new_target_img): '''Create a new matcher of the given shape and replace its state with a scaled up version of the current matcher's state. ''' new_matcher = PatchMatcher(new_shape, new_target_img, patch_size=self.patch_size, patch_stride=self.patch_stride, jump_size=self.jump_size, num_propagation_steps=self.num_propagation_steps, num_random_steps=self.num_random_steps, random_max_radius=self.random_max_radius, random_scale=self.random_scale) new_matcher.coords = congrid(self.coords, new_matcher.coords.shape, method='neighbour') new_matcher.similarity = congrid(self.similarity, new_matcher.coords.shape, method='neighbour') return new_matcher def congrid(a, newdims, method='linear', centre=False, minusone=False): '''Arbitrary resampling of source array to new dimension sizes. Currently only supports maintaining the same number of dimensions. To use 1-D arrays, first promote them to shape (x,1). Uses the same parameters and creates the same co-ordinate lookup points as IDL''s congrid routine, which apparently originally came from a VAX/VMS routine of the same name. method: neighbour - closest value from original data nearest and linear - uses n x 1-D interpolations using scipy.interpolate.interp1d (see Numerical Recipes for validity of use of n 1-D interpolations) spline - uses ndimage.map_coordinates centre: True - interpolation points are at the centres of the bins False - points are at the front edge of the bin minusone: For example- inarray.shape = (i,j) & new dimensions = (x,y) False - inarray is resampled by factors of (i/x) * (j/y) True - inarray is resampled by(i-1)/(x-1) * (j-1)/(y-1) This prevents extrapolation one element beyond bounds of input array. ''' if not a.dtype in [np.float64, np.float32]: a = np.cast[float](a) m1 = np.cast[int](minusone) ofs = np.cast[int](centre) * 0.5 old = np.array( a.shape ) ndims = len( a.shape ) if len( newdims ) != ndims: print("[congrid] dimensions error. " \ "This routine currently only support " \ "rebinning to the same number of dimensions.") return None newdims = np.asarray( newdims, dtype=float ) dimlist = [] if method == 'neighbour': for i in range( ndims ): base = np.indices(newdims)[i] dimlist.append( (old[i] - m1) / (newdims[i] - m1) \ * (base + ofs) - ofs ) cd = np.array( dimlist ).round().astype(int) newa = a[list( cd )] return newa elif method in ['nearest','linear']: # calculate new dims for i in range( ndims ): base = np.arange( newdims[i] ) dimlist.append( (old[i] - m1) / (newdims[i] - m1) \ * (base + ofs) - ofs ) # specify old dims olddims = [np.arange(i, dtype = np.float) for i in list( a.shape )] # first interpolation - for ndims = any mint = scipy.interpolate.interp1d( olddims[-1], a, kind=method ) newa = mint( dimlist[-1] ) trorder = [ndims - 1] + range( ndims - 1 ) for i in range( ndims - 2, -1, -1 ): newa = newa.transpose( trorder ) mint = scipy.interpolate.interp1d( olddims[i], newa, kind=method ) newa = mint( dimlist[i] ) if ndims > 1: # need one more transpose to return to original dimensions newa = newa.transpose( trorder ) return newa elif method in ['spline']: oslices = [ slice(0,j) for j in old ] oldcoords = np.ogrid[oslices] nslices = [ slice(0,j) for j in list(newdims) ] newcoords = np.mgrid[nslices] newcoords_dims = range(np.rank(newcoords)) #make first index last newcoords_dims.append(newcoords_dims.pop(0)) newcoords_tr = newcoords.transpose(newcoords_dims) # makes a view that affects newcoords newcoords_tr += ofs deltas = (np.asarray(old) - m1) / (newdims - m1) newcoords_tr *= deltas newcoords_tr -= ofs newa = scipy.ndimage.map_coordinates(a, newcoords) return newa else: print("Congrid error: Unrecognized interpolation type.\n", \ "Currently only \'neighbour\', \'nearest\',\'linear\',", \ "and \'spline\' are supported.") return None if __name__ == '__main__': import sys import time from scipy.misc import imsave from image_analogy.img_utils import load_image, preprocess_image, deprocess_image content_image_path, style_image_path, output_prefix = sys.argv[1:] jump_size = 1.0 num_steps = 7 patch_size = 1 patch_stride = 1 feat_chans = 512 feat_style_shape = (feat_chans, 12, 18) feat_style = np.random.uniform(0.0, 1.0, feat_style_shape) feat_in_shape = (feat_chans, 17, 10) feat_in = np.random.uniform(0.0, 1.0, feat_in_shape) matcher = PatchMatcher(feat_in_shape[::-1], feat_style, patch_size=patch_size) feat_in_normed = matcher.normalize_patches(matcher.get_patches_for(feat_in)) for i in range(num_steps): matcher.update_with_patches(feat_in_normed) r = matcher.get_reconstruction() content_img_img = load_image(content_image_path) content_n_channels, content_n_rows, content_n_cols = content_img_img.shape[::-1] content_img = preprocess_image(content_img_img, content_n_cols, content_n_rows)[0]#.transpose((2,1,0)) style_img = load_image(style_image_path) style_n_channels, style_n_rows, style_n_cols = content_img_img.shape[::-1] style_img = preprocess_image( load_image(style_image_path), style_n_cols, style_n_rows)[0]#.transpose((2,1,0)) pg = make_patch_grid(content_img, patch_size) result = combine_patches_grid(pg, content_img.shape[::-1]) outimg = deprocess_image(result, contrast_percent=0) imsave(output_prefix + '_bestre.png', outimg) # # # matcher = PatchMatcher((content_n_cols, content_n_rows, content_n_channels), style_img, patch_size=patch_size) for i in range(num_steps): start = time.time() matcher.update(content_img, reverse_propagation=bool(i % 2)) print(matcher.similarity.min(), matcher.similarity.max(), matcher.similarity.mean()) end = time.time() #print end-start start = time.time() result = matcher.get_reconstruction(patches=matcher.target_patches) print(result.shape) end = time.time() print(end-start) outimg = deprocess_image(result, contrast_percent=0) # # imsave takes (rows, cols, channels) imsave(output_prefix + '_best.png', outimg)
[((527, 574), 'sklearn.feature_extraction.image.extract_patches_2d', 'extract_patches_2d', (['x', '(patch_size, patch_size)'], {}), '(x, (patch_size, patch_size))\n', (545, 574), False, 'from sklearn.feature_extraction.image import extract_patches_2d, reconstruct_from_patches_2d\n'), ((1228, 1303), 'numpy.reshape', 'np.reshape', (['in_patches', '(num_patches, num_channels, patch_size, patch_size)'], {}), '(in_patches, (num_patches, num_channels, patch_size, patch_size))\n', (1238, 1303), True, 'import numpy as np\n'), ((1352, 1390), 'numpy.transpose', 'np.transpose', (['in_patches', '(0, 2, 3, 1)'], {}), '(in_patches, (0, 2, 3, 1))\n', (1364, 1390), True, 'import numpy as np\n'), ((1431, 1481), 'sklearn.feature_extraction.image.reconstruct_from_patches_2d', 'reconstruct_from_patches_2d', (['in_patches', 'out_shape'], {}), '(in_patches, out_shape)\n', (1458, 1481), False, 'from sklearn.feature_extraction.image import extract_patches_2d, reconstruct_from_patches_2d\n'), ((8773, 8790), 'numpy.array', 'np.array', (['a.shape'], {}), '(a.shape)\n', (8781, 8790), True, 'import numpy as np\n'), ((9049, 9081), 'numpy.asarray', 'np.asarray', (['newdims'], {'dtype': 'float'}), '(newdims, dtype=float)\n', (9059, 9081), True, 'import numpy as np\n'), ((11676, 11721), 'numpy.random.uniform', 'np.random.uniform', (['(0.0)', '(1.0)', 'feat_style_shape'], {}), '(0.0, 1.0, feat_style_shape)\n', (11693, 11721), True, 'import numpy as np\n'), ((11777, 11819), 'numpy.random.uniform', 'np.random.uniform', (['(0.0)', '(1.0)', 'feat_in_shape'], {}), '(0.0, 1.0, feat_in_shape)\n', (11794, 11819), True, 'import numpy as np\n'), ((12127, 12157), 'image_analogy.img_utils.load_image', 'load_image', (['content_image_path'], {}), '(content_image_path)\n', (12137, 12157), False, 'from image_analogy.img_utils import load_image, preprocess_image, deprocess_image\n'), ((12366, 12394), 'image_analogy.img_utils.load_image', 'load_image', (['style_image_path'], {}), '(style_image_path)\n', (12376, 12394), False, 'from image_analogy.img_utils import load_image, preprocess_image, deprocess_image\n'), ((12724, 12767), 'image_analogy.img_utils.deprocess_image', 'deprocess_image', (['result'], {'contrast_percent': '(0)'}), '(result, contrast_percent=0)\n', (12739, 12767), False, 'from image_analogy.img_utils import load_image, preprocess_image, deprocess_image\n'), ((12772, 12817), 'scipy.misc.imsave', 'imsave', (["(output_prefix + '_bestre.png')", 'outimg'], {}), "(output_prefix + '_bestre.png', outimg)\n", (12778, 12817), False, 'from scipy.misc import imsave\n'), ((13228, 13239), 'time.time', 'time.time', ([], {}), '()\n', (13237, 13239), False, 'import time\n'), ((13346, 13357), 'time.time', 'time.time', ([], {}), '()\n', (13355, 13357), False, 'import time\n'), ((13392, 13435), 'image_analogy.img_utils.deprocess_image', 'deprocess_image', (['result'], {'contrast_percent': '(0)'}), '(result, contrast_percent=0)\n', (13407, 13435), False, 'from image_analogy.img_utils import load_image, preprocess_image, deprocess_image\n'), ((13484, 13527), 'scipy.misc.imsave', 'imsave', (["(output_prefix + '_best.png')", 'outimg'], {}), "(output_prefix + '_best.png', outimg)\n", (13490, 13527), False, 'from scipy.misc import imsave\n'), ((2520, 2594), 'numpy.random.uniform', 'np.random.uniform', (['(0.0)', '(1.0)', '(2, self.num_input_rows, self.num_input_cols)'], {}), '(0.0, 1.0, (2, self.num_input_rows, self.num_input_cols))\n', (2537, 2594), True, 'import numpy as np\n'), ((2712, 2758), 'numpy.zeros', 'np.zeros', (['input_shape[:2:-1]'], {'dtype': 'np.float32'}), '(input_shape[:2:-1], dtype=np.float32)\n', (2720, 2758), True, 'import numpy as np\n'), ((2908, 2958), 'numpy.array', 'np.array', (['[[[self.min_propagration_row]], [[0.0]]]'], {}), '([[[self.min_propagration_row]], [[0.0]]])\n', (2916, 2958), True, 'import numpy as np\n'), ((2984, 3034), 'numpy.array', 'np.array', (['[[[0.0]], [[self.min_propagration_col]]]'], {}), '([[[0.0]], [[self.min_propagration_col]]])\n', (2992, 3034), True, 'import numpy as np\n'), ((5102, 5157), 'numpy.where', 'np.where', (['(delta_similarity > 0)', 'new_coords', 'self.coords'], {}), '(delta_similarity > 0, new_coords, self.coords)\n', (5110, 5157), True, 'import numpy as np\n'), ((5184, 5247), 'numpy.where', 'np.where', (['(delta_similarity > 0)', 'new_similarity', 'self.similarity'], {}), '(delta_similarity > 0, new_similarity, self.similarity)\n', (5192, 5247), True, 'import numpy as np\n'), ((5438, 5488), 'numpy.where', 'np.where', (['(delta_similarity > 0)', 'coords_a', 'coords_b'], {}), '(delta_similarity > 0, coords_a, coords_b)\n', (5446, 5488), True, 'import numpy as np\n'), ((5515, 5573), 'numpy.where', 'np.where', (['(delta_similarity > 0)', 'similarity_a', 'similarity_b'], {}), '(delta_similarity > 0, similarity_a, similarity_b)\n', (5523, 5573), True, 'import numpy as np\n'), ((5865, 5892), 'numpy.sum', 'np.sum', (['err'], {'axis': '(2, 3, 4)'}), '(err, axis=(2, 3, 4))\n', (5871, 5892), True, 'import numpy as np\n'), ((5997, 6022), 'numpy.clip', 'np.clip', (['coords', '(0.0)', '(1.0)'], {}), '(coords, 0.0, 1.0)\n', (6004, 6022), True, 'import numpy as np\n'), ((12261, 12326), 'image_analogy.img_utils.preprocess_image', 'preprocess_image', (['content_img_img', 'content_n_cols', 'content_n_rows'], {}), '(content_img_img, content_n_cols, content_n_rows)\n', (12277, 12326), False, 'from image_analogy.img_utils import load_image, preprocess_image, deprocess_image\n'), ((12991, 13002), 'time.time', 'time.time', ([], {}), '()\n', (13000, 13002), False, 'import time\n'), ((13179, 13190), 'time.time', 'time.time', ([], {}), '()\n', (13188, 13190), False, 'import time\n'), ((6119, 6146), 'numpy.expand_dims', 'np.expand_dims', (['x.shape', '(-1)'], {}), '(x.shape, -1)\n', (6133, 6146), True, 'import numpy as np\n'), ((12517, 12545), 'image_analogy.img_utils.load_image', 'load_image', (['style_image_path'], {}), '(style_image_path)\n', (12527, 12545), False, 'from image_analogy.img_utils import load_image, preprocess_image, deprocess_image\n'), ((3630, 3648), 'numpy.square', 'np.square', (['patches'], {}), '(patches)\n', (3639, 3648), True, 'import numpy as np\n'), ((6171, 6207), 'numpy.round', 'np.round', (['(coords * (x_shape[:2] - 1))'], {}), '(coords * (x_shape[:2] - 1))\n', (6179, 6207), True, 'import numpy as np\n'), ((9184, 9203), 'numpy.indices', 'np.indices', (['newdims'], {}), '(newdims)\n', (9194, 9203), True, 'import numpy as np\n'), ((9547, 9568), 'numpy.arange', 'np.arange', (['newdims[i]'], {}), '(newdims[i])\n', (9556, 9568), True, 'import numpy as np\n'), ((9732, 9760), 'numpy.arange', 'np.arange', (['i'], {'dtype': 'np.float'}), '(i, dtype=np.float)\n', (9741, 9760), True, 'import numpy as np\n'), ((4026, 4065), 'numpy.roll', 'np.roll', (['self.coords', 'roll_direction', '(1)'], {}), '(self.coords, roll_direction, 1)\n', (4033, 4065), True, 'import numpy as np\n'), ((4217, 4256), 'numpy.roll', 'np.roll', (['self.coords', 'roll_direction', '(2)'], {}), '(self.coords, roll_direction, 2)\n', (4224, 4256), True, 'import numpy as np\n'), ((10607, 10625), 'numpy.rank', 'np.rank', (['newcoords'], {}), '(newcoords)\n', (10614, 10625), True, 'import numpy as np\n'), ((4695, 4785), 'numpy.random.uniform', 'np.random.uniform', (['(-self.random_max_radius)', 'self.random_max_radius', 'self.coords.shape'], {}), '(-self.random_max_radius, self.random_max_radius, self.\n coords.shape)\n', (4712, 4785), True, 'import numpy as np\n'), ((9335, 9352), 'numpy.array', 'np.array', (['dimlist'], {}), '(dimlist)\n', (9343, 9352), True, 'import numpy as np\n'), ((10864, 10879), 'numpy.asarray', 'np.asarray', (['old'], {}), '(old)\n', (10874, 10879), True, 'import numpy as np\n')]
desafinadude/muni-portal-backend
muni_portal/core/migrations/0030_remove_servicerequest_mobile_reference.py
9ffc447194b8f29619585cd919f67d62062457a3
# Generated by Django 2.2.10 on 2021-02-24 09:42 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0029_auto_20210224_0936'), ] operations = [ migrations.RemoveField( model_name='servicerequest', name='mobile_reference', ), ]
[((225, 301), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""servicerequest"""', 'name': '"""mobile_reference"""'}), "(model_name='servicerequest', name='mobile_reference')\n", (247, 301), False, 'from django.db import migrations\n')]
noahshpak/ray
rllib/agents/ppo/tests/test_appo.py
edd783bc327760a4892ab89222ee551e42df15b9
import unittest import ray import ray.rllib.agents.ppo as ppo from ray.rllib.utils.test_utils import check_compute_single_action, \ framework_iterator class TestAPPO(unittest.TestCase): @classmethod def setUpClass(cls): ray.init() @classmethod def tearDownClass(cls): ray.shutdown() def test_appo_compilation(self): """Test whether an APPOTrainer can be built with both frameworks.""" config = ppo.appo.DEFAULT_CONFIG.copy() config["num_workers"] = 1 num_iterations = 2 for _ in framework_iterator(config, frameworks=("torch", "tf")): _config = config.copy() trainer = ppo.APPOTrainer(config=_config, env="CartPole-v0") for i in range(num_iterations): print(trainer.train()) check_compute_single_action(trainer) _config = config.copy() _config["vtrace"] = True trainer = ppo.APPOTrainer(config=_config, env="CartPole-v0") for i in range(num_iterations): print(trainer.train()) check_compute_single_action(trainer) if __name__ == "__main__": import pytest import sys sys.exit(pytest.main(["-v", __file__]))
[((243, 253), 'ray.init', 'ray.init', ([], {}), '()\n', (251, 253), False, 'import ray\n'), ((308, 322), 'ray.shutdown', 'ray.shutdown', ([], {}), '()\n', (320, 322), False, 'import ray\n'), ((455, 485), 'ray.rllib.agents.ppo.appo.DEFAULT_CONFIG.copy', 'ppo.appo.DEFAULT_CONFIG.copy', ([], {}), '()\n', (483, 485), True, 'import ray.rllib.agents.ppo as ppo\n'), ((565, 619), 'ray.rllib.utils.test_utils.framework_iterator', 'framework_iterator', (['config'], {'frameworks': "('torch', 'tf')"}), "(config, frameworks=('torch', 'tf'))\n", (583, 619), False, 'from ray.rllib.utils.test_utils import check_compute_single_action, framework_iterator\n'), ((1216, 1245), 'pytest.main', 'pytest.main', (["['-v', __file__]"], {}), "(['-v', __file__])\n", (1227, 1245), False, 'import pytest\n'), ((679, 729), 'ray.rllib.agents.ppo.APPOTrainer', 'ppo.APPOTrainer', ([], {'config': '_config', 'env': '"""CartPole-v0"""'}), "(config=_config, env='CartPole-v0')\n", (694, 729), True, 'import ray.rllib.agents.ppo as ppo\n'), ((825, 861), 'ray.rllib.utils.test_utils.check_compute_single_action', 'check_compute_single_action', (['trainer'], {}), '(trainer)\n', (852, 861), False, 'from ray.rllib.utils.test_utils import check_compute_single_action, framework_iterator\n'), ((958, 1008), 'ray.rllib.agents.ppo.APPOTrainer', 'ppo.APPOTrainer', ([], {'config': '_config', 'env': '"""CartPole-v0"""'}), "(config=_config, env='CartPole-v0')\n", (973, 1008), True, 'import ray.rllib.agents.ppo as ppo\n'), ((1104, 1140), 'ray.rllib.utils.test_utils.check_compute_single_action', 'check_compute_single_action', (['trainer'], {}), '(trainer)\n', (1131, 1140), False, 'from ray.rllib.utils.test_utils import check_compute_single_action, framework_iterator\n')]