content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import os from time import sleep import requests querysub0 = 'https://linkeddata1.calcul.u-psud.fr/sparql?default-graph-uri=&query=construct%7B+%3Fs+%3Fp+%3Fo%7D+where+%7B+%0D%0Aselect+distinct+%3Fs+%3Fp+%3Fo+where+%7B%0D%0A%7B%0D%0A%3Fs1+++%3Chttp%3A%2F%2Fyago-knowledge.org%2Fresource%2FactedIn%3E+++%3Fs+.%0D%0A%3Fs2+++%3Chttp%3A%2F%2Fyago-knowledge.org%2Fresource%2Fdirected%3E+++%3Fs+.%0D%0A%3Fs+++%3Fp+++%3Fo.%0D%0A%7D+Union%7B%0D%0A%3Fs+++%3Chttp%3A%2F%2Fyago-knowledge.org%2Fresource%2FactedIn%3E+++%3Fs3+.%0D%0A%3Fs4+++%3Chttp%3A%2F%2Fyago-knowledge.org%2Fresource%2Fdirected%3E+++%3Fs3+.%0D%0A%3Fs+++%3Fp+++%3Fo.%0D%0A%7D+Union%7B%0D%0A%3Fs7+++%3Chttp%3A%2F%2Fyago-knowledge.org%2Fresource%2FactedIn%3E+++%3Fs5+.%0D%0A%3Fs+++%3Chttp%3A%2F%2Fyago-knowledge.org%2Fresource%2Fdirected%3E+++%3Fs5+.%0D%0A%3Fs+++%3Fp+++%3Fo.%7D+%0D%0A%7D%0D%0ALimit+10000+offset+' querysub1 = '+%7D%0D%0A&format=text%2Fplain&timeout=0' for counter in range(1, 700, 1): sleep(10) # sleep so to let the server breath download_big_file(counter) print "making yagoMovies.nt ..." os.system('find . -name "*.nt" -size -15 -delete') os.system("cat *.nt > a.ntt") os.system("rm *.nt") os.system("mv a.ntt yagoMovies.nt") print "yagoMovies.nt is created. have fun!"
[ 11748, 28686, 198, 6738, 640, 1330, 3993, 198, 11748, 7007, 198, 198, 10819, 893, 549, 15, 796, 705, 5450, 1378, 8726, 6048, 1045, 16, 13, 9948, 3129, 13, 84, 12, 862, 463, 13, 8310, 14, 82, 1845, 13976, 30, 12286, 12, 34960, 12, ...
1.877612
670
''' Created on Apr 12, 2011 @author: svenkratz ''' import TestGestures import Protractor3D.Protractor3D from Protractor3D.Protractor3D import * triangle = triplify(TestGestures.Triangle) print triangle circle1 = triplify(TestGestures.Circle_1) circle2 = triplify(TestGestures.Circle_2) rectangle = triplify(TestGestures.Rectangle) p_triangle = Protractor3D(triangle) p_circle1 = Protractor3D(circle1) p_circle2 = Protractor3D(circle2) p_rectangle = Protractor3D(rectangle) #print p_circle1.trace # #print "Trace", p_triangle.trace #print "Resampled", p_triangle.resampled #print "Scaled", p_triangle.scaled #print "Centered", p_triangle.centered #print "Template", p_triangle.template print "========== Evaluations ==============" Protractor3D.DEBUG = 5 gesturesAndNames = [(p_triangle,"Triangle"), (p_circle1,"Circle1"), ( p_circle2, "Circle2") , (p_rectangle, "Rectangle")] while gesturesAndNames != []: gesture = gesturesAndNames[0] templates = gesturesAndNames[1:] gesturesAndNames = templates if len(templates) != 0: for t in templates: print "=======================================" print "Results for", gesture[1]," <---> ", t[1] gesture[0].protractor3D_classify(gesture[0].template, t[0].template)
[ 7061, 6, 198, 41972, 319, 2758, 1105, 11, 2813, 198, 198, 31, 9800, 25, 264, 574, 74, 10366, 89, 198, 7061, 6, 628, 198, 11748, 6208, 38, 395, 942, 198, 11748, 5038, 40450, 18, 35, 13, 19703, 40450, 18, 35, 198, 6738, 5038, 40450,...
2.727473
455
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: Jos Snchez-Gallego (gallegoj@uw.edu) # @Date: 2021-03-24 # @Filename: test_hal.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) import pytest from hal import __version__ pytestmark = [pytest.mark.asyncio]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 2488, 13838, 25, 22568, 5489, 2395, 89, 12, 26552, 1455, 78, 357, 13528, 1455, 13210, 31, 84, 86, 13, 15...
2.328125
128
import numpy as np if __name__ == '__main__': with open('input.txt') as f: pin = np.array([int(x) for x in f.read().split(',')]) distances = np.abs(pin[None, :] - np.arange(pin.max() + 1)[:, None]) total_fuel = np.sum(distances, axis=1) print(f'Solution 1: {total_fuel.min()}') distances_v2 = crab_fuel(distances) total_fuel_v2 = np.sum(distances_v2, axis=1) print(f'Solution 2: {total_fuel_v2.min()}')
[ 11748, 299, 32152, 355, 45941, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 351, 1280, 10786, 15414, 13, 14116, 11537, 355, 277, 25, 198, 220, 220, 220, 220, 220, 220, 220, 6757, 796, ...
2.242424
198
# Generated by Django 2.2.10 on 2020-05-18 10:49 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 940, 319, 12131, 12, 2713, 12, 1507, 838, 25, 2920, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.8
30
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import numpy as np from torchvision import datasets, transforms import logging import random import torch # Settings for a multiplicative linear congruential generator (aka Lehmer # generator) suggested in 'Random Number Generators: Good # Ones are Hard to Find' by Park and Miller. MLCG_MODULUS = 2**(31) - 1 MLCG_MULTIPLIER = 16807 # Default quantiles for federated evaluations. DEFAULT_QUANTILES = (0.0, 0.25, 0.5, 0.75, 1.0) def mnist_iid(dataset, num_users): """ Sample I.I.D. client data from MNIST dataset :param dataset: :param num_users: :return: dict of image index """ num_items = int(len(dataset) / num_users) dict_users, all_idxs = {}, [i for i in range(len(dataset))] for i in range(num_users): dict_users[i] = set(np.random.choice(all_idxs, num_items, replace=False)) all_idxs = list(set(all_idxs) - dict_users[i]) return dict_users def mnist_noniid(dataset, num_users): """ Sample non-I.I.D client data from MNIST dataset :param dataset: :param num_users: :return: """ # 60,000 training imgs --> 200 imgs/shard X 300 shards num_shards, num_imgs = 200, 300 idx_shard = [i for i in range(num_shards)] dict_users = {i: np.array([]) for i in range(num_users)} idxs = np.arange(num_shards * num_imgs) labels = dataset.train_labels.numpy() # sort labels idxs_labels = np.vstack((idxs, labels)) idxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()] idxs = idxs_labels[0, :] # divide and assign 2 shards/client for i in range(num_users): rand_set = set(np.random.choice(idx_shard, 2, replace=False)) idx_shard = list(set(idx_shard) - rand_set) for rand in rand_set: dict_users[i] = np.concatenate( (dict_users[i], idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0) return dict_users def mnist_noniid_unequal(dataset, num_users): """ Sample non-I.I.D client data from MNIST dataset s.t clients have unequal amount of data :param dataset: :param num_users: :returns a dict of clients with each clients assigned certain number of training imgs """ # 60,000 training imgs --> 50 imgs/shard X 1200 shards num_shards, num_imgs = 1200, 50 idx_shard = [i for i in range(num_shards)] dict_users = {i: np.array([]) for i in range(num_users)} idxs = np.arange(num_shards * num_imgs) labels = dataset.train_labels.numpy() # sort labels idxs_labels = np.vstack((idxs, labels)) idxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()] idxs = idxs_labels[0, :] # Minimum and maximum shards assigned per client: min_shard = 1 max_shard = 30 # Divide the shards into random chunks for every client # s.t the sum of these chunks = num_shards random_shard_size = np.random.randint(min_shard, max_shard + 1, size=num_users) random_shard_size = np.around(random_shard_size / sum(random_shard_size) * num_shards) random_shard_size = random_shard_size.astype(int) # Assign the shards randomly to each client if sum(random_shard_size) > num_shards: for i in range(num_users): # First assign each client 1 shard to ensure every client has # atleast one shard of data rand_set = set(np.random.choice(idx_shard, 1, replace=False)) idx_shard = list(set(idx_shard) - rand_set) for rand in rand_set: dict_users[i] = np.concatenate( (dict_users[i], idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0) random_shard_size = random_shard_size - 1 # Next, randomly assign the remaining shards for i in range(num_users): if len(idx_shard) == 0: continue shard_size = random_shard_size[i] if shard_size > len(idx_shard): shard_size = len(idx_shard) rand_set = set(np.random.choice(idx_shard, shard_size, replace=False)) idx_shard = list(set(idx_shard) - rand_set) for rand in rand_set: dict_users[i] = np.concatenate( (dict_users[i], idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0) else: for i in range(num_users): shard_size = random_shard_size[i] rand_set = set(np.random.choice(idx_shard, shard_size, replace=False)) idx_shard = list(set(idx_shard) - rand_set) for rand in rand_set: dict_users[i] = np.concatenate( (dict_users[i], idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0) if len(idx_shard) > 0: # Add the leftover shards to the client with minimum images: shard_size = len(idx_shard) # Add the remaining shard to the client with lowest data k = min(dict_users, key=lambda x: len(dict_users.get(x))) rand_set = set(np.random.choice(idx_shard, shard_size, replace=False)) idx_shard = list(set(idx_shard) - rand_set) for rand in rand_set: dict_users[k] = np.concatenate( (dict_users[k], idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0) return dict_users def cifar_iid(dataset, num_users, args): """ Sample I.I.D. client data from CIFAR10 dataset :param dataset: :param num_users: :return: dict of image index """ torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) random.seed(args.seed) np.random.seed(args.seed) num_items = int(len(dataset) / num_users) # dict_users? 0~100 50000 100 . indx list dict_users, all_idxs = {}, [i for i in range(len(dataset))] for i in range(num_users): dict_users[i] = set(np.random.choice(all_idxs, num_items, replace=False)) all_idxs = list(set(all_idxs) - dict_users[i]) return dict_users def imagenet_noniid(dataset, num_users, args, class_num=2): """ Sample non-I.I.D client data from CIFAR10 dataset :param dataset: :param num_users: :return: """ #num_shards -> / num_imgs -> .but imagenet . / # idxs torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) random.seed(args.seed) np.random.seed(args.seed) # . #idx_shards -> n(n .) -> 2 x 100 = 200 #num_imgs -> . 5/100 =500, 2 500 num_shards, num_imgs = num_users*class_num, int(len(dataset)/num_users/class_num) idx_shard = [i for i in range(num_shards)] dict_users = {i: np.array([]) for i in range(num_users)} idxs = np.arange(num_shards * num_imgs) # labels = dataset.train_labels.numpy() labels = np.array(dataset.targets) # sort labels idxs = np.argsort(labels) class_count = [0 for i in range(num_shards)] for i in labels: class_count[i] += 1 accumulate_class_count = [0 for i in range(num_shards)] for c in range(num_shards): if c==0: accumulate_class_count[c] = class_count[0] else: accumulate_class_count[c] = accumulate_class_count[c-1] + class_count[c] idx_shuffle = np.random.permutation(idx_shard) client_class_set = [] for i in range(num_users): user_class_set = idx_shuffle[i*class_num:(i+1)*class_num] client_class_set.append(user_class_set) for class_seed in user_class_set: dict_users[i] = np.concatenate( (dict_users[i], idxs[accumulate_class_count[class_seed] -class_count[class_seed] :accumulate_class_count[class_seed]]), axis=0) return dict_users,client_class_set def cifar_noniid(dataset, num_users, args, class_num=2): """ Sample non-I.I.D client data from CIFAR10 dataset :param dataset: :param num_users: :return: """ torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) random.seed(args.seed) np.random.seed(args.seed) # . #idx_shards -> n(n .) -> 2 x 100 = 200 #num_imgs -> . 5/100 =500, 2 500 num_shards, num_imgs = num_users*class_num, int(len(dataset)/num_users/class_num) idx_shard = [i for i in range(num_shards)] dict_users = {i: np.array([]) for i in range(num_users)} idxs = np.arange(num_shards * num_imgs) # labels = dataset.train_labels.numpy() labels = np.array(dataset.targets) #sort_index = np.argsort(labels) # sort labels idxs_labels = np.vstack((idxs, labels)) idxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()] idxs = idxs_labels[0, :] user_classs_dict = [] # divide and assign for i in range(num_users): # 200 2 . rand_set = set(np.random.choice(idx_shard, class_num, replace=False)) if class_num > 1 and i != num_users-1: while dataset.targets[idxs[list(rand_set)[1] * num_imgs]] == dataset.targets[idxs[list(rand_set)[0] *num_imgs]]: rand_set = set(np.random.choice(idx_shard, class_num, replace=False)) #print(dataset.targets[idxs[list(rand_set)[1] * num_imgs]]) #print(dataset.targets[idxs[list(rand_set)[0] * num_imgs]]) #print('\t') user_classs_dict.append(rand_set) idx_shard = list(set(idx_shard) - rand_set) for rand in rand_set: dict_users[i] = np.concatenate( (dict_users[i], idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0) # for data_idx, j in enumerate(dict_users[i]): # print(i, data_idx, dataset.targets[int(j)]) return dict_users, user_classs_dict if __name__ == '__main__': dataset_train = datasets.MNIST('./data/mnist/', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])) num = 100 d = mnist_noniid(dataset_train, num)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 11361, 2196, 25, 513, 13, 21, 628, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 28034, 10178, 1330, 40522, 11, 3...
2.035028
5,310
#! /usr/bin/python3 # Author: gaurav512 ''' Script written to scrape basic information about a Codeforces profile given the user id Usage: Enter the userid as command line argument OR as the input after running the following in terminal- python3 codeforces.py [userid] ''' import requests, bs4, sys if __name__ == '__main__': main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 18, 198, 198, 2, 6434, 25, 308, 2899, 615, 25836, 198, 198, 7061, 6, 12327, 3194, 284, 42778, 4096, 1321, 546, 257, 220, 198, 43806, 891, 273, 728, 7034, 1813, 262, 2836, 4686, 198, 28350, 2...
3.166667
108
#!/usr/bin/env python # -*- coding: utf-8 -*- # # test_combinator.py # # Copyright 2020 QuatroPe # # This file is part of ProperImage (https://github.com/quatrope/ProperImage) # License: BSD-3-Clause # Full Text: https://github.com/quatrope/ProperImage/blob/master/LICENSE.txt # """ test_combinator module from ProperImage for analysis of astronomical images Written by Bruno SANCHEZ PhD of Astromoy - UNC bruno@oac.unc.edu.ar Instituto de Astronomia Teorica y Experimental (IATE) UNC Cordoba - Argentina Of 301 """
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 1332, 62, 785, 8800, 1352, 13, 9078, 198, 2, 198, 2, 220, 15069, 12131, 2264, 47756, 6435, 198, 2, ...
2.692308
195
''' parameter --------- df:woe,logit logitsklearn, return ------ Score example: df= cal_score(df,logit) '''
[ 220, 220, 220, 220, 198, 7061, 6, 198, 17143, 2357, 198, 45537, 198, 7568, 25, 86, 2577, 11, 6404, 270, 198, 6404, 896, 74, 35720, 11, 198, 198, 7783, 198, 23031, 198, 220, 220, 220, 15178, 198, 198, 20688, 25, 198, 220, 220, 220,...
1.955882
68
#! /usr/bin/env python3 """ Runs process_logdata_ekf.py on the .ulg files in the supplied directory. ulog files are skipped from the analysis, if a corresponding .pdf file already exists (unless the overwrite flag was set). """ # -*- coding: utf-8 -*- import argparse import os, glob from process_logdata_ekf import process_logdata_ekf if __name__ == '__main__': main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 10987, 82, 1429, 62, 6404, 7890, 62, 988, 69, 13, 9078, 319, 262, 764, 377, 70, 3696, 287, 262, 14275, 8619, 13, 334, 6404, 3696, 389, 26684, 422, 262, 3781, 11, ...
3.056452
124
import inspect import warnings from pathlib import Path
[ 11748, 10104, 198, 11748, 14601, 198, 6738, 3108, 8019, 1330, 10644, 628, 198 ]
4.461538
13
# Python import logging from os import path # Abstract from genie.abstract import Lookup # Parser from genie.libs import parser from genie.metaparser.util.exceptions import SchemaEmptyParserError # unicon from unicon.eal.dialogs import Statement, Dialog log = logging.getLogger(__name__) def save_device_information(device, **kwargs): """Install the commit packages. This is for IOSXR devices. Args: Mandatory: device (`obj`) : Device object. Returns: True: Result is PASSED False: Result is PASSX Raises: None Example: >>> save_device_information(device=Device()) """ # Checking the config-register has 0x2 # if not configure 0x2 # RP/0/RSP1/CPU0:PE1#admin config-register 0x2 if device.is_ha: conn = device.active else: conn = device # Install commit ( when thre are package to bring up features) # from admin prompt conn.admin_execute('install commit') def get_default_dir(device): """ Get the default directory of this device Args: Mandatory: device (`obj`) : Device object. Returns: default_dir (`str`): Default directory of the system Raises: Exception Example: >>> get_default_dir(device=device) """ try: lookup = Lookup.from_device(device) parsed_dict = lookup.parser.show_platform.Dir(device=device).parse() if ":" in parsed_dict['dir']['dir_name']: default_dir = parsed_dict['dir']['dir_name'] else: default_dir = '' except SchemaEmptyParserError as e: raise Exception("No output when executing 'dir' command") from e except Exception as e: raise Exception("Unable to execute 'dir' command") from e # Return default_dir to caller log.info("Default directory on '{d}' is '{dir}'".format(d=device.name, dir=default_dir)) return default_dir def configure_replace(device, file_location, timeout=60, file_name=None): """Configure replace on device Args: device (`obj`): Device object file_location (`str`): File location timeout (`int`): Timeout value in seconds file_name (`str`): File name Returns: None Raises: pyATS Results """ if file_name: file_location = '{}{}'.format( file_location, file_name) try: # check if file exist device.execute.error_pattern.append('.*Path does not exist.*') device.execute("dir {}".format(file_location)) except Exception: raise Exception("File {} does not exist".format(file_location)) dialog = Dialog([ Statement(pattern=r'\[no\]', action='sendline(y)', loop_continue=True, continue_timer=False)]) device.configure("load {}\ncommit replace".format(file_location), timeout=timeout, reply=dialog)
[ 2, 11361, 198, 11748, 18931, 198, 6738, 28686, 1330, 3108, 198, 198, 2, 27741, 198, 6738, 2429, 494, 13, 397, 8709, 1330, 6803, 929, 198, 198, 2, 23042, 263, 198, 6738, 2429, 494, 13, 8019, 82, 1330, 30751, 198, 6738, 2429, 494, 13,...
2.316143
1,338
import matplotlib.pyplot as plt import numpy as np from labellines import labelLines # # Trying to get interpolation to work but getting error: # # ValueError: The number of derivatives at boundaries does not match: expected 1, got 0+0 # from scipy.interpolate import make_interp_spline, BSpline # n_users = np.array([100, 10000, 1000000]) # bw_case8 = np.array([1, 1.5, 98.1]) # # 300 represents number of points to make between T.min and T.max # n_users_new = np.linspace(n_users.min(), n_users.max(), 300) # spl8 = make_interp_spline(n_users, bw_case8, k=3) # type: BSpline # bw_case8_smooth = spl8(n_users_new) # plt.plot(n_users_new, bw_case8_smooth, label='case 8', linewidth=2) n_users = [100, 10000, 1000000] bw_case1 = [1, 1, 1] bw_case2 = [97.7, 9.5*1000, 935.7*1000] bw_case3 = [49.3, 4.*10008, 476.8*1000] bw_case4 = [1, 1.5, 98.1] bw_case5 = [10.7, 978, 95.5*1000] bw_case6 = [21.5, 1.9*1000, 190.9*1000] bw_case7 = [3.9, 284.8, 27.8*1000] bw_case8 = [1, 1.5, 98.1] plt.xlim(100, 10**6) plt.ylim(1, 10**6) plt.plot(n_users, bw_case1, label='case 1', linewidth=4, linestyle='dashed') plt.plot(n_users, bw_case2, label='case 2', linewidth=4, linestyle='dashed') plt.plot(n_users, bw_case3, label='case 3', linewidth=4, linestyle='dashed') plt.plot(n_users, bw_case4, label='case 4', linewidth=4, linestyle='dashed') plt.plot(n_users, bw_case5, label='case 5', linewidth=4) plt.plot(n_users, bw_case6, label='case 6', linewidth=4) plt.plot(n_users, bw_case7, label='case 7', linewidth=4) plt.plot(n_users, bw_case8, label='case 8', linewidth=4) #labelLines(plt.gca().get_lines(),zorder=0) case1 = "Case 1. Only receiving messages meant for you [naive case]" case2 = "Case 2. Receiving messages for everyone [naive case]" case3 = "Case 3. All private messages go over one discovery topic [naive case]" case4 = "Case 4. All private messages partitioned into shards [naive case]" case5 = "Case 5. Case 4 + All messages passed through bloom filter" case6 = "Case 6. Case 5 + Benign duplicate receives" case7 = "Case 7. Case 6 + Mailserver case under good conditions with small bloom fp and mostly offline" case8 = "Case 8. Waku - No metadata protection with bloom filter and one node connected; static shard" plt.xlabel('number of users (log)') plt.ylabel('mb/day (log)') plt.legend([case1, case2, case3, case4, case5, case6, case7, case8], loc='upper left') plt.xscale('log') plt.yscale('log') plt.axhspan(0, 10, facecolor='0.2', alpha=0.2, color='blue') plt.axhspan(10, 30, facecolor='0.2', alpha=0.2, color='green') plt.axhspan(30, 100, facecolor='0.2', alpha=0.2, color='orange') plt.axhspan(100, 10**6, facecolor='0.2', alpha=0.2, color='red') #plt.axvspan(0, 10**2+3, facecolor='0.2', alpha=0.5) #plt.axvspan(10**4, 10**4+10**2, facecolor='0.2', alpha=0.5) #plt.axvspan(10**6, 10**6+10**4, facecolor='0.2', alpha=0.5) #for i in range(0, 5): # plt.axhspan(i, i+.2, facecolor='0.2', alpha=0.5) plt.show()
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2248, 695, 1127, 1330, 6167, 43, 1127, 198, 198, 2, 1303, 31165, 284, 651, 39555, 341, 284, 670, 475, 1972, 4049, 25, 198, 2, 13...
2.357717
1,244
# import the necessary packages import argparse import cv2 import numpy as np from polydomino.colordescriptor import ColorDescriptor from polydomino.searcher import Searcher # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument( "-i", "--index", required=True, help="Path to where the computed index will be stored", ) ap.add_argument("-q", "--query", required=True, help="Path to the query image") ap.add_argument( "-fm", "--features", required=True, help="Method to get features of pics", ) ap.add_argument( "-sm", "--searcher", required=True, help="Method to search pics", ) # ap.add_argument("-r", "--result-path", required=True, help="Path to the result path") args = vars(ap.parse_args()) # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query image and describe it query = cv2.imread(args["query"]) if args["features"] == "color-moments": features = cd.color_moments(query) elif args["features"] == "hsv-describe": features = cd.hsv_describe(query) elif args["features"] == "gray-matrix": features = cd.gray_matrix(query) elif args["features"] == "humoments": features = cd.humoments(query) elif args["features"] == "ahash": features = cd.ahash(query) elif args["features"] == "phash": features = cd.phash(query) elif args["features"] == "dhash": features = cd.dhash(query) elif args["features"] == "mse": features = cd.mse(query) elif args["features"] == "hog": features = cd.hog(query) else: print("Sorry, we don't support this method.") exit(1) # perform the search method = args["searcher"] searcher = Searcher(args["index"]) results = searcher.search(features, method) print(results) # display the query cv2.namedWindow("Query", 0) cv2.resizeWindow("Query", 640, 480) cv2.imshow("Query", query) # loop over the results for (score, resultID) in results: result = cv2.imread(resultID) cv2.imshow("Result", result) cv2.waitKey(0)
[ 2, 1330, 262, 3306, 10392, 198, 11748, 1822, 29572, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 7514, 3438, 2879, 13, 4033, 585, 3798, 1968, 273, 1330, 5315, 24564, 1968, 273, 198, 6738, 7514, 343...
2.828854
707
import click from irekua_dev_tools.utils import load_config from irekua_dev_tools.utils import get_working_directory from irekua_dev_tools.utils import load_environment_variables from irekua_dev_tools.utils import load_repository_info from . import git from . import dev from . import config from . import db from .extra import clean cli.add_command(dev.cli) cli.add_command(git.cli) cli.add_command(config.cli) cli.add_command(db.cli) cli.add_command(clean)
[ 11748, 3904, 198, 198, 6738, 35918, 74, 6413, 62, 7959, 62, 31391, 13, 26791, 1330, 3440, 62, 11250, 198, 6738, 35918, 74, 6413, 62, 7959, 62, 31391, 13, 26791, 1330, 651, 62, 16090, 62, 34945, 198, 6738, 35918, 74, 6413, 62, 7959, ...
2.980769
156
from optimism.JaxConfig import * from optimism import MinimizeScalar from optimism.test import TestFixture from optimism.material import J2Plastic df = jacfwd(f) if __name__ == '__main__': TestFixture.unittest.main()
[ 6738, 24323, 13, 41, 897, 16934, 1330, 1635, 198, 6738, 24323, 1330, 1855, 48439, 3351, 282, 283, 198, 6738, 24323, 13, 9288, 1330, 6208, 37, 9602, 198, 198, 6738, 24323, 13, 33665, 1330, 449, 17, 3646, 3477, 198, 7568, 796, 474, 330,...
2.829268
82
# -*- coding: utf-8 -*- """ import datetime from anima import defaults defaults.timing_resolution = datetime.timedelta(minutes=10) from anima.ui import SET_PYSIDE2 SET_PYSIDE2() from anima.ui.widgets.review import APPROVE, REQUEST_REVISION from anima.ui import review_dialog review_dialog.UI(review_type=REQUEST_REVISION) """ from anima.ui.lib import QtCore, QtWidgets from anima.ui.base import ui_caller, AnimaDialogBase def UI(app_in=None, executor=None, **kwargs): """ :param app_in: A Qt Application instance, which you can pass to let the UI be attached to the given applications event process. :param executor: Instead of calling app.exec_ the UI will call this given function. It also passes the created app instance to this executor. """ return ui_caller(app_in, executor, ReviewDialog, **kwargs)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 11748, 4818, 8079, 198, 6738, 2355, 64, 1330, 26235, 198, 12286, 82, 13, 16514, 278, 62, 29268, 796, 4818, 8079, 13, 16514, 276, 12514, 7, 1084, 1769, 28, ...
2.858108
296
import math import re from itertools import permutations from logging import getLogger from typing import Tuple, Union from rpy2 import robjects from rpy2.rinterface_lib.embedded import RRuntimeError from z3 import BitVecVal from .. import util, results from ..decider import RowNumberInfo from ..program import LineInterpreter from ..tyrell.interpreter import InterpreterError logger = getLogger('squares.interpreter')
[ 11748, 10688, 198, 11748, 302, 198, 6738, 340, 861, 10141, 1330, 9943, 32855, 198, 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 19720, 1330, 309, 29291, 11, 4479, 198, 198, 6738, 374, 9078, 17, 1330, 3857, 752, 82, 198, 6738, 374, ...
3.479675
123
# -*- coding: utf-8 -*- """ ------ What is this file? ------ This script targets the istanbul_airbnb_raw.csv file. It cleans the .csv file in order to prepare it for further analysis """ #%% --- Import Required Packages --- import os import pathlib from pathlib import Path # To wrap around filepaths import numpy as np import pandas as pd from matplotlib import pyplot as plt from scipy.stats import iqr from src.helper_functions.data_preparation_helper_functions import sample_and_read_from_df from src.helper_functions.data_preparation_helper_functions import report_null_values #%% --- Set proper directory to assure integration with doit --- abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) #%% --- Import Data --- import_fp = Path("../../data/raw/istanbul_airbnb_raw.csv") airbnb = pd.read_csv(import_fp, encoding='utf-8-sig') #%% --- Get a general sense of the datasets --- # Shape of the data print(airbnb.shape) # 16251 rows, 16 cols # First few lines print(airbnb.head()) #Not much info, let's print the columns airbnb_columns = airbnb.columns #%% --- Clean the dataset: Relevant - Irrelevant Columns --- airbnb_unwanted_columns = ["neighbourhood_group", "last_review", "number_of_reviews", "minimum_nights", "reviews_per_month", "calculated_host_listings_count", "availability_365"] #Drop unwanted columns airbnb.drop(columns = airbnb_unwanted_columns, axis = 1, inplace = True) # Check shape now print(airbnb.shape) # 16251 rows, 9 cols #%% --- Clean the dataset: Further Troubleshooting --- #I want to be able to randomly take n samples from each dataset and then print them #on a clean format to see the potential problems #If i had something to test for, i'd strive for somewhat of a representative sample size #while sampling. However, i think the best to do here would be to print what i can read #because i don't have any computational measure to test for something: sample_and_read_from_df(airbnb, 20) #SPOTTED PROBLEMS: # dataframe airbnb column neigborhood is not properly formatted: # Formatting fixes # should actually be called "district_tr" # There should be an accompanying "district_eng" column. #%% --- Fix column naming --- #I can use either dataframe.columns attribute to assign new columns #or i can pass a dictionary with old names/new names into dataframe.rename() airbnb_columns_in_english = ["listing_id", "name", "host_id", "host_name", "district_eng", "latitude", "longitude", "room_type", "price"] airbnb.columns = airbnb_columns_in_english #%% --- One-off fix for districts named "Eyup" --- eyup_mask = airbnb.loc[:,"district_eng"] == "Eyup" airbnb.loc[eyup_mask, "district_eng"] = "Eyupsultan" #%% --- Add a new "district_tr" column airbnb.loc[:,"district_tr"] = airbnb.loc[:,"district_eng"].str.lower().str.capitalize() #I will be using df.map() method, so i'll need two dataframes: one for existing values - tr values #and one for exixsting values - eng values unique_districts_tr_corrected = ["Kadky", "Fatih", "Tuzla", "Gaziosmanpaa", "skdar", "Adalar", "Saryer", "Arnavutky", "Silivri", "atalca", "Kkekmece", "Beyolu", "ile", "Kartal", "ili", "Beikta", "Kathane", "Esenyurt", "Bahelievler", "Avclar", "Baakehir", "Sultangazi", "Maltepe", "Sancaktepe", "Beykoz", "Bykekmece", "Bakrky", "Pendik", "Baclar", "Esenler", "Beylikdz", "mraniye", "Eypsultan", "ekmeky", "Ataehir", "Sultanbeyli", "Zeytinburnu", "Gngren", "Bayrampaa"] unique_districts_eng_corrected = ["Kadikoy", "Fatih", "Tuzla", "Gaziosmanpasa", "Uskudar", "Adalar", "Sariyer", "Arnavutkoy", "Silivri", "Catalca", "Kucukcekmece", "Beyoglu", "Sile", "Kartal", "Sisli", "Besiktas", "Kagithane", "Esenyurt", "Bahcelievler", "Avcilar", "Basaksehir", "Sultangazi", "Maltepe", "Sancaktepe", "Beykoz", "Buyukcekmece", "Bakirkoy", "Pendik", "Bagcilar", "Esenler", "Beylikduzu", "Umraniye", "Eyupsultan", "Cekmekoy", "Atasehir", "Sultanbeyli", "Zeytinburnu", "Gungoren", "Bayrampasa"] airbnb_unique_districts_dict_tr = dict(zip(unique_districts_eng_corrected, unique_districts_tr_corrected)) airbnb.loc[:,"district_tr"] = airbnb.loc[:,"district_tr"].map(airbnb_unique_districts_dict_tr) #%% --- EDA: Explore Missing Values --- #Let's check null values first null_report = report_null_values(airbnb) #We have so few missing values, dropping them won't affect our quality at all. # Let's do exactly that. airbnb.dropna(axis = 0, inplace = True) #%% --- EDA: Explore Datatype agreement --- #Now, let's check data type agreement for each column. data_types = airbnb.dtypes # The data types with "object" warrant further investigation #They could just be strings, but mixed data types also show as "object" # Let's select "object" data types and query once again. airbnb_dtype_object_only = airbnb.select_dtypes(include = ["object"]) print(airbnb_dtype_object_only.columns) #As all the column names seem to accomodate only strings, we can be #pretty sure that showing up as object is correct behavior. #%% --- EDA - Explore Outliers in price --- fig = plt.figure(figsize = (19.20, 10.80)) ax = fig.add_subplot(1,1,1) ax.hist(x = airbnb.loc[:,"price"], bins = 20) #Our histogram is very wonky. It's obvious that there are some issues. Let's see: # It doesn't make sense for a airbnb room to cost 0 liras. That's for sure. print(airbnb.loc[:,"price"].sort_values().head(20)) #What about maxes? print(airbnb.loc[:,"price"].sort_values(ascending = False).head(30)) #There are some very high maxes, that's for sure. Let's try to make heads and tails of #what these houses are: possible_outliers = airbnb.sort_values(by = "price", axis = 0, ascending = False).head(30) # A qualitative analysis of such houses show that there really aappears to be a problem #with pricing. Let's calculate the IQR to drop the outliers: #Calculate the iqr price_iqr = iqr(airbnb.loc[:,"price"], axis = 0) #Calculate q3 and q1 q1 = airbnb["price"].quantile(0.25) q3 = airbnb["price"].quantile(0.75) #Create min and max mask min_mask = airbnb.loc[:,"price"] >= q1 - (1.5 * price_iqr) max_mask = airbnb.loc[:,"price"] <= q3 + (1.5 * price_iqr) #Combine masks combined_mask = min_mask & max_mask #Create subset airbnb_within_iqr = airbnb.loc[combined_mask] fig = plt.figure(figsize = (19.20, 10.80)) ax = fig.add_subplot(1,1,1) ax.hist(x = airbnb_within_iqr.loc[:,"price"], bins = 20) #Alright, limiting our data to an IQR appears to omit a whole lot of data. #I am sure that some of the outliers we have are errors of entry. #However, the only ones that we can conclusively prove are the entries that are rated at 0. #We'll drop these #Create a mask for zeros zero_mask = (airbnb.loc[:,"price"] > 0) #Filter using the mask airbnb = airbnb.loc[zero_mask,:] # #%% --- Export Data --- export_fp = Path("../../data/processed/istanbul_airbnb_processed.csv") airbnb.to_csv(export_fp, encoding='utf-8-sig', index = False)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 23031, 1867, 318, 428, 2393, 30, 40103, 198, 198, 1212, 4226, 6670, 262, 318, 38006, 15065, 62, 958, 31971, 62, 1831, 13, 40664, 2393, 13, 632, 20658, 262, ...
2.301676
3,401
import time import select import queue import atexit import sys import logging from networkdevice import ShureNetworkDevice from channel import chart_update_list, data_update_list # from mic import WirelessMic # from iem import IEM NetworkDevices = [] DeviceMessageQueue = queue.Queue() # @atexit.register # atexit.register(on_exit) # signal.signal(signal.SIGTERM, on_exit) # signal.signal(signal.SIGINT, on_exit)
[ 11748, 640, 198, 11748, 2922, 198, 11748, 16834, 198, 11748, 379, 37023, 198, 11748, 25064, 198, 11748, 18931, 198, 198, 6738, 3127, 25202, 1330, 911, 495, 26245, 24728, 198, 6738, 6518, 1330, 8262, 62, 19119, 62, 4868, 11, 1366, 62, 19...
3.149254
134
import enum QUEUED = Status.QUEUED STARTED = Status.STARTED FINISHED = Status.FINISHED ERROR = Status.ERROR
[ 11748, 33829, 198, 198, 48, 8924, 52, 1961, 796, 12678, 13, 48, 8924, 52, 1961, 198, 2257, 7227, 1961, 796, 12678, 13, 2257, 7227, 1961, 198, 20032, 18422, 1961, 796, 12678, 13, 20032, 18422, 1961, 198, 24908, 796, 12678, 13, 24908, 1...
2.595238
42
"""Simulation 1:1:1 comptition binding""" import numpy as np from high_accuracy_binding_equations import * # We can choose to work in a common unit, typically nM, or uM, as long as all # numbers are in the same unit, the result is valid. We assume uM for all # concentrations bellow. # First, lets simulate a few single points from three different systems # p, l and i are protrin, ligand and inhibitor concentrations respectively # kdpl is the dissociation constant (KD) of the protein-ligand interaction # kdpi is the dissociation constant (KD) of the protein-inhibitor interaction # We can either expand the dictionary with ** as shown in the example with # system1, or we can pass arguments to competition_pl with the following # singature: competition_pl(p, l , i, kdpl, kdpi) system1={"p":1, "l":2, "i":10, "kdpl":0.1, "kdpi":10} pl_conc=competition_pl(**system1) print(f"pl_conc = {round(pl_conc,4)}, fraction ligand bound = {round(pl_conc/system1['l'],4)}")
[ 37811, 8890, 1741, 352, 25, 16, 25, 16, 401, 457, 653, 12765, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1029, 62, 4134, 23843, 62, 30786, 62, 4853, 602, 1330, 1635, 198, 198, 2, 775, 460, 3853, 284, 670, 287, 257, ...
3.111465
314
import numpy as np from pathlib import Path import sys if __name__ == '__main__': # absolute path my_path = Path(__file__).parent.resolve().expanduser() main_path = my_path.parent.parent seed = 0 nlat = 10 alpha = 1.0 beta = 6.0 gamma = 1.0 epochs = 100 # cmd template cmd = f'python main.py btcvae_mnist_{epochs}ep/z{nlat}_a{alpha}_b{beta}_g{gamma}_s{seed} -s {seed} ' \ f'--checkpoint-every 25 -d mnist -e {epochs} -b 64 --lr 0.0005 ' \ f'-z {nlat} -l btcvae --btcvae-A {alpha} --btcvae-B {beta} --btcvae-G {gamma} ' \ f'--no-test\n' with open(my_path / f'train_beta{beta}.sh', 'w') as f: unnormalized_beta = beta * nlat f.write(cmd)
[ 11748, 299, 32152, 355, 45941, 201, 198, 6738, 3108, 8019, 1330, 10644, 201, 198, 11748, 25064, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 201, 198, 220, 220, 220, 1303, 4112, 3108, 201, 19...
1.9325
400
########################################################################## # # Unit tests (pytest) for load.py # ########################################################################## # SimFin - Simple financial data for Python. # www.simfin.com - www.github.com/simfin/simfin # See README.md for instructions and LICENSE.txt for license details. ########################################################################## import simfin as sf from simfin.datasets import iter_all_datasets ########################################################################## # Test configuration. # Set data directory. sf.set_data_dir(data_dir='~/simfin_data/') # Load API key or use default 'free' if key-file doesn't exist. sf.load_api_key(path='~/simfin_api_key.txt', default_key='free') # Set number of days before refreshing data from SimFin server. refresh_days = 30 ########################################################################## # Helper functions. def _create_kwargs(variant, market): """ Create a dict with keyword args for sf.load() functions that take variant, market and refresh_days as kwargs. """ kwargs = \ { 'variant': variant, 'market': market, 'refresh_days': refresh_days, } return kwargs ########################################################################## # Test functions. def test_load(): """Test simfin.bulk.load()""" for dataset, variant, market in iter_all_datasets(): sf.load(dataset=dataset, variant=variant, market=market, refresh_days=refresh_days) def test_load_income(): """Test simfin.bulk.load_income()""" for dataset, variant, market in iter_all_datasets(datasets='income'): kwargs = _create_kwargs(variant=variant, market=market) sf.load_income(**kwargs) sf.load_income_banks(**kwargs) sf.load_income_insurance(**kwargs) def test_load_balance(): """Test simfin.bulk.load_balance()""" for dataset, variant, market in iter_all_datasets(datasets='balance'): kwargs = _create_kwargs(variant=variant, market=market) sf.load_balance(**kwargs) sf.load_balance_banks(**kwargs) sf.load_balance_insurance(**kwargs) def test_load_cashflow(): """Test simfin.bulk.load_cashflow()""" for dataset, variant, market in iter_all_datasets(datasets='cashflow'): kwargs = _create_kwargs(variant=variant, market=market) sf.load_cashflow(**kwargs) sf.load_cashflow_banks(**kwargs) sf.load_cashflow_insurance(**kwargs) def test_load_shareprices(): """Test simfin.bulk.load_shareprices()""" for dataset, variant, market in iter_all_datasets(datasets='shareprices'): kwargs = _create_kwargs(variant=variant, market=market) sf.load_shareprices(**kwargs) def test_load_companies(): """Test simfin.bulk.load_companies()""" for dataset, variant, market in iter_all_datasets(datasets='companies'): kwargs = _create_kwargs(variant=variant, market=market) sf.load_companies(**kwargs) def test_load_industries(): """Test simfin.bulk.load_industries()""" sf.load_industries(refresh_days=refresh_days) ##########################################################################
[ 29113, 29113, 7804, 2235, 198, 2, 198, 2, 11801, 5254, 357, 9078, 9288, 8, 329, 3440, 13, 9078, 198, 2, 198, 29113, 29113, 7804, 2235, 198, 2, 3184, 18467, 532, 17427, 3176, 1366, 329, 11361, 13, 198, 2, 7324, 13, 14323, 15643, 13, ...
2.746084
1,213
import sys from plum import Dispatcher B = sys.modules[__name__] # Allow both import styles. dispatch = Dispatcher() # This dispatch namespace will be used everywhere. from .generic import * from .shaping import * from .linear_algebra import * from .random import * from .numpy import * from .types import * from .control_flow import * # Fix namespace issues with `B.bvn_cdf` simply by setting it explicitly. B.bvn_cdf = B.generic.bvn_cdf
[ 11748, 25064, 198, 198, 6738, 22802, 1330, 3167, 8071, 2044, 198, 198, 33, 796, 25064, 13, 18170, 58, 834, 3672, 834, 60, 220, 1303, 22507, 1111, 1330, 12186, 13, 198, 6381, 17147, 796, 3167, 8071, 2044, 3419, 220, 1303, 770, 27965, 2...
3.125874
143
# coding: utf-8 from nbgrader.api import Gradebook from nbgrader.apps import ExportApp as BaseExportApp from traitlets import Instance from traitlets import Type from traitlets import default from ..plugins import CanvasCsvExportPlugin from ..plugins import CustomExportPlugin aliases = { "log-level": "Application.log_level", "db": "CourseDirectory.db_url", "to": "CanvasCsvExportPlugin.to", "canvas_import": "CanvasCsvExportPlugin.canvas_import", "exporter": "ExportApp.plugin_class", "assignment": "CanvasCsvExportPlugin.assignment", "student": "CanvasCsvExportPlugin.student", "course": "CourseDirectory.course_id", } flags = {}
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 6738, 299, 65, 2164, 5067, 13, 15042, 1330, 22653, 2070, 198, 6738, 299, 65, 2164, 5067, 13, 18211, 1330, 36472, 4677, 355, 7308, 43834, 4677, 198, 6738, 1291, 2578, 912, 1330, 2262, 590, 19...
2.938596
228
""" django_ocr_server/conf.py +++++++++++++++++++++++++ The settings manager for **django_ocr_server**. Usage: .. code-block:: python from django_ocr_server.conf import ocr_settings # Next line will print a value of **OCR_TESSERACT_LANG** # using the variable from the Django's *settings.py* file # if the variable is set there. # Or the default value of **OCR_TESSERACT_LANG** from # *django_ocr_server/default_settings.py* otherwise. print(ocr_settings.OCR_TESSERACT_LANG) | Author: shmakovpn <shmakovpn@yandex.ru> | Date: 2021-01-20 """ from typing import List from datetime import timedelta from django.conf import settings as _s import django_ocr_server.default_settings as _ds ocr_settings: DjangoOcrSettings = DjangoOcrSettings() """The instance of settings manager of **django_ocr_server**"""
[ 37811, 198, 28241, 14208, 62, 1696, 62, 15388, 14, 10414, 13, 9078, 198, 44627, 25128, 10, 198, 198, 464, 6460, 4706, 329, 12429, 28241, 14208, 62, 1696, 62, 15388, 1174, 13, 198, 198, 28350, 25, 198, 198, 492, 2438, 12, 9967, 3712, ...
3.098859
263
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 198 ]
3.777778
9
import math import numpy as np from openeye import oechem from torsion.inchi_keys import get_torsion_oeatom_list, get_torsion_oebond def GetPairwiseDistanceMatrix(icoords, jcoords): ''' input: two sets of coordinates, icoords, jcoords; each of which are a list of OEDoubleArray(3) containing x, y, and z component output: xij - the x component of the distance matrix yij - the y component of the distance matrix zij - the z component of the distance matrix rij - the distance matrix rij2 - square of the distance matrix ''' nullRet = [None, None, None, None, None] ni = len(icoords) nj = len(jcoords) try: iArrayX = np.array([c[0] for c in icoords]) iArrayY = np.array([c[1] for c in icoords]) iArrayZ = np.array([c[2] for c in icoords]) iArrayX = np.repeat(iArrayX, nj) iArrayY = np.repeat(iArrayY, nj) iArrayZ = np.repeat(iArrayZ, nj) iArrayX = iArrayX.reshape(ni, nj) iArrayY = iArrayY.reshape(ni, nj) iArrayZ = iArrayZ.reshape(ni, nj) jArrayX = np.array([c[0] for c in jcoords]) jArrayY = np.array([c[1] for c in jcoords]) jArrayZ = np.array([c[2] for c in jcoords]) jArrayX = np.repeat(jArrayX, ni) jArrayY = np.repeat(jArrayY, ni) jArrayZ = np.repeat(jArrayZ, ni) jArrayX = jArrayX.reshape(nj, ni) jArrayY = jArrayY.reshape(nj, ni) jArrayZ = jArrayZ.reshape(nj, ni) jArrayX = np.transpose(jArrayX) jArrayY = np.transpose(jArrayY) jArrayZ = np.transpose(jArrayZ) ijArrayX = jArrayX - iArrayX ijArrayY = jArrayY - iArrayY ijArrayZ = jArrayZ - iArrayZ rijArraySq = (ijArrayX * ijArrayX) + (ijArrayY * ijArrayY) + (ijArrayZ * ijArrayZ) rijArray = np.sqrt(rijArraySq) return ijArrayX, ijArrayY, ijArrayZ, rijArray, rijArraySq except: return nullRet def GetThetaIJKMatrix(iCoords, jCoords, kCoords): ''' Using the given input, calculates a matrix of angles ijk iCoords -> OEDoubleArray containing x, y, and z component of the reference coordinate jCoordsList -> list of N OEDoubleArrays, each OEDoubleArray is of size 3 kCoordsList -> list of M OEDoubleArrays, each OEDoubleArray is of size 3 return a N-by-M matrix of angle theta_ijk ''' jiArrayX, jiArrayY, jiArrayZ, rjiArray, rjiArraySq \ = GetPairwiseDistanceMatrix(jCoords, iCoords) jkArrayX, jkArrayY, jkArrayZ, rjkArray, rjkArraySq \ = GetPairwiseDistanceMatrix(jCoords, kCoords) if jCoords == kCoords: rjkArray = np.eye(len(jCoords)) + np.sqrt(rjkArraySq) else: rjkArray = np.sqrt(rjkArraySq) if jCoords == iCoords: rjiArray = np.eye(len(jCoords)) + np.sqrt(rjiArraySq) else: rjiArray = np.sqrt(rjiArraySq) jiArrayX = jiArrayX / rjiArray jiArrayY = jiArrayY / rjiArray jiArrayZ = jiArrayZ / rjiArray jkArrayX = jkArrayX / rjkArray jkArrayY = jkArrayY / rjkArray jkArrayZ = jkArrayZ / rjkArray dotProduct = (jiArrayX * jkArrayX) + (jiArrayY * jkArrayY) + (jiArrayZ * jkArrayZ) dotProduct = np.select([dotProduct <= -1.0, dotProduct >= 1.0, np.abs(dotProduct) < 1.0], [-0.999, 0.999, dotProduct]) theta_ijk = np.arccos(dotProduct) return theta_ijk def GetThetaIJKLMatrix(mol, iAtoms, jAtom, kAtom, lAtoms, transform=True): ''' Using the given input, calculates a matrix of torsion angles around jk jAtom, kAtom -> OEAtombase, middle two atoms of the torsion iAtoms -> list of N OEAtombase lAtoms -> list of M OEAtombase return a N-by-M matrix of angle theta_ijkl ''' torsions = [] for iAtom in iAtoms: for lAtom in lAtoms: tor_angle = oechem.OEGetTorsion(mol, iAtom, jAtom, kAtom, lAtom) if not transform: torsions.append(tor_angle) else: torsions.append((math.pi + tor_angle) / 4.0) theta_ijkl = np.array(torsions) theta_ijkl = theta_ijkl.reshape(len(iAtoms), len(lAtoms)) return theta_ijkl
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1280, 25379, 1330, 267, 721, 4411, 198, 6738, 256, 669, 295, 13, 8589, 72, 62, 13083, 1330, 651, 62, 83, 669, 295, 62, 2577, 37696, 62, 4868, 11, 651, 62, 83, 669, 295, ...
2.098945
1,991
""" Candidate generation & LTR Learning to Ranking""" # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import argparse from operator import itemgetter from math import sqrt import pandas as pd import pymysql from sklearn.model_selection import train_test_split # from sklearn.metrics.pairwise import pairwise_distances # from sklearn.metrics import mean_squared_error FLAGS = None def main(_): """main function""" user_cf = UserBasedCF(20, 10) user_cf.load_data() user_cf.calc_user_similarity() recommended_articled = user_cf.recommendation(FLAGS.uid) print(recommended_articled[0:10]) out = PrintArticles(recommended_articled[0:10]) out.output() # user_cf.evaluate() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.register("type", "bool", lambda v: v.lower() == "true") parser.add_argument( "--uid", type=int, default=80871, help="The user who is going to be recommended articles." ) parser.add_argument( "--n", type=int, default=10, help="Number of recommended articles." ) FLAGS, unparsed = parser.parse_known_args() print("{} {}".format(sys.argv[0], unparsed)) print(FLAGS) main(FLAGS)
[ 37811, 40327, 5270, 1222, 406, 5446, 18252, 284, 45407, 37811, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11...
2.591255
526
from datetime import timedelta from airflow import DAG from airflow.utils.dates import days_ago from airflow.operators.python_operator import PythonOperator from tweetstream.consumers.twitter_streaming import TwitterStreamingConsumer from tweetstream.clients.spark import SparkClient default_args = { "owner": "tweeetstream", "depends_on_past": False, "start_date": days_ago(1), "email": ["tweetstream@team.com"], "email_on_failure": False, "email_on_retry": False, "retries": 1, "retry_delay": timedelta(minutes=5), } dag = DAG( dag_id="twitter_streaming", default_args=default_args, description="Tweets Streaming Consumer", schedule_interval=timedelta(days=1), ) start_job_task = PythonOperator( dag=dag, task_id="start_streaming", python_callable=main, execution_timeout=None, )
[ 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, 45771, 1330, 360, 4760, 198, 6738, 45771, 13, 26791, 13, 19581, 1330, 1528, 62, 3839, 198, 6738, 45771, 13, 3575, 2024, 13, 29412, 62, 46616, 1330, 11361, 18843, 1352, 198, 6738, 6126, 55...
2.71885
313
from polyphony import testbench test()
[ 6738, 7514, 23021, 1330, 1332, 26968, 198, 198, 9288, 3419, 198 ]
3.636364
11
#!/usr/bin/python from setuptools import setup, find_packages from codecs import open with open('README.rst', 'r', 'utf-8') as fd: long_description = fd.read() setup(name='ipynb_format', version='0.1.1', description='A code formatter for python code in ipython notebooks', long_description=long_description, url='https://github.com/fg1/ipynb_format', author='fg1', license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', ], keywords='ipython notebook', packages=find_packages(), install_requires=['yapf'], entry_points={ 'console_scripts': [ 'ipynb_format=ipynb_format:cli', ], }, )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 40481, 82, 1330, 1280, 198, 198, 4480, 1280, 10786, 15675, 11682, 13, 81, 301, 3256, 705, 81, 3256, 705, 40477, 12, ...
2.348115
451
# -*- coding: utf-8 -*- feet = eval(input("Enter a value for feet: ")) meter = feet * 0.305 print (feet, "feet is %.4f meters" %(meter))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 39690, 796, 5418, 7, 15414, 7203, 17469, 257, 1988, 329, 3625, 25, 366, 4008, 198, 198, 27231, 796, 3625, 1635, 657, 13, 22515, 198, 198, 4798, 357, 39690, 11, 36...
2.413793
58
from mxnet import gluon from mxnet.gluon import HybridBlock from ceecnet.nn.layers.conv2Dnormed import * from ceecnet.utils.get_norm import * from ceecnet.nn.layers.attention import * # ======= Definitions for CEEC unit v2 (replace concatenations with Fusion ========================= # -------------------------------------- helper functions ------------------------------------------- # -------------------------------------------------------------------------------------------------------------------
[ 6738, 285, 87, 3262, 1330, 1278, 84, 261, 198, 6738, 285, 87, 3262, 13, 70, 2290, 261, 1330, 29481, 12235, 198, 6738, 2906, 721, 3262, 13, 20471, 13, 75, 6962, 13, 42946, 17, 35, 27237, 276, 1330, 1635, 198, 6738, 2906, 721, 3262, ...
4.705357
112
from django.db.models import Q from haystack import indexes from reviewboard.reviews.models import ReviewRequest
[ 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 1195, 198, 6738, 27678, 25558, 1330, 39199, 198, 198, 6738, 2423, 3526, 13, 19023, 82, 13, 27530, 1330, 6602, 18453, 628 ]
3.965517
29
from .statement import Statement, StatementType from .event import Event from ._helpers import debugmsg, simulation_error
[ 6738, 764, 26090, 1330, 21983, 11, 21983, 6030, 198, 6738, 764, 15596, 1330, 8558, 198, 6738, 47540, 16794, 364, 1330, 14257, 19662, 11, 18640, 62, 18224, 198 ]
4.518519
27
REDIS_URL = "redis://redis:6379/0" DEBUG = True TESTING = False JOBS = [ { 'id': 'actoken_refresh', 'func': 'actoken:refresh', 'args': None, 'trigger': 'interval', 'seconds': 7000 } ]
[ 22083, 1797, 62, 21886, 796, 366, 445, 271, 1378, 445, 271, 25, 21, 29088, 14, 15, 1, 198, 30531, 796, 6407, 198, 51, 6465, 2751, 796, 10352, 198, 198, 45006, 4462, 796, 685, 198, 220, 220, 220, 1391, 198, 220, 220, 220, 220, 220,...
1.918033
122
from shutil import copy, copytree, rmtree import pathlib import os import time def update(): """Update is a script to auto update all the files that the user is using""" print('Warehouse Hub is updating, do not close this window...') time.sleep(3) print('Applying patch...') time.sleep(1) copy('C:/warehousehub/warehousehub.exe', pathlib.Path().absolute()) rmtree(f'{pathlib.Path().absolute()}/templates') copytree('C:/warehousehub/templates', f'{pathlib.Path().absolute()}/templates') print('Patch Completed!') print('Warehouse Hub is restarting, please wait...') os.system(f'cmd /c "{pathlib.Path().absolute()}/warehousehub.exe"') if __name__ == '__main__': update()
[ 6738, 4423, 346, 1330, 4866, 11, 4866, 21048, 11, 374, 16762, 631, 198, 11748, 3108, 8019, 198, 11748, 28686, 198, 11748, 640, 628, 198, 4299, 4296, 33529, 198, 220, 220, 220, 37227, 10260, 318, 257, 4226, 284, 8295, 4296, 477, 262, 3...
2.873518
253
import functools import tensorflow as tf from core import trainer_video, input_reader from core.model_builder import build_man_model from google.protobuf import text_format from object_detection.builders import input_reader_builder from object_detection.protos import input_reader_pb2 from object_detection.protos import model_pb2 from object_detection.protos import pipeline_pb2 from object_detection.protos import train_pb2 import os ''' lijun's code modify bb to conv1*2 conv3*2 l2 normalization to match ''' os.environ["CUDA_VISIBLE_DEVICES"]="0" #os.environ["CUDA_VISIBLE_DEVICES"]="0" tf.logging.set_verbosity(tf.logging.INFO) flags = tf.app.flags flags.DEFINE_string('train_dir', 'model/dump', 'Directory to save the checkpoints and training summaries.') flags.DEFINE_string('pipeline_config_path', 'model/ssd_mobilenet_video.config', 'Path to a pipeline_pb2.TrainEvalPipelineConfig config ' 'file. If provided, other configs are ignored') flags.DEFINE_string('train_config_path', '', 'Path to a train_pb2.TrainConfig config file.') flags.DEFINE_string('input_config_path', '', 'Path to an input_reader_pb2.InputReader config file.') flags.DEFINE_string('model_config_path', '', 'Path to a model_pb2.DetectionModel config file.') flags.DEFINE_string('image_root', '/home/xiaobai/Documents/ILSVRC2014_DET_train/image/ILSVRC2014_DET_train', 'Root path to input images') flags.DEFINE_string('video_root', '/home/xiaobai/Documents/ILSVRC2015/', 'Root path to input videos') flags.DEFINE_string('image_tfrecord', './train_seq.record', 'Path to image tfrecord.') flags.DEFINE_string('video_tfrecord', './train_vid.record', 'Path to video tfrecord') FLAGS = flags.FLAGS def get_configs_from_pipeline_file(): """Reads training configuration from a pipeline_pb2.TrainEvalPipelineConfig. Reads training config from file specified by pipeline_config_path flag. Returns: model_config: model_pb2.DetectionModel train_config: train_pb2.TrainConfig input_config: input_reader_pb2.InputReader """ pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() with tf.gfile.GFile(FLAGS.pipeline_config_path, 'r') as f: text_format.Merge(f.read(), pipeline_config) model_config = pipeline_config.model.ssd train_config = pipeline_config.train_config input_config = pipeline_config.train_input_reader return model_config, train_config, input_config if __name__ == '__main__': # update moving average tf.app.run()
[ 11748, 1257, 310, 10141, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 4755, 1330, 21997, 62, 15588, 11, 5128, 62, 46862, 198, 6738, 4755, 13, 19849, 62, 38272, 1330, 1382, 62, 805, 62, 19849, 198, 6738, 23645, 13, 11235, 672, ...
2.601371
1,021
# -*- coding: utf-8 -*-
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628 ]
1.785714
14
# -*- coding: utf-8 -*- """ Created on Sat Mar 17 23:01:40 2018 @author: pc """ import scholarly,re,urllib.request,nltk import bs4 as bs # ============================================================================= # #Problme les derniere conf ne se rajoute pas # ============================================================================= # pass url_deb='https://dblp.uni-trier.de/db/conf/' url_deb2='http://dblp.uni-trier.de/db/conf/3dim/3dimpvt2012.html' url_deb3='http://dblp.uni-trier.de/db/conf/3dpvt/' #Timeline_of_conferences(url_deb2) publication_conf_dblp(url_deb3) #find_ComputerScienceConferences_Workshops_names_DBLP(url_deb)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 7031, 1526, 1596, 2242, 25, 486, 25, 1821, 2864, 201, 198, 201, 198, 31, 9800, 25, 40653, 201, 198, 37811, 201, 198, 201, 198, 11748,...
2.561338
269
#!/usr/bin/env python3 """ Main code for Robot """ import wpilib import robotmap from wpilib import Joystick from subsystems.drivetrain import DriveTrain as Drive from subsystems.grabber import cubeGrabber from subsystems.elevator import Elevator from subsystems.climber import Climber from subsystems.autonomous import Autonomous from wpilib.sendablechooser import SendableChooser # from robotpy_ext.common_drivers.navx import AHRS if __name__ == "__main__": wpilib.run(Robot)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 13383, 2438, 329, 16071, 198, 37811, 198, 198, 11748, 266, 79, 22282, 198, 11748, 9379, 8899, 198, 6738, 266, 79, 22282, 1330, 14087, 13915, 198, 6738, 39335, 82, 13, 1...
3.255034
149
#!/usr/bin/env python3 """ ATTOM API https://api.developer.attomdata.com """ import requests from urllib.parse import quote, urlencode from api import api PATH = "attomavm/detail" def get_avm_by_address(number_street, city_state): """ API request to get attomavm/detail """ params = urlencode( { "address1": number_street, "address2": city_state, } ) url = "{}/{}?{}".format(api.ATTOM_URL, PATH, params) r = requests.get(url, headers=api.headers) return r.json()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 198, 17139, 2662, 7824, 198, 5450, 1378, 15042, 13, 16244, 263, 13, 1078, 296, 7890, 13, 785, 198, 37811, 198, 11748, 7007, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 9577,...
2.515
200
import django from django.db import models from django.db.models.base import ModelBase from django.utils import six from .manager import IdMapManager from . import tls # thread local storage META_VALUES = { 'use_strong_refs': False, 'multi_db': False }
[ 11748, 42625, 14208, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 8692, 1330, 9104, 14881, 198, 198, 6738, 42625, 14208, 13, 26791, 1330, 2237, 198, 198, 6738, 764, 37153, 1330, 5121, ...
2.977778
90
from unittest import TestCase from search_in_rotated_sorted_array import Solution
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 2989, 62, 259, 62, 10599, 515, 62, 82, 9741, 62, 18747, 1330, 28186, 628 ]
3.5
24
#!/usr/bin/env python # -*- coding: utf-8 -*- # 3rd party imports import numpy as np import xarray as xr __author__ = "Louis Richard" __email__ = "louisr@irfu.se" __copyright__ = "Copyright 2020-2021" __license__ = "MIT" __version__ = "2.3.7" __status__ = "Prototype" def ts_skymap(time, data, energy, phi, theta, **kwargs): r"""Creates a skymap of the distribution function. Parameters ---------- time : ndarray List of times. data : ndarray Values of the distribution function. energy : ndarray Energy levels. phi : ndarray Azimuthal angles. theta : ndarray Elevation angles. Other Parameters --------------- **kwargs Hash table of keyword arguments with : * energy0 : ndarray Energy table 0 (odd time indices). * energy1 : ndarray Energy table 1 (even time indices). * esteptable : ndarray Time series of the stepping table between energies (burst). Returns ------- out : xarray.Dataset Skymap of the distribution function. """ energy0, energy1, esteptable = [None] * 3 energy0_ok, energy1_ok, esteptable_ok = [False] * 3 if energy is None: if "energy0" in kwargs: energy0, energy0_ok = [kwargs["energy0"], True] if "energy1" in kwargs: energy1, energy1_ok = [kwargs["energy1"], True] if "esteptable" in kwargs: esteptable, esteptable_ok = [kwargs["esteptable"], True] if not energy0_ok and not energy1_ok and not esteptable_ok: raise ValueError("Energy input required") energy = np.tile(energy0, (len(esteptable), 1)) energy[esteptable == 1] = np.tile(energy1, (int(np.sum(esteptable)), 1)) if phi.ndim == 1: phi = np.tile(phi, (len(time), 1)) out_dict = {"data": (["time", "idx0", "idx1", "idx2"], data), "phi": (["time", "idx1"], phi), "theta": (["idx2"], theta), "energy": (["time", "idx0"], energy), "time": time, "idx0": np.arange(energy.shape[1]), "idx1": np.arange(phi.shape[1]), "idx2": np.arange(len(theta))} out = xr.Dataset(out_dict) if energy0_ok: out.attrs["energy0"] = energy0 if energy1_ok: out.attrs["energy1"] = energy1 if energy0_ok: out.attrs["esteptable"] = esteptable return out
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 513, 4372, 2151, 17944, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2124, 18747, 355, 2124, 81, 198, 198, ...
2.130324
1,174
''' Author: Alex Wong <alexw@cs.ucla.edu> If you use this code, please cite the following paper: A. Wong, and S. Soatto. Unsupervised Depth Completion with Calibrated Backprojection Layers. https://arxiv.org/pdf/2108.10531.pdf @inproceedings{wong2021unsupervised, title={Unsupervised Depth Completion with Calibrated Backprojection Layers}, author={Wong, Alex and Soatto, Stefano}, booktitle={Proceedings of the IEEE/CVF International Conference on Computer Vision}, pages={12747--12756}, year={2021} } ''' import os import torch import numpy as np from matplotlib import pyplot as plt def log(s, filepath=None, to_console=True): ''' Logs a string to either file or console Arg(s): s : str string to log filepath output filepath for logging to_console : bool log to console ''' if to_console: print(s) if filepath is not None: if not os.path.isdir(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath)) with open(filepath, 'w+') as o: o.write(s + '\n') else: with open(filepath, 'a+') as o: o.write(s + '\n') def colorize(T, colormap='magma'): ''' Colorizes a 1-channel tensor with matplotlib colormaps Arg(s): T : torch.Tensor[float32] 1-channel tensor colormap : str matplotlib colormap ''' cm = plt.cm.get_cmap(colormap) shape = T.shape # Convert to numpy array and transpose if shape[0] > 1: T = np.squeeze(np.transpose(T.cpu().numpy(), (0, 2, 3, 1))) else: T = np.squeeze(np.transpose(T.cpu().numpy(), (0, 2, 3, 1)), axis=-1) # Colorize using colormap and transpose back color = np.concatenate([ np.expand_dims(cm(T[n, ...])[..., 0:3], 0) for n in range(T.shape[0])], axis=0) color = np.transpose(color, (0, 3, 1, 2)) # Convert back to tensor return torch.from_numpy(color.astype(np.float32))
[ 7061, 6, 198, 13838, 25, 4422, 27247, 1279, 1000, 87, 86, 31, 6359, 13, 36616, 64, 13, 15532, 29, 198, 198, 1532, 345, 779, 428, 2438, 11, 3387, 21729, 262, 1708, 3348, 25, 198, 198, 32, 13, 27247, 11, 290, 311, 13, 1406, 45807, ...
2.202162
925
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next
[ 2, 30396, 329, 1702, 306, 12, 25614, 1351, 13, 198, 2, 1398, 7343, 19667, 25, 198, 2, 220, 220, 220, 220, 825, 11593, 15003, 834, 7, 944, 11, 1188, 28, 15, 11, 1306, 28, 14202, 2599, 198, 2, 220, 220, 220, 220, 220, 220, 220, ...
2.272727
66
import time import re import tweepy import preprocessor as p import config import string consumer_key = config.consumer_key consumer_secret = config.consumer_secret access_token = config.access_token access_token_secret = config.access_token_secret bearer_token = config.bearer_token username = config.username password = config.password def clean_text(text): """ Function to clean the text. Parameters: text: the raw text as a string value that needs to be cleaned Returns: cleaned_text: the cleaned text as string """ # convert to lower case cleaned_text = text.lower() # remove HTML tags html_pattern = re.compile('<.*?>') cleaned_text = re.sub(html_pattern, '', cleaned_text) # remove punctuations cleaned_text = cleaned_text.translate( str.maketrans('', '', string.punctuation)) return cleaned_text.strip() client = tweepy.Client(bearer_token=bearer_token) list_id = "1467207384011526144" # all missouri legislators response = client.get_list_members(list_id, max_results = 100) users = response.data metadata = response.meta next_token = metadata.get("next_token") print(next_token) while next_token is not None: for user in users: string = str(user.name)+","+str(user.id)+","+str(user.username)+"\n" with open('moleglistmembership.txt', 'a') as f: f.write(string) response = client.get_list_members(list_id, pagination_token = next_token, max_results = 100) users = response.data metadata = response.meta next_token = metadata.get("next_token") print(next_token) # tweet_text = tweet.text # tweet_clean_text = clean_tweets(tweet.text) # tweet_created_at = tweet.created_at # tweet_clean_text = clean_text(tweet_clean_text) # print(tweet_clean_text) # print('\n') # print(tweet_created_at) # print('\n') # print('-----------------------------------------------------------------') # with open('molegmembership.txt', 'a') as f: # f.write(tweet_clean_text) # f.write('\n') # response = client.get_list_tweets(list_id, max_results=100)
[ 11748, 640, 198, 11748, 302, 198, 11748, 4184, 538, 88, 198, 11748, 662, 41341, 355, 279, 198, 11748, 4566, 198, 11748, 4731, 198, 198, 49827, 62, 2539, 796, 4566, 13, 49827, 62, 2539, 198, 49827, 62, 21078, 796, 4566, 13, 49827, 62, ...
2.740741
783
# Generated by Django 2.0.3 on 2018-03-14 09:59 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 18, 319, 2864, 12, 3070, 12, 1415, 7769, 25, 3270, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import tensorflow as tf import numpy as np from tensorflow.python.ops.gen_batch_ops import batch from model import AudioClass from qrnn import QRNN from numpy.random import seed from numpy.random import randn from random import randint from lstmfcn import LSTM_FCN import librosa import os if __name__ == "__main__": main()
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 2840, 13, 5235, 62, 43501, 62, 2840, 1330, 15458, 198, 6738, 2746, 1330, 13491, 9487, 198, 6738, 10662, 81, 20471, 13...
3.084112
107
from pytanga.components import AbstractComponent
[ 6738, 12972, 83, 16484, 13, 5589, 3906, 1330, 27741, 21950, 628, 198 ]
4.25
12
import math from typing import List, Tuple if __name__ == '__main__': solucao_problema()
[ 11748, 10688, 198, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 628, 628, 628, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1540, 1229, 5488, 62, 1676, 903, 2611, 3419, 198 ]
2.560976
41
from pymongo import MongoClient import pymongo from datetime import datetime,time import time from bson.code import Code mongo_client=MongoClient('mongodb://localhost:27017/') db=mongo_client.mydb db_col=db.things dbc = mongo_client.mydb.things print mongo_client print(db) print("connected") data = dbc.find() ans=True while ans: print(""" 1.How many unique users are there? 2.How many tweets (%) did the top 10 users (measured by the number of messages) publish? 3.What was the earliest and latest date (YYYY-MM-DD HH:MM:SS) that a message was published? 4.What is the mean time delta between all messages? 5.What is the mean length of a message? 6.What are the 10 most common unigram within the messages? 7.What are the 10 most common bigram within the messages? 8.What is the average number of hashtags (#) used within a message? 10.Exit/Quit """) ans = raw_input("What would you like to do? ") if ans == "1": print "The summary of all unique users is: ", first_querry() elif ans == "2": print("The percentage of the ALL messages of top ten user"), second_querry(), "%", elif ans == "3": print"The last message published on:", third_querry()[0] print"The earliest message published on:", third_querry()[1] elif ans == "4": print"The mean time delta between all messages is :", fourth_querry() elif ans == "5": print"The mean length of the messages is :", fifth_querry(data) elif ans == "6": print"The 10 most common unigrams within the messages are:", sixth_querry() elif ans == "7": print"The 10 most common bigrams within the messages are:", seventh_querry() elif ans == "8": print"The average number of hashtags (#) used within a message is:", eight_querry(data) elif ans == "9": ninth_querry() elif ans == "10": print("\n Goodbye") ans = None else: print("\n Not Valid Choice Try again")
[ 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 11748, 279, 4948, 25162, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 2435, 198, 11748, 640, 198, 6738, 275, 1559, 13, 8189, 1330, 6127, 198, 198, 76, 25162, 62, 16366, 28, 44, 25162, 1...
2.631918
777
#!/usr/bin/env python # -*- coding: utf-8 -*- """ serialize provide means to persist and recreate the currently known set of W_Tags and all shapes and transformations reachable from there. The rmarshal modules is used for serialization; the format is marshal_proto = ( int, # number of shapes [ # shape list ( # a shape int, # id (str, int), # tag [int], # structure: list of id's { # _hist (int, int) : # index, id int # count }, { # transformation_rules (int, int) : # index, id int # id } ) ], { (str, int) : # name arity int #id } ) The serialized tree is written to a '.docked' files """ import os.path from rpython.rlib.streamio import open_file_as_stream from rpython.rlib.rmarshal import get_marshaller, get_unmarshaller from rpython.rlib.debug import debug_start, debug_stop, debug_print from theseus.model import W_Tag from theseus.shape import in_storage_shape, CompoundShape marshal_proto = ( int, # number of shapes [ # shape list ( # a shape int, # id (str, int), # tag [int], # structure: list of id's { # _hist (int, int) : # index, id int # count }, { # transformation_rules (int, int) : # index, id int # id } ) ], { (str, int) : # name arity int #id } ) marshaller = get_marshaller(marshal_proto) unmarshaller = get_unmarshaller(marshal_proto) def punch_shape(s, registry): """ Punch a shape to a tuple for marshalling. See slurp_shapes, configure_shapes for inverse. Format is ( # a shape int, # id (str, int), # tag [int], # structure: list of id's { # _hist (int, int) : # index, id int # count }, { # transformation_rules (int, int) : # index, id int # id } ) """ if s == in_storage_shape: return (0, ('', 0), [], {}, {}) else: assert isinstance(s, CompoundShape) my_index = registry.index(s) hist = {} for (index, shape), count in s._hist.items(): shape_id = registry.index(shape) hist[(index, shape_id)] = count trans = {} for (index, shape), to_shape in s.transformation_rules.items(): shape_id = registry.index(shape) to_shape_id = registry.index(to_shape) trans[(index, registry.index(shape))] = registry.index(to_shape) punchee = ( registry.index(s), (s._tag.name, s._tag.arity()), [registry.index(subshape) for subshape in s._structure], hist, trans ) return punchee def recreate_shape(shape_desc, tags, registry): """ Recreate a shape from its punched format; see punch_shape. Does not handle history and transformations. See configure_shape(s). """ id, tag, structure_ids = shape_desc structure = [None] * len(structure_ids) for structure_index, sub_id in enumerate(structure_ids): assert sub_id < id subshape = registry[sub_id] assert subshape is not None structure[structure_index] = subshape return CompoundShape(tags[tag], structure) def configure_shape(shape, hist, trans, registry): """ Reconfigure a shape from its punched format; see punch_shape. Does _only_ handle history and transformations. See configure_shapes. """ assert isinstance(shape, CompoundShape) shape._hist = {} for (index, s_id), count in hist.items(): k = (index, registry[s_id]) shape._hist[k] = count shape.transformation_rules = {} for (index, s_id), to_s_id in trans.items(): k = (index, registry[s_id]) shape.transformation_rules[k] = registry[to_s_id] def configure_shapes(shapes, registry): """ Reconfigure all shapes. Does _only_ handle history and transformations. See configure_shapes. """ for id, _tag, _structure_ids, hist, trans in shapes: if id == 0: continue # in_storage_shape, no configure configure_shape(registry[id], hist, trans, registry) def slurp_registry(shapes, registry, tags_slurp, tags): """ Slurp all shapes from their punched format (see punch_shape) not including history or transformation """ known_ids = [0] for default_id in tags_slurp.values(): known_ids.append(default_id) for id, tag, structure_ids, _hist, _trans in shapes: if id in known_ids: continue assert registry[id] is None registry[id] = recreate_shape((id, tag, structure_ids), tags, registry) def punch_tags(tags): """ Punch all tags into marshallable format: ( int, # number of shapes [ # shape list ], { (str, int) : # name arity int #id } ) """ reg = [in_storage_shape] + CompoundShape._shapes punch_reg = [punch_shape(s, reg) for s in reg] res = {} for key, value in tags.items(): res[key] = reg.index(value.default_shape) return (len(punch_reg), punch_reg, res) def slurp_tags(un_tags): """ Slurp all tags from their punched format (see punch_tag). Recursively slurps shapes and then configures them. """ num_shapes, shapes_slurp, tags_slurp = un_tags registry = [None] * num_shapes registry[0] = in_storage_shape tags = {} for (name, arity), default_id in tags_slurp.items(): tag = W_Tag(name, arity) tags[(name, arity)] = tag registry[default_id] = tag.default_shape slurp_registry(shapes_slurp, registry, tags_slurp, tags) configure_shapes(shapes_slurp, registry) return tags def come_up(basename): """ Bring up previously marshalled Tags, shapes and transformations from '.docked' file un-marshalling, slurping and replacement of current Tags. """ from theseus.shape import CompoundShape # later # from os import stat # statres = stat(path) debug_start("theseus-come-up") path = basename + '.docked' if not os.path.exists(path): return try: f = open_file_as_stream(path, buffering=0) except OSError as e: os.write(2, "Error(come_up)%s -- %s\n" % (os.strerror(e.errno), path)) return try: res = unmarshaller(f.readall()) finally: f.close() del CompoundShape._shapes[:] W_Tag.tags.clear() new_tags = slurp_tags(res) for key, value in new_tags.items(): W_Tag.tags[key] = value debug_stop("theseus-come-up") def settle(basename): """ Settle Tags, shapes and transformations to a '.docked' file punching and marshalling all current Tags. """ debug_start("theseus-settle") path = basename + '.docked' buf = [] marshaller(buf, punch_tags(W_Tag.tags)) try: f = open_file_as_stream(path, mode="w", buffering=0) except OSError as e: os.write(2, "Error(settle)%s -- %s\n" % (os.strerror(e.errno), path)) return try: f.write(''.join(buf)) finally: f.close() debug_stop("theseus-settle")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 198, 46911, 1096, 198, 198, 15234, 485, 1724, 284, 21160, 290, 32049, 262, 3058, 1900, 198, 2617, 286, 370,...
2.238052
3,306
from web3 import Web3, HTTPProvider import json import os w3 = Web3(HTTPProvider("http://127.0.0.1:7545", request_kwargs={'timeout': 60})) print(f"Web3 is connected : {w3.isConnected()}") accounts = w3.eth.accounts # ------------------------------- get contract ------------------------------- # abi_path = "./vapp/src/contracts/" with open(os.path.join(abi_path, 'TokenHolderPayer.json'), "r") as file: property_contract_compiled = json.load(file) property_contract_abi = property_contract_compiled['abi'] contract_address = "0xE5972821D1218120C4E98986A3eEc997931690b4" property_contract = w3.eth.contract(address=contract_address, abi=property_contract_abi) # ------------------- buy some token from realestate agent ------------------- # amount = 500 # Allow token to be sent property_contract.functions.increaseAllowance(accounts[1], amount).transact({'from':accounts[0], 'gas': 420000, 'gasPrice': 21000}) balance = property_contract.functions.balanceOf(accounts[1]).call() print(f"initial balance {balance}") tx_hash = property_contract.functions.transferFrom(accounts[0], accounts[1], 500).transact({'from':accounts[1], 'gas': 420000, 'gasPrice': 21000}) receipt = w3.eth.waitForTransactionReceipt(tx_hash) balance = property_contract.functions.balanceOf(accounts[1]).call() print(f"final balance {balance}")
[ 6738, 3992, 18, 1330, 5313, 18, 11, 14626, 29495, 198, 11748, 33918, 198, 11748, 28686, 628, 198, 86, 18, 796, 5313, 18, 7, 40717, 29495, 7203, 4023, 1378, 16799, 13, 15, 13, 15, 13, 16, 25, 2425, 2231, 1600, 198, 220, 220, 220, 2...
2.922581
465
from preprocessing import preprocess from approach1_rulebased import get_predictions_rulebased from approach2_machine_learning import get_predictions_ml from bertopic_clustering import cluster_precursors def main(): '''Main function to use from commandline, preprocess input to generate embeddings, detect agression clauses using provided approach, extract features and labels from training and features from input data, trains a model and classifies test data using the trained model, evaluates predictions and goldlabels from input''' inputfile = 'sample_input.xls' preprocess(inputfile) get_predictions_rulebased() get_predictions_ml() ### only clusters with enough data, else everything in outlier cluster cluster_precursors() if __name__ == '__main__': main()
[ 6738, 662, 36948, 1330, 662, 14681, 201, 198, 6738, 3164, 16, 62, 25135, 3106, 1330, 651, 62, 28764, 9278, 62, 25135, 3106, 201, 198, 6738, 3164, 17, 62, 30243, 62, 40684, 1330, 651, 62, 28764, 9278, 62, 4029, 201, 198, 6738, 275, 8...
3.381148
244
from tkinter import * import threading import sql_manager as ss g=GUI()
[ 6738, 256, 74, 3849, 1330, 1635, 201, 198, 11748, 4704, 278, 201, 198, 11748, 44161, 62, 37153, 355, 37786, 201, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 201, 198, 201, 198, 70, 28, 40156, 3419, 2...
2.088889
45
import sys OPERATIONS = { 'addr': lambda a, b, c, registers: registers[a] + registers[b], 'addi': lambda a, b, c, registers: registers[a] + b, 'mulr': lambda a, b, c, registers: registers[a] * registers[b], 'muli': lambda a, b, c, registers: registers[a] * b, 'banr': lambda a, b, c, registers: registers[a] & registers[b], 'bani': lambda a, b, c, registers: registers[a] & b, 'borr': lambda a, b, c, registers: registers[a] | registers[b], 'bori': lambda a, b, c, registers: registers[a] | b, 'setr': lambda a, b, c, registers: registers[a], 'seti': lambda a, b, c, registers: a, 'grir': lambda a, b, c, registers: 1 if a > registers[b] else 0, 'gtri': lambda a, b, c, registers: 1 if registers[a] > b else 0, 'gtrr': lambda a, b, c, registers: 1 if registers[a] > registers[b] else 0, 'eqir': lambda a, b, c, registers: 1 if a == registers[b] else 0, 'eqri': lambda a, b, c, registers: 1 if registers[a] == b else 0, 'eqrr': lambda a, b, c, registers: 1 if registers[a] == registers[b] else 0 } print(solve(sys.stdin))
[ 11748, 25064, 628, 198, 31054, 18421, 796, 1391, 198, 220, 705, 29851, 10354, 37456, 257, 11, 275, 11, 269, 11, 28441, 25, 28441, 58, 64, 60, 1343, 28441, 58, 65, 4357, 198, 220, 705, 2860, 72, 10354, 37456, 257, 11, 275, 11, 269, ...
2.605911
406
from aiohttp import web from agents import Agent if __name__ == "__main__": webserver = WebServer("127.0.0.1", 8080, "/ws")
[ 6738, 257, 952, 4023, 1330, 3992, 198, 198, 6738, 6554, 1330, 15906, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 2639, 18497, 796, 5313, 10697, 7203, 16799, 13, 15, 13, 15, 13, 16, 160...
2.64
50
from wazimap.data.tables import FieldTable # Define our tables so the data API can discover them. # Household tables FieldTable(['rural population'], universe='Population', table_per_level=False) FieldTable(['area', 'sex'], universe='Population', table_per_level=False) FieldTable(['census_year', 'measure'], universe='A2-Decadal Variation', table_per_level=False) FieldTable(['census_year', 'sex_vis'], universe='VISUAL', table_per_level=False) FieldTable(['area', 'sex', 'literacy'], universe='Population', table_per_level=False) FieldTable(['area','village_town_comparison'], universe='A3APPENDIX', table_per_level=False) FieldTable(['religion', 'area', 'sex'], universe='Religion', table_per_level=False) FieldTable(['age', 'area', 'sex'], universe='Age', table_per_level=False) FieldTable(['village_town_measures','area'], universe='A1-', table_per_level=False) FieldTable(['education', 'area', 'sex'], universe='Education', table_per_level=False) FieldTable(['houseless_population','area', 'sex'], universe='A7-Houseless', table_per_level=False) FieldTable(['sc_houseless_population','area', 'sex'], universe='A8-SC_Houseless', table_per_level=False) FieldTable(['st_houseless_population','area', 'sex'], universe='A9-ST_Houseless', table_per_level=False) FieldTable(['village_measures','population_range'], universe='A3-Inhabited Villages', table_per_level=False) FieldTable(['maritalstatus', 'area', 'sex'], universe='Relation', table_per_level=False) FieldTable(['workertype','age_group','area','sex'], universe='B1-Workerstype', table_per_level=False) FieldTable(['sc_workertype','age_group','area','sex'], universe='B1SC-Workerstype', table_per_level=False) FieldTable(['st_workertype','age_group','area','sex'], universe='B1ST-Workerstype', table_per_level=False) FieldTable(['workers', 'area', 'workerssex'], universe='Workers', table_per_level=False) FieldTable(['workertype','education_level', 'area', 'sex'], universe='B3', table_per_level=False) FieldTable(['education_level', 'area', 'sex_vis'], universe='VISUAL', table_per_level=False) FieldTable(['sc_workertype','education_level', 'area', 'sex'], universe='B3SC', table_per_level=False) FieldTable(['st_workertype','education_level', 'area', 'sex'], universe='B3ST', table_per_level=False) FieldTable(['nonworkertype', 'age_group','area','sex'], universe='B13', table_per_level=False) FieldTable(['nonworkertype_vis', 'age_group','area','sex'], universe='VISUAL', table_per_level=False) FieldTable(['sc_nonworkertype', 'age_group','area','sex'], universe='B13SC', table_per_level=False) FieldTable(['st_nonworkertype', 'age_group','area','sex'], universe='B13ST', table_per_level=False) FieldTable(['religion','nonworkertype','age_group','area', 'sex'], universe='B14', table_per_level=False) FieldTable(['religion','area', 'sex'], universe='C1', table_per_level=False) FieldTable(['religious_community','area', 'sex'], universe='C1APPENDIX', table_per_level=False) FieldTable(['age_group','marital_status','area', 'sex'], universe='C2', table_per_level=False) FieldTable(['religion','marital_status','area', 'sex'], universe='C3', table_per_level=False) FieldTable(['mother_tongue_vis','area', 'sex'], universe='VISUAL', table_per_level=False) FieldTable(['disability','age_group','area', 'sex'], universe='c20', table_per_level=False) FieldTable(['mother_tongue','area', 'sex'], universe='c16', table_per_level=False) FieldTable(['educational_institution','age','area', 'sex'], universe='c10', table_per_level=False) FieldTable(['sc_educational_institution','age','area', 'sex'], universe='c10sc', table_per_level=False) FieldTable(['st_educational_institution','age','area', 'sex'], universe='c10st', table_per_level=False) FieldTable(['economic_activity','age','area', 'sex'], universe='c12', table_per_level=False) FieldTable(['marriage_duration','age','area', 'sex'], universe='c4', table_per_level=False) FieldTable(['parity','age','area'], universe='F1', table_per_level=False) FieldTable(['sc_parity','age','area'], universe='F1sc', table_per_level=False) FieldTable(['st_parity','age','area'], universe='F1st', table_per_level=False) FieldTable(['parity_vis','age','area'], universe='VISUAL', table_per_level=False) FieldTable(['surviving_children','age','area'], universe='F5', table_per_level=False) FieldTable(['sc_surviving_children','age','area'], universe='F5SC', table_per_level=False) FieldTable(['st_surviving_children','age','area'], universe='F5ST', table_per_level=False) FieldTable(['household_size','area'], universe='HH1', table_per_level=False) FieldTable(['household_size_vis','area'], universe='VISUAL', table_per_level=False) FieldTable(['sc_household_size','area'], universe='HH1SC', table_per_level=False) FieldTable(['st_household_size','area'], universe='HH1ST', table_per_level=False) FieldTable(['household_workers','workers_in_household','area'], universe='HH11', table_per_level=False) FieldTable(['household_size','available_for_work','area'], universe='HH12', table_per_level=False) FieldTable(['sevenyearsandabove','literates_in_household','area'], universe='HH08', table_per_level=False) FieldTable(['age','area', 'head','household_marital_status'], universe='HH06', table_per_level=False) FieldTable(['houseless_households','area'], universe='HH02', table_per_level=False) FieldTable(['households_size','aged_persons','area'], universe='HH05', table_per_level=False)
[ 6738, 266, 1031, 320, 499, 13, 7890, 13, 83, 2977, 1330, 7663, 10962, 628, 198, 2, 2896, 500, 674, 8893, 523, 262, 1366, 7824, 460, 7073, 606, 13, 198, 2, 37306, 8893, 198, 15878, 10962, 7, 17816, 81, 1523, 3265, 6, 4357, 6881, 11...
2.964325
1,822
import os import asyncio import logging from pony.orm import * import logger from database import start_orm, get_biggest_virgin, Guild, Virgin logger = logging.getLogger('virginity-bot') if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main())
[ 11748, 28686, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 198, 6738, 26902, 13, 579, 1330, 1635, 198, 198, 11748, 49706, 198, 6738, 6831, 1330, 923, 62, 579, 11, 651, 62, 14261, 3495, 62, 85, 4672, 11, 16446, 11, 5283, 198, 198, ...
3.010417
96
import os import shutil from .base import GnuRecipe
[ 11748, 28686, 198, 11748, 4423, 346, 198, 6738, 764, 8692, 1330, 18509, 84, 37523, 628 ]
3.533333
15
import os import sys import berserk from github import Github, InputFileContent, Gist SEPARATOR = "." PADDING = {"puzzle": 0, "crazyhouse": 0, "chess960": 0, "kingOfTheHill": 0, "threeCheck": 2, "antichess": 0, "atomic": 0, "horde": 0, "racingKings": 0, "ultraBullet": 0, "blitz": 1, "classical": 1, "rapid": 0, "bullet": 0, "correspondence": 3} emojis = {"puzzle": "", "crazyhouse": "", "chess960": "960", "kingOfTheHill": "", "threeCheck": "3", "antichess": "", "atomic": "", "horde": "", "racingKings": "", "ultraBullet": "", "blitz": "", "classical": "", "rapid": "", "bullet": "", "correspondence": ""} ENV_VAR_GIST_ID = "GIST_ID" ENV_VAR_GITHUB_TOKEN = "GH_TOKEN" ENV_VAR_LICHESS_USERNAME = "LICHESS_USERNAME" REQUIRED_ENVS = [ ENV_VAR_GIST_ID, ENV_VAR_GITHUB_TOKEN, ENV_VAR_LICHESS_USERNAME ] if __name__ == "__main__": # test with python lichess-gist.py test <gist> <github-token> <user> if len(sys.argv) > 1: os.environ[ENV_VAR_GIST_ID] = sys.argv[2] os.environ[ENV_VAR_GITHUB_TOKEN] = sys.argv[3] os.environ[ENV_VAR_LICHESS_USERNAME] = sys.argv[4] main() # %%
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 275, 364, 9587, 198, 6738, 33084, 1330, 38994, 11, 23412, 8979, 19746, 11, 402, 396, 198, 198, 5188, 27082, 25633, 796, 366, 526, 628, 198, 47, 29266, 2751, 796, 19779, 79, 9625, 1298, 657, ...
2.070423
568
"""empty message Revision ID: 60c735df8d2f Revises: 88bb7e12da60 Create Date: 2019-09-06 08:27:03.082097 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "60c735df8d2f" down_revision = "88bb7e12da60" branch_labels = None depends_on = None
[ 37811, 28920, 3275, 198, 198, 18009, 1166, 4522, 25, 3126, 66, 22, 2327, 7568, 23, 67, 17, 69, 198, 18009, 2696, 25, 9193, 11848, 22, 68, 1065, 6814, 1899, 198, 16447, 7536, 25, 13130, 12, 2931, 12, 3312, 8487, 25, 1983, 25, 3070, ...
2.430894
123
import scipy.io.wavfile as wav import numpy as np import os import pickle import random import operator from python_speech_features import mfcc dataset = [] training_set = [] test_set = [] # Get the distance between feature vectors # Find Neighbors # Identify the Nearest Neighbor (Genres) # Model Evaluation to get the accuracy # Extract features from the audio files and store them in a model file # Load in the Dataset if __name__ == '__main__': print('Starting....') local_filename = "dataset.aliran" extracting = False if extracting: print('Extracting Features...') print('Building Model...') extract_features(local_filename) print('Loading Dataset...') load_dataset(local_filename, 0.66, training_set, test_set) print('Making a prediction...') print('(This may take a few minutes)') predictions = [] for x in range(len(test_set)): predictions.append(nearest_genre(get_neighbors(training_set, test_set[x], 5))) accuracy = get_accuracy(test_set, predictions) print('Prediction Accuracy is:') print(accuracy)
[ 11748, 629, 541, 88, 13, 952, 13, 45137, 7753, 355, 266, 615, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 4738, 198, 11748, 10088, 198, 6738, 21015, 62, 45862, 62, 40890, 1330, 285, 69, 53...
2.924084
382
import argparse from libs.data_model import AnchorNorthstarDataframe, SalesForceDataframe, \ AnchorSalesforceAccountsDataframe, AnchorSalesforceContactsDataframe from libs.utils import save_dataframes_to_excel parser = argparse.ArgumentParser(description='Reconcile accounts and contacts between Anchor and Salesforce') parser.add_argument('-a', '--anchor-file', help='Path to Anchor Excel workbook', required=True) parser.add_argument('-n', '--northstar-file', help='Path to Northstar Excel workbook', required=True) parser.add_argument('-s', '--salesforce-file', help='Path to Salesforce Excel workbook', required=True) parser.add_argument('-t', '--account-name-match-ratio-threshold', type=int, help='Account names with specified (or above) similarity ratio will be used for joining Anchor and ' 'Salesforce account data. Number between 0 and 100.', default=75) parser.add_argument('-r', '--result-file', help='Path to result Excel workbook. The file will have 2 spreadsheets for accounts and ' 'contacts reconciliation', required=True) args = parser.parse_args() anchor_ns = AnchorNorthstarDataframe(args.anchor_file, args.northstar_file) salesforce = SalesForceDataframe(args.salesforce_file) anchor_sf_accounts = AnchorSalesforceAccountsDataframe(anchor_ns, salesforce, args.account_name_match_ratio_threshold) anchor_sf_contacts = AnchorSalesforceContactsDataframe(anchor_ns, salesforce) save_dataframes_to_excel(args.result_file, {'Accounts': anchor_sf_accounts.df, 'Contacts': anchor_sf_contacts.df}, wrap_text=False)
[ 11748, 1822, 29572, 198, 198, 6738, 9195, 82, 13, 7890, 62, 19849, 1330, 29253, 273, 14157, 7364, 6601, 14535, 11, 17329, 10292, 6601, 14535, 11, 3467, 198, 220, 220, 220, 29253, 273, 44490, 3174, 30116, 82, 6601, 14535, 11, 29253, 273,...
2.825641
585
bill()
[ 198, 198, 35546, 3419 ]
2
4
test = { 'name': 'q3b1', 'points': 2, 'suites': [ { 'cases': [ { 'code': '>>> 4 <= ' "sum(list(X1.describe().loc['mean'])) " '<= 9\n' 'True', 'hidden': False, 'locked': False}, { 'code': '>>> len(X1) == 768\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
[ 9288, 796, 1391, 220, 220, 705, 3672, 10354, 705, 80, 18, 65, 16, 3256, 198, 220, 220, 220, 705, 13033, 10354, 362, 11, 198, 220, 220, 220, 705, 2385, 2737, 10354, 685, 220, 220, 1391, 220, 220, 705, 33964, 10354, 685, 220, 220, 1...
1.32807
570
"""Scanpy's high-level API provides an overview of all features relevant to pratical use:: import scanpy.api as sc .. raw:: html <h3>Preprocessing tools</h3> Filtering of highly-variable genes, batch-effect correction, per-cell (UMI) normalization, preprocessing recipes. .. raw:: html <h4>Basic Preprocessing</h4> .. autosummary:: :toctree: . pp.filter_cells pp.filter_genes pp.filter_genes_dispersion pp.log1p pp.pca pp.normalize_per_cell pp.regress_out pp.scale pp.subsample .. raw:: html <h4>Recipes</h4> .. autosummary:: :toctree: . pp.recipe_zheng17 pp.recipe_weinreb16 .. raw:: html <h3>Machine Learning and Statistics tools<h3> .. raw:: html <h4>Visualization</h4> .. autosummary:: :toctree: . tl.pca tl.tsne tl.diffmap tl.draw_graph .. raw:: html <h4>Branching trajectories and pseudotime, clustering, differential expression</h4> .. autosummary:: :toctree: . tl.aga tl.louvain tl.dpt tl.rank_genes_groups .. raw:: html <h4>Simulations</h4> .. autosummary:: :toctree: . tl.sim .. raw:: html <h3>Generic methods</h3> .. raw:: html <h4>Reading and Writing</h4> .. autosummary:: :toctree: . read write read_10x_h5 .. raw:: html <h4>Data Structures</h4> .. autosummary:: :toctree: . AnnData DataGraph .. raw:: html <h3>Plotting</h3> .. raw:: html <h4>Generic plotting with AnnData</h4> .. autosummary:: :toctree: . pl.scatter pl.violin pl.ranking .. raw:: html <h4>Plotting tool results</h4> Methods that extract and visualize tool-specific annotation in an AnnData object. .. raw:: html <h5>Visualization</h5> .. autosummary:: :toctree: . pl.pca pl.pca_loadings pl.pca_scatter pl.pca_variance_ratio pl.tsne pl.diffmap pl.draw_graph .. raw:: html <h5>Branching trajectories and pseudotime, clustering, differential expression</h5> .. autosummary:: :toctree: . pl.aga pl.aga_graph pl.aga_path pl.louvain pl.dpt pl.dpt_scatter pl.dpt_groups_pseudotime pl.dpt_timeseries pl.rank_genes_groups pl.rank_genes_groups_violin .. raw:: html <h5>Simulations</h5> .. autosummary:: :toctree: . pl.sim .. raw:: html <h4>Builtin datasets</h4> Simple functions that provide annotated datasets for benchmarking. See `here <https://scanpy.readthedocs.io/en/latest/examples.html>`_ for extensive documented tutorials and use cases. All of these functions return an Annotated Data object. .. autosummary:: :toctree: . datasets.paul15 datasets.toggleswitch datasets.krumsiek11 datasets.blobs datasets.moignard15 """ from .. import __version__ from .. import settings from .. import logging from . import tl tools = tl from . import pl plotting = pl from . import pp preprocessing = pp from ..readwrite import read, read_10x_h5, write, read_params, write_params from . import datasets from ..data_structs import AnnData, DataGraph from .. import utils
[ 37811, 33351, 9078, 338, 1029, 12, 5715, 7824, 3769, 281, 16700, 286, 477, 3033, 5981, 284, 778, 39056, 779, 3712, 628, 220, 220, 1330, 9367, 9078, 13, 15042, 355, 629, 628, 198, 198, 492, 8246, 3712, 27711, 628, 220, 220, 1279, 71, ...
2.475649
1,232
import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from .modeling_albert import AlbertPreTrainedModel, AlbertLayerNorm, AlbertLayerGroup from .modeling_bert import BertEmbeddings from .modeling_highway_bert import BertPooler import numpy as np
[ 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 6372, 14539, 28338, 43, 793, 11, 6579, 3698, 793, 198, 198, 6738, 764, 4666, 10809, 62, 282, 4835, 1330, 9966, 6719, 2898, 1328, 17633, 11, 9966, 49925, ...
3.426829
82
# Copyright 2020 Kapil Thangavelu # # 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 .common import BaseTest
[ 2, 15069, 12131, 27344, 346, 536, 16484, 626, 84, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 1...
3.897436
156
import json import os import sys sys.path.append('/usr/lib/python2.7/dist-packages') import cv2 import numpy as np from tqdm import * import dataset_utils
[ 11748, 33918, 198, 11748, 28686, 198, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 10786, 14, 14629, 14, 8019, 14, 29412, 17, 13, 22, 14, 17080, 12, 43789, 11537, 220, 198, 11748, 269, 85, 17, 198, 198, 11748, 299, 32152, 355, ...
2.758621
58
import numpy as np from scipy.constants import mu_0, epsilon_0 import matplotlib.pyplot as plt from PIL import Image import warnings warnings.filterwarnings('ignore') from ipywidgets import interact, interactive, IntSlider, widget, FloatText, FloatSlider, fixed from .Wiggle import wiggle, PrimaryWave, ReflectedWave import requests from io import BytesIO ######################################## # DOWNLOAD FUNCTIONS ######################################## ######################################## # WIDGETS ######################################## ######################################## # FUNCTIONS ########################################
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 9979, 1187, 1330, 38779, 62, 15, 11, 304, 862, 33576, 62, 15, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 14...
3.819672
183
data = ( 'bols', # 0x00 'bolt', # 0x01 'bolp', # 0x02 'bolh', # 0x03 'bom', # 0x04 'bob', # 0x05 'bobs', # 0x06 'bos', # 0x07 'boss', # 0x08 'bong', # 0x09 'boj', # 0x0a 'boc', # 0x0b 'bok', # 0x0c 'bot', # 0x0d 'bop', # 0x0e 'boh', # 0x0f 'bwa', # 0x10 'bwag', # 0x11 'bwagg', # 0x12 'bwags', # 0x13 'bwan', # 0x14 'bwanj', # 0x15 'bwanh', # 0x16 'bwad', # 0x17 'bwal', # 0x18 'bwalg', # 0x19 'bwalm', # 0x1a 'bwalb', # 0x1b 'bwals', # 0x1c 'bwalt', # 0x1d 'bwalp', # 0x1e 'bwalh', # 0x1f 'bwam', # 0x20 'bwab', # 0x21 'bwabs', # 0x22 'bwas', # 0x23 'bwass', # 0x24 'bwang', # 0x25 'bwaj', # 0x26 'bwac', # 0x27 'bwak', # 0x28 'bwat', # 0x29 'bwap', # 0x2a 'bwah', # 0x2b 'bwae', # 0x2c 'bwaeg', # 0x2d 'bwaegg', # 0x2e 'bwaegs', # 0x2f 'bwaen', # 0x30 'bwaenj', # 0x31 'bwaenh', # 0x32 'bwaed', # 0x33 'bwael', # 0x34 'bwaelg', # 0x35 'bwaelm', # 0x36 'bwaelb', # 0x37 'bwaels', # 0x38 'bwaelt', # 0x39 'bwaelp', # 0x3a 'bwaelh', # 0x3b 'bwaem', # 0x3c 'bwaeb', # 0x3d 'bwaebs', # 0x3e 'bwaes', # 0x3f 'bwaess', # 0x40 'bwaeng', # 0x41 'bwaej', # 0x42 'bwaec', # 0x43 'bwaek', # 0x44 'bwaet', # 0x45 'bwaep', # 0x46 'bwaeh', # 0x47 'boe', # 0x48 'boeg', # 0x49 'boegg', # 0x4a 'boegs', # 0x4b 'boen', # 0x4c 'boenj', # 0x4d 'boenh', # 0x4e 'boed', # 0x4f 'boel', # 0x50 'boelg', # 0x51 'boelm', # 0x52 'boelb', # 0x53 'boels', # 0x54 'boelt', # 0x55 'boelp', # 0x56 'boelh', # 0x57 'boem', # 0x58 'boeb', # 0x59 'boebs', # 0x5a 'boes', # 0x5b 'boess', # 0x5c 'boeng', # 0x5d 'boej', # 0x5e 'boec', # 0x5f 'boek', # 0x60 'boet', # 0x61 'boep', # 0x62 'boeh', # 0x63 'byo', # 0x64 'byog', # 0x65 'byogg', # 0x66 'byogs', # 0x67 'byon', # 0x68 'byonj', # 0x69 'byonh', # 0x6a 'byod', # 0x6b 'byol', # 0x6c 'byolg', # 0x6d 'byolm', # 0x6e 'byolb', # 0x6f 'byols', # 0x70 'byolt', # 0x71 'byolp', # 0x72 'byolh', # 0x73 'byom', # 0x74 'byob', # 0x75 'byobs', # 0x76 'byos', # 0x77 'byoss', # 0x78 'byong', # 0x79 'byoj', # 0x7a 'byoc', # 0x7b 'byok', # 0x7c 'byot', # 0x7d 'byop', # 0x7e 'byoh', # 0x7f 'bu', # 0x80 'bug', # 0x81 'bugg', # 0x82 'bugs', # 0x83 'bun', # 0x84 'bunj', # 0x85 'bunh', # 0x86 'bud', # 0x87 'bul', # 0x88 'bulg', # 0x89 'bulm', # 0x8a 'bulb', # 0x8b 'buls', # 0x8c 'bult', # 0x8d 'bulp', # 0x8e 'bulh', # 0x8f 'bum', # 0x90 'bub', # 0x91 'bubs', # 0x92 'bus', # 0x93 'buss', # 0x94 'bung', # 0x95 'buj', # 0x96 'buc', # 0x97 'buk', # 0x98 'but', # 0x99 'bup', # 0x9a 'buh', # 0x9b 'bweo', # 0x9c 'bweog', # 0x9d 'bweogg', # 0x9e 'bweogs', # 0x9f 'bweon', # 0xa0 'bweonj', # 0xa1 'bweonh', # 0xa2 'bweod', # 0xa3 'bweol', # 0xa4 'bweolg', # 0xa5 'bweolm', # 0xa6 'bweolb', # 0xa7 'bweols', # 0xa8 'bweolt', # 0xa9 'bweolp', # 0xaa 'bweolh', # 0xab 'bweom', # 0xac 'bweob', # 0xad 'bweobs', # 0xae 'bweos', # 0xaf 'bweoss', # 0xb0 'bweong', # 0xb1 'bweoj', # 0xb2 'bweoc', # 0xb3 'bweok', # 0xb4 'bweot', # 0xb5 'bweop', # 0xb6 'bweoh', # 0xb7 'bwe', # 0xb8 'bweg', # 0xb9 'bwegg', # 0xba 'bwegs', # 0xbb 'bwen', # 0xbc 'bwenj', # 0xbd 'bwenh', # 0xbe 'bwed', # 0xbf 'bwel', # 0xc0 'bwelg', # 0xc1 'bwelm', # 0xc2 'bwelb', # 0xc3 'bwels', # 0xc4 'bwelt', # 0xc5 'bwelp', # 0xc6 'bwelh', # 0xc7 'bwem', # 0xc8 'bweb', # 0xc9 'bwebs', # 0xca 'bwes', # 0xcb 'bwess', # 0xcc 'bweng', # 0xcd 'bwej', # 0xce 'bwec', # 0xcf 'bwek', # 0xd0 'bwet', # 0xd1 'bwep', # 0xd2 'bweh', # 0xd3 'bwi', # 0xd4 'bwig', # 0xd5 'bwigg', # 0xd6 'bwigs', # 0xd7 'bwin', # 0xd8 'bwinj', # 0xd9 'bwinh', # 0xda 'bwid', # 0xdb 'bwil', # 0xdc 'bwilg', # 0xdd 'bwilm', # 0xde 'bwilb', # 0xdf 'bwils', # 0xe0 'bwilt', # 0xe1 'bwilp', # 0xe2 'bwilh', # 0xe3 'bwim', # 0xe4 'bwib', # 0xe5 'bwibs', # 0xe6 'bwis', # 0xe7 'bwiss', # 0xe8 'bwing', # 0xe9 'bwij', # 0xea 'bwic', # 0xeb 'bwik', # 0xec 'bwit', # 0xed 'bwip', # 0xee 'bwih', # 0xef 'byu', # 0xf0 'byug', # 0xf1 'byugg', # 0xf2 'byugs', # 0xf3 'byun', # 0xf4 'byunj', # 0xf5 'byunh', # 0xf6 'byud', # 0xf7 'byul', # 0xf8 'byulg', # 0xf9 'byulm', # 0xfa 'byulb', # 0xfb 'byuls', # 0xfc 'byult', # 0xfd 'byulp', # 0xfe 'byulh', # 0xff )
[ 7890, 796, 357, 201, 198, 6, 65, 10220, 3256, 220, 220, 220, 1303, 657, 87, 405, 201, 198, 6, 25593, 3256, 220, 220, 220, 1303, 657, 87, 486, 201, 198, 6, 28984, 79, 3256, 220, 220, 220, 1303, 657, 87, 2999, 201, 198, 6, 28984, ...
1.408094
3,558
from social_core.backends.azuread import AzureADOAuth2
[ 6738, 1919, 62, 7295, 13, 1891, 2412, 13, 1031, 495, 324, 1330, 22134, 2885, 23621, 1071, 17, 198 ]
3.055556
18
# Copyright (c) 2012 Israel Herraiz <isra@herraiz.org> # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import wx import numpy from numpy import zeros
[ 2, 15069, 357, 66, 8, 2321, 2692, 2332, 430, 528, 1279, 271, 430, 31, 372, 430, 528, 13, 2398, 29, 198, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 198, 2, 257, 4866, 286, 428, 3788, 290...
3.762987
308
import traceback from typing import Optional from .i18n import _
[ 11748, 12854, 1891, 198, 6738, 19720, 1330, 32233, 198, 6738, 764, 72, 1507, 77, 1330, 4808, 628, 628, 628, 628 ]
3.6
20
import sys import csv import requests from parsel import Selector from scraper.parser import get_features_from_item start_url = 'http://www.world-art.ru/animation/rating_top.php' SIGN_STDOUT = '-' FORMAT_CSV = 'csv' FORMAT_JL = 'jl' def parse(url: str, out_path: str, out_format: str): """ gets link and returns the response """ response = requests.get(url) assert response.status_code == 200, f'bad status code: {response.status_code}' response_html = Selector(response.text) links_to_films = response_html.xpath('//td[@class="review"]/a[@class="review"]/@href').getall() out_file = sys.stdout if out_path == SIGN_STDOUT else open(out_path, 'w', buffering=1, newline='') for link in links_to_films: item_response = requests.get(link) assert response.status_code == 200, f'bad status code: {item_response.status_code}' item = get_features_from_item(item_response) if out_format == FORMAT_CSV: item_writer = csv.writer(out_file, delimiter=' ', quotechar=',', quoting=csv.QUOTE_MINIMAL) item_writer.writerow(item.values()) out_file.close() return
[ 11748, 25064, 198, 11748, 269, 21370, 198, 11748, 7007, 198, 6738, 1582, 741, 1330, 9683, 273, 198, 6738, 19320, 525, 13, 48610, 1330, 651, 62, 40890, 62, 6738, 62, 9186, 628, 198, 9688, 62, 6371, 796, 705, 4023, 1378, 2503, 13, 6894,...
2.573333
450
from __future__ import print_function import os import sys import serial.tools.list_ports from PyQt4 import QtCore from PyQt4 import QtGui from photogate_ui import Ui_PhotogateMainWindow from photogate_serial import PhotogateDevice from photogate_serial import getListOfPorts import dependency_hack try: import scipy.io HAVE_SCIPY_IO = True except ImportError: HAVE_SCIPY_IO = False # Utility functions # ----------------------------------------------------------------------------- def getPhotogateTimes(photogateDict): entryTime = uSecToSec(float(photogateDict['entryTime'])) exitTime = uSecToSec(float(photogateDict['exitTime'])) timeInGate = exitTime - entryTime return entryTime, exitTime, timeInGate def getTimeBetweenGates(photogateList): entryTime0 = uSecToSec(float(photogateList[0]['entryTime'])) entryTime1 = uSecToSec(float(photogateList[1]['entryTime'])) timeBetween = entryTime1 - entryTime0 return timeBetween def autoAddFileExtension(fileName,autoExt): fileNameBase, fileNameExt = os.path.splitext(fileName) if not fileNameExt: # Only add extension if there isn't one already fileName = '{0}{1}'.format(fileNameBase,autoExt) return fileName def uSecToSec(value): return (1.0e-6)*value def runPhotogateApp(): app = QtGui.QApplication(sys.argv) mainWindow = PhotogateMainWindow() mainWindow.main() app.exec_() # ----------------------------------------------------------------------------- if __name__ == '__main__': runPhotogateApp()
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 11389, 13, 31391, 13, 4868, 62, 3742, 198, 6738, 9485, 48, 83, 19, 1330, 33734, 14055, 198, 6738, 9485, 48, 83, 19, 1330, 33734, 8205, 72...
2.903525
539
from core import Variable from operation import * a = Variable(2) b = square(a) c = square(b) print(c.data)
[ 198, 6738, 4755, 1330, 35748, 198, 6738, 4905, 1330, 1635, 628, 198, 64, 796, 35748, 7, 17, 8, 198, 65, 796, 6616, 7, 64, 8, 198, 66, 796, 6616, 7, 65, 8, 628, 198, 4798, 7, 66, 13, 7890, 8, 628 ]
2.780488
41
name = 'sharepoint' from .sharepoint import SharePointSite __author__='James Classen' __version__='0.0.2'
[ 3672, 796, 705, 20077, 4122, 6, 198, 198, 6738, 764, 20077, 4122, 1330, 8734, 12727, 29123, 198, 834, 9800, 834, 11639, 14731, 5016, 268, 6, 198, 834, 9641, 834, 11639, 15, 13, 15, 13, 17, 6 ]
2.944444
36
# Copyright 2015 The Offline Content Packager Authors. 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. from os import makedirs from os.path import dirname from os.path import isdir from os.path import join import shutil import tempfile import unittest import jinja2 from scripts.transformations import VideoTransformation import yaml if __name__ == "__main__": unittest.main()
[ 2, 15069, 1853, 383, 49749, 14041, 6400, 3536, 46665, 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, 345, 743, 407, 779, 428, 2393, 2845, 287, ...
3.716049
243
from pathlib import Path from pyspark.sql import SparkSession, functions as f from pyspark.sql.dataframe import DataFrame # Monkeypatch in case I don't use Spark 3.0 DataFrame.transform = transform # Sample/demo purposes mpns_v8_name_relationships_filepath: str = ( "data/analysis/mpns/sample_mpns_v8/name_relationships/" ) output_filepath: str = "data/analysis/mpns/sample_mpns_v8/name_relationships/query/" query_mpns_v8_name_relationships( input_filepath=mpns_v8_name_relationships_filepath, output_filepath=output_filepath, sample_run=True, ) # # Real data # mpns_v8_name_relationships_filepath: str = ( # "data/analysis/mpns/mpns_v8/name_relationships/" # ) # output_filepath: str = "data/analysis/mpns/mpns_v8/name_relationships/query/" # query_mpns_v8_name_relationships( # input_filepath=mpns_v8_name_relationships_filepath, # output_filepath=output_filepath, # sample_run=False, # )
[ 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 279, 893, 20928, 13, 25410, 1330, 17732, 36044, 11, 5499, 355, 277, 198, 6738, 279, 893, 20928, 13, 25410, 13, 7890, 14535, 1330, 6060, 19778, 628, 198, 2, 220, 26997, 17147, 287, 1339, 3...
2.595568
361
# -*- coding: utf-8 -*- """ Created on Wed May 23 16:56:57 2018 @author: tommy_mizuki """ import my_library my_func(1,2)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 1737, 2242, 1467, 25, 3980, 25, 3553, 2864, 198, 198, 31, 9800, 25, 16667, 1820, 62, 76, 528, 11308, 198, 37811, 628, 198, 11748, 616, 62...
2.214286
56
n = int(input()) count = 0 number = 0 while True: if '666' in str(number): # '666' count . count += 1 if count == n: #count print -> n print(number) break number += 1
[ 77, 796, 493, 7, 15414, 28955, 198, 9127, 796, 657, 198, 17618, 796, 657, 198, 4514, 6407, 25, 198, 220, 220, 220, 611, 705, 27310, 6, 287, 965, 7, 17618, 2599, 197, 2, 220, 705, 27310, 6, 220, 954, 764, 198, 220, 220, 220, 220,...
2.1
100
""" plot request rate """ import os, sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../")) from utils.common import * if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("--trace", type=str, help="trace path") ap.add_argument("--type", type=str, default="cnt", help="plot type") ap.add_argument("--window", type=int, default=60, help="the size of window in sec") p = ap.parse_args() plot_req_rate(TwrShortBinTraceReader(p.trace), p.window, plot_type=(p.type, ))
[ 37811, 7110, 2581, 2494, 198, 198, 37811, 198, 198, 11748, 28686, 11, 25064, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834,...
2.697561
205
import os import redis import logging config = { 'development': DevelopmentConfig, 'production': ProductionConfig, 'default': DevelopmentConfig }
[ 11748, 28686, 198, 11748, 2266, 271, 198, 11748, 18931, 628, 198, 11250, 796, 1391, 198, 220, 220, 220, 705, 31267, 10354, 7712, 16934, 11, 198, 220, 220, 220, 705, 25493, 10354, 19174, 16934, 11, 198, 220, 220, 220, 705, 12286, 10354, ...
3.232143
56
import tensorflow as tf from tensorflow.python import pywrap_tensorflow from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import saver as tf_saver def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradient calculation for each tower. Returns: List of pairs of (gradient, variable) where the gradient has been averaged across all towers. """ average_grads = [] for grad_and_vars in zip(*tower_grads): # Note that each grad_and_vars looks like the following: # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) grads = [] for g, _ in grad_and_vars: # Add 0 dimension to the gradients to represent the tower. expanded_g = tf.expand_dims(g, 0) # Append on a 'tower' dimension which we will average over below. grads.append(expanded_g) # Average over the 'tower' dimension. grad = tf.concat(axis=0, values=grads) grad = tf.reduce_mean(grad, 0) # Keep in mind that the Variables are redundant because they are shared # across towers. So .. we will just return the first tower's pointer to # the Variable. v = grad_and_vars[0][1] grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads def montage_tf(imgs, num_h, num_w): """Makes a montage of imgs that can be used in image_summaries. Args: imgs: Tensor of images num_h: Number of images per column num_w: Number of images per row Returns: A montage of num_h*num_w images """ imgs = tf.unstack(imgs) img_rows = [None] * num_h for r in range(num_h): img_rows[r] = tf.concat(axis=1, values=imgs[r * num_w:(r + 1) * num_w]) montage = tf.concat(axis=0, values=img_rows) return tf.expand_dims(montage, 0) def assign_from_checkpoint_fn(model_path, var_list, ignore_missing_vars=False, reshape_variables=False): """Returns a function that assigns specific variables from a checkpoint. Args: model_path: The full path to the model checkpoint. To get latest checkpoint use `model_path = tf.train.latest_checkpoint(checkpoint_dir)` var_list: A list of `Variable` objects or a dictionary mapping names in the checkpoint to the correspoing variables to initialize. If empty or None, it would return no_op(), None. ignore_missing_vars: Boolean, if True it would ignore variables missing in the checkpoint with a warning instead of failing. reshape_variables: Boolean, if True it would automatically reshape variables which are of different shape then the ones stored in the checkpoint but which have the same number of elements. Returns: A function that takes a single argument, a `tf.Session`, that applies the assignment operation. Raises: ValueError: If the checkpoint specified at `model_path` is missing one of the variables in `var_list`. """ if ignore_missing_vars: var_list = remove_missing(var_list, model_path) saver = tf_saver.Saver(var_list, reshape=reshape_variables) return callback def get_variables_to_train(trainable_scopes=None): """Returns a list of variables to train. Returns: A list of variables to train by the optimizer. """ if trainable_scopes is None: variables_to_train = tf.trainable_variables() else: scopes = [scope.strip() for scope in trainable_scopes.split(',')] variables_to_train = [] for scope in scopes: variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope) variables_to_train.extend(variables) print('Variables to train: {}'.format([v.op.name for v in variables_to_train])) return variables_to_train
[ 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 13, 29412, 1330, 12972, 37150, 62, 83, 22854, 11125, 198, 6738, 11192, 273, 11125, 13, 29412, 13, 24254, 1330, 48700, 62, 6404, 2667, 355, 18931, 198, 6738, 11192, 273, ...
2.576271
1,652
from dataclasses import dataclass from typing import List from paralleldomain.model.annotation.common import Annotation from paralleldomain.model.annotation.polyline_2d import Polyline2D
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 9315, 23826, 391, 13, 19849, 13, 1236, 14221, 13, 11321, 1330, 1052, 38983, 198, 6738, 9315, 23826, 391, 13, 19849, 13, 1236, 14221, 13, 35428...
3.653846
52
import os import shutil import sys from maplist import installed_games backup_dir = "F:/bsps" if len(sys.argv) == 2: backup_dir = sys.argv[1] print(f"Making backups in '{backup_dir}'") i = 0 for base_dir, game_dir in installed_games: i += 1 print(f"Backing up ({i}/{len(installed_games)}) {game_dir}...") for map_dir in installed_games[(base_dir, game_dir)]: src_dir = os.path.join(base_dir, game_dir, map_dir) dest_dir = os.path.join(backup_dir, game_dir, map_dir) os.makedirs(dest_dir, exist_ok=True) try: # note the missed file(s) and continue shutil.copytree(src_dir, dest_dir, dirs_exist_ok=True) except shutil.Error as err: print(f"*** ERROR *** {err}") except FileNotFoundError as err: print(f"*** ERROR *** {err}")
[ 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 25064, 198, 198, 6738, 17266, 489, 396, 1330, 6589, 62, 19966, 628, 198, 1891, 929, 62, 15908, 796, 366, 37, 14079, 1443, 862, 1, 198, 361, 18896, 7, 17597, 13, 853, 85, 8, 6624, 362,...
2.208
375
from typing import List, Optional from pydantic import AnyHttpUrl from infobip_channels.core.models import CamelCaseModel, ResponseBase
[ 6738, 19720, 1330, 7343, 11, 32233, 198, 198, 6738, 279, 5173, 5109, 1330, 4377, 43481, 28165, 198, 198, 6738, 1167, 672, 541, 62, 354, 8961, 13, 7295, 13, 27530, 1330, 43281, 20448, 17633, 11, 18261, 14881, 628, 628, 628 ]
3.666667
39
import logging from flask import Flask, request, jsonify from extractor.document import Document from extractor.five_w_extractor import FiveWExtractor app = Flask(__name__) log = logging.getLogger(__name__) host = None port = 5000 debug = False options = None extractor = FiveWExtractor() ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) log.addHandler(ch) log.setLevel(logging.DEBUG) if __name__ == "__main__": run()
[ 11748, 18931, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 33918, 1958, 198, 198, 6738, 7925, 273, 13, 22897, 1330, 16854, 198, 6738, 7925, 273, 13, 13261, 62, 86, 62, 2302, 40450, 1330, 10579, 8845, 742, 40450, 198, 198, 1324, 796, 4...
3.041958
143
import os import tempfile import pkg_resources as p from CPAC.utils.symlinks import create_symlinks mocked_outputs = \ p.resource_filename( "CPAC", os.path.join( 'utils', 'tests', 'test_symlinks-outputs.txt' ) )
[ 11748, 28686, 198, 11748, 20218, 7753, 198, 11748, 279, 10025, 62, 37540, 355, 279, 198, 198, 6738, 16932, 2246, 13, 26791, 13, 37047, 28751, 1330, 2251, 62, 37047, 28751, 628, 198, 76, 3543, 62, 22915, 82, 796, 3467, 198, 220, 220, 2...
1.992958
142
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-09 15:33 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django_extensions.db.fields
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 16, 319, 1584, 12, 2931, 12, 2931, 1315, 25, 2091, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.8
80
"""Script for running the dserve server.""" import os from flask import ( Flask, jsonify, send_file, abort, request, ) from flask_cors import CORS, cross_origin app = Flask(__name__) cors = CORS(app) def overlay_root(): overlays = app._dataset.access_overlays() content = { "_links": { "self": {"href": "/overlays"}}, } for overlay_name in overlays.keys(): value = {"href": "/overlays/{}".format(overlay_name)} content["_links"][overlay_name] = value return jsonify(content) def specific_overlay(overlay_name): overlays = app._dataset.access_overlays() try: overlay = overlays[overlay_name] except KeyError: abort(404) return jsonify(overlay) def creaate_new_overlay(overlay_name): empty_overlay = app._dataset.empty_overlay() try: app._dataset.persist_overlay(overlay_name, empty_overlay) except IOError: abort(409) return "", 201
[ 37811, 7391, 329, 2491, 262, 288, 2655, 303, 4382, 526, 15931, 198, 198, 11748, 28686, 198, 198, 6738, 42903, 1330, 357, 198, 220, 220, 220, 46947, 11, 198, 220, 220, 220, 33918, 1958, 11, 198, 220, 220, 220, 3758, 62, 7753, 11, 198...
2.313084
428
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ util regex tool refs: http://www.symantec.com/connect/articles/detection-sql-injection-and-cross-site-scripting-attacks """ import re INJECTION_REGEX = re.compile( r"(%27)|(\')|(\-\-)|(%23)|(#)|" # Regex for detection of SQL meta-characters r"\w*((%27)|(\'))\s+((%6F)|o|(%4F))((%72)|r|(%52))\s*|" # Modified regex for detection of SQL meta-characters eg: ' or 1 = 1' detect word 'or', r"((%3D)|(=))[^\n]*((%27)|(\')|(\-\-)|(%3B)|(;))" # Regex for typical SQL Injection attack eg: '= 1 --' r"((%27)|(\'))union|" # Regex for detecting SQL Injection with the UNION keyword r"((%27)|(\'))select|" # Regex for detecting SQL Injection with the UNION keyword r"((%27)|(\'))insert|" # Regex for detecting SQL Injection with the UNION keyword r"((%27)|(\'))update|" # Regex for detecting SQL Injection with the UNION keyword r"((%27)|(\'))drop", # Regex for detecting SQL Injection with the UNION keyword re.IGNORECASE ) CSS_ATTACK_REGREX = re.compile(r"((%3C)|<)((%2F)|/)*[a-z0-9%]+((%3E)|>)", re.IGNORECASE) CSS_IMG_SRC_ATTACK_REGEX = re.compile( r"((%3C)|<)((%69)|i|(%49))((%6D)|m|(%4D))((%67)|g|(%47))[^\n]+((%3E)|>)", re.IGNORECASE ) CSS_PARANOID_ATTACK_REGEX = re.compile("((%3C)|<)[^\n]+((%3E)|>)", re.IGNORECASE)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 628, 198, 37811, 198, 22602, 40364, 2891, 198, 5420, 82, 25, 198, 4023, 1378, 2503, 13, 37047, 415, 721, 13, 785, ...
2.190083
605
#!/usr/bin/env python REGISTERS = { 'IOCFG2': 0x00, 'IOCFG1': 0x01, 'IOCFG0': 0x02, 'FIFOTHR': 0x03, 'SYNC1': 0x04, 'SYNC0': 0x05, 'PKTLEN': 0x06, 'PKTCTRL1': 0x07, 'PKTCTRL0': 0x08, 'ADDR': 0x09, 'CHANNR': 0x0A, 'FSCTRL1': 0x0B, 'FSCTRL0': 0x0C, 'FREQ2': 0x0D, 'FREQ1': 0x0E, 'FREQ0': 0x0F, 'MDMCFG4': 0x10, 'MDMCFG3': 0x11, 'MDMCFG2': 0x12, 'MDMCFG1': 0x13, 'MDMCFG0': 0x14, 'DEVIATN': 0x15, 'MCSM2': 0x16, 'MCSM1': 0x17, 'MCSM0': 0x18, 'FOCCFG': 0x19, 'BSCFG': 0x1A, 'AGCCTRL2': 0x1B, 'AGCCTRL1': 0x1C, 'AGCCTRL0': 0x1D, 'WOREVT1': 0x1E, 'WOREVT0': 0x1F, 'WORCTRL': 0x20, 'FREND1': 0x21, 'FREND0': 0x22, 'FSCAL3': 0x23, 'FSCAL2': 0x24, 'FSCAL1': 0x25, 'FSCAL0': 0x26, 'RCCTRL1': 0x27, 'RCCTRL0': 0x28, 'FSTEST': 0x29, 'PTEST': 0x2A, 'AGCTEST': 0x2B, 'TEST2': 0x2C, 'TEST1': 0x2D, 'TEST0': 0x2E, 'PATABLE': 0x3E, } if __name__ == '__main__': import sys import re with open('eeprom', 'r+b') as fh: fh.seek(20) for line in sys.stdin: if re.match('^\s*#', line): continue m = re.match('(?P<reg>\w+)\s+(?P<value>[0-9a-fA-F]+)', line) if not m: continue m = m.groupdict() fh.write(chr(REGISTERS[m['reg']])) fh.write(chr(int(m['value'], 16))) fh.write(b"\xff" * (512 - fh.tell()))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 31553, 8808, 4877, 796, 1391, 198, 220, 220, 220, 705, 40, 4503, 30386, 17, 10354, 657, 87, 405, 11, 198, 220, 220, 220, 705, 40, 4503, 30386, 16, 10354, 657, 87, 486, 11, 198...
1.513944
1,004
''' @func:to store useful links module @create:2021.10.20 '''
[ 7061, 6, 198, 31, 20786, 25, 1462, 3650, 4465, 6117, 8265, 198, 31, 17953, 25, 1238, 2481, 13, 940, 13, 1238, 198, 7061, 6 ]
2.541667
24