content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import pytest # External imports import numpy as np from gpmap import GenotypePhenotypeMap # Module to test import epistasis from epistasis.models.classifiers import * THRESHOLD = 0.2
[ 11748, 12972, 9288, 198, 198, 2, 34579, 17944, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 308, 4426, 499, 1330, 5215, 8690, 47, 831, 8690, 13912, 198, 198, 2, 19937, 284, 1332, 198, 11748, 34795, 17765, 198, 6738, 34795, 17765, 13, ...
3.224138
58
from django.contrib import admin from .models import Notification admin.site.register(Notification, NotificationAdmin)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 42808, 628, 198, 198, 28482, 13, 15654, 13, 30238, 7, 3673, 2649, 11, 42808, 46787, 8, 198 ]
4.066667
30
import bz2 import time import urllib.request import io from typing import List, Tuple from credo_cf import load_json_from_stream, progress_and_process_image, group_by_device_id, group_by_resolution, too_often, near_hot_pixel2, \ too_bright from credo_cf import xor_preprocess from credo_cf.commons.utils import get_and_add WORKING_SET = 'http://mars.iti.pk.edu.pl/~nkg/credo/working_set.json.bz2' time_profile = {} if __name__ == '__main__': main()
[ 11748, 275, 89, 17, 198, 11748, 640, 198, 11748, 2956, 297, 571, 13, 25927, 198, 11748, 33245, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 198, 198, 6738, 2600, 78, 62, 12993, 1330, 3440, 62, 17752, 62, 6738, 62, 5532, 11, 4371, 6...
2.61236
178
from apptweak.plateform import *
[ 6738, 598, 83, 38695, 13, 6816, 687, 1330, 1635, 198 ]
3.3
10
print('---------- Opening Files for Reading ----------') f = open('./files/reading_file_example.txt') print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='cp936'> print('\t---------- read() ----------') # read(): read the whole text as string. If we want to limit the number of characters we read, # we can limit it by passing int value to the methods. f = open('./files/reading_file_example.txt') txt = f.read() print(type(txt)) # <class 'str'> print(txt) # Hello,Python! f.close() f = open('./files/reading_file_example.txt') txt = f.read(5) print(type(txt)) # <class 'str'> print(txt) # Hello f.close() print('\t---------- readline(): read only the first line ----------') f = open('./files/reading_file_example.txt') line = f.readline() print(type(line)) # <class 'str'> print(line) # Hello,Python! f.close() print('\t---------- readlines(): read all the text line by line and returns a list of lines ----------') f = open('./files/reading_file_example.txt') lines = f.readlines() print(type(lines)) # <class 'list'> print(lines) # ['Hello,Python!'] f.close() print('\t---------- splitlines() ----------') f = open('./files/reading_file_example.txt') lines = f.read().splitlines() print(type(lines)) # <class 'list'> print(lines) # ['Hello,Python!'] f.close() print('\t---------- Another way to close a file ----------') with open('./files/reading_file_example.txt') as f: lines = f.read().splitlines() print(type(lines)) # <class 'list'> print(lines) # ['Hello,Python!'] print('---------- Opening Files for Writing and Updating ----------') # To write to an existing file, we must add a mode as parameter to the open() function: # "a" - append - will append to the end of the file, if the file does not exist it raise FileNotFoundError. # "w" - write - will overwrite any existing content, if the file does not exist it creates. with open('./files/writing_file_example.txt', 'a') as f: f.write('Hello,Python!') with open('./files/writing_file_example.txt', 'w') as f: f.write('Hello,Java!') print('---------- Deleting Files ----------') import os if os.path.exists('./files/writing_file_example.txt'): os.remove('./files/writing_file_example.txt') else: os.remove('The file does not exist!') print('---------- File Types ----------') print('\t---------- File with json Extension ----------') # dictionary person_dct = { "name": "Zhang San", "country": "China", "city": "Hangzhou", "skills": ["Java", "C#", "Python"] } # JSON: A string form a dictionary person_json = "{'name': 'Zhang San', 'country': 'China', 'city': 'Hangzhou', 'skills': ['Java', 'C#', 'Python']}" # we use three quotes and make it multiple line to make it more readable person_json = '''{ "name":"Zhang San", "country":"China", "city":"Hangzhou", "skills":["Java", "C#","Python"] }''' print('\t---------- Changing JSON to Dictionary ----------') import json person_json = '''{ "name":"Zhang San", "country":"China", "city":"Hangzhou", "skills":["Java", "C#","Python"] }''' person_dct = json.loads(person_json) print(person_dct) print(person_dct['name']) print('\t---------- Changing Dictionary to JSON ----------') person_dct = { "name": "Zhang San", "country": "China", "city": "Hangzhou", "skills": ["Java", "C#", "Python"] } person_json = json.dumps(person_dct, indent=4) # indent could be 2, 4, 8. It beautifies the json print(type(person_json)) # <class 'str'> print(person_json) print('\t---------- Saving as JSON File ----------') person_dct = { "name": "Zhang San", "country": "China", "city": "Hangzhou", "skills": ["Java", "C#", "Python"] } with open('./files/json_example.json', 'w', encoding='utf-8') as f: json.dump(person_dct, f, ensure_ascii=False, indent=4) print('\t---------- File with csv Extension ----------') import csv # with open('./files/csv_example.csv') as f:
[ 4798, 10786, 35937, 25522, 13283, 329, 11725, 24200, 438, 11537, 198, 69, 796, 1280, 7, 4458, 14, 16624, 14, 25782, 62, 7753, 62, 20688, 13, 14116, 11537, 198, 4798, 7, 69, 8, 220, 1303, 1279, 62, 952, 13, 8206, 40, 3913, 430, 2848,...
2.82724
1,395
#!/usr/bin/env python import os from glob import glob import json import pandas import datetime import sys here = os.path.dirname(os.path.abspath(__file__)) folder = os.path.basename(here) latest = '%s/latest' % here year = datetime.datetime.today().year output_data = os.path.join(here, 'data-latest.tsv') output_year = os.path.join(here, 'data-%s.tsv' % year) # Function read zip into memory # Don't continue if we don't have latest folder if not os.path.exists(latest): print('%s does not have parsed data.' % folder) sys.exit(0) # Don't continue if we don't have results.json results_json = os.path.join(latest, 'records.json') if not os.path.exists(results_json): print('%s does not have results.json' % folder) sys.exit(1) with open(results_json, 'r') as filey: results = json.loads(filey.read()) columns = ['charge_code', 'price', 'description', 'hospital_id', 'filename', 'charge_type'] df = pandas.DataFrame(columns=columns) for result in results: filename = os.path.join(latest, result['filename']) if not os.path.exists(filename): print('%s is not found in latest folder.' % filename) continue if os.stat(filename).st_size == 0: print('%s is empty, skipping.' % filename) continue contents = None if filename.endswith('txt'): # ['DESCRIPTION', 'Unnamed: 1', 'PRICE'] contents = pandas.read_csv(filename) contents = contents.dropna(how='all') print("Parsing %s" % filename) print(contents.head()) # Update by row for row in contents.iterrows(): idx = df.shape[0] + 1 price = row[1]['PRICE'].replace('$','').replace(',','').strip() entry = [None, # charge code price, # price row[1]["DESCRIPTION"], # description result['hospital_id'], # hospital_id result['filename'], 'standard'] # filename df.loc[idx,:] = entry # Remove empty rows df = df.dropna(how='all') # Save data! print(df.shape) df.to_csv(output_data, sep='\t', index=False) df.to_csv(output_year, sep='\t', index=False)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 6738, 15095, 1330, 15095, 198, 11748, 33918, 198, 11748, 19798, 292, 198, 11748, 4818, 8079, 198, 11748, 25064, 198, 198, 1456, 796, 28686, 13, 6978, 13, 15908, 3...
2.164673
1,087
# -*- coding: utf-8 -*- """ Created on Mon Jan 10 07:20:39 2022 @author: maout """ import numpy as np from scipy.spatial.distance import cdist import torch #from score_function_estimators import my_cdist from typing import Union from torch.autograd import grad #%% select available device #%% #%% numpy versions of kernels functions def Knp(x,y,l,multil=False): if multil: res = np.ones((x.shape[0],y.shape[0])) for ii in range(len(l)): tempi = np.zeros((x[:,ii].size, y[:,ii].size )) ##puts into tempi the cdist result tempi = cdist(x[:,ii].reshape(-1,1), y[:,ii].reshape(-1,1),metric='sqeuclidean') res = np.multiply(res,np.exp(-tempi/(2*l[ii]*l[ii]))) return res else: tempi = np.zeros((x.shape[0], y.shape[0] )) tempi = cdist(x, y,'sqeuclidean') #this sets into the array tempi the cdist result return np.exp(-0.5*tempi/(l*l)) def grdx_K_all(x,y,l,multil=False): #gradient with respect to the 1st argument - only which_dim N,dim = x.shape M,_ = y.shape diffs = x[:,None]-y redifs = np.zeros((1*N,M,dim)) for ii in range(dim): if multil: redifs[:,:,ii] = np.multiply(diffs[:,:,ii],Knp(x,y,l,True))/(l[ii]*l[ii]) else: redifs[:,:,ii] = np.multiply(diffs[:,:,ii],Knp(x,y,l))/(l*l) return redifs #%% DEVICE = set_device() dtype = torch.float dim = 2 N = 3 M = 4 X = torch.randn(N, dim, device=DEVICE) Z = torch.randn(M, dim, device=DEVICE) # common device agnostic way of writing code that can run on cpu OR gpu # that we provide for you in each of the tutorials #%% test kernel evaluation with single lengthscale lengthsc = 2 # pytorched K_instance = RBF(length_scale=lengthsc, multil=False, device=DEVICE) ##instance of kernel object - non-evaluated if DEVICE=='cpu': Ktorch = K_instance.Kernel(X, Z).detach().numpy() gradK_torch = K_instance.gradient_X(X, Z).detach().numpy() else: Ktorch = K_instance.Kernel(X, Z).cpu().detach().numpy() gradK_torch = K_instance.gradient_X(X, Z).cpu().detach().numpy() # numpyed if DEVICE=='cpu': K_numpy = Knp(X.detach().numpy(), Z.detach().numpy(),l=lengthsc, multil=False).astype(np.float32) grad_K_numpy = grdx_K_all(X.detach().numpy(), Z.detach().numpy(), l=lengthsc, multil=False).astype(np.float32) else: K_numpy = Knp(X.cpu().detach().numpy(), Z.cpu().detach().numpy(),l=lengthsc, multil=False).astype(np.float32) grad_K_numpy = grdx_K_all(X.cpu().detach().numpy(), Z.cpu().detach().numpy(), l=lengthsc, multil=False).astype(np.float32) np.testing.assert_allclose(Ktorch, K_numpy, rtol=1e-06) np.testing.assert_allclose(gradK_torch, grad_K_numpy, rtol=1e-06) #%% test kernel evaluation with multiple lengthscales lengthsc = np.array([1,2]) # pytorched if DEVICE=='cpu': K_instance2 = RBF(length_scale=lengthsc, multil=True, device=DEVICE) ##instance of kernel object - non-evaluated Ktorch = K_instance2.Kernel(X, Z).detach().numpy() gradK_torch = K_instance2.gradient_X(X, Z).detach().numpy() else: K_instance2 = RBF(length_scale=lengthsc, multil=True, device=DEVICE) ##instance of kernel object - non-evaluated Ktorch = K_instance2.Kernel(X, Z).cpu().detach().numpy() gradK_torch = K_instance2.gradient_X(X, Z).cpu().detach().numpy() # numpyed if DEVICE=='cpu': K_numpy = Knp(X.detach().numpy(), Z.detach().numpy(),l=lengthsc, multil=True).astype(np.float32) grad_K_numpy = grdx_K_all(X.detach().numpy(), Z.detach().numpy(), l=lengthsc, multil=True).astype(np.float32) else: K_numpy = Knp(X.cpu().detach().numpy(), Z.cpu().detach().numpy(),l=lengthsc, multil=True).astype(np.float32) grad_K_numpy = grdx_K_all(X.cpu().detach().numpy(), Z.cpu().detach().numpy(), l=lengthsc, multil=True).astype(np.float32) np.testing.assert_allclose(Ktorch, K_numpy, rtol=1e-06) np.testing.assert_allclose(gradK_torch, grad_K_numpy, rtol=1e-06)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2365, 838, 8753, 25, 1238, 25, 2670, 33160, 198, 198, 31, 9800, 25, 17266, 448, 198, 37811, 628, 198, 11748, 299, 32152, 355, 45941, 198, ...
2.147781
1,915
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import tensorflow as tf import tflearn from tflearn import variables as vs from tflearn import activations from tflearn import initializations from tflearn import losses from tflearn import utils componentInherit = { 'globalDroppath': False, 'localDroppath': False, 'localDroppathProb': .5, 'parentType': '', 'currentType': '' }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 3601, 62, 8818, 11, 4112, 62, 11748, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 11748, 256, 27919, 1501, 198, 673...
2.891026
156
from ..testcases import DustyTestCase from dusty.warnings import Warnings
[ 6738, 11485, 9288, 33964, 1330, 16240, 88, 14402, 20448, 198, 198, 6738, 36972, 13, 40539, 654, 1330, 39567, 654, 198 ]
3.75
20
from random import randint import re # Supported formats: # [A]dX[(L|H|K)n][.Y1[.Y2[...]]] # A - number of dice # X - number of sides of dice # . - operation: allowed are + - * x / # Ln/Hn/Kn - discard the Lowest n dice or Keep the Highest n dice. - will only apply the first of these, in order LHK # Y1,Y2,... - operand # warning: doesn't respect order of operations. So +5*3 will first add 5, then multiply by 3. # example: 4d6+3 rolls 4 dice with 6 faces each, afterwards adds 3. # Thanks to tara, maximum number of allowed dice/faces is 999. # Parse a single dice roll # Parse a whole expression. # # Format: dice1[+dice2[+dice3[...]]] # dice1, dice2, dice3, ...: Any valid dice format as written in the randomDice function. # # Returns: The total of all rolls as integer, None if there was no valid dice notation found
[ 6738, 4738, 1330, 43720, 600, 201, 198, 11748, 302, 201, 198, 201, 198, 2, 36848, 17519, 25, 201, 198, 2, 685, 32, 60, 67, 55, 58, 7, 43, 91, 39, 91, 42, 8, 77, 7131, 13, 56, 16, 58, 13, 56, 17, 58, 986, 11907, 60, 201, 19...
2.900685
292
import os from sentiment_discovery.reparameterization import remove_weight_norm from sentiment_discovery.model import make_model def configure_model(parser): """add cmdline args for configuring models""" parser.add_argument('-load_model', default='', help="""a specific checkpoint file to load from experiment's model directory""") parser.add_argument('-should_test', action='store_true', help='whether to train or evaluate a model') parser.add_argument('-model_dir', default='model', help='directory where models are saved to/loaded from') parser.add_argument('-rnn_type', default='mlstm', help='mlstm, lstm or gru') parser.add_argument('-layers', type=int, default=1, help='Number of layers in the rnn') parser.add_argument('-rnn_size', type=int, default=4096, help='Size of hidden states') parser.add_argument('-embed_size', type=int, default=64, help='Size of embeddings') parser.add_argument('-weight_norm', action='store_true', help='whether to use weight normalization for training NNs') parser.add_argument('-lstm_only', action='store_true', help='if `-weight_norm` is applied to the model, apply it to the lstm parmeters only') parser.add_argument('-dropout', type=float, default=0.1, help='Dropout probability.') return ModuleConfig(parser)
[ 11748, 28686, 201, 198, 201, 198, 6738, 15598, 62, 67, 40821, 13, 260, 17143, 2357, 1634, 1330, 4781, 62, 6551, 62, 27237, 201, 198, 6738, 15598, 62, 67, 40821, 13, 19849, 1330, 787, 62, 19849, 201, 198, 201, 198, 4299, 17425, 62, 1...
2.822547
479
"""Tests for the ConsoleEnvironment and Console helper.""" from j5.backends.console import Console def test_console_instantiation() -> None: """Test that we can create a console.""" console = Console("MockConsole") assert type(console) is Console assert console._descriptor == "MockConsole" def test_console_info() -> None: """Test that the console can output information.""" console = MockPrintConsole("TestBoard") console.info("Test the console info") def test_console_read() -> None: """Test that we can read from the console.""" console = MockInputConsole("TestBoard") assert str(console.read("Enter Test Input")) == str(reversed("Enter Test Input")) def test_console_read_none_type() -> None: """Test that we can read None from console, i.e any input.""" console = ConsoleNone("TestBoard") assert console.read("Enter test input", None) is None def test_console_read_bad_type() -> None: """Test that the console emits an error if it cannot cast to the desired type.""" console = MockConsoleWithState("TestConsole") assert console.read("I want an int", int) == 6 def test_console_handle_boolean_correctly() -> None: """Test that the console handles bools correctly.""" console = MockConsoleBoolean("TestConsole") for _ in MockConsoleBoolean.true_cases: val = console.read("I want an bool", bool, check_stdin=False) assert isinstance(val, bool) assert val for _ in MockConsoleBoolean.false_cases: val = console.read("I want an bool", bool, check_stdin=False) assert isinstance(val, bool) assert not val # Test if false inputs are skipped. val = console.read("I want an bool", bool, check_stdin=False) assert isinstance(val, bool) assert val assert console.is_finished
[ 37811, 51, 3558, 329, 262, 24371, 31441, 290, 24371, 31904, 526, 15931, 198, 198, 6738, 474, 20, 13, 1891, 2412, 13, 41947, 1330, 24371, 628, 198, 4299, 1332, 62, 41947, 62, 8625, 415, 3920, 3419, 4613, 6045, 25, 198, 220, 220, 220, ...
3.083612
598
from os import listdir, remove, makedirs from os.path import isfile, join, exists import shutil import joblib from termcolor import cprint import json from pathlib import Path _cache_path = None _log_actions = True def init(cache_path, log_actions=True): """ Initializes the cache. Keyword Arguments: - cache_path: directory where cached files are saved - log_actions: when true, all actions are logged """ global _cache_path, _log_actions _log_actions = log_actions _cache_path = cache_path try: if not exists(cache_path): makedirs(cache_path) except Exception as e: cprint(e, 'red') def write(filename, data): """ Pickles a file and writes it to the cache. Keyword Arguments: - filename: name of the file to write to - data: object to cache """ if _log_actions: cprint('Writing to cache: "{}"'.format(filename), 'green') joblib.dump(data, join(_cache_path, filename)) def write_plain(filename, data, add_extension=True): """ Simply writes the textual data to a file. """ if _log_actions: cprint('Writing to cache (plain): "{}"'.format(filename), 'green') if add_extension: filename += '.json' with open(join(_cache_path, filename), 'w') as f: f.write(data) def write_dict_json(filename, data, add_extension=True): """ Writes a dictionary to file using JSON format. """ if _log_actions: cprint('Writing to cache (json): "{}"'.format(filename), 'green') json_string = json.dumps(data, sort_keys=False, indent=4) if add_extension: filename += '.json' with open(join(_cache_path, filename), 'w') as f: f.write(json_string) def read(filename): """ Reads a file from the cache and unpickles it. Keyword Arguments: - filename: name of the file to read Returns: - data: unpickled object """ if _log_actions: cprint('Loading from cache: "{}"'.format(filename), 'green') return joblib.load(join(_cache_path, filename)) def read_multiple(filenames): """ Reads multiple file from the cache and unpickles them. Keyword Arguments: - filenames: names of the files to read Returns: - result: unpickled object - success_files: list of successful filenames - errors: filenames for which exceptions happened """ result = [] success_files = [] errors = [] for f in filenames: try: result.append(read(f)) success_files.append(f) except Exception as e: cprint(f'Loading {f} failed!', 'red') cprint(e, 'red') errors.append(f) return result, success_files, errors def read_plain(filename): """ Reads a file from the cache and unpickles it. Keyword Arguments: - filename: name of the file to read Returns: - data: unpickled object """ if _log_actions: cprint('Loading from cache: "{}"'.format(filename), 'green') return Path(join(_cache_path, filename)).read_text() def delete(filename): """ Removes all files from the cache that have names starting with filename. """ deleted = 0 errors = 0 for f in entries(): try: if f.startswith(filename): remove(join(_cache_path, f)) deleted += 1 except: cprint(f'Cannot remove from cache: {filename}', 'red') errors += 1 cprint(f'Removed from cache all files starting with {filename}', 'green') msg = f'Removed {deleted} files, {errors} errors' cprint(msg, 'yellow') return { 'type': 'success' if errors == 0 else 'error', 'msg': msg } def delete_all_clf_projs(): """ Deletes all classifier projections """ deleted = 0 errors = 0 for f in entries(): try: if '__clf_proj_' in f: remove(join(_cache_path, f)) deleted += 1 except: cprint(f'Cannot remove from cache: {f}', 'red') errors += 1 cprint(f'Removed from cache all classifier projections', 'green') msg = f'Removed {deleted} files, {errors} errors' cprint(msg, 'yellow') return { 'type': 'success' if errors == 0 else 'error', 'msg': msg } def clear(): """ Deletes the cache. """ cprint('Clearing cache', 'yellow') shutil.rmtree(_cache_path, ignore_errors=True) def entries(): """ Lists all files in the cache. Returns: - list of all file names in the cache directory """ return [f for f in listdir(_cache_path) if isfile(join(_cache_path, f))] def content(): """ Returns all .json files in the cache to allow showing what classifiers etc. have been trained so far. Returns: - a dictionary containing all files' contents """ cached_files = entries() json_files = [f for f in cached_files if f.endswith('_args.json')] datasets = [] classifiers = [] projections = [] classifier_projections = [] for f in json_files: try: filepath = join(_cache_path, f) contents = Path(filepath).read_text() json_dict = { 'file': f, 'args': json.loads(contents) } if '__proj_' in f: projections.append(json_dict) elif '__clf_proj_' in f: classifier_projections.append(json_dict) elif '__clf_' in f: # send scores for cached classifications score_file = f.replace('_args.json', '_scores.json') scores = Path(join(_cache_path, score_file)).read_text() json_dict['scores'] = json.loads(scores) classifiers.append(json_dict) elif f.startswith('data_'): datasets.append(json_dict) except Exception as e: cprint( f'Error: Some related files may be missing for file {f}, check if you copied files correctly or run you jobs again!', 'red') cprint(e, 'red') return { 'datasets': datasets, 'classifiers': classifiers, 'projections': projections, 'classifier_projections': classifier_projections }
[ 6738, 28686, 1330, 1351, 15908, 11, 4781, 11, 285, 4335, 17062, 198, 6738, 28686, 13, 6978, 1330, 318, 7753, 11, 4654, 11, 7160, 198, 11748, 4423, 346, 198, 11748, 1693, 8019, 198, 6738, 3381, 8043, 1330, 269, 4798, 198, 11748, 33918, ...
2.367126
2,683
import torch import os import numpy as np import random import pandas as pd from sklearn.model_selection import StratifiedKFold from data.tileimages import * from data.multitask import * import fastai from fastai.vision import *
[ 11748, 28034, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 29186, 1431, 42, 37, 727, 198, 6738, 1366, 13, 40927, 17566...
3.523077
65
if __name__ == '__main__': main()
[ 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.105263
19
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from ase.build import molecule from ase.lattice.cubic import SimpleCubic from graphdot.graph import Graph from graphdot.graph.adjacency import AtomicAdjacency adjacencies = [ AtomicAdjacency(shape='tent1', length_scale=1.0, zoom=1), AtomicAdjacency(shape='tent2', length_scale='vdw_radius', zoom=1), AtomicAdjacency( shape='gaussian', length_scale='covalent_radius_pyykko', zoom=1.5 ), AtomicAdjacency(shape='compactbell3,2'), ]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 12972, 9288, 198, 6738, 257, 325, 13, 11249, 1330, 27756, 198, 6738, 257, 325, 13, 75, 1078, 501, 13, 66, 549,...
2.563725
204
import string import scipy import PslgIo, ElementAwarePslg
[ 11748, 4731, 198, 11748, 629, 541, 88, 198, 11748, 350, 6649, 70, 40, 78, 11, 11703, 32, 1574, 47, 6649, 70 ]
2.761905
21
""" DIANNA: Deep Insight And Neural Network Analysis. Modern scientific challenges are often tackled with (Deep) Neural Networks (DNN). Despite their high predictive accuracy, DNNs lack inherent explainability. Many DNN users, especially scientists, do not harvest DNNs power because of lack of trust and understanding of their working. Meanwhile, the eXplainable AI (XAI) methods offer some post-hoc interpretability and insight into the DNN reasoning. This is done by quantifying the relevance of individual features (image pixels, words in text, etc.) with respect to the prediction. These "relevance heatmaps" indicate how the network has reached its decision directly in the input modality (images, text, speech etc.) of the data. There are many Open Source Software (OSS) implementations of these methods, alas, supporting a single DNN format and the libraries are known mostly by the AI experts. The DIANNA library supports the best XAI methods in the context of scientific usage providing their OSS implementation based on the ONNX standard and demonstrations on benchmark datasets. Representing visually the captured knowledge by the AI system can become a source of (scientific) insights. See https://github.com/dianna-ai/dianna """ import logging from onnx_tf.backend import prepare # To avoid Access Violation on Windows with SHAP from . import methods from . import utils logging.getLogger(__name__).addHandler(logging.NullHandler()) __author__ = "DIANNA Team" __email__ = "dianna-ai@esciencecenter.nl" __version__ = "0.2.1" def explain_image(model_or_function, input_data, method, labels=(1,), **kwargs): """ Explain an image (input_data) given a model and a chosen method. Args: model_or_function (callable or str): The function that runs the model to be explained _or_ the path to a ONNX model on disk. input_data (np.ndarray): Image data to be explained method (string): One of the supported methods: RISE, LIME or KernelSHAP labels (tuple): Labels to be explained Returns: One heatmap (2D array) per class. """ explainer = _get_explainer(method, kwargs) explain_image_kwargs = utils.get_kwargs_applicable_to_function(explainer.explain_image, kwargs) return explainer.explain_image(model_or_function, input_data, labels, **explain_image_kwargs) def explain_text(model_or_function, input_data, method, labels=(1,), **kwargs): """ Explain text (input_data) given a model and a chosen method. Args: model_or_function (callable or str): The function that runs the model to be explained _or_ the path to a ONNX model on disk. input_data (string): Text to be explained method (string): One of the supported methods: RISE or LIME labels (tuple): Labels to be explained Returns: List of (word, index of word in raw text, importance for target class) tuples. """ explainer = _get_explainer(method, kwargs) explain_text_kwargs = utils.get_kwargs_applicable_to_function(explainer.explain_text, kwargs) return explainer.explain_text(model_or_function, input_data, labels, **explain_text_kwargs)
[ 37811, 198, 35, 16868, 4535, 25, 10766, 39917, 843, 47986, 7311, 14691, 13, 198, 198, 31439, 5654, 6459, 389, 1690, 35457, 351, 357, 29744, 8, 47986, 27862, 357, 35, 6144, 737, 198, 8332, 511, 1029, 33344, 9922, 11, 360, 6144, 82, 309...
3.051595
1,066
try: import RPi.GPIO as GPIO except RuntimeError: print("Error importing RPi.GPIO! This is probably because you need " "superuser privileges. You can achieve this by using 'sudo' to run " "your script") gpios = [7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26, 29, 31, 32, 33, 35, 36, 37, 38, 40] header = Header() try: GPIO.setmode(GPIO.BOARD) for id in gpios: print('Initializing gpio ' + str(id)) GPIO.setup(id, GPIO.OUT, initial=GPIO.LOW) print('Initialized GPIOs') except: print('Could not set GPIO mode to BOARD.')
[ 28311, 25, 198, 220, 220, 220, 1330, 25812, 72, 13, 16960, 9399, 355, 50143, 198, 16341, 43160, 12331, 25, 198, 220, 220, 220, 3601, 7203, 12331, 33332, 25812, 72, 13, 16960, 9399, 0, 220, 770, 318, 2192, 780, 345, 761, 366, 198, 22...
2.374016
254
#!/usr/bin/env python import rospy # For all things ros with python # JointState is defined in sensor_msgs.msg # If you know a message but not where it is # call rosmsg info MSGNAME from the terminal from sensor_msgs.msg import JointState # This tutorial takes heavily from # http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber(python) # In this example we make a simple subscriber that listens for JointState # messages, and prints them. Uses a functional approach. def message_callback(msg): """This function is called on the message every time a message arrives.""" rospy.loginfo("Joint position received:"+str(msg.position)) def joint_listener(): """Blocking function that sets up node, subscription and waits for messages.""" # Start ros node rospy.init_node("joint_listener", anonymous=True) # Tell the central command we want to hear about /joint_states rospy.Subscriber("/joint_states", # Topic we subscribe to JointState, # message type that topic has message_callback) # function to call when message arrives rospy.spin() # If this script is run alone, not just imported: if __name__ == "__main__": joint_listener() # Ensure that the python script is executable by running: # chmod +x joint_subscriber.py # Call this script by running: # rosrun joint_subscriber joint_subscriber.py
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 686, 2777, 88, 1303, 1114, 477, 1243, 686, 82, 351, 21015, 198, 198, 2, 16798, 9012, 318, 5447, 287, 12694, 62, 907, 14542, 13, 19662, 198, 2, 1002, 345, 760, 257, 3275, 475, ...
3.093126
451
#!/usr/bin/env python # Aran Sena 2018 # # Code example only, provided without guarantees # # Example for how to get both cameras streaming together # #### import rospy from intera_core_msgs.srv._IOComponentCommandSrv import IOComponentCommandSrv from intera_core_msgs.msg._IOComponentCommand import IOComponentCommand if __name__ == '__main__': rospy.init_node('camera_command_client') camera_command_client(camera='head_camera', status=True) camera_command_client(camera='right_hand_camera', status=True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 220, 198, 2, 943, 272, 2311, 64, 2864, 220, 198, 2, 220, 198, 2, 6127, 1672, 691, 11, 2810, 1231, 19026, 220, 198, 2, 220, 198, 2, 17934, 329, 703, 284, 651, 1111, 9073, 11305, 1978, ...
2.77551
196
# -*- coding: utf-8 -*- """ Created on Sun May 2 2021 @name: CityData CensusTract Download Application @author: Jack Kirby Cook """ import sys import os.path import warnings import logging import regex as re MAIN_DIR = os.path.dirname(os.path.realpath(__file__)) MODULE_DIR = os.path.abspath(os.path.join(MAIN_DIR, os.pardir)) ROOT_DIR = os.path.abspath(os.path.join(MODULE_DIR, os.pardir)) RESOURCE_DIR = os.path.join(ROOT_DIR, "resources") SAVE_DIR = os.path.join(ROOT_DIR, "save") DRIVER_FILE = os.path.join(RESOURCE_DIR, "chromedriver.exe") REPOSITORY_DIR = os.path.join(SAVE_DIR, "citydata") QUEUE_FILE = os.path.join(RESOURCE_DIR, "zipcodes.zip.csv") REPORT_FILE = os.path.join(SAVE_DIR, "citydata", "censustracts.csv") if ROOT_DIR not in sys.path: sys.path.append(ROOT_DIR) from utilities.iostream import InputParser from utilities.dataframes import dataframe_parser from webscraping.webtimers import WebDelayer from webscraping.webdrivers import WebDriver from webscraping.weburl import WebURL from webscraping.webpages import WebBrowserPage from webscraping.webpages import BadRequestError from webscraping.webpages import WebContents from webscraping.webloaders import WebLoader from webscraping.webquerys import WebQuery, WebDatasets from webscraping.webqueues import WebScheduler from webscraping.webdownloaders import WebDownloader, CacheMixin, AttemptsMixin from webscraping.webdata import WebClickable, WebText, WebInput, WebSelect from webscraping.webactions import WebScroll, WebMoveTo, WebMoveToClick, WebMoveToClickSelect, WebMoveToClickFillSend __version__ = "1.0.0" __author__ = "Jack Kirby Cook" __all__ = ["CityData_WebDelayer", "CityData_WebDownloader", "CityData_WebScheduler"] __copyright__ = "Copyright 2021, Jack Kirby Cook" __license__ = "" LOGGER = logging.getLogger(__name__) warnings.filterwarnings("ignore") DATASETS = {"violentcrime": "Crime - Violent crime index", "propertycrime": "Crime - Property crime index", "airpollution": "Air pollution - Air Quality Index (AQI)"} GEOGRAPHYS = ("state", "county", "tract", "blockgroup") dataset_select_xpath = r"//select[contains(@id, 'selmapOSM')]" zipcode_click_xpath = r"//div[@id='searchOSM']//div[contains(@id, 'sboxOuter')]//b" zipcode_input_xpath = r"//div[@id='searchOSM']//div[contains(@id, 'sboxOuter')]//input[contains(@id, 's2id')]" zipcode_xpath = r"//div[@id='searchOSM']//div[contains(@id, 'sboxOuter')]//span[@class='select2-chosen']" geography_xpath = r"//div[@id='legendBOX']/div[@id='mapOSM_legend']" canvas_xpath = r"//div[@id='mapOSM']//canvas" fullscreen_xpath = r"//div[@id='mapOSM']//a[@title='Full Screen']" zoomin_xpath = r"//div[@id='mapOSM']//a[@title='Zoom in']" zoomout_xpath = r"//div[@id='mapOSM']//a[@title='Zoom out']" dataset_select_webloader = WebLoader(xpath=dataset_select_xpath) zipcode_click_webloader = WebLoader(xpath=zipcode_click_xpath) zipcode_input_webloader = WebLoader(xpath=zipcode_input_xpath) zipcode_webloader = WebLoader(xpath=zipcode_xpath) geography_webloader = WebLoader(xpath=geography_xpath) canvas_webloader = WebLoader(xpath=canvas_xpath) fullscreen_webloader = WebLoader(xpath=fullscreen_xpath) zoomin_webloader = WebLoader(xpath=zoomin_xpath) zoomout_webloader = WebLoader(xpath=zoomout_xpath) zipcode_parser = lambda x: re.findall("^\d{5}(?=\, [A-Z]{2}$)", str(x).strip())[0] state_parser = lambda x: re.findall("(?<=^\d{5}\, )[A-Z]{2}$", str(x).strip())[0] geography_parser = lambda x: {"block groups": "blockgroup", "tracts": "tract", "counties": "county", "states": "state"}[re.findall("(?<=Displaying\: )[a-z ]+(?=\.)", str(x).strip())[0]] geography_pattern = "(?P<blockgroup>(?<=Census Block Group )[\.0-9]+)|(?P<tract>(?<=Census Tract )[\.0-9]+)|(?P<state>(?<=\, )[A-Z]{2}|(?<=\()[A-Z]{2}(?=\)))|(?P<county>[a-zA-Z ]+ County(?=\, ))" def main(*args, **kwargs): delayer = CityData_WebDelayer("constant", wait=3) scheduler = CityData_WebScheduler(*args, file=REPORT_FILE, **kwargs) downloader = CityData_WebDownloader(*args, repository=REPOSITORY_DIR, **kwargs) queue = scheduler(*args, **kwargs) downloader(*args, queue=queue, delayer=delayer, **kwargs) LOGGER.info(str(downloader)) for results in downloader.results: LOGGER.info(str(results)) if not bool(downloader): raise downloader.error if __name__ == "__main__": sys.argv += ["state=CA", "city=Bakersfield", "dataset=violentcrime", "geography=tract"] logging.basicConfig(level="INFO", format="[%(levelname)s, %(threadName)s]: %(message)s") inputparser = InputParser(proxys={"assign": "=", "space": "_"}, parsers={}, default=str) inputparser(*sys.argv[1:]) main(*inputparser.arguments, **inputparser.parameters)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3825, 1737, 362, 33448, 198, 31, 3672, 25, 220, 220, 2254, 6601, 20962, 51, 974, 10472, 15678, 198, 31, 9800, 25, 3619, 23965, 8261, 198, 198, ...
2.525172
1,887
import math def estimate_lowest_divisor(method, divisor, populations, seats): """ Calculates the estimated lowest possible divisor. :param method: The method used. :type method: str :param divisor: A working divisor in calculating fair shares. :type divisor: float :param populations: The populations for each state respectively. :type populations: [float] :param seats: The amount of seats to apportion. :type seats: int :return: An estimation of the lowest possible divisor. """ # The number of states to apportion to. states = sum(populations) # Initialize lists for fair shares and quotas. quotas = [0] * states fair_shares = [0] * states # Keep track of the previous divisor calculated and lowest of them. prev_divisor = 0 lowest_divisor = 0 # Estimator to use in predicting divisors. estimator = 1000000000 counter = 0 while counter < 1000: for i, population in enumerate(populations): if divisor is None or population is None: return None quotas[i] = population / divisor if method.upper() == "ADAM": fair_shares[i] = math.ceil(quotas[i]) elif method.upper() == "WEBSTER": fair_shares[i] = round(quotas[i]) elif method.upper() == "JEFFERSON": fair_shares[i] = math.floor(quotas[i]) if sum(fair_shares) != seats: estimator = estimator / 10 prev_divisor = divisor divisor = lowest_divisor - estimator else: lowest_divisor = divisor divisor = prev_divisor - estimator if lowest_divisor == divisor: break counter += 1 return math.ceil(lowest_divisor * 1000) / 1000 def estimate_highest_divisor(method, divisor, populations, seats): """ Calculates the estimated highest possible divisor. :param method: The method used. :type method: str :param divisor: A working divisor in calculating fair shares. :type divisor: float :param populations: The populations for each state respectively. :type populations: [float] :param seats: The amount of seats to apportion. :type seats: int :return: An estimation of the lowest possible divisor. """ # The number of states to apportion to. states = sum(populations) # Initialize lists for fair shares and quotas. quotas = [0] * states fair_shares = [0] * states # Keep track of the previous divisor calculated and highest of them. prev_divisor = 0 highest_divisor = 0 # Estimator to use in predicting divisors. estimator = 1000000000 counter = 0 while counter < 1000: for i, population in enumerate(populations): if divisor is None or population is None: return None quotas[i] = population / divisor if method.upper() == "ADAM": fair_shares[i] = math.ceil(quotas[i]) elif method.upper() == "WEBSTER": fair_shares[i] = round(quotas[i]) elif method.upper() == "JEFFERSON": fair_shares[i] = math.floor(quotas[i]) if sum(fair_shares) != seats: estimator = estimator / 10 prev_divisor = divisor divisor = highest_divisor + estimator else: highest_divisor = divisor divisor = prev_divisor - estimator if highest_divisor == divisor: break counter += 1 return math.ceil(highest_divisor * 1000) / 1000
[ 11748, 10688, 628, 198, 4299, 8636, 62, 9319, 395, 62, 7146, 271, 273, 7, 24396, 11, 2659, 271, 273, 11, 9684, 11, 8632, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 27131, 689, 262, 6108, 9016, 1744, 2659, 271, 273, 13, 6...
2.349452
1,551
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np # import pylatex from pylatex import Document, Section, Tabular, Math, Axis, Subsection import pandas as pd import sys import os main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 299, 32152, 355, 45941, 198, 2, 1330, 279, 2645, 378, 87, 198, 6738, 279, 2645, 378, 87, 1330, 16854, 11,...
2.733333
75
import os.path as osp import yaml import torch.nn as nn from torch import hub __all__ = ['get_vggish', 'vggish_category_metadata'] model_urls = { 'vggish': "https://github.com/w-hc/vggish/releases/download/v0.1/vggish_orig.pth", 'vggish_with_classifier': "https://github.com/w-hc/vggish/releases/download/v0.1/vggish_with_classifier.pth" } def get_vggish(with_classifier=False, pretrained=True): if with_classifier: model = VGGishClassify() url = model_urls['vggish_with_classifier'] else: model = VGGish() url = model_urls['vggish'] if pretrained: state_dict = hub.load_state_dict_from_url(url, progress=True) model.load_state_dict(state_dict) return model
[ 11748, 28686, 13, 6978, 355, 267, 2777, 198, 11748, 331, 43695, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 1330, 12575, 198, 198, 834, 439, 834, 796, 37250, 1136, 62, 85, 1130, 680, 3256, 705, 85, 1130, 680, 62, 2...
2.24924
329
import os import warnings import pandas import sqlite3 import logging from typing import List from dask import delayed, dataframe from contextlib import closing from cuchemcommon.utils.singleton import Singleton from cuchemcommon.context import Context warnings.filterwarnings("ignore", message=r"deprecated", category=FutureWarning) logger = logging.getLogger(__name__) BATCH_SIZE = 100000 ADDITIONAL_FEILD = ['canonical_smiles', 'transformed_smiles'] IMP_PROPS = [ 'alogp', 'aromatic_rings', 'full_mwt', 'psa', 'rtb'] IMP_PROPS_TYPE = [pandas.Series([], dtype='float64'), pandas.Series([], dtype='int64'), pandas.Series([], dtype='float64'), pandas.Series([], dtype='float64'), pandas.Series([], dtype='int64')] ADDITIONAL_FEILD_TYPE = [pandas.Series([], dtype='object'), pandas.Series([], dtype='object')] SQL_MOLECULAR_PROP = """ SELECT md.molregno as molregno, md.chembl_id, cp.*, cs.* FROM compound_properties cp, compound_structures cs, molecule_dictionary md WHERE cp.molregno = md.molregno AND md.molregno = cs.molregno AND md.molregno in (%s) """ # DEPRECATED. Please add code to DAO classes.
[ 11748, 28686, 198, 11748, 14601, 198, 11748, 19798, 292, 198, 11748, 44161, 578, 18, 198, 11748, 18931, 198, 198, 6738, 19720, 1330, 7343, 198, 6738, 288, 2093, 1330, 11038, 11, 1366, 14535, 198, 198, 6738, 4732, 8019, 1330, 9605, 198, ...
2.38447
528
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 628 ]
2.891892
37
from PyObjCTools.TestSupport import * import objc import Foundation if hasattr(Foundation, 'NSMachPort'): if __name__ == '__main__': main( )
[ 6738, 9485, 49201, 4177, 10141, 13, 14402, 15514, 1330, 1635, 198, 11748, 26181, 66, 198, 11748, 5693, 198, 198, 361, 468, 35226, 7, 21077, 341, 11, 705, 8035, 49999, 13924, 6, 2599, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12...
2.826923
52
#!/usr/bin/env python2 """Command line utility for querying the Logitech Harmony.""" import argparse import logging import json import sys import auth import client as harmony_client LOGGER = logging.getLogger(__name__) def login_to_logitech(args): """Logs in to the Logitech service. Args: args: argparse arguments needed to login. Returns: Session token that can be used to log in to the Harmony device. """ token = auth.login(args.email, args.password) if not token: sys.exit('Could not get token from Logitech server.') session_token = auth.swap_auth_token( args.harmony_ip, args.harmony_port, token) if not session_token: sys.exit('Could not swap login token for session token.') return session_token def pprint(obj): """Pretty JSON dump of an object.""" print(json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))) def get_client(args): """Connect to the Harmony and return a Client instance.""" token = login_to_logitech(args) client = harmony_client.create_and_connect_client( args.harmony_ip, args.harmony_port, token) return client def show_config(args): """Connects to the Harmony and prints its configuration.""" client = get_client(args) pprint(client.get_config()) client.disconnect(send_close=True) return 0 def show_current_activity(args): """Connects to the Harmony and prints the current activity block from the config.""" client = get_client(args) config = client.get_config() current_activity_id = client.get_current_activity() activity = [x for x in config['activity'] if int(x['id']) == current_activity_id][0] pprint(activity) client.disconnect(send_close=True) return 0 def sync(args): """Connects to the Harmony and syncs it. """ client = get_client(args) client.sync() client.disconnect(send_close=True) return 0 def turn_off(args): """Sends a 'turn off' command to the harmony, which is the activity '-1'.""" args.activity = '-1' start_activity(args) def start_activity(args): """Connects to the Harmony and switches to a different activity, specified as an id or label.""" client = get_client(args) config = client.get_config() print args activity_off = False activity_numeric = False activity_id = None activity_label = None try: activity_off = float(args.activity) == -1 activity_id = int(float(args.activity)) activity_numeric = True except ValueError: activity_off = args.activity.lower() == 'turn off' activity_label = str(args.activity) if activity_off: activity = [{'id': -1, 'label': 'Turn Off'}] else: activity = [x for x in config['activity'] if (activity_numeric and int(x['id']) == activity_id) or x['label'].lower() == activity_label ] if not activity: LOGGER.error('could not find activity: ' + args.activity) client.disconnect(send_close=True) return 1 activity = activity[0] client.start_activity(int(activity['id'])) LOGGER.info("started activity: '%s' of id: '%s'" % (activity['label'], activity['id'])) client.disconnect(send_close=True) return 0 def send_command(args): """Connects to the Harmony and send a simple command.""" client = get_client(args) config = client.get_config() device = args.device if args.device_id is None else args.device_id device_numeric = None try: device_numeric = int(float(device)) except ValueError: pass device_config = [x for x in config['device'] if device.lower() == x['label'].lower() or ((device_numeric is not None) and device_numeric == int(x['id']))] if not device_config: LOGGER.error('could not find device: ' + device) client.disconnect(send_close=True) return 1 device_id = int(device_config[0]['id']) client.send_command(device_id, args.command) client.disconnect(send_close=True) return 0 def main(): """Main method for the script.""" parser = argparse.ArgumentParser( description='pyharmony utility script', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Required flags go here. required_flags = parser.add_argument_group('required arguments') required_flags.add_argument('--email', required=True, help=( 'Logitech username in the form of an email address.')) required_flags.add_argument( '--password', required=True, help='Logitech password.') required_flags.add_argument( '--harmony_ip', required=True, help='IP Address of the Harmony device.') # Flags with defaults go here. parser.add_argument('--harmony_port', default=5222, type=int, help=( 'Network port that the Harmony is listening on.')) loglevels = dict((logging.getLevelName(level), level) for level in [10, 20, 30, 40, 50]) parser.add_argument('--loglevel', default='INFO', choices=loglevels.keys(), help='Logging level to print to the console.') subparsers = parser.add_subparsers() show_config_parser = subparsers.add_parser( 'show_config', help='Print the Harmony device configuration.') show_config_parser.set_defaults(func=show_config) show_activity_parser = subparsers.add_parser( 'show_current_activity', help='Print the current activity config.') show_activity_parser.set_defaults(func=show_current_activity) start_activity_parser = subparsers.add_parser( 'start_activity', help='Switch to a different activity.') start_activity_parser.add_argument( 'activity', help='Activity to switch to, id or label.') start_activity_parser.set_defaults(func=start_activity) sync_parser = subparsers.add_parser( 'sync', help='Sync the harmony.') sync_parser.set_defaults(func=sync) turn_off_parser = subparsers.add_parser( 'turn_off', help='Send a turn off command to the harmony.') turn_off_parser.set_defaults(func=turn_off) command_parser = subparsers.add_parser( 'send_command', help='Send a simple command.') command_parser.add_argument('--command', help='IR Command to send to the device.', required=True) device_arg_group = command_parser.add_mutually_exclusive_group(required=True) device_arg_group.add_argument('--device_id', help='Specify the device id to which we will send the command.') device_arg_group.add_argument('--device', help='Specify the device id or label to which we will send the command.') command_parser.set_defaults(func=send_command) args = parser.parse_args() logging.basicConfig( level=loglevels[args.loglevel], format='%(levelname)s:\t%(name)s\t%(message)s') sys.exit(args.func(args)) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 198, 37811, 21575, 1627, 10361, 329, 42517, 1112, 262, 5972, 45396, 35088, 526, 15931, 198, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 33918, 198, 11748, 25064, 198, 198, ...
2.614679
2,725
# # MIT No Attribution # # 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. # # 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. # from __future__ import print_function from botocore.exceptions import ClientError import os import sys import logging import traceback import boto3 import json LOG_LEVELS = {'CRITICAL': 50, 'ERROR': 40, 'WARNING': 30, 'INFO': 20, 'DEBUG': 10} stackname = 'WebServersForResiliencyTesting' AWS_REGION = 'us-east-2' ARCH_TO_AMI_NAME_PATTERN = { # Architecture: (pattern, owner) "PV64": ("amzn2-ami-pv*.x86_64-ebs", "amazon"), "HVM64": ("amzn2-ami-hvm-*-x86_64-gp2", "amazon"), "HVMG2": ("amzn2-ami-graphics-hvm-*x86_64-ebs*", "679593333241") } if __name__ == "__main__": logger = init_logging() event = { 'vpc': { 'stackname': 'ResiliencyVPC', 'status': 'CREATE_COMPLETE' }, 'rds': { 'stackname': 'MySQLforResiliencyTesting', 'status': 'CREATE_COMPLETE' }, 'log_level': 'DEBUG', 'region_name': 'ap-northeast-2', 'cfn_region': 'us-east-2', 'cfn_bucket': 'aws-well-architected-labs-ohio', 'folder': 'Reliability/', 'boot_bucket': 'aws-well-architected-labs-ohio', 'boot_prefix': 'Reliability/', 'boot_object': 'bootstrapARC327.sh', 'websiteimage': 'https://s3.us-east-2.amazonaws.com/arc327-well-architected-for-reliability/Cirque_of_the_Towers.jpg', 'workshop': 'LondonSummit' } os.environ['log_level'] = os.environ.get('log_level', event['log_level']) logger = setup_local_logging(logger, os.environ['log_level']) # Add default level of debug for local execution lambda_handler(event, 0)
[ 2, 198, 2, 17168, 1400, 45336, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 198, 2, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, 12340, 284, 1730, 287, ...
2.549139
987
alpha = "abcdefghijklmnopqrstuvwxyz" n = int(raw_input()) for i in xrange(n): word = raw_input() aux_word = "" first_part = "" second_part = "" for j in xrange(len(word)-1, -1, -1): if(word[j].lower() in alpha): aux_word += chr(ord(word[j]) + 3) else: aux_word += word[j] middle = (len(word)/2) first_part = aux_word[0:middle] for k in xrange((len(aux_word)/2), len(aux_word)): second_part += chr(ord(aux_word[k]) -1) print first_part + second_part
[ 26591, 796, 366, 39305, 4299, 456, 2926, 41582, 10295, 404, 80, 81, 301, 14795, 86, 5431, 89, 1, 198, 198, 77, 796, 493, 7, 1831, 62, 15414, 28955, 198, 198, 1640, 1312, 287, 2124, 9521, 7, 77, 2599, 198, 197, 4775, 796, 8246, 62,...
2.137168
226
import numpy as np # For file manipulation and locating import os # For the progress bar from tqdm import tqdm # To create a deep copy of the data import copy # To load the pre-processed and split data from pre_process import load_data as ld # For normalization of the samples from sklearn.preprocessing import normalize # We define some constant that we reuse PROCESSED_DIR = "data/processed/" def save_data(data, file_path, name): """ Saves the data given the name and the file path Parameters ---------- data: numpy matrix Data matrix with features file_path: str File path where the file should be saved name: str Specific name of the given file """ np.save(file_path + "{}.npy".format(name),data) def preprocess(X, Y, size = 100000,lower_bound=0, upper_bound = 7368,samples = 10, same_class=0.4, different = 0.5, penalty = 10, same_class_penalty=1): """ Preprocessed the dataset It creates two lists X,Y It randomly chooses a sample from the input list and then that sample is repeated in total * samples time For each repeated sample it finds a portion of images corresponding to different labels, images corresponding to the same class and a certain portion of identities based on the class membership a penalty is applied or not Parameters ---------- X: numpy array of features Numpy array of features from which the pairs are created Y: numpy array Numpy array of corresponding labels Returns ------- X_selected: numpy array Numpy array of the first input in the pairs Y_selected: numpy array Numpy array of the second input in the pairs values: numpy array Artificially determined distances """ X = normalize(X, axis=1) N,F = X.shape X_selected = [] Y_selected = [] values = [] C = int(samples*same_class) D = int(samples*different) selected_i = [] for i in tqdm(range(int(size/samples))): # Randomly select a sample but do not repeat it with respect ot previous samples random_i = np.random.randint(lower_bound,upper_bound) while random_i in selected_i: random_i = np.random.randint(lower_bound,upper_bound) selected_i.append(random_i) C_counter = 0 D_counter = 0 offset = 0 # Add samples which correspond to different label than the original image selected_j = [] while D_counter<D: random_j = np.random.randint(lower_bound,upper_bound) while random_j in selected_j: random_j = np.random.randint(lower_bound,upper_bound) if Y[random_i] != Y[random_j]: D_counter+=1 offset+=1 X_selected.append(copy.deepcopy(X[random_i])) Y_selected.append(copy.deepcopy(X[random_j])) values.append(penalty) selected_j.append(random_j) # Add samples which correspond to the same class selected_j = [] while C_counter<C: low = 0 high = N if random_i-10>lower_bound: low = random_i-10 if random_i+10<upper_bound: high = random_i+10 random_j = np.random.randint(lower_bound,upper_bound) while random_j in selected_j: random_j = np.random.randint(lower_bound,upper_bound) if Y[random_i] == Y[random_j] and random_i!=random_j: C_counter+=1 offset +=1 X_selected.append(copy.deepcopy(X[random_i])) Y_selected.append(copy.deepcopy(X[random_j])) values.append(same_class_penalty) selected_j.append(random_j) # Fill in the rest with identities while offset < samples: X_selected.append(copy.deepcopy(X[random_i])) Y_selected.append(copy.deepcopy(X[random_i])) offset+=1 values.append(0) indeces = np.random.choice(size, size=size, replace=False) X_selected = np.array(X_selected) Y_selected = np.array(Y_selected) values = np.array(values) return [X_selected[indeces], Y_selected[indeces], values[indeces]] def load_data(retrain=False): """ Load the cached data or call preprocess() to generate new data Parameters ---------- None Returns ------- all_data: list * All the data split into lists of [features, labels] """ all_data = ld(False) training_data = all_data[0] Y = training_data[1] X = training_data[0] if retrain is True: print("Generating new data...") X_train, Y_train, values_train = preprocess(X,Y, 40000, 0, 6379,samples = 10, same_class=0.4, different = 0.5, penalty = 1,same_class_penalty=0) X_validation, Y_validation, values_validation = preprocess(X,Y, 7500, 6380,samples = 10, same_class=0.2, different = 0.7, penalty = 1, same_class_penalty=0) save_data(X_train,PROCESSED_DIR,"training_nn_X") save_data(Y_train,PROCESSED_DIR,"training_nn_Y") save_data(values_train,PROCESSED_DIR,"training_nn_values") save_data(X_validation,PROCESSED_DIR,"validation_nn_X") save_data(Y_validation,PROCESSED_DIR,"validation_nn_Y") save_data(values_validation,PROCESSED_DIR,"validation_nn_values") return [X_train, Y_train, values_train, X_validation, Y_validation, values_validation] else: print("Loading data...") data = [] data.append(np.load(PROCESSED_DIR + "training_nn_X.npy")) data.append(np.load(PROCESSED_DIR + "training_nn_Y.npy")) data.append(np.load(PROCESSED_DIR + "training_nn_values.npy")) data.append(np.load(PROCESSED_DIR + "validation_nn_X.npy")) data.append(np.load(PROCESSED_DIR + "validation_nn_Y.npy")) data.append(np.load(PROCESSED_DIR + "validation_nn_values.npy")) return data if __name__ == '__main__': load_data(retrain=True)
[ 11748, 299, 32152, 355, 45941, 198, 2, 1114, 2393, 17512, 290, 42139, 198, 11748, 28686, 198, 2, 1114, 262, 4371, 2318, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 2, 1675, 2251, 257, 2769, 4866, 286, 262, 1366, 198, 11748, ...
2.315729
2,632
import pandas as pd import time from image_matcher import read_image, bjorn_score if __name__ == "__main__": main()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 640, 198, 6738, 2939, 62, 6759, 2044, 1330, 1100, 62, 9060, 11, 275, 73, 1211, 62, 26675, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388,...
2.733333
45
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import serialization
[ 6738, 45898, 13, 71, 1031, 6759, 13, 1891, 2412, 1330, 4277, 62, 1891, 437, 201, 198, 6738, 45898, 13, 71, 1031, 6759, 13, 19795, 20288, 1330, 46621, 201, 198, 6738, 45898, 13, 71, 1031, 6759, 13, 19795, 20288, 13, 4107, 3020, 19482, ...
3.575758
66
# Question 7 # Find out the number of CPUs using import os print("Number of CPUs using:", os.cpu_count()) # Alternative, """ import multiprocessing print("Number of CPUs using:", multiprocessing.cpu_count()) """
[ 2, 18233, 767, 198, 2, 9938, 503, 262, 1271, 286, 32340, 1262, 198, 198, 11748, 28686, 220, 198, 198, 4798, 7203, 15057, 286, 32340, 1262, 25, 1600, 28686, 13, 36166, 62, 9127, 28955, 220, 198, 198, 2, 27182, 11, 198, 37811, 1330, 1...
3.253731
67
import re import datetime import lxml.html import requests from billy.utils.fulltext import text_after_line_numbers from .bills import IABillScraper from .legislators import IALegislatorScraper from .events import IAEventScraper from .votes import IAVoteScraper # Silencing unverified HTTPS request warnings. requests.packages.urllib3.disable_warnings() settings = dict(SCRAPELIB_TIMEOUT=240) metadata = dict( name = 'Iowa', abbreviation = 'ia', capitol_timezone = 'America/Chicago', legislature_name = 'Iowa General Assembly', legislature_url = 'https://www.legis.iowa.gov/', chambers = { 'upper': {'name': 'Senate', 'title': 'Senator'}, 'lower': {'name': 'House', 'title': 'Representative'}, }, terms = [ { 'name': '2011-2012', 'start_year': 2011, 'end_year': 2012, 'sessions': ['2011-2012'], }, { 'name': '2013-2014', 'start_year': 2013, 'end_year': 2014, 'sessions': ['2013-2014'], }, { 'name': '2015-2016', 'start_year': 2015, 'end_year': 2016, 'sessions': ['2015-2016'], }, ], session_details = { '2011-2012': { 'display_name': '2011-2012 Regular Session', '_scraped_name': 'General Assembly: 84', 'number': '84', 'start_date': datetime.date(2011, 1, 10), 'end_date': datetime.date(2013, 1, 13), }, '2013-2014': { 'display_name': '2013-2014 Regular Session', '_scraped_name': 'General Assembly: 85', 'number': '85', }, '2015-2016': { 'display_name': '2015-2016 Regular Session', '_scraped_name': 'General Assembly: 86', 'number': '86', }, }, feature_flags = ['events', 'influenceexplorer'], _ignored_scraped_sessions = [ 'Legislative Assembly: 86', 'General Assembly: 83', 'General Assembly: 82', 'General Assembly: 81', 'General Assembly: 80', 'General Assembly: 79', 'General Assembly: 79', 'General Assembly: 78', 'General Assembly: 78', 'General Assembly: 77', 'General Assembly: 77', 'General Assembly: 76', ] )
[ 11748, 302, 198, 11748, 4818, 8079, 198, 11748, 300, 19875, 13, 6494, 198, 11748, 7007, 198, 6738, 2855, 88, 13, 26791, 13, 12853, 5239, 1330, 2420, 62, 8499, 62, 1370, 62, 77, 17024, 198, 6738, 764, 65, 2171, 1330, 314, 6242, 359, ...
2.119964
1,117
from openpyxl import Workbook from openpyxl.utils import get_column_letter from openpyxl.writer.excel import save_virtual_workbook
[ 6738, 1280, 9078, 87, 75, 1330, 5521, 2070, 198, 6738, 1280, 9078, 87, 75, 13, 26791, 1330, 651, 62, 28665, 62, 9291, 198, 6738, 1280, 9078, 87, 75, 13, 16002, 13, 1069, 5276, 1330, 3613, 62, 32844, 62, 1818, 2070, 628 ]
3.219512
41
import vipy from vipy.flow import Flow import numpy as np if __name__ == "__main__": test_flow()
[ 11748, 410, 541, 88, 198, 6738, 410, 541, 88, 13, 11125, 1330, 27782, 198, 11748, 299, 32152, 355, 45941, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1332, 62, 11125, 3419, 198, 220, 220, 2...
2.369565
46
from typing import Optional from fastapi import FastAPI app = FastAPI() import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) LED=21 BUZZER=23 GPIO.setup(LED,GPIO.OUT)
[ 6738, 19720, 1330, 32233, 198, 6738, 3049, 15042, 1330, 12549, 17614, 198, 1324, 796, 12549, 17614, 3419, 628, 198, 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 198, 11748, 640, 220, 198, 16960, 9399, 13, 2617, 14171, 7, 16960, 9399, ...
2.5
82
# -*- coding: utf-8 -*- """bootstrap_py.tests.test_package.""" import unittest import os import shutil import tempfile from glob import glob from datetime import datetime from mock import patch from bootstrap_py import package from bootstrap_py.tests.stub import stub_request_metadata # pylint: disable=too-few-public-methods
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 18769, 26418, 62, 9078, 13, 41989, 13, 9288, 62, 26495, 526, 15931, 198, 11748, 555, 715, 395, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 20218, 7753, ...
3.173077
104
# Generated by Django 3.2.6 on 2021-08-30 13:48 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 21, 319, 33448, 12, 2919, 12, 1270, 1511, 25, 2780, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
from pathlib import Path import numpy as np import tables # Use snapshot from aug08 before the last update that broke things. with tables.open_file('cmds_aug08.h5') as h5: cmds = h5.root.data[:] print(cmds.dtype) # [('idx', '<u2'), ('date', 'S21'), ('type', 'S12'), ('tlmsid', 'S10'), # ('scs', 'u1'), ('step', '<u2'), ('timeline_id', '<u4'), ('vcdu', '<i4')] new_dtype = [('idx', '<i4'), ('date', 'S21'), ('type', 'S12'), ('tlmsid', 'S10'), ('scs', 'u1'), ('step', '<u2'), ('timeline_id', '<u4'), ('vcdu', '<i4')] new_cmds = cmds.astype(new_dtype) for name in cmds.dtype.names: assert np.all(cmds[name] == new_cmds[name]) cmds_h5 = Path('cmds.h5') if cmds_h5.exists(): cmds_h5.unlink() with tables.open_file('cmds.h5', mode='a') as h5: h5.create_table(h5.root, 'data', new_cmds, "cmds", expectedrows=2e6) # Make sure the new file is really the same except the dtype with tables.open_file('cmds.h5') as h5: new_cmds = h5.root.data[:] for name in cmds.dtype.names: assert np.all(cmds[name] == new_cmds[name]) if name != 'idx': assert cmds[name].dtype == new_cmds[name].dtype assert new_cmds['idx'].dtype.str == '<i4'
[ 6738, 3108, 8019, 1330, 10644, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 8893, 198, 198, 2, 5765, 27479, 422, 16339, 2919, 878, 262, 938, 4296, 326, 6265, 1243, 13, 198, 4480, 8893, 13, 9654, 62, 7753, 10786, 28758, 82, 62, 7493...
2.188082
537
""" 18. Faa um programa que pea o tamanho de um arquivo para download (em MB) e a velocidade de um link de Internet (em Mbps), calcule e informe o tempo aproximado de download do arquivo usando este link (em minutos). """ mb_arquivo = float(input('Informe o tamanho de um arquivo para download (em MB): ')) mbps_link = float(input('Informe a velocidade do link de Internet (em Mbps): ')) velocidade_segundos = mb_arquivo / mbps_link velocidade_minutos = velocidade_segundos / 60 print('O tempo aproximado para download do arquivo de %d minuto(s).' %velocidade_minutos)
[ 37811, 198, 1507, 13, 376, 7252, 23781, 1430, 64, 8358, 613, 64, 267, 256, 10546, 8873, 390, 23781, 610, 421, 23593, 31215, 4321, 357, 368, 10771, 8, 304, 220, 198, 64, 11555, 420, 312, 671, 390, 23781, 2792, 390, 4455, 357, 368, 41...
2.654378
217
import argparse import pickle import os import json from sklearn.metrics import confusion_matrix from utils.data_reader import embed_data_sets_with_glove, embed_data_set_given_vocab, prediction_2_label from utils.text_processing import vocab_map from common.util.log_helper import LogHelper from deep_models.MatchPyramid import MatchPyramid if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--mode', help='\'train\' or \'test\'', required=True) parser.add_argument('--train', help='/path/to/training/set') parser.add_argument('--valid', help='/path/to/validation/set') parser.add_argument('--test', help='/path/to/test/set') parser.add_argument('--model', help='/path/to/model/file', required=True) parser.add_argument( '--save-data', help='/path/to/save/data', default="data/rte/train/") parser.add_argument('--load-data', help='/path/to/load/data/file') parser.add_argument('--db', help='/path/to/data/base', required=True) parser.add_argument( '--max-sent', type=int, help='Maximal number of sentences per claim', default=5) parser.add_argument('--embed', help='/path/to/embedding') parser.add_argument( '--save-result', help='/path/to/save/result', default="data/rte/result/") args = parser.parse_args() LogHelper.setup() logger = LogHelper.get_logger(args.mode) if args.mode == 'train': assert args.train is not None or args.load_data is not None, "--train training set or --load-data should be provided in train mode" assert args.embed is not None, "--embed should be provided in train mode" # training mode if args.load_data: # load pre-processed training data with open(args.load_data, "rb") as file: param = pickle.load(file) else: # process training JSONL file paths = [args.train, args.valid] dataset_list, vocab, embeddings, b_max_sent_num, b_max_sent_size = embed_data_sets_with_glove( paths, args.db, args.embed, threshold_b_sent_num=args.max_sent) vocab = vocab_map(vocab) param = { 'dataset_list': dataset_list, 'vocab': vocab, 'embeddings': embeddings, 'max_sent_size': b_max_sent_size, 'max_sent': args.max_sent } # save processed training data os.makedirs(args.save_data, exist_ok=True) train_data_path = os.path.join( args.save_data, "train.{}.s{}.p".format("matchpyramid", str(args.max_sent))) with open(train_data_path, "wb") as file: pickle.dump(param, file, protocol=pickle.HIGHEST_PROTOCOL) pyramid = _instantiate_model(param) pyramid.fit(param['dataset_list'][0]['data'], param['dataset_list'][0]['label'], param['dataset_list'][1]['data'], param['dataset_list'][1]['label']) pyramid.save(args.model) else: # testing mode assert args.load_data is not None, "--load_data should be provided in test mode" assert args.test is not None, "--test test set should be provided in test mode" with open(args.load_data, "rb") as file: param = pickle.load(file) pyramid = _instantiate_model(param) pyramid.restore_model(args.model) data_set = embed_data_set_given_vocab(args.test, args.db, param['vocab'], threshold_b_sent_num=param['max_sent'], threshold_b_sent_size=param['max_sent_size'], threshold_h_sent_size=param['max_sent_size']) os.makedirs(args.save_result, exist_ok=True) test_result_path = os.path.join( args.save_result, "predicted.pyramid.s{}.jsonl".format(param['max_sent'])) with open(test_result_path, "w") as result_file: predictions = pyramid.predict(data_set['data']) for i, prediction in enumerate(predictions): data = {'predicted': prediction_2_label(prediction)} if 'label' in data_set: data['label'] = prediction_2_label(data_set['label'][i]) result_file.write(json.dumps(data) + "\n") if 'label' in data_set: logger.info("Confusion Matrix:") logger.info(confusion_matrix(data_set['label'], predictions))
[ 11748, 1822, 29572, 198, 11748, 2298, 293, 198, 11748, 28686, 198, 11748, 33918, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 10802, 62, 6759, 8609, 198, 6738, 3384, 4487, 13, 7890, 62, 46862, 1330, 11525, 62, 7890, 62, 28709, 62, 448...
2.248346
1,965
import shutil, os, random from pydub import AudioSegment try: os.mkdir('noise') except: shutil.rmtree('noise') os.mkdir('noise') listdir=os.listdir() mp3files=list() for i in range(len(listdir)): if listdir[i][-4:]=='.mp3': mp3files.append(listdir[i]) random.shuffle(mp3files) for i in range(len(mp3files)): extract_noise(mp3files[i],300) if i == 100: break os.chdir('noise') listdir=os.listdir() for i in range(len(listdir)): if listdir[i][-4:]=='.mp3': os.system('play %s'%(listdir[i])) remove=input('should remove? type y to remove') if remove=='y': os.remove(listdir[i])
[ 11748, 4423, 346, 11, 28686, 11, 4738, 198, 6738, 279, 5173, 549, 1330, 13491, 41030, 434, 198, 28311, 25, 198, 197, 418, 13, 28015, 15908, 10786, 3919, 786, 11537, 198, 16341, 25, 198, 197, 1477, 22602, 13, 81, 16762, 631, 10786, 391...
2.245283
265
from django.conf.urls import url from Apps.Apiv2.views import GetARResourcesView, GetARExperienceDetailView from Apps.Apiv2.views import GetTagListView,GetARExperienceRecommendList,GetARExperiencePublicListView,GetARExperiencesView from Apps.Apiv2.views import GetARexperienceByTagsListView app_name = 'Apps.Users' urlpatterns = [ url(r'^getarresources$', GetARResourcesView.as_view(), name='getarresources'), url(r'^getarexperience$', GetARExperienceDetailView.as_view(), name='getarexperience'), url(r'^getarexperiencelist$', GetARExperiencesView.as_view(), name='getarexperience'), url(r'^gettaglist$', GetTagListView.as_view(), name='getshowcasetags'), url(r'^getrecommendslist$', GetARExperienceRecommendList.as_view(), name='getshowcaserecommends'), url(r'^getarexperiencepubliclist$', GetARExperiencePublicListView.as_view(), name='getarexperiencepubliclist'), url(r'^getarexperiencebytagslist$', GetARexperienceByTagsListView.as_view(), name='getarexperiencebytagslist'), # api/v2/ ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 27710, 13, 25189, 452, 17, 13, 33571, 1330, 3497, 1503, 33236, 7680, 11, 3497, 1503, 44901, 11242, 603, 7680, 198, 6738, 27710, 13, 25189, 452, 17, 13, 33571, 1330, ...
2.845304
362
"""Construit le site Explorer et comprendre l'Univers, incluant les diapositives et le livre. Le logiciel Pandoc est utilis pour obtenir des prsentations dans diffrents formats. On peut construire tous les fichiers html avec la commande $ python make.py """ import subprocess import os import sys # Dossiers de prsentation DIAPOS_DIRS = [os.path.join('diapos', d) for d in os.listdir('diapos') if d != 'reveal.js'] def run(call_str): """Excute la chane de caractre sur la ligne de commande.""" try: subprocess.check_call(call_str.split()) print("complet!") except subprocess.CalledProcessError as e: print(call_str, end='... ') print("erreur, la compilation a chou") def revealjs(in_fname, out_fname): """Cre une prsentation avec la librairie javascript Reveal.js.""" call_str = "pandoc -t revealjs " \ "-V revealjs-url=../reveal.js -s " \ "--slide-level=1 " \ "--mathjax {} -o {}".format(in_fname, out_fname) run(call_str) def diapos(): """Construits les fichiers HTML des diapositives.""" cwd = os.getcwd() for folder in DIAPOS_DIRS: try: os.chdir(folder) except (FileNotFoundError, NotADirectoryError): os.chdir(cwd) continue # Dterminer le nom du fichier source. for fname in os.listdir(): if fname.endswith(".md"): break else: os.chdir(cwd) continue in_fname = fname out_fname = "{}.html".format(os.path.splitext(os.path.basename(fname))[0]) print("{}: ".format(folder), end='') revealjs(in_fname, out_fname) os.chdir(cwd) def livre(): """Construit les fichiers HTML du livre.""" for fname in os.listdir('livre'): if not fname.endswith('.md'): continue in_fname = os.path.join('livre', fname) out_fname = os.path.join( 'livre', '{}.html'.format(os.path.splitext(os.path.basename(fname))[0])) call_str = 'pandoc -s -c ../www/style.css --mathjax ' \ '--template www/book-template.html ' \ '--include-after-body www/sidebar.html ' \ '--include-after-body www/footer.html ' \ '{} -o {}'.format(in_fname, out_fname) print("{}: ".format(in_fname), end='') run(call_str) if __name__ == '__main__': if len(sys.argv) != 1: print("usage: python make.py\n") exit() diapos() livre()
[ 37811, 34184, 4872, 443, 2524, 19142, 2123, 552, 10920, 260, 300, 6, 3118, 1191, 11, 13358, 84, 415, 10287, 2566, 499, 7434, 1083, 198, 316, 443, 17717, 260, 13, 220, 1004, 9156, 8207, 16492, 420, 1556, 7736, 271, 12797, 909, 1452, 34...
2.026625
1,277
import os from pathlib import PurePath try: from geosnap import io except: pass path = os.getcwd() try: io.store_ltdb(sample=PurePath(path, 'ltdb_sample.zip'), fullcount=PurePath(path, 'ltdb_full.zip')) io.store_ncdb(PurePath(path, "ncdb.csv")) except: pass
[ 11748, 28686, 198, 6738, 3108, 8019, 1330, 17129, 15235, 198, 28311, 25, 198, 220, 220, 220, 422, 4903, 418, 77, 499, 1330, 33245, 198, 16341, 25, 198, 220, 220, 220, 1208, 198, 198, 6978, 796, 28686, 13, 1136, 66, 16993, 3419, 198, ...
2.352941
119
import numpy as np import torch from tqdm import tqdm import matplotlib as mpl # https://gist.github.com/thriveth/8560036 color_cycle = ['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3', '#999999', '#e41a1c', '#dede00'] labels_dict = {"ic": "IC", "prior": "Prior", "ars-1": r"$\mathrm{ARS}_{M=1}$", "ars-2": r"$\mathrm{ARS}_{M=2}$", "ars-5": r"$\mathrm{ARS}_{M=5}$", "ars-10": r"$\mathrm{ARS}_{M=10}$", "ars-20": r"$\mathrm{ARS}_{M=20}$", "ars-50": r"$\mathrm{ARS}_{M=50}$", "biased": "Biased", "gt": "Groundtruth", "is": "IS", "collapsed": "Collapsed"} color_dict = {'gt': color_cycle[0], 'prior': color_cycle[5], 'ic': color_cycle[2], 'biased': color_cycle[3], 'ars-1': color_cycle[4], 'ars-2': color_cycle[1], 'ars-5': color_cycle[7], 'ars-10': color_cycle[6], 'ars-100': color_cycle[8], 'ars-50': color_cycle[8], 'is': color_cycle[8], 'ars-20': "C1", "collapsed": color_cycle[7]} ######################################## ## matplotlib style and configs ## ######################################## def set_size(width, fraction=1, subplots=(1, 1)): # https://jwalton.info/Embed-Publication-Matplotlib-Latex/ """ Set aesthetic figure dimensions to avoid scaling in latex. Parameters ---------- width: float Width in pts fraction: float Fraction of the width which you wish the figure to occupy subplots: array-like, optional The number of rows and columns of subplots. Returns ------- fig_dim: tuple Dimensions of figure in inches """ if width == 'thesis': width_pt = 426.79135 elif width == 'beamer': width_pt = 307.28987 elif width == 'pnas': width_pt = 246.09686 elif width == 'aistats22': width_pt = 487.8225 else: width_pt = width # Width of figure fig_width_pt = width_pt * fraction # Convert from pt to inches inches_per_pt = 1 / 72.27 # Golden ratio to set aesthetic figure height golden_ratio = (5**.5 - 1) / 2 # Figure width in inches fig_width_in = fig_width_pt * inches_per_pt # Figure height in inches fig_height_in = fig_width_in * golden_ratio * (subplots[0] / subplots[1]) return (fig_width_in, fig_height_in) ######################################## ## Loading from disk ## ######################################## def load_log_weights(log_weights_root, iw_mode): """Loads the log_weights from the disk. It assumes a file structure of <log_weights_root>/<iw_mode>/*.npy of mulyiple npy files. This function loads all the weights in a single numpy array, concatenating all npy files. Finally, it caches the result in a file stored at <log_weights_root>/<iw_mode>.npy In the further calls, it reuses the cached file. Args: log_weights_root (str or pathlib.Path) iw_mode (str) Returns: np.ndarray: log importance weights """ agg_weights_file = log_weights_root / f"{iw_mode}.npy" agg_weights_dir = log_weights_root / iw_mode assert agg_weights_dir.exists() or agg_weights_file.exists() if not agg_weights_file.exists(): log_weights = np.concatenate( [np.load(weight_file) for weight_file in agg_weights_dir.glob("*.npy")]) np.save(agg_weights_file, log_weights) else: log_weights = np.load(agg_weights_file) print(f"{log_weights_root} / {iw_mode} has {len(log_weights):,} traces") return log_weights ######################################## ## Estimators and metrics ## ######################################## def _compute_estimator_helper(log_weights, dx, estimator_func, **kwargs): """A helper function for computing the plotting data. It generates the x-values and y-values of the plot. x-values is an increasing sequence of integers, with incremens of dx and ending with N. y-values is a TxK tensor where T is the number of trials and K is the size of x-values. The j-th column of y-values is the estimator applied to the log_weights up to the corresponding x-value. Args: log_weights (torch.FloatTensor of shape TxN): All the log importance weights of a particular experiment. dx (int): different between points of evaluating the estimator. estimator_func (function): the estimator function that operates on a tensor of shape Txn where n <= N. **kwargs: optional additional arguments to the estimator function """ (T, N) = log_weights.shape xvals = _get_xvals(end=N, dx=dx) yvals_all = [estimator_func(log_weights[:, :x], **kwargs) for x in xvals] yvals_all = torch.stack(yvals_all, dim=1) return xvals, yvals_all def _get_xvals(end, dx): """Returns a integer numpy array of x-values incrementing by "dx" and ending with "end". Args: end (int) dx (int) """ arange = np.arange(0, end-1+dx, dx, dtype=int) xvals = arange[1:] return xvals def _log_evidence_func(arr): """Returns an estimate of the log evidence from a set of log importance wegiths in arr. arr has shape TxN where T is the number of trials and N is the number of samples for estimation. Args: arr (torch.FloatTensor of shape TxN): log importance weights Returns: A tensor of shape (T,) representing the estimates for each set of sampels. """ T, N = arr.shape log_evidence = torch.logsumexp(arr, dim=1) - np.log(N) return log_evidence def _ess_func(arr): """Effective sample size (ESS)""" a = torch.logsumexp(arr, dim=1) * 2 b = torch.logsumexp(2 * arr, dim=1) return torch.exp(a - b) def _ess_inf_func(arr): """ESS-infinity (Q_n)""" a = torch.max(arr, dim=1)[0] b = torch.logsumexp(arr, dim=1) return torch.exp(a - b) def get_ness(log_weights, dx): """Normalized ESS (ESS / N)""" xvals, yvals = get_ess(log_weights, dx=dx) return xvals, yvals / xvals ######################################## ## Plotting functions ## ######################################## def _lineplot_helper(*, name, func, ax, log_weights_dict, iw_mode_list, dx, bias=None, **kwargs): """A helper function for making the line functions of the paper. Args: name (string): Metric name. Used for logging only. func (function): The metric computation function. Should be a function that takes in log_weights and dx and returns x-values and y-values. Any additional arguments in kwargs will be passed to this function. ax (matplotlib.axes): A matrplotlib ax object in which the plot should be drawn. log_weights_dict (dict): A dictionary of the form {iw_mode: log_imprtance_weights as a TxN tensor} iw_mode_list (list): An ordered list of iw modes specifying the order of drawing the lines. dx (int): The distance between consequent x-values. bias (float, optional): If not None, shifts all the line's y-values according to it. Defaults to None. """ for iw_mode in tqdm(iw_mode_list, desc=name): if iw_mode not in log_weights_dict: print(f"Skipping {iw_mode}.") continue log_weights = torch.tensor(log_weights_dict[iw_mode]) label = labels_dict[iw_mode] color = color_dict[iw_mode] xs, ys_all = func(log_weights, dx=dx) means = ys_all.mean(dim=0) stds = ys_all.std(dim=0) if bias is not None: means -= bias ax.plot(xs, means, color=color, label=label) ax.fill_between(xs, means - stds, means + stds, color=color, alpha=0.2) print(f"> ({name}) {iw_mode, means[-1].item(), stds[-1].item()}")
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 628, 198, 2, 3740, 1378, 70, 396, 13, 12567, 13, 785, 14, 400, 11590, 400, 14, 23, 3980...
2.358997
3,429
from __future__ import division from __future__ import print_function import numpy as np import cv2 import matplotlib.pyplot as plt from .face import compute_bbox_size end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype=np.int32) - 1 def plot_kpt(image, kpt): ''' Draw 68 key points Args: image: the input image kpt: (68, 3). ''' image = image.copy() kpt = np.round(kpt).astype(np.int32) for i in range(kpt.shape[0]): st = kpt[i, :2] image = cv2.circle(image, (st[0], st[1]), 1, (0, 0, 255), 2) if i in end_list: continue ed = kpt[i + 1, :2] image = cv2.line(image, (st[0], st[1]), (ed[0], ed[1]), (255, 255, 255), 1) return image def plot_pose_box(image, Ps, pts68s, color=(40, 255, 0), line_width=2): ''' Draw a 3D box as annotation of pose. Ref:https://github.com/yinguobing/head-pose-estimation/blob/master/pose_estimator.py Args: image: the input image P: (3, 4). Affine Camera Matrix. kpt: (2, 68) or (3, 68) ''' image = image.copy() if not isinstance(pts68s, list): pts68s = [pts68s] if not isinstance(Ps, list): Ps = [Ps] for i in range(len(pts68s)): pts68 = pts68s[i] llength = compute_bbox_size(pts68) point_3d = build_camera_box(llength) P = Ps[i] # Map to 2d image points point_3d_homo = np.hstack((point_3d, np.ones([point_3d.shape[0], 1]))) # n x 4 point_2d = point_3d_homo.dot(P.T)[:, :2] point_2d[:, 1] = - point_2d[:, 1] point_2d[:, :2] = point_2d[:, :2] - np.mean(point_2d[:4, :2], 0) + np.mean(pts68[:2, :27], 1) point_2d = np.int32(point_2d.reshape(-1, 2)) # Draw all the lines cv2.polylines(image, [point_2d], True, color, line_width, cv2.LINE_AA) cv2.line(image, tuple(point_2d[1]), tuple( point_2d[6]), color, line_width, cv2.LINE_AA) cv2.line(image, tuple(point_2d[2]), tuple( point_2d[7]), color, line_width, cv2.LINE_AA) cv2.line(image, tuple(point_2d[3]), tuple( point_2d[8]), color, line_width, cv2.LINE_AA) return image def draw_landmarks(img, pts, style='fancy', wfp=None, show_flg=False, **kwargs): """Draw landmarks using matplotlib""" # height, width = img.shape[:2] # plt.figure(figsize=(12, height / width * 12)) plt.imshow(img[:, :, ::-1]) plt.subplots_adjust(left=0, right=1, top=1, bottom=0) plt.axis('off') if not type(pts) in [tuple, list]: pts = [pts] for i in range(len(pts)): if style == 'simple': plt.plot(pts[i][0, :], pts[i][1, :], 'o', markersize=4, color='g') elif style == 'fancy': alpha = 0.8 markersize = 4 lw = 1.5 color = kwargs.get('color', 'w') markeredgecolor = kwargs.get('markeredgecolor', 'black') nums = [0, 17, 22, 27, 31, 36, 42, 48, 60, 68] # close eyes and mouths plot_close = lambda i1, i2: plt.plot([pts[i][0, i1], pts[i][0, i2]], [pts[i][1, i1], pts[i][1, i2]], color=color, lw=lw, alpha=alpha - 0.1) plot_close(41, 36) plot_close(47, 42) plot_close(59, 48) plot_close(67, 60) for ind in range(len(nums) - 1): l, r = nums[ind], nums[ind + 1] plt.plot(pts[i][0, l:r], pts[i][1, l:r], color=color, lw=lw, alpha=alpha - 0.1) plt.plot(pts[i][0, l:r], pts[i][1, l:r], marker='o', linestyle='None', markersize=markersize, color=color, markeredgecolor=markeredgecolor, alpha=alpha) if wfp is not None: plt.savefig(wfp, dpi=200) print('Save visualization result to {}'.format(wfp)) if show_flg: plt.show()
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 764, 2...
1.89055
2,074
# calculate the curverture import numpy as np import matplotlib.pyplot as plt from predusion.tools import curvature radius = 2 n_point = 10 circle_curve = [[radius * np.sin(t), radius * np.cos(t)] for t in np.linspace(0, 2 * np.pi, n_point, endpoint=False)] circle_curve = np.array(circle_curve) #plt.figure() #plt.scatter(circle_curve[:, 0], circle_curve[:, 1]) #plt.show() ct, ct_mean = curvature(circle_curve) print(ct, ct_mean)
[ 2, 15284, 262, 1090, 1851, 495, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6738, 2747, 4241, 13, 31391, 1330, 46171, 1300, 628, 198, 42172, 796, 362, 198, 77, 62, 4122, ...
2.508571
175
import cocos.device import cocos.numerics as cn import numpy as np import pytest test_data = [np.array([[1, 2, 3], [4, 5, 6], [7, 8, 20]], dtype=np.int32), np.array([[0.2, 1.0, 0.5], [0.4, 0.5, 0.6], [0.7, 0.2, 0.25]], dtype=np.float32), np.array([[0.5, 2.3, 3.1], [4, 5.5, 6], [7 - 9j, 8 + 1j, 2 + 10j]], dtype=np.complex64)]
[ 11748, 8954, 418, 13, 25202, 198, 11748, 8954, 418, 13, 77, 6975, 873, 355, 269, 77, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 628, 198, 9288, 62, 7890, 796, 685, 37659, 13, 18747, 26933, 58, 16, 11, 362, 11, 513,...
1.604563
263
""" this is a very long docstring this is a very long docstring this is a very long docstring this is a very long docstring this is a very long docstring this is a very long docstring this is a very long docstring this is a very long docstring this is a very long docstring """
[ 37811, 198, 5661, 318, 257, 845, 890, 2205, 8841, 198, 198, 5661, 318, 257, 845, 890, 2205, 8841, 198, 5661, 318, 257, 845, 890, 2205, 8841, 198, 5661, 318, 257, 845, 890, 2205, 8841, 198, 5661, 318, 257, 845, 890, 2205, 8841, 198, ...
3.636364
77
import django.dispatch # signal fired just before calling model.index_search_document pre_index = django.dispatch.Signal(providing_args=["instance", "index"]) # signal fired just before calling model.update_search_document pre_update = django.dispatch.Signal( providing_args=["instance", "index", "update_fields"] ) # signal fired just before calling model.delete_search_document pre_delete = django.dispatch.Signal(providing_args=["instance", "index"])
[ 11748, 42625, 14208, 13, 6381, 17147, 198, 198, 2, 6737, 6294, 655, 878, 4585, 2746, 13, 9630, 62, 12947, 62, 22897, 198, 3866, 62, 9630, 796, 42625, 14208, 13, 6381, 17147, 13, 11712, 282, 7, 15234, 2530, 62, 22046, 28, 14692, 39098,...
3.316547
139
from django.db.models.signals import post_save from django.dispatch import receiver from communique.utils.utils_signals import generate_notifications from user.models import NotificationRegistration from .models import AdverseEvent
[ 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 12683, 874, 1330, 1281, 62, 21928, 198, 6738, 42625, 14208, 13, 6381, 17147, 1330, 9733, 198, 198, 6738, 1316, 2350, 13, 26791, 13, 26791, 62, 12683, 874, 1330, 7716, 62, 1662, 6637, 198, 6...
4.087719
57
# -*- coding: iso-8859-1 -*- # Maintainer: joaander import hoomd hoomd.context.initialize() import unittest if __name__ == '__main__': unittest.main(argv = ['test.py', '-v'])
[ 2, 532, 9, 12, 19617, 25, 47279, 12, 3459, 3270, 12, 16, 532, 9, 12, 198, 2, 337, 2913, 10613, 25, 2525, 64, 4066, 198, 198, 11748, 289, 4207, 67, 198, 71, 4207, 67, 13, 22866, 13, 36733, 1096, 3419, 198, 11748, 555, 715, 395, ...
2.234568
81
import cStringIO import StringIO from xml.sax import make_parser, ErrorHandler, SAXParseException from xml.sax import InputSource as SaxInput from xml.dom.minidom import parseString as domParseString from xml.parsers.expat import ExpatError from lxml import etree from cheshire3.baseObjects import Parser from cheshire3.record import ( SaxRecord, SaxContentHandler, DomRecord, MinidomRecord, MarcRecord ) from cheshire3.record import LxmlRecord from cheshire3.utils import nonTextToken from exceptions import XMLSyntaxError
[ 198, 11748, 269, 10100, 9399, 198, 11748, 10903, 9399, 198, 198, 6738, 35555, 13, 82, 897, 1330, 787, 62, 48610, 11, 13047, 25060, 11, 14719, 55, 10044, 325, 16922, 198, 6738, 35555, 13, 82, 897, 1330, 23412, 7416, 355, 29242, 20560, ...
3.094444
180
from hepqpr.qallse import * from hepqpr.qallse.plotting import * from hepqpr.qallse.cli.func import time_this import time import pickle # import the method from hepqpr.qallse.dsmaker import create_dataset modelName = "D0" #modelName = "Mp" #modelName = "Doublet" maxTry=1 # 5e-3 : 167 MeV # 8e-4 : 1.04 GeV varDensity = [] for ptThr_w in [0.15, 0.20, 0.30, 0.4, 0.50, 0.6, 0.75, 0.9, 1.0, 1.2]: for ptThr_r in [3e-4, 3.5e-4, 4e-4, 4.5e-4, 5e-4, 6e-4, 7e-4, 8e-4, 9e-4, 1e-3, 1.2e-3, 1.5e-3, 1.7e-3, 2e-3, 2.5e-3, 3e-3, 4e-3, 5e-3]: varDensity.append((modelName, ptThr_w, ptThr_r, maxTry)) #varDensity = [ # (modelName, 0.20, 5e-3, maxTry), # (modelName, 1.00, 5e-3, maxTry), # #] picklename = ".tmp.checkpT_curv.pickle" try: with open(picklename,'rb') as f: results = pickle.load(f) except: print ("No pickle files.") results = {} for v in varDensity: nTry = v[3] for iTry in range(nTry): k = (v[0], v[1], v[2], iTry) print (k) ModelName = k[0] ptThr_w = k[1] ptThr_r = k[2] Density = 0.05 if k in results: continue results[k] = {} results[k]["density"] = Density results[k]["ptThr_w"] = ptThr_w results[k]["ptThr_r"] = ptThr_r results[k]["ModelName"] = ModelName # dataset creation options ds_options = dict( # output directory: output_path+prefix output_path='/tmp', #prefix='ds_'+k, #prefix=prefix, # size density = Density, #phi_bounds = (0.15, 1.05), # important: no pt cut high_pt_cut = ptThr_w, ) prefix = f'ez-{Density}' if ds_options["high_pt_cut"] > 0: prefix += f'_hpt-{ds_options["high_pt_cut"]}' else: prefix += '_baby' prefix += f'_{iTry}' prefix += f'_noPhiCut' ds_options["prefix"] = prefix # generate the dataset import os path = os.path.join(ds_options['output_path'], prefix, "event000001000") if os.path.exists(path + "-hits.csv"): import json with open(path + "-meta.json") as f: meta = json.load(f) with open(path+"-metaHits.pickle", 'rb') as f: time_info= pickle.load(f) else: with time_this() as time_info: meta, path = create_dataset(**ds_options) with open(os.path.join(path+"-metaHits.pickle"), 'wb') as f: pickle.dump(time_info, f) results[k]['TReadingHits'] = time_info[1] results[k]['meta']=meta from hepqpr.qallse.seeding import generate_doublets, SeedingConfig # generate the doublets: the important part is the config_cls ! if os.path.exists(path + "-doublets.csv"): doublets = pd.read_csv(path + "-doublets.csv", index_col=0) results[k]['TInitialDoubletBuilding'] = time_info[1] with open(path+"-metaDoublets.pickle", 'rb') as f: time_info= pickle.load(f) else: with time_this() as time_info: doublets = generate_doublets(hits_path=path+'-hits.csv', config_cls=SeedingConfig) doublets.to_csv(path+'-doublets.csv') with open(os.path.join(path+"-metaDoublets.pickle"), 'wb') as f: pickle.dump(time_info, f) results[k]['TInitialDoubletBuilding'] = time_info[1] print('number of doublets = ', len(doublets)) results[k]['Ndoublets'] = len(doublets) from hepqpr.qallse.qallse import Config config = Config() config.tplet_max_curv = ptThr_r dw = DataWrapper.from_path(path + '-hits.csv') if modelName == "D0": from hepqpr.qallse.qallse_d0 import D0Config new_config = merge_dicts(D0Config().as_dict(), config.as_dict()) model = QallseD0(dw, **new_config) elif modelName == "Mp": from hepqpr.qallse.qallse_mp import MpConfig new_config = merge_dicts(MpConfig().as_dict(), config.as_dict()) model = QallseMp(dw, **new_config) elif modelName == "Nominal": from hepqpr.qallse.qallse import Config1GeV new_config = merge_dicts(Config1GeV().as_dict(), config.as_dict()) model = Qallse1GeV(dw, **new_config) elif modelName == "Doublet": from hepqpr.qallse.qallse_doublet import DoubletConfig new_config = merge_dicts(DoubletConfig().as_dict(), config.as_dict()) model = QallseDoublet(dw, **new_config) p, r, ms = model.dataw.compute_score(doublets) results[k]['precision_initDoublet'] = p results[k]['recall_initDoublet'] = r results[k]['missing_initDoublet'] = len(ms) # generate the qubo as usual with time_this() as time_info: model.build_model(doublets) print(f'Time of model building = {time_info[1]:.2f}s.') results[k]['TModelBuilding'] = time_info[1] with time_this() as time_info: Q = model.to_qubo() print(f'Time of qubo building = {time_info[1]:.2f}s.') results[k]['TQuboBuilding'] = time_info[1] results[k]['QuboSize'] = len(Q) from hepqpr.qallse.cli.func import * with time_this() as time_info: response = solve_neal(Q) print(f'Time of neal = {time_info[1]:.2f}s.') results[k]['TNeal'] = time_info[1] final_doublets, final_tracks = process_response(response) en0 = 0 if Q is None else dw.compute_energy(Q) en = response.record.energy[0] results[k]['obsEnergy'] = en results[k]['idealEnergy'] = en0 occs = response.record.num_occurrences results[k]['bestOcc'] = occs[0] results[k]['OccSum'] = occs.sum() p, r, ms = dw.compute_score(final_doublets) results[k]['precision'] = p results[k]['recall'] = r results[k]['missing'] = len(ms) trackml_score = dw.compute_trackml_score(final_tracks) results[k]['trackmlScore'] = trackml_score with open(picklename, 'wb') as f: pickle.dump(results, f) #print(results)
[ 6738, 47585, 80, 1050, 13, 80, 439, 325, 1330, 1635, 198, 6738, 47585, 80, 1050, 13, 80, 439, 325, 13, 29487, 889, 1330, 1635, 220, 198, 6738, 47585, 80, 1050, 13, 80, 439, 325, 13, 44506, 13, 20786, 1330, 640, 62, 5661, 628, 198,...
1.951182
3,216
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================== # # File name: __init__.py # Author: threeheadedknight@protonmail.com # Date created: 30.06.2018 17:00 # Python Version: 3.7 # # ====================================================== from .ifconfig_parser import IfconfigParser __author__ = "KnightWhoSayNi" __email__ = 'threeheadedknight@protonmail.com' __version__ = '0.0.5'
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 46111, 4770, 1421, 28, 198, 2, 198, 2, 220, 220, 220, 9220, 1438, 25, 11593, 15003, 834, 13, 9078, 198, 2, 220, ...
2.972973
148
from abc import ABC, abstractmethod import tmdbsimple as tmdb from django.contrib.auth.decorators import login_required from django.http import Http404 from django.utils.decorators import method_decorator from rest_framework.response import Response from rest_framework.views import APIView from api.serializers import MovieSerializer from app.models import Movie, SearchedMovie, User, CollectedMovie MAX_NUM_CASTS = 4
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 198, 11748, 256, 9132, 1443, 320, 1154, 355, 256, 9132, 65, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 42625, 14208, 13...
3.416
125
from django.shortcuts import render from django.http import Http404, HttpResponseRedirect from django.urls import reverse from apps.index.models import User, UserHistory from sova_avia.settings import MEDIA_ROOT from imageai.Prediction import ImagePrediction import json from .models import Article from .forms import ArticleForm
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 26429, 11, 367, 29281, 31077, 7738, 1060, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 6725, 13, 9630, 13, 27530, 13...
3.666667
93
#!/usr/bin/env python3 from distutils.core import setup version = '3.0' setup( name='deckard', version=version, description='DNS toolkit', long_description=( "Deckard is a DNS software testing based on library pydnstest." "It supports parsing and running Unbound-like test scenarios," "and setting up a mock DNS server. It's based on dnspython."), author='CZ.NIC', author_email='knot-dns-users@lists.nic.cz', license='BSD', url='https://gitlab.labs.nic.cz/knot/deckard', packages=['pydnstest'], python_requires='>=3.5', install_requires=[ 'dnspython>=1.15', 'jinja2', 'PyYAML', 'python-augeas' ], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3 :: Only' 'Operating System :: POSIX :: Linux', 'Topic :: Internet :: Name Service (DNS)', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', ] )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 198, 9641, 796, 705, 18, 13, 15, 6, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 35875, 446, 3256, 198, 220, 220, 220, 219...
2.471215
469
import os from urllib.parse import urljoin from selenium import webdriver from TrackApp.models import User, Track from libs import track
[ 11748, 28686, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 22179, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 198, 6738, 17762, 4677, 13, 27530, 1330, 11787, 11, 17762, 198, 6738, 9195, 82, 1330, 2610, 628, 628, 628, 198 ...
3.512195
41
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from simuleval.states import TextStates, SpeechStates
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 42...
4
63
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import boto3 import json import sys import time import ffmpeg from MediaReplayEnginePluginHelper import OutputHelper from MediaReplayEnginePluginHelper import Status from MediaReplayEnginePluginHelper import DataPlane s3_client = boto3.client('s3')
[ 2, 15069, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 12, 15, 198, 198, 11748, 275, 2069, 18, 198, 11748, 33918, 198, 11748, 25064, 198, 11748, ...
3.639175
97
from __future__ import division from chempy.util.testing import requires from ..integrated import pseudo_irrev, pseudo_rev, binary_irrev, binary_rev import pytest try: import sympy except ImportError: sympy = None else: one = sympy.S(1) t, kf, kb, prod, major, minor = sympy.symbols( 't kf kb prod major minor', negative=False, nonnegative=True, real=True) subsd = {t: one*2, kf: one*3, kb: one*7, major: one*11, minor: one*13, prod: one*0}
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 6738, 1125, 3149, 88, 13, 22602, 13, 33407, 1330, 4433, 198, 6738, 11485, 18908, 4111, 1330, 24543, 62, 343, 18218, 11, 24543, 62, 18218, 11, 13934, 62, 343, 18218, 11, 13934, 62, 18218, ...
2.442786
201
#!/usr/bin/python import sys import os import shutil if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 1388, 3419, 628, 220, 220, 198 ]
2.540541
37
from setuptools import setup setup( name='netbox_plugin_osism', version='0.0.1', description='NetBox Plugin OSISM', long_description='Netbox Plugin OSISM', url='https://github.com/osism/netbox-plugin-osism', download_url='https://github.com/osism/netbox-plugin-osism', author='OSISM GmbH', author_email='info@osism.tech', maintainer='OSISM GmbH', maintainer_email='info@osism.tech', install_requires=[], packages=['netbox_plugin_osism'], package_data={ 'netbox_plugin_osism': ['templates/netbox_plugin_osism/*.html'] }, include_package_data=True, zip_safe=False, platforms=['Any'], keywords=['netbox', 'netbox-plugin'], classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: Apache Software License', 'Framework :: Django', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Intended Audience :: Developers', 'Environment :: Console', ], )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 3262, 3524, 62, 33803, 62, 418, 1042, 3256, 198, 220, 220, 220, 2196, 11639, 15, 13, 15, 13, 16, 3256, 198, 220, 220, 220, 6764, 11639, 7934, ...
2.4819
442
from starlette.responses import HTMLResponse
[ 6738, 3491, 21348, 13, 16733, 274, 1330, 11532, 31077, 198 ]
4.5
10
from .core import Observer, Observable, AnonymousObserver as _
[ 6738, 764, 7295, 1330, 27058, 11, 19243, 540, 11, 19200, 31310, 18497, 355, 4808, 198 ]
4.2
15
VESPA_IP = "172.16.100.65" VESPA_PORT = "8080"
[ 53, 1546, 4537, 62, 4061, 796, 366, 23628, 13, 1433, 13, 3064, 13, 2996, 1, 198, 53, 1546, 4537, 62, 15490, 796, 366, 1795, 1795, 1, 198 ]
1.740741
27
import cozmo from cozmo.util import distance_mm, speed_mmps,degrees cozmo.run_program(cozmo_program)
[ 11748, 763, 89, 5908, 198, 6738, 763, 89, 5908, 13, 22602, 1330, 5253, 62, 3020, 11, 2866, 62, 3020, 862, 11, 13500, 6037, 198, 198, 1073, 89, 5908, 13, 5143, 62, 23065, 7, 1073, 89, 5908, 62, 23065, 8, 198 ]
2.55
40
#!/usr/bin/env python # Krzysztof Kosiski 2014 """ Detect the Clang C compiler """ from waflib.Configure import conf from waflib.Tools import ar from waflib.Tools import ccroot from waflib.Tools import gcc
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 13685, 89, 893, 89, 1462, 69, 18884, 1984, 72, 1946, 198, 37811, 198, 47504, 262, 1012, 648, 327, 17050, 198, 37811, 198, 6738, 266, 1878, 8019, 13, 16934, 495, 1330, 1013, 198, 6...
2.929577
71
import unittest from lambda_function import gather_anagrams if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 37456, 62, 8818, 1330, 6431, 62, 272, 6713, 82, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.842105
38
''' Find the smallest cube for which exactly five permutations of its digits are cube. ''' import math, itertools print(math.pow(8, 1/3).is_integer()) tried = {} for i in range(1000, 1200): cb = int(math.pow(i, 3)) #print(cb) #print(math.pow(int(cb), 1/3)) roots = 1 tried[i] = [str(cb)] for x in itertools.permutations(str(cb)): x = ''.join(x) if x not in tried[i]: #print('x =', x) y = round(math.pow(int(x), 1/3)) #print(y**3, x) if y**3 == int(x): roots += 1 tried[i].append(x) print(roots, i, y, x) if roots == 5: print(cb) break
[ 7061, 6, 198, 16742, 262, 18197, 23441, 329, 543, 3446, 1936, 9943, 32855, 286, 663, 19561, 389, 23441, 13, 198, 7061, 6, 198, 11748, 10688, 11, 340, 861, 10141, 198, 4798, 7, 11018, 13, 79, 322, 7, 23, 11, 352, 14, 18, 737, 271, ...
2.083032
277
from ants.medium import MediumX from ants.materials import Materials from ants.mapper import Mapper from ants.multi_group import source_iteration import numpy as np import matplotlib.pyplot as plt groups = 1 cells_x = 1000 medium_width = 16. cell_width_x = medium_width / cells_x angles = 16 xbounds = np.array([1, 0]) materials = ['reed-vacuum', 'reed-strong-source', \ 'reed-scatter','reed-absorber'] problem_01 = Materials(materials, 1, None) medium = MediumX(cells_x, cell_width_x, angles, xbounds) medium.add_external_source("reed") map_obj = Mapper.load_map('reed_problem2.mpr') if cells_x != map_obj.cells_x: map_obj.adjust_widths(cells_x) reversed_key = {v: k for k, v in map_obj.map_key.items()} total = [] scatter = [] fission = [] for position in range(len(map_obj.map_key)): map_material = reversed_key[position] total.append(problem_01.data[map_material][0]) scatter.append(problem_01.data[map_material][1]) fission.append(problem_01.data[map_material][2]) total = np.array(total) scatter = np.array(scatter) fission = np.array(fission) print(map_obj.map_key.keys()) print(problem_01.data.keys()) mu_x = medium.mu_x weight = medium.weight print(mu_x) print(weight) medium_map = map_obj.map_x.astype(int) phi = source_iteration(groups, mu_x / cell_width_x, weight, total, scatter, \ fission, medium.ex_source, medium_map, xbounds, \ cell_width_x) print(medium.ex_source.shape) fig, ax = plt.subplots() solution = np.load('reed_solution.npy') print(len(solution)) print(np.allclose(solution, phi[:,0],atol=1e-12)) ax.plot(np.linspace(0, 16, len(solution)), solution, label='solution', c='k', ls='--') ax.plot(np.linspace(0, medium_width, cells_x), phi[:,0], label='New', c='r', alpha=0.6) ax.legend(loc=0) plt.show()
[ 6738, 27842, 13, 24132, 1330, 13398, 55, 198, 6738, 27842, 13, 33665, 82, 1330, 24310, 198, 6738, 27842, 13, 76, 11463, 1330, 337, 11463, 198, 6738, 27842, 13, 41684, 62, 8094, 1330, 2723, 62, 2676, 341, 628, 198, 11748, 299, 32152, 3...
2.428191
752
import os import time import logging import argparse import numpy as np import cv2 as cv import trimesh import torch import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter from shutil import copyfile from icecream import ic from tqdm import tqdm from pyhocon import ConfigFactory from models.dataset import Dataset, load_K_Rt_from_P from models.fields import RenderingNetwork, SDFNetwork, SingleVarianceNetwork, NeRF from models.renderer import NeuSRenderer from models.poses import LearnPose, LearnIntrin, RaysGenerator # from models.depth import SiLogLoss if __name__ == '__main__': print('Hello Wooden') torch.set_default_tensor_type('torch.cuda.FloatTensor') FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s" logging.basicConfig(level=logging.DEBUG, format=FORMAT) parser = argparse.ArgumentParser() parser.add_argument('--conf', type=str, default='./confs/base.conf') parser.add_argument('--mode', type=str, default='train') parser.add_argument('--mcube_threshold', type=float, default=0.0) parser.add_argument('--is_continue', default=False, action="store_true") parser.add_argument('--gpu', type=int, default=0) parser.add_argument('--case', type=str, default='') args = parser.parse_args() torch.cuda.set_device(args.gpu) runner = Runner(args.conf, args.mode, args.case, args.is_continue) if args.mode == 'train': runner.train() elif args.mode == 'validate_mesh': runner.validate_mesh(world_space=True, resolution=512, threshold=args.mcube_threshold) elif args.mode.startswith('interpolate'): # Interpolate views given two image indices _, img_idx_0, img_idx_1 = args.mode.split('_') img_idx_0 = int(img_idx_0) img_idx_1 = int(img_idx_1) runner.interpolate_view(img_idx_0, img_idx_1) elif args.mode.startswith('showcam'): _, iter_show = args.mode.split('_') runner.load_pnf_checkpoint(('pnf_{:0>6d}.pth').format(int(iter_show))) runner.show_cam_pose(int(iter_show))
[ 11748, 28686, 198, 11748, 640, 198, 11748, 18931, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 355, 269, 85, 198, 11748, 491, 999, 71, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, ...
2.589263
801
#Python v3, OpenCV v3.4.2 import numpy as np import cv2 videoCapture = cv2.VideoCapture("video.mp4") ret,camera_input = videoCapture.read() rows, cols = camera_input.shape[:2] ''' Video dosyas zerine Mean Shift iin bir alan belirlenir. Bu koordinatlar arlkl ortalamas belirlenecek olan drtgen alandr. ''' #w ve h boyutlandrmasn deitirerek sonular gzlemleyebilirsiniz w = 10 h = 15 col = int((cols - w) / 2) row = int((rows - h) / 2) shiftWindow = (col, row, w, h) ''' imdi grnt zerindeki parlakl, renk dalmlarn dengelemek iin bir maskeleme alan oluturalm ve bu alan zerinde histogram eitleme yapalm ''' roi = camera_input[row:row + h, col:col + w] hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.))) histogram = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180]) cv2.normalize(histogram,histogram,0,255,cv2.NORM_MINMAX) ''' Bu parametre / durdurma lt algoritmann kendi ierisinde kaydrma/hesaplama ilemini ka defa yapacan belirlemektedir. ''' term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 ) while True: #Video'dan bir frame okunur ret ,camera_input = videoCapture.read() ''' video ierisinde ncelikli HSV renk uzay zerinde histogram alp histogram back projection yapacaz ve tm grnt zerinde istediimiz yerin segmentlerini bulacaz. ''' hsv = cv2.cvtColor(camera_input, cv2.COLOR_BGR2HSV) dst = cv2.calcBackProject([hsv],[0],histogram,[0,180],1) #her yeni konum iin meanshift tekrar uygulanr ret, shiftWindow = cv2.CamShift(dst, shiftWindow, term_crit) #Grnt zerinde tespit edilen alan izelim pts = cv2.boxPoints(ret) pts = np.int0(pts) result_image = cv2.polylines(camera_input,[pts],True, 255,2) cv2.imshow('Camshift (Surekli Mean Shift) Algoritmasi', result_image) k = cv2.waitKey(60) & 0xff videoCapture.release() cv2.destroyAllWindows()
[ 2, 37906, 410, 18, 11, 4946, 33538, 410, 18, 13, 19, 13, 17, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 198, 15588, 49630, 796, 269, 85, 17, 13, 10798, 49630, 7203, 15588, 13, 3149, 19, 4943, 198, 1186,...
2.194098
881
from dtt_class import DTT from parser import args if __name__ == "__main__": dtt = DTT() # Creates a list of files and subdirectories try: l = dtt.dir_to_list(args.directory, args) # Creates a .txt file with the list dtt.list_to_txt(args.output_file, l) except Exception as e: print(f"Error: {e}")
[ 6738, 288, 926, 62, 4871, 1330, 360, 15751, 198, 6738, 30751, 1330, 26498, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 288, 926, 796, 360, 15751, 3419, 198, 220, 220, 220, 1303, 7921, 274, ...
2.291391
151
import torch.nn as nn import collections
[ 11748, 28034, 13, 20471, 355, 299, 77, 201, 198, 11748, 17268, 201, 198, 201, 198, 201, 198, 201, 198, 201, 198 ]
2.428571
21
from __future__ import unicode_literals, print_function, absolute_import import flask import os import os.path import json import sjoh.flask import logging import asgard app = asgard.Asgard(__name__, flask_parameters={"static_folder": None}) # load configuration about files and folders folder = os.path.dirname(__file__) fc = os.path.join(folder, "filesconfig.json") with open(fc, "rb") as file_: fc_content = file_.read().decode("utf8") files_config = json.loads(fc_content) # register static folders for s in files_config["static_folders"]: route = "/" + s + "/<path:path>" app.web_app.add_url_rule(route, "static:"+s, gen_fct(s))
[ 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 11, 3601, 62, 8818, 11, 4112, 62, 11748, 198, 198, 11748, 42903, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 33918, 198, 11748, 264, 73, 1219, 13, 2704, ...
2.859649
228
import io import os import unittest import numpy as np from PIL import Image from vltk import SingleImageViz PATH = os.path.dirname(os.path.realpath(__file__)) URL = "https://raw.githubusercontent.com/airsplay/py-bottom-up-attention/master/demo/data/images/input.jpg"
[ 11748, 33245, 198, 11748, 28686, 198, 11748, 555, 715, 395, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 6738, 410, 2528, 74, 1330, 14206, 5159, 53, 528, 628, 198, 34219, 796, 28686, 13, 6978, 1...
2.854167
96
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import torch from collections import OrderedDict from ..builder import build_tracker, TRAIN_WRAPPERS from ...datasets import TrainPairDataset, build_dataloader from ...runner import Runner from ...utils.parallel import MMDataParallel from ...utils import load_checkpoint
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 198, 198, 11748, 28034, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 6738, 11485, 38272, 1330, 1382, 62, 2213, 10735, ...
3.793814
97
""" View helpers ============ Coaster provides classes, functions and decorators for common scenarios in view handlers. """ # flake8: noqa from .classview import * from .decorators import * from .misc import *
[ 37811, 198, 7680, 49385, 198, 25609, 198, 198, 7222, 1603, 3769, 6097, 11, 5499, 290, 11705, 2024, 329, 2219, 13858, 287, 1570, 198, 4993, 8116, 13, 198, 37811, 198, 2, 781, 539, 23, 25, 645, 20402, 198, 198, 6738, 764, 4871, 1177, ...
3.59322
59
# Generated by Django 2.1.5 on 2020-03-08 05:39 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 20, 319, 12131, 12, 3070, 12, 2919, 8870, 25, 2670, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== from incomming import CacheTick from incomming import SaveLogin from incomming import RemoveLogin from incomming import StatusUpdate from outgoing import UploadRequest from outgoing import AfterDBCleanupRequest
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 4225, 3866, 353, 2196, 25, 21015, 362, 13, 22, 198, 2, 198, 2, 1846, 3742, 38093, 1421, 198, 6738, 7...
3.968421
95
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # # Code generated. DO NOT EDIT! # template file: justice_py_sdk_codegen/__main__.py # pylint: disable=duplicate-code # pylint: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-lines # pylint: disable=too-many-locals # pylint: disable=too-many-public-methods # pylint: disable=too-many-return-statements # pylint: disable=too-many-statements # pylint: disable=unused-import from typing import Any, Dict, List, Optional, Tuple, Union from ....core import HeaderStr from ....core import get_namespace as get_services_namespace from ....core import run_request from ....core import run_request_async from ....core import same_doc_as from ..operations.anonymization import AnonymizeCampaign from ..operations.anonymization import AnonymizeEntitlement from ..operations.anonymization import AnonymizeFulfillment from ..operations.anonymization import AnonymizeIntegration from ..operations.anonymization import AnonymizeOrder from ..operations.anonymization import AnonymizePayment from ..operations.anonymization import AnonymizeSubscription from ..operations.anonymization import AnonymizeWallet
[ 2, 15069, 357, 66, 8, 33448, 4013, 5276, 40778, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 770, 318, 11971, 3788, 422, 4013, 5276, 40778, 3457, 11, 329, 11247, 198, 2, 290, 8733, 2800, 534, 1664, 2775, 4706, 13, 198, 2, 220, 198, 2,...
3.286624
471
from django.contrib.auth.models import User, Group from rest_framework import serializers from rest_framework_json_api.relations import * #load django and webapp models #from django.contrib.auth.models import * from api.models import *
[ 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 11, 4912, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 1334, 62, 30604, 62, 17752, 62, 15042, 13, 39468, 1330, 1635, 628, 198, 2, 2220, 42625, 14...
3.529412
68
import numpy as np import pylab as pl x = [] # Make an array of x values y = [] # Make an array of y values for each x value for i in range(-128,127): x.append(i) for j in range(-128,127): temp = j *(2**(1 - abs((j/128)))) y.append(temp) # print('y',y) # pl.xlim(-128, 127)# set axis limits # pl.ylim(-128, 127) pl.axis([-128, 127,-128, 127]) pl.title('S-model Curve Function ',fontsize=20)# give plot a title pl.xlabel('Input Value',fontsize=20)# make axis labels pl.ylabel('Output Value',fontsize=20) pl.plot(x, y,color='red') # use pylab to plot x and y pl.show() # show the plot on the screen
[ 11748, 299, 32152, 355, 45941, 198, 11748, 279, 2645, 397, 355, 458, 198, 198, 87, 796, 17635, 220, 1303, 6889, 281, 7177, 286, 2124, 3815, 198, 88, 796, 17635, 220, 1303, 6889, 281, 7177, 286, 331, 3815, 329, 1123, 2124, 1988, 198, ...
2.528455
246
bl_info = { "name": "Gothic Materials and Textures Blender", "description": "Makes life easier for Gothic material export", "author": "Diego", "version": (1, 3, 0), "blender": (2, 78, 0), "location": "3D View > Tools", "warning": "", # used for warning icon and text in addons panel "wiki_url": "", "tracker_url": "", "category": "Development" } import bpy # if not blenders bundled python is used, packages might not be installed try: from mathutils import Color except ImportError: raise ImportError('Package mathutils needed, but not installed') try: import numpy except ImportError: raise ImportError('Package numpy needed, but not installed') try: import os.path except ImportError: raise ImportError('Package os needed, but not installed') try: import colorsys except ImportError: raise ImportError('Package colorsys needed, but not installed') from bpy.props import (StringProperty, BoolProperty, IntProperty, FloatProperty, EnumProperty, PointerProperty, ) from bpy.types import (Panel, Operator, PropertyGroup, ) # ------------------------------------------------------------------------ # store properties in the active scene # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # operators # ------------------------------------------------------------------------ # hides all objects that do not have the material specified in the "searched_material" property # optional: isolate in all layers # changes the names of all used images to their filename # if multiple images use the same file, only one is kept # the others will be replaced by this one # Removes suffixes like ".001" and renames textures to image filename # replaces materials with same name except suffixes # keeps only one texture per image file, replaces others by this one # takes a sample of pixels and calculates average color for every material with image # replaces all UV textures by the image that the material of this face has # replaces materials by those that belong to the assigned UV textures # at every call matlib.ini is parsed and for every image a matching material is searched_material # depending on how often this texture is used by a material, the used material name is # never: texture name without file extension # once: take name from materialfilter # more: ambiguous, depending on settings # optionally faces with portal materials are not overwritten # note that this will create a material for all used images in the file if they dont exist. this is done because # it would be more troublesome to first filter out the actually needed materials # ------------------------------------------------------------------------ # gothic tools in objectmode # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # register and unregister # ------------------------------------------------------------------------ def register(): bpy.utils.register_module(__name__) bpy.types.Scene.gothic_tools = PointerProperty(type=GothicMaterialSettings) def unregister(): bpy.utils.unregister_module(__name__) del bpy.types.Scene.gothic_tools if __name__ == "__main__": register()
[ 2436, 62, 10951, 796, 1391, 201, 198, 220, 220, 220, 366, 3672, 1298, 366, 38, 849, 291, 24310, 290, 8255, 942, 1086, 2194, 1600, 201, 198, 220, 220, 220, 366, 11213, 1298, 366, 44, 1124, 1204, 4577, 329, 38845, 2587, 10784, 1600, 2...
3.134055
1,201
# Massive Black 2 galaxy catalog class import numpy as np from astropy.table import Table import astropy.units as u import astropy.cosmology from .GalaxyCatalogInterface import GalaxyCatalog
[ 2, 38756, 2619, 362, 16161, 18388, 1398, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 6468, 28338, 13, 11487, 1330, 8655, 198, 11748, 6468, 28338, 13, 41667, 355, 334, 198, 11748, 6468, 28338, 13, 6966, 29126, 198, 6738, 764, 265...
4
48
from django.shortcuts import get_object_or_404, render from django.contrib.staticfiles.templatetags.staticfiles import static
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 651, 62, 15252, 62, 273, 62, 26429, 11, 8543, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 12708, 16624, 13, 11498, 489, 265, 316, 3775, 13, 12708, 16624, 1330, 9037, 628, 198 ]
3.282051
39
from src.dirac_notation.bra import Bra from src.dirac_notation.ket import Ket from src.dirac_notation.matrix import Matrix from src.dirac_notation import functions as dirac from src.dirac_notation import constants as const from src.objects.quantum_system import QuantumSystem, SystemType
[ 6738, 12351, 13, 15908, 330, 62, 38983, 13, 16057, 1330, 9718, 198, 6738, 12351, 13, 15908, 330, 62, 38983, 13, 7126, 1330, 43092, 198, 6738, 12351, 13, 15908, 330, 62, 38983, 13, 6759, 8609, 1330, 24936, 198, 6738, 12351, 13, 15908, ...
3.658228
79
import sys, re, textwrap def parse_hunks(text): # return a list of tuples. Each is one of: # ("raw", string) : non-API blocks # ("api-json", dict) : API blocks processed = 0 # we've handled all bytes up-to-but-not-including this offset line_number = 1 for m in re.finditer("<api[\w\W]*?</api>", text, re.M): start = m.start() if start > processed+1: hunk = text[processed:start] yield ("markdown", hunk) processed = start line_number += hunk.count("\n") api_text = m.group(0) api_lines = api_text.splitlines() d = APIParser().parse(api_lines, line_number) yield ("api-json", d) processed = m.end() line_number += api_text.count("\n") if processed < len(text): yield ("markdown", text[processed:]) if __name__ == "__main__": json = False if sys.argv[1] == "--json": json = True del sys.argv[1] docs_text = open(sys.argv[1]).read() docs_parsed = list(parse_hunks(docs_text)) if json: import simplejson print simplejson.dumps(docs_parsed, indent=2) else: TestRenderer().render_docs(docs_parsed)
[ 11748, 25064, 11, 302, 11, 2420, 37150, 628, 198, 198, 4299, 21136, 62, 71, 14125, 7, 5239, 2599, 198, 220, 220, 220, 1303, 1441, 257, 1351, 286, 12777, 2374, 13, 5501, 318, 530, 286, 25, 198, 220, 220, 220, 1303, 220, 220, 220, 5...
2.13438
573
# -*- coding: utf-8 -*- import attest from acrylamid.core import cache
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 44477, 198, 6738, 936, 563, 2543, 312, 13, 7295, 1330, 12940, 628 ]
2.607143
28
from subplot_animation import subplot_animation import sys import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import os import numpy as np import glob sys.path.append("/home/smp16fm/forked_amrvac/amrvac/tools/python") from amrvac_pytools.datfiles.reading import amrvac_reader from amrvac_pytools.vtkfiles import read, amrplot program_name = sys.argv[0] path2files = sys.argv[1:] # Switches refiner = '__' fps = 3 start_frame = 0 in_extension = 'png' out_extension = 'avi' # set time to look over time_start = 0 time_end = None text_x_pos = 0.85 text_y_pos = 0.01 save_dir = '/shared/mhd_jet1/User/smp16fm/j/2D/results' # make dirs #path2files = "/shared/mhd_jet1/User/smp16fm/sj/2D/P300/B100/A20/" # path2files = "../test/" # dummy_name = 'solar_jet_con_' dummy_name = '' #read.load_vtkfile(0, file='/shared/mhd_jet1/User/smp16fm/sj/2D/P300/B100/A20/jet_t300_B100A_20_', type='vtu') print(path2files[0]) test = subplot_animation(path2files[0], save_dir=save_dir, dummy_name='', refiner=None, text_x_pos=0.85, text_y_pos=0.01, time_start=0, time_end=time_end, start_frame=0, fps=fps, in_extension='png', out_extension='avi')
[ 6738, 850, 29487, 62, 11227, 341, 1330, 850, 29487, 62, 11227, 341, 198, 11748, 25064, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 9460, 11537, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 19...
2.132988
579
from flask.helpers import flash from flask.wrappers import Request from swcf import app from flask import render_template, redirect, request, url_for from swcf.dao.indexDAO import *
[ 6738, 42903, 13, 16794, 364, 1330, 7644, 198, 6738, 42903, 13, 29988, 11799, 1330, 19390, 198, 6738, 1509, 12993, 1330, 598, 198, 6738, 42903, 1330, 8543, 62, 28243, 11, 18941, 11, 2581, 11, 19016, 62, 1640, 198, 6738, 1509, 12993, 13, ...
3.693878
49
from testlib2 import _puw
[ 6738, 1332, 8019, 17, 1330, 4808, 19944, 86, 198 ]
2.888889
9
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # 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. """Module for testing the show machine command.""" import unittest if __name__ == "__main__": import utils utils.import_depends() from brokertest import TestBrokerCommand if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestShowMachine) unittest.TextTestRunner(verbosity=2).run(suite)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 269, 9078, 12, 521, 298, 12, 5715, 25, 604, 26, 33793, 12, 8658, 82, 12, 14171, 25, 18038, 532, 9, 12, 198, 2, 409, 25, 900, 4292, 8658, 2705, 8658, 11338, 28, 1...
3.179412
340
host="mysql-general.cyqv8he15vrg.ap-southeast-2.rds.amazonaws.com" user="admin" password="" database="silver_giggle"
[ 4774, 2625, 28744, 13976, 12, 24622, 13, 948, 44179, 23, 258, 1314, 37020, 70, 13, 499, 12, 82, 14474, 12, 17, 13, 4372, 82, 13, 33103, 8356, 13, 785, 1, 198, 7220, 2625, 28482, 1, 198, 28712, 33151, 198, 48806, 2625, 40503, 62, 7...
2.489362
47