content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from elasticapm.contrib.flask import ElasticAPM import os from flask import Flask, request, render_template from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy APP = Flask(__name__) APP.config['ELASTIC_APM'] = { } apm = ElasticAPM(APP) APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False APP.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://%s:%s@%s/%s' % ( # ARGS.dbuser, ARGS.dbpass, ARGS.dbhost, ARGS.dbname os.environ['DBUSER'], os.environ['DBPASS'], os.environ['DBHOST'], os.environ['DBNAME'] ) # initialize the database connection DB = SQLAlchemy(APP) # initialize database migration management MIGRATE = Migrate(APP, DB) from models import * # bad query # error message # Error # Unhandled error
[ 6738, 27468, 499, 76, 13, 3642, 822, 13, 2704, 2093, 1330, 48567, 2969, 44, 198, 11748, 28686, 198, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 8543, 62, 28243, 198, 6738, 42903, 62, 76, 42175, 1330, 337, 42175, 198, 6738, 42903, 62,...
2.680851
282
# -*- coding: utf-8 -*- from sys import platform
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 25064, 1330, 3859, 198 ]
2.578947
19
# -*- coding: utf-8 -*- from datetime import datetime import logging import os.path import requests import time import urllib from bs4 import BeautifulSoup from utils import mongo
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 18931, 198, 11748, 28686, 13, 6978, 198, 11748, 7007, 198, 11748, 640, 198, 11748, 2956, 297, 571, 198, 6738, 275, 82, 19...
3.192982
57
from django import template register = template.Library()
[ 6738, 42625, 14208, 1330, 11055, 198, 198, 30238, 796, 11055, 13, 23377, 3419, 628 ]
4.285714
14
import os import boto3 import dj_database_url from mbq import env, metrics SECRET_KEY = 'fake-key' DEBUG = True ATOMIQ = { 'env': 'Test', 'service': 'test-service', } database_url = os.environ.get('DATABASE_URL', 'mysql://root:@mysql:3306/atomiqdb') DATABASES = { 'default': dj_database_url.parse(database_url), } INSTALLED_APPS = [ 'mbq.atomiq', ] USE_TZ = True boto3.setup_default_session( region_name='us-east-1', ) ENV = env.get_environment("ENV_NAME") metrics.init('mbq.atomiq', env=ENV, constant_tags={"env": ENV.long_name})
[ 11748, 28686, 198, 198, 11748, 275, 2069, 18, 198, 11748, 42625, 62, 48806, 62, 6371, 198, 198, 6738, 285, 65, 80, 1330, 17365, 11, 20731, 628, 198, 23683, 26087, 62, 20373, 796, 705, 30706, 12, 2539, 6, 198, 30531, 796, 6407, 198, ...
2.262097
248
import json import requests
[ 11748, 33918, 198, 198, 11748, 7007, 628, 628, 198 ]
3.666667
9
""" Tools for creating a CA cert and signed server certs. Divined from http://svn.osafoundation.org/m2crypto/trunk/tests/test_x509.py The mk_temporary_xxx calls return a NamedTemporaryFile with certs. Usage ; # Create a temporary CA cert and it's private key cacert, cakey = mk_temporary_cacert() # Create a temporary server cert+key, signed by the CA server_cert = mk_temporary_cert(cacert.name, cakey.name, '*.server.co.uk') """ from tempfile import NamedTemporaryFile as namedtmp import time from M2Crypto import X509, EVP, RSA, ASN1 __author__ = 'eskil@yelp.com' __all__ = ['mk_temporary_cacert', 'mk_temporary_cert'] def mk_ca_issuer(): """ Our default CA issuer name. """ issuer = X509.X509_Name() issuer.C = "US" issuer.CN = "ca_testing_server" issuer.ST = 'CA' issuer.L = 'San Francisco' issuer.O = 'ca_yelp' issuer.OU = 'ca_testing' return issuer def mk_cert_valid(cert, days=365): """ Make a cert valid from now and til 'days' from now. Args: cert -- cert to make valid days -- number of days cert is valid for from now. """ t = long(time.time()) now = ASN1.ASN1_UTCTIME() now.set_time(t) expire = ASN1.ASN1_UTCTIME() expire.set_time(t + days * 24 * 60 * 60) cert.set_not_before(now) cert.set_not_after(expire) def mk_request(bits, cn='localhost'): """ Create a X509 request with the given number of bits in they key. Args: bits -- number of RSA key bits cn -- common name in the request Returns a X509 request and the private key (EVP) """ pk = EVP.PKey() x = X509.Request() rsa = RSA.gen_key(bits, 65537, lambda: None) pk.assign_rsa(rsa) x.set_pubkey(pk) name = x.get_subject() name.C = "US" name.CN = cn name.ST = 'CA' name.O = 'yelp' name.OU = 'testing' x.sign(pk,'sha1') return x, pk def mk_cacert(): """ Make a CA certificate. Returns the certificate, private key and public key. """ req, pk = mk_request(1024) pkey = req.get_pubkey() cert = X509.X509() cert.set_serial_number(1) cert.set_version(2) mk_cert_valid(cert) cert.set_issuer(mk_ca_issuer()) cert.set_subject(cert.get_issuer()) cert.set_pubkey(pkey) cert.add_ext(X509.new_extension('basicConstraints', 'CA:TRUE')) cert.add_ext(X509.new_extension('subjectKeyIdentifier', cert.get_fingerprint())) cert.sign(pk, 'sha1') return cert, pk, pkey def mk_cert(): """ Make a certificate. Returns a new cert. """ cert = X509.X509() cert.set_serial_number(2) cert.set_version(2) mk_cert_valid(cert) cert.add_ext(X509.new_extension('nsComment', 'SSL sever')) return cert def mk_casigned_cert(): """ Create a CA cert + server cert + server private key. """ # unused, left for history. cacert, pk1, _ = mk_cacert() cert_req, pk2 = mk_request(1024, cn='testing_server') cert = mk_cert(cacert) cert.set_subject(cert_req.get_subject()) cert.set_pubkey(cert_req.get_pubkey()) cert.sign(pk1, 'sha1') return cacert, cert, pk2 def mk_temporary_cacert(): """ Create a temporary CA cert. Returns a tuple of NamedTemporaryFiles holding the CA cert and private key. """ cacert, pk1, pkey = mk_cacert() cacertf = namedtmp() cacertf.write(cacert.as_pem()) cacertf.flush() pk1f = namedtmp() pk1f.write(pk1.as_pem(None)) pk1f.flush() return cacertf, pk1f def mk_temporary_cert(cacert_file, ca_key_file, cn): """ Create a temporary certificate signed by the given CA, and with the given common name. If cacert_file and ca_key_file is None, the certificate will be self-signed. Args: cacert_file -- file containing the CA certificate ca_key_file -- file containing the CA private key cn -- desired common name Returns a namedtemporary file with the certificate and private key """ cert_req, pk2 = mk_request(1024, cn=cn) if cacert_file and ca_key_file: cacert = X509.load_cert(cacert_file) pk1 = EVP.load_key(ca_key_file) else: cacert = None pk1 = None cert = mk_cert() cert.set_subject(cert_req.get_subject()) cert.set_pubkey(cert_req.get_pubkey()) if cacert and pk1: cert.set_issuer(cacert.get_issuer()) cert.sign(pk1, 'sha1') else: cert.set_issuer(cert.get_subject()) cert.sign(pk2, 'sha1') certf = namedtmp() certf.write(cert.as_pem()) certf.write(pk2.as_pem(None)) certf.flush() return certf if __name__ == '__main__': cacert, cert, pk = mk_casigned_cert() with open('cacert.crt', 'w') as f: f.write(cacert.as_pem()) with open('cert.crt', 'w') as f: f.write(cert.as_pem()) f.write(pk.as_pem(None)) # Sanity checks... cac = X509.load_cert('cacert.crt') print cac.verify(), cac.check_ca() cc = X509.load_cert('cert.crt') print cc.verify(cac.get_pubkey()) # protips # openssl verify -CAfile cacert.crt cacert.crt cert.crt # openssl x509 -in cert.crt -noout -text # openssl x509 -in cacert.crt -noout -text
[ 37811, 198, 33637, 329, 4441, 257, 7257, 5051, 290, 4488, 4382, 27802, 13, 198, 24095, 1389, 422, 2638, 1378, 21370, 77, 13, 418, 1878, 633, 341, 13, 2398, 14, 76, 17, 29609, 78, 14, 2213, 2954, 14, 41989, 14, 9288, 62, 87, 29022, ...
2.399698
1,984
from collections import deque
[ 6738, 17268, 1330, 390, 4188, 198 ]
5
6
import copy from utils.file_utils.dataset_reader_pack.ml_dataset_reader import get_TV_T_dataset, get_T_V_T_dataset from ml_sl.rf.dt_0 import Node, save_node, load_node from ml_sl.ml_data_wrapper import pack_list_2_list, single_point_list_2_list, reform_labeled_dataset_list from ml_sl.ml_data_wrapper import split_labeled_dataset_list from utils.file_utils.filename_utils import get_date_prefix from ml_sl.ml_critrions import cal_accuracy, cal_kappa, cal_accuracy_on_2, cal_accuracy_on_3 label_list = [2, 4, 5, 6, 7, 8, 9] # Import dataset (Training, validation, Test) ml_dataset_pickle_file_path = '../../datasets/ml_datasets/normed' tr_dataset, va_dataset, te_dataset = get_T_V_T_dataset(file_path=ml_dataset_pickle_file_path) tr_va_dataset, test_dataset = get_TV_T_dataset(file_path=ml_dataset_pickle_file_path) tr_label_list, tr_data_list = split_labeled_dataset_list(tr_dataset) va_label_list, va_data_list = split_labeled_dataset_list(va_dataset) tr_va_label_list, tr_va_data_list = split_labeled_dataset_list(tr_va_dataset) te_label_list, te_data_list = split_labeled_dataset_list(te_dataset) # --------------------- 1-No Pruning --------------------- #------------- Train on tr, tested on va #------------- # acc,kappa = dt_no_pruning(training_dataset=tr_dataset, validation_dataset=[], test_dataset=tr_dataset) # print(acc,kappa) # --> 1.0 1.0 #------------- Train on tr, tested on va #------------- # if __name__ == '__main__': # training_dataset, validation_dataset, test_dataset = get_T_V_T_dataset(file_path='../../datasets/ml_datasets/normed') # Running condition-1 # acc, kappa = dt_no_pruning(training_dataset, validation_dataset, test_dataset) # print('Accuracy: {0}, Kappa: {1}'.format(acc, kappa)) # Running condition-2 # acc, kappa = dt_no_pruning(training_dataset, validation_dataset=[], test_dataset=validation_dataset) # print('Accuracy: {0}, Kappa: {1}'.format(acc, kappa)) """ Running condition-1 Train on [Training+validation]-dataset Test on test-dataset 1-Accuracy: 0.45054945054945056, Kappa: 0.3173293323330833 2-Accuracy: 0.45054945054945056, Kappa: 0.3173293323330833 Running condition-2 Train on [Training]-dataset Test on validation-dataset 1-Accuracy: 0.5319148936170213, Kappa: 0.42762247439800716 2-Accuracy: 0.5319148936170213, Kappa: 0.42762247439800716 """ # training_dataset, validation_dataset, test_dataset = get_T_V_T_dataset(file_path='../../datasets/ml_datasets/normed') # load_dt_no_pruning(training_dataset, validation_dataset, test_dataset, label_list=[2,4,5,6,7,8,9]) # Decision Tree with no pruning: Accuracy on 1 = 0.4945054945054945, Accuracy on 2 = 0.5164835164835165, # Accuracy on 3 = 0.6923076923076923, Kappa=0.3706209592542475 # --------------------- 1-No Pruning --------------------- """ EA-Revise EA-Revise, DTGS no pruning / posterior pruning,DTGSFinal res DT final config no pruning tr+va te """ # dtFinalRes() """ node = pickle.load(file) ModuleNotFoundError: No module named 'ml_sl' Final res: trVaAcc=0.9163568773234201, trVaKappa=0.897055384288296, trVaAK=1.813412261611716, teAcc=0.4945054945054945, teKappa=0.3706209592542475, teAK=0.8651264537597421 """ # --------------------- 2-Pruning --------------------- # if __name__ == '__main__': # training_dataset, validation_dataset, test_dataset = get_T_V_T_dataset(file_path='../../datasets/ml_datasets/normed') # acc, kappa = dt_pruning(training_dataset, validation_dataset, test_dataset, label_list=[2, 4, 5, 6, 7, 8, 9]) # print('Accuracy: {0}, Kappa: {1}'.format(acc, kappa)) """ 1- Accuracy: 0.4835164835164835, Kappa: 0.3591549295774648 2- Accuracy: 0.4835164835164835, Kappa: 0.3591549295774648 """ # training_dataset, validation_dataset, test_dataset = get_T_V_T_dataset(file_path='../../datasets/ml_datasets/normed') # load_dt_pruning(test_dataset, label_list=[2,4,5,6,7,8,9]) # Decision Tree with pruning: Accuracy on 1 = 0.4835164835164835, Accuracy on 2 = 0.5054945054945055, # Accuracy on 3 = 0.6703296703296703, Kappa = 0.3591549295774648 # --------------------- 2-Pruning ---------------------
[ 11748, 4866, 198, 198, 6738, 3384, 4487, 13, 7753, 62, 26791, 13, 19608, 292, 316, 62, 46862, 62, 8002, 13, 4029, 62, 19608, 292, 316, 62, 46862, 1330, 651, 62, 6849, 62, 51, 62, 19608, 292, 316, 11, 651, 62, 51, 62, 53, 62, 51,...
2.377049
1,769
from SAGIRIBOT.basics.aio_mysql_excute import execute_sql
[ 6738, 311, 4760, 4663, 9865, 2394, 13, 12093, 873, 13, 64, 952, 62, 28744, 13976, 62, 41194, 1133, 1330, 12260, 62, 25410, 628 ]
2.565217
23
from distutils.core import setup setup( name = 'caro-diario', packages = ['caro-diario'], # this must be the same as the name above version = '0.1', description = 'Diario', author = 'Francesco Maida', author_email = 'francesco.maida@gmail.com', url = 'https://github.com/fmaida/caro-diario.git', # use the URL to the github repo download_url = '', # I'll explain this in a second keywords = ['diario', 'logging', 'esempio'], # arbitrary keywords classifiers = [], )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 40406, 7, 198, 220, 1438, 796, 705, 7718, 78, 12, 10989, 4982, 3256, 198, 220, 10392, 796, 37250, 7718, 78, 12, 10989, 4982, 6, 4357, 1303, 428, 1276, 307, 262, 976, 355, 262, 1438, 2029...
2.91018
167
# Copyright 2021 Guillermo Blzquez # # 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 functools import reduce from qiskit.aqua.operators.converters import ConverterBase from qiskit.aqua.operators.list_ops import TensoredOp, SummedOp from qiskit.aqua.operators.primitive_ops import PauliOp
[ 2, 15069, 33448, 1962, 4665, 5908, 1086, 89, 22281, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 4943, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, ...
3.53125
224
# -*- coding: utf-8 -*- """ This file contains tests for tensor.py """ import sys import pathlib import pytest import numpy as np from testing_utils import isclose # Ensure that 'matmodlab2' is imported from parent directory. sys.path.insert(0, str(pathlib.Path(__file__).absolute().parent.parent)) import matmodlab2 import matmodlab2.core.deformation as df deformation_measures_db = [ {"name": "Uniaxial Extension", "eps": np.array([0.042857142857142857143,0,0,0,0,0]), "depsdt": np.array([0.10000000000000000000,0,0,0,0,0]), "subtests": [ { "k": 2, "u": np.array([1.0419761445034553738,1.0000000000000000000,1.0000000000000000000,0,0,0]), "dudt": np.array([0.095971486993739310740,0,0,0,0,0]), "d": np.array([0.092105263157894736842,0,0,0,0,0]), }, { "k": 1, "u": np.array([1.0428571428571428571,1.0000000000000000000,1.0000000000000000000,0,0,0]), "dudt": np.array([0.10000000000000000000,0,0,0,0,0]), "d": np.array([0.095890410958904109589,0,0,0,0,0]), }, { "k": 0, "u": np.array([1.0437887715175541853,1.0000000000000000000,1.0000000000000000000,0,0,0]), "dudt": np.array([0.10437887715175541853,0,0,0,0,0]), "d": np.array([0.10000000000000000000,0,0,0,0,0]), }, { "k": -1, "u": np.array([1.0447761194029850746,1.0000000000000000000,1.0000000000000000000,0,0,0]), "dudt": np.array([0.10915571396747605257,0,0,0,0,0]), "d": np.array([0.10447761194029850746,0,0,0,0,0]), }, { "k": -2, "u": np.array([1.0458250331675944350,1.0000000000000000000,1.0000000000000000000,0,0,0]), "dudt": np.array([0.11438711300270564133,0,0,0,0,0]), "d": np.array([0.10937500000000000000,0,0,0,0,0]), }, ], }, {"name": "Uniaxial Extension with rotation", "eps": np.array([0.026196877156206737235,0.016660265700936119908,0,0.020891312403896220150,0,0]), "depsdt": np.array([-0.0045059468741139683829,0.10450594687411396838,0,0.063726469853100399588,0,0]), "subtests": [ { "k": 2, "u": np.array([1.0256583576911247384,1.0163177868123306353,1.0000000000000000000,0.020461857461098139159,0,0]), "dudt": np.array([-0.0056192451222061811013,0.10159073211594549184,0,0.061454775148472809312,0,0]), "d": np.array([-0.0066876940055755266344,0.098792957163470263477,0,0.059274595960483676859,0,0]), }, { "k": 1, "u": np.array([1.0261968771562067372,1.0166602657009361199,1.0000000000000000000,0.020891312403896220150,0,0]), "dudt": np.array([-0.0045059468741139683829,0.10450594687411396838,0,0.063726469853100399588,0,0]), "d": np.array([-0.0056693735828201687630,0.10155978454172427835,0,0.061415383576480024658,0,0]), }, { "k": 0, "u": np.array([1.0267663449262200007,1.0170224265913341846,1.0000000000000000000,0.021345447796308002806,0,0]), "dudt": np.array([-0.0032560207940279426371,0.10763489794578336117,0,0.066186651517750065998,0,0]), "d": np.array([-0.0045260401459293278687,0.10452604014592932787,0,0.063731056011271402912,0,0]), }, { "k": -1, "u": np.array([1.0273698716557383822,1.0174062477472466924,1.0000000000000000000,0.021826744302578140456,0,0]), "dudt": np.array([-0.0018481668596687927090,0.11100388082714484528,0,0.068860299997538432155,0,0]), "d": np.array([-0.0032383326989564664762,0.10771594463925497394,0,0.066244519079865882721,0,0]), }, { "k": -2, "u": np.array([1.0280110311733133167,1.0178140019942811183,1.0000000000000000000,0.022338051955872830687,0,0]), "dudt": np.array([-0.00025673980976010909772,0.11464385281246575042,0,0.071777050608761226760,0,0]), "d": np.array([-0.0017829682784827673453,0.11115796827848276735,0,0.068982906840537447349,0,0]), }, ], }, ] def test_deformation_measures_from_strain_dissertation_test(): """ Verify that we are converting from strain to D correctly. """ a = 0.5 t = 0.1 # Setup (inputs) st = np.sin(np.pi * t) ct = np.cos(np.pi * t) sht = np.sinh(a * t) eat = np.exp(a * t) eps = np.array([a * t * np.cos(np.pi * t / 2.0) ** 2, a * t * np.sin(np.pi * t / 2.0) ** 2, 0.0, a * t * np.sin(np.pi * t) / 2.0, 0.0, 0.0]) depsdt = np.array([a / 2.0 * (1.0 + ct - np.pi * t * st), a / 2.0 * (1.0 - ct + np.pi * t * st), 0.0, a / 2.0 * (np.pi * t * ct + st), 0.0, 0.0]) # Setup (expected outputs) d_g = np.array([(a + a * ct - np.pi * st * sht) / 2.0, (a - a * ct + np.pi * st * sht) / 2.0, 0.0, (a * st + np.pi * ct * sht) / 2.0, 0.0, 0.0]) # Test d = df.rate_of_strain_to_rate_of_deformation(depsdt, eps, 0) assert vec_isclose("D", d, d_g) # Teardown pass def test_deformation_measures_from_strain_dissertation_static(): """ Verify that we are converting from strain to D correctly. """ # Setup (inputs) eps=np.array([2.6634453918413015230,0.13875241035650067478,0,0.60791403008229297100,0,0]) depsdt=np.array([-0.66687706806142212351,1.9745693757537298158,0,4.2494716756395844993,0,0]) # Setup (expected outputs) d_g=np.array([-4.3525785227788080461,5.6602708304711157384,0,11.902909607738023219,0,0]) # Test d = df.rate_of_strain_to_rate_of_deformation(depsdt, eps, 0) assert vec_isclose("D", d, d_g) # Teardown pass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1212, 2393, 4909, 5254, 329, 11192, 273, 13, 9078, 198, 37811, 198, 198, 11748, 25064, 198, 11748, 3108, 8019, 198, 11748, 12972, 9288, 198, 11748, 299, 32152,...
1.778008
3,374
from trumania.core import circus import trumania.core.population as population import trumania.core.random_generators as gen import trumania.core.operations as ops import trumania.core.story as story import trumania.components.time_patterns.profilers as profilers import trumania.core.util_functions as util_functions import trumania.components.db as DB import pandas as pd # each step?() function below implement one step of the fourth example of the # tutorial documented at # https://realimpactanalytics.atlassian.net/wiki/display/LM/Data+generator+tutorial # this is essentially a modification of example3, with some supplementary # features demonstrating persistence if __name__ == "__main__": util_functions.setup_logging() step2()
[ 6738, 491, 3778, 544, 13, 7295, 1330, 33125, 198, 11748, 491, 3778, 544, 13, 7295, 13, 39748, 355, 3265, 198, 11748, 491, 3778, 544, 13, 7295, 13, 25120, 62, 8612, 2024, 355, 2429, 198, 11748, 491, 3778, 544, 13, 7295, 13, 3575, 602...
3.46789
218
import math if __name__ == '__main__': c = map(float, input().split()) d = map(float, input().split()) x = Complex(*c) y = Complex(*d) print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n')
[ 11748, 10688, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 269, 796, 3975, 7, 22468, 11, 5128, 22446, 35312, 28955, 198, 220, 220, 220, 288, 796, 3975, 7, 22468, 11, 5128, 22446, 35312, 28955...
2.15534
103
from itertools import product from hyperparameter_tuner.single_parameter_generator import single_parameter_generator as sgen if __name__ == '__main__': commands = default_commands_generator() for c in commands: print(c)
[ 6738, 340, 861, 10141, 1330, 1720, 198, 198, 6738, 8718, 17143, 2357, 62, 28286, 263, 13, 29762, 62, 17143, 2357, 62, 8612, 1352, 1330, 2060, 62, 17143, 2357, 62, 8612, 1352, 355, 264, 5235, 628, 628, 198, 361, 11593, 3672, 834, 6624,...
2.903614
83
# # Copyright 2017 Barcelona Supercomputing Center (www.bsc.es) # # 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. # '''Redis Storage Object implementation for the PyCOMPSs Python Binding @author: srodrig1 ''' import uuid import storage.api '''Add support for camelCase ''' StorageObject = storage_object
[ 2, 198, 2, 220, 15069, 2177, 15142, 3115, 785, 48074, 3337, 357, 2503, 13, 65, 1416, 13, 274, 8, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 345, 743, 40...
3.561404
228
# pylint: disable=C0114 import unittest from origin_response import lambda_handler event = { "Records": [ { "cf": { "config": {"requestId": "thisfakeidisthisfakeidisthisfakeidis"}, "request": {"uri": ""}, "response": {"headers": {}, "status": 0}, } } ] } if __name__ == "__main__": unittest.main()
[ 2, 279, 2645, 600, 25, 15560, 28, 34, 486, 1415, 198, 11748, 555, 715, 395, 198, 198, 6738, 8159, 62, 26209, 1330, 37456, 62, 30281, 628, 198, 15596, 796, 1391, 198, 220, 220, 220, 366, 6690, 3669, 1298, 685, 198, 220, 220, 220, 2...
1.933014
209
from abc import ABCMeta, abstractmethod
[ 6738, 450, 66, 1330, 9738, 48526, 11, 12531, 24396, 628 ]
4.1
10
from rest_framework.routers import DefaultRouter from .views import PermissionsViewset, GroupPermissionsViewset permission_router = DefaultRouter() permission_router.register(r'permissions', PermissionsViewset, basename="permissions") permission_router.register(r'grouppermissions', GroupPermissionsViewset, basename="grouppermissions")
[ 6738, 1334, 62, 30604, 13, 472, 1010, 1330, 15161, 49, 39605, 198, 6738, 764, 33571, 1330, 2448, 8481, 7680, 2617, 11, 4912, 5990, 8481, 7680, 2617, 628, 198, 525, 3411, 62, 472, 353, 796, 15161, 49, 39605, 3419, 198, 525, 3411, 62, ...
3.634409
93
#!/usr/bin/env python # encoding: utf-8 """Classes used for rendering (parts) of the canvas. Every parsed :class:`~inscriptis.model.html_element.HtmlElement` writes its textual content to the canvas which is managed by the following three classes: - :class:`Canvas` provides the drawing board on which the HTML page is serialized and annotations are recorded. - :class:`~inscriptis.model.canvas.block.Block` contains the current line to which text is written. - :class:`~inscriptis.model.canvas.prefix.Prefix` handles indentation and bullets that prefix a line. """ from inscriptis.annotation import Annotation from inscriptis.html_properties import WhiteSpace, Display from inscriptis.model.canvas.block import Block from inscriptis.model.html_element import HtmlElement from inscriptis.model.canvas.prefix import Prefix
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 37811, 9487, 274, 973, 329, 14837, 357, 42632, 8, 286, 262, 21978, 13, 198, 198, 6109, 44267, 1058, 4871, 25, 63, 93, 1040, 6519, 271, 13,...
3.421053
247
# -*- coding: utf-8 -*- """ zoom.tests.webdriver_tests.test_admin test admin app functions """ from zoom.testing.webtest import AdminTestCase
[ 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 220, 220, 220, 19792, 13, 41989, 13, 12384, 26230, 62, 41989, 13, 9288, 62, 28482, 628, 220, 220, 220, 1332, 13169, 598, 5499, 198, 37811, 198, 1...
2.689655
58
import json import torch from flask import Flask, request, jsonify from flask_limiter import Limiter from flask_limiter.util import get_remote_address from model.lofi2lofi_model import Decoder as Lofi2LofiDecoder from model.lyrics2lofi_model import Lyrics2LofiModel from server.lofi2lofi_generate import decode from server.lyrics2lofi_predict import predict device = "cpu" app = Flask(__name__) limiter = Limiter( app, key_func=get_remote_address, default_limits=["30 per minute"] ) lofi2lofi_checkpoint = "checkpoints/lofi2lofi_decoder.pth" print("Loading lofi model...", end=" ") lofi2lofi_model = Lofi2LofiDecoder(device=device) lofi2lofi_model.load_state_dict(torch.load(lofi2lofi_checkpoint, map_location=device)) print(f"Loaded {lofi2lofi_checkpoint}.") lofi2lofi_model.to(device) lofi2lofi_model.eval() lyrics2lofi_checkpoint = "checkpoints/lyrics2lofi.pth" print("Loading lyrics2lofi model...", end=" ") lyrics2lofi_model = Lyrics2LofiModel(device=device) lyrics2lofi_model.load_state_dict(torch.load(lyrics2lofi_checkpoint, map_location=device)) print(f"Loaded {lyrics2lofi_checkpoint}.") lyrics2lofi_model.to(device) lyrics2lofi_model.eval()
[ 11748, 33918, 198, 198, 11748, 28034, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 33918, 1958, 198, 6738, 42903, 62, 2475, 2676, 1330, 7576, 2676, 198, 6738, 42903, 62, 2475, 2676, 13, 22602, 1330, 651, 62, 47960, 62, 21975, 198, 198, ...
2.657596
441
#!/usr/bin/env python3 ''' Cryptowat.ch API https://cryptowat.ch/docs/api https://api.cryptowat.ch/markets/prices ''' import urllib.request, json, datetime, time from urllib.request import urlopen from pathlib import Path csv_file_price = Path(__file__).parents[0] / 'data' / 'cryptowatch-bitcoin-price2.csv' if __name__ == '__main__': #main() while True: now = datetime.datetime.now() while (now.second % 5): now = datetime.datetime.now() print(now.second) time.sleep(0.5) main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 7061, 6, 198, 23919, 322, 265, 13, 354, 7824, 198, 5450, 1378, 29609, 322, 265, 13, 354, 14, 31628, 14, 15042, 198, 5450, 1378, 15042, 13, 29609, 322, 265, 13, 354, 14, 34162, ...
2.253061
245
# -*- coding: utf-8 -*- """actor_critic.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/17Gpya9yswf-xonOvKhoHpmQGhCYpq8x4 """ # !pip install box2d-py # !pip install gym[Box_2D] import torch from torch import nn from torch.nn import functional as F import numpy as np import gym import os agent = Agent() agent.play() torch.save(agent.ac_network.state_dict(), agent.MODEL_PATH)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 11218, 62, 22213, 291, 13, 541, 2047, 65, 198, 198, 38062, 4142, 7560, 416, 1623, 4820, 2870, 13, 198, 198, 20556, 2393, 318, 5140, 379, 198, 220, 220, 220, 374...
2.597701
174
#!/usr/bin/env python # coding: UTF-8 import os import struct from .sta import * import json import copy import base64 from collections import OrderedDict def unpack_obj(stream, **kwargs): """ Convert an stream(sta format) to object(json format) :param stream: Stream of binary sta file :param workshop: path to write binary file :param getway: the getway to all values :param binary_mode: 0(default): means write @base64@... 1: means @file@path 2: means write @binary@size 3: means str for binary memory :return: unpacked object """ mark = struct.unpack('=b', stream.read(1))[0] if mark == STA_NIL: return unpack_nil(stream, **kwargs) elif mark == STA_INT: return unpack_int(stream, **kwargs) elif mark == STA_FLOAT: return unpack_float(stream, **kwargs) elif mark == STA_STRING: return unpack_string(stream, **kwargs) elif mark == STA_BINARY: return unpack_binary(stream, **kwargs) elif mark == STA_LIST: return unpack_list(stream, **kwargs) elif mark == STA_DICT: return unpack_dict(stream, **kwargs) else: raise Exception("Unsupported mark type: ", type(mark)) def sta2obj(sta_filename, **kwargs): """ Convert filename.sta to object :param sta_filename: input sta filename :param binary_mode: 0(default): means write @base64@... 1: means @file@path 2: means write @binary@size 3: means str for binary memory :return: """ byte = '' with open(sta_filename, 'rb') as ifile: byte = ifile.read() stream = Stream(byte) mark = struct.unpack('=i', stream.read(4))[0] if mark != STA_MARK: raise Exception("%s is not a valid sta file." % sta_filename) # kwargs = {} if 'binary_mode' not in kwargs: kwargs['binary_mode'] = 0 obj = unpack_obj(stream, **kwargs) return obj def sta2json(sta_filename, json_filename=None, **kwargs): """ Convert filename.sta to filename.json. :param sta_filename: input sta filename :param json_filename: output json filename or path :param binary_mode: 0(default): means write @base64@... 1: means @file@path 2: means write @binary@size 3: means str for binary memory :return: """ filepath, filename_ext = os.path.split(sta_filename) filename, ext = os.path.splitext(filename_ext) if json_filename is None: json_filename = os.path.join(filepath, filename + ".json") if os.path.isdir(json_filename): json_filename = os.path.join(json_filename, filename + ".json") workshop, getway_ext = os.path.split(json_filename) getway = os.path.splitext(getway_ext)[0] if len(workshop) > 0 and not os.path.isdir(workshop): raise Exception("%s/ is not a valid path." % workshop) with open(json_filename, 'w') as ofile: byte = '' with open(sta_filename, 'rb') as ifile: byte = ifile.read() stream = Stream(byte) mark = struct.unpack('=i', stream.read(4))[0] if mark != STA_MARK: raise Exception("%s is not a valid sta file." % sta_filename) kwargs['workshop'] = workshop kwargs['getway'] = getway if 'binary_mode' not in kwargs: kwargs['binary_mode'] = 1 obj = unpack_obj(stream, **kwargs) json.dump(obj, ofile, indent=2)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 41002, 12, 23, 198, 198, 11748, 28686, 198, 11748, 2878, 198, 6738, 764, 38031, 1330, 1635, 198, 11748, 33918, 198, 11748, 4866, 198, 11748, 2779, 2414, 198, 6738, 17268, ...
2.286078
1,573
#!/usr/bin/python3 """ Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence. For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8). Two binary trees are considered leaf-similar if their leaf value sequence is the same. Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar. Note: Both of the given trees will have between 1 and 100 nodes. """ # Definition for a binary tree node.
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 37811, 198, 19626, 477, 262, 5667, 286, 257, 13934, 5509, 13, 220, 3574, 1364, 284, 826, 1502, 11, 262, 3815, 198, 1659, 883, 5667, 1296, 257, 12835, 1988, 8379, 13, 198, 198, 1890, 167...
3.627586
145
from datetime import datetime, timedelta from typing import Optional from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from passlib.context import CryptContext from apollo.crud import query_first_user from apollo.main import site_settings from apollo.schemas import TokenData, UserModel oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/token") pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 201, 198, 6738, 19720, 1330, 32233, 201, 198, 201, 198, 6738, 3049, 15042, 1330, 2129, 2412, 11, 14626, 16922, 11, 3722, 201, 198, 6738, 3049, 15042, 13, 12961, 1330, 440, 30515, 17,...
3
177
from App import App from utils.get_screen_size import get_screen_size if __name__ == "__main__": app = App() h, w, ch = get_screen_size() while True: app.proccessing(h, w, ch)
[ 6738, 2034, 1330, 2034, 198, 6738, 3384, 4487, 13, 1136, 62, 9612, 62, 7857, 1330, 651, 62, 9612, 62, 7857, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 598, 796, 2034, 3419, 198, 220, 220, ...
2.352941
85
#!/usr/bin/python2.4 # # Copyright 2008 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 common.py.""" import warnings from graphy import common from graphy import graphy_test from graphy.backends import google_chart_api if __name__ == '__main__': graphy_test.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 13, 19, 198, 2, 198, 2, 15069, 3648, 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.495614
228
# Download the data you import os import tarfile import requests
[ 2, 10472, 262, 1366, 345, 198, 11748, 28686, 198, 11748, 13422, 7753, 198, 11748, 7007, 198 ]
4.0625
16
""" A place to implement built-in functions. We use the bytecode for these when doing cross-version interpreting """ from xpython.pyobj import Function, Cell, make_cell from xdis import codeType2Portable, PYTHON_VERSION, IS_PYPY # This code was originally written by Darius Bacon, # but follows code from PEP 3115 listed below. # Rocky Bernstein did the xdis adaptions and # added a couple of bug fixes. def build_class(opc, func, name, *bases, **kwds): """ Like built-in __build_class__() in bltinmodule.c, but running in the byterun VM. See also: PEP 3115: https://www.python.org/dev/peps/pep-3115/ and https://mail.python.org/pipermail/python-3000/2007-March/006338.html """ # Parameter checking... if not (isinstance(func, Function)): raise TypeError("func must be a PyVM function") if not isinstance(name, str): raise TypeError("name is not a string") metaclass = kwds.pop("metaclass", None) if metaclass is None: metaclass = type(bases[0]) if bases else type if isinstance(metaclass, type): metaclass = calculate_metaclass(metaclass, bases) if hasattr(metaclass, "__prepare__"): prepare = metaclass.__prepare__ namespace = prepare(name, bases, **kwds) else: namespace = {} python_implementation = "PyPy" if IS_PYPY else "CPython" if not ( opc.version == PYTHON_VERSION and python_implementation == opc.python_implementation ): # convert code to xdis's portable code type. class_body_code = codeType2Portable(func_code(func)) else: class_body_code = func.func_code # Execute the body of func. This is the step that would go wrong if # we tried to use the built-in __build_class__, because __build_class__ # does not call func, it magically executes its body directly, as we # do here (except we invoke our PyVM instead of CPython's). # # This behavior when interpreting bytecode that isn't the same as # the bytecode using in the running Python can cause a SEGV, specifically # between Python 3.5 running 3.4 or earlier. frame = func._vm.make_frame( code=class_body_code, f_globals=func.func_globals, f_locals=namespace, closure=func.__closure__, ) # rocky: cell is the return value of a function where? cell = func._vm.eval_frame(frame) # Add any class variables that may have been added in running class_body_code. # See test_attribute_access.py for a simple example that needs the update below. namespace.update(frame.f_locals) # If metaclass is builtin "type", it can't deal with a xpython.pyobj.Cell object # but needs a builtin cell object. make_cell() can do this. if "__classcell__" in namespace and metaclass == type: namespace["__classcell__"] = make_cell(namespace["__classcell__"].get()) try: cls = metaclass(name, bases, namespace) except TypeError: # For mysterious reasons the above can raise a: # __init__() takes *n* positional arguments but *n+1* were given. # In particular for: # class G(Generic[T]): # pass import types cls = types.new_class(name, bases, kwds, exec_body=lambda ns: namespace) pass if isinstance(cell, Cell): cell.set(cls) return cls # From Pypy 3.6 # def find_metaclass(bases, namespace, globals, builtin): # if '__metaclass__' in namespace: # return namespace['__metaclass__'] # elif len(bases) > 0: # base = bases[0] # if hasattr(base, '__class__'): # return base.__class__ # else: # return type(base) # elif '__metaclass__' in globals: # return globals['__metaclass__'] # else: # try: # return builtin.__metaclass__ # except AttributeError: # return type def calculate_metaclass(metaclass, bases): "Determine the most derived metatype." winner = metaclass for base in bases: t = type(base) if issubclass(t, winner): winner = t elif not issubclass(winner, t): raise TypeError("metaclass conflict", winner, t) return winner
[ 37811, 198, 32, 1295, 284, 3494, 3170, 12, 259, 5499, 13, 198, 198, 1135, 779, 262, 18022, 8189, 329, 777, 618, 1804, 3272, 12, 9641, 35391, 198, 37811, 198, 198, 6738, 2124, 29412, 13, 9078, 26801, 1330, 15553, 11, 12440, 11, 787, ...
2.503817
1,703
# import the necessary packages import os # Set the dataset base path here BASE_PATH = "/content/Keras-retinanet-Training-on-custom-datasets-for-Object-Detection--/dataset" # build the path to the annotations and input images ANNOT_PATH = os.path.sep.join([BASE_PATH, 'annotations']) IMAGES_PATH = os.path.sep.join([BASE_PATH, 'images']) # degine the training/testing split # If you have only training dataset then put here TRAIN_TEST_SPLIT = 1 TRAIN_TEST_SPLIT = 0.80 # build the path to the output training and test .csv files TRAIN_CSV = os.path.sep.join([BASE_PATH, 'train.csv']) TEST_CSV = os.path.sep.join([BASE_PATH, 'test.csv']) # build the path to the output classes CSV files CLASSES_CSV = os.path.sep.join([BASE_PATH, 'classes.csv']) # build the path to the output predictions dir OUTPUT_DIR = os.path.sep.join([BASE_PATH, 'predictions'])
[ 2, 1330, 262, 3306, 10392, 198, 11748, 28686, 198, 198, 2, 5345, 262, 27039, 2779, 3108, 994, 198, 33, 11159, 62, 34219, 796, 12813, 11299, 14, 42, 263, 292, 12, 1186, 259, 272, 316, 12, 44357, 12, 261, 12, 23144, 12, 19608, 292, ...
2.738019
313
# -*- coding: utf-8 -*- # Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, # DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS # SOFTWARE. __author__ = 'essepuntato' import os import requests import codecs import argparse import re if __name__ == "__main__": arg_parser = argparse.ArgumentParser("static_lode.py") arg_parser.add_argument("-pu", "--prefix-url", dest="prefurl", required=True, help="The prefix followed by a ':' plus the URL of the ontology to convert.") arg_parser.add_argument("-o", "--output-dir", dest="output_dir", required=True, help="The directory where to store the documentation files created.") arg_parser.add_argument("-s", "--source-material-url", dest="source_material_url", help="The directory that contains all the LODE related files for " "presentation on the browser.") arg_parser.add_argument("-l", "--lode-url", dest="lode_url", default="http://eelst.cs.unibo.it/apps/LODE", help="The URL where LODE is available.") arg_parser.add_argument("-lang", "--language", dest="language", default="en", help="The ISO code of the language used to retrieve the documentation " "(default: 'en?).") arg_parser.add_argument("-repl", "--string-replace", dest="string_replace", help="A 'source->replace' regular expression for replacement of strings.") args = arg_parser.parse_args() all_ontologies_url = {} split_input = args.prefurl.split(":", 1) all_ontologies_url.update({split_input[0]: split_input[1]}) sl = StaticLODE(args.output_dir, all_ontologies_url, args.language, args.source_material_url, args.lode_url, args.string_replace) sl.create_documentation() # How to call it for a specific ontology: # python static_lode.py -pu fabio:http://purl.org/spar/fabio -o spar/ontology_documentations -s /static/lode
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 1584, 11, 4243, 85, 952, 2448, 14651, 1279, 35270, 79, 2797, 5549, 31, 14816, 13, 785, 29, 198, 2, 198, 2, 2448, 3411, 284, 779, 11, 4866, 11...
2.569159
1,070
import re import os from collections import OrderedDict as odict from .conf import USER_DIR from .util import cacheattr, setcwd, runsyscmd, logdbg from . import util from . import err _cache_entry = r'^(.*?)(:.*?)=(.*)$' def loadvars(builddir): """if builddir does not exist or does not have a cache, returns an empty odict""" v = odict() if builddir is None or not os.path.exists(builddir): return v c = os.path.join(builddir, 'CMakeCache.txt') if os.path.exists(c): with open(c, 'r') as f: for line in f: # logdbg("loadvars0", line.strip()) if not re.match(_cache_entry, line): continue ls = line.strip() name = re.sub(_cache_entry, r'\1', ls) vartype = re.sub(_cache_entry, r'\2', ls)[1:] value = re.sub(_cache_entry, r'\3', ls) # logdbg("loadvars1", name, vartype, value) v[name] = CMakeCacheVar(name, value, vartype) return v # ----------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- def _remove_invalid_args_from_sysinfo_cmd(cmd): gotit = None # remove compile commands args for i, elm in enumerate(cmd): if 'CMAKE_EXPORT_COMPILE_COMMANDS' in elm: # can't strip out if compile commands is not given as one, # because the command will become malformed when we remove if elm not in ('-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', '-DCMAKE_EXPORT_COMPILE_COMMANDS=OFF'): raise Exception("malformed command") gotit = i if gotit is not None: del cmd[gotit] # remove architecture args if '-A' in cmd: i = cmd.index('-A') del cmd[i+1] del cmd[i] # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # def get_toolchain_cache(toolchain): # d = os.path.join(USER_DIR, 'toolchains', re.sub(os.sep, '+', toolchain)) # logdbg("toolchain cache: USER_DIR=", USER_DIR) # logdbg("toolchain cache: d=", d) # bd = os.path.join(d, 'build') # logdbg("toolchain cache: bd=", bd) # if not os.path.exists(d): # os.makedirs(d) # with setcwd(d): # with open('main.cpp', 'w') as f: # f.write("int main() {}") # with open('CMakeLists.txt', 'w') as f: # f.write(""" # cmake_minimum_required(VERSION 2.6) # project(toolchain_test) # add_executable(main main.cpp) # """) # if not os.path.exists(bd): # os.makedirs(bd) # with setcwd(bd): # cmd = ['cmake', '-DCMAKE_TOOLCHAIN_FILE='+toolchain, '..'] # runsyscmd(cmd, echo_output=True) # return loadvars(bd)
[ 11748, 302, 198, 11748, 28686, 198, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 355, 267, 11600, 198, 198, 6738, 764, 10414, 1330, 1294, 1137, 62, 34720, 198, 6738, 764, 22602, 1330, 12940, 35226, 11, 900, 66, 16993, 11, 4539, 28349, ...
2.595097
1,346
#!/usr/bin/env python __author__ = "bt3" import random ''' The simplest way...''' ''' If you don't want to use pythons feature at all and also select pivot randomly''' if __name__ == '__main__': # Checking the Answer seq = [10, 60, 100, 50, 60, 75, 31, 50, 30, 20, 120, 170, 200] #seq = [3, 7, 2, 1, 4, 6, 5, 10, 9, 11] # we want the middle element k = len(seq) // 2 # Note that this only work for odd arrays, since median in # even arrays is the mean of the two middle elements print(quickSelect(seq, k)) print(quickSelectHard(seq, k)) import numpy print numpy.median(seq)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 834, 9800, 834, 796, 366, 18347, 18, 1, 628, 198, 11748, 4738, 198, 198, 7061, 6, 383, 24043, 835, 986, 7061, 6, 628, 198, 198, 7061, 6, 1002, 345, 836, 470, 765, 284, 779, ...
2.591837
245
import numpy as np import cv2 import sys import os #######################RGB Image Data Analysis############################################################ ###Should follow the data structure of image data: Genotype --> Replicates (Plants) --> Different Views --> Image captured by each Day### # mfold defines the folder name that stores the data in our data structure mfold = sys.argv[1] # The ratio between pixels further zoom level and closer zoom level is 1:2.02, each pixel in closer zoom level is 0.746mm. This script generates values based on pixel counts. # binary function is going to extract green pixels by defined threshold of (2*G)/(R+B) > 1.15 # create a function to extract values of plant height, plant width and plant area pixel counts whole = os.listdir(mfold) # because two zoom levels were applied on the RGB images in different days, and we analyze plant images in two zoom levels close = set([]) far = set([]) for i in range(1,27): close.add('Day_'+str(i).zfill(3)) close.remove('Day_'+str(11).zfill(3)) for i in range(27,33): far.add('Day_'+str(i).zfill(3)) far.add('Day_'+str(11).zfill(3)) # out is the file with extracted numeric values from RGB images out = open('RGB_extraction.csv','w') # create this file to trace some image files that can not load correctly to make sure the whole loop can go correctly error = open('RGB_extraction_error.csv','w') out.write('PlantID'+'\t'+'Date'+'\t'+'View'+'\t'+'Plant Height'+'\t'+'Plant Width'+'\t'+'Projected Plant Area'+'\n') views = ['VIS SV 0','VIS SV 90'] for j1 in sorted(whole): if j1 == 'Genotype_ZL022':continue for i1 in os.listdir('{0}/{1}'.format(mfold,j1)): for v in views: for d1 in sorted(os.listdir('{0}/{1}/{2}/{3}/'.format(mfold,j1,i1,v))): nlist = [i1,d1.replace('.png','')] myview = 'View'+v.replace('VIS SV ','') na = [myview,'NA','NA','NA'] date = d1.replace('.png','') try: abc = cv2.imread('{0}/{1}/{2}/{3}/{4}'.format(mfold,j1,i1,v,d1)) abc = abc.astype(np.float) imgreen = (2*abc[:,:,1])/(abc[:,:,0]+abc[:,:,2]) if date in close: thresh = binary(imgreen,50,1950,335,2280) elif date in far: thresh = binary(imgreen,50,1450,815,1780) cv2.imwrite('test.jpg',thresh) thresh = cv2.imread("test.jpg",cv2.CV_LOAD_IMAGE_GRAYSCALE) h,w,area,areas0 = call_numeric(thresh) total = max(areas0) k = areas0.index(total) del areas0[k] for i in areas0: total -= i nlist.append(myview) if date in far: nlist.append(str(float(h)*2.02)) nlist.append(str(float(w)*2.02)) nlist.append(str(float(total))) else: nlist.append(h) nlist.append(w) nlist.append(total) except: nlist.extend(na) error.write(j1+':'+i1+':'+v+':'+d1+'\n') out.write('\t'.join(nlist)+'\n') out.close() error.close()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 220, 198, 11748, 25064, 198, 11748, 28686, 198, 14468, 4242, 21017, 36982, 7412, 6060, 14691, 29113, 14468, 7804, 4242, 198, 21017, 19926, 1061, 262, 1366, 4645, 286, 2939, 1366, 25,...
2.37594
1,197
import numpy as np from . import vector as V def blend_skinning(pts, BW, rbms, method='lbs'): """ perform blend skinning of pts given blend weights BW and the 4x4 rigid body motions in rbms pts should be an array of points, so the shape should be (num_points, 3) BW should be an array of blendweights, so the shape should be (num_points, num_rbms) where num_rbms give the number of rigid body motion parts (joints) rbms should be an array of shape (num_rbms, 4, 4) - one rigid body motions for each column in BW supported methods are "lbs" (linear blend skinning) and "dq" (dual quaternion skinning) """ # TODO use masked arrays to accellerate? if method == 'lbs': transformed_pts = np.tensordot(V.hom(pts), rbms, axes=(1, 2)) if transformed_pts.shape[-1] == 4: transformed_pts = V.dehom(transformed_pts) return np.sum(BW[:,:,np.newaxis] * transformed_pts, axis=1) elif method == 'dq': rbms = np.asanyarray(rbms) dqs = np.array(list(map(rbm_to_dualquat, rbms))) return dq_skinning(pts, BW, dqs) else: raise ValueError("Unknown skinning method")
[ 11748, 299, 32152, 355, 45941, 198, 6738, 764, 1330, 15879, 355, 569, 628, 198, 4299, 13516, 62, 20407, 768, 7, 457, 82, 11, 37869, 11, 374, 65, 907, 11, 2446, 11639, 32133, 6, 2599, 198, 220, 220, 220, 37227, 220, 198, 220, 220, ...
2.431772
491
# coding: utf-8 # Team : uyplayer team # Author uyplayer # Date 2019/11/20 4:22 # Tool PyCharm ''' https://blog.csdn.net/c9Yv2cf9I06K2A9E/article/details/79739287 https://msd.misuland.com/pd/13340603045208861 '''
[ 2, 19617, 25, 3384, 69, 12, 23, 201, 198, 2, 4816, 1058, 220, 334, 88, 7829, 1074, 201, 198, 2, 6434, 334, 88, 7829, 220, 201, 198, 2, 7536, 13130, 14, 1157, 14, 1238, 604, 25, 1828, 201, 198, 2, 16984, 9485, 1925, 1670, 201, ...
2.00885
113
""" Write a Python program that reads a date (from 2016/1/1 to 2016/12/31) and prints the day of the date. Jan. 1, 2016, is Friday. Note that 2016 is a leap year. """ from datetime import date print("Input month and date(separated by a single space): ") m, d = map(int, input().split()) weeks = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4:"Thursday", 5: "Friday", 6: "Saturday", 7: "sunday"} w = date.isoweekday(date(2016, m, d)) print("Name of the date: ", weeks[w]) #Reference: w3resources
[ 37811, 198, 16594, 257, 11361, 1430, 326, 9743, 257, 3128, 357, 6738, 1584, 14, 16, 14, 16, 284, 1584, 14, 1065, 14, 3132, 8, 290, 20842, 262, 1110, 286, 262, 3128, 13, 198, 12128, 13, 352, 11, 1584, 11, 318, 3217, 13, 220, 198, ...
2.906433
171
""" nn : n(1n1000),nn(100), : n 1 9 cap to cat card two too up boat boot boat boot cap card cat to too two up """ list = [] n = int(input()) for i in range(0, n): s = input() list.append(s) list.sort() for i in list: print(i)
[ 37811, 198, 198, 20471, 198, 25, 198, 77, 7, 16, 77, 12825, 828, 20471, 7, 3064, 828, 198, 25, 198, 77, 198, 16, 198, 198, 24, 198, 11128, 198, 1462, 198, 9246, 198, 9517, 198, 11545, 198, 18820, 198, 929, 198, 24482, 198, 18769, ...
1.914063
128
import jsonhandler from LuyckxFeatures import * import timblClassification as timbl import os import numpy as np from collections import Counter dictPath = "c10" jsonhandler.loadJson(dictPath) jsonhandler.loadTraining() candidates = jsonhandler.candidates unknowns = jsonhandler.unknowns authors = list() uAuthors = list() for cand in candidates: a = author(cand) for fileName in jsonhandler.trainings[cand]: fName = '%s/%s/%s' % (dictPath, cand, fileName) pName = '%s/%s/%s' % (dictPath, cand, os.path.splitext(fileName)[0] + '.mbsp') a.addDoc(fName, pName) authors.append(a) for unknown in unknowns: fName = '%s/unknown/%s' % (dictPath, unknown) pName = '%s/unknown/%s' % (dictPath, os.path.splitext(unknown)[0] + '.mbsp') a = author(os.path.splitext(unknown)[0]) a.addDoc(fName, pName) uAuthors.append(a) docs = getAllDocuments(authors + uAuthors) globalFeatures = dict.fromkeys((docs[0].features.keys())) accuracy = dict.fromkeys((docs[0].features.keys())) predict = dict.fromkeys((docs[0].features.keys())) for idk, key in enumerate(globalFeatures.keys()): globalFeatures[key] = globalFeature(key, docs) train_fName = '%s/%s_training.c5' % (dictPath, key) test_fName = '%s/%s_test.c5' % (dictPath, key) exportC5(getAllDocuments(authors), authors, globalFeatures[key], 50, train_fName) exportC5(getAllDocuments(uAuthors), uAuthors, globalFeatures[key], 50, test_fName) noFeatures = len(Counter(globalFeatures[key].chi2).most_common(50)) predict[key] = timbl.classify(train_fName, test_fName, noFeatures) os.remove(train_fName) os.remove(test_fName) # jsonhandler.storeJson(unknowns, predict) jsonhandler.loadGroundTruth() with open('%s/results' % dictPath, 'w') as rHandle: for key in globalFeatures.keys(): cMatrix = timbl.confusionMatrix(jsonhandler.trueAuthors, predict[key]) accuracy[key] = np.sum(np.diag(cMatrix)) / np.sum(cMatrix) rHandle.write('%s \t %.4f \n' % (key, accuracy[key]))
[ 11748, 33918, 30281, 198, 6738, 406, 4669, 694, 87, 23595, 1330, 1635, 198, 11748, 4628, 2436, 9487, 2649, 355, 4628, 2436, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 17268, 1330, 15034, 628, 220, 220, 220, 220, 1...
2.409874
871
from bs4 import BeautifulSoup from multiprocessing import Pool import requests if __name__ == "__main__": print(bus())
[ 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 18540, 305, 919, 278, 1330, 19850, 198, 11748, 7007, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220...
2.75
48
# -*- coding: utf-8 -*- """ Created on Mon Nov 23 13:54:58 2020 @author: Patrice CHANOL & Corentin MORVAN--CHAUMEIL """ import numpy as np import torch import time import visualisation from datetime import datetime def main(model, criterion, optimizer, scheduler, data_train_loader, data_test_loader, num_epochs, input_window, output_window, batch_size): """ Entrainement du modle et Loss Test. Parameters ---------- model : TYPE DESCRIPTION. model to train criterion : TYPE DESCRIPTION. criterion to compute optimizer : TYPE DESCRIPTION. scheduler : TYPE DESCRIPTION. data_loader_train : TYPE DESCRIPTION. train set data_loader_test : TYPE DESCRIPTION. test set num_epochs : TYPE DESCRIPTION. number of epoch to compute input_window : TYPE DESCRIPTION. input windonw length output_window : TYPE DESCRIPTION. output windonw length batch_size : TYPE DESCRIPTION. batch_size Returns ------- model : TYPE DESCRIPTION. trained model test_loss_list : TYPE DESCRIPTION. test loss """ device = torch.device("cuda" if torch.cuda.is_available() else "cpu") dateTimeObj = datetime.now() print('Dbut Entrainement : ', dateTimeObj.hour, 'H', dateTimeObj.minute) test_loss_list = [] n_batches = len(data_train_loader) # On va entrainer le modle num_epochs fois for epoch in range(1, num_epochs + 1): # Temps epoch epoch_start_time = time.time() dateTimeObj = datetime.now() print('Dbut epoch', epoch, ':', dateTimeObj.hour, 'H', dateTimeObj.minute) # Modle en mode entrainement model.train() # Pourcentage du Dataset raliser pourcentage = 0. # Loss du batch en cours test_loss_batch = [] # Temps pour raliser 10% start_time = time.time() for batch, ((day_of_week, serie_input), serie_output) in enumerate(data_train_loader): # Initializing a gradient as 0 so there is no mixing of gradient among the batches optimizer.zero_grad() # Forward pass output = model.forward(day_of_week.to(device), serie_input.float().to(device)) loss = criterion(output, serie_output.float().to(device)) # Propagating the error backward loss.backward() # Normalisation des gradients si Transformer if model.name_model == 'Transformer': torch.nn.utils.clip_grad_norm_(model.parameters(), 0.7) # Optimizing the parameters optimizer.step() # Pourcentage rel raliser count_pourcentage = batch / n_batches # Si on a ralis 10% nouveau du Dataset, on test if count_pourcentage >= pourcentage: # Temps des 10% T = time.time() - start_time # Evaluation du model model.eval() with torch.no_grad(): for ((day_of_week_t, serie_input_t), serie_output_t) in data_test_loader: output_t = model.forward(day_of_week_t.to(device), serie_input_t.float().to(device)) loss_t = criterion(output_t, serie_output_t.float().to(device)) test_loss_batch.append(loss_t.item()) test_loss = np.mean(test_loss_batch) test_loss_list.append(test_loss) print('-'*10) print("Pourcentage: {}%, Test Loss : {}, Epoch: {}, Temps : {}s".format(round(100*pourcentage), test_loss, epoch, round(T))) print('-'*10) # Visualisation visualisation.pred_vs_reality(model, input_window, output_window, epoch=epoch, pourcentage=round(100*pourcentage)) pourcentage += 0.1 start_time = time.time() model.train() print('Fin epoch : {}, Temps de l\'epoch : {}s'.format(epoch, round(time.time() - epoch_start_time))) visualisation.forecast(model, input_window, output_window, epoch=epoch) scheduler.step() model.save() return model, test_loss_list
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 5267, 2242, 1511, 25, 4051, 25, 3365, 12131, 198, 198, 31, 9800, 25, 3208, 20970, 5870, 1565, 3535, 1222, 7231, 429, 259, 35208, 53, 1565, ...
2.226653
1,906
import numpy as np import pandas as pd import datetime if __name__=='__main__': CreateFeature('EURUSD', 16, 1)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4818, 8079, 198, 198, 361, 11593, 3672, 834, 855, 6, 834, 12417, 834, 10354, 198, 220, 220, 220, 13610, 38816, 10786, 36, 4261, 29072, 3256, 1467, 11, 35...
2.636364
44
import math import os from argparse import ArgumentParser import numpy as np import torch from pytorch_lightning import Trainer from pytorch_lightning import seed_everything from pytorch_lightning.utilities import rank_zero_info from pytorch_lightning.callbacks import XLAStatsMonitor from torch.utils.data import Dataset, DataLoader from pytorch_lightning import LightningDataModule from mingpt.lr_decay import LearningRateDecayCallback from mingpt.model import GPT if __name__ == '__main__': seed_everything(42) parser = ArgumentParser() parser = Trainer.add_argparse_args(parser) parser.add_argument('--n_layer', default=22, type=int) parser.add_argument('--n_head', default=16, type=int) parser.add_argument('--n_embd', default=720, type=int) parser.add_argument('--learning_rate', default=6e-4, type=float) parser.add_argument('--block_size', default=128, type=int) parser.add_argument('--batch_size', default=64, type=int) parser.add_argument('--num_workers', default=16, type=int) args = parser.parse_args() if not os.path.exists("input.txt"): os.system("wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt") dm = CharDataModule(args.batch_size, args.num_workers, args.block_size) dm.setup() model = GPT( vocab_size=dm.train_dataset.vocab_size, block_size=dm.train_dataset.block_size, n_layer=args.n_layer, n_head=args.n_head, n_embd=args.n_embd, learning_rate=args.learning_rate ) lr_decay = LearningRateDecayCallback( learning_rate=6e-4, warmup_tokens=512 * 20, final_tokens=2 * len(dm.train_dataset) * args.block_size ) trainer = Trainer.from_argparse_args( args, max_epochs=5, tpu_cores=8, gradient_clip_val=1.0, callbacks=[lr_decay, XLAStatsMonitor()], ) trainer.fit(model, datamodule = dm )
[ 11748, 10688, 198, 11748, 28686, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 12972, 13165, 354, 62, 2971, 768, 1330, 31924, 198, 6738, 12972, 13165, 354, 62, 2971, 768...
2.445137
802
# -*- coding: utf-8 -* import requests import json
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 198, 11748, 7007, 198, 11748, 33918, 628, 198 ]
2.65
20
import os import numpy as np from .utils import get_class_names from ..abstract import Loader from ..backend.image import resize_image # IMAGES_PATH = '../datasets/fer2013/fer2013.csv' # LABELS_PATH = '../datasets/fer2013/fer2013new.csv'
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 26791, 1330, 651, 62, 4871, 62, 14933, 198, 6738, 11485, 397, 8709, 1330, 8778, 263, 198, 6738, 11485, 1891, 437, 13, 9060, 1330, 47558, 62, 9060, 198, 198, 2, 453...
2.903614
83
from typing import List
[ 6738, 19720, 1330, 7343 ]
5.75
4
# This Python file uses the following encoding: utf-8 """ MIT License Copyright (c) 2020 Nils DEYBACH & Lo OUDART 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. """ """ It serves as a containers for various utility functions. They can be useful in a multitude of cases. """ from math import cos, sin, radians, degrees, acos, atan2, pi from PySide2.QtCore import QRandomGenerator from PySide2.QtGui import QVector3D, QColor, QQuaternion ######## NUMBER GENERATION ######### """ Return randomly -1 or 1 as a random sign generator. """ ######## ANGLES CONVERTIONS ######### """ Returns rotated quaternion from a rotation (theta) applied to original direction around specified axis. """ """ Returns quaternion rotation from spherical position (following physics convention) with a (1,0,0) oriention initialy. phi, theta: angles in physics convention in degrees. """ """ Returns orientation (following physics convention) to a quaternion representing the rotation needed to get a vector to follow the orientation """ ######## COLORS ######### """ Returns a color from a 3D vector of angles. phi, theta: angles in physics convention in radians. """ """ Returns a random color. """
[ 2, 770, 11361, 2393, 3544, 262, 1708, 21004, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 36393, 13789, 198, 198, 15269, 357, 66, 8, 12131, 399, 4487, 5550, 56, 33, 16219, 1222, 6706, 440, 8322, 7227, 198, 198, 5990, 3411, 318, 29376...
3.721649
582
from correlcalc import * bins = np.arange(0.002,0.062,0.002) #corrdr12flcdmls=tpcf('/usr3/vstr/yrohin/Downloads/galaxy_DR12v5_CMASS_North.fits',bins,randfile='/usr3/vstr/yrohin/randcat_dr12cmn_2x_pdf10k.dat',estimator='ls',cosmology='lcdm',weights='eq') print("--------------------------------------------") corrdr12flcls=tpcf('/usr3/vstr/yrohin/Downloads/galaxy_DR12v5_CMASS_North.fits',bins,randfile='/usr3/vstr/yrohin/randcat_dr12cmn_2x_pdf10k.dat',estimator='ls',cosmology='lcdm',weights=True) print("--------------------------------------------") #corrdr12flcls=tpcf('/usr3/vstr/yrohin/Downloads/galaxy_DR12v5_CMASS_North.fits',bins,randfile='/usr3/vstr/yrohin/randcat_dr12cmn_2x_pdf10k.dat',estimator='ls',cosmology='lc',weights='eq') #print("--------------------------------------------") #corrdr12olcls=tpcf('/usr3/vstr/yrohin/Downloads/galaxy_DR12v5_CMASS_North.fits',bins,randfile='/usr3/vstr/yrohin/randcat_dr12cmn_2x_pdf10k.dat',estimator='ls',cosmology='lc',weights='eq',geometry='open') print("--------------------------------------------") corrdr12flclsw=tpcf('/usr3/vstr/yrohin/Downloads/galaxy_DR12v5_CMASS_North.fits',bins,randfile='/usr3/vstr/yrohin/randcat_dr12cmn_2x_pdf10k.dat',estimator='ls',cosmology='lc',weights=True) print("--------------------------------------------") corrdr12flolsw=tpcf('/usr3/vstr/yrohin/Downloads/galaxy_DR12v5_CMASS_North.fits',bins,randfile='/usr3/vstr/yrohin/randcat_dr12cmn_2x_pdf10k.dat',estimator='ls',cosmology='lc',weights=True,geometry='open')
[ 6738, 10895, 9948, 66, 1330, 1635, 198, 65, 1040, 796, 45941, 13, 283, 858, 7, 15, 13, 21601, 11, 15, 13, 3312, 17, 11, 15, 13, 21601, 8, 198, 2, 10215, 4372, 81, 1065, 2704, 10210, 4029, 82, 28, 34788, 12993, 10786, 14, 14629, ...
2.432039
618
import torch from torchvision import transforms from PIL import Image import numpy as np import math from sklearn.linear_model import LinearRegression from .grid import Grid, grid_split import torch.backends.cudnn as cudnn ''' Global Constants: TASK_NAME: Name of the verification task (deprecated) PATH: The path of the model file. (Initialized in imagenet_verify) mean, stdvar: The normalization parameters of the data. (Initialized in imagenet_verify, default mean=(0.4914,0.4822,0.4465) stdvar=(0.2023,0.1994,0.2010)) delta: The radius of the L-inf Ball. (Initialized in imagenet_verify, default 4/255) significance, error: The significance and the error rate of the PAC-Model. (Initialized in imagenet_verify, default 0.01 and 0.001) final_samples: The number of samples needed to calculate the final margin. (Initialized in imagenet_verify, default 1600, according to defualt error rate and significance) Batchsize: The batchsize of sampling procedure. (Initialized in imagenet_verify, defualt 200) device: Which device to be utilised by Pytorch. (Initialized in imagenet_verify, default 'cuda') model: The Pytorch Network to be verified. (Initialized in imagenet_verify) pretrans: The torchvision transform to process the image. (Resize and Tensorize) normalization_trans: The normalization transform to normalize the data. (Initialized in imagenet_verify) sampling_budget: The sampling limit for each stepwise splitting. (Initialized in imagenet_verify) init_grid: The Grid for Imagenet Data (224*224) Functions: grid_batch_sample: Grid-based Sampling for Scenario Optimization (Untargetted) scenario_optimization: Main Verification Function (Focused Learning, Stepwise-Splitting) imagenet_verify: Entry Function ''' pretrans = transforms.Compose([transforms.Resize((224, 224)), transforms.ToTensor(), ]) mean = (0.485, 0.456, 0.406) stdvar = (0.229, 0.224, 0.225) normalization_trans = transforms.Normalize(mean, stdvar) sampling_budget = 20000 delta = 4/255 error = 1e-2 significance = 1e-3 Batchsize = 200 device = 'cuda' init_grid = [Grid(0, 0, 224, 224)] PATH = './models/imagenet_linf_4.pth'
[ 11748, 28034, 201, 198, 6738, 28034, 10178, 1330, 31408, 201, 198, 6738, 350, 4146, 1330, 7412, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 10688, 201, 198, 6738, 1341, 35720, 13, 29127, 62, 19849, 1330, 44800, 8081, 2234, ...
2.619256
914
from telnetlib import Telnet from exception.exceptions import * from datetime import date import time import os from dotenv import load_dotenv import json load_dotenv() ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) f = open(f'{ROOT_DIR}/equipamentos.json') equipamentos = json.load(f)['equipamentos'] for switch in equipamentos: try: USER = os.environ.get('USER') PASS = os.environ.get('PASS') PORT_TELNET = os.environ.get('PORT_TELNET') print(f"Iniciando Backup no Switch {switch['hostname']}") equipamento = Equipamento(switch['hostname'],switch['ip'],PORT_TELNET,USER,PASS) main(equipamento) except: pass
[ 6738, 13632, 3262, 8019, 1330, 12088, 3262, 198, 6738, 6631, 13, 1069, 11755, 1330, 1635, 198, 6738, 4818, 8079, 1330, 3128, 198, 11748, 640, 198, 11748, 28686, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 11748, 33918, 198...
2.383275
287
#!/usr/bin/env python PROJECT = 'musubi' VERSION = '0.2' import distribute_setup distribute_setup.use_setuptools() from setuptools import setup, find_packages try: long_description = open('README.rst', 'rt').read() except IOError: long_description = 'Uh oh, we may need a new hard drive.' setup( name=PROJECT, version=VERSION, description='Musubi is a command-line DNSBL checker and MX toolkit.', long_description=long_description, author='Rob Cakebread', author_email='cakebread@gmail.com', url='https://github.com/cakebread/musubi', download_url='https://github.com/cakebread/musubi/tarball/master', classifiers=['Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', 'Environment :: Console', ], platforms=['Any'], scripts=[], provides=[], install_requires=['requests', 'dnspython', 'IPy', 'distribute', 'cliff', 'cliff-tablib', 'gevent', 'greenlet'], namespace_packages=[], packages=find_packages(), include_package_data=True, entry_points={ 'console_scripts': [ 'musubi = musubi.main:main' ], 'musubi.cli': [ 'ips = musubi.ips:GetIPs', 'mx = musubi.mx:GetMX', 'spf = musubi.spf:GetSPF', 'scan = musubi.scan:Scan', ], }, zip_safe=False, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 31190, 23680, 796, 705, 14664, 29603, 6, 198, 43717, 796, 705, 15, 13, 17, 6, 198, 198, 11748, 14983, 62, 40406, 198, 17080, 4163, 62, 40406, 13, 1904, 62, 2617, 37623, 10141, 3...
2.273109
714
import os import pandas as pd import click from datetime import date if __name__ == '__main__': preprocess()
[ 11748, 28686, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 3904, 198, 198, 6738, 4818, 8079, 1330, 3128, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 662, 14681, 3419, 198 ]
2.925
40
from time import sleep from sys import stdout if __name__ == "__main__": main()
[ 6738, 640, 1330, 3993, 198, 6738, 25064, 1330, 14367, 448, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.870968
31
from datetime import datetime from sqlalchemy import or_ from app import db from .mixin import ModelMixin
[ 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 6738, 44161, 282, 26599, 1330, 393, 62, 201, 198, 6738, 598, 1330, 20613, 201, 198, 6738, 764, 19816, 259, 1330, 9104, 35608, 259, 201, 198, 201, 198 ]
3.2
35
# Generated by Django 2.2.4 on 2019-08-30 21:56 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 19, 319, 13130, 12, 2919, 12, 1270, 2310, 25, 3980, 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.983333
60
from .alien_config import AlienConfig from .alien_connection import AlienConnection from .alien_tag import AlienTag from .alien_tag_list import AlienTagList
[ 6738, 764, 42690, 62, 11250, 1330, 17610, 16934, 198, 6738, 764, 42690, 62, 38659, 1330, 17610, 32048, 198, 6738, 764, 42690, 62, 12985, 1330, 17610, 24835, 198, 6738, 764, 42690, 62, 12985, 62, 4868, 1330, 17610, 24835, 8053 ]
4.105263
38
from subprocess import run, PIPE main()
[ 6738, 850, 14681, 1330, 1057, 11, 350, 4061, 36, 198, 198, 12417, 3419, 198 ]
2.928571
14
import sys as _sys import pandas as _pd from apodeixi.testing_framework.a6i_unit_test import ApodeixiUnitTest from apodeixi.util.formatting_utils import DictionaryFormatter from apodeixi.util.a6i_error import ApodeixiError, FunctionalTrace from apodeixi.text_layout.column_layout import ColumnWidthCalculator if __name__ == "__main__": # execute only if run as a script main(_sys.argv)
[ 11748, 25064, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 355, 4808, 17597, 198, 11748, 19798, 292, 220, 220, 220, 220, 220, 220,...
2.18552
221
import numpy as np DefaultMate = RandomPickMate
[ 11748, 299, 32152, 355, 45941, 628, 628, 628, 198, 19463, 44, 378, 796, 14534, 31686, 44, 378, 628 ]
3.055556
18
__author__ = 'varun' from django import forms
[ 834, 9800, 834, 796, 705, 7785, 403, 6, 198, 198, 6738, 42625, 14208, 1330, 5107, 198 ]
2.9375
16
# # Copyright (c) 2018 Via Technology Ltd. All Rights Reserved. # Consult your license regarding permissions and restrictions. # """ Administration operations for the geo db. """ import os import socket import time from pru.db.geo.geo_init import load_airspace, remove_all_sectors, tear_down from pru.db.geo.geo_init import load_airports, remove_all_airports from pru.db.geo.geo_init import load_user_airspace, remove_all_user_defined_sectors from pru.db.common_init import create as create_db, DB_TYPE_GEO from pru.db.geo.geo_init import create as create_geo_db from pru.logger import logger import pru.db.context as ctx log = logger(__name__) def remove_geo_db(): """ Remove the db """ remove_all_sectors() remove_all_airports() remove_all_user_defined_sectors() tear_down() def create_geo_database(): """ Create a geo db. """ log.info("Starting to create the geo db") log.info("Waiting for the database to be ready") log.info(f"Testing connection on host: {ctx.geo_db_hostname} and port {ctx.geo_db_port}") # We need to sleep and retry ubtil the db wakes up s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: s.connect((ctx.geo_db_hostname, int(ctx.geo_db_port))) s.close() break except socket.error as ex: log.debug("Database not ready..") time.sleep(5) # 5 seconds between tests log.info("Geo database is now ready.") if create_db(DB_TYPE_GEO): if create_geo_db(): log.info("Geo database creation is complete.") return True else: log.info("Failed to make the airspace db, could not create the tables.") else: log.info("Failed to make the airspace db, could not create the database.") def initialise_airspace(sector_file_path, reset=False): """ Uses the provided file path to load the sectors file, may be csv or geojson. If no sectors file is found we return false. Reset=True Remove all and replace with this file. Reset=False Add these sectors to the sectors table. Note, this is not an update. return True if we succeeded A tuple of (False, message) if we fail """ connection = ctx.get_connection(ctx.CONTEXT, ctx.DB_USER) context = ctx.CONTEXT if os.path.exists(sector_file_path): if reset: remove_all_sectors() load_airspace(sector_file_path, context, connection) return True else: return (False, "Path not found " + sector_file_path) def initialise_airports(airports_file_path, reset=False): """ Uses the provided file path to load an airports file, must be csv. If no airports file is found we return false. Reset=True Remove all and replace with this file. Reset=False Add these airports to the sectors table. Note, this is not an update. return True if we succeeded A tuple of (False, message) if we fail """ connection = ctx.get_connection(ctx.CONTEXT, ctx.DB_USER) context = ctx.CONTEXT if os.path.exists(airports_file_path): if reset: remove_all_airports() load_airports(airports_file_path, context, connection) return True else: return (False, "Path not found " + airports_file_path) def initialise_user_airspace(user_sector_file_path, reset=False): """ Uses the provided file path to load the users sectors file, may be csv or geojson. If no sectors file is found we return false. Reset=True Remove all and replace with this file. Reset=False Add these sectors to the user sectors table. Note, this is not an update. return True if we succeeded A tuple of (False, message) if we fail """ connection = ctx.get_connection(ctx.CONTEXT, ctx.DB_USER) context = ctx.CONTEXT if os.path.exists(user_sector_file_path): if reset: remove_all_user_defined_sectors() load_user_airspace(user_sector_file_path, context, connection) return True else: return (False, "Path not found " + user_sector_file_path)
[ 2, 198, 2, 15069, 357, 66, 8, 2864, 33356, 8987, 12052, 13, 1439, 6923, 33876, 13, 198, 2, 21651, 534, 5964, 5115, 21627, 290, 8733, 13, 198, 2, 198, 198, 37811, 198, 41862, 1358, 4560, 329, 262, 40087, 20613, 13, 198, 37811, 198, ...
2.536527
1,670
from typing import List, Tuple import easymunk as a from easymunk import BB, Vec2d
[ 6738, 19720, 1330, 7343, 11, 309, 29291, 198, 198, 11748, 2562, 76, 2954, 355, 257, 198, 6738, 2562, 76, 2954, 1330, 12597, 11, 38692, 17, 67, 628 ]
3.148148
27
# -*- coding: utf-8 -*- import cffi import ctypes import numpy as np import pandas as pd from darshan.api_def_c import load_darshan_header from darshan.discover_darshan import find_utils from darshan.discover_darshan import check_version API_def_c = load_darshan_header() ffi = cffi.FFI() ffi.cdef(API_def_c) libdutil = None libdutil = find_utils(ffi, libdutil) def log_open(filename): """ Opens a darshan logfile. Args: filename (str): Path to a darshan log file Return: log handle """ b_fname = filename.encode() handle = libdutil.darshan_log_open(b_fname) log = {"handle": handle, 'modules': None, 'name_records': None} return log def log_close(log): """ Closes the logfile and releases allocated memory. """ libdutil.darshan_log_close(log['handle']) #modules = {} return def log_get_job(log): """ Returns a dictionary with information about the current job. """ job = {} jobrec = ffi.new("struct darshan_job *") libdutil.darshan_log_get_job(log['handle'], jobrec) job['uid'] = jobrec[0].uid job['start_time'] = jobrec[0].start_time job['end_time'] = jobrec[0].end_time job['nprocs'] = jobrec[0].nprocs job['jobid'] = jobrec[0].jobid mstr = ffi.string(jobrec[0].metadata).decode("utf-8") md = {} for kv in mstr.split('\n')[:-1]: k,v = kv.split('=', maxsplit=1) md[k] = v job['metadata'] = md return job def log_get_exe(log): """ Get details about the executable (path and arguments) Args: log: handle returned by darshan.open Return: string: executeable path and arguments """ exestr = ffi.new("char[]", 4096) libdutil.darshan_log_get_exe(log['handle'], exestr) return ffi.string(exestr).decode("utf-8") def log_get_mounts(log): """ Returns a list of available mounts recorded for the log. Args: log: handle returned by darshan.open """ mntlst = [] mnts = ffi.new("struct darshan_mnt_info **") cnt = ffi.new("int *") libdutil.darshan_log_get_mounts(log['handle'], mnts, cnt) for i in range(0, cnt[0]): mntlst.append((ffi.string(mnts[0][i].mnt_path).decode("utf-8"), ffi.string(mnts[0][i].mnt_type).decode("utf-8"))) return mntlst def log_get_modules(log): """ Return a dictionary containing available modules including information about the contents available for each module in the current log. Args: log: handle returned by darshan.open Return: dict: Modules with additional info for current log. """ # use cached module index if already present if log['modules'] != None: return log['modules'] modules = {} mods = ffi.new("struct darshan_mod_info **") cnt = ffi.new("int *") libdutil.darshan_log_get_modules(log['handle'], mods, cnt) for i in range(0, cnt[0]): modules[ffi.string(mods[0][i].name).decode("utf-8")] = \ {'len': mods[0][i].len, 'ver': mods[0][i].ver, 'idx': mods[0][i].idx} # add to cache log['modules'] = modules return modules def log_get_name_records(log): """ Return a dictionary resovling hash to string (typically a filepath). Args: log: handle returned by darshan.open hash: hash-value (a number) Return: dict: the name records """ # used cached name_records if already present if log['name_records'] != None: return log['name_records'] name_records = {} nrecs = ffi.new("struct darshan_name_record **") cnt = ffi.new("int *") libdutil.darshan_log_get_name_records(log['handle'], nrecs, cnt) for i in range(0, cnt[0]): name_records[nrecs[0][i].id] = ffi.string(nrecs[0][i].name).decode("utf-8") # add to cache log['name_records'] = name_records return name_records def log_lookup_name_records(log, ids=[]): """ Resolve a single hash to it's name record string (typically a filepath). Args: log: handle returned by darshan.open hash: hash-value (a number) Return: dict: the name records """ name_records = {} #cids = ffi.new("darshan_record_id *") * len(ids) whitelist = (ctypes.c_ulonglong * len(ids))(*ids) whitelist_cnt = len(ids) whitelistp = ffi.from_buffer(whitelist) nrecs = ffi.new("struct darshan_name_record **") cnt = ffi.new("int *") libdutil.darshan_log_get_filtered_name_records(log['handle'], nrecs, cnt, ffi.cast("darshan_record_id *", whitelistp), whitelist_cnt) for i in range(0, cnt[0]): name_records[nrecs[0][i].id] = ffi.string(nrecs[0][i].name).decode("utf-8") # add to cache log['name_records'] = name_records return name_records def log_get_dxt_record(log, mod_name, mod_type, reads=True, writes=True, mode='dict'): """ Returns a dictionary holding a dxt darshan log record. Args: log: Handle returned by darshan.open mod_name (str): Name of the Darshan module mod_type (str): String containing the C type Return: dict: generic log record Example: The typical darshan log record provides two arrays, on for integer counters and one for floating point counters: >>> darshan.log_get_dxt_record(log, "DXT_POSIX", "struct dxt_file_record **") {'rank': 0, 'read_count': 11, 'read_segments': array([...]), ...} """ modules = log_get_modules(log) #name_records = log_get_name_records(log) rec = {} buf = ffi.new("void **") r = libdutil.darshan_log_get_record(log['handle'], modules[mod_name]['idx'], buf) if r < 1: return None filerec = ffi.cast(mod_type, buf) clst = [] rec['id'] = filerec[0].base_rec.id rec['rank'] = filerec[0].base_rec.rank rec['hostname'] = ffi.string(filerec[0].hostname).decode("utf-8") #rec['filename'] = name_records[rec['id']] wcnt = filerec[0].write_count rcnt = filerec[0].read_count rec['write_count'] = wcnt rec['read_count'] = rcnt rec['write_segments'] = [] rec['read_segments'] = [] size_of = ffi.sizeof("struct dxt_file_record") segments = ffi.cast("struct segment_info *", buf[0] + size_of ) for i in range(wcnt): seg = { "offset": segments[i].offset, "length": segments[i].length, "start_time": segments[i].start_time, "end_time": segments[i].end_time } rec['write_segments'].append(seg) for i in range(rcnt): i = i + wcnt seg = { "offset": segments[i].offset, "length": segments[i].length, "start_time": segments[i].start_time, "end_time": segments[i].end_time } rec['read_segments'].append(seg) if mode == "pandas": rec['read_segments'] = pd.DataFrame(rec['read_segments']) rec['write_segments'] = pd.DataFrame(rec['write_segments']) return rec def log_get_generic_record(log, mod_name, mod_type, mode='numpy'): """ Returns a dictionary holding a generic darshan log record. Args: log: Handle returned by darshan.open mod_name (str): Name of the Darshan module mod_type (str): String containing the C type Return: dict: generic log record Example: The typical darshan log record provides two arrays, on for integer counters and one for floating point counters: >>> darshan.log_get_generic_record(log, "POSIX", "struct darshan_posix_file **") {'counters': array([...], dtype=int64), 'fcounters': array([...])} """ modules = log_get_modules(log) rec = {} buf = ffi.new("void **") r = libdutil.darshan_log_get_record(log['handle'], modules[mod_name]['idx'], buf) if r < 1: return None rbuf = ffi.cast(mod_type, buf) rec['id'] = rbuf[0].base_rec.id rec['rank'] = rbuf[0].base_rec.rank clst = [] for i in range(0, len(rbuf[0].counters)): clst.append(rbuf[0].counters[i]) rec['counters'] = np.array(clst, dtype=np.int64) cdict = dict(zip(counter_names(mod_name), rec['counters'])) flst = [] for i in range(0, len(rbuf[0].fcounters)): flst.append(rbuf[0].fcounters[i]) rec['fcounters'] = np.array(flst, dtype=np.float64) fcdict = dict(zip(fcounter_names(mod_name), rec['fcounters'])) if mode == "dict": rec = {'counters': cdict, 'fcounter': fcdict} if mode == "pandas": rec = { 'counters': pd.DataFrame(cdict, index=[0]), 'fcounters': pd.DataFrame(fcdict, index=[0]) } return rec def counter_names(mod_name, fcnts=False): """ Returns a list of available counter names for the module. By default only integer counter names are listed, unless fcnts is set to true in which case only the floating point counter names are listed. Args: mod_name (str): Name of the module to return counter names. fcnts (bool): Switch to request floating point counters instead of integer. (Default: False) Return: list: Counter names as strings. """ if mod_name == 'MPI-IO': mod_name = 'MPIIO' names = [] i = 0 if fcnts: F = "f_" else: F = "" end = "{0}_{1}NUM_INDICES".format(mod_name.upper(), F.upper()) var_name = "{0}_{1}counter_names".format(mod_name.lower(), F.lower()) while True: try: var = getattr(libdutil, var_name) except: var = None if not var: return None name = ffi.string(var[i]).decode("utf-8") if name == end: break names.append(name) i += 1 return names def fcounter_names(mod_name): """ Returns a list of available floating point counter names for the module. Args: mod_name (str): Name of the module to return counter names. Return: list: Available floiting point counter names as strings. """ return counter_names(mod_name, fcnts=True) def log_get_bgq_record(log): """ Returns a darshan log record for BG/Q. Args: log: handle returned by darshan.open """ return log_get_generic_record(log, "BG/Q", "struct darshan_bgq_record **") def log_get_hdf5_file_record(log): """ Returns a darshan log record for an HDF5 file. Args: log: handle returned by darshan.open """ return log_get_generic_record(log, "H5F", "struct darshan_hdf5_file **") def log_get_hdf5_dataset_record(log): """ Returns a darshan log record for an HDF5 dataset. Args: log: handle returned by darshan.open """ return log_get_generic_record(log, "H5D", "struct darshan_hdf5_dataset **") def log_get_lustre_record(log): """ Returns a darshan log record for Lustre. Args: log: handle returned by darshan.open """ modules = log_get_modules(log) rec = {} buf = ffi.new("void **") r = libdutil.darshan_log_get_record(log['handle'], modules['LUSTRE']['idx'], buf) if r < 1: return None rbuf = ffi.cast("struct darshan_lustre_record **", buf) rec['id'] = rbuf[0].base_rec.id rec['rank'] = rbuf[0].base_rec.rank clst = [] for i in range(0, len(rbuf[0].counters)): clst.append(rbuf[0].counters[i]) rec['counters'] = np.array(clst, dtype=np.int64) cdict = dict(zip(counter_names('LUSTRE'), rec['counters'])) # FIXME ostlst = [] for i in range(0, cdict['LUSTRE_STRIPE_WIDTH']): print(rbuf[0].ost_ids[i]) rec['ost_ids'] = np.array(ostlst, dtype=np.int64) print(rec['ost_ids']) sys.exit() if mode == "dict": rec = {'counters': cdict, 'fcounter': fcdict} if mode == "pandas": rec = { 'counters': pd.DataFrame(cdict, index=[0]), 'fcounters': pd.DataFrame(fcdict, index=[0]) } return rec def log_get_mpiio_record(log): """ Returns a darshan log record for MPI-IO. Args: log: handle returned by darshan.open Returns: dict: log record """ return log_get_generic_record(log, "MPI-IO", "struct darshan_mpiio_file **") def log_get_pnetcdf_record(log): """ Returns a darshan log record for PnetCDF. Args: log: handle returned by darshan.open Returns: dict: log record """ return log_get_generic_record(log, "PNETCDF", "struct darshan_pnetcdf_file **") def log_get_posix_record(log): """ Returns a darshan log record for Args: log: handle returned by darshan.open Returns: dict: log record """ return log_get_generic_record(log, "POSIX", "struct darshan_posix_file **") def log_get_stdio_record(log): """ Returns a darshan log record for STDIO. Args: log: handle returned by darshan.open Returns: dict: log record """ return log_get_generic_record(log, "STDIO", "struct darshan_stdio_file **")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 269, 487, 72, 198, 11748, 269, 19199, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 628, 198, 6738, 288, 5406, 272, 13, 15...
2.263475
5,807
from django.conf import settings from rest_framework import generics, status from rest_framework.response import Response from rest_framework_simplejwt.backends import TokenBackend from rest_framework.permissions import IsAuthenticated from authApp.models.user import User from authApp.serializers.userSerializer import UserSerializer
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 1334, 62, 30604, 1330, 1152, 873, 11, 3722, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 1334, 62, 30604, 62, 36439, 73, 46569, 13, 1891, 2412, 1330, 29130, 7282, ...
4.1875
80
import time if __name__ == "__main__": main()
[ 11748, 640, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 201, 198, 220, 220, 220, 1388, 3419, 201, 198 ]
2.111111
27
from django.shortcuts import render, get_object_or_404 from django.views.decorators.cache import cache_page from .models import PhotoAlbum, VideoAlbum from blog.utils import get_pagination_page
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 651, 62, 15252, 62, 273, 62, 26429, 198, 6738, 42625, 14208, 13, 33571, 13, 12501, 273, 2024, 13, 23870, 1330, 12940, 62, 7700, 198, 198, 6738, 764, 27530, 1330, 5555, 2348, 4435, ...
3.283333
60
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function, division, unicode_literals import unittest import os import json from zhihu import Post from test_utils import TEST_DATA_PATH
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 11, 28000, 1098, 62, 17201, 874, 198, 11748, 555, 7...
2.986111
72
from tfutils.helpers import import_transformer import_transformer()
[ 6738, 48700, 26791, 13, 16794, 364, 1330, 1330, 62, 7645, 16354, 198, 198, 11748, 62, 7645, 16354, 3419, 198 ]
3.631579
19
from .modules.linear import LazyBilinear from .modules.mlp import MLP from .modules.mlp import LazyMLP from .modules.normalization import LazyBatchNorm from .modules.normalization import LazyBatchNorm1d from .modules.normalization import LazyBatchNorm2d from .modules.normalization import LazyBatchNorm3d from .modules.normalization import LazyLayerNorm
[ 6738, 764, 18170, 13, 29127, 1330, 406, 12582, 33, 346, 259, 451, 198, 6738, 764, 18170, 13, 4029, 79, 1330, 10373, 47, 198, 6738, 764, 18170, 13, 4029, 79, 1330, 406, 12582, 5805, 47, 198, 6738, 764, 18170, 13, 11265, 1634, 1330, 4...
3.371429
105
import sys import json import numpy as np import imageio from argparse import Namespace def loadenv(config_path): """Load configuration file of Lightmetrica environment""" # Open config file with open(config_path) as f: config = json.load(f) # Add root directory and binary directory to sys.path if config['path'] not in sys.path: sys.path.insert(0, config['path']) if config['bin_path'] not in sys.path: sys.path.insert(0, config['bin_path']) return Namespace(**config) # Environment configuration env = loadenv('.lmenv') def save(path, img): """Save image""" imageio.imwrite(path, np.clip(np.power(img, 1/2.2) * 256, 0, 255).astype(np.uint8))
[ 11748, 25064, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2939, 952, 198, 6738, 1822, 29572, 1330, 28531, 10223, 198, 198, 4299, 3440, 24330, 7, 11250, 62, 6978, 2599, 198, 220, 220, 220, 37227, 8912, 8398, 2393, ...
2.709924
262
s1 = getArray() s2 = getArray() s = merge(s1, s2) output(s)
[ 198, 197, 198, 82, 16, 796, 651, 19182, 3419, 198, 82, 17, 796, 651, 19182, 3419, 198, 82, 796, 20121, 7, 82, 16, 11, 264, 17, 8, 198, 22915, 7, 82, 8, 198 ]
1.909091
33
import csv import json from pprint import pprint import os stockData = ['RIO'] for i in range(0,len(stockData)): csvfile = open(stockData[i]+'.csv', 'r') fieldnames = ("NetworkTime","StockID","Open","High", "Low", "Close", "Adj Close", "Volume") reader = csv.DictReader( csvfile, fieldnames) data = open(stockData[i]+'.json', 'w') data.write('[\n') for row in reader: data.write('{ \n' \ + '"MoteTimestamp": "%s",' %row['NetworkTime'] \ + '\n"MoteID": %s,' %row['StockID'] \ + '\n "StockData":{' \ + '\n "OpenPrice": %s,' %row['Open'] \ + '\n "HighPrice": %s,' %row['High'] \ + '\n "LowPrice": %s,' %row['Low'] \ + '\n "ClosePrice": %s,' %row['Close'] \ + '\n "Adj Close": %s,' %row['Adj Close'] \ + '\n "VolumeNumber": %s' %row['Volume'] \ + '\n }' \ + '\n},\n' ) data.close() with open(stockData[i]+'.json', 'rb+') as filehandle: filehandle.seek(-3, os.SEEK_END) filehandle.truncate() filehandle.close() with open(stockData[i]+'.json', 'a') as filehandle: filehandle.write("\n]")
[ 11748, 269, 21370, 198, 11748, 33918, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 11748, 28686, 198, 198, 13578, 6601, 796, 37250, 7112, 46, 20520, 198, 198, 1640, 1312, 287, 2837, 7, 15, 11, 11925, 7, 13578, 6601, 8, 2599, 198, 220, ...
1.904478
670
import requests
[ 11748, 7007, 628 ]
5.666667
3
import time,sys,os import subprocess st = 0 cmd = ['tasklist','/fo','csv'] subs = set('') # win proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) while True: if st == 0: st = 1 time.sleep(1) #for sub_pid in subs: # ps_line = line.split(',').replace('\"','') # if str(sub_pid) == : # print(str(sub_pid) + '') #print(os.getpid()) # log = popen_obj.returncode #print(log) #print(type(popen_obj.communicate())) #print(popen_obj.communicate())
[ 198, 11748, 640, 11, 17597, 11, 418, 198, 11748, 850, 14681, 628, 198, 198, 301, 796, 657, 198, 28758, 796, 37250, 35943, 4868, 3256, 26488, 6513, 41707, 40664, 20520, 198, 7266, 82, 796, 900, 7, 7061, 8, 198, 2, 1592, 198, 36942, 7...
2.06015
266
#!/usr/bin/env python """ DBS 3 Migrate REST model unittests The DBS3 Migration Service must be stopped before executing the unittest. In addition, take care that no instance is running on the same DB. Else the single unittests can happen to fail due to race conditions with DBS3 Migration Service. """ from dbsserver_t.utils.DBSRestApi import DBSRestApi from dbsserver_t.utils.DBSDataProvider import DBSBlockDataProvider, create_child_data_provider from dbsserver_t.utils.TestTools import expectedFailure from itertools import chain import os import socket import unittest if __name__ == "__main__": SUITE = unittest.TestLoader().loadTestsFromTestCase(DBSMigrateModel_t) unittest.TextTestRunner(verbosity=2).run(SUITE)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 35, 4462, 513, 337, 42175, 30617, 2746, 555, 715, 3558, 198, 198, 464, 360, 4462, 18, 36991, 4809, 1276, 307, 5025, 878, 23710, 262, 555, 715, 395, 13, 554, 3090, 11, 101...
3.20524
229
from setuptools import setup, find_packages # from distutils.core import setup # import py2exe # import sys import os del os.link # sys.setrecursionlimit(5000) with open('requirements.txt') as f: required = f.read().splitlines() setup(name='varta-chat', version='1.0', description='Audio Chat framework', long_description=readme(), url='https://github.com/sgang007/audio_chat_client', author='Shubhojyoti Ganguly', author_email='shubho.important@gmail.com', license='MIT', packages=find_packages(), install_requires=required, entry_points={ 'console_scripts': [ 'varta = client.__main__:key_listener', ] }, include_package_data=True, zip_safe=True)
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 2, 422, 1233, 26791, 13, 7295, 1330, 9058, 198, 2, 1330, 12972, 17, 13499, 198, 2, 1330, 25064, 198, 11748, 28686, 198, 12381, 28686, 13, 8726, 198, 198, 2, 25064, 13, 2...
2.397516
322
# # Copyright (C) 2021 Vaticle # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 sys import unittest from kglib.kgcn_tensorflow.examples.diagnosis.diagnosis import diagnosis_example if __name__ == "__main__": # This handles the fact that additional arguments that are supplied by our py_test definition # https://stackoverflow.com/a/38012249 unittest.main(argv=['ignored-arg'])
[ 2, 198, 2, 220, 15069, 357, 34, 8, 33448, 569, 1512, 293, 198, 2, 198, 2, 220, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 220, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, ...
3.509036
332
# copy of Python 3.5 implementation - probably not needed def gcd(a, b): """Greatest common divisor""" return _gcd_internal(abs(a), abs(b)) def _gcd_internal(a, b): """Greatest common divisor internal""" # Impl. notes: Euler algorithm, both a and b are not negative # There exists faster algorithm (which uses division by 2, which is faster) # -> Stein's algorithm https://en.wikipedia.org/wiki/Binary_GCD_algorithm # print a, b if a == b: return a if b == 1: return 1 if a == 0 or b == 0: return max(a, b) return gcd(b, a % b)
[ 198, 198, 2, 4866, 286, 11361, 513, 13, 20, 7822, 532, 2192, 407, 2622, 628, 198, 4299, 308, 10210, 7, 64, 11, 275, 2599, 198, 220, 220, 220, 37227, 13681, 395, 2219, 2659, 271, 273, 37811, 198, 220, 220, 220, 1441, 4808, 70, 1021...
2.537815
238
import sys sys.path.insert(1, './GR_BASS/BASS_only_original/') sys.path.insert(1, './GR_BASS/') import bass as md import numpy as np import sys import bassLibrary as bl # BASS algorithm parameters eps = 0.1 p_d = 0.2 Jthr = 0.15 seed = 0 # Creating synthetic data for process BASS on and to learn the GMM model nbClasses = 5 classNames = ['a', 'b', 'c', 'd', 'e'] nbInstDataAnalyze = 4000 probElemDictAppear = 0.05 [dataToAnalyze1, dataForLearn] = bl.createSyntheticDataSet(nbClasses, nbInstDataAnalyze, [[3, 2, 1, 0], [0, 1, 2, 3]], [probElemDictAppear, probElemDictAppear]) l = int(len(dataToAnalyze1)/4) lengths_data1 = np.array([l, l, l, l]) # Learning the model with the data previously created model_fit = md.GMM_model(nbClasses) model_fit.solve(dataForLearn) # Launch BASS on the synthetic data previously created posteriorProb1 = bl.getPosteriorProbabilities(dataToAnalyze1, lengths_data1, model_fit) [P_w1, nbInstances1, w_dict1] = bl.launchBASS(posteriorProb1, lengths_data1, model_fit, eps, p_d, Jthr, seed) [transmat_, stationary_probs_, a, b, c] = bl.launchMarkovianCompare(posteriorProb1, lengths_data1, model_fit, eps, p_d, Jthr, seed, w_dict1, classNames, 0, {'nameOfFile' : 'syntheticDataTest'}) # Comparing different dataset with different amounts of insertions for idx, probElemDictAppear2 in enumerate([0.1, 0.05]): print("Comparing two different dataset with SAME amounts of insertions. Probability: ", probElemDictAppear2) [dataToAnalyze2, dataForLearn2] = bl.createSyntheticDataSet(nbClasses, nbInstDataAnalyze, [[3, 2, 1, 0], [0, 1, 2, 3]], [probElemDictAppear2, probElemDictAppear2]) l = int(len(dataToAnalyze2)/4) lengths_data2 = np.array([l, l, l, l]) posteriorProb2 = bl.getPosteriorProbabilities(dataToAnalyze2, lengths_data2, model_fit) [P_w2, nbInstances2, w_dict2] = bl.launchBASS(posteriorProb2, lengths_data2, model_fit, eps, p_d, Jthr, seed) w_thr = 1e-4 p_ins = 0.2 mu = 1.0 H_beta_fac = 0 Sigma = dataToAnalyze1.shape[1] std = 0.05 params = np.array([eps,p_d,p_ins, mu, w_thr,H_beta_fac, Jthr, Sigma, std], dtype =float) bl.compareTwoBASSresults(w_dict1, w_dict2, params, model_fit, dataToAnalyze1, lengths_data1, dataToAnalyze2, lengths_data2, {'nameOfFile' : 'syntheticDataTest'}, classNames, str(idx)) # TODO: change compareTwoBASSresults for it to accept the posterior probabilities posteriorProb1 and posteriorProb2 instead of the data dataToAnalyze1 and dataToAnalyze2
[ 11748, 25064, 198, 17597, 13, 6978, 13, 28463, 7, 16, 11, 705, 19571, 10761, 62, 33, 10705, 14, 33, 10705, 62, 8807, 62, 14986, 14, 11537, 198, 17597, 13, 6978, 13, 28463, 7, 16, 11, 705, 19571, 10761, 62, 33, 10705, 14, 11537, 19...
2.50455
989
from pydantic import BaseModel, EmailStr
[ 6738, 279, 5173, 5109, 1330, 7308, 17633, 11, 9570, 13290, 628 ]
3.818182
11
#! /bin/env python """ Examples ======== **Rectilinear** Create a rectilinear grid that is 2x3:: (0) --- (1) --- (2) | | | | | | | [0] | [1] | | | | | | | (3) --- (4) --- (5) Numbers in parens are node IDs, and numbers in square brackets are cell IDs. >>> g = RectilinearMap ([0, 2], [0, 1, 2]) >>> g.get_x () array([ 0., 1., 2., 0., 1., 2.]) >>> g.get_y () array([ 0., 0., 0., 2., 2., 2.]) Node 1 is shared by both cell 0, and 1; node 5 only is part of cell 1. >>> g.get_shared_cells (1) [0, 1] >>> g.get_shared_cells (5) [1] Point (.5, 1.) is contained only within cell 0. >>> g.is_in_cell (.5, 1., 0) True >>> g.is_in_cell (.5, 1., 1) False Point (1., 1.) is on a border and so is contained by both cells. >>> g.is_in_cell (1, 1., 0) True >>> g.is_in_cell (1, 1., 1) True """ from shapely.geometry import Point, asLineString, asPoint, asPolygon from pymt.grids import ( Rectilinear, Structured, UniformRectilinear, Unstructured, UnstructuredPoints, ) if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
[ 2, 0, 1220, 8800, 14, 24330, 21015, 198, 37811, 198, 27730, 198, 2559, 198, 198, 1174, 45474, 346, 259, 451, 1174, 198, 198, 16447, 257, 13621, 346, 259, 451, 10706, 326, 318, 362, 87, 18, 3712, 628, 220, 220, 220, 357, 15, 8, 114...
2.133452
562
import pygame from conteudo import Conteudo, Nave, Tiro import random
[ 11748, 12972, 6057, 198, 6738, 542, 68, 12003, 1330, 1482, 660, 12003, 11, 399, 1015, 11, 309, 7058, 198, 11748, 4738, 628, 628, 198 ]
3.083333
24
import inspect import typing from di.api.dependencies import CacheKey from di.dependant import Dependant, Marker from xpresso._utils.typing import Protocol from xpresso.binders.api import SupportsExtractor, SupportsOpenAPI T = typing.TypeVar("T", covariant=True)
[ 11748, 10104, 198, 11748, 19720, 198, 198, 6738, 2566, 13, 15042, 13, 45841, 3976, 1330, 34088, 9218, 198, 6738, 2566, 13, 45841, 415, 1330, 2129, 23048, 11, 2940, 263, 198, 198, 6738, 2124, 18302, 568, 13557, 26791, 13, 774, 13886, 133...
3.448718
78
import sys import unittest as ut import numpy as np import xarray as xr # Import from directory structure if coverage test, or from installed # packages otherwise if "--cov" in str(sys.argv): from src.geocat.f2py import grid_to_triple else: from geocat.f2py import grid_to_triple # Size of the grids ny = 2 mx = 3 # Nominal input data = np.asarray([2.740655, 2.745848, 4.893587, 2.965059, 1.707929, 0.746007]).reshape((ny, mx)) # Missing value = np.nan input data_nan = data.copy() data_nan[0, 1] = np.nan data_nan[1, 2] = np.nan # Missing value = -99 input data_msg = data_nan.copy() data_msg[np.isnan(data_msg)] = -99 # Coordinates x = np.asarray([1.0, 3.0, 5.0]) y = np.asarray([2.0, 4.0]) # Expected output out_expected = np.asarray([1, 3, 5, 1, 3, 5, 2, 2, 2, 4, 4, 4, 2.740655, 2.745848, 4.893587, 2.965059, 1.707929, 0.746007])\ .reshape((3, ny * mx)) out_expected_msg = np.asarray([1, 5, 1, 3, 2, 2, 4, 4, 2.740655, 4.893587, 2.965059, 1.707929])\ .reshape((3, 4))
[ 11748, 25064, 198, 11748, 555, 715, 395, 355, 3384, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2124, 18747, 355, 2124, 81, 198, 198, 2, 17267, 422, 8619, 4645, 611, 5197, 1332, 11, 393, 422, 6589, 198, 2, 10392, 4306, 198, ...
2.083665
502
if __name__ == '__main__': main()
[ 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 1388, 3419 ]
2
21
#!/usr/bin/env python # Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script builds a small sample spm file tests/fixtures/test_sentencepiece_no_bos.model, with features needed by pegasus # 1. pip install sentencepiece # # 2. wget https://raw.githubusercontent.com/google/sentencepiece/master/data/botchan.txt # 3. build import sentencepiece as spm # pegasus: # 1. no bos # 2. eos_id is 1 # 3. unk_id is 2 # build a sample spm file accordingly spm.SentencePieceTrainer.train('--input=botchan.txt --model_prefix=test_sentencepiece_no_bos --bos_id=-1 --unk_id=2 --eos_id=1 --vocab_size=1000') # 4. now update the fixture # mv test_sentencepiece_no_bos.model ../../tests/fixtures/
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 12131, 383, 12905, 2667, 32388, 4816, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2...
3.185751
393
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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. """ Running inference for sequence classification on various datasets (Bert, XLM, XLNet).""" from __future__ import absolute_import, division, print_function import argparse import logging import os import numpy as np from scipy.special import softmax import torch from torch.utils.data import (DataLoader, SequentialSampler, TensorDataset) from tqdm import tqdm, trange from pytorch_transformers import (WEIGHTS_NAME, BertConfig, BertForSequenceClassification, BertTokenizer, XLMConfig, XLMForSequenceClassification, XLMTokenizer, XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer) from utils_dataset import (compute_metrics, convert_examples_to_features, output_modes, processors, InputExample) logger = logging.getLogger(__name__) ALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) for conf in (BertConfig, XLNetConfig, XLMConfig)), ()) MODEL_CLASSES = { 'bert': (BertConfig, BertForSequenceClassification, BertTokenizer), 'xlnet': (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer), 'xlm': (XLMConfig, XLMForSequenceClassification, XLMTokenizer), } if __name__ == "__main__": main()
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 2864, 383, 3012, 9552, 15417, 4816, 46665, 290, 383, 12905, 2667, 32388, 3457, 13, 1074, 13, 198, 2, 15069, 357, 66, 8, 2864, 11, 15127, 23929, 44680, 6234, 13, 220, 1439, 2489, 10395, 13,...
2.738032
752
"""<a href="https://projecteuler.net/problem=12" class="title-custom-link">Highly divisible triangular number</a> The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? """ from utils.oeis import triangular_numbers from utils.fibonacci import trial_division from utils.fibonacci import factors_to_dictionary def main(): """Solves this problem Utilizes [A000005](http://oeis.org/A000005) which is solved via a lemma to Euler's Totient Function Returns: Integer: Solution to this problem """ i = 1 divisors = 0 while divisors <= 500: triangle = triangular_numbers(i) prime_factors = trial_division(triangle) prime_factors = factors_to_dictionary(prime_factors) divisors = 1 for k, v in prime_factors.items(): divisors = divisors * (v + 1) i = i + 1 return triangular_numbers(i - 1)
[ 37811, 27, 64, 13291, 2625, 5450, 1378, 16302, 68, 18173, 13, 3262, 14, 45573, 28, 1065, 1, 1398, 2625, 7839, 12, 23144, 12, 8726, 5320, 11922, 306, 2659, 12843, 46963, 1271, 3556, 64, 29, 198, 464, 8379, 286, 22950, 3146, 318, 7560, ...
2.53578
545
import sqlite3 import os #DB_FILEPATH = "data/chinook.db" DB_FILEPATH = os.path.join(os.path.dirname(__file__), "..", "data", "rpg_db.sqlite3") conn = sqlite3.connect(DB_FILEPATH) conn.row_factory = sqlite3.Row print(type(conn)) #> <class 'sqlite3.Connection'> curs = conn.cursor() print(type(curs)) #> <class 'sqlite3.Cursor'> query = """SELECT count(DISTINCT character_id) as character_count FROM charactercreator_character""" # query1 = """SELECT # count(DISTINCT character_ptr_id) as character_ptr_count # FROM charactercreator_cleric""" # query2 = """SELECT # count(DISTINCT character_ptr_id) as character_ptr_count # FROM charactercreator_fighter""" # query3 = """SELECT # count(DISTINCT character_ptr_id) as character_ptr_count # FROM charactercreator_mage""" # query4 = """SELECT # count(DISTINCT character_ptr_id) as character_ptr_count # FROM charactercreator_thief""" queries_combined = """SELECT count(distinct c.character_ptr_id) as total_clerics ,count(distinct f.character_ptr_id) as total_fighters ,count(distinct m.character_ptr_id) as total_mages ,count(distinct n.mage_ptr_id) as total_necromancers ,count(distinct t.character_ptr_id) as total_thieves FROM charactercreator_character ccc LEFT JOIN charactercreator_fighter f ON ccc.character_id = f.character_ptr_id LEFT JOIN charactercreator_cleric c ON ccc.character_id= c.character_ptr_id LEFT JOIN charactercreator_mage m ON ccc.character_id = m.character_ptr_id LEFT JOIN charactercreator_necromancer n ON ccc.character_id = n.mage_ptr_id LEFT JOIN charactercreator_thief t ON ccc.character_id = t.character_ptr_id""" query5 = """SELECT count(DISTINCT item_id ) as total_item FROM armory_item""" query6 = """SELECT count(DISTINCT item_ptr_id) as weapons FROM armory_weapon""" query7 = """SELECT count(DISTINCT item_id) - count(DISTINCT item_ptr_id) as total_non_weapons FROM armory_item, armory_weapon""" query8 = """SELECT item_id , count(DISTINCT item_id) as item FROM charactercreator_character_inventory GROUP BY character_id LIMIT 20 """ query9 = """SELECT cci.character_id , count(DISTINCT aw.item_ptr_id) as number_of_weapons FROM charactercreator_character_inventory as cci LEFT JOIN armory_item as ai ON cci.item_id = ai.item_id LEFT JOIN armory_weapon as aw ON ai.item_id = aw.item_ptr_id GROUP BY character_id LIMIT 20""" query10 = """SELECT avg(total_items) as avg_items FROM ( -- row per character = 302 SELECT c.character_id ,c.name --,ci.item_id ,count(distinct ci.item_id) as total_items FROM charactercreator_character c LEFT JOIN charactercreator_character_inventory ci ON c.character_id = ci.character_id GROUP BY c.character_id ) subz""" query11 = """SELECT avg(weapon_count) as avg_weapon FROM ( SELECT cci.character_id ,count(DISTINCT aw.item_ptr_id) as weapon_count FROM charactercreator_character_inventory cci LEFT JOIN armory_item ai ON cci.item_id = ai.item_id LEFT JOIN armory_weapon aw ON ai.item_id = aw.item_ptr_id GROUP BY 1 ) subz""" print("----------") result = curs.execute(query).fetchone() print("RESULTS FOR CHARACTERCREATOR_CHARACTER", result) print(result["character_count"]) # print("-------------") # result1 = curs.execute(query1).fetchone() # print("Results for charactercreator_cleric", result1) # print(result1["character_ptr_count"]) # print("---------") # result2 = curs.execute(query2).fetchone() # print("Results for charactercreator_fighter", result2) # print(result2["character_ptr_count"]) # print("---------") # result3 = curs.execute(query3).fetchone() # print("Results for charactercreator_mage", result3) # print(result3["character_ptr_count"]) # print('--------') # result4 = curs.execute(query4).fetchone() # print("Results for charactercreator_thief", result4) # print(result4["character_ptr_count"]) # print("-------------") # result5 = curs.execute(query5).fetchone() # print("Results for total Items", result5) # print(result5["total_item"]) result_queries = curs.execute(queries_combined).fetchall() print("Results of each specific subclass", result_queries) result6 = curs.execute(query6).fetchone() print("Results for total weapons", result6) print(result6["weapons"]) print("---------") result7 = curs.execute(query7).fetchone() print("Results for total non weapons", result7) print(result7["total_non_weapons"]) print("---------") result8 = curs.execute(query8).fetchall() for rw in result8: print(rw[0], rw[1]) print("---------") result9 = curs.execute(query9).fetchall() for rw in result9: print(rw['character_id'], rw['number_of_weapons']) print("---------") result10 = curs.execute(query10).fetchone() print("Average item per character", result10) print(result10["avg_items"]) print("---------") result11= curs.execute(query11).fetchone() print("Average weapon per character", result11) print(result11["avg_weapon"]) print("---------")
[ 11748, 44161, 578, 18, 198, 11748, 28686, 198, 198, 2, 11012, 62, 25664, 34219, 796, 366, 7890, 14, 24658, 566, 13, 9945, 1, 198, 11012, 62, 25664, 34219, 796, 28686, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, ...
2.75969
1,806
#!/usr/bin/env python3 # ISC License # # Copyright (c) 2019, Bryon Vandiver # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from json import dumps import os import csv CSV_LOCATION = os.path.join(os.path.abspath(os.path.dirname(__file__)), 's1c88.csv') op0s, op1s, op2s = [None] * 0x100, [None] * 0x100, [None] * 0x100 CONDITIONS = { 'C': 'cpu.reg.flag.c', 'NC': '!cpu.reg.flag.c', 'Z': 'cpu.reg.flag.z', 'NZ': '!cpu.reg.flag.z', 'V': 'cpu.reg.flag.v', 'NV': '!cpu.reg.flag.v', 'M': 'cpu.reg.flag.n', 'P': '!cpu.reg.flag.n', 'LT': 'cpu.reg.flag.n != cpu.reg.flag.v', 'LE': '(cpu.reg.flag.n != cpu.reg.flag.v) || cpu.reg.flag.z', 'GT': '(cpu.reg.flag.n == cpu.reg.flag.v) && !cpu.reg.flag.z', 'GE': 'cpu.reg.flag.n == cpu.reg.flag.v', 'F0': 'cpu.reg.flag.f0', 'F1': 'cpu.reg.flag.f1', 'F2': 'cpu.reg.flag.f2', 'F3': 'cpu.reg.flag.f3', 'NF0': '!cpu.reg.flag.f0', 'NF1': '!cpu.reg.flag.f1', 'NF2': '!cpu.reg.flag.f2', 'NF3': '!cpu.reg.flag.f3', } ARGUMENTS = { 'A': (8, False, False, 'a'), 'B': (8, False, False, 'b'), 'L': (8, False, False, 'l'), 'H': (8, False, False, 'h'), 'BR': (8, False, False, 'br'), 'SC': (8, False, False, 'sc'), 'EP': (8, False, False, 'ep'), 'XP': (8, False, False, 'xp'), 'YP': (8, False, False, 'yp'), 'NB': (8, False, False, 'nb'), 'BA': (16, False, False, 'ba'), 'HL': (16, False, False, 'hl'), 'IX': (16, False, False, 'ix'), 'IY': (16, False, False, 'iy'), 'SP': (16, False, False, 'sp'), 'PC': (16, False, False, 'pc'), '#nn': (8, True, False, 'imm8'), 'rr': (8, True, False, 'imm8'), '#mmnn': (16, True, False, 'imm16'), 'qqrr': (16, True, False, 'imm16'), '[kk]': (16, True, True, 'vect'), # Special '[hhll]': (-1, True, True, 'ind16'), '[HL]': (-1, True, True, 'absHL'), '[IX]': (-1, True, True, 'absIX'), '[IY]': (-1, True, True, 'absIY'), '[BR:ll]': (-1, True, True, 'absBR'), '[SP+dd]': (-1, True, True, 'indDSP'), '[IX+dd]': (-1, True, True, 'indDIX'), '[IY+dd]': (-1, True, True, 'indDIY'), '[IX+L]': (-1, True, True, 'indIIX'), '[IY+L]': (-1, True, True, 'indIIY'), } OPERATIONS = { 'INC': (8, 'ReadWrite'), 'DEC': (8, 'ReadWrite'), 'SLA': (8, 'ReadWrite'), 'SLL': (8, 'ReadWrite'), 'SRA': (8, 'ReadWrite'), 'SRL': (8, 'ReadWrite'), 'RL': (8, 'ReadWrite'), 'RLC': (8, 'ReadWrite'), 'RR': (8, 'ReadWrite'), 'RRC': (8, 'ReadWrite'), 'CPL': (8, 'ReadWrite'), 'NEG': (8, 'ReadWrite'), 'LD': (8, 'Write', 'Read'), 'ADD': (8, 'ReadWrite', 'Read'), 'ADC': (8, 'ReadWrite', 'Read'), 'SUB': (8, 'ReadWrite', 'Read'), 'SBC': (8, 'ReadWrite', 'Read'), 'AND': (8, 'ReadWrite', 'Read'), 'OR': (8, 'ReadWrite', 'Read'), 'XOR': (8, 'ReadWrite', 'Read'), 'CP': (8, 'Read', 'Read'), 'BIT': (8, 'Read', 'Read'), 'CALL': (16, 'Read'), 'CARS': (8, 'Read'), 'CARL': (16, 'Read'), 'JRS': (8, 'Read'), 'JRL': (16, 'Read'), 'JP': (8, 'Read'), 'INT': (8, 'Read'), 'RETE': (8,), 'PUSH': (-1, 'Read'), 'POP': (-1, 'Write'), 'EX': (-1, 'ReadWrite', 'ReadWrite'), 'SWAP': (8, 'ReadWrite') } # Generate switch table with open(CSV_LOCATION, 'r') as csvfile: spamreader = csv.reader(csvfile) next(spamreader) for row in spamreader: code, cycles0, op0, arg0_1, arg0_2, cycles1, op1, arg1_1, arg1_2, cycles2, op2, arg2_1, arg2_2 = row code = int(code, 16) if op0 != 'undefined': op0s[code] = format(cycles0, op0, arg0_1, arg0_2) if op1 != 'undefined': op1s[code] = format(cycles1, op1, arg1_1, arg1_2) if op2 != 'undefined': op2s[code] = format(cycles2, op2, arg2_1, arg2_2) print ("int inst_advance(Machine::State& cpu) {") print ("\tswitch (cpu_imm8(cpu)) {") dump_table(op0s, '\t') print ("\tcase 0xCE:") print ("\t\tswitch (cpu_imm8(cpu)) {") dump_table(op1s, '\t\t') print ("\t\t}") print ("\tcase 0xCF:") print ("\t\tswitch (cpu_imm8(cpu)) {") dump_table(op2s, '\t\t') print ("\t\t}") print ("\t}") print ("}")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 201, 198, 2, 3180, 34, 13789, 201, 198, 2, 220, 201, 198, 2, 15069, 357, 66, 8, 13130, 11, 9092, 261, 35464, 1428, 201, 198, 2, 220, 201, 198, 2, 2448, 3411, 284, 779, ...
2.023482
2,470
############################################################################### # # Copyright (C) 2012 # ASTRON (Netherlands Institute for Radio Astronomy) <http://www.astron.nl/> # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # 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/>. # ############################################################################### """Test logging utilities * Provide logging with standardized prefixes: . time : self, if notime = 0 . verbosity level : self, if noVLevel = 0 . test case ID : self, if noTestId = 0 . message text : argument msgString, the actual text to log * All append_log statements that have verbosity level equal or lower than the test case verbosity level will get logged. * The logging gets output to the stdio and to a file if a file name is provided. * It is also possible to append other files to the test logging file. * Best practise is to use the following verbosity levels for the append_log argument: -v 0 Log test result -v 1 Log test title -v 2 Log errors -v 3 Log info -v 4 Log error details -v 5 Log info details -v 6 Log debug -v 7 Log debug details """ ################################################################################ # System imports import sys import time import common as cm ################################################################################ # Functions
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 198, 2, 15069, 357, 34, 8, 2321, 198, 2, 317, 18601, 1340, 357, 45, 6750, 4447, 5136, 329, 8829, 25398, 9145, 8, 1279, 4023, 1378, 2503, 13, 459, 1313, 13, 21283, 15913, 198, 2, 350, 13, 46...
3.740809
544
import re
[ 11748, 302, 628, 628 ]
3.25
4
from sqlalchemy import func from application import db from application.helpers.error_handlers import ServerError
[ 6738, 44161, 282, 26599, 1330, 25439, 198, 6738, 3586, 1330, 20613, 198, 6738, 3586, 13, 16794, 364, 13, 18224, 62, 4993, 8116, 1330, 9652, 12331, 628 ]
4.423077
26
import os from unittest.mock import patch import alteia from tests.alteiatest import AlteiaTestBase
[ 11748, 28686, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 11748, 435, 660, 544, 198, 6738, 5254, 13, 282, 660, 5375, 395, 1330, 978, 660, 544, 14402, 14881, 628 ]
3.090909
33
from ecgdigitize.signal.extraction.viterbi import * if __name__ == "__main__": print(list(interpolate(Point(0,0), Point(5,5))))
[ 6738, 9940, 70, 27003, 1096, 13, 12683, 282, 13, 2302, 7861, 13, 85, 2676, 8482, 1330, 1635, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 220, 220, 220, 220, 3601, 7, 4868, 7, 3849, 16104, ...
2.403509
57
from typing import Any, Dict import boto3 import pytest from s3fs import S3FileSystem from peakina.io.s3.s3_fetcher import S3Fetcher
[ 6738, 19720, 1330, 4377, 11, 360, 713, 198, 198, 11748, 275, 2069, 18, 198, 11748, 12972, 9288, 198, 6738, 264, 18, 9501, 1330, 311, 18, 8979, 11964, 198, 198, 6738, 9103, 1437, 13, 952, 13, 82, 18, 13, 82, 18, 62, 34045, 2044, 13...
2.692308
52
# Generated by Django 2.2.7 on 2019-12-02 05:19 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 22, 319, 13130, 12, 1065, 12, 2999, 8870, 25, 1129, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30