content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import logging from queue import Queue from threading import Thread from time import time logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) if __name__ == '__main__': main()
[ 11748, 18931, 198, 6738, 16834, 1330, 4670, 518, 198, 6738, 4704, 278, 1330, 14122, 198, 6738, 640, 1330, 640, 198, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 10778, 11, 5794, 11639, 4, 7, 292, 310, 524, 8, 82, ...
2.795918
98
#!/usr/bin/env python import saml2 from saml2 import SamlBase from saml2.xmldsig import KeyInfo NAMESPACE = 'urn:net:eustix:names:tc:PEFIM:0.0:assertion' ELEMENT_FROM_STRING = { SPCertEnc.c_tag: spcertenc_from_string, SPCertEncType_.c_tag: spcertenc_type__from_string, } ELEMENT_BY_TAG = { 'SPCertEnc': SPCertEnc, 'SPCertEncType': SPCertEncType_, }
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 6072, 75, 17, 198, 6738, 6072, 75, 17, 1330, 3409, 75, 14881, 198, 6738, 6072, 75, 17, 13, 87, 76, 335, 82, 328, 1330, 7383, 12360, 198, 198, 45, 29559, 47, 11598, 796,...
2.137143
175
# Generated by Django 2.2.4 on 2019-08-24 06:02 from django.db import connection as con, migrations from psycopg2 import sql
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 19, 319, 13130, 12, 2919, 12, 1731, 9130, 25, 2999, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4637, 355, 369, 11, 15720, 602, 198, 6738, 17331, 22163, 70, 17, 1330, 44161, 628, 198 ]
2.976744
43
#!/usr/bin/env python """ Read TFLOC output from stdin and write out a summary in which the nth line contains the number of sites found in the nth alignment of the input. TODO: This is very special case, should it be here? """ import sys from collections import defaultdict counts = defaultdict(int) max_index = -1 for line in sys.stdin: if line[0].isdigit(): current_index = int(line) max_index = max(current_index, max_index) elif line[0] == "'": counts[current_index] += 1 else: raise ValueError("Invalid input line " + line) for i in range(max_index + 1): print(counts.get(i, 0))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 5569, 309, 3697, 4503, 5072, 422, 14367, 259, 290, 3551, 503, 257, 10638, 287, 543, 262, 299, 400, 1627, 198, 3642, 1299, 262, 1271, 286, 5043, 1043, 287, 262, 299, ...
2.67364
239
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. import os from digits.utils import subclass, override, constants from digits.extensions.data.interface import DataIngestionInterface from .forms import DatasetForm, InferenceForm from . import utils from flask_babel import lazy_gettext as _ DATASET_TEMPLATE = "templates/dataset_template.html" INFERENCE_TEMPLATE = "templates/inference_template.html"
[ 2, 15069, 357, 66, 8, 1584, 11, 15127, 23929, 44680, 6234, 13, 220, 1439, 2489, 10395, 13, 628, 198, 11748, 28686, 198, 198, 6738, 19561, 13, 26791, 1330, 47611, 11, 20957, 11, 38491, 198, 6738, 19561, 13, 2302, 5736, 13, 7890, 13, ...
3.314961
127
import filehelper fileResult = filehelper.readfile() # ****************************************** # PART 2 - Fold plastic transparent sheet # Finish folding the transparent paper according to the instructions. The manual says the code is always eight capital letters. # What code do you use to activate the infrared thermal imaging camera system? # ****************************************** matrix = Matrix(fileResult.maxX, fileResult.maxY) matrix.fill_coords(fileResult.coords) # Perform folds for fold in fileResult.folds: print(f"performing fold {fold}") matrix = matrix.fold(fold)
[ 11748, 2393, 2978, 525, 198, 7753, 23004, 796, 2393, 2978, 525, 13, 961, 7753, 3419, 198, 198, 2, 41906, 4557, 1174, 198, 2, 16652, 362, 532, 39957, 7309, 13245, 9629, 198, 2, 32585, 29909, 262, 13245, 3348, 1864, 284, 262, 7729, 13, ...
4
149
if __name__ == '__main__': main()
[ 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.166667
18
import logging import time import requests import lxml.etree import re import os from schema import ScopedSession, SyncState logging.basicConfig( filename=os.getenv("LOG_FILE", "../logs/scan_comments.log"), format="%(asctime)s %(levelname)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.DEBUG) COMMENTS_URL = "http://govnokod.ru/comments" FAST_DELAY = 15 SLOW_DELAY = 60 FAST_TO_SLOW_STEPS = 20 logging.info("=== started ===") fast_requests = 0 while True: try: comments = fetch_latest_comments() has_updates = update_sync_states(comments) if has_updates: fast_requests = FAST_TO_SLOW_STEPS except Exception as e: logging.exception(e) fast_requests = 0 if fast_requests > 0: delay = FAST_DELAY fast_requests -= 1 else: delay = SLOW_DELAY logging.debug("Sleeping for %d seconds (%d fast requests left)...", delay, fast_requests) time.sleep(delay)
[ 11748, 18931, 198, 11748, 640, 198, 11748, 7007, 198, 11748, 300, 19875, 13, 316, 631, 198, 11748, 302, 198, 11748, 28686, 198, 6738, 32815, 1330, 1446, 19458, 36044, 11, 35908, 9012, 628, 198, 6404, 2667, 13, 35487, 16934, 7, 198, 220,...
2.299065
428
from .expert import UpstreamExpert as _UpstreamExpert def customized_upstream(*args, **kwargs): """ To enable your customized pretrained model, you only need to implement upstream/example/expert.py and leave this file as is. This file is used to register the UpstreamExpert in upstream/example/expert.py The following is a brief introduction of the registration mechanism. The s3prl/hub.py will collect all the entries registered in this file (callable variables without the underscore prefix) as a centralized upstream factory. One can pick up this upstream from the factory via 1. from s3prl.hub import customized_upstream model = customized_upstream(ckpt, model_config) 2. model = torch.hub.load( 'your_s3prl_path', 'customized_upstream', ckpt, model_config, source='local', ) Our run_downstream.py and downstream/runner.py follows the first usage """ return _UpstreamExpert(*args, **kwargs)
[ 6738, 764, 1069, 11766, 1330, 3205, 5532, 3109, 11766, 355, 4808, 4933, 5532, 3109, 11766, 628, 198, 4299, 27658, 62, 929, 5532, 46491, 22046, 11, 12429, 46265, 22046, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1675, 7139, 534...
2.967647
340
from typing import Dict from g_code_parsing.g_code_functionality_defs.g_code_functionality_def_base import ( GCodeFunctionalityDefBase, )
[ 6738, 19720, 1330, 360, 713, 198, 6738, 308, 62, 8189, 62, 79, 945, 278, 13, 70, 62, 8189, 62, 8818, 1483, 62, 4299, 82, 13, 70, 62, 8189, 62, 8818, 1483, 62, 4299, 62, 8692, 1330, 357, 198, 220, 220, 220, 402, 10669, 22203, 148...
2.803922
51
import os,sys import pandas as pd import numpy as np import subprocess from tqdm import tqdm from ras_method import ras_method import warnings warnings.filterwarnings('ignore') def est_trade_value(x,output_new,sector): """ Function to estimate the trade value between two sectors """ if (sector is not 'other1') & (sector is not 'other2'): sec_output = output_new.sum(axis=1).loc[output_new.sum(axis=1).index.get_level_values(1) == sector].reset_index() else: sec_output = output_new.sum(axis=1).loc[output_new.sum(axis=1).index.get_level_values(1) == 'IMP'].reset_index() x['gdp'] = x.gdp*min(sec_output.loc[sec_output.region==x.reg1].values[0][2],sec_output.loc[sec_output.region==x.reg2].values[0][2]) return x def estimate(table='INDEC',year=2015,print_output=False,print_progress=True): """ Function to create a province-level MRIO table, based on a national IO table. The default is the INDEC table. """ data_path = os.path.join('..','data') # load sector data sectors = list(pd.read_excel(os.path.join(data_path,'other_sources', 'industry_high_level_classification.xlsx'))['SEC_CODE'].values) # load provincial mappers reg_mapper = pd.read_excel(os.path.join(data_path,'INDEC','sh_cou_06_16.xls'),sheet_name='reg_mapper',header=None).iloc[:,:2] reg_mapper = dict(zip(reg_mapper[0],reg_mapper[1])) # load provincial data prov_data = pd.read_excel(os.path.join(data_path,'INDEC','PIB_provincial_06_17.xls'),sheet_name='VBP', skiprows=3,index_col=[0],header=[0],nrows=71) prov_data = prov_data.loc[[x.isupper() for x in prov_data.index],:] prov_data.columns = [x.replace(' ','_') for x in ['Ciudad de Buenos Aires', 'Buenos Aires', 'Catamarca', 'Cordoba', 'Corrientes', 'Chaco', 'Chubut', 'Entre Rios', 'Formosa', 'Jujuy', 'La Pampa', 'La Rioja', 'Mendoza', 'Misiones', 'Neuquen', 'Rio Negro', 'Salta', 'San Juan', 'San Luis', 'Santa Cruz', 'Santa Fe', 'Santiago del Estero', 'Tucuman', 'Tierra del Fuego', 'No distribuido', 'Total']] region_names = list(prov_data.columns)[:-2] prov_data.index = sectors+['TOTAL'] prov_data = prov_data.replace(0, 1) ### Create proxy data for first iteration sectors+['other1','other2'] # proxy level 2 proxy_reg_arg = pd.DataFrame(prov_data.iloc[-1,:24]/prov_data.iloc[-1,:24].sum()).reset_index() proxy_reg_arg['year'] = 2016 proxy_reg_arg = proxy_reg_arg[['year','index','TOTAL']] proxy_reg_arg.columns = ['year','id','gdp'] proxy_reg_arg.to_csv(os.path.join('..','mrio_downscaling','proxy_reg_arg.csv'),index=False) # proxy level 4 for iter_,sector in enumerate(sectors+['other1','other2']): if (sector is not 'other1') & (sector is not 'other2'): proxy_sector = pd.DataFrame(prov_data.iloc[iter_,:24]/prov_data.iloc[iter_,:24].sum()).reset_index() proxy_sector['year'] = 2016 proxy_sector['sector'] = 'sec{}'.format(sector) proxy_sector = proxy_sector[['year','sector','index',sector]] proxy_sector.columns = ['year','sector','region','gdp'] proxy_sector.to_csv(os.path.join('..','mrio_downscaling','proxy_sec{}.csv'.format(sector)),index=False) else: proxy_sector = pd.DataFrame(prov_data.iloc[-1,:24]/prov_data.iloc[-1,:24].sum()).reset_index() proxy_sector['year'] = 2016 proxy_sector['sector'] = sector+'1' proxy_sector = proxy_sector[['year','sector','index','TOTAL']] proxy_sector.columns = ['year','sector','region','gdp'] proxy_sector.to_csv(os.path.join('..','mrio_downscaling','proxy_{}.csv'.format(sector)),index=False) # proxy level 18 mi_index = pd.MultiIndex.from_product([sectors+['other1','other2'], region_names, sectors+['other1','other2'], region_names], names=['sec1', 'reg1','sec2','reg2']) for iter_,sector in enumerate(sectors+['other1','other2']): if (sector is not 'other1') & (sector is not 'other2'): proxy_trade = pd.DataFrame(columns=['year','gdp'],index= mi_index).reset_index() proxy_trade['year'] = 2016 proxy_trade['gdp'] = 0 proxy_trade = proxy_trade.query("reg1 != reg2") proxy_trade = proxy_trade.loc[proxy_trade.sec1 == sector] proxy_trade['sec1'] = proxy_trade.sec1.apply(change_name) proxy_trade['sec2'] = proxy_trade.sec2.apply(change_name) proxy_trade = proxy_trade[['year','sec1','reg1','sec2','reg2','gdp']] proxy_trade.columns = ['year','sector','region','sector','region','gdp'] proxy_trade.to_csv(os.path.join('..','mrio_downscaling','proxy_trade_sec{}.csv'.format(sector)),index=False) else: proxy_trade = pd.DataFrame(columns=['year','gdp'],index= mi_index).reset_index() proxy_trade['year'] = 2016 proxy_trade['gdp'] = 0 proxy_trade = proxy_trade.query("reg1 != reg2") proxy_trade = proxy_trade.loc[proxy_trade.sec1 == sector] proxy_trade['sec1'] = proxy_trade.sec1.apply(change_name) proxy_trade['sec2'] = proxy_trade.sec2.apply(change_name) proxy_trade = proxy_trade[['year','sec1','reg1','sec2','reg2','gdp']] proxy_trade.columns = ['year','sector','region','sector','region','gdp'] proxy_trade.to_csv(os.path.join('..','mrio_downscaling','proxy_trade_{}.csv'.format(sector)),index=False) """ Create first version of MRIO for Argentina, without trade """ ### save basetable for disaggregation usin the specific source: basetable = pd.read_csv(os.path.join(data_path,'national_tables','{}_{}.csv'.format(year,table)),index_col=[0]) basetable.to_csv(os.path.join('..','mrio_downscaling','basetable.csv'),header=False,index=False) ### run libmrio p = subprocess.Popen([r'..\mrio_downscaling\mrio_disaggregate', 'settings_notrade.yml'], cwd=os.path.join('..','mrio_downscaling')) p.wait() ### load data and reorder region_names_list = [item for sublist in [[x]*(len(sectors)+2) for x in region_names] for item in sublist] rows = ([x for x in sectors+['VA','IMP']])*len(region_names) cols = ([x for x in sectors+['FD','EXP']])*len(region_names) index_mi = pd.MultiIndex.from_arrays([region_names_list, rows], names=('region', 'row')) column_mi = pd.MultiIndex.from_arrays([region_names_list, cols], names=('region', 'col')) MRIO = pd.read_csv(os.path.join('..','mrio_downscaling','output1.csv'),header=None,index_col=None) MRIO.index = index_mi MRIO.columns = column_mi # create predefined index and col, which is easier to read sector_only = [x for x in sectors]*len(region_names) col_only = ['FD']*len(region_names) region_col = [item for sublist in [[x]*len(sectors) for x in region_names] for item in sublist] + \ [item for sublist in [[x]*1 for x in region_names] for item in sublist] column_mi_reorder = pd.MultiIndex.from_arrays( [region_col, sector_only+col_only], names=('region', 'col')) # sum va and imports valueA = MRIO.xs('VA', level=1, axis=0).sum(axis=0) valueA.drop('FD', level=1,axis=0,inplace=True) valueA.drop('EXP', level=1,axis=0,inplace=True) imports = MRIO.xs('IMP', level=1, axis=0).sum(axis=0) imports.drop('FD', level=1,axis=0,inplace=True) imports.drop('EXP', level=1,axis=0,inplace=True) FinalD = MRIO.xs('FD', level=1, axis=1).sum(axis=1) FinalD.drop('VA', level=1,axis=0,inplace=True) FinalD.drop('IMP', level=1,axis=0,inplace=True) Export = MRIO.xs('EXP', level=1, axis=1).sum(axis=1) Export.drop('VA', level=1,axis=0,inplace=True) Export.drop('IMP', level=1,axis=0,inplace=True) output_new = MRIO.copy() """ Balance first MRIO version """ # convert to numpy matrix X0 = MRIO.as_matrix() # get sum of rows and columns u = X0.sum(axis=1) v = X0.sum(axis=0) # and only keep T v[:(len(u)-2)] = u[:-2] # apply RAS method to rebalance the table X1 = ras_method(X0, u, v, eps=1e-5,print_out=print_output) #translate to pandas dataframe output_new = pd.DataFrame(X1) output_new.index = index_mi output_new.columns = column_mi if print_progress: print('NOTE : Balanced MRIO table without trade finished using {} data'.format(table)) """ Create second version of MRIO for Argentina, with trade """ ### Load OD matrix od_matrix_total = pd.DataFrame(pd.read_excel(os.path.join(data_path,'OD_data','province_ods.xlsx'), sheet_name='total',index_col=[0,1],usecols =[0,1,2,3,4,5,6,7])).unstack(1).fillna(0) od_matrix_total.columns.set_levels(['A','G','C','D','B','I'],level=0,inplace=True) od_matrix_total.index = od_matrix_total.index.map(reg_mapper) od_matrix_total = od_matrix_total.stack(0) od_matrix_total.columns = od_matrix_total.columns.map(reg_mapper) od_matrix_total = od_matrix_total.swaplevel(i=-2, j=-1, axis=0) od_matrix_total = od_matrix_total.loc[:, od_matrix_total.columns.notnull()] ### Create proxy data # proxy level 14 mi_index = pd.MultiIndex.from_product([sectors+['other1','other2'], region_names, region_names], names=['sec1', 'reg1','reg2']) for iter_,sector in enumerate((sectors+['other1','other2'])): if sector in ['A','G','C','D','B','I']: proxy_trade = (od_matrix_total.sum(level=1).divide(od_matrix_total.sum(level=1).sum(axis=1),axis='rows')).stack(0).reset_index() proxy_trade.columns = ['reg1','reg2','gdp'] proxy_trade['year'] = 2016 proxy_trade = proxy_trade.apply(lambda x: est_trade_value(x,output_new,sector),axis=1) proxy_trade['sec1'] = 'sec{}'.format(sector) proxy_trade = proxy_trade[['year','sec1','reg1','reg2','gdp']] proxy_trade.columns = ['year','sector','region','region','gdp'] proxy_trade.to_csv(os.path.join('..','mrio_downscaling','proxy_trade14_sec{}.csv'.format(sector)),index=False) elif (sector is not 'other1') & (sector is not 'other2') & (sector not in ['A','G','C','D','B','I']): # & (sector not in ['L','M','N','O','P']): proxy_trade = (od_matrix_total.sum(level=1).divide(od_matrix_total.sum(level=1).sum(axis=1),axis='rows')).stack(0).reset_index() #proxy_trade[0].loc[(proxy_trade.origin_province == proxy_trade.destination_province)] = 0.9 #proxy_trade[0].loc[~(proxy_trade.origin_province == proxy_trade.destination_province)] = 0.1 proxy_trade.columns = ['reg1','reg2','gdp'] proxy_trade['year'] = 2016 proxy_trade = proxy_trade.apply(lambda x: est_trade_value(x,output_new,sector),axis=1) proxy_trade['sec1'] = 'sec{}'.format(sector) proxy_trade = proxy_trade[['year','sec1','reg1','reg2','gdp']] proxy_trade.columns = ['year','sector','region','region','gdp'] proxy_trade.to_csv(os.path.join('..','mrio_downscaling','proxy_trade14_sec{}.csv'.format(sector)),index=False) else: proxy_trade = (od_matrix_total.sum(level=1).divide(od_matrix_total.sum(level=1).sum(axis=1),axis='rows')).stack(0).reset_index() proxy_trade.columns = ['reg1','reg2','gdp'] proxy_trade['year'] = 2016 proxy_trade = proxy_trade.apply(lambda x: est_trade_value(x,output_new,sector),axis=1) proxy_trade['sec1'] = sector+'1' proxy_trade = proxy_trade[['year','sec1','reg1','reg2','gdp']] proxy_trade.columns = ['year','sector','region','region','gdp'] proxy_trade.to_csv(os.path.join('..','mrio_downscaling','proxy_trade14_{}.csv'.format(sector)),index=False) # proxy level 18 mi_index = pd.MultiIndex.from_product([sectors+['other1','other2'], region_names, sectors+['other1','other2'], region_names], names=['sec1', 'reg1','sec2','reg2']) for iter_,sector in enumerate((sectors+['other1','other2'])): if (sector is not 'other1') & (sector is not 'other2'): proxy_trade = pd.DataFrame(columns=['year','gdp'],index= mi_index).reset_index() proxy_trade['year'] = 2016 proxy_trade['gdp'] = 0 proxy_trade = proxy_trade.query("reg1 != reg2") proxy_trade = proxy_trade.loc[proxy_trade.sec1 == sector] proxy_trade = proxy_trade.loc[proxy_trade.sec2.isin(['L','M','N','O','P'])] proxy_trade['sec1'] = proxy_trade.sec1.apply(change_name) proxy_trade['sec2'] = proxy_trade.sec2.apply(change_name) proxy_trade = proxy_trade.query("reg1 == reg2") proxy_trade = proxy_trade[['year','sec1','reg1','sec2','reg2','gdp']] proxy_trade.columns = ['year','sector','region','sector','region','gdp'] proxy_trade.to_csv(os.path.join('..','mrio_downscaling','proxy_trade_sec{}.csv'.format(sector)),index=False) else: proxy_trade = pd.DataFrame(columns=['year','gdp'],index= mi_index).reset_index() proxy_trade['year'] = 2016 proxy_trade['gdp'] = 0 proxy_trade = proxy_trade.query("reg1 != reg2") proxy_trade = proxy_trade.loc[proxy_trade.sec1 == sector] proxy_trade = proxy_trade.loc[proxy_trade.sec2.isin(['L','M','N','O','P'])] proxy_trade['sec1'] = proxy_trade.sec1.apply(change_name) proxy_trade['sec2'] = proxy_trade.sec2.apply(change_name) proxy_trade = proxy_trade.query("reg1 == reg2") proxy_trade = proxy_trade[['year','sec1','reg1','sec2','reg2','gdp']] proxy_trade.columns = ['year','sector','region','sector','region','gdp'] proxy_trade.to_csv(os.path.join('..','mrio_downscaling','proxy_trade_{}.csv'.format(sector)),index=False) ### run libmrio p = subprocess.Popen([r'..\mrio_downscaling\mrio_disaggregate', 'settings_trade.yml'], cwd=os.path.join('..','mrio_downscaling')) p.wait() # load data and reorder region_names_list = [item for sublist in [[x]*(len(sectors)+2) for x in region_names] for item in sublist] rows = ([x for x in sectors+['VA','IMP']])*len(region_names) cols = ([x for x in sectors+['FD','EXP']])*len(region_names) index_mi = pd.MultiIndex.from_arrays([region_names_list, rows], names=('region', 'row')) column_mi = pd.MultiIndex.from_arrays([region_names_list, cols], names=('region', 'col')) MRIO = pd.read_csv(os.path.join('..','mrio_downscaling','output2.csv'),header=None,index_col=None) MRIO.index = index_mi MRIO.columns = column_mi # create predefined index and col, which is easier to read sector_only = [x for x in sectors]*len(region_names) col_only = ['FD','EXP']*len(region_names) region_col = [item for sublist in [[x]*len(sectors) for x in region_names] for item in sublist] + \ [item for sublist in [[x]*2 for x in region_names] for item in sublist] column_mi_reorder = pd.MultiIndex.from_arrays( [region_col, sector_only+col_only], names=('region', 'col')) # sum va and imports valueA = pd.DataFrame(MRIO.loc[MRIO.index.get_level_values(1) == 'VA'].sum(axis='index')) valueA.columns = pd.MultiIndex.from_product([['Total'],['ValueA']],names=['region','row']) IMP = pd.DataFrame(MRIO.loc[MRIO.index.get_level_values(1) == 'IMP'].sum(axis='index')) IMP.columns = pd.MultiIndex.from_product([['Total'],['IMP']],names=['region','row']) output = pd.concat([MRIO.loc[~MRIO.index.get_level_values(1).isin(['FD','EXP'])]]) output = output.drop(['VA','IMP'], level=1) output = pd.concat([output,valueA.T,IMP.T]) output = output.reindex(column_mi_reorder, axis='columns') mrio_arg = ras_method(np.array(output).T,np.array(list(output.sum(axis=1))[:384]+list(output.sum(axis=0)[-48:])), np.array(list(output.sum(axis=1))[:384]+[output.loc[('Total','ValueA'),:].sum(),output.loc[('Total','IMP'),:].sum()]), eps=1e-3,print_out=print_output) mrio_argentina = pd.DataFrame(mrio_arg.T,index=output.index,columns=output.columns) mrio_argentina.to_csv(os.path.join(data_path,'MRIO','MRIO_Argentina_{}_{}.csv'.format(table,year))) if print_progress: print('NOTE : Balanced MRIO table with trade finished using {} data'.format(table)) def prepare_table_mria(table='INDEC',year='2015',print_output=True): """ Convert MRIO table to an excel file in which all elements of the table are disaggregated. """ data_path = os.path.join('..','data') # load table MRIO = pd.read_csv(os.path.join(data_path,'MRIO','MRIO_Argentina_{}_{}.csv'.format(table,year)),index_col=[0,1],header=[0,1]) Xnew = MRIO.copy() Xnew = Xnew+1e-6 # write to excel writer = pd.ExcelWriter(os.path.join(data_path,'MRIO', 'mrio_argentina_disaggregated_{}_{}.xlsx'.format(table,year))) # write T df_T = Xnew.iloc[:384, :384] df_T.columns = df_T.columns.droplevel() df_labels_T = pd.DataFrame(df_T.reset_index()[['region', 'row']]) df_T.reset_index(inplace=True, drop=True) df_T.to_excel(writer, 'T', index=False, header=False) df_labels_T.to_excel(writer, 'labels_T', index=False, header=False) # write FD df_FD = Xnew.iloc[:384, 384:].iloc[:, Xnew.iloc[:384, 384:].columns.get_level_values(1)=='FD'] df_labels_FD = pd.DataFrame(list(df_FD.columns)) df_FD.columns = df_FD.columns.droplevel() df_FD.reset_index(inplace=True, drop=True) df_FD.to_excel(writer, 'FD', index=False, header=False) df_labels_FD.to_excel(writer, 'labels_FD', index=False, header=False) # write ExpROW df_ExpROW = pd.DataFrame(Xnew.iloc[:384, 384:].iloc[:, Xnew.iloc[:384, 384:].columns.get_level_values(1)=='EXP'].sum(axis=1)) df_labels_ExpROW = pd.DataFrame(['Export']) df_ExpROW.reset_index(inplace=True, drop=True) df_ExpROW.to_excel(writer, 'ExpROW', index=False, header=False) df_labels_ExpROW.reset_index(inplace=True, drop=True) df_labels_ExpROW.columns = ['Export'] df_labels_ExpROW.to_excel(writer, 'labels_ExpROW', index=False, header=False) # write VA df_VA = pd.DataFrame(Xnew.iloc[384:, :409].T[('Total', 'ValueA')]) df_VA.columns = ['VA'] df_VA['imports'] = pd.DataFrame(Xnew.iloc[384:, :].T[('Total', 'IMP')]) df_VA.reset_index(inplace=True, drop=True) df_VA.to_excel(writer, 'VA', index=False, header=False) df_labels_VA = pd.DataFrame(['Import', 'VA']).T df_labels_VA.to_excel(writer, 'labels_VA', index=False, header=False) # save excel writer.save() if print_output: print('NOTE : MRIO table ready to use for MRIA model using {} data'.format(table)) if __name__ == "__main__": estimate(table='GTAP',year='2014',print_output=True) prepare_table_mria(table='GTAP',year='2014',print_output=True)
[ 11748, 28686, 11, 17597, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 850, 14681, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 6738, 374, 292, 62, 24396, 1330, 374, 292, 62, 24396, 198...
2.249912
8,567
from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import ( AuthenticationForm, UserCreationForm, UsernameField, ) User = get_user_model()
[ 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 357, 198, 220, 220, 220, 48191, 8479, 11, 198, 220,...
2.942857
70
from __future__ import annotations from typing import Any, Dict, Optional from boa3.model.method import Method from boa3.model.property import Property from boa3.model.type.classes.classarraytype import ClassArrayType from boa3.model.variable import Variable _Oracle = OracleType()
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 32233, 198, 198, 6738, 1489, 64, 18, 13, 19849, 13, 24396, 1330, 11789, 198, 6738, 1489, 64, 18, 13, 19849, 13, 26745, 1330, 14161, 198, 6738, ...
3.5875
80
from rest_framework.pagination import PageNumberPagination
[ 6738, 1334, 62, 30604, 13, 79, 363, 1883, 1330, 7873, 15057, 47, 363, 1883 ]
4.142857
14
import os, glob try: os.mkdir("output") except: pass wiiudir="input/wiiu" try: os.makedirs(wiiudir) print('The directories have been made.') input('Insert your textures in input/wiiu and then run the tool again to convert it.') except: pass dir = 'input/temp' try: os.makedirs(dir) except: pass try: for ckdtextures in os.listdir(wiiudir): with open(wiiudir+'/'+ckdtextures,'rb') as f: f.read(44) data = f.read() dds=open('input/temp/'+ckdtextures.replace('.tga.ckd','.gtx').replace('.png.ckd','.gtx'),'wb') dds.write(data) dds.close() except: pass try: for gtx in os.listdir(dir): print('making '+gtx.replace(".gtx","")+'...') os.system("texconv2 -i input/temp/"+gtx+" -o output/"+gtx.replace(".gtx",".dds")) except: pass filelist = glob.glob(os.path.join(dir, "*")) for f in filelist: os.remove(f) os.rmdir(dir)
[ 11748, 28686, 11, 15095, 201, 198, 201, 198, 28311, 25, 201, 198, 220, 220, 220, 28686, 13, 28015, 15908, 7203, 22915, 4943, 201, 198, 201, 198, 16341, 25, 201, 198, 220, 220, 220, 1208, 201, 198, 201, 198, 86, 4178, 463, 343, 2625,...
1.901304
537
import sys n = int(sys.stdin.readline().rstrip()) ab = map(int, sys.stdin.read().split()) ab = list(zip(ab, ab)) if __name__ == "__main__": ans = main() print(ans)
[ 11748, 25064, 201, 198, 201, 198, 77, 796, 493, 7, 17597, 13, 19282, 259, 13, 961, 1370, 22446, 81, 36311, 28955, 201, 198, 397, 796, 3975, 7, 600, 11, 25064, 13, 19282, 259, 13, 961, 22446, 35312, 28955, 201, 198, 397, 796, 1351, ...
2.125
88
# -*- coding: utf-8 -*- # ================================================================= # # Authors: Tom Kralidis <tomkralidis@gmail.com> # Angelos Tzotsos <tzotsos@gmail.com> # # Copyright (c) 2015 Tom Kralidis # Copyright (c) 2015 Angelos Tzotsos # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # ================================================================= import os import warnings def load_profiles(path, cls, profiles): ''' load CSW profiles, return dict by class name ''' aps = {} aps['plugins'] = {} aps['loaded'] = {} for prof in profiles.split(','): # fgdc, atom, dif, gm03 are supported in core # no need to specify them explicitly anymore # provide deprecation warning # https://github.com/geopython/pycsw/issues/118 if prof in ['fgdc', 'atom', 'dif', 'gm03']: warnings.warn('%s is now a core module, and does not need to be' ' specified explicitly. So you can remove %s from ' 'server.profiles' % (prof, prof)) else: modulename='%s.%s.%s' % (path.replace(os.sep, '.'), prof, prof) look_for_subclass(modulename) return aps
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 38093, 198, 2, 198, 2, 46665, 25, 4186, 509, 1373, 29207, 1279, 39532, 74, 1373, 29207, 31, 14816, 13, 785, 29, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.964191
754
#!/usr/bin/env python # Copyright 2017 The Fuchsia 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 argparse import errno import json import os import subprocess import sys import tempfile DEFAULT_DST_ROOT = '/system' DEFAULT_OUT_DIR = 'out/debug-x64' if __name__ == '__main__': sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 2177, 383, 376, 37533, 544, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, ...
3.061538
130
import logging import pytest from ocs_ci.framework.testlib import workloads, E2ETest, ignore_leftovers from ocs_ci.ocs import ocp, registry, constants from ocs_ci.framework import config from ocs_ci.ocs.exceptions import UnexpectedBehaviour logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 11748, 12972, 9288, 198, 6738, 267, 6359, 62, 979, 13, 30604, 13, 9288, 8019, 1330, 26211, 82, 11, 412, 17, 2767, 395, 11, 8856, 62, 9464, 13801, 198, 6738, 267, 6359, 62, 979, 13, 420, 82, 1330, 267, 13155, 11, ...
3.146067
89
elements = { 'em': '', 'blockquote': '<br/>' }
[ 68, 3639, 796, 1391, 198, 220, 220, 220, 705, 368, 10354, 705, 3256, 198, 220, 220, 220, 705, 9967, 22708, 10354, 705, 27, 1671, 15913, 6, 198, 92, 198 ]
1.896552
29
#!/usr/bin/env python import json import yaml my_list = [0, 1, 2, 3, 'whatever', 'hello', {'attribs': [0, 1, 2, 3, 4], 'ip_addr': '10.10.10.239'}] with open("my_file.json", "w") as f: json.dump(my_list, f) with open("my_file.yaml", "w") as f: f.write(yaml.dump(my_list, default_flow_style=False))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 33918, 198, 11748, 331, 43695, 628, 198, 1820, 62, 4868, 796, 685, 15, 11, 352, 11, 362, 11, 513, 11, 705, 39664, 3256, 705, 31373, 3256, 1391, 6, 1078, 822, 82, 10354, ...
2.136986
146
import sys n, *a = map(int, sys.stdin.read().split()) if __name__ == "__main__": main()
[ 11748, 25064, 201, 198, 201, 198, 77, 11, 1635, 64, 796, 3975, 7, 600, 11, 25064, 13, 19282, 259, 13, 961, 22446, 35312, 28955, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 201, ...
2.039216
51
# -*- coding: utf-8 -*- import logging import sys import unittest from src.util.tree_codec import encode_hashes, decode_url url = 'AAAABAMDAQQHBLMGSQj0Dc0OPA5cES0UIBRxFScWbxhWGF0YkRo4HM4c3CSqJy8o-itQLJwy0TWSNuk6UjpYOuE8LUGHRARFR0V-RZ1Ms025TeNQR' \ '1NSVcZZ81qRXz9mnmebaGVodGpDaqxq-mvbcg9yqXasfIN99YIHgseDX4PMg9uFYIhAjLGOvo8akDOQVZLBmK2a4JuKogCmV6asqH2qxKyYrKqtja' \ '3xrj6vp7c-uJO8n7zqvk_AZsT2xq7MvM9-0B_Tj9P72L3ZXtl82mLfsONq5FHqGOvu7IPsiu8O7-vwH_JF8933MvfX-Ov56PrS_Ev-Cv5U_oH-jw==' decoded = (4, 3, 3, 1, [1031, 1203, 1609, 2292, 3533, 3644, 3676, 4397, 5152, 5233, 5415, 5743, 6230, 6237, 6289, 6712, 7374, 7388, 9386, 10031, 10490, 11088, 11420, 13009, 13714, 14057, 14930, 14936, 15073, 15405, 16775, 17412, 17735, 17790, 17821, 19635, 19897, 19939, 20551, 21330, 21958, 23027, 23185, 24383, 26270, 26523, 26725, 26740, 27203, 27308, 27386, 27611, 29199, 29353, 30380, 31875, 32245, 33287, 33479, 33631, 33740, 33755, 34144, 34880, 36017, 36542, 36634, 36915, 36949, 37569, 39085, 39648, 39818, 41472, 42583, 42668, 43133, 43716, 44184, 44202, 44429, 44529, 44606, 44967, 46910, 47251, 48287, 48362, 48719, 49254, 50422, 50862, 52412, 53118, 53279, 54159, 54267, 55485, 55646, 55676, 55906, 57264, 58218, 58449, 59928, 60398, 60547, 60554, 61198, 61419, 61471, 62021, 62429, 63282, 63447, 63723, 63976, 64210, 64587, 65034, 65108, 65153, 65167]) if __name__ == '__main__': logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) unittest.main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 18931, 198, 198, 11748, 25064, 628, 198, 11748, 555, 715, 395, 198, 198, 6738, 12351, 13, 22602, 13, 21048, 62, 19815, 721, 1330, 37773, 62, 71, 7465, 11, 36899, ...
1.671329
1,144
# source http://itasuke.hatenablog.com/entry/2018/01/08/133510 import winreg newkey = winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, r'Software\__javacommons__\abc') newkey.Close() winreg.DeleteKeyEx(winreg.HKEY_CURRENT_USER, r'Software\__javacommons__\abc')
[ 2, 2723, 2638, 1378, 21416, 4649, 13, 5183, 268, 397, 6404, 13, 785, 14, 13000, 14, 7908, 14, 486, 14, 2919, 14, 1485, 2327, 940, 201, 198, 11748, 1592, 2301, 201, 198, 3605, 2539, 796, 1592, 2301, 13, 16447, 9218, 3109, 7, 5404, ...
2.381818
110
import inspect import re import textwrap import pytest import pkg_resources from .test_resources import Metadata def parametrize_test_working_set_resolve(*test_list): idlist = [] argvalues = [] for test in test_list: ( name, installed_dists, installable_dists, requirements, expected1, expected2 ) = [ strip_comments(s.lstrip()) for s in textwrap.dedent(test).lstrip().split('\n\n', 5) ] installed_dists = list(parse_distributions(installed_dists)) installable_dists = list(parse_distributions(installable_dists)) requirements = list(pkg_resources.parse_requirements(requirements)) for id_, replace_conflicting, expected in ( (name, False, expected1), (name + '_replace_conflicting', True, expected2), ): idlist.append(id_) expected = strip_comments(expected.strip()) if re.match('\w+$', expected): expected = getattr(pkg_resources, expected) assert issubclass(expected, Exception) else: expected = list(parse_distributions(expected)) argvalues.append(pytest.param(installed_dists, installable_dists, requirements, replace_conflicting, expected)) return pytest.mark.parametrize('installed_dists,installable_dists,' 'requirements,replace_conflicting,' 'resolved_dists_or_exception', argvalues, ids=idlist)
[ 11748, 10104, 198, 11748, 302, 198, 11748, 2420, 37150, 198, 198, 11748, 12972, 9288, 198, 198, 11748, 279, 10025, 62, 37540, 198, 198, 6738, 764, 9288, 62, 37540, 1330, 3395, 14706, 628, 628, 198, 4299, 5772, 316, 380, 2736, 62, 9288, ...
1.9953
851
from setuptools import find_packages, setup install_requires = [dep.strip() for dep in open('requirements.txt')] setup( name='yolo_tf2', version='1.5', packages=find_packages(), url='https://github.com/schissmantics/yolo-tf2', license='MIT', author='schismantics', author_email='schissmantics@outlook.com', description='yolo(v3/v4) implementation in keras and tensorflow 2.5', setup_requires=['numpy==1.19.5'], install_requires=install_requires, python_requires='>=3.7', entry_points={ 'console_scripts': [ 'yolotf2=yolo_tf2.cli:execute', ], }, )
[ 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 17350, 62, 47911, 796, 685, 10378, 13, 36311, 3419, 329, 1207, 287, 1280, 10786, 8897, 18883, 13, 14116, 11537, 60, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 1163...
2.355805
267
from .pspace import (PMatDense, PMatBlockDiag, PMatDiag, PMatLowRank, PMatImplicit, PMatKFAC, PMatEKFAC, PMatQuasiDiag) from .vector import (PVector, FVector) from .fspace import (FMatDense,) from .map import (PushForwardDense, PushForwardImplicit, PullBackDense)
[ 6738, 764, 862, 10223, 1330, 357, 5868, 265, 35, 1072, 11, 3122, 265, 12235, 18683, 363, 11, 3122, 265, 18683, 363, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 3122,...
2.050633
158
from abc import ABC, abstractmethod from typing import List, NewType from vkwave.bots.core.dispatching.events.base import BaseEvent MiddlewareResult = NewType("MiddlewareResult", bool)
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 19720, 1330, 7343, 11, 968, 6030, 198, 198, 6738, 410, 74, 19204, 13, 42478, 13, 7295, 13, 6381, 17147, 278, 13, 31534, 13, 8692, 1330, 7308, 9237, 198, 198, 34621, 1574, 23004, ...
3.5
54
import networkx as nx import numpy as np import matplotlib.pyplot as plt if __name__ == '__main__': adj1 = np.array([[0, 1, 1, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0]]) op1 = ['in', 'conv1x1', 'conv3x3', 'mp3x3', 'out'] adj2 = np.array([[0, 1, 1, 1, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0]]) op2 = ['in', 'conv1x1', 'mp3x3', 'conv3x3', 'out'] adj3 = np.array([[0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0]]) op3 = ['in', 'conv1x1', 'conv3x3', 'mp3x3', 'out','out2'] adj4 = np.array([[0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) op4 = np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0]]) adj4, op4 = preprocess_adj_op(adj4, op4) G1 = gen_graph(adj1, op1) G2 = gen_graph(adj2, op2) G3 = gen_graph(adj3, op3) G4 = gen_graph(adj4, op4) plt.subplot(141) nx.draw(G1, with_labels=True, font_weight='bold') plt.subplot(142) nx.draw(G2, with_labels=True, font_weight='bold') plt.subplot(143) nx.draw(G3, with_labels=True, font_weight='bold') plt.subplot(144) nx.draw(G4, with_labels=True, font_weight='bold') nx.graph_edit_distance(G1,G2, node_match=node_match, edge_match=edge_match) nx.graph_edit_distance(G2,G3, node_match=node_match, edge_match=edge_match)
[ 11748, 3127, 87, 355, 299, 87, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 628, 220, 220, 220, 9224, 16, ...
1.528919
1,314
import bitmath
[ 11748, 1643, 11018, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628, 628 ]
2.533333
15
''' LICENSE: MIT license This module can help us know about who can ask when we have troubles in some buggy codes while solving problems. ''' from asyncio import gather, get_event_loop from pandas import DataFrame, set_option from online_judge import Online_Judge loop = get_event_loop() set_option('display.max_colwidth', -1)
[ 7061, 6, 198, 43, 2149, 24290, 25, 17168, 5964, 198, 198, 1212, 8265, 460, 1037, 514, 760, 546, 508, 460, 1265, 618, 198, 732, 423, 14979, 287, 617, 46542, 12416, 981, 18120, 2761, 13, 198, 198, 7061, 6, 198, 6738, 30351, 952, 1330,...
3.363636
99
import torch import random import numpy as np import cv2 import os import torch.nn as nn from torchvision import transforms def edge_contour(label, edge_width=3): import cv2 cuda_type = label.is_cuda label = label.cpu().numpy().astype(np.int) b, h, w = label.shape edge = np.zeros(label.shape) # right edge_right = edge[:, 1:h, :] edge_right[(label[:, 1:h, :] != label[:, :h - 1, :]) & (label[:, 1:h, :] != 255) & (label[:, :h - 1, :] != 255)] = 1 # up edge_up = edge[:, :, :w - 1] edge_up[(label[:, :, :w - 1] != label[:, :, 1:w]) & (label[:, :, :w - 1] != 255) & (label[:, :, 1:w] != 255)] = 1 # upright edge_upright = edge[:, :h - 1, :w - 1] edge_upright[(label[:, :h - 1, :w - 1] != label[:, 1:h, 1:w]) & (label[:, :h - 1, :w - 1] != 255) & (label[:, 1:h, 1:w] != 255)] = 1 # bottomright edge_bottomright = edge[:, :h - 1, 1:w] edge_bottomright[(label[:, :h - 1, 1:w] != label[:, 1:h, :w - 1]) & (label[:, :h - 1, 1:w] != 255) & (label[:, 1:h, :w - 1] != 255)] = 1 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (edge_width, edge_width)) for i in range(edge.shape[0]): edge[i] = cv2.dilate(edge[i], kernel) # edge[edge == 1] = 255 # view edge # import random # cv2.imwrite(os.path.join('./edge', '{}.png'.format(random.random())), edge[0]) if cuda_type: edge = torch.from_numpy(edge).cuda() else: edge = torch.from_numpy(edge) return edge if __name__ == '__main__': path = './data/vaihingen/annotations/labels' filelist = os.listdir(path) for file in filelist: print(file) img = cv2.imread(os.path.join(path, file), cv2.IMREAD_UNCHANGED) img = torch.from_numpy(img).unsqueeze(dim=0).repeat(2, 1, 1) img = edge_contour(img) # cv2.imwrite(os.path.join(save_path, os.path.splitext(file)[0] + '.png'), gray)
[ 11748, 28034, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 28686, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 10178, 1330, 31408, 628, 628, 628, 628, 198, 4299, 5743, 62, ...
1.999013
1,013
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'staff.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 28120, 13, 9019, 6, 198, 2, 198, 2, 15622, 416, 25, 9485, 48, 83, 20, 12454, 2438, 17301, 642, 13, 1485, 1...
2.845238
84
import os import pickle import numpy as np from PIL import Image import torch from torch.utils.data import Dataset from torchvision import transforms import h5py from transforms import Scale transform = transforms.Compose([ Scale([224, 224]), transforms.Pad(4), transforms.RandomCrop([224, 224]), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) ])
[ 11748, 28686, 198, 11748, 2298, 293, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 198, 6738, 28034, 10178, 1330, 31408, 198, ...
2.598802
167
import pytest import numpy as np import pandas as pd from xgboost_distribution.distributions import LogNormal def test_loss(lognormal): loss_name, loss_value = lognormal.loss( # fmt: off y=np.array([0, ]), params=np.array([[1, 0], ]), ) assert loss_name == "LogNormalError" assert loss_value == np.inf
[ 11748, 12972, 9288, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 2124, 70, 39521, 62, 17080, 3890, 13, 17080, 2455, 507, 1330, 5972, 26447, 628, 628, 628, 198, 4299, 1332, 62, 22462, 7...
2.380952
147
#!/usr/bin/env python3 """ Main script for workload forecasting. Example usage: - Generate data (runs OLTP benchmark on the built database) and perform training, and save the trained model ./forecaster --gen_data --models=LSTM --model_save_path=model.pickle - Use the trained models (LSTM) to generate predictions. ./forecaster --model_load_path=model.pickle --test_file=test_query.csv --test_model=LSTM TODO: - Better metrics for training and prediction (currently not focusing on models' accuracy yet) - Multiple models (currently only simple-one-layer-untuned LSTM used) - API and interaction with Pilot """ import argparse import json import pickle from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import numpy as np from ..testing.self_driving.constants import (DEFAULT_ITER_NUM, DEFAULT_QUERY_TRACE_FILE, DEFAULT_TPCC_WEIGHTS, DEFAULT_WORKLOAD_PATTERN) from ..testing.self_driving.forecast import gen_oltp_trace from ..testing.util.constants import LOG from .cluster import QueryCluster from .data_loader import DataLoader from .models import ForecastModel, get_models # Interval duration for aggregation in microseconds INTERVAL_MICRO_SEC = 500000 # Number of Microseconds per second MICRO_SEC_PER_SEC = 1000000 # Number of data points in a sequence SEQ_LEN = 10 * MICRO_SEC_PER_SEC // INTERVAL_MICRO_SEC # Number of data points for the horizon HORIZON_LEN = 30 * MICRO_SEC_PER_SEC // INTERVAL_MICRO_SEC # Number of data points for testing set EVAL_DATA_SIZE = 2 * SEQ_LEN + HORIZON_LEN argp = argparse.ArgumentParser(description="Query Load Forecaster") # Generation stage related options argp.add_argument( "--gen_data", default=False, action="store_true", help="If specified, OLTP benchmark would be downloaded and built to generate the query trace data") argp.add_argument( "--tpcc_weight", type=str, default=DEFAULT_TPCC_WEIGHTS, help="Workload weights for the TPCC") argp.add_argument( "--tpcc_rates", nargs="+", default=DEFAULT_WORKLOAD_PATTERN, help="Rate array for the TPCC workload") argp.add_argument( "--pattern_iter", type=int, default=DEFAULT_ITER_NUM, help="Number of iterations the DEFAULT_WORKLOAD_PATTERN should be run") argp.add_argument("--trace_file", default=DEFAULT_QUERY_TRACE_FILE, help="Path to the query trace file", metavar="FILE") # Model specific argp.add_argument("--models", nargs='+', type=str, help="Models to use") argp.add_argument("--models_config", type=str, metavar="FILE", help="Models and init arguments JSON config file") argp.add_argument("--seq_len", type=int, default=SEQ_LEN, help="Length of one sequence in number of data points") argp.add_argument( "--horizon_len", type=int, default=HORIZON_LEN, help="Length of the horizon in number of data points, " "aka, how many further in the a sequence is used for prediction" ) # Training stage related options argp.add_argument("--model_save_path", metavar="FILE", help="Where the model trained will be stored") argp.add_argument( "--eval_size", type=int, default=EVAL_DATA_SIZE, help="Length of the evaluation data set length in number of data points") argp.add_argument("--lr", type=float, default=0.001, help="Learning rate") argp.add_argument("--epochs", type=int, default=10, help="Number of epochs for training") # Testing stage related options argp.add_argument( "--model_load_path", default="model.pickle", metavar="FILE", help="Where the model should be loaded from") argp.add_argument( "--test_file", help="Path to the test query trace file", metavar="FILE") argp.add_argument( "--test_model", type=str, help="Model to be used for forecasting" ) def parse_model_config(model_names: Optional[List[str]], models_config: Optional[str]) -> Dict: """ Load models from :param model_names: List of model names :param models_config: JSON model config file :return: Merged model config Dict """ model_kwargs = dict([(model_name, {}) for model_name in model_names]) if models_config is not None: with open(models_config, 'r') as f: custom_config = json.load(f) # Simple and non-recursive merging of options model_kwargs.update(custom_config) if len(model_kwargs) < 1: raise ValueError("At least 1 model needs to be used.") return model_kwargs if __name__ == "__main__": args = argp.parse_args() if args.test_file is None: # Parse models arguments models_kwargs = parse_model_config(args.models, args.models_config) # Generate OLTP trace file if args.gen_data: gen_oltp_trace( tpcc_weight=args.tpcc_weight, tpcc_rates=args.tpcc_rates, pattern_iter=args.pattern_iter) trace_file = DEFAULT_QUERY_TRACE_FILE else: trace_file = args.trace_file forecaster = Forecaster( trace_file=trace_file, interval_us=INTERVAL_MICRO_SEC, seq_len=args.seq_len, eval_size=args.eval_size, horizon_len=args.horizon_len) models = forecaster.train(models_kwargs) # Save the model if args.model_save_path: with open(args.model_save_path, "wb") as f: pickle.dump(models, f) else: # Do inference on a trained model with open(args.model_load_path, "rb") as f: models = pickle.load(f) forecaster = Forecaster( trace_file=args.test_file, test_mode=True, interval_us=INTERVAL_MICRO_SEC, seq_len=args.seq_len, eval_size=args.eval_size, horizon_len=args.horizon_len) # FIXME: # Assuming all the queries in the current trace file are from # the same cluster for now query_pred = forecaster.predict(0, models[0][args.test_model]) # TODO: # How are we consuming predictions? for qid, ts in query_pred.items(): LOG.info(f"[Query: {qid}] pred={ts[:10]}")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 13383, 4226, 329, 26211, 41164, 13, 198, 16281, 8748, 25, 198, 12, 2980, 378, 1366, 357, 48381, 22258, 7250, 18335, 319, 262, 3170, 6831, 8, 290, 1620, 3047, 11, 290, ...
2.416479
2,658
# No shebang line, this module is meant to be imported # # Copyright 2013 Oliver Palmer # Copyright 2014 Ambient Entertainment GmbH & Co. KG # # 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 json import dumps # test class must be loaded first from pyfarm.master.testutil import BaseTestCase BaseTestCase.build_environment() from pyfarm.master.application import get_api_blueprint from pyfarm.master.entrypoints import load_api from pyfarm.models.jobtype import JobType, JobTypeVersion code = """from pyfarm.jobtypes.core.jobtype import JobType class TestJobType(JobType): def get_command(self): return "/usr/bin/touch" def get_arguments(self): return [os.path.join( self.assignment_data["job"]["data"]["path"], "%04d" % self.assignment_data[\"tasks\"][0][\"frame\"])] """
[ 2, 1400, 673, 36668, 1627, 11, 428, 8265, 318, 4001, 284, 307, 17392, 198, 2, 198, 2, 15069, 2211, 15416, 18918, 198, 2, 15069, 1946, 12457, 1153, 11058, 402, 2022, 39, 1222, 1766, 13, 509, 38, 198, 2, 198, 2, 49962, 739, 262, 248...
3.226277
411
from copy import copy from hashlib import md5 from pickle import Pickler, MARK, DICT from types import DictionaryType from .lib import StringIO
[ 6738, 4866, 1330, 4866, 198, 6738, 12234, 8019, 1330, 45243, 20, 198, 6738, 2298, 293, 1330, 12346, 1754, 11, 39641, 11, 360, 18379, 198, 6738, 3858, 1330, 28261, 6030, 198, 6738, 764, 8019, 1330, 10903, 9399, 628, 198 ]
3.842105
38
'''Meeus: Astronomical Algorithms (2nd ed.), chapter 25''' import math from nutation_ecliptic import ecliptic from constants import AU def coordinates(jd): '''equatorial coordinates of Sun''' lon=math.radians(longitude(jd)) eps=math.radians(ecliptic(jd)) ra=math.degrees(math.atan2(math.cos(eps)*math.sin(lon),math.cos(lon))) dec=math.degrees(math.asin(math.sin(eps)*math.sin(lon))) return ra,dec def longitude(jd): '''longitude of Sun''' T=(jd-2451545)/36525. L=math.radians(280.46646+36000.76983*T+0.0003032*T**2) M=math.radians(357.52911+35999.05029*T-0.0001537*T**2) C=math.radians((1.914602-0.004817*T-0.000014*T**2)*math.sin(M)+(0.019993-0.000101*T)*math.sin(2*M)+0.000289*math.sin(3*M)) lon=L+C return math.degrees(lon) def distance(jd,km=True): '''Earth-Sun distance in km''' T=(jd-2451545)/36525. e=0.016708634-0.000042037*T-0.0000001267*T**2 M=math.radians(357.52911+35999.05029*T-0.0001537*T**2) C=math.radians((1.914602-0.004817*T-0.000014*T**2)*math.sin(M)+(0.019993-0.000101*T)*math.sin(2*M)+0.000289*math.sin(3*M)) nu=M+C R=1.000001018*(1-e**2)/(1+e*math.cos(nu)) if km: R*=AU return R
[ 7061, 6, 44, 1453, 385, 25, 25398, 22545, 978, 7727, 907, 357, 17, 358, 1225, 12179, 6843, 1679, 7061, 6, 220, 220, 220, 198, 198, 11748, 10688, 198, 198, 6738, 6701, 341, 62, 68, 565, 10257, 291, 1330, 304, 565, 10257, 291, 198, ...
1.861357
678
#!/usr/bin/python import numpy as np import cv2 from matplotlib import pyplot as plt import networkx as nx if __name__ == "__main__": image = cv2.imread('map/map.pgm', 0) rotated = rotate_image(image, -7.66) #cv2.imwrite('map/rotated.pgm', rotated) _, th = cv2.threshold(rotated, 245, 255, cv2.THRESH_BINARY) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3)) op = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel) skel = cv2.ximgproc.thinning(op) plt.figure() plt.subplot(1,3,1) plt.imshow(image, cmap='gray') plt.axis('off') plt.title('Original') plt.subplot(1,3,2) plt.imshow(rotated, cmap='gray') plt.axis('off') plt.title('Rotada') plt.subplot(1,3,3) plt.imshow(skel, cmap='gray') plt.axis('off') plt.title('Adelgazada') base = cv2.dilate(skel, None, iterations=12) path = cv2.cvtColor(base, cv2.COLOR_GRAY2RGB) corners = cv2.cornerHarris(skel,7,7,0.04) corners = cv2.dilate(corners, None) _, corners = cv2.threshold(corners,0.001,255,cv2.THRESH_BINARY) corners = np.uint8(corners) contours, _ = cv2.findContours(corners,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) path[corners>0.0]=[0,255,0] cv2.drawContours(path,contours,-1,(255,0,0),1) G = nx.Graph() points = [] for i, c in enumerate(contours): # calculate moments for each contour M = cv2.moments(c) # calculate x,y coordinate of center cX = int(round(M["m10"] / M["m00"])) cY = int(round(M["m01"] / M["m00"])) path[cY,cX]=[0,0,255] G.add_node(i, pos=(cX,cY)) points.append((cX,cY)) font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 0.4 fontColor = (0,0,255) thickness = 1 path = cv2.putText(path, str(i), (cX,cY), font, fontScale, fontColor, thickness) plt.figure() plt.subplot(1,2,1) plt.imshow(base,cmap='gray') plt.axis('off') plt.title('Imagen base') plt.subplot(1,2,2) plt.imshow(path) plt.axis('off') plt.title('Esquinas') noBlack = cv2.countNonZero(cv2.cvtColor(path,cv2.COLOR_BGR2GRAY)) for i, p1 in enumerate(points): for j, p2 in enumerate(points): if p1 == p2: continue test_img = cv2.line(path.copy(), p1, p2, (234,0,234), 1) # Recount to see if the images are the same if cv2.countNonZero(cv2.cvtColor(test_img,cv2.COLOR_BGR2GRAY)) == noBlack: # path = cv2.line(path, p1, p2, (234,0,234), 1) G.add_edge(i,j,weight=np.hypot(p1[0]-p2[0], p1[1]-p2[1])) plt.figure() nx.draw(G,with_labels=True) x_0, y_0 = [492,500] x_f = np.random.randint(487) + 277 y_f = np.random.randint(448) + 368 path[y_0+1,x_0+1] = (255,0,0) path[y_f+1,x_f+1] = (255,0,0) _, th = cv2.threshold(rotated, 245, 255, cv2.THRESH_BINARY) ero = cv2.erode(th,None,iterations=10) th = ero.copy() noBlack = cv2.countNonZero(th) for i, p in enumerate(points): test_img = cv2.line(th.copy(), (x_0,y_0), p, 234, 1) # Recount to see if the images are the same if cv2.countNonZero(test_img) == noBlack: # path = cv2.line(path, p1, p2, (234,0,234), 1) G.add_edge('p_0',i,weight=np.hypot(p[0]-x_0, y_0-p[1])) for i, p in enumerate(points): test_img = cv2.line(th.copy(), (x_f,y_f), p, 234, 1) # Recount to see if the images are the same if cv2.countNonZero(test_img) == noBlack: # path = cv2.line(path, p1, p2, (234,0,234), 1) G.add_edge('p_f',i,weight=np.hypot(p[0]-x_f, y_f-p[1])) plan = nx.shortest_path(G,'p_0','p_f') print plan for i in range(len(plan)-1): if i == 0: path = cv2.line(path, (x_0,y_0), points[plan[i+1]], (251,229,78), 1) elif i == len(plan)-2: path = cv2.line(path, points[plan[i]], (x_f,y_f), (251,229,78), 1) else: path = cv2.line(path, points[plan[i]], points[plan[i+1]], (251,229,78), 1) plt.figure() plt.imshow(ero,cmap='gray') plt.axis('off') plt.title('Imagen erosionada') plt.show()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 11748, 3127, 87, 355, 299, 87, 628, 198, 198, 361, 11593, 3672, ...
1.751868
2,543
# Assume that we execute the following assignment statements # width = 17 # height = 12.0 width = 17 height = 12.0 value_1 = width // 2 value_2 = width / 2.0 value_3 = height / 3 value_4 = 1 + 2 * 5 print(f"value_1 is {value_1} and it's type is {type(value_1)}") print(f"value_2 is {value_2} and it's type is {type(value_2)}") print(f"value_3 is {value_3} and it's type is {type(value_3)}") print(f"value_4 is {value_4} and it's type is {type(value_4)}")
[ 2, 2195, 2454, 326, 356, 12260, 262, 1708, 16237, 6299, 198, 2, 9647, 796, 1596, 198, 2, 6001, 796, 1105, 13, 15, 198, 198, 10394, 796, 1596, 198, 17015, 796, 1105, 13, 15, 198, 198, 8367, 62, 16, 796, 9647, 3373, 362, 198, 8367, ...
2.544444
180
from django.contrib import admin # Register your models here. from apps.weapons.models import Weapon admin.site.register(Weapon)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 6738, 6725, 13, 33999, 13, 27530, 1330, 13072, 198, 198, 28482, 13, 15654, 13, 30238, 7, 27632, 8, 198 ]
3.638889
36
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628, 628 ]
3.555556
9
#!/usr/bin/python # -*- coding: utf-8 -*- import logging from datetime import datetime from scholarly_citation_finder import config from scholarly_citation_finder.apps.parser.Parser import Parser from scholarly_citation_finder.apps.core.models import PublicationUrl from scholarly_citation_finder.tools.extractor.grobid.GrobidExtractor import GrobidExtractor from scholarly_citation_finder.lib.file import download_file_pdf, DownloadFailedException, UnexpectedContentTypeException from scholarly_citation_finder.lib.process import ProcessException from scholarly_citation_finder.apps.parser.Exceptions import ParserRollbackError from scholarly_citation_finder.lib.string import normalize_string from scholarly_citation_finder.tools.extractor.grobid.TeiParser import TeiParserNoDocumentTitle,\ TeiParserNoReferences from scholarly_citation_finder.tools.nameparser.StringMatching import nearly_match logger = logging.getLogger(__name__)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 18931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 31950, 62, 66, 3780, 62, 22805, 1330, 4566, 198, 6738, ...
3.637066
259
import sys import os import json import urllib from PIL import Image from flask import Flask, request, redirect, url_for from flask import send_from_directory, render_template from werkzeug.utils import secure_filename from datetime import datetime from caption_service import CaptionService from translation_service import TranslationService sys.path.append(os.curdir) # UPLOAD_FOLDER = '/tmp/uploads' os.makedirs(UPLOAD_FOLDER, exist_ok=True) ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__, static_url_path='/static', static_folder='assets/static') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER cs = CaptionService() ts = TranslationService() def get_caption(filepath): print('getting caption', filepath) caption_en = cs.get_caption(filepath) caption_ja = ts.get_translation(caption_en) return caption_en, caption_ja if __name__ == '__main__': port = os.environ.get('PORT', 5000) app.run(host='0.0.0.0', port=port)
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 2956, 297, 571, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 18941, 11, 19016, 62, 1640, 198, 6738, 42903, 1330, 3758, 62, 6738, 62, 34945...
2.843931
346
import geopandas as gpd from shapely.geometry import LineString, Polygon,MultiLineString import os.path from map2loop import m2l_utils import warnings import numpy as np import pandas as pd #explodes polylines and modifies objectid for exploded parts
[ 11748, 30324, 392, 292, 355, 27809, 67, 198, 6738, 5485, 306, 13, 469, 15748, 1330, 220, 6910, 10100, 11, 12280, 14520, 11, 29800, 13949, 10100, 198, 11748, 28686, 13, 6978, 198, 6738, 3975, 17, 26268, 1330, 285, 17, 75, 62, 26791, 22...
3.207317
82
#! /usr/bin/env python # -*- coding: utf-8 -*- # # author: Avinash Kori # contact: koriavinash1@gmail.com # MIT License # Copyright (c) 2020 Avinash Kori # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import tempfile from time import time import datetime import numpy as np import nibabel as nib
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 220, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 1772, 25, 5184, 259, 1077, 509, 10145, 198, 2, 2800, 25, 479, 7661, 7114, 1077, 16, 31, 14816, ...
3.610959
365
import os import tensorflow as tf os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' x1 = tf.constant(5) x2 = tf.constant(6) result = tf.multiply(x1, x2) print(result) sess = tf.Session() with tf.Session() as sess: output = sess.run(result) print(output)
[ 11748, 28686, 198, 11748, 11192, 273, 11125, 355, 48700, 220, 198, 198, 418, 13, 268, 2268, 17816, 10234, 62, 8697, 47, 62, 23678, 62, 25294, 62, 2538, 18697, 20520, 796, 705, 17, 6, 198, 198, 87, 16, 796, 48700, 13, 9979, 415, 7, ...
2.176471
119
import auth_key import tweepy import time auth = tweepy.OAuthHandler(auth_key.API_key, auth_key.API_secret_key) auth.set_access_token(auth_key.Access_token, auth_key.Access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) user = api.me() indId = 2282863 india_trend = api.trends_place(indId) tweetNo = 5 a =[] trndInd = api.trends_place(indId) for trend in trndInd[0]['trends']: a.append(trend['name']) for item in a: print(item) for tweet in tweepy.Cursor(api.search, item).items(tweetNo): try: print("tweet liked & retweeted") tweet.favorite() tweet.retweet() time.sleep(10) except tweepy.TweepError as e: print(e.reason) except StopIteration: break
[ 11748, 6284, 62, 2539, 201, 198, 11748, 4184, 538, 88, 201, 198, 11748, 640, 201, 198, 201, 198, 18439, 796, 4184, 538, 88, 13, 23621, 1071, 25060, 7, 18439, 62, 2539, 13, 17614, 62, 2539, 11, 6284, 62, 2539, 13, 17614, 62, 21078, ...
2.03125
416
from ds_discovery import Controller import os import warnings warnings.simplefilter(action='ignore', category=FutureWarning) warnings.simplefilter(action='ignore', category=DeprecationWarning) __author__ = 'Darryl Oatridge' if __name__ == '__main__': domain_controller()
[ 6738, 288, 82, 62, 67, 40821, 1330, 22741, 198, 11748, 28686, 198, 11748, 14601, 198, 198, 40539, 654, 13, 36439, 24455, 7, 2673, 11639, 46430, 3256, 6536, 28, 29783, 20361, 8, 198, 40539, 654, 13, 36439, 24455, 7, 2673, 11639, 46430, ...
3.294118
85
import json import unittest from utils import CustomEncoder, Paging, ValidationError, generate_uuid, Validator
[ 11748, 33918, 198, 11748, 555, 715, 395, 198, 198, 6738, 3384, 4487, 1330, 8562, 27195, 12342, 11, 350, 3039, 11, 3254, 24765, 12331, 11, 7716, 62, 12303, 312, 11, 48951, 1352, 628, 220, 220, 220, 220, 220, 220, 220, 220 ]
3.025
40
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import logging import os import sys from . import entries, meta logger = logging.getLogger(__name__) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 6738, 764, 1330, 12784, 11, ...
2.6375
80
from flask import Flask, render_template, url_for, redirect, request from flask_sqlalchemy import SQLAlchemy from datetime import datetime from dateutil.relativedelta import relativedelta from demail import demail __author__ = 'Zhongxuan Wang' __doc__ = 'Never Forget online remainder' app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///list.db' # Remember, every time you make changes to the column (such as adding one col or removing one col, change the value), # you have to do the following: open terminal from pycharm, python3.7, from app import db, db.create_all() and exit. db = SQLAlchemy(app) db.create_all() datetime_format = '%b-%d-%Y %H:%M' ''' This part requires your email information in order to receive email notifications. (This is left blank intentionally) ''' email_account = '' email_password = '' # TODO send email warning if the due time is so soon and still incomplete, ''' This will return a new date & time that after adding the values in time dictionaries ''' def read_file(filename): try: with open(filename) as f: return f.readline() except IOError: print("IO ERROR Raised. Reading file failed,") f = open(filename, "w") f.write('email@example.com') f.close() return 'content' def write_file(filename, file_content): try: with open(filename, 'w') as f: f.write(file_content) except IOError: print("IO ERROR Raised. Writing file failed,") return '' if __name__ == '__main__': app.run(debug=False)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 19016, 62, 1640, 11, 18941, 11, 2581, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 3128, 22602, 13, 2411, 265, ...
2.825
560
"""The solaredge integration.""" from __future__ import annotations from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from .const import DOMAIN CONFIG_SCHEMA = cv.deprecated(DOMAIN)
[ 37811, 464, 1540, 1144, 469, 11812, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 1363, 562, 10167, 13, 11250, 62, 298, 1678, 1330, 17056, 30150, 198, 6738, 1363, 562, 10167, 13, 7295, 1330, 5995, 48902, 198, 11...
3.5
82
import uos import utime import machine from machine import Pin, PWM import utils default_config = dict( sleep_time_ms = 250, freezer_delay_ms = 1000, fridge_delay_ms = 1000, write_battery_voltage = True, piezo_plus_pin_num = 12, piezo_min_pin_num = 33, freezer_switch_pin_num = 23, fridge_switch_pin_num = 21 ) try: config_dct = {} execfile('config.py', config_dct) except Exception as e: print("Could not run config file, using defaults:", default_config, '. File error:') print(e) globals().update(default_config) else: for varnm in default_config.keys(): if varnm in config_dct: globals()[varnm] = config_dct[varnm] print('Loaded config value for', varnm, ':', config_dct[varnm]) else: globals()[varnm] = default_config[varnm] print('Using default config value for', varnm, ':', default_config[varnm]) # setup pins led_pin = Pin(13, Pin.OUT) piezo_min_pin = Pin(piezo_min_pin_num, Pin.OUT) freezer_switch_pin = Pin(freezer_switch_pin_num, Pin.IN, Pin.PULL_UP) fridge_switch_pin = Pin(fridge_switch_pin_num, Pin.IN, Pin.PULL_UP) #set initial state of pins piezo_min_pin.value(0) led_pin.value(0) # set up PWM piezo_plus_pwm = PWM(Pin(piezo_plus_pin_num), duty=512) piezo_plus_pwm.deinit() # how often to write out the battery status. None means don't do it at all battery_time_spacing_secs = 600 # use an infinite loop to watch for door opening last_battery_time = None open_times = {'Freezer': None, 'Fridge': None} while True: check_open(freezer_switch_pin, 'Freezer', open_times, ([1300,1000], 10, 500), freezer_delay_ms) check_open(fridge_switch_pin, 'Fridge', open_times, ([1200,900], 10, 500), fridge_delay_ms) utime.sleep_ms(sleep_time_ms) # write out battery status if desired if battery_time_spacing_secs is not None: if last_battery_time is None: last_battery_time = utime.time() else: if (utime.time() - last_battery_time) > battery_time_spacing_secs: voltage = utils.read_battery_voltage() print('Battery level:', voltage, 'V') if write_battery_voltage: with open('battery_voltage', 'a') as f: f.write(str(utime.time())) f.write(' ') f.write(str(voltage)) f.write('\n') last_battery_time = utime.time()
[ 11748, 334, 418, 201, 198, 11748, 3384, 524, 201, 198, 11748, 4572, 201, 198, 6738, 4572, 1330, 13727, 11, 350, 22117, 201, 198, 201, 198, 11748, 3384, 4487, 201, 198, 201, 198, 12286, 62, 11250, 796, 8633, 7, 201, 198, 220, 220, 22...
2.112757
1,215
import os, sys from distutils.util import strtobool import numpy as np import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.python.util import nest, tf_inspect from tensorflow.python.eager import tape # from tensorflow.python.ops.custom_gradient import graph_mode_decorator # do_recompute = strtobool(os.environ.get('RECOMPUTE', '0')) # https://zhuanlan.zhihu.com/p/349492378 # https://arxiv.53yu.com/pdf/1606.08415.pdf def gelu_erf(x): """erfgelu """ # np64tf32 return 0.5 * x * (1.0 + tf.math.erf(x / np.sqrt(2.0))) def set_gelu(version): """gelu """ version = version.lower() assert version in ['erf', 'tanh'], 'gelu version must in erf or tanh' if version == 'erf': tf.keras.utils.get_custom_objects()['gelu'] = gelu_erf elif version == 'tanh': tf.keras.utils.get_custom_objects()['gelu'] = gelu_tanh def align(tensor, axes, ndim=None): """tensorexpand_dimstranspose axes: itensoraxes[i] ndim: tensor Example: >>> tensor = tf.constant(np.arange(12).reshape(3,4), dtype=tf.float32) >>> print(tensor) tf.Tensor( [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.]], shape=(3, 4), dtype=float32) >>> same_dim = align(tensor, [0, -1], 2) >>> print(same_dim) tf.Tensor( [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.]], shape=(3, 4), dtype=float32) >>> more_dim = align(tensor, [0, -1], 3) >>> print(more_dim) tf.Tensor( [[[ 0. 1. 2. 3.]] <BLANKLINE> [[ 4. 5. 6. 7.]] <BLANKLINE> [[ 8. 9. 10. 11.]]], shape=(3, 1, 4), dtype=float32) """ assert len(axes) == K.ndim(tensor) indices = [None] * (ndim or max(axes)) for i in axes: indices[i] = slice(None) return tensor[indices] def sequence_masking(x, mask, value=0, axis=None): """mask parameters: ----------- x: tensor mask: tensor (batch_size, seq_len)0-1 value: float or str mask'inf''-inf' axis: int 1 """ if mask is None: return x # x* x_type = K.dtype(x) if x_type == 'bool': x = K.cast(x, 'int32') # mask = x if K.dtype(mask) != K.dtype(x): mask = K.cast(mask, K.dtype(x)) if value == '-inf': # -------------------------- value = -K.infinity if value == 'inf': value = K.infinity value = K.cast(value, K.dtype(x)) # axis if axis is None: axis = 1 if axis < 0: axis = K.ndim(x) + axis assert axis > 0, 'axis must be greater than 0' # shape for _ in range(axis - 1): # > 1 mask = K.expand_dims(mask, 1) # 0batch_size for _ in range(K.ndim(x) - K.ndim(mask)): mask = K.expand_dims(mask, K.ndim(mask)) x = x * mask + value * (1 - mask) # x if x_type == 'bool': x = K.cast(x, x_type) return x def recompute_grad(call): # ---------------------------------------------- """kerascall https://arxiv.org/abs/1604.06174 """ if not do_recompute: return call return inner def infinity(): """ """ return tf.keras.utils.get_custom_objects().get('infinity', 1e12) def set_infinity(value): """ """ tf.keras.utils.get_custom_objects()['infinity'] = value # keras.backend K.epsilon() K.infinity = infinity K.set_infinity = set_infinity sys.modules['tensorflow.keras.backend'] = K custom_objects = { 'gelu_erf': gelu_erf, 'gelu_tanh': gelu_tanh, 'gelu': gelu_erf, } tf.keras.utils.get_custom_objects().update(custom_objects) if __name__ == '__main__': import doctest doctest.testmod()
[ 11748, 28686, 11, 25064, 201, 198, 6738, 1233, 26791, 13, 22602, 1330, 965, 83, 672, 970, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 11192, 273, 11125, 355, 48700, 201, 198, 11748, 11192, 273, 11125, 13, 6122, 292, 13, ...
1.992765
1,935
import datetime import os import requests import tweepy from PIL import Image # Get your own keys from developer.twitter.com # You can find a detailed tutorial about authenticating accounts from github.com/gultugaydemir/Twitter_OAuth1.0a consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # You can get your own API key from api.nasa.gov. However simply writing "DEMO_KEY" works too, as it can be seen on the website. response = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY") #This link contains the data we needed about the photo of the day. data = response.json() # Converts the data to JSON format so that we can retrieve data from it. description = data["title"] # Getting the title of the photo. date = datetime.datetime.now().strftime("%y%m%d") # We need the {yymmdd} format for the source link. source = "https://apod.nasa.gov/apod/ap{date}.html".format(date=date) # Creating the source link for the posted photo. message = '"' + description + '" \n' + source # The status format for the image tweets. message_video = '"' + description + '" \n' # The status format for the YouTube tweets. try: image = data["hdurl"] # The image URL from API. except KeyError: # Code throws KeyError if a video is posted that day, since API doesn't include a "hdurl" element. image = data["url"] image = image.replace("embed/", "watch?v=") api.update_status(status = message_video+ source + ' \n'+ image) # Bot only tweets the YouTube link and not a picture. print("Video tweeted successfully.") quit() # Tweepy's "update_with_media" function only allows us to tweet an image from the local directory. # Since posting the picture from a URL would be more practical, I'm using a function that will complete this step for me automatically. tweet_image(image, message) # Tweeting the picture with the status. Image URL and the status message are used as parameters.
[ 11748, 4818, 8079, 198, 11748, 28686, 198, 11748, 7007, 198, 11748, 4184, 538, 88, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 2, 3497, 534, 898, 8251, 422, 8517, 13, 6956, 13, 785, 198, 2, 921, 460, 1064, 257, 6496, 11808, 546, 832...
3.385366
615
import pickle import os import tensorflow as tf from glob import glob import utils.DataLoaderUtils as dlu from utils.AnnotationUtils import write_dad_masks # Static Dataset Config Options TAG_NAMES = {'highlights', 'urls_to_supplementary', 'abbreviation', 'abstract', 'additional_file', 'affiliation', 'appendice', 'author_bio', 'author_contribution', 'author_name', 'availability_of_data', 'caption', 'conflict_int', 'contact_info', 'copyright', 'core_text', 'date', 'doi', 'figure', 'funding_info', 'index', 'keywords', 'list', 'math_formula', 'note', 'publisher_note', 'reference', 'section_heading', 'subheading', 'table', 'title', 'nomenclature', 'code', 'publisher', 'journal', 'corresponding_author', 'editor', 'ethics', 'consent_publication', 'MSC', 'article_history', 'acknowledgment', 'background'} TAG_MAPPING = {'abbreviation': 'background', 'acknowledgment': 'background', 'additional_file': 'background', 'affiliation': 'background', 'article_history': 'background', 'author_contribution': 'background', 'availability_of_data': 'background', 'code': 'background', 'conflict_int': 'background', 'consent_publication': 'background', 'corresponding_author': 'background', 'date': 'background', 'ethics': 'background', 'index': 'background', 'journal': 'background', 'nomenclature': 'background', 'publisher_note': 'background', 'urls_to_supplementary': 'background', 'msc': 'background', 'MSC': 'background', 'highlights': 'background', 'subheading': 'section_heading'} SAVED_PKL_FILE = 'saved_dad_paths.pkl' BUFFER_SIZE = 500 MASKS_DIR = "masks" DOCUMENTS_DIR = "documents" ANNOTATIONS_DIR = "annotations"
[ 11748, 2298, 293, 198, 11748, 28686, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 15095, 1330, 15095, 198, 198, 11748, 3384, 4487, 13, 6601, 17401, 18274, 4487, 355, 288, 2290, 198, 6738, 3384, 4487, 13, 2025, 38983, 18274, 4487,...
1.767684
1,442
# terrascript/resource/ddelnano/mikrotik.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:21:43 UTC) import terrascript __all__ = [ "mikrotik_bgp_instance", "mikrotik_bgp_peer", "mikrotik_dhcp_lease", "mikrotik_dns_record", "mikrotik_pool", "mikrotik_scheduler", "mikrotik_script", ]
[ 2, 8812, 15961, 14, 31092, 14, 1860, 45542, 5733, 14, 76, 1134, 10599, 1134, 13, 9078, 198, 2, 17406, 4142, 7560, 416, 4899, 14, 15883, 8189, 13, 9078, 357, 1731, 12, 19117, 12, 1238, 2481, 1315, 25, 2481, 25, 3559, 18119, 8, 198, ...
2.139241
158
import time import queue import threading if __name__ == '__main__': num_of_threads = 5 source = [i for i in range(1, 21)] q = queue.Queue() threads = [] for i in range(1, num_of_threads + 1): t = threading.Thread(target=aaa, args=(i,)) threads.append(t) t.start() for item in source: time.sleep(0.01) q.put(item) q.join() # print("----------") # # for i in range(num_of_threads): q.put(None) # for t in threads: # t.join() # print(threads)
[ 11748, 640, 198, 11748, 16834, 198, 11748, 4704, 278, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 997, 62, 1659, 62, 16663, 82, 796, 642, 198, 220, 220, 220, 2723, 796, 685, 72, 329, ...
2.079245
265
# : 68 ms # : 16.6 MB # sentinelhead # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
[ 2, 220, 1058, 8257, 13845, 198, 2, 220, 1058, 1467, 13, 21, 10771, 198, 198, 2, 220, 1908, 20538, 2256, 198, 198, 2, 30396, 329, 1702, 306, 12, 25614, 1351, 13, 198, 2, 1398, 7343, 19667, 25, 198, 2, 220, 220, 220, 220, 825, 115...
2.13253
83
# Generated by Django 3.2.5 on 2021-07-06 14:18 import uuid from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 20, 319, 33448, 12, 2998, 12, 3312, 1478, 25, 1507, 198, 198, 11748, 334, 27112, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.861111
36
from tests.primitives.flow import probe_tcpip_extended_biflow_test from netexp.primitives.flow import TCPIPFlowExtendedUniBiFlowInfo from netexp.common import naming
[ 6738, 5254, 13, 19795, 20288, 13, 11125, 1330, 12774, 62, 83, 13155, 541, 62, 2302, 1631, 62, 65, 361, 9319, 62, 9288, 198, 198, 6738, 2010, 11201, 13, 19795, 20288, 13, 11125, 1330, 23633, 4061, 37535, 11627, 1631, 3118, 72, 23286, 3...
3.230769
52
import time import mysql.connector from optionstrader.customlogging import CustomLog from optionstrader.parser import Parser MYSQL_IP_ADDR = '192.168.1.10' # Used to debug via logs DEBUG = False
[ 11748, 640, 198, 11748, 48761, 13, 8443, 273, 198, 198, 6738, 3038, 2536, 5067, 13, 23144, 6404, 2667, 1330, 8562, 11187, 198, 6738, 3038, 2536, 5067, 13, 48610, 1330, 23042, 263, 198, 198, 44, 16309, 9711, 62, 4061, 62, 2885, 7707, 7...
3.126984
63
# Generated by Django 3.2.9 on 2021-11-24 02:52 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 24, 319, 33448, 12, 1157, 12, 1731, 7816, 25, 4309, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
from unittest import TestCase from CTCI.Ch2_Linked_Lists.common.SinglyLinkedList import Empty, Node from CTCI.Ch2_Linked_Lists.exercises.CTCI_Ch2_Ex6 import PalindromeSinglyLinkedList, is_palindrome_brute_force from CTCI.Ch2_Linked_Lists.exercises.CTCI_Ch2_Ex6 import is_palindrome_reverse
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 327, 4825, 40, 13, 1925, 17, 62, 11280, 276, 62, 43, 1023, 13, 11321, 13, 50, 4420, 11280, 276, 8053, 1330, 33523, 11, 19081, 198, 6738, 327, 4825, 40, 13, 1925, 17, 62, 11280, 27...
2.504274
117
# utils for working with 3d-protein structures import os import numpy as np import torch from functools import wraps from einops import rearrange, repeat # import torch_sparse # only needed for sparse nth_deg adj calculation # bio from Bio import SeqIO import itertools import string # sidechainnet from sidechainnet.utils.sequence import ProteinVocabulary, ONE_TO_THREE_LETTER_MAP from sidechainnet.utils.measure import GLOBAL_PAD_CHAR from sidechainnet.structure.build_info import NUM_COORDS_PER_RES, BB_BUILD_INFO, SC_BUILD_INFO from sidechainnet.structure.StructureBuilder import _get_residue_build_iter # build vocabulary VOCAB = ProteinVocabulary() # constants import alphafold2_pytorch.constants as constants # helpers # constants: same as in alphafold2.py DISTANCE_THRESHOLDS = torch.linspace(2, 20, steps = constants.DISTOGRAM_BUCKETS) # distance binning function # decorators def expand_arg_dims(dim_len = 3): """ pack here for reuse. turns input into (B x D x N) """ return outer # preprocess data def get_atom_ids_dict(): """ Get's a dict mapping each atom to a token. """ ids = set(["", "N", "CA", "C", "O"]) for k,v in SC_BUILD_INFO.items(): for name in v["atom-names"]: ids.add(name) return {k: i for i,k in enumerate(sorted(ids))} def make_cloud_mask(aa): """ relevent points will be 1. paddings will be 0. """ mask = np.zeros(14) # early stop if padding token if aa == "_": return mask # get num of atoms in aa n_atoms = 4+len( SC_BUILD_INFO[ ONE_TO_THREE_LETTER_MAP[aa] ]["atom-names"] ) mask[:n_atoms] = 1 return mask def make_atom_id_embedds(aa, atom_ids): """ Return the tokens for each atom in the aa. """ mask = np.zeros(14) # early stop if padding token if aa == "_": return mask # get atom id atom_list = ["N", "CA", "C", "O"] + SC_BUILD_INFO[ ONE_TO_THREE_LETTER_MAP[aa] ]["atom-names"] for i,atom in enumerate(atom_list): mask[i] = ATOM_IDS[atom] return mask ATOM_IDS = get_atom_ids_dict() CUSTOM_INFO = {k: {"cloud_mask": make_cloud_mask(k), "atom_id_embedd": make_atom_id_embedds(k, atom_ids=ATOM_IDS), } for k in "ARNDCQEGHILKMFPSTWYV_"} #common utils # parsing to pdb for easier visualization - other example from sidechainnet is: # https://github.com/jonathanking/sidechainnet/tree/master/sidechainnet/structure def download_pdb(name, route): """ Downloads a PDB entry from the RCSB PDB. Inputs: * name: str. the PDB entry id. 4 characters, capitalized. * route: str. route of the destin file. usually ".pdb" extension Output: route of destin file """ os.system(f"curl https://files.rcsb.org/download/{name}.pdb > {route}") return route def clean_pdb(name, route=None, chain_num=None): """ Cleans the structure to only leave the important part. Inputs: * name: str. route of the input .pdb file * route: str. route of the output. will overwrite input if not provided * chain_num: int. index of chain to select (1-indexed as pdb files) Output: route of destin file. """ import mdtraj destin = route if route is not None else name # read input raw_prot = mdtraj.load_pdb(name) # iterate over prot and select the specified chains idxs = [] for chain in raw_prot.topology.chains: # if arg passed, only select that chain if chain_num is not None: if chain_num != chain.index: continue # select indexes of chain chain_idxs = raw_prot.topology.select(f"chainid == {str(chain.index)}") idxs.extend( chain_idxs.tolist() ) # sort: topology and xyz selection are ordered idxs = sorted(idxs) # get new trajectory from the sleected subset of indexes and save prot = mdtraj.Trajectory(xyz=raw_prot.xyz[:, idxs], topology=raw_prot.topology.subset(idxs)) prot.save(destin) return destin def custom2pdb(coords, proteinnet_id, route): """ Takes a custom representation and turns into a .pdb file. Inputs: * coords: array/tensor of shape (3 x N) or (N x 3). in Angstroms. same order as in the proteinnnet is assumed (same as raw pdb file) * proteinnet_id: str. proteinnet id format (<class>#<pdb_id>_<chain_number>_<chain_id>) see: https://github.com/aqlaboratory/proteinnet/ * route: str. destin route. Output: tuple of routes: (original, generated) for the structures. """ import mdtraj # convert to numpy if isinstance(coords, torch.Tensor): coords = coords.detach().cpu().numpy() # ensure (1, N, 3) if coords.shape[1] == 3: coords = coords.T coords = np.newaxis(coords, axis=0) # get pdb id and chain num pdb_name, chain_num = proteinnet_id.split("#")[-1].split("_")[:-1] pdb_destin = "/".join(route.split("/")[:-1])+"/"+pdb_name+".pdb" # download pdb file and select appropiate download_pdb(pdb_name, pdb_destin) clean_pdb(pdb_destin, chain_num=chain_num) # load trajectory scaffold and replace coordinates - assumes same order scaffold = mdtraj.load_pdb(pdb_destin) scaffold.xyz = coords scaffold.save(route) return pdb_destin, route def coords2pdb(seq, coords, cloud_mask, prefix="", name="af2_struct.pdb"): """ Turns coordinates into PDB files ready to be visualized. Inputs: * seq: (L,) tensor of ints (sidechainnet aa-key pairs) * coords: (3, N) coords of atoms * cloud_mask: (L, C) boolean mask of occupied spaces in scn format * prefix: str. directory to save files. * name: str. name of destin file (ex: pred1.pdb) """ scaffold = torch.zeros( cloud_mask.shape, 3 ) scaffold[cloud_mask] = coords.cpu().float() # build structures and save pred = scn.StructureBuilder( seq, crd=scaffold ) pred.to_pdb(prefix+name) #adapted from https://github.com/facebookresearch/esm def remove_insertions(sequence: str) -> str: """ Removes any insertions into the sequence. Needed to load aligned sequences in an MSA. """ deletekeys = dict.fromkeys(string.ascii_lowercase) deletekeys["."] = None deletekeys["*"] = None translation = str.maketrans(deletekeys) return sequence.translate(translation) def read_msa(filename: str, nseq: int): """ Reads the first nseq sequences from an MSA file, automatically removes insertions.""" return [(record.description, remove_insertions(str(record.seq))) for record in itertools.islice(SeqIO.parse(filename, "fasta"), nseq)] # sidechainnet / MSA / other data utils def ids_to_embed_input(x): """ Returns the amino acid string input for calculating the ESM and MSA transformer embeddings Inputs: * x: any deeply nested list of integers that correspond with amino acid id """ assert isinstance(x, list), 'input must be a list' id2aa = VOCAB._int2char out = [] for el in x: if isinstance(el, list): out.append(ids_to_embed_input(el)) elif isinstance(el, int): out.append(id2aa[el]) else: raise TypeError('type must be either list or character') if all(map(lambda c: isinstance(c, str), out)): return (None, ''.join(out)) return out def get_msa_embedd(msa, embedd_model, batch_converter, device = None): """ Returns the MSA_tr embeddings for a protein. Inputs: * seq: ( (b,) L,) tensor of ints (in sidechainnet int-char convention) * embedd_model: MSA_tr model (see train_end2end.py for an example) * batch_converter: MSA_tr batch converter (see train_end2end.py for an example) Outputs: tensor of (batch, n_seqs, L, embedd_dim) * n_seqs: number of sequences in the MSA * embedd_dim: number of embedding dimensions. 768 for MSA_Transformer """ #use MSA transformer REPR_LAYER_NUM = 12 device = embedd_model.device max_seq_len = msa.shape[-1] embedd_inputs = ids_to_embed_input(msa.cpu().tolist()) msa_batch_labels, msa_batch_strs, msa_batch_tokens = batch_converter(embedd_inputs) with torch.no_grad(): results = embedd_model(msa_batch_tokens.to(device), repr_layers=[REPR_LAYER_NUM], return_contacts=False) # index 0 is for start token. so take from 1 one token_reps = results["representations"][REPR_LAYER_NUM][..., 1:, :] return token_reps def get_esm_embedd(seq, embedd_model, batch_converter, msa_data=None): """ Returns the ESM embeddings for a protein. Inputs: * seq: ( (b,) L,) tensor of ints (in sidechainnet int-char convention) * embedd_model: ESM model (see train_end2end.py for an example) * batch_converter: ESM batch converter (see train_end2end.py for an example) Outputs: tensor of (batch, n_seqs, L, embedd_dim) * n_seqs: number of sequences in the MSA. 1 for ESM-1b * embedd_dim: number of embedding dimensions. 1280 for ESM-1b """ #use ESM transformer device = embedd_model.device REPR_LAYER_NUM = 33 max_seq_len = seq.shape[-1] embedd_inputs = ids_to_embed_input(seq.cpu().tolist()) batch_labels, batch_strs, batch_tokens = batch_converter(embedd_inputs) with torch.no_grad(): results = embedd_model(batch_tokens.to(device), repr_layers=[REPR_LAYER_NUM], return_contacts=False) # index 0 is for start token. so take from 1 one token_reps = results["representations"][REPR_LAYER_NUM][..., 1:, :].unsqueeze(dim=1) return token_reps def get_all_protein_ids(dataloader, verbose=False): """ Given a sidechainnet dataloader for a CASP version, Returns all the ids belonging to proteins. Inputs: * dataloader: a sidechainnet dataloader for a CASP version Outputs: a set containing the ids for all protein entries. """ # store ids here ids = set([]) #iterate for all batches for i,batch in tqdm(enumerate(dataloaders['train'])): # for breaking from 2 loops at once try: for i in range(batch.int_seqs.shape[0]): # check if all fragments are : 4_LETTER_PDB + NUM + CHAIN max_len_10 = len(batch.pids[i]) < 10 fragments = [len(x) <= 4 for x in batch.pids[i].split("_")] fragments_under_4 = sum(fragments) == len(fragments) # AND CONDITION # record id if max_len_10 and fragments_under_4: ids.add(batch.pids[i]) else: if verbose: print("skip:", batch.pids[i], "under 4", fragments) except StopIteration: break #returns set of ids return ids def scn_cloud_mask(scn_seq, boolean=True, coords=None): """ Gets the boolean mask atom positions (not all aas have same atoms). Inputs: * scn_seq: (batch, length) sequence as provided by Sidechainnet package * boolean: whether to return as array of idxs or boolean values * coords: optional .(batch, lc, 3). sidechainnet coords. returns the true mask (solves potential atoms that might not be provided) Outputs: (batch, length, NUM_COORDS_PER_RES) boolean mask """ scn_seq = expand_dims_to(scn_seq, 2 - len(scn_seq.shape)) # early check for coords mask if coords is not None: batch_mask = ( rearrange(coords, '... (l c) d -> ... l c d', c=14) == 0 ).sum(dim=-1) < coords.shape[-1] if boolean: return batch_mask.bool() else: return batch_mask.nonzero() # do loop in cpu device = scn_seq.device batch_mask = [] scn_seq = scn_seq.cpu().tolist() for i, seq in enumerate(scn_seq): # get masks for each prot (points for each aa) batch_mask.append( torch.tensor([CUSTOM_INFO[VOCAB.int2char(aa)]['cloud_mask'] \ for aa in seq]).bool().to(device).unsqueeze(0) ) # concat in last dim batch_mask = torch.cat(batch_mask, dim=0) # return mask (boolean or indexes) if boolean: return batch_mask.bool() else: return batch_mask.nonzero() def scn_backbone_mask(scn_seq, boolean=True, n_aa=3): """ Gets the boolean mask for N and CA positions. Inputs: * scn_seq: sequence(s) as provided by Sidechainnet package (int tensor/s) * n_aa: number of atoms in a backbone. (may include cbeta as 4th pos) * bool: whether to return as array of idxs or boolean values Outputs: (N_mask, CA_mask, C_mask) """ wrapper = torch.zeros(*scn_seq.shape, n_aa).to(scn_seq.device) # N is the first atom in every AA. CA is the 2nd. wrapper[..., 0] = 1 wrapper[..., 1] = 2 wrapper[..., 2] = 3 wrapper = rearrange(wrapper, '... l c -> ... (l c)') # find idxs N_mask = wrapper == 1 CA_mask = wrapper == 2 C_mask = wrapper == 3 if boolean: return N_mask, CA_mask, C_mask return torch.nonzero(N_mask), torch.nonzero(CA_mask), torch.nonzero(C_mask) def scn_atom_embedd(scn_seq): """ Returns the token for each atom in the aa. Inputs: * scn_seq: sequence(s) as provided by Sidechainnet package (int tensor/s) """ device = scn_seq.device batch_tokens = [] # do loop in cpu scn_seq = scn_seq.cpu() for i,seq in enumerate(scn_seq): batch_tokens.append( torch.tensor([CUSTOM_INFO[VOCAB.int2char(aa.item())]["atom_id_embedd"] \ for aa in seq]).long().to(device).unsqueeze(0) ) batch_tokens = torch.cat(batch_tokens, dim=0) return batch_tokens def nth_deg_adjacency(adj_mat, n=1, sparse=False): """ Calculates the n-th degree adjacency matrix. Performs mm of adj_mat and adds the newly added. Default is dense. Mods for sparse version are done when needed. Inputs: * adj_mat: (N, N) adjacency tensor * n: int. degree of the output adjacency * sparse: bool. whether to use torch-sparse module Outputs: * edge_idxs: ij positions of the adjacency matrix * edge_attrs: degree of connectivity (1 for neighs, 2 for neighs^2, ... ) """ adj_mat = adj_mat.float() attr_mat = torch.zeros_like(adj_mat) new_adj_mat = adj_mat.clone() for i in range(n): if i == 0: attr_mat += adj_mat continue if i == 1 and sparse: idxs = adj_mat.nonzero().t() vals = adj_mat[idxs[0], idxs[1]] new_idxs = idxs.clone() new_vals = vals.clone() m, k, n = 3 * [adj_mat.shape[0]] #(m, n) * (n, k) , but adj_mats are squared: m=n=k if sparse: new_idxs, new_vals = torch_sparse.spspmm(new_idxs, new_vals, idxs, vals, m=m, k=k, n=n) new_vals = new_vals.bool().float() new_adj_mat = torch.zeros_like(attr_mat) new_adj_mat[new_idxs[0], new_idxs[1]] = new_vals # sparse to dense is slower # torch.sparse.FloatTensor(idxs, vals).to_dense() else: new_adj_mat = (new_adj_mat @ adj_mat).bool().float() attr_mat.masked_fill( (new_adj_mat - attr_mat.bool().float()).bool(), i+1 ) return new_adj_mat, attr_mat def prot_covalent_bond(seqs, adj_degree=1, cloud_mask=None, mat=True): """ Returns the idxs of covalent bonds for a protein. Inputs * seq: (b, n) torch long. * adj_degree: int. adjacency degree * cloud_mask: mask selecting the present atoms. * mat: whether to return as indexes or matrices. for indexes, only 1 seq is supported Outputs: edge_idxs, edge_attrs """ device = seqs.device # get starting poses for every aa adj_mat = torch.zeros(seqs.shape[0], seqs.shape[1]*14, seqs.shape[1]*14) # not needed to device since it's only for indices. scaff = torch.zeros(seqs.shape[1], 14) scaff[:, 0] = 1 idxs = torch.nonzero(scaff).reshape(-1) for s,seq in enumerate(seqs): for i,idx in enumerate(idxs): if i >= seq.shape[0]: break # offset by pos in chain ( intra-aa bonds + with next aa ) bonds = idx + torch.tensor( constants.AA_DATA[VOCAB.int2char(seq[i].item())]['bonds'] + [[2, 14]] ).t() # delete link with next if final AA in seq if i == idxs.shape[0]-1: bonds = bonds[:, :-1] # modify adj mat adj_mat[s, bonds[0], bonds[1]] = 1 #convert to undirected adj_mat[s] = adj_mat[s] + adj_mat[s].t() # do N_th degree adjacency adj_mat, attr_mat = nth_deg_adjacency(adj_mat, n=adj_degree, sparse=False) # True if mat: return attr_mat.bool().to(seqs.device), attr_mat.to(device) else: edge_idxs = attr_mat[0].nonzero().t().long() edge_attrs = attr_mat[0, edge_idxs[0], edge_idxs[1]] return edge_idxs.to(seqs.device), edge_attrs.to(seqs.device) def nerf_torch(a, b, c, l, theta, chi): """ Custom Natural extension of Reference Frame. Inputs: * a: (batch, 3) or (3,). point(s) of the plane, not connected to d * b: (batch, 3) or (3,). point(s) of the plane, not connected to d * c: (batch, 3) or (3,). point(s) of the plane, connected to d * theta: (batch,) or (float). angle(s) between b-c-d * chi: (batch,) or float. dihedral angle(s) between the a-b-c and b-c-d planes Outputs: d (batch, 3) or (3,). the next point in the sequence, linked to c """ #safety check if not ( (-np.pi <= theta) * (theta <= np.pi) ).all().item(): raise ValueError(f"theta(s) must be in radians and in [-pi, pi]. theta(s) = {theta}") # calc vecs ba = b-a cb = c-b # calc rotation matrix. based on plane normals and normalized n_plane = torch.cross(ba, cb, dim=-1) n_plane_ = torch.cross(n_plane, cb, dim=-1) rotate = torch.stack([cb, n_plane_, n_plane], dim=-1) rotate /= torch.norm(rotate, dim=-2, keepdim=True) # calc proto point, rotate d = torch.stack([-torch.cos(theta), torch.sin(theta) * torch.cos(chi), torch.sin(theta) * torch.sin(chi)], dim=-1).unsqueeze(-1) # extend base point, set length return c + l.unsqueeze(-1) * torch.matmul(rotate, d).squeeze() def sidechain_container(backbones, n_aa, cloud_mask=None, place_oxygen=False, n_atoms=NUM_COORDS_PER_RES, padding=GLOBAL_PAD_CHAR): """ Gets a backbone of the protein, returns the whole coordinates with sidechains (same format as sidechainnet). Keeps differentiability. Inputs: * backbones: (batch, L*3, 3): assume batch=1 (could be extended later). Coords for (N-term, C-alpha, C-term) of every aa. * n_aa: int. number of points for each aa in the backbones. * cloud_mask: (batch, l, c). optional. cloud mask from scn_cloud_mask`. returns point outside to 0. if passed, else c_alpha * place_oxygen: whether to claculate the oxygen of the carbonyl group via NeRF * n_atoms: int. n of atom positions / atom. same as in sidechainnet: 14 * padding: int. padding token. same as in sidechainnet: 0 Outputs: whole coordinates of shape (batch, L, n_atoms, 3) """ device = backbones.device batch, length = backbones.shape[0], backbones.shape[1] // n_aa # build scaffold from (N, CA, C, CB) new_coords = torch.zeros(batch, length, NUM_COORDS_PER_RES, 3).to(device) predicted = rearrange(backbones, 'b (l back) d -> b l back d', l=length) # set backbone positions new_coords[:, :, :3] = predicted[:, :, :3] # set rest of positions to c_beta if present, else c_alpha if n_aa == 4: new_coords[:, :, 4:] = repeat(predicted[:, :, -1], 'b l d -> b l scn d', scn=10) else: new_coords[:, :, 4:] = repeat(new_coords[:, :, 1], 'b l d -> b l scn d', scn=10) if cloud_mask is not None: new_coords[torch.logical_not(cloud_mask)] = 0. # hard-calculate oxygen position of carbonyl group with parallel version of NERF if place_oxygen: # build (=O) position of revery aa in each chain for s in range(batch): # dihedrals phi=f(c-1, n, ca, c) & psi=f(n, ca, c, n+1) # phi = get_dihedral_torch(*backbone[s, i*3 - 1 : i*3 + 3]) if i>0 else None psis = torch.tensor([ get_dihedral_torch(*backbones[s, i*3 + 0 : i*3 + 4] )if i < length-1 else np.pi*5/4 \ for i in range(length) ]) # the angle for placing oxygen is opposite to psi of current res. # psi not available for last one so pi/4 taken for now bond_lens = repeat(torch.tensor(BB_BUILD_INFO["BONDLENS"]["c-o"]), ' -> b', b=length).to(psis.device) bond_angs = repeat(torch.tensor(BB_BUILD_INFO["BONDANGS"]["ca-c-o"]), ' -> b', b=length).to(psis.device) correction = repeat(torch.tensor(-np.pi), ' -> b', b=length).to(psis.device) new_coords[:, :, 3] = nerf_torch(new_coords[:, :, 0], new_coords[:, :, 1], new_coords[:, :, 2], bond_lens, bond_angs, psis + correction) else: # init oxygen to carbonyl new_coords[:, :, 3] = predicted[:, :, 2] return new_coords # distance utils (distogram to dist mat + masking) def center_distogram_torch(distogram, bins=DISTANCE_THRESHOLDS, min_t=1., center="mean", wide="std"): """ Returns the central estimate of a distogram. Median for now. Inputs: * distogram: (batch, N, N, B) where B is the number of buckets. * bins: (B,) containing the cutoffs for the different buckets * min_t: float. lower bound for distances. Outputs: * central: (batch, N, N) * dispersion: (batch, N, N) * weights: (batch, N, N) """ shape, device = distogram.shape, distogram.device # threshold to weights and find mean value of each bin n_bins = ( bins - 0.5 * (bins[2] - bins[1]) ).to(device) n_bins[0] = 1.5 n_bins[-1] = 1.33*bins[-1] # above last threshold is ignored max_bin_allowed = torch.tensor(n_bins.shape[0]-1).to(device).long() # calculate measures of centrality and dispersion - magnitudes = distogram.sum(dim=-1) if center == "median": cum_dist = torch.cumsum(distogram, dim=-1) medium = 0.5 * cum_dist[..., -1:] central = torch.searchsorted(cum_dist, medium).squeeze() central = n_bins[ torch.min(central, max_bin_allowed) ] elif center == "mean": central = (distogram * n_bins).sum(dim=-1) / magnitudes # create mask for last class - (IGNORE_INDEX) mask = (central <= bins[-2].item()).float() # mask diagonal to 0 dist - don't do masked filling to avoid inplace errors diag_idxs = np.arange(shape[-2]) central = expand_dims_to(central, 3 - len(central.shape)) central[:, diag_idxs, diag_idxs] *= 0. # provide weights if wide == "var": dispersion = (distogram * (n_bins - central.unsqueeze(-1))**2).sum(dim=-1) / magnitudes elif wide == "std": dispersion = ((distogram * (n_bins - central.unsqueeze(-1))**2).sum(dim=-1) / magnitudes).sqrt() else: dispersion = torch.zeros_like(central, device=device) # rescale to 0-1. lower std / var --> weight=1. set potential nan's to 0 weights = mask / (1+dispersion) weights[weights != weights] *= 0. weights[:, diag_idxs, diag_idxs] *= 0. return central, weights # distance matrix to 3d coords: https://github.com/scikit-learn/scikit-learn/blob/42aff4e2e/sklearn/manifold/_mds.py#L279 def mds_torch(pre_dist_mat, weights=None, iters=10, tol=1e-5, eigen=False, verbose=2): """ Gets distance matrix. Outputs 3d. See below for wrapper. Assumes (for now) distogram is (N x N) and symmetric Outs: * best_3d_coords: (batch x 3 x N) * historic_stresses: (batch x steps) """ device, dtype = pre_dist_mat.device, pre_dist_mat.type() # ensure batched MDS pre_dist_mat = expand_dims_to(pre_dist_mat, length = ( 3 - len(pre_dist_mat.shape) )) # start batch, N, _ = pre_dist_mat.shape diag_idxs = np.arange(N) his = [torch.tensor([np.inf]*batch, device=device)] # initialize by eigendecomposition: https://www.lptmc.jussieu.fr/user/lesne/bioinformatics.pdf #follow : https://www.biorxiv.org/content/10.1101/2020.11.27.401232v1.full.pdf D = pre_dist_mat**2 M = 0.5 * (D[:, :1, :] + D[:, :, :1] - D) # do loop svd bc it's faster: (2-3x in CPU and 1-2x in GPU) #https://discuss.pytorch.org/t/batched-svd-lowrank-being-much-slower-than-loop-implementation-both-cpu-and-gpu/119336 svds = [torch.svd_lowrank(mi) for mi in M] u = torch.stack([svd[0] for svd in svds], dim=0) s = torch.stack([svd[1] for svd in svds], dim=0) v = torch.stack([svd[2] for svd in svds], dim=0) best_3d_coords = torch.bmm(u, torch.diag_embed(s).sqrt())[..., :3] # only eigen - way faster but not weights if weights is None and eigen==True: return torch.transpose( best_3d_coords, -1, -2), torch.zeros_like(torch.stack(his, dim=0)) elif eigen==True: if verbose: print("Can't use eigen flag if weights are active. Fallback to iterative") #continue the iterative way if weights is None: weights = torch.ones_like(pre_dist_mat) # iterative updates: for i in range(iters): # compute distance matrix of coords and stress best_3d_coords = best_3d_coords.contiguous() dist_mat = torch.cdist(best_3d_coords, best_3d_coords, p=2).clone() stress = ( weights * (dist_mat - pre_dist_mat)**2 ).sum(dim=(-1,-2)) * 0.5 # perturb - update X using the Guttman transform - sklearn-like dist_mat[ dist_mat <= 0 ] += 1e-7 ratio = weights * (pre_dist_mat / dist_mat) B = -ratio B[:, diag_idxs, diag_idxs] += ratio.sum(dim=-1) # update coords = (1. / N * torch.matmul(B, best_3d_coords)) dis = torch.norm(coords, dim=(-1, -2)) if verbose >= 2: print('it: %d, stress %s' % (i, stress)) # update metrics if relative improvement above tolerance if (his[-1] - stress / dis).mean() <= tol: if verbose: print('breaking at iteration %d with stress %s' % (i, stress / dis)) break best_3d_coords = coords his.append( stress / dis ) return torch.transpose(best_3d_coords, -1,-2), torch.stack(his, dim=0) def mds_numpy(pre_dist_mat, weights=None, iters=10, tol=1e-5, eigen=False, verbose=2): """ Gets distance matrix. Outputs 3d. See below for wrapper. Assumes (for now) distrogram is (N x N) and symmetric Out: * best_3d_coords: (3 x N) * historic_stress """ if weights is None: weights = np.ones_like(pre_dist_mat) # ensure batched MDS pre_dist_mat = expand_dims_to(pre_dist_mat, length = ( 3 - len(pre_dist_mat.shape) )) # start batch, N, _ = pre_dist_mat.shape his = [np.inf] # init random coords best_stress = np.inf * np.ones(batch) best_3d_coords = 2*np.random.rand(batch, 3, N) - 1 # iterative updates: for i in range(iters): # compute distance matrix of coords and stress dist_mat = np.linalg.norm(best_3d_coords[:, :, :, None] - best_3d_coords[:, :, None, :], axis=-3) stress = (( weights * (dist_mat - pre_dist_mat) )**2).sum(axis=(-1, -2)) * 0.5 # perturb - update X using the Guttman transform - sklearn-like dist_mat[dist_mat == 0] = 1e-7 ratio = weights * (pre_dist_mat / dist_mat) B = -ratio B[:, np.arange(N), np.arange(N)] += ratio.sum(axis=-1) # update - double transpose. TODO: consider fix coords = (1. / N * np.matmul(best_3d_coords, B)) dis = np.linalg.norm(coords, axis=(-1, -2)) if verbose >= 2: print('it: %d, stress %s' % (i, stress)) # update metrics if relative improvement above tolerance if (best_stress - stress / dis).mean() <= tol: if verbose: print('breaking at iteration %d with stress %s' % (i, stress / dis)) break best_3d_coords = coords best_stress = stress / dis his.append(best_stress) return best_3d_coords, np.array(his) def get_dihedral_torch(c1, c2, c3, c4): """ Returns the dihedral angle in radians. Will use atan2 formula from: https://en.wikipedia.org/wiki/Dihedral_angle#In_polymer_physics Can't use torch.dot bc it does not broadcast Inputs: * c1: (batch, 3) or (3,) * c1: (batch, 3) or (3,) * c1: (batch, 3) or (3,) * c1: (batch, 3) or (3,) """ u1 = c2 - c1 u2 = c3 - c2 u3 = c4 - c3 return torch.atan2( ( (torch.norm(u2, dim=-1, keepdim=True) * u1) * torch.cross(u2,u3, dim=-1) ).sum(dim=-1) , ( torch.cross(u1,u2, dim=-1) * torch.cross(u2, u3, dim=-1) ).sum(dim=-1) ) def get_dihedral_numpy(c1, c2, c3, c4): """ Returns the dihedral angle in radians. Will use atan2 formula from: https://en.wikipedia.org/wiki/Dihedral_angle#In_polymer_physics Inputs: * c1: (batch, 3) or (3,) * c1: (batch, 3) or (3,) * c1: (batch, 3) or (3,) * c1: (batch, 3) or (3,) """ u1 = c2 - c1 u2 = c3 - c2 u3 = c4 - c3 return np.arctan2( ( (np.linalg.norm(u2, axis=-1, keepdims=True) * u1) * np.cross(u2,u3, axis=-1)).sum(axis=-1), ( np.cross(u1,u2, axis=-1) * np.cross(u2, u3, axis=-1) ).sum(axis=-1) ) def calc_phis_torch(pred_coords, N_mask, CA_mask, C_mask=None, prop=True, verbose=0): """ Filters mirrors selecting the 1 with most N of negative phis. Used as part of the MDScaling wrapper if arg is passed. See below. Angle Phi between planes: (Cterm{-1}, N, Ca{0}) and (N{0}, Ca{+1}, Cterm{+1}) Inputs: * pred_coords: (batch, 3, N) predicted coordinates * N_mask: (batch, N) boolean mask for N-term positions * CA_mask: (batch, N) boolean mask for C-alpha positions * C_mask: (batch, N) or None. boolean mask for C-alpha positions or automatically calculate from N_mask and CA_mask if None. * prop: bool. whether to return as a proportion of negative phis. * verbose: bool. verbosity level Output: (batch, N) containing the phi angles or (batch,) containing the proportions. Note: use [0] since all prots in batch have same backbone """ # detach gradients for angle calculation - mirror selection pred_coords_ = torch.transpose(pred_coords.detach(), -1 , -2).cpu() # ensure dims N_mask = expand_dims_to( N_mask, 2-len(N_mask.shape) ) CA_mask = expand_dims_to( CA_mask, 2-len(CA_mask.shape) ) if C_mask is not None: C_mask = expand_dims_to( C_mask, 2-len(C_mask.shape) ) else: C_mask = torch.logical_not(torch.logical_or(N_mask,CA_mask)) # select points n_terms = pred_coords_[:, N_mask[0].squeeze()] c_alphas = pred_coords_[:, CA_mask[0].squeeze()] c_terms = pred_coords_[:, C_mask[0].squeeze()] # compute phis for every pritein in the batch phis = [get_dihedral_torch(c_terms[i, :-1], n_terms[i, 1:], c_alphas[i, 1:], c_terms[i, 1:]) for i in range(pred_coords.shape[0])] # return percentage of lower than 0 if prop: return torch.tensor( [(x<0).float().mean().item() for x in phis] ) return phis def calc_phis_numpy(pred_coords, N_mask, CA_mask, C_mask=None, prop=True, verbose=0): """ Filters mirrors selecting the 1 with most N of negative phis. Used as part of the MDScaling wrapper if arg is passed. See below. Angle Phi between planes: (Cterm{-1}, N, Ca{0}) and (N{0}, Ca{+1}, Cterm{+1}) Inputs: * pred_coords: (batch, 3, N) predicted coordinates * N_mask: (N, ) boolean mask for N-term positions * CA_mask: (N, ) boolean mask for C-alpha positions * C_mask: (N, ) or None. boolean mask for C-alpha positions or automatically calculate from N_mask and CA_mask if None. * prop: bool. whether to return as a proportion of negative phis. * verbose: bool. verbosity level Output: (batch, N) containing the phi angles or (batch,) containing the proportions. """ # detach gradients for angle calculation - mirror selection pred_coords_ = np.transpose(pred_coords, (0, 2, 1)) n_terms = pred_coords_[:, N_mask.squeeze()] c_alphas = pred_coords_[:, CA_mask.squeeze()] # select c_term auto if not passed if C_mask is not None: c_terms = pred_coords_[:, C_mask] else: c_terms = pred_coords_[:, (np.ones_like(N_mask)-N_mask-CA_mask).squeeze().astype(bool) ] # compute phis for every pritein in the batch phis = [get_dihedral_numpy(c_terms[i, :-1], n_terms[i, 1:], c_alphas[i, 1:], c_terms[i, 1:]) for i in range(pred_coords.shape[0])] # return percentage of lower than 0 if prop: return np.array( [(x<0).mean() for x in phis] ) return phis #alignment by centering + rotation to compute optimal RMSD #adapted from : https://github.com/charnley/rmsd/ def kabsch_torch(X, Y, cpu=True): """ Kabsch alignment of X into Y. Assumes X,Y are both (Dims x N_points). See below for wrapper. """ device = X.device # center X and Y to the origin X_ = X - X.mean(dim=-1, keepdim=True) Y_ = Y - Y.mean(dim=-1, keepdim=True) # calculate convariance matrix (for each prot in the batch) C = torch.matmul(X_, Y_.t()).detach() if cpu: C = C.cpu() # Optimal rotation matrix via SVD if int(torch.__version__.split(".")[1]) < 8: #warning! int torch 1.<8 : W must be transposed V, S, W = torch.svd(C) W = W.t() else: V, S, W = torch.linalg.svd(C) # determinant sign for direction correction d = (torch.det(V) * torch.det(W)) < 0.0 if d: S[-1] = S[-1] * (-1) V[:, -1] = V[:, -1] * (-1) # Create Rotation matrix U U = torch.matmul(V, W).to(device) # calculate rotations X_ = torch.matmul(X_.t(), U).t() # return centered and aligned return X_, Y_ def kabsch_numpy(X, Y): """ Kabsch alignment of X into Y. Assumes X,Y are both (Dims x N_points). See below for wrapper. """ # center X and Y to the origin X_ = X - X.mean(axis=-1, keepdims=True) Y_ = Y - Y.mean(axis=-1, keepdims=True) # calculate convariance matrix (for each prot in the batch) C = np.dot(X_, Y_.transpose()) # Optimal rotation matrix via SVD V, S, W = np.linalg.svd(C) # determinant sign for direction correction d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0 if d: S[-1] = S[-1] * (-1) V[:, -1] = V[:, -1] * (-1) # Create Rotation matrix U U = np.dot(V, W) # calculate rotations X_ = np.dot(X_.T, U).T # return centered and aligned return X_, Y_ # metrics - more formulas here: http://predictioncenter.org/casp12/doc/help.html def distmat_loss_torch(X=None, Y=None, X_mat=None, Y_mat=None, p=2, q=2, custom=None, distmat_mask=None): """ Calculates a loss on the distance matrix - no need to align structs. Inputs: * X: (N, d) tensor. the predicted structure. One of (X, X_mat) is needed. * X_mat: (N, N) tensor. the predicted distance matrix. Optional () * Y: (N, d) tensor. the true structure. One of (Y, Y_mat) is needed. * Y_mat: (N, N) tensor. the predicted distance matrix. Optional () * p: int. power for the distance calculation (2 for euclidean) * q: float. power for the scaling of the loss (2 for MSE, 1 for MAE, etc) * custom: func or None. custom loss over distance matrices. ex: lambda x,y: 1 - 1/ (1 + ((x-y))**2) (1 is very bad. 0 is good) * distmat_mask: (N, N) mask (boolean or weights for each ij pos). optional. """ assert (X is not None or X_mat is not None) and \ (Y is not None or Y_mat is not None), "The true and predicted coords or dist mats must be provided" #calculate distance matrices if X_mat is None: X_mat = torch.cdist(X, X, p=p) if Y_mat is None: Y_mat = torch.cdist(Y, Y, p=p) if distmat_mask is None: distmat_mask = torch.ones_like(Y_mat).bool() #do custom expression if passed if custom is not None: loss = custom(X_mat, Y_mat).mean() #**2 ensures always positive. Later scale back to desired power else: loss = ( X_mat - Y_mat )**2 if q != 2: loss = loss**(q/2) return loss[distmat_mask].mean() def rmsd_torch(X, Y): """ Assumes x,y are both (B x D x N). See below for wrapper. """ return torch.sqrt( torch.mean((X - Y)**2, axis=(-1, -2)) ) def rmsd_numpy(X, Y): """ Assumes x,y are both (B x D x N). See below for wrapper. """ return np.sqrt( np.mean((X - Y)**2, axis=(-1, -2)) ) def gdt_torch(X, Y, cutoffs, weights=None): """ Assumes x,y are both (B x D x N). see below for wrapper. * cutoffs is a list of `K` thresholds * weights is a list of `K` weights (1 x each threshold) """ device = X.device if weights is None: weights = torch.ones(1,len(cutoffs)) else: weights = torch.tensor([weights]).to(device) # set zeros and fill with values GDT = torch.zeros(X.shape[0], len(cutoffs), device=device) dist = ((X - Y)**2).sum(dim=1).sqrt() # iterate over thresholds for i,cutoff in enumerate(cutoffs): GDT[:, i] = (dist <= cutoff).float().mean(dim=-1) # weighted mean return (GDT*weights).mean(-1) def gdt_numpy(X, Y, cutoffs, weights=None): """ Assumes x,y are both (B x D x N). see below for wrapper. * cutoffs is a list of `K` thresholds * weights is a list of `K` weights (1 x each threshold) """ if weights is None: weights = np.ones( (1,len(cutoffs)) ) else: weights = np.array([weights]) # set zeros and fill with values GDT = np.zeros( (X.shape[0], len(cutoffs)) ) dist = np.sqrt( ((X - Y)**2).sum(axis=1) ) # iterate over thresholds for i,cutoff in enumerate(cutoffs): GDT[:, i] = (dist <= cutoff).mean(axis=-1) # weighted mean return (GDT*weights).mean(-1) def tmscore_torch(X, Y): """ Assumes x,y are both (B x D x N). see below for wrapper. """ L = X.shape[-1] d0 = 1.24 * np.cbrt(L - 15) - 1.8 # get distance dist = ((X - Y)**2).sum(dim=1).sqrt() # formula (see wrapper for source): return (1 / (1 + (dist/d0)**2)).mean(dim=-1) def tmscore_numpy(X, Y): """ Assumes x,y are both (B x D x N). see below for wrapper. """ L = X.shape[-1] d0 = 1.24 * np.cbrt(L - 15) - 1.8 # get distance dist = np.sqrt( ((X - Y)**2).sum(axis=1) ) # formula (see wrapper for source): return (1 / (1 + (dist/d0)**2)).mean(axis=-1) def mdscaling_torch(pre_dist_mat, weights=None, iters=10, tol=1e-5, fix_mirror=True, N_mask=None, CA_mask=None, C_mask=None, eigen=False, verbose=2): """ Handles the specifics of MDS for proteins (mirrors, ...) """ #batched mds for full parallel preds, stresses = mds_torch(pre_dist_mat, weights=weights,iters=iters, tol=tol, eigen=eigen, verbose=verbose) if not fix_mirror: return preds, stresses # no need to caculate multiple mirrors - just correct Z axis phi_ratios = calc_phis_torch(preds, N_mask, CA_mask, C_mask, prop=True) to_correct = torch.nonzero( (phi_ratios < 0.5)).view(-1) # fix mirrors by (-1)*Z if more (+) than (-) phi angles preds[to_correct, -1] = (-1)*preds[to_correct, -1] if verbose == 2: print("Corrected mirror idxs:", to_correct) return preds, stresses def mdscaling_numpy(pre_dist_mat, weights=None, iters=10, tol=1e-5, fix_mirror=True, N_mask=None, CA_mask=None, C_mask=None, verbose=2): """ Handles the specifics of MDS for proteins (mirrors, ...) """ #batched mds for full parallel preds, stresses = mds_numpy(pre_dist_mat, weights=weights,iters=iters, tol=tol, verbose=verbose) if not fix_mirror: return preds, stresses # no need to caculate multiple mirrors - just correct Z axis phi_ratios = calc_phis_numpy(preds, N_mask, CA_mask, C_mask, prop=True) for i,pred in enumerate(preds): # fix mirrors by (-1)*Z if more (+) than (-) phi angles if phi_ratios < 0.5: preds[i, -1] = (-1)*preds[i, -1] if verbose == 2: print("Corrected mirror in struct no.", i) return preds, stresses def lddt_ca_torch(true_coords, pred_coords, cloud_mask, r_0=15.): """ Computes the lddt score for each C_alpha. https://academic.oup.com/bioinformatics/article/29/21/2722/195896 Inputs: * true_coords: (b, l, c, d) in sidechainnet format. * pred_coords: (b, l, c, d) in sidechainnet format. * cloud_mask : (b, l, c) adapted for scn format. * r_0: float. maximum inclusion radius in reference struct. Outputs: * (b, l) lddt for c_alpha scores (ranging between 0 and 1) See wrapper below. """ device, dtype = true_coords.device, true_coords.type() thresholds = torch.tensor([0.5, 1, 2, 4], device=device).type(dtype) # adapt masks cloud_mask = cloud_mask.bool().cpu() c_alpha_mask = torch.zeros(cloud_mask.shape[1:], device=device).bool() # doesn't have batch dim c_alpha_mask[..., 1] = True # container for c_alpha scores (between 0,1) wrapper = torch.zeros(true_coords.shape[:2], device=device).type(dtype) for bi, seq in enumerate(true_coords): # select atoms for study c_alphas = cloud_mask[bi]*c_alpha_mask #only pick c_alpha positions selected_pred = pred_coords[bi, c_alphas, :] selected_target = true_coords[bi, c_alphas, :] # get number under distance dist_mat_pred = torch.cdist(selected_pred, selected_pred, p=2) dist_mat_target = torch.cdist(selected_target, selected_target, p=2) under_r0_target = dist_mat_target < r_0 compare_dists = torch.abs(dist_mat_pred - dist_mat_target)[under_r0_target] # measure diff below threshold score = torch.zeros_like(under_r0_target).float() max_score = torch.zeros_like(under_r0_target).float() max_score[under_r0_target] = 4. #measure under how many thresholds score[under_r0_target] = thresholds.shape[0] - \ torch.bucketize( compare_dists, boundaries=thresholds ).float() # dont include diagonal l_mask = c_alphas.float().sum(dim=-1).bool() wrapper[bi, l_mask] = ( score.sum(dim=-1) - thresholds.shape[0] ) / \ ( max_score.sum(dim=-1) - thresholds.shape[0] ) return wrapper ################ ###WRAPPERS ### ################
[ 2, 3384, 4487, 329, 1762, 351, 513, 67, 12, 48693, 8573, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 304, 259, 2840, 1330, 37825, 858, 11, 9585, 198, 2...
2.212179
20,002
__author__ = 'walthermaciel' import pandas as pd import numpy as np if __name__ == '__main__': main()
[ 834, 9800, 834, 796, 705, 16783, 490, 20285, 8207, 6, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, ...
2.511628
43
""" Interfaces with Verisure sensors. For more details about this platform, please refer to the documentation at documentation at https://home-assistant.io/components/verisure/ """ import logging from homeassistant.components.verisure import HUB as hub from homeassistant.const import TEMP_CELSIUS from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Verisure platform.""" sensors = [] if int(hub.config.get('thermometers', '1')): hub.update_climate() sensors.extend([ VerisureThermometer(value.id) for value in hub.climate_status.values() if hasattr(value, 'temperature') and value.temperature ]) if int(hub.config.get('hygrometers', '1')): hub.update_climate() sensors.extend([ VerisureHygrometer(value.id) for value in hub.climate_status.values() if hasattr(value, 'humidity') and value.humidity ]) if int(hub.config.get('mouse', '1')): hub.update_mousedetection() sensors.extend([ VerisureMouseDetection(value.deviceLabel) for value in hub.mouse_status.values() # is this if needed? if hasattr(value, 'amountText') and value.amountText ]) add_devices(sensors) class VerisureHygrometer(Entity): """Representation of a Verisure hygrometer.""" def __init__(self, device_id): """Initialize the sensor.""" self._id = device_id def update(self): """Update the sensor.""" hub.update_climate() class VerisureMouseDetection(Entity): """Representation of a Verisure mouse detector.""" def __init__(self, device_id): """Initialize the sensor.""" self._id = device_id def update(self): """Update the sensor.""" hub.update_mousedetection()
[ 37811, 198, 9492, 32186, 351, 4643, 20609, 15736, 13, 198, 198, 1890, 517, 3307, 546, 428, 3859, 11, 3387, 3522, 284, 262, 10314, 379, 198, 22897, 341, 379, 3740, 1378, 11195, 12, 562, 10167, 13, 952, 14, 5589, 3906, 14, 332, 20609, ...
2.455335
806
import factory from factory.django import DjangoModelFactory as Factory from django.contrib.auth.models import Permission from ..models import Blog from articles.users.tests.factories import UserFactory
[ 11748, 8860, 198, 198, 6738, 8860, 13, 28241, 14208, 1330, 37770, 17633, 22810, 355, 19239, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 2448, 3411, 198, 198, 6738, 11485, 27530, 1330, 14001, 198, 6738, 6685, 13, ...
4.078431
51
from datetime import datetime from django.urls import reverse from rest_framework import serializers from .view_helpers import description_from_notes
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 764, 1177, 62, 16794, 364, 1330, 6764, 62, 6738, 62, 17815, 628, 628, 628, 628...
3.5
50
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-23 19:58 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 24, 13, 20, 319, 1584, 12, 2931, 12, 1954, 678, 25, 3365, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 19...
2.863014
73
from mopidy import httpclient from mopidy.internal.gi import Gst def calculate_duration(num_samples, sample_rate): """Determine duration of samples using GStreamer helper for precise math.""" return Gst.util_uint64_scale(num_samples, Gst.SECOND, sample_rate) def create_buffer(data, timestamp=None, duration=None): """Create a new GStreamer buffer based on provided data. Mainly intended to keep gst imports out of non-audio modules. .. versionchanged:: 2.0 ``capabilites`` argument was removed. """ if not data: raise ValueError("Cannot create buffer without data") buffer_ = Gst.Buffer.new_wrapped(data) if timestamp is not None: buffer_.pts = timestamp if duration is not None: buffer_.duration = duration return buffer_ def millisecond_to_clocktime(value): """Convert a millisecond time to internal GStreamer time.""" return value * Gst.MSECOND def clocktime_to_millisecond(value): """Convert an internal GStreamer time to millisecond time.""" return value // Gst.MSECOND def supported_uri_schemes(uri_schemes): """Determine which URIs we can actually support from provided whitelist. :param uri_schemes: list/set of URIs to check support for. :type uri_schemes: list or set or URI schemes as strings. :rtype: set of URI schemes we can support via this GStreamer install. """ supported_schemes = set() registry = Gst.Registry.get() for factory in registry.get_feature_list(Gst.ElementFactory): for uri in factory.get_uri_protocols(): if uri in uri_schemes: supported_schemes.add(uri) return supported_schemes def setup_proxy(element, config): """Configure a GStreamer element with proxy settings. :param element: element to setup proxy in. :type element: :class:`Gst.GstElement` :param config: proxy settings to use. :type config: :class:`dict` """ if not hasattr(element.props, "proxy") or not config.get("hostname"): return element.set_property("proxy", httpclient.format_proxy(config, auth=False)) element.set_property("proxy-id", config.get("username")) element.set_property("proxy-pw", config.get("password"))
[ 6738, 285, 404, 19325, 1330, 2638, 16366, 198, 6738, 285, 404, 19325, 13, 32538, 13, 12397, 1330, 402, 301, 628, 198, 4299, 15284, 62, 32257, 7, 22510, 62, 82, 12629, 11, 6291, 62, 4873, 2599, 198, 220, 220, 220, 37227, 35, 2357, 38...
2.84005
794
#!/usr/bin/env python3 import re with open("input.txt") as f: content = f.read().strip() ans = "" i = 0 while i < len(content): if content[i] == "(": end = content[i:].find(")") + i instr = content[i+1:end] chars, times = map(int, content[i+1:end].split("x")) to_copy = content[end+1:end+1+chars] ans += times * to_copy i = end + 1 + chars else: ans += content[i] i += 1 print(len(ans))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 302, 628, 198, 4480, 1280, 7203, 15414, 13, 14116, 4943, 355, 277, 25, 198, 220, 220, 220, 2695, 796, 277, 13, 961, 22446, 36311, 3419, 198, 198, 504, 796, 13538, 198...
2.057269
227
# ---------------------------------------------------------------------- # Alcatel.AOS.get_inventory # ---------------------------------------------------------------------- # Copyright (C) 2007-2014 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Python modules import re # NOC modules from noc.core.script.base import BaseScript from noc.sa.interfaces.igetinventory import IGetInventory
[ 2, 16529, 23031, 198, 2, 43757, 25791, 13, 32, 2640, 13, 1136, 62, 24807, 198, 2, 16529, 23031, 198, 2, 15069, 357, 34, 8, 4343, 12, 4967, 383, 399, 4503, 4935, 198, 2, 4091, 38559, 24290, 329, 3307, 198, 2, 16529, 23031, 198, 198...
5.238636
88
import sqlite3
[ 11748, 44161, 578, 18 ]
3.5
4
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright 2018 ARM Ltd. # # SPDX-License-Identifier: Apache-2.0 # # 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 cbor2 import struct from pyclibrary import CParser from collections import namedtuple CERTIFICATE_KEYS = ('MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_CERTIFICATE', 'MBED_CLOUD_DEV_BOOTSTRAP_SERVER_ROOT_CA_CERTIFICATE', 'arm_uc_default_certificate') KEY_KEYS = ('MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_PRIVATE_KEY') UPDATE_KEYS = ('arm_uc_default_certificate', 'arm_uc_class_id', 'arm_uc_vendor_id') KEY_MAP = { 'MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_CERTIFICATE': 'mbed.BootstrapDeviceCert', 'MBED_CLOUD_DEV_BOOTSTRAP_SERVER_ROOT_CA_CERTIFICATE': 'mbed.BootstrapServerCACert', 'MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_PRIVATE_KEY': 'mbed.BootstrapDevicePrivateKey', 'MBED_CLOUD_DEV_BOOTSTRAP_ENDPOINT_NAME': 'mbed.EndpointName', 'MBED_CLOUD_DEV_BOOTSTRAP_SERVER_URI': 'mbed.BootstrapServerURI', 'MBED_CLOUD_DEV_ACCOUNT_ID': 'mbed.AccountID', 'MBED_CLOUD_DEV_MANUFACTURER': 'mbed.Manufacturer', 'MBED_CLOUD_DEV_MODEL_NUMBER': 'mbed.ModelNumber', 'MBED_CLOUD_DEV_SERIAL_NUMBER': 'mbed.SerialNumber', 'MBED_CLOUD_DEV_DEVICE_TYPE': 'mbed.DeviceType', 'MBED_CLOUD_DEV_HARDWARE_VERSION': 'mbed.HardwareVersion', 'MBED_CLOUD_DEV_MEMORY_TOTAL_KB': 'mbed.MemoryTotalKB', 'arm_uc_default_certificate': 'mbed.UpdateAuthCert', 'arm_uc_class_id': 'mbed.ClassId', 'arm_uc_vendor_id': 'mbed.VendorId' } ConfigParam = namedtuple('ConfigParam', ['Data', 'Name']) Certificate = namedtuple('Certificate', ['Data', 'Format', 'Name']) Key = namedtuple('Key', ['Data', 'Format', 'Name', 'Type'])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 16529, 10541, 198, 2, 15069, 2864, 20359, 12052, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 198, 2, 49962, 739, 262, 24...
2.570506
929
# -*- coding: utf-8 -*- # Copyright 2019 Google Inc. # # 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. """Tests for the Archive processor to compress and decompress folders.""" from __future__ import unicode_literals import os import tarfile import unittest import tempfile from random import randint from shutil import rmtree from turbinia.processors import archive from turbinia import TurbiniaException if __name__ == '__main__': unittest.main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 13130, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428...
3.627376
263
from utils import database
[ 6738, 3384, 4487, 1330, 6831 ]
5.2
5
from .test_db import TestDal
[ 6738, 764, 9288, 62, 9945, 1330, 6208, 35, 282, 198 ]
2.9
10
from django.db import models # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 2, 13610, 534, 4981, 994, 13 ]
3.733333
15
import numpy as np import tectosaur.util.gpu as gpu from tectosaur.fmm.c2e import build_c2e import logging logger = logging.getLogger(__name__)
[ 11748, 299, 32152, 355, 45941, 198, 198, 11748, 256, 478, 418, 2899, 13, 22602, 13, 46999, 355, 308, 19944, 198, 6738, 256, 478, 418, 2899, 13, 69, 3020, 13, 66, 17, 68, 1330, 1382, 62, 66, 17, 68, 198, 198, 11748, 18931, 198, 640...
2.561404
57
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Project: Fable Input Output # https://github.com/silx-kit/fabio # # Copyright (C) European Synchrotron Radiation Facility, Grenoble, France # # Principal author: Jrme Kieffer (Jerome.Kieffer@ESRF.eu) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Multiwire Unit tests""" from __future__ import print_function, with_statement, division, absolute_import import unittest import logging logger = logging.getLogger(__name__) import fabio from ..utilstest import UtilsTest if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(suite())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 220, 220, 4935, 25, 376, 540, 23412, 25235, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
3.011905
420
# -*- coding: utf-8 -*- import scrapy import codecs import sys # utf-8 utf-8 reload(sys) sys.setdefaultencoding('utf8') # scrapy spider crawling/scrapping #crawling/scrapping
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 15881, 88, 198, 11748, 40481, 82, 198, 11748, 25064, 198, 2, 3384, 69, 12, 23, 220, 220, 220, 220, 220, 220, 220, 3384, 69, 12, 23, 220, 220, 198, 260, 2220, ...
2.204545
88
import numpy as np import pandas as pd from feature_engine.sanity_check import SimilarColumns
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 3895, 62, 18392, 13, 12807, 414, 62, 9122, 1330, 11014, 39470, 82, 628, 198 ]
3.344828
29
import __init__ import os #os.environ['LD_LIBRARY_PATH'] += ':/usr/local/cuda-11.1/bin64:/usr/local/cuda-11.2/bin64' import numpy as np import torch import torch.multiprocessing as mp import torch_geometric.datasets as GeoData from torch_geometric.loader import DenseDataLoader import torch_geometric.transforms as T from torch.nn.parallel import DistributedDataParallel from torch.utils.data.distributed import DistributedSampler from config import OptInit from architecture import DenseDeepGCN, CustomDenseDeepGCN from utils.ckpt_util import load_pretrained_models, load_pretrained_optimizer, save_checkpoint from utils.metrics import AverageMeter import logging from tqdm import tqdm from parallel_wrapper import launch import comm from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter(log_dir='log/mlp4') if __name__ == '__main__': main()
[ 198, 11748, 11593, 15003, 834, 198, 11748, 28686, 198, 198, 2, 418, 13, 268, 2268, 17816, 11163, 62, 40347, 49, 13153, 62, 34219, 20520, 15853, 705, 14079, 14629, 14, 12001, 14, 66, 15339, 12, 1157, 13, 16, 14, 8800, 2414, 14079, 1462...
3.151079
278
import tkinter as tk from tkinter import ttk win = tk.Tk() win.title("Python GUI") win.resizable(False, False) win.configure(background = "grey94") a_label = ttk.Label(win, text = "Gib Deinen Namen ein:") a_label.grid(column = 0, row = 0) a_label.grid_configure(padx = 8, pady = 8) name = tk.StringVar() name_entered = ttk.Entry(win, width = 12, textvariable = name) name_entered.grid(column = 0, row = 1) name_entered.grid_configure(padx = 8, pady = 8) name_entered.focus() action = ttk.Button(win, text = "Drck mich!", command = clickMe) action.grid(column = 1, row = 1) action.grid_configure(padx = 8, pady = 8) win.mainloop()
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 6738, 256, 74, 3849, 1330, 256, 30488, 198, 198, 5404, 796, 256, 74, 13, 51, 74, 3419, 198, 5404, 13, 7839, 7203, 37906, 25757, 4943, 198, 5404, 13, 411, 13821, 7, 25101, 11, 10352, 8, 198,...
2.490196
255
""" Initialise the Celery instance to be used by the application This is largely just boiler plate, and we could probably look at coming back to it and cleaning it up a bit in the future. """ from __future__ import absolute_import from celery import Celery celery = Celery() from openarticlegauge import celeryconfig celery.config_from_object(celeryconfig) # Optional configuration, see the application user guide. celery.conf.update( CELERY_TASK_RESULT_EXPIRES=3600, ) if __name__ == '__main__': celery.start()
[ 37811, 198, 24243, 786, 262, 15248, 1924, 4554, 284, 307, 973, 416, 262, 3586, 198, 198, 1212, 318, 5688, 655, 36741, 7480, 11, 290, 356, 714, 2192, 804, 379, 2406, 736, 284, 340, 290, 12724, 340, 198, 929, 257, 1643, 287, 262, 2003...
3.180723
166
#! /usr/bin/env python # call roscore # $ roscore # # If start in manual # $ rosrun cbf_ros cbf_controller.py import rospy import sys import argparse import re import numpy as np from scipy.integrate import odeint from sympy import symbols, Matrix, sin, cos, lambdify, exp, sqrt, log import matplotlib.pyplot as plt import matplotlib.animation as animation import cvxopt as cvxopt # ROS msg from geometry_msgs.msg import Twist from geometry_msgs.msg import PoseStamped from geometry_msgs.msg import Vector3 from nav_msgs.msg import Odometry from gazebo_msgs.msg import ModelState from gazebo_msgs.srv import GetWorldProperties, GetModelState, GetModelStateRequest # ROS others import tf DEBUG = False if __name__ == '__main__': ## Parameters findBestCommandAnyway = 1 #make this zero if you don't want to do anything if it's riskier than intended #use 1 if you want to do the best even if there is risk plotanimation = 0 # Goal info GoalCenter = np.array([0, 0]) rGoal = np.power(0.5,2) # Unsafe UnsafeInclude = 9 # consider obstacle if in radius UnsafeRadius = 0.5 #radius of unsafe sets/distance from obstacles # Enviroment Bounds env_bounds = type('', (), {})() env_bounds.y_min = -1.2 env_bounds.y_max = 1 # env_bounds.x_max = 1.25 # env_bounds.x_min = -1.35 l = 0.01 #bicycle model approximation parameter U = np.array([[-0.33,0.33],[-0.3,0.3]]) T = 1 #Lookahead horizon risk = 0.1 # max risk desired gamma = 5 # CBF coefficient u1d = 0 # desired input to save energy! # Plotting options plotit = 1 plotlanes = 1 robot = robot(l) GoalInfo = robot.GoalFuncs(GoalCenter,rGoal) UnsafeInfo = robot.UnsafeFuncs(gamma,UnsafeRadius) MapInfo = robot.MapFuncs(env_bounds) # Process arguments p = argparse.ArgumentParser(description='CBF controller') args = p.parse_args(rospy.myargv()[1:]) try: rospy.init_node('cbf_controller') cbf_controller = CBF_CONTROLLER(robot,GoalInfo,UnsafeInfo,MapInfo) control_priod = 0.05 #[sec] we can change controll priod with this parameter. rospy.Timer(rospy.Duration(control_priod), cbf_controller.controller_loop_callback) rospy.spin() except rospy.ROSInterruptException: pass plottrajs(cbf_controller.trajs)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 869, 686, 26675, 198, 2, 720, 686, 26675, 198, 2, 198, 2, 1002, 923, 287, 10107, 198, 2, 720, 686, 82, 5143, 269, 19881, 62, 4951, 269, 19881, 62, 36500, 13, 9078, 198, 1174...
2.176664
1,217
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'src/gui/ui_paste_dialog.ui' # # Created by: PyQt5 UI code generator 5.11.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 10677, 14, 48317, 14, 9019, 62, 34274, 62, 38969, 519, 13, 9019, 6, 198, 2, 198, 2, 15622, 416, 25, 9485, ...
2.752688
93
__all__ = ['a_star', 'best_first', 'bi_a_star', 'breadth_first', 'dijkstra', 'finder', 'ida_star']
[ 834, 439, 834, 796, 37250, 64, 62, 7364, 3256, 705, 13466, 62, 11085, 3256, 705, 8482, 62, 64, 62, 7364, 3256, 705, 29573, 400, 62, 11085, 3256, 705, 67, 45961, 12044, 3256, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 7...
2.115385
52
#Uche's test from Sun's SVG slide publisher import os from Xml.Xslt import test_harness #From Sun's toolkit sheet_1_uri = "Xml/Xslt/Borrowed/svgslides.xsl" sheet_2_uri = "Xml/Xslt/Borrowed/svgslides_custom.xsl" sheet_3_uri = "Xml/Xslt/Borrowed/slidescript.xsl" source_1_uri = "Xml/Xslt/Borrowed/slides4svg.xml" saxon_output = """""" expected_1 = """<?xml version='1.0' encoding='UTF-8'?> <?xml-stylesheet href="slides.css" type="text/css"?> <svg height='768' width='1024' style='pointer-events:visible' xml:space='preserve' onload='initSlides(evt)' xmlns:xlink='http://www.w3.org/2000/xlink/namespace/'> <script><![CDATA[ var doc = null; // Called upon presentation loading function initSlides(evt){ var target = evt.getTarget(); doc = target.getOwnerDocument(); hideAndShow(evt, curSlide, curSlide); } function onPrevSlide(evt){ // Process new current slide var oldCurSlide = curSlide; curSlide = curSlide - 1; if(curSlide < 0){ curSlide = slideList.length - 1; } hideAndShow(evt, oldCurSlide, curSlide); } function onNextSlide(evt){ // Process new current slide var prevSlide = curSlide; curSlide = curSlide + 1; if(curSlide > (slideList.length - 1)){ curSlide = 0; } hideAndShow(evt, prevSlide, curSlide); // alert("onNextSlide"); } function hideAndShow(evt, hideSlide, showSlide){ // alert("Hiding : " + hideSlide + " and showing : " + showSlide); // Hide previous current slide and show new // one. var hideSlideName = slideList[hideSlide]; var showSlideName = slideList[showSlide]; /*if(hideSlideName == null) alert("hideSlideName is null"); else alert("hideSlideName is NOT null:" + hideSlideName);*/ var slideGroup = doc.getElementById(hideSlideName); slideGroup.setAttribute("style", "visibility:hidden"); slideGroup = doc.getElementById(showSlideName); slideGroup.setAttribute("style", "visibility:show"); var slideMenuItemId = slideList[hideSlide] + "MenuItem"; var menuItem = doc.getElementById(slideMenuItemId); if(menuItem != null) menuItem.setAttribute("class", "slideMenuItem"); slideMenuItemId = slideList[showSlide] + "MenuItem"; menuItem = doc.getElementById(slideMenuItemId); if(menuItem != null) menuItem.setAttribute("class", "currentSlideMenuItem"); } function onHighlightMenuItem(evt, highlight, itemId){ var target = evt.getTarget(); var doc = target.getOwnerDocument(); var menuItem = doc.getElementById(itemId); if(highlight == "true") menuItem.setAttribute("class", "highlightedSlideMenuItem"); else{ var curSlideMenuItemId = slideList[curSlide] + "MenuItem"; if(curSlideMenuItemId == itemId) menuItem.setAttribute("class", "currentSlideMenuItem"); else menuItem.setAttribute("class", "slideMenuItem"); } } function onMenuItemSelected(evt, index){ // alert("Should show slide # " + index); var oldCurSlide = curSlide; curSlide = index; hideAndShow(evt, oldCurSlide, index); } function onSetFill(evt, elementId, fillValue){ var element = doc.getElementById(elementId); element.setAttribute("style", "fill:" + fillValue); } function onExpand(evt, submenuGroupId){ var submenuGroup = doc.getElementById(submenuGroupId); submenuGroup.setAttribute("style", "visibility:hidden"); var javaScriptCode = "window.expandNow('" + submenuGroupId + "')"; window.expandNow = expandNow; setTimeout(javaScriptCode, 1000); } function expandNow(submenuGroupId){ var submenuGroup = doc.getElementById(submenuGroupId); submenuGroup.setAttribute("style", "visibility:show"); } function onCollapse(evt, submenuGroupId){ var submenuGroup = doc.getElementById(submenuGroupId); submenuGroup.setAttribute("style", "visibility:hidden"); } ]]></script> <script><![CDATA[ var slideList = new Array(); var slideIndex = new Object(); var curSlide = 0; slideList[0]="slideShowCover"; slideIndex["slideShowCover"] = 0; slideList[1]="slidesetCover1"; slideIndex["slidesetCover1"] = 1; slideList[2] = "slide1-1"; slideIndex["slide1-1"] = 2; slideList[3]="slidesetCover2"; slideIndex["slidesetCover2"] = 3; slideList[4] = "slide2-1"; slideIndex["slide2-1"] = 4; slideList[5] = "slide2-2"; slideIndex["slide2-2"] = 5; slideList[6] = "slide2-3"; slideIndex["slide2-3"] = 6; slideList[7]="slidesetCover3"; slideIndex["slidesetCover3"] = 7; slideList[8] = "slide3-1"; slideIndex["slide3-1"] = 8; slideList[9] = "slide3-2"; slideIndex["slide3-2"] = 9; ]]></script> <defs> <linearGradient spreadMethod='pad' id='slideBackgroundPaint' x1='0' y2='768' x2='1024' y1='0' gradientUnits='userSpaceOnUse'> <stop offset='0%' style='stop-color:black; stop-opacity:1;'/> <stop offset='100%' style='stop-color:rgb(103, 107, 157); stop-opacity:1;'/> </linearGradient> <linearGradient spreadMethod='pad' id='slideTitleSeparatorPaint' x1='0' y2='0' x2='1024' y1='0' gradientUnits='userSpaceOnUse'> <stop offset='0%' style='stop-color:rgb(23, 27, 77); stop-opacity:1;'/> <stop offset='.5' style='stop-color:rgb(103, 107, 157); stop-opacity:1;'/> <stop offset='100%' style='stop-color:rgb(23, 27, 77); stop-opacity:1;'/> </linearGradient> <linearGradient spreadMethod='pad' id='menuBarPaint' x1='0' y2='0' x2='210' y1='0' gradientUnits='userSpaceOnUse'> <stop offset='0%' style='stop-color:black; stop-opacity:1;'/> <stop offset='50%' style='stop-color:rgb(103, 107, 157); stop-opacity:1;'/> <stop offset='100%' style='stop-color:white; stop-opacity:1;'/> </linearGradient> <linearGradient spreadMethod='pad' id='slideBackgroundHeaderPaint' x1='0' y2='100' x2='0' y1='0' gradientUnits='userSpaceOnUse'> <stop offset='0%' style='stop-color:black; stop-opacity:1;'/> <stop offset='50%' style='stop-color:rgb(103, 107, 157); stop-opacity:1;'/> <stop offset='100%' style='stop-color:white; stop-opacity:1;'/> </linearGradient> <g id='stripePattern'> <g style='fill:black; fill-opacity:.25'> <rect height='2' width='1' y='0'/> <rect height='2' width='1' y='4'/> <rect height='2' width='1' y='8'/> <rect height='2' width='1' y='12'/> <rect height='2' width='1' y='16'/> <rect height='2' width='1' y='20'/> <rect height='2' width='1' y='24'/> <rect height='2' width='1' y='28'/> <rect height='2' width='1' y='32'/> <rect height='2' width='1' y='36'/> <rect height='2' width='1' y='40'/> <rect height='2' width='1' y='44'/> <rect height='2' width='1' y='48'/> <rect height='2' width='1' y='52'/> <rect height='2' width='1' y='56'/> <rect height='2' width='1' y='60'/> <rect height='2' width='1' y='64'/> <rect height='2' width='1' y='68'/> <rect height='2' width='1' y='72'/> <rect height='2' width='1' y='76'/> <rect height='2' width='1' y='80'/> <rect height='2' width='1' y='84'/> <rect height='2' width='1' y='88'/> <rect height='2' width='1' y='92'/> <rect height='2' width='1' y='96'/> <rect height='2' width='1' y='100'/> <rect height='2' width='1' y='104'/> <rect height='2' width='1' y='108'/> <rect height='2' width='1' y='112'/> <rect height='2' width='1' y='116'/> <rect height='2' width='1' y='120'/> <rect height='2' width='1' y='124'/> <rect height='2' width='1' y='128'/> <rect height='2' width='1' y='132'/> <rect height='2' width='1' y='136'/> <rect height='2' width='1' y='140'/> <rect height='2' width='1' y='144'/> <rect height='2' width='1' y='148'/> <rect height='2' width='1' y='152'/> <rect height='2' width='1' y='156'/> <rect height='2' width='1' y='160'/> <rect height='2' width='1' y='164'/> <rect height='2' width='1' y='168'/> <rect height='2' width='1' y='172'/> <rect height='2' width='1' y='176'/> <rect height='2' width='1' y='180'/> <rect height='2' width='1' y='184'/> <rect height='2' width='1' y='188'/> <rect height='2' width='1' y='192'/> <rect height='2' width='1' y='196'/> <rect height='2' width='1' y='200'/> <rect height='2' width='1' y='204'/> <rect height='2' width='1' y='208'/> <rect height='2' width='1' y='212'/> <rect height='2' width='1' y='216'/> <rect height='2' width='1' y='220'/> <rect height='2' width='1' y='224'/> <rect height='2' width='1' y='228'/> <rect height='2' width='1' y='232'/> <rect height='2' width='1' y='236'/> <rect height='2' width='1' y='240'/> <rect height='2' width='1' y='244'/> <rect height='2' width='1' y='248'/> <rect height='2' width='1' y='252'/> <rect height='2' width='1' y='256'/> <rect height='2' width='1' y='260'/> <rect height='2' width='1' y='264'/> <rect height='2' width='1' y='268'/> <rect height='2' width='1' y='272'/> <rect height='2' width='1' y='276'/> <rect height='2' width='1' y='280'/> <rect height='2' width='1' y='284'/> <rect height='2' width='1' y='288'/> <rect height='2' width='1' y='292'/> <rect height='2' width='1' y='296'/> <rect height='2' width='1' y='300'/> <rect height='2' width='1' y='304'/> <rect height='2' width='1' y='308'/> <rect height='2' width='1' y='312'/> <rect height='2' width='1' y='316'/> <rect height='2' width='1' y='320'/> <rect height='2' width='1' y='324'/> <rect height='2' width='1' y='328'/> <rect height='2' width='1' y='332'/> <rect height='2' width='1' y='336'/> <rect height='2' width='1' y='340'/> <rect height='2' width='1' y='344'/> <rect height='2' width='1' y='348'/> <rect height='2' width='1' y='352'/> <rect height='2' width='1' y='356'/> <rect height='2' width='1' y='360'/> <rect height='2' width='1' y='364'/> <rect height='2' width='1' y='368'/> <rect height='2' width='1' y='372'/> <rect height='2' width='1' y='376'/> <rect height='2' width='1' y='380'/> <rect height='2' width='1' y='384'/> <rect height='2' width='1' y='388'/> <rect height='2' width='1' y='392'/> <rect height='2' width='1' y='396'/> <rect height='2' width='1' y='400'/> <rect height='2' width='1' y='404'/> <rect height='2' width='1' y='408'/> <rect height='2' width='1' y='412'/> <rect height='2' width='1' y='416'/> <rect height='2' width='1' y='420'/> <rect height='2' width='1' y='424'/> <rect height='2' width='1' y='428'/> <rect height='2' width='1' y='432'/> <rect height='2' width='1' y='436'/> <rect height='2' width='1' y='440'/> <rect height='2' width='1' y='444'/> <rect height='2' width='1' y='448'/> <rect height='2' width='1' y='452'/> <rect height='2' width='1' y='456'/> <rect height='2' width='1' y='460'/> <rect height='2' width='1' y='464'/> <rect height='2' width='1' y='468'/> <rect height='2' width='1' y='472'/> <rect height='2' width='1' y='476'/> <rect height='2' width='1' y='480'/> <rect height='2' width='1' y='484'/> <rect height='2' width='1' y='488'/> <rect height='2' width='1' y='492'/> <rect height='2' width='1' y='496'/> <rect height='2' width='1' y='500'/> <rect height='2' width='1' y='504'/> <rect height='2' width='1' y='508'/> <rect height='2' width='1' y='512'/> <rect height='2' width='1' y='516'/> <rect height='2' width='1' y='520'/> <rect height='2' width='1' y='524'/> <rect height='2' width='1' y='528'/> <rect height='2' width='1' y='532'/> <rect height='2' width='1' y='536'/> <rect height='2' width='1' y='540'/> <rect height='2' width='1' y='544'/> <rect height='2' width='1' y='548'/> <rect height='2' width='1' y='552'/> <rect height='2' width='1' y='556'/> <rect height='2' width='1' y='560'/> <rect height='2' width='1' y='564'/> <rect height='2' width='1' y='568'/> <rect height='2' width='1' y='572'/> <rect height='2' width='1' y='576'/> <rect height='2' width='1' y='580'/> <rect height='2' width='1' y='584'/> <rect height='2' width='1' y='588'/> <rect height='2' width='1' y='592'/> <rect height='2' width='1' y='596'/> <rect height='2' width='1' y='600'/> <rect height='2' width='1' y='604'/> <rect height='2' width='1' y='608'/> <rect height='2' width='1' y='612'/> <rect height='2' width='1' y='616'/> <rect height='2' width='1' y='620'/> <rect height='2' width='1' y='624'/> <rect height='2' width='1' y='628'/> <rect height='2' width='1' y='632'/> <rect height='2' width='1' y='636'/> <rect height='2' width='1' y='640'/> <rect height='2' width='1' y='644'/> <rect height='2' width='1' y='648'/> <rect height='2' width='1' y='652'/> <rect height='2' width='1' y='656'/> <rect height='2' width='1' y='660'/> <rect height='2' width='1' y='664'/> <rect height='2' width='1' y='668'/> <rect height='2' width='1' y='672'/> <rect height='2' width='1' y='676'/> <rect height='2' width='1' y='680'/> <rect height='2' width='1' y='684'/> <rect height='2' width='1' y='688'/> <rect height='2' width='1' y='692'/> <rect height='2' width='1' y='696'/> <rect height='2' width='1' y='700'/> <rect height='2' width='1' y='704'/> <rect height='2' width='1' y='708'/> <rect height='2' width='1' y='712'/> <rect height='2' width='1' y='716'/> <rect height='2' width='1' y='720'/> <rect height='2' width='1' y='724'/> <rect height='2' width='1' y='728'/> <rect height='2' width='1' y='732'/> <rect height='2' width='1' y='736'/> <rect height='2' width='1' y='740'/> <rect height='2' width='1' y='744'/> <rect height='2' width='1' y='748'/> <rect height='2' width='1' y='752'/> <rect height='2' width='1' y='756'/> <rect height='2' width='1' y='760'/> <rect height='2' width='1' y='764'/> <rect height='2' width='1' y='768'/> <rect height='2' width='1' y='772'/> <rect height='2' width='1' y='776'/> <rect height='2' width='1' y='780'/> <rect height='2' width='1' y='784'/> <rect height='2' width='1' y='788'/> <rect height='2' width='1' y='792'/> <rect height='2' width='1' y='796'/> </g> </g> <g id='bullet' transform='translate(0, -20)'> <path style='stroke:white; stroke-width:2; fill:none' d='M0.436,1.418C7.853-1.088,16.396,1.706,19.52,7.658c2.498,4.762-0.287,10.248-6.22,12.252c-4.747,1.604-10.215-0.184-12.213-3.993c-1.599-3.048,0.183-6.559,3.981-7.842c3.038-1.026,6.538,0.118,7.816,2.556 c1.024,1.951-0.117,4.198-2.547,5.019c-1.945,0.657-4.185-0.076-5.003-1.636c-0.655-1.248,0.075-2.686,1.63-3.212c1.245-0.42,2.678,0.048,3.202,1.047'/> </g> </defs> <g id='slideBackground' class='slideBackground'> <rect height='768' style='fill:black' width='1024' x='0' y='0'/> <rect height='668' style='fill:url(#menuBarPaint)' width='210' x='0' y='100'/> <rect height='100' style='fill:url(#slideBackgroundHeaderPaint)' width='1024' x='0' y='0'/> <use xlink:href='#stripePattern' transform='scale(1024, 1)'/> <rect height='5' style='fill:url(#slideTitleSeparatorPaint)' width='1024' x='0' y='100'/> </g> <g id='navigationGroup' style='fill:white' transform='translate(984, 45) scale(2, 2)'> <polygon id='prevSlideControl' onclick='onPrevSlide(evt)' onmouseover="onSetFill(evt, 'prevSlideControl', 'rgb(176, 22, 40)')" points='1 10 10 0 1 -10 1 10' onmouseout="onSetFill(evt, 'prevSlideControl', 'white')" transform='rotate(180)'/> <polygon id='nextSlideControl' onclick='onNextSlide(evt)' onmouseover="onSetFill(evt, 'nextSlideControl', 'rgb(176, 22, 40)')" points='1 10 10 0 1 -10 1 10' onmouseout="onSetFill(evt, 'nextSlideControl', 'white')"/> </g> <g id='slideMenu' transform='translate(15, 130)'> <text onclick='onMenuItemSelected(evt, 1)' class='slidesetMenuHeader' x='0' y='0'>Background and Motivation</text> <g style='visibility:visible'> <rect height='5' id='Expand1' x='-10' y='-5' onclick="onExpand(evt, 'slideSetSubmenu1')" style='fill:white' width='5'/> <rect height='5' id='Collapse1' x='-10' y='-5' onclick="onCollapse(evt, 'slideSetSubmenu1')" style='fill:red; visibility:hidden' width='5'> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='hidden' begin='Collapse1.click'/> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='visible' begin='Expand1.click'/> </rect> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='visible' begin='Collapse1.click'/> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='hidden' begin='Expand1.click'/> </g> <g style='visibility:hidden' id='slideSetSubmenu1'> <text id='slide1-1MenuItem' x='10' y='20' onmouseout="onHighlightMenuItem(evt, 'false', 'slide1-1MenuItem')" onclick='onMenuItemSelected(evt, 2)' onmouseover="onHighlightMenuItem(evt, 'true', 'slide1-1MenuItem')" class='slideMenuItem'>Why Yet Another Grap...</text> </g> <g transform='translate(0, 20)'> <g> <text onclick='onMenuItemSelected(evt, 3)' class='slidesetMenuHeader' x='0' y='0'>The ABCs of SVG</text> <g style='visibility:visible'> <rect height='5' id='Expand2' x='-10' y='-5' onclick="onExpand(evt, 'slideSetSubmenu2')" style='fill:white' width='5'/> <rect height='5' id='Collapse2' x='-10' y='-5' onclick="onCollapse(evt, 'slideSetSubmenu2')" style='fill:red; visibility:hidden' width='5'> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='hidden' begin='Collapse2.click'/> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='visible' begin='Expand2.click'/> </rect> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='visible' begin='Collapse2.click'/> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='hidden' begin='Expand2.click'/> </g> <g style='visibility:hidden' id='slideSetSubmenu2'> <text id='slide2-1MenuItem' x='10' y='20' onmouseout="onHighlightMenuItem(evt, 'false', 'slide2-1MenuItem')" onclick='onMenuItemSelected(evt, 4)' onmouseover="onHighlightMenuItem(evt, 'true', 'slide2-1MenuItem')" class='slideMenuItem'>SVG Features</text> <text id='slide2-2MenuItem' x='10' y='40' onmouseout="onHighlightMenuItem(evt, 'false', 'slide2-2MenuItem')" onclick='onMenuItemSelected(evt, 5)' onmouseover="onHighlightMenuItem(evt, 'true', 'slide2-2MenuItem')" class='slideMenuItem'>SVG Sample Source</text> <text id='slide2-3MenuItem' x='10' y='60' onmouseout="onHighlightMenuItem(evt, 'false', 'slide2-3MenuItem')" onclick='onMenuItemSelected(evt, 6)' onmouseover="onHighlightMenuItem(evt, 'true', 'slide2-3MenuItem')" class='slideMenuItem'>SVG Sample Output</text> </g> <g transform='translate(0, 20)'> <g> <text onclick='onMenuItemSelected(evt, 7)' class='slidesetMenuHeader' x='0' y='0'>The SVG Community</text> <g style='visibility:visible'> <rect height='5' id='Expand3' x='-10' y='-5' onclick="onExpand(evt, 'slideSetSubmenu3')" style='fill:white' width='5'/> <rect height='5' id='Collapse3' x='-10' y='-5' onclick="onCollapse(evt, 'slideSetSubmenu3')" style='fill:red; visibility:hidden' width='5'> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='hidden' begin='Collapse3.click'/> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='visible' begin='Expand3.click'/> </rect> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='visible' begin='Collapse3.click'/> <set fill='freeze' attributeType='CSS' attributeName='visibility' dur='0s' to='hidden' begin='Expand3.click'/> </g> <g style='visibility:hidden' id='slideSetSubmenu3'> <text id='slide3-1MenuItem' x='10' y='20' onmouseout="onHighlightMenuItem(evt, 'false', 'slide3-1MenuItem')" onclick='onMenuItemSelected(evt, 8)' onmouseover="onHighlightMenuItem(evt, 'true', 'slide3-1MenuItem')" class='slideMenuItem'>Some SVG Resources</text> <text id='slide3-2MenuItem' x='10' y='40' onmouseout="onHighlightMenuItem(evt, 'false', 'slide3-2MenuItem')" onclick='onMenuItemSelected(evt, 9)' onmouseover="onHighlightMenuItem(evt, 'true', 'slide3-2MenuItem')" class='slideMenuItem'>Quote Them on it</text> </g> <animateTransform fill='freeze' id='translator' type='translate' from='0, 0' dur='1s' accumulate='none' attributeName='transform' attributeType='XML' additive='replace' begin='Expand2.click' to='0, 60'/> <animateTransform fill='freeze' id='translator2' type='translate' from='0, 0' dur='1s' accumulate='sum' attributeName='transform' attributeType='XML' additive='sum' begin='Collapse2.click' to='0, -60'/> </g> </g> <animateTransform fill='freeze' id='translator' type='translate' from='0, 0' dur='1s' accumulate='none' attributeName='transform' attributeType='XML' additive='replace' begin='Expand1.click' to='0, 20'/> <animateTransform fill='freeze' id='translator2' type='translate' from='0, 0' dur='1s' accumulate='sum' attributeName='transform' attributeType='XML' additive='sum' begin='Collapse1.click' to='0, -20'/> </g> </g> </g> <g onclick='onNextSlide(evt)' style='visibility:hidden' id='slideShowCover'> <defs> <linearGradient spreadMethod='pad' id='backgroundPaint' x1='0' y2='768' x2='0' y1='0' gradientUnits='userSpaceOnUse'> <stop offset='0%' style='stop-color:black; stop-opacity:1;'/> <stop offset='25%' style='stop-color:rgb(103, 103, 157); stop-opacity:1;'/> <stop offset='50%' style='stop-color:white; stop-opacity:1;'/> <stop offset='75%' style='stop-color:rgb(103, 103, 157); stop-opacity:1;'/> <stop offset='100%' style='stop-color:black; stop-opacity:1;'/> </linearGradient> <filter height='105%' id='dropShadow' filterUnits='objectBoundingBox' x='0%' width='105%' y='0%'> <feGaussianBlur in='SourceAlpha' result='blur' stdDeviation='4'/> <feOffset dy='4' dx='4' result='offsetBlur' in='blur'/> <feFlood style='flood-color:black' result='solidBlack'/> <feComposite in='solidBlack' in2='SourceAlpha' result='separation' operator='in'/> <feOffset dy='-1' dx='-1' result='offsetSeparation' in='separation'/> <feMerge> <feMergeNode in='offsetBlur'/> <feMergeNode in='offsetSeparation'/> <feMergeNode in='SourceGraphic'/> </feMerge> </filter> </defs> <rect height='768' style='fill:url(#backgroundPaint)' width='1024'/> <use xlink:href='#stripePattern' transform='scale(1024, 1)'/> <g style='filter:url(#dropShadow)'> <text class='slideCoverTitle' style='text-anchor:middle' x='512' y='300'>Introduction to SVG</text> <g transform='translate(512, 490)' id='metadata' style='text-anchor:middle;'> <text x='0' class='slideCoverSubTitle' y='0'>Uche Ogbuji</text> <text x='0' class='slideCoverSubTitle' y='50'>Principal Consultant</text> <text x='0' class='slideCoverSubTitle' y='100'>Fourthought Inc.</text> <text x='0' class='slideCoverSubTitle' y='150'>Front Range XML Keiretsu</text> </g> </g> </g> <g onclick='onNextSlide(evt)' style='visibility:hidden' id='slidesetCover1'> <rect height='768' style='fill:black' width='1024' x='0' y='0'/> <rect height='768' style='fill:url(#menuBarPaint)' width='210' x='0' y='0'/> <g transform='scale(210, 1)'> <use xlink:href='#stripePattern'/> </g> <text x='240' class='slidesetCoverTitle' y='200'>Background and Motivation</text> </g> <g onclick='onNextSlide(evt)' style='visibility:hidden' id='slidesetCover2'> <rect height='768' style='fill:black' width='1024' x='0' y='0'/> <rect height='768' style='fill:url(#menuBarPaint)' width='210' x='0' y='0'/> <g transform='scale(210, 1)'> <use xlink:href='#stripePattern'/> </g> <text x='240' class='slidesetCoverTitle' y='200'>The ABCs of SVG</text> </g> <g onclick='onNextSlide(evt)' style='visibility:hidden' id='slidesetCover3'> <rect height='768' style='fill:black' width='1024' x='0' y='0'/> <rect height='768' style='fill:url(#menuBarPaint)' width='210' x='0' y='0'/> <g transform='scale(210, 1)'> <use xlink:href='#stripePattern'/> </g> <text x='240' class='slidesetCoverTitle' y='200'>The SVG Community</text> </g> <g id='slide1-1' style='visibility:hidden' class='slide'> <text class='slideTitle' x='30' y='60'>Why Yet Another Graphics Format?</text> <g><text x="240" y="150" class="itemClass">Leveraging the existing XML technology base</text></g> <g><text x="240" y="185" class="itemClass">Integrating graphics into the semantic Web</text></g> <g><text x="240" y="220" class="itemClass">Giving browsers access to image <tspan class='emphasis'>internals</tspan></text></g> <g><text x="240" y="255" class="itemClass">Supporting the next generation of browsers</text></g> </g> <g id='slide2-1' style='visibility:hidden' class='slide'> <text class='slideTitle' x='30' y='60'>SVG Features</text> <text x='240' class='headingInline' y='150'>Basic Features</text> <use class='listBullet' xlink:href='#bullet' x='240' y='185'/> <g><text x="270" y="185" class="itemClass">Coordinate spaces and transforms</text></g> <use class='listBullet' xlink:href='#bullet' x='240' y='220'/> <g><text x="270" y="220" class="itemClass">Graphics primitives: ellipses, polygons, polylines, curves, etc.</text></g> <use class='listBullet' xlink:href='#bullet' x='240' y='255'/> <g><text x="270" y="255" class="itemClass">Stylesheets: CSS, XSL, etc.</text></g> <text x='240' class='headingInline' y='290'>Advanced Features</text> <use class='listBullet' xlink:href='#bullet' x='240' y='325'/> <g><text x="270" y="325" class="itemClass">Raster filter effects</text></g> <use class='listBullet' xlink:href='#bullet' x='240' y='360'/> <g><text x="270" y="360" class="itemClass">Alpha masking</text></g> <use class='listBullet' xlink:href='#bullet' x='240' y='395'/> <g><text x="270" y="395" class="itemClass">Animation</text></g> <use class='listBullet' xlink:href='#bullet' x='240' y='430'/> <g><text x="270" y="430" class="itemClass">Zooming and Panning</text></g> <use class='listBullet' xlink:href='#bullet' x='240' y='465'/> <g><text x="270" y="465" class="itemClass">Scripting and extensibility</text></g> </g> <g id='slide2-2' style='visibility:hidden' class='slide'> <text class='slideTitle' x='30' y='60'>SVG Sample Source</text> <text x='240' class='preformattedInline' y='135'> &lt;?xml version="1.0"?> &lt;!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000802//EN" "http://www.w3.org/TR/2000/CR-SVG-20000802/DTD/svg-20000802.dtd" > &lt;svg width="800" height="800"> &lt;desc>SVG Sample for SunWorld Article&lt;/desc> &lt;style type="text/css"> .Lagos { fill: white; stroke: green; stroke-width: 30 } .ViaAppia { fill: none; stroke: black; stroke-width: 10 } .OrthoLogos { font-size: 32; font-family: helvetica } &lt;/style> &lt;ellipse transform="translate(500 200)" rx="250" ry="100" style="fill: brown; stroke: yellow; stroke-width: 10"/> &lt;polygon transform="translate(100 200) rotate(45)" class="Lagos" points="350,75 379,161 469,161 397,215 423,301 350,250 277, 301 303,215 231,161 321,161"/> &lt;text class="OrthoLogos" x="400" y="400">TO KALON&lt;/text> &lt;path class="ViaAppia" d="M500,600 C500,500 650,500 650,600 S800,700 800,600"/> &lt;/svg> </text> </g> <g id='slide2-3' style='visibility:hidden' class='slide'> <text class='slideTitle' x='30' y='60'>SVG Sample Output</text> <g transform='translate(240, 135)'> <svg height='10cm' width='10cm' viewBox='0 0 200 200'> <desc>SVG Sample for SunWorld Article</desc> <style type='text/css'> .Lagos { fill: white; stroke: green; stroke-width: 30 } .ViaAppia { fill: none; stroke: white; stroke-width: 10 } .OrthoLogos { font-size: 32; font-family: helvetica; fill:white } </style> <ellipse transform='translate(500 200)' ry='100' rx='250' style='fill: brown; stroke: yellow; stroke-width: 10'/> <polygon points='350,75 379,161 469,161 397,215 423,301 350,250 277, 301 303,215 231,161 321,161' transform='translate(100 200) rotate(45)' class='Lagos'/> <text class='OrthoLogos' x='400' y='400'>TO KALON</text> <path class='ViaAppia' d='M500,600 C500,500 650,500 650,600 S800,700 800,600'/> </svg> </g> </g> <g id='slide3-1' style='visibility:hidden' class='slide'> <text class='slideTitle' x='30' y='60'>Some SVG Resources</text> <g><text x="240" y="150" class="itemClass"><tspan class='linkStyle'>The W3C's SVG Page</tspan></text></g> <g><text x="240" y="185" class="itemClass"><tspan class='linkStyle'>OpenDirectory SVG Links</tspan></text></g> <g><text x="240" y="220" class="itemClass"><tspan class='linkStyle'>How to make slides like these</tspan></text></g> </g> <g id='slide3-2' style='visibility:hidden' class='slide'> <text class='slideTitle' x='30' y='60'>Quote Them on it</text> <text x='240' class='paraInline' y='150'>"Over twenty organizations, including Sun Microsystems, Adobe, Apple, IBM, and Kodak, have been involved in defining SVG."<tspan class='emphasis'> -- Vincent J. Hardy, Sun</tspan> </text> <text x='240' class='paraInline' y='185'>"I have been working with computer graphics for over 25 years and split an immense amount of blood on the floor at midnight. With SVG I can now do almost anything I want [except for 3D - in which I also have a molecular interest]. And I suspect that I can stick with it for the foreseeable future." <tspan class='emphasis'>-- Peter Murray-Rust, XML-DEV Founder</tspan> </text> <text x='240' class='paraInline' y='220'>"I envision a day where we have XHTML Web pages with SVG as the "chrome" of our interfaces--defining the buttons, the layers, the coloring, and the grid--where we can actually use a language that's XML-based rather than theses separate GIF files that can take so long to download. That's certainly one vision; that vision not just extending on the Web, on a monitor, but wireless onto my Palm Pilot or to print and other output as well." <tspan class='emphasis'>-- Steve Mulder, Razorfish</tspan> </text> </g> </svg>""" #"' expected_1=""" <svg/>"""
[ 2, 52, 2395, 338, 1332, 422, 3825, 338, 45809, 10649, 9991, 198, 11748, 28686, 198, 6738, 1395, 4029, 13, 55, 82, 2528, 1330, 1332, 62, 9869, 1108, 198, 198, 2, 4863, 3825, 338, 2891, 15813, 198, 21760, 62, 16, 62, 9900, 796, 366, ...
2.11343
16,054
""" 2338. : xCrypt0r : Python 3 : 29,380 KB : 72 ms : 2020 9 13 """ if __name__ == '__main__': main()
[ 37811, 198, 1954, 2548, 13, 220, 220, 198, 198, 25, 2124, 23919, 15, 81, 198, 25, 11361, 513, 198, 1058, 2808, 11, 23734, 14204, 198, 1058, 7724, 13845, 198, 1058, 12131, 860, 1511, 198, 37811, 198, 198, 361, 11593, 3672, 834, 6624, ...
2.092593
54
# Copyright 2020 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """ test Activations """ import numpy as np import mindspore.nn as nn from mindspore import Tensor from mindspore.common.api import _cell_graph_executor from ..ut_filter import non_graph_engine class LogSoftmaxNet(nn.Cell): def test_compile_relu(): net = Net1() input_data = Tensor(np.array([[1.2, 2.1], [2.2, 3.2]], dtype=np.float32)) _cell_graph_executor.compile(net, input_data)
[ 2, 15069, 12131, 43208, 21852, 1766, 1539, 12052, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198...
3.445513
312
from abc import ABC, abstractmethod from typing import Dict import pandas as pd from feast.data_source import DataSource from feast.repo_config import FeastConfigBaseModel
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 19720, 1330, 360, 713, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 26951, 13, 7890, 62, 10459, 1330, 6060, 7416, 198, 6738, 26951, 13, 260, 7501, 62, 11250, 1330, ...
3.723404
47
from yalul.interpreters.environment import Environment from yalul.interpreters.expressions.var_assignment_interpreter import VarAssignmentInterpreter from yalul.interpreters.interpreter_errors import InterpreterErrors
[ 6738, 331, 282, 377, 13, 3849, 3866, 1010, 13, 38986, 1330, 9344, 198, 6738, 331, 282, 377, 13, 3849, 3866, 1010, 13, 42712, 507, 13, 7785, 62, 562, 16747, 62, 3849, 3866, 353, 1330, 12372, 8021, 16747, 9492, 3866, 353, 198, 6738, 3...
3.532258
62
import boto3 from django.conf import settings from backend.models import CloudWatchEvent import json
[ 11748, 275, 2069, 18, 201, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 201, 198, 6738, 30203, 13, 27530, 1330, 10130, 10723, 9237, 201, 198, 11748, 33918, 201, 198, 201, 198 ]
3.451613
31
#!/usr/bin/env python # Manipulate sys.path to be able to import converscript from this local git # repository. import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) from converscript import RiveScript import json bot = RiveScript() bot.load_file("example.rive") dep = bot.deparse() print(json.dumps(dep, indent=2))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 35045, 5039, 25064, 13, 6978, 284, 307, 1498, 284, 1330, 3453, 6519, 422, 428, 1957, 17606, 198, 2, 16099, 13, 198, 11748, 28686, 198, 11748, 25064, 198, 17597, 13, 6978, 13, ...
2.918033
122
import matplotlib.pyplot as plt import numpy as np from scipy import signal, linalg from matplotlib import rc from matplotlib import rcParams __author__ = 'ernesto' # if use latex or mathtext rc('text', usetex=True) rcParams['text.latex.preamble'] = [r"\usepackage{amsmath}"] #respuesta al impulso deseada: sinc N = 50 # numero par fc = 0.1 nf = 1024 n = np.arange(-N/2, N/2+1) N += 1 f = np.arange(nf)/(2 * nf) # parmetros del filtro a disear p = 10 q = 10 # respuesta al impulso hd = 2 * fc * np.sinc(2 * fc * n) # * np.hanning(N) # respuesta en frecuencia _, Hd = signal.freqz(hd, a=1, worN=nf, whole=False, plot=None) # estimacin de los coeficientes del denominador (a) # hd = np.arange(N) x = hd[q + 1:] H = linalg.toeplitz(hd[q: N - 1], hd[q: q - p: -1]) # a_est = np.linalg.solve(H.T @ H, -H.T @ x) epsilon = 1e-16 #epsilon = 0 a_est = linalg.solve(H.T @ H + epsilon * np.eye(p), -H.T @ x) print("Nmero de Condicin 1: {}".format(np.linalg.cond(H.T @ H))) h = hd[: q + 1] H0 = linalg.toeplitz(np.concatenate(([0], hd[: q])), np.zeros((p, ))) b_est = h + H0 @ a_est #print(h) #print(H0) # respuesta en frecuencia a_est = np.concatenate(([1], a_est)) print(a_est) print(b_est) _, H_est = signal.freqz(b_est, a_est, worN=nf, whole=False, plot=None) # respuesta al impulso delta = np.zeros((N,)) delta[0] = 1 h_est = signal.lfilter(b_est, a_est, delta, axis=- 1, zi=None) ms = 3 fs = 12 n = np.arange(N) fig = plt.figure(0, figsize=(9, 5), frameon=False) ax = plt.subplot2grid((8, 2), (0, 0), rowspan=6, colspan=1) plt.xlim(0, N-1) plt.ylim(np.amin(hd)-0.02, np.amax(hd)+0.02) plt.plot(n, hd, linestyle='-', marker='s', color='k', markersize=ms, lw=1, label='${\\rm deseada}$') plt.plot(n, h_est, linestyle='-', marker='s', color='r', markersize=ms, lw=1, label='${\\rm estimada}$') leg = plt.legend(loc=1, frameon=False, fontsize=fs) ax.set_xticklabels([]) ax.set_ylabel('${\\rm Respuesta\;al\;impulso}$', fontsize=fs) ax = plt.subplot2grid((8, 2), (6, 0), rowspan=2, colspan=1) e = hd-h_est plt.xlim(0, N-1) plt.ylim(np.amin(e)-0.001, np.amax(e)+0.001) plt.plot(n, e, linestyle='-', marker='s', color='k', markersize=ms) ax.set_xlabel(r'$n$', fontsize=fs) ax.set_ylabel(r'$\epsilon[n]$', fontsize=fs) ax = plt.subplot2grid((8, 2), (0, 1), rowspan=8, colspan=1) plt.xlim(0, 0.5) plt.ylim(-55, 8) plt.plot(f, 10 * np.log10(np.abs(Hd)), 'k', label='${\\rm deseada}$') plt.plot(f, 10 * np.log10(np.abs(H_est)), 'r', label='${\\rm estimada}$') ax.set_xlabel('${\\rm Frecuencia\;normalizada}$', fontsize=fs) ax.set_ylabel('${\\rm Respuesta\;en\;frecuencia\;(dB)}$', fontsize=fs) leg = plt.legend(loc=1, frameon=False, fontsize=fs) plt.savefig('example_8_11.pdf', bbox_inches='tight') plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 6737, 11, 300, 1292, 70, 198, 198, 6738, 2603, 29487, 8019, 1330, 48321, 198, 6738, 2603, 29487, 8019, 1330, 4...
2.039127
1,329
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 wx from robotide.controller.commands import ( RenameKeywordOccurrences, RemoveMacro, AddKeyword, AddTestCase, RenameTest, CopyMacroAs, AddVariable, UpdateVariableName, RenameFile, RenameResourceFile, DeleteFile, SortKeywords, Include, Exclude) from robotide.controller.settingcontrollers import VariableController from robotide.controller.macrocontrollers import ( TestCaseController, UserKeywordController) from robotide.controller.filecontrollers import ( TestDataDirectoryController, ResourceFileController, TestCaseFileController, ExcludedDirectoryController, DirtyRobotDataException) from robotide.editor.editordialogs import ( TestCaseNameDialog, UserKeywordNameDialog, ScalarVariableDialog, ListVariableDialog, CopyUserKeywordDialog, DictionaryVariableDialog) from robotide.publish import RideOpenVariableDialog from robotide.ui.progress import LoadProgressObserver from robotide.usages.UsageRunner import Usages, ResourceFileUsages from .filedialogs import ( AddSuiteDialog, AddDirectoryDialog, ChangeFormatDialog, NewResourceDialog, RobotFilePathDialog) from robotide.utils import overrides from robotide.widgets import PopupMenuItems from .progress import RenameProgressObserver from .resourcedialogs import ResourceRenameDialog, ResourceDeleteDialog from robotide.ui.resourcedialogs import FolderDeleteDialog class _CanBeRenamed(object): class DirectoryHandler(_ActionHandler): is_draggable = False is_test_suite = False can_be_rendered = False _actions = [_ActionHandler._label_new_resource] class TestDataHandler(_ActionHandler): accepts_drag = lambda self, dragged: \ (isinstance(dragged, UserKeywordHandler) or isinstance(dragged, VariableHandler)) is_draggable = False is_test_suite = True def has_been_modified_on_disk(self): return self.item.has_been_modified_on_disk() def do_drop(self, item): self.controller.add_test_or_keyword(item) def rename(self, new_name): return False def OnSortKeywords(self, event): """Sorts the keywords inside the treenode""" self.controller.execute(SortKeywords()) def _rename_command(self, label): raise NotImplementedError(self.__class__) def _set_node_label(self, label): self._tree.SetItemText(self._node, label) class ResourceFileHandler(_FileHandlerThanCanBeRenamed, TestDataHandler): is_test_suite = False _actions = [_ActionHandler._label_new_user_keyword, _ActionHandler._label_new_scalar, _ActionHandler._label_new_list_variable, _ActionHandler._label_new_dict_variable, '---', _ActionHandler._label_rename, _ActionHandler._label_change_format, _ActionHandler._label_sort_keywords, _ActionHandler._label_find_usages, _ActionHandler._label_delete] class TestCaseFileHandler(_FileHandlerThanCanBeRenamed, TestDataHandler): accepts_drag = lambda *args: True _actions = [_ActionHandler._label_new_test_case, _ActionHandler._label_new_user_keyword, _ActionHandler._label_new_scalar, _ActionHandler._label_new_list_variable, _ActionHandler._label_new_dict_variable, '---', _ActionHandler._label_rename, _ActionHandler._label_change_format, _ActionHandler._label_sort_keywords, _ActionHandler._label_delete, '---', _ActionHandler._label_select_all, _ActionHandler._label_deselect_all, _ActionHandler._label_select_failed_tests, _ActionHandler._label_select_passed_tests ]
[ 2, 220, 15069, 3648, 12, 4626, 26182, 23555, 290, 27862, 201, 198, 2, 201, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 201, 198, 2, 220, 345, 743, 407, 779, 428, 2393, 2845, 28...
2.564117
1,778