content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
#!/usr/bin/env python3 # ============================================================== # author: Lars Gabriel # # gff32gtf.py: Convert gff3 to gtf # ============================================================== import argparse def parseCmd(): """Parse command line arguments Returns: dictionary: Dictionary with arguments """ parser = argparse.ArgumentParser(description='Convert file from gff3 to gtf ') parser.add_argument('--gff', type=str, help='File in gff3 format') parser.add_argument('--out', type=str, help='Output in gtf format') return parser.parse_args() if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 46111, 4770, 25609, 28, 198, 2, 1772, 25, 31239, 17371, 198, 2, 198, 2, 308, 487, 2624, 13655, 69, 13, 9078, 25, 38240, 308, 487, 18, 284, 308, 27110, 198, 2, 46111, 4770, ...
3.07907
215
import numpy as np import numpy.testing as npt import pandas as pd import pandas.testing as pdt import pytest import datetime from pandas.api.types import is_numeric_dtype import timeserio.ini as ini from timeserio.data.mock import mock_fit_data from timeserio.preprocessing import PandasDateTimeFeaturizer from timeserio.preprocessing.datetime import ( get_fractional_day_from_series, get_fractional_hour_from_series, get_fractional_year_from_series, truncate_series, get_zero_indexed_month_from_series, get_time_is_in_interval_from_series, get_is_holiday_from_series ) datetime_column = ini.Columns.datetime seq_column = f'seq_{ini.Columns.datetime}' usage_column = ini.Columns.target @pytest.fixture @pytest.fixture @pytest.mark.parametrize( "country, expected", [("England", [1, 0, 0, 1]), ("Scotland", [1, 1, 1, 0])] ) @pytest.mark.parametrize( 'series_data, truncation_period, expected_data', [ ([pd.Timestamp(2019, 1, 1, 1, 9)], 'H', [pd.Timestamp(2019, 1, 1, 1)]), ([pd.Timestamp(2019, 1, 2, 1)], 'd', [pd.Timestamp(2019, 1, 2)]), ([pd.Timestamp(2019, 1, 1)], 'W', [pd.Timestamp(2018, 12, 31)]), ([pd.Timestamp(2019, 1, 1)], 'W-FRI', [pd.Timestamp(2018, 12, 29)]), ([pd.Timestamp(2019, 1, 1)], 'W-TUE', [pd.Timestamp(2018, 12, 26)]), ([pd.Timestamp(2019, 2, 8)], 'm', [pd.Timestamp(2019, 2, 1)]), ([pd.Timestamp(2019, 3, 4)], 'Y', [pd.Timestamp(2019, 1, 1)]), ( [pd.Timestamp(2019, 1, 1, 1, 30), pd.Timestamp(2019, 1, 1, 2, 30)], 'H', [pd.Timestamp(2019, 1, 1, 1), pd.Timestamp(2019, 1, 1, 2)], ), ] ) @pytest.mark.parametrize('periods', [48, 96]) @pytest.mark.parametrize('periods', [48, 96]) @pytest.mark.parametrize('periods', [48, 96]) @pytest.mark.parametrize( 'transformer, required_columns', [ ( PandasDateTimeFeaturizer(column=datetime_column), {datetime_column} ) ] ) @pytest.mark.parametrize( 'transformer, transformed_columns', [ ( PandasDateTimeFeaturizer( column=datetime_column, attributes=['hour'] ), {datetime_column, 'hour'} ) ] ) @pytest.mark.parametrize( 'transformer, transformed_columns, input_columns', [ ( PandasDateTimeFeaturizer( column=datetime_column, attributes=['hour'] ), {datetime_column, 'hour'}, {datetime_column} ), ( PandasDateTimeFeaturizer( column=datetime_column, attributes=['hour'] ), {usage_column, datetime_column, 'hour'}, {usage_column, datetime_column} ) ] )
[ 11748, 299, 32152, 355, 45941, 198, 11748, 299, 32152, 13, 33407, 355, 299, 457, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 19798, 292, 13, 33407, 355, 279, 28664, 198, 11748, 12972, 9288, 198, 11748, 4818, 8079, 198, 6738, 19798...
2.040462
1,384
# ----------------------------------------------------------------------------- # @brief: # Define some signals used during parallel # @author: # Tingwu Wang # ----------------------------------------------------------------------------- TRAIN_SIGNAL = 1 SAVE_SIGNAL = 2 # it makes the main trpo agent push its weights into the tunnel START_SIGNAL = 3 # it ends the training END_SIGNAL = 4 # ends the rollout END_ROLLOUT_SIGNAL = 5 # ask the rollout agents to collect the ob normalizer's info AGENT_COLLECT_FILTER_INFO = 6 # ask the rollout agents to synchronize the ob normalizer's info AGENT_SYNCHRONIZE_FILTER = 7 # ask the agents to set their parameters of network AGENT_SET_WEIGHTS = 8 # reset RESET_SIGNAL = 9 # Initial training for mbmf policy netwrok. MBMF_INITIAL = 666 # ask for policy network. GET_POLICY_NETWORK = 6666 # ask and set for policy network weight. GET_POLICY_WEIGHT = 66 SET_POLICY_WEIGHT = 66666 WORKER_PLANNING = 10 WORKER_PLAYING = 11 WORKER_GET_MODEL = 12 WORKER_RATE_ACTIONS = 13 # make sure that no signals are using the same number var_dict = locals() var_list = [var_dict[var] for var in dir() if (not var.startswith('_') and type(var_dict[var]) == int)] assert len(var_list) == len(set(var_list))
[ 2, 16529, 32501, 198, 2, 220, 220, 2488, 65, 3796, 25, 198, 2, 220, 220, 220, 220, 220, 220, 2896, 500, 617, 10425, 973, 1141, 10730, 198, 2, 220, 220, 2488, 9800, 25, 198, 2, 220, 220, 220, 220, 220, 220, 309, 278, 43812, 15233...
3.016588
422
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pytest import os from sedona.core.enums import FileDataSplitter, GridType, IndexType from sedona.core.enums.join_build_side import JoinBuildSide from sedona.core.spatialOperator import JoinQuery from sedona.core.spatialOperator.join_params import JoinParams from tests.spatial_operator.test_join_base import TestJoinBase from tests.tools import tests_resource input_location = os.path.join(tests_resource, "arealm-small.csv") input_location_query_window = os.path.join(tests_resource, "zcta510-small.csv") offset = 1 splitter = FileDataSplitter.CSV numPartitions = 11 distance = 0.01 query_polygon_set = os.path.join(tests_resource, "primaryroads-polygon.csv") inputCount = 3000 inputBoundary = -173.120769, -84.965961, 30.244859, 71.355134 rectangle_match_count = 103 rectangle_match_with_original_duplicates_count = 103 polygon_match_count = 472 polygon_match_with_original_duplicates_count = 562 parameters = [ dict(num_partitions=11, grid_type=GridType.QUADTREE), dict(num_partitions=11, grid_type=GridType.QUADTREE), dict(num_partitions=11, grid_type=GridType.KDBTREE), ]
[ 2, 220, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 220, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 220, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 220, 5115, 6634, 9238,...
3.20202
594
import os from typing import Union, Tuple import numpy as np import open3d as o3d import trimesh from easy_o3d.utils import get_camera_parameters_from_blenderproc_bopwriter, convert_depth_image_to_point_cloud from scipy.spatial.transform import Rotation from src.common import coord2index, normalize_coord, look_at, get_rotation_from_point, sample_point_on_upper_hemisphere from src.data.core import Field from src.utils import binvox_rw class IndexField(Field): """ Basic index field.""" def load(self, model_path, idx, category): """ Loads the index field. Args: model_path (str): mesh_path to model idx (int): ID of data point category (int): index of category """ return idx def check_complete(self, files): """ Check if field is complete. Args: files: files """ return True # 3D Fields class PatchPointsField(Field): """ Patch Point Field. It provides the field to load point data. This is used for the points randomly sampled in the bounding volume of the 3D shape and then split to patches. Args: file_name (str): file name transform (list): list of transformations which will be applied to the points tensor multi_files (callable): number of files """ def load(self, model_path, idx, vol): """ Loads the data point. Args: model_path (str): mesh_path to model idx (int): ID of data point vol (dict): precomputed volume info """ if self.multi_files is None: file_path = os.path.join(model_path, self.file_name) else: num = np.random.randint(self.multi_files) file_path = os.path.join(model_path, self.file_name, '%s_%02d.npz' % (self.file_name, num)) points_dict = np.load(file_path) points = points_dict['points'] # Break symmetry if given in float16: if points.dtype == np.float16: points = points.astype(np.float32) points += 1e-4 * np.random.randn(*points.shape) occupancies = points_dict['occupancies'] if self.unpackbits: occupancies = np.unpackbits(occupancies)[:points.shape[0]] occupancies = occupancies.astype(np.float32) # acquire the crop ind_list = [] for i in range(3): ind_list.append((points[:, i] >= vol['query_vol'][0][i]) & (points[:, i] <= vol['query_vol'][1][i])) ind = ind_list[0] & ind_list[1] & ind_list[2] data = {None: points[ind], 'occ': occupancies[ind]} if self.transform is not None: data = self.transform(data) # calculate normalized coordinate w.r.t. defined query volume p_n = {} for key in vol['plane_type']: # projected coordinates normalized to the range of [0, 1] p_n[key] = normalize_coord(data[None].copy(), vol['input_vol'], plane=key) data['normalized'] = p_n return data class PointsField(Field): """ Point Field. It provides the field to load point data. This is used for the points randomly sampled in the bounding volume of the 3D shape. Args: file_name (str): file name transform (list): list of transformations which will be applied to the points tensor multi_files (callable): number of files """ def load(self, model_path, idx, category): """ Loads the data point. Args: model_path (str): mesh_path to model idx (int): ID of data point category (int): index of category """ if self.multi_files is None: file_path = os.path.join(model_path, self.file_name) else: num = np.random.randint(self.multi_files) file_path = os.path.join(model_path, self.file_name, '%s_%02d.npz' % (self.file_name, num)) points_data = np.load(file_path) if isinstance(points_data, np.lib.npyio.NpzFile): points = points_data["points"] else: points = points_data[:, :3] # Break symmetry if given in float16: if points.dtype == np.float16: points = points.astype(np.float32) points += 1e-4 * np.random.randn(*points.shape) if isinstance(points_data, np.lib.npyio.NpzFile): occupancies = points_data["occupancies"] if self.unpackbits: occupancies = np.unpackbits(occupancies)[:points.shape[0]] occupancies = occupancies.astype(np.float32) elif self.occ_from_sdf: occupancies = (points_data[:, 3] <= 0).astype(np.float32) else: occupancies = points_data[:, 3] if occupancies.dtype == np.float16: occupancies = occupancies.astype(np.float32) occupancies += 1e-4 * np.random.randn(*occupancies.shape) data = {None: points, "occ": occupancies} if self.transform is not None: data = self.transform(data) return data class VoxelsField(Field): """ Voxel field class. It provides the class used for voxel-based data. Args: file_name (str): file name transform (list): list of transformations applied to data points """ def load(self, model_path, idx, category, use_trimesh: bool = False): """ Loads the data point. Args: model_path (str): mesh_path to model idx (int): ID of data point category (int): index of category use_trimesh (bool): Whether to use Trimesh to load the binvox file """ file_path = os.path.join(model_path, self.file_name) with open(file_path, 'rb') as f: if use_trimesh: voxels = trimesh.exchange.binvox.load_binvox(f) else: voxels = binvox_rw.read_as_3d_array(f) if not use_trimesh: voxels = voxels.data.astype(np.float32) if self.transform is not None: voxels = self.transform(voxels) return voxels class PatchPointCloudField(Field): """ Patch point cloud field. It provides the field used for patched point cloud data. These are the points randomly sampled on the mesh and then partitioned. Args: file_name (str): file name transform (list): list of transformations applied to data points multi_files (callable): number of files """ def load(self, model_path, idx, vol): """ Loads the data point. Args: model_path (str): mesh_path to model idx (int): ID of data point vol (dict): precomputed volume info """ if self.multi_files is None: file_path = os.path.join(model_path, self.file_name) else: num = np.random.randint(self.multi_files) file_path = os.path.join(model_path, self.file_name, '%s_%02d.npz' % (self.file_name, num)) pointcloud_dict = np.load(file_path) points = pointcloud_dict['points'].astype(np.float32) normals = pointcloud_dict['normals'].astype(np.float32) # add noise globally if self.transform is not None: data = {None: points, 'normals': normals} data = self.transform(data) points = data[None] # acquire the crop index ind_list = [] for i in range(3): ind_list.append((points[:, i] >= vol['input_vol'][0][i]) & (points[:, i] <= vol['input_vol'][1][i])) mask = ind_list[0] & ind_list[1] & ind_list[2] # points inside the input volume mask = ~mask # True means outside the boundary!! data['mask'] = mask points[mask] = 0.0 # calculate index of each point w.r.t. defined resolution index = {} for key in vol['plane_type']: index[key] = coord2index(points.copy(), vol['input_vol'], reso=vol['reso'], plane=key) if key == 'grid': index[key][:, mask] = vol['reso'] ** 3 else: index[key][:, mask] = vol['reso'] ** 2 data['ind'] = index return data class PointCloudField(Field): """ Point cloud field. It provides the field used for point cloud data. These are the points randomly sampled on the mesh. Args: file_name (str): file name transform (list): list of transformations applied to data points multi_files (callable): number of files """ def load(self, model_path, idx, category): """ Loads the data point. Args: model_path (str): mesh_path to model idx (int): ID of data point category (int): index of category """ if self.multi_files is None: file_path = os.path.join(model_path, self.file_name) else: num = np.random.randint(self.multi_files) file_path = os.path.join(model_path, self.file_name, '%s_%02d.npz' % (self.file_name, num)) pointcloud_dict = np.load(file_path) if isinstance(pointcloud_dict, np.lib.npyio.NpzFile): points = pointcloud_dict["points"].astype(np.float32) normals = pointcloud_dict["normals"].astype(np.float32) else: points = pointcloud_dict.astype(np.float32) normals = None data = {None: points} if normals is not None: data["normals"] = normals if self.transform is not None: data = self.transform(data) return data class PartialPointCloudField(Field): """ Partial Point cloud field. It provides the field used for partial point cloud data. These are the points randomly sampled on the mesh and a bounding box with random size is applied. Args: file_name (str): file name transform (torch.): list of transformations applied to data points multi_files (callable): number of files part_ratio (float): max ratio for the remaining part """ def load(self, model_path, idx, category): """ Loads the data point. Args: model_path (str): mesh_path to model idx (int): ID of data point category (int): index of category """ if self.multi_files is None: file_path = os.path.join(model_path, self.file_name) else: num = np.random.randint(self.multi_files) file_path = os.path.join(model_path, self.file_name, '%s_%02d.npz' % (self.file_name, num)) pointcloud_dict = np.load(file_path) if isinstance(pointcloud_dict, np.lib.npyio.NpzFile): points = pointcloud_dict['points'].astype(np.float32) normals = pointcloud_dict['normals'].astype(np.float32) else: points = pointcloud_dict.astype(np.float32) normals = None rot = np.eye(3) if self.rotate_object: angles = np.random.uniform(360, size=len(self.rotate_object) if len(self.rotate_object) > 1 else None) rot = Rotation.from_euler(self.rotate_object, angles, degrees=True).as_matrix() points = (rot @ points.T).T if normals is not None: normals = (rot @ normals.T).T if self.axes == "xyz": side = np.random.randint(3) else: side = list() if 'x' in self.axes: side.append(0) if 'y' in self.axes: side.append(1) if 'z' in self.axes: side.append(2) side = np.random.choice(side) xb = [points[:, side].min(), points[:, side].max()] if isinstance(self.part_ratio, float): length = np.random.uniform(self.part_ratio * (xb[1] - xb[0]), (xb[1] - xb[0])) elif isinstance(self.part_ratio, (tuple, list)): length = np.random.uniform(self.part_ratio[0] * (xb[1] - xb[0]), self.part_ratio[1] * (xb[1] - xb[0])) else: raise TypeError indices = (points[:, side] - xb[0]) > length points = points[indices] if normals is not None: normals = normals[indices] if self.rotate_object: points = (rot.T @ points.T).T if normals is not None: normals = (rot.T @ normals.T).T data = {None: points.astype(np.float32), "rot": rot} if normals is not None: data["normals"] = normals.astype(np.float32) if self.transform is not None: data = self.transform(data) return data
[ 11748, 28686, 198, 6738, 19720, 1330, 4479, 11, 309, 29291, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1280, 18, 67, 355, 267, 18, 67, 198, 11748, 491, 999, 71, 198, 6738, 2562, 62, 78, 18, 67, 13, 26791, 1330, 651, 62, ...
2.16532
5,940
#!usr/bin/env python # -*- coding:utf-8 -*- """ @author:sqin @file: serializes.py @time: 2019/01/02 """ from flask_marshmallow import Schema from marshmallow import fields from .models import * from . import ma
[ 2, 0, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 9800, 25, 31166, 259, 198, 31, 7753, 25, 11389, 4340, 13, 9078, 198, 31, 2435, 25, 13130, 14, 486, 14, 299...
2.766234
77
import pytest from django.contrib.auth.models import User from django.utils.datetime_safe import datetime from mixer.backend.django import mixer from escola.models import Turma, Profile, Aluno, Professor, MateriaDaTurma, CargoTurma, Horario from escola.utils import dar_permissao_user pytestmark = pytest.mark.django_db
[ 11748, 12972, 9288, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 26791, 13, 19608, 8079, 62, 21230, 1330, 4818, 8079, 198, 6738, 33938, 13, 1891, 437, 13, 28241, 14208, 1330, 33...
3.114286
105
from .ACE import settings as st from .ACE.encoder import Encoder from .netNormExtended import netNormExtended from .utilities import * """ The implementation of RESNets framework. Details can be found in the original paper: will be filled when accepted --------------------------------------------------------------------- This file contains the implementation of three key steps of our RESNets framework: (1) Embedding of baseline population and test subject, (2) Building of CBT of the population and embedding of the CBT (3) Selection of top K similar subject at baseline and prediction of follow up data: test_trajectory = RESNets(testing_subject, baseline_population, follow_up_data, K, n_r) Inputs: n_r: number of regions of interest(ROIs) n_s: number of subjects n_t: number of follow-up timepoints n_f: size of feature vector = (n_r * (n_r - 1) / 2) test_subject = row vector with dimension (1 x n_f) baseline_population: matrix of feature vectors (n_s x n_f) follow_up_data: Tensor of populations (n_t x n_s x n_f) K: number of similar subjects to be selected when predicting follow-up trajectory n_r: number of regions of interest(ROIs) Outputs: test_trajectory: prediction of test subject at each timepoint (n_t x n_f) To evaluate our framework we used Leave-One-Out cross validation strategy. To test RESNets on random data, we defined the function 'simulateData' where the size of the dataset is chosen by the user. --------------------------------------------------------------------- Copyright 2020 Ahmet Serkan Göktaş, Istanbul Technical University. Please cite the above paper if you use this python code. All rights reserved. """
[ 6738, 764, 11598, 1330, 6460, 355, 336, 198, 6738, 764, 11598, 13, 12685, 12342, 1330, 14711, 12342, 198, 6738, 764, 3262, 35393, 11627, 1631, 1330, 2010, 35393, 11627, 1631, 198, 6738, 764, 315, 2410, 1330, 1635, 198, 198, 37811, 198, ...
2.455607
856
from .is_openff_Molecule import is_openff_Molecule from .to_molsysmt_MolSys import to_molsysmt_MolSys from .to_molsysmt_Topology import to_molsysmt_Topology from .to_molsysmt_Structures import to_molsysmt_Structures from .to_openff_Topology import to_openff_Topology from .to_openmm_Topology import to_openmm_Topology
[ 6738, 764, 271, 62, 9654, 487, 62, 44, 2305, 23172, 1330, 318, 62, 9654, 487, 62, 44, 2305, 23172, 198, 6738, 764, 1462, 62, 76, 10220, 893, 16762, 62, 44, 349, 44387, 1330, 284, 62, 76, 10220, 893, 16762, 62, 44, 349, 44387, 198,...
2.572581
124
from .my_api import test_api from flask import Flask
[ 6738, 764, 1820, 62, 15042, 1330, 1332, 62, 15042, 198, 6738, 42903, 1330, 46947, 628 ]
3.6
15
#!/usr/bin/env python3 -B from PIL import Image from utils import lerp, ccir601 import sys if __name__ == "__main__": im1 = Image.open(sys.argv[1]) im2 = Image.open(sys.argv[2]) pal1 = sorted(getcolors(im1), key=ccir601) pal2 = sorted(getcolors(im2), key=ccir601) im = Image.new('RGB', (16, 16)) pix = im.load() for y in range(16): for x in range(16): r = lerp(pal1[x][0], pal2[x][0], float(y) / 15) g = lerp(pal1[x][1], pal2[x][1], float(y) / 15) b = lerp(pal1[x][2], pal2[x][2], float(y) / 15) pix[x, y] = (int(r), int(g), int(b)) im.save(sys.argv[3], 'PNG')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 532, 33, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 3384, 4487, 1330, 300, 263, 79, 11, 36624, 343, 41706, 198, 11748, 25064, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 8...
1.88
350
import time from threading import Thread if __name__ == "__main__": Main()
[ 11748, 640, 198, 6738, 4704, 278, 1330, 14122, 628, 220, 220, 220, 220, 220, 220, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 8774, 3419, 198, 220, 220, 198 ]
2.588235
34
from typing import Any import aiosqlite from chia.util.byte_types import hexstr_to_bytes from chia.util.db_wrapper import DBWrapper from chia.util.streamable import Streamable class KeyValStore: """ Multipurpose persistent key-value store """ db_connection: aiosqlite.Connection db_wrapper: DBWrapper @classmethod async def get_object(self, key: str, type: Any) -> Any: """ Return bytes representation of stored object """ cursor = await self.db_connection.execute("SELECT * from key_val_store WHERE key=?", (key,)) row = await cursor.fetchone() await cursor.close() if row is None: return None return type.from_bytes(hexstr_to_bytes(row[1])) async def set_object(self, key: str, obj: Streamable): """ Adds object to key val store """ async with self.db_wrapper.lock: cursor = await self.db_connection.execute( "INSERT OR REPLACE INTO key_val_store VALUES(?, ?)", (key, bytes(obj).hex()), ) await cursor.close() await self.db_connection.commit()
[ 6738, 19720, 1330, 4377, 198, 198, 11748, 257, 4267, 13976, 578, 198, 198, 6738, 442, 544, 13, 22602, 13, 26327, 62, 19199, 1330, 17910, 2536, 62, 1462, 62, 33661, 198, 6738, 442, 544, 13, 22602, 13, 9945, 62, 48553, 1330, 20137, 3691...
2.368209
497
import os import openai class GPT: """Base object for GPT-3 completions""" api_key = os.environ.get('OPENAI_API_KEY') @classmethod def requires_key(cls, func): """Decorator function which allows passing API key as keyword argument""" return wrapped
[ 11748, 28686, 198, 198, 11748, 1280, 1872, 628, 198, 4871, 402, 11571, 25, 198, 220, 220, 220, 37227, 14881, 2134, 329, 402, 11571, 12, 18, 1224, 45240, 37811, 628, 220, 220, 220, 40391, 62, 2539, 796, 28686, 13, 268, 2268, 13, 1136, ...
2.733333
105
from transformers import BertTokenizerFast model_path = '/Users/joezhao/Documents/pretrain model/chinese_roberta_wwm_ext_L-12_H-768_A-12' tokenizer = BertTokenizerFast.from_pretrained(model_path) print(tokenizer.decode(tokenizer('朝阳区嘉翔大厦A座0000室')['input_ids']))
[ 6738, 6121, 364, 1330, 22108, 30642, 7509, 22968, 198, 198, 19849, 62, 6978, 796, 31051, 14490, 14, 73, 2577, 89, 23778, 14, 38354, 14, 5310, 3201, 2746, 14, 354, 3762, 62, 305, 4835, 64, 62, 1383, 76, 62, 2302, 62, 43, 12, 1065, ...
2.348214
112
from collections import Mapping, MutableMapping
[ 6738, 17268, 1330, 337, 5912, 11, 13859, 540, 44, 5912, 628 ]
4.454545
11
""" Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true """ # V0 # IDEA : STACK + DICT # @return a boolean # V0' # IDEA : STACK + DICT # V1 # https://blog.csdn.net/coder_orz/article/details/51697963 # IDEA : STACK # V1' # https://blog.csdn.net/coder_orz/article/details/51697963 # IDEA : STACK # V1'' # @return a boolean # if __name__ == "__main__": # print(Solution().isValid("()[]{}")) # print(Solution().isValid("()[{]}")) # V2 # Time: O(n) # Space: O(n) # @return a boolean
[ 37811, 198, 198, 15056, 257, 4731, 7268, 655, 262, 3435, 29513, 3256, 705, 8, 3256, 705, 90, 3256, 705, 92, 3256, 705, 17816, 290, 705, 60, 3256, 220, 198, 67, 2357, 3810, 611, 262, 5128, 4731, 318, 4938, 13, 198, 198, 2025, 5128, ...
2.53125
384
import time import os import re def counter(file = 'README.md'): """ read .md or .txt format file :param file: .md or .txt format file :return: data """ num = 0 with open(file, 'r', encoding='UTF-8') as f: lines = f.readlines() for line in lines: p1 = re.compile(r'[{](.*?)[}]', re.S) # 最小匹配 if re.findall(p1, line): num += int(re.findall(p1, line)[0]) return num # write_num('README.md') if __name__ == '__main__': write_num('README.md') # extract_reference('./2019/02') # extract_cite('./2019/02')
[ 11748, 640, 198, 11748, 28686, 198, 11748, 302, 198, 4299, 3753, 7, 7753, 796, 705, 15675, 11682, 13, 9132, 6, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1100, 764, 9132, 393, 764, 14116, 5794, 2393, 198, 220, 220, 220, 10...
2.096429
280
# Christopher Ryba, 2016 # This code calculates the character values \chi_\mu^\lambda of the # symmetric groups. Here \lambda and \mu are partitions of the same size, # represented as either lists or tuples of integers without trailing zeros. # The function that returns the character value is char_val, so an example # use might be char_val([4,1],[3,1,1]), which would return 1, indicating # that the character value of a 3-cycle on the standard representation of # S_5 is equal to 1. The algorithm is a combination of the # Murnaghan-Nakayama rule and the hook-length formula. # This helper function takes a partition and a skew-hook, and returns # the partition obtained by removing the skew-hook from the partition. # For the sake of efficiency, calculated character values are stored in a # dictionary so they do not need to be recomputed later ("memoisation"). # Initially we only have the base case of the trivial group S_0. chardict = {} chardict[( tuple([]) , tuple([]) )] = 1 # This helper function finds the dual (or transpose) partition. # Given a partition, this function returns the dimension of the corresponding # irreducible representation of the symmetric group using the hook-length formula. from math import factorial # This function calculuates character values of the symmetric groups for the # irreducible representation char at an element of cycle type elt.
[ 2, 12803, 11089, 7012, 11, 1584, 198, 198, 2, 770, 2438, 43707, 262, 2095, 3815, 3467, 11072, 62, 59, 30300, 61, 59, 50033, 286, 262, 220, 198, 2, 23606, 19482, 2628, 13, 3423, 3467, 50033, 290, 3467, 30300, 389, 43869, 286, 262, 97...
3.994253
348
import sqlite3 from sqlite3 import Error import pathlib import logging import sys import os, shutil import time from pydriller import GitRepository from Model_commits_info import Model_commits_info_Controller from Project_commits_info import Project_commits_info_Controller from Project_commits_verbatim import Project_commits_verbatim_Controller from Model_commits_verbatim import Model_commits_verbatim_Controller logging.basicConfig(filename='commits.log', filemode='a', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) #logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) from get_model_level_commits import get_model_level_commits from get_project_level_commits import get_project_level_commits def create_connection(db_file): """ create a database connection to the SQLite database specified by the db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn def get_repo_id_urls(conn): """ Query tasks :param conn: the Connection object :param :return: """ cur = conn.cursor() cur.execute("SELECT id,project_url,model_files,version_sha FROM GitHub_Projects ") rows = cur.fetchall() return rows if __name__ == '__main__': main()
[ 11748, 44161, 578, 18, 198, 6738, 44161, 578, 18, 1330, 13047, 198, 11748, 3108, 8019, 198, 11748, 18931, 198, 11748, 25064, 198, 11748, 28686, 11, 4423, 346, 198, 11748, 640, 198, 198, 6738, 279, 5173, 81, 4665, 1330, 15151, 6207, 1326...
2.774067
509
""" The wappsto encoding module. Handles encoding object instances to a JSON file. """ import logging from ..connection.seluxit_rpc import SeluxitRpc class WappstoEncoder: """ The wappsto encoding class. Handles encoding the current runtime object instances into JSON. This allows the system to be saved as a parsable JSON file similar to the one used to start the package. """ def __init__(self): """ Initialize WappstoEncoder. Initializes the WappstoEncoder class. """ self.wapp_log = logging.getLogger(__name__) self.wapp_log.addHandler(logging.NullHandler()) def encode_network(self, network): """ Encode instance of Network class. Handles the encoding of the network instance, contains a template to encode the network with. Args: network: Reference to the instance of the Network class. Returns: The dictionary. """ encoded_devices = [] for device in network.devices: encoded_device = self.encode_device(device) encoded_devices.append(encoded_device) encoded_network = { 'name': network.name, 'device': encoded_devices, 'meta': { 'id': network.uuid, 'version': '2.0', 'type': 'network' } } if SeluxitRpc.is_upgradable(): encoded_network.get('meta').update({'upgradable': True}) self.wapp_log.debug("Network JSON: {}".format(encoded_network)) return encoded_network def encode_device(self, device): """ Encode instance of Device class. Handles the encoding of the device instance, contains a template to encode the device with. Args: device: Reference to the instance of the Device class. Returns: The dictionary. """ encoded_values = [] for value in device.values: encoded_value = self.encode_value(value) encoded_values.append(encoded_value) encoded_device = { 'name': device.name, 'product': device.product, 'protocol': device.protocol, 'serial': device.serial_number, 'manufacturer': device.manufacturer, 'communication': device.communication, 'description': device.description, 'version': device.version, 'value': encoded_values, 'meta': { 'id': device.uuid, 'version': '2.0', 'type': 'device' } } self.wapp_log.debug("Device JSON: {}".format(encoded_device)) return encoded_device def encode_value(self, value): """ Encode instance of Value class. Handles the encoding of the value instance, contains a template to encode the value with. Args: value: Reference to the instance of the Value class. Returns: The dictionary. """ states = [] if value.report_state: encoded_state = self.encode_state( value.report_state ) states.append(encoded_state) if value.control_state: encoded_state = self.encode_state( value.control_state ) states.append(encoded_state) if value.data_type == 'string': details = { 'encoding': value.string_encoding, 'max': value.string_max } elif value.data_type == 'blob': details = { 'encoding': value.blob_encoding, 'max': value.blob_max } elif value.data_type == 'number': details = { 'min': value.number_min, 'max': value.number_max, 'step': value.number_step, 'unit': value.number_unit } encoded_value = { 'name': value.name, 'type': value.type_of_value, 'permission': value.permission, 'state': states, value.data_type: details, 'meta': { 'id': value.uuid, 'type': 'value', 'version': '2.0' } } self.wapp_log.debug("Value JSON: {}".format(encoded_value)) return encoded_value def encode_state(self, state): """ Encode instance of State class. Handles the encoding of the state instance, contains a template to encode the state with. Args: state: Reference to the instance of the State class. Returns: The dictionary. """ encoded_state = { 'data': state.data, 'type': state.state_type, 'timestamp': state.timestamp, 'meta': { 'id': state.uuid, 'type': 'state', 'version': '2.0', 'contract': [] } } self.wapp_log.debug("State JSON: {}".format(encoded_state)) return encoded_state
[ 37811, 198, 464, 266, 1324, 301, 78, 21004, 8265, 13, 198, 198, 12885, 829, 21004, 2134, 10245, 284, 257, 19449, 2393, 13, 198, 37811, 198, 11748, 18931, 198, 6738, 11485, 38659, 13, 741, 2821, 270, 62, 81, 14751, 1330, 15300, 2821, 2...
2.030199
2,616
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import TwilioTaskRouterClient # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" workspace_sid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" worker_sid = "WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" reservation_sid = 'WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' client = TwilioTaskRouterClient(account_sid, auth_token) # accept a reservation reservation = client.workers(workspace_sid) \ .get(worker_sid).reservations \ .update(reservation_sid, reservation_status='accepted') print(reservation.reservation_status) print(reservation.worker_name)
[ 2, 10472, 262, 11361, 31904, 5888, 422, 665, 346, 952, 13, 785, 14, 31628, 14, 29412, 14, 17350, 198, 6738, 665, 346, 952, 13, 2118, 1330, 1815, 346, 952, 25714, 49, 39605, 11792, 198, 198, 2, 3406, 10781, 15686, 290, 26828, 29130, ...
3.15859
227
#!/usr/bin/env python3 from collections import OrderedDict assert make_palindrome("") == "" assert make_palindrome("a") == "a" assert make_palindrome("aab") == "aba" assert make_palindrome("aaa") == "aaa" assert(make_palindrome("bbaa")) == "baab" assert(make_palindrome("aaaabbc")) == "aabcbaa" assert(make_palindrome("bab")) == "bab"
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 30493, 787, 62, 18596, 521, 5998, 7203, 4943, 6624, 13538, 198, 30493, 787, 62, 18596, 521, 5998, 7203, 64, 4943, 6624, 366,...
2.612403
129
from setuptools import setup, find_packages import carton with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name='py3-django-enriched-carton', version=carton.__version__, description=carton.__doc__, packages=find_packages(), url='https://github.com/knyazz/py3-django-enriched-carton', author='smirnov.ev', author_email='knyazz@gmail.com', classifiers=[ 'Programming Language :: Python', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', 'Intended Audience :: Developers', 'Development Status :: 4 - Beta' ], install_requires=[ 'Django>=3.2.0', ], long_description=long_description, long_description_content_type='text/markdown', include_package_data=True, )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 11748, 6383, 261, 628, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 1600, 21004, 2625, 40477, 12, 23, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 8...
2.561798
356
from model.project import Project testdata = [ Project(name="name1", description="1"), Project(name="name2", description="2") ]
[ 6738, 2746, 13, 16302, 1330, 4935, 628, 198, 9288, 7890, 796, 685, 198, 220, 220, 220, 4935, 7, 3672, 2625, 3672, 16, 1600, 6764, 2625, 16, 12340, 198, 220, 220, 220, 4935, 7, 3672, 2625, 3672, 17, 1600, 6764, 2625, 17, 4943, 198, ...
3.066667
45
#!/usr/bin/env/ python # coding=utf-8 __author__ = 'Achelics' __Date__ = '2017/05/16' from data_pre_process.split_banner_man import * import os import json as _json def get_ip_banner(path, filename, protocol_validity_json): """ 提取ip和标语 :param path: 标语文件所在路径 :param filename: 标语文件名称 :param protocol_validity_json: 标语文件合法提取函数 :return: """ file_name = os.path.join(path, filename) resultname = filename.split('.')[0] + '_clear.json' result_name = os.path.join(path, resultname) result_file = open(result_name, 'a') with open(file_name, 'r') as f: for line in f: raw_data = _json.loads(line.strip('\n'), strict=False) ip = raw_data['ip'] result = protocol_validity_json(raw_data) if result["banner_flag"]: banner = result["banner_string"] result_file.write(str(ip) + '卍' + str(banner) + '\n') else: result_file.write(str(ip) + '\n') f.close() result_file.close() def get_only_banner(path, filename): """ 提取ip存在的标语 :param path: 标语文件所在路径 :param filename: 标语文件名称 :return: """ file_name = os.path.join(path, filename) resultname = filename.split('.')[0] + '_only_banner.json' result_name = os.path.join(path, resultname) result_file = open(result_name, 'a') with open(file_name, 'r') as f: for line in f: raw_data = line.strip('\n') if '卍' in raw_data: result_file.write(line) f.close() result_file.close() if __name__ == '__main__': path = r'F:\mutil_result\five_protocol\five_protocol_all' banner_name = ['banner21.json', 'banner22.json', 'banner23.json', 'banner80.json', 'banner554.json'] protocol_json_list = [ftp_validity_json, ssh_validity_json, telnet_validity_json, http_validity_json, rtsp_validity_json] clear_name = ['banner21_clear.json', 'banner22_clear.json', 'banner23_clear.json', 'banner80_clear.json', 'banner554_clear.json'] # for i in range(0, len(clear_name)): # process = multiprocessing.Process(target=get_ip_banner, args=(path, banner_name[i], protocol_json_list[i])) # process.start() for i in range(0, len(clear_name)): process = multiprocessing.Process(target=get_only_banner, args=(path, clear_name[i])) process.start()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 14, 21015, 198, 2, 19617, 28, 40477, 12, 23, 198, 834, 9800, 834, 796, 705, 32, 2395, 677, 82, 6, 198, 834, 10430, 834, 796, 705, 5539, 14, 2713, 14, 1433, 6, 198, 198, 6738, 1366, 62, 3866,...
2.038429
1,171
import os
[ 11748, 28686 ]
4.5
2
import requirements from requirements import * engine = pyttsx3.init('sapi5') client = wolframalpha.Client('33UPA7-YGAUU4EYQA') voices = engine.getProperty('voices') #engine.setProperty('voice', voices[2].id) engine.setProperty('voices',voices[len(voices)-1]) #engine.setProperty('voice', voices[1].id) engine.setProperty('rate', 135) greetme() speak('Hello , I am digital assistant! ') #speak('How May I Help You?') if __name__ == '__main__': while True: query = command(); query = query.lower() if 'date' in query: today =datetime.datetime.now().today speak(today) #today = int(today) month = datetime.datetime.now().month speak(month) year= datetime.datetime.now().year speak(year) print(today,":",month,":",year) elif 'time' in query: hour = int(datetime.datetime.now().hour) minute = int(datetime.datetime.now().minute) sec = int(datetime.datetime.now().second) speak(hour) speak(minute) speak(sec) print(hour,":",minute,":",sec) elif 'instagram' or 'ig'in query: speak('Opening Instagram!') from instagram import insta insta() elif 'whatsapp' in query: speak('Opening whatsapp!') from whatsapp import whatsapp whatsapp() elif 'facebook' or 'fb' in query: speak('Opening Facebook!') from facebook import fb fb() elif 'send eamil' or 'mail' or 'email' in query: speak('Intializing Process To Send Email!') from email_bot import email_bot email_bot() elif 'voice recorder' or 'record voice' or 'record sound' or 'sound recorder' in query: speak('Starting Sound recorder') from Sound_Recorder import Sound_Recorder Sound_Recorder() elif 'paly music' or 'play some music' or 'music player' in query: speak('Starting Music player') from Music_Player import Music_Player Music_Player() elif 'movie rating' 'get movie rating' or 'movie details' in query: speak('Getting Details Using IMBD') from Movie_Rating import Movie_Rating Movie_Rating() elif 'pencil art' in query: speak('Intializing Process For Pencil Art') from pencil_art import pencil_art pencil_art() elif 'vector art' in query: speak('Intializing Process For Vector Art') from vector_art import vector_art vector_art() elif 'screen recorder' in query: speak('Starting Screen recorder') from Screen_Recorder import Screen_Recorder Screen_Recorder() elif 'twitter' in query: speak('Opening twitter') from twitter import twitter twitter() elif 'close' or 'bye' or 'exit' in query: sys.exit() else: query = query speak("searching") try: res = client.query(query) results = next(res.results).text speak(results) print(results) except: results = wikipedia.summary(query) speak('Getting Details From Wikipedia') speak(results) print(results) speak("NEXT COMMAND ")
[ 11748, 5359, 201, 198, 6738, 5359, 1330, 1635, 201, 198, 201, 198, 18392, 796, 12972, 83, 912, 87, 18, 13, 15003, 10786, 82, 15042, 20, 11537, 201, 198, 201, 198, 16366, 796, 17481, 859, 26591, 13, 11792, 10786, 2091, 52, 4537, 22, ...
2.03801
1,789
# 无参数 print_hello() # 带参数 fuckfuck r = print_str("fuck") print(r) # 带默认参数 print_default() print_default("default") # 不定长参数 print_args("hello") print_args("hello", "world", "1") # 参数次序可以变 print_two(a="a", b="b") print_two(b="b", a="a")
[ 2, 10545, 245, 254, 20998, 224, 46763, 108, 628, 198, 4798, 62, 31373, 3419, 628, 198, 2, 10263, 116, 99, 20998, 224, 46763, 108, 220, 5089, 31699, 628, 198, 81, 796, 3601, 62, 2536, 7203, 31699, 4943, 198, 4798, 7, 81, 8, 628, 19...
1.671053
152
''' Get the coordinates of a wikipage from some KML. Joe Collins 26 March 2011 ''' import re # for regular expressions import string kml = '''<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.1"> <Document> <name><![CDATA[Bedford Museum & Art Gallery]]></name> <open>1</open> <Folder> <name><![CDATA[External links]]></name> <open>1</open> <Placemark> <name><![CDATA[Bedford Museum & Art Gallery]]></name> <Point> <coordinates>-0.46408,52.13607,0</coordinates> </Point> <Snippet></Snippet> <description><![CDATA[<br>Source: Wikipedia article <a href="http://en.wikipedia.org/wiki/Bedford_Museum_&_Art_Gallery">Bedford Museum & Art Gallery</a>]]></description> </Placemark> </Folder> </Document> </kml>''' coordinates = re.search('(?<=<coordinates>)(.*?)(?=</coordinates>)', kml) # <coordinates>-0.46408,52.13607,0</coordinates> lat = lng = None if coordinates != None: lat = string.split(coordinates.group(), ',')[1] lng = string.split(coordinates.group(), ',')[0] print "lat:" + lat + " Lng:" + lng raw_input("Press ENTER to exit")
[ 7061, 6, 198, 3855, 262, 22715, 286, 257, 47145, 541, 496, 422, 617, 509, 5805, 13, 198, 198, 19585, 14006, 198, 2075, 2805, 2813, 198, 198, 7061, 6, 198, 11748, 302, 1303, 329, 3218, 14700, 198, 11748, 4731, 198, 74, 4029, 796, 705...
2.497748
444
from ProjectEulerCommons.Base import * Answer( count_summation_way(200, [200, 100, 50, 20, 10, 5, 2, 1]) ) """ ------------------------------------------------ ProjectEuler.Problem.031.py The Answer is: 73682 Time Elasped: 0.07277131080627441sec ------------------------------------------------ """
[ 6738, 4935, 36, 18173, 6935, 684, 13, 14881, 1330, 1635, 198, 198, 33706, 7, 198, 220, 220, 220, 954, 62, 82, 13929, 341, 62, 1014, 7, 2167, 11, 685, 2167, 11, 1802, 11, 2026, 11, 1160, 11, 838, 11, 642, 11, 362, 11, 352, 12962,...
3.270833
96
from __future__ import unicode_literals from django.apps import AppConfig
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.75
20
#!/usr/bin/env python import sys import logging import os from tuna.runners import AllenNlpRunner from tuna.executors import RayExecutor if os.environ.get("TUNA_DEBUG"): LEVEL = logging.DEBUG else: LEVEL = logging.INFO logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", level=LEVEL ) if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 28686, 198, 198, 6738, 38883, 13, 36740, 1330, 9659, 45, 34431, 49493, 198, 6738, 38883, 13, 18558, 315, 669, 1330, 7760, 23002, 38409, 198, ...
2.590278
144
from django.urls import path, re_path from . import views urlpatterns = [path('', views.index, name="inicio"), path('vista', views.vista), re_path(r'^claves/(?P<clave>[0-9]{4}$)', views.clave), path('claves/<int:numero>', views.numero), path('claves/<str:nombre>', views.saluda), path('json', views.respuesta_json), path('contenido', views.contenido), path('error', views.error), path('listas', views.listas)]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 302, 62, 6978, 220, 201, 198, 6738, 764, 1330, 5009, 201, 198, 201, 198, 201, 198, 6371, 33279, 82, 796, 685, 6978, 10786, 3256, 5009, 13, 9630, 11, 1438, 2625, 259, 46441, 12340, 22...
1.898955
287
#!/usr/bin/env python3 ###################################### # Steem Peers Scanner - Main Python Script # Part of https://github.com/someguy123/steem-peers # # Usage: # # sudo -H pip3 install -r requirements.txt # sudo ./update_geoip.sh # sudo ./peers.py # # # Environment Options (place in .env or pass on command line): # # USE_DOCKER [true] - Boolean (true/false/1/0) - true = scan peers inside of docker container $DOCKER_NAME # - false = scan peers on the host running this script # # DOCKER_NAME [seed] - String - If USE_DOCKER is true, this is the name of the container to scan peers inside # # License: AGPL v3 # (C) 2020 Someguy123 / Privex Inc. ###################################### import sys from privex.helpers import ErrHelpParser from os import path from steempeers import settings from steempeers.core import set_log_level, detect_geoip from steempeers.scanner import PeerScanner parser = ErrHelpParser(description='Linux Peer Scanner (C) 2020 Someguy123') parser.add_argument('-c', '--container', default=settings.DOCKER_NAME, type=str, dest='container') parser.add_argument('--geoip-dir', default=settings.GEOIP_DIR, type=str, dest='geoip_dir') parser.add_argument('--geoasn', default=settings.GEOASN_NAME, type=str) parser.add_argument('--geocity', default=settings.GEOCITY_NAME, type=str) parser.add_argument('-l', '--log-level', default=settings.LOG_LEVEL, type=str, dest='log_level') parser.add_argument( '-d', '--use-docker', action='store_true', default=settings.USE_DOCKER, dest='use_docker' ) parser.add_argument( '-k', '--no-docker', action='store_false', default=settings.USE_DOCKER, dest='use_docker' ) try: args = parser.parse_args() except Exception: parser.error('Failed parsing arguments') sys.exit(1) settings.GEOASN_NAME, settings.GEOCITY_NAME = args.geoasn, args.geocity settings.GEOIP_DIR = args.geoip_dir[:-1] if args.geoip_dir.endswith('/') else args.geoip_dir settings.LOG_LEVEL = args.log_level settings.USE_DOCKER = args.use_docker settings.DOCKER_NAME = args.container log = set_log_level(settings.LOG_LEVEL) settings.GEOCITY, settings.GEOASN = path.join(settings.GEOIP_DIR, settings.GEOCITY_NAME), path.join(settings.GEOIP_DIR, settings.GEOASN_NAME) settings.GEOCITY, settings.GEOASN = detect_geoip(geoasn=settings.GEOCITY, geocity=settings.GEOASN) PeerScanner().run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 29113, 4242, 2235, 198, 2, 2441, 368, 2631, 364, 20937, 1008, 532, 8774, 11361, 12327, 220, 198, 2, 2142, 286, 3740, 1378, 12567, 13, 785, 14, 11246, 22932, 10163, 14, 4169, 368, ...
2.688196
898
from ...factory.factory import UefiCallFactory from .ReadSaveState import ReadSaveStateCall from .WriteSaveState import WriteSaveStateCall SmmCpuCallsFactory = UefiCallFactory() SmmCpuCallsFactory.register('ReadSaveState', ReadSaveStateCall) SmmCpuCallsFactory.register('WriteSaveState', WriteSaveStateCall)
[ 6738, 2644, 69, 9548, 13, 69, 9548, 1330, 471, 891, 72, 14134, 22810, 198, 198, 6738, 764, 5569, 16928, 9012, 1330, 4149, 16928, 9012, 14134, 198, 6738, 764, 16594, 16928, 9012, 1330, 19430, 16928, 9012, 14134, 198, 198, 50, 3020, 34, ...
3.237113
97
#!/usr/bin/env python # Copyright (C) 2013 Jive Software. All rights reserved. """Context manager marking a path with a .lock directory for exclusive access. """ import os import time class Error(Exception): """Base exception class for this module.""" class ProtectedFilePath(object): """Context manager for exclusive access to a file path.""" WAIT_INTERVALS_SEC = (0.1, 0.2, 0.3, 0.5, 0.7, 1.0) def __init__(self, file_path, noop=False): """Initialize the ProtectedFilePath context manager.""" self.file_path = file_path self.lockdir_path = '{}.lock'.format(self.file_path) self.noop = noop def __enter__(self): """Control access to 'afile' using lock dir 'afile.lock'.""" if not self.noop: for interval in self.WAIT_INTERVALS_SEC: try: os.mkdir(self.lockdir_path) break except OSError: time.sleep(interval) else: raise Error('Cannot create lock directory at {}.'.format( self.lockdir_path)) def __exit__(self, exception_type, exception_value, traceback): """On exit, remove the lock.""" if not self.noop: try: os.rmdir(self.lockdir_path) except IOError, err: raise Error('Cannot remove lock directory at {}:\n{}'.format( self.lockdir_path, err))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 357, 34, 8, 2211, 449, 425, 10442, 13, 1439, 2489, 10395, 13, 198, 198, 37811, 21947, 4706, 18730, 257, 3108, 351, 257, 764, 5354, 8619, 329, 8568, 1895, 13, 198, 37811, 19...
2.46679
542
from pygame.draw import aaline from math import ceil
[ 6738, 12972, 6057, 13, 19334, 1330, 257, 20663, 198, 6738, 10688, 1330, 2906, 346 ]
3.714286
14
from spddb import * db = ziverdb("hello.db") db.insert("hello", "world") print db.have("hello") == True print db.get("hello") == "world" print db.getsize() == 18 print db.getkeys() == ['hello'] db.delete("hello") print db.have("hello") == False print db.get("hello") == False print db.getsize() == 2 os.remove("hello.db") db = ziverdb("hello.db") db.insert("hello", "world") db.drop("hello.db") try: size = db.getsize() except Exception, e: print True else: print False
[ 6738, 599, 1860, 65, 1330, 1635, 220, 628, 198, 198, 9945, 796, 1976, 1428, 9945, 7203, 31373, 13, 9945, 4943, 198, 198, 9945, 13, 28463, 7203, 31373, 1600, 366, 6894, 4943, 628, 198, 198, 4798, 20613, 13, 14150, 7203, 31373, 4943, 66...
2.574359
195
import os from deep_rl.actor_critic import Unreal as UnrealTrainer, UnrealAgent from deep_rl.actor_critic.unreal.unreal import without_last_item from deep_rl.actor_critic.unreal.utils import autocrop_observations from deep_rl.utils import KeepTensor, detach_all, expand_time_dimension, pytorch_call from deep_rl.common.pytorch import to_tensor from torch.nn import functional as F from configuration import configuration import torch
[ 11748, 28686, 198, 6738, 2769, 62, 45895, 13, 11218, 62, 22213, 291, 1330, 42536, 355, 42536, 2898, 10613, 11, 42536, 36772, 198, 6738, 2769, 62, 45895, 13, 11218, 62, 22213, 291, 13, 403, 5305, 13, 403, 5305, 1330, 1231, 62, 12957, 6...
3.425197
127
import requests import json import datetime url = "http://api-gateway-dbs-techtrek.ap-southeast-1.elasticbeanstalk.com/transactions/10" querystring = {"from":"01-01-2019","to":"01-31-2019"} payload = "" headers = { 'identity': "Group11", 'token': "bf38d9ac-fade-40ef-b7d2-eabdb183acce", 'cache-control': "no-cache", 'Postman-Token': "7cd5530c-91e6-4038-86cb-6ccb857a2d4b" } response = requests.request("GET", url, data=payload, headers=headers, params=querystring) json_data = response.text python_obj = json.loads(json_data) item_dict = {} for trans in python_obj: if trans['tag'] not in item_dict: item_dict[trans['tag']] = float(trans['amount']) else: item_dict[trans['tag']] += float(trans['amount']) total = 0 for cat, amount in item_dict.items(): total += amount final = {} for cat, amount in item_dict.items(): final[cat] = round(amount/total,2) * 100 print(final)
[ 11748, 7007, 198, 11748, 33918, 198, 11748, 4818, 8079, 220, 198, 6371, 796, 366, 4023, 1378, 15042, 12, 10494, 1014, 12, 67, 1443, 12, 13670, 33945, 74, 13, 499, 12, 82, 14474, 12, 16, 13, 417, 3477, 14289, 301, 971, 13, 785, 14, ...
2.445026
382
import calendar month = int(input("Enter the month: ")) year = int(input("Enter the year: ")) Calendar = calendar.month(year, month) print(Calendar)
[ 11748, 11845, 198, 8424, 796, 493, 7, 15414, 7203, 17469, 262, 1227, 25, 366, 4008, 197, 198, 1941, 796, 493, 7, 15414, 7203, 17469, 262, 614, 25, 366, 4008, 197, 198, 220, 220, 220, 198, 9771, 9239, 796, 11845, 13, 8424, 7, 1941, ...
2.758621
58
#!/usr/bin/env python import PySimpleGUI as sg import glob import ntpath import subprocess LOCATION_OF_YOUR_SCRIPTS = '' # Execute the command. Will not see the output from the command until it completes. # Executes command and immediately returns. Will not see anything the script outputs if __name__ == '__main__': Launcher2()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 9485, 26437, 40156, 355, 264, 70, 198, 11748, 15095, 198, 11748, 299, 83, 6978, 198, 11748, 850, 14681, 198, 198, 29701, 6234, 62, 19238, 62, 56, 11698, 62, 6173, 32618, 4694, 7...
3.330097
103
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2010 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 201, 198, 201, 198, 37811, 201, 198, 4851, 42, 35352, 532, 383, 2420, 5464, 329, 4455, 532, 2638, 1378, 2503, 13, 69, 694, 35352, 13, 3262, 201, 198, 15269, 357, 34, 8, 5816, 12, 10333, ...
2.835452
1,495
class DictField(Field): """ MSG Pack in Blob field as Dict """ field_type = 'blob' _dict = {} pass
[ 4871, 360, 713, 15878, 7, 15878, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 49064, 6400, 287, 1086, 672, 2214, 355, 360, 713, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 2214, 62, 4906, 796, 705, 2436, 672, 6, 198, 22...
2.196429
56
#!/usr/bin/env python3 from LoLIM.stationTimings.autoCorrelator3_fromLOC import save_EventByLoc ## these lines are anachronistic and should be fixed at some point from LoLIM import utilities utilities.default_raw_data_loc = "/exp_app2/appexp1/public/raw_data" utilities.default_processed_data_loc = "/home/brian/processed_files" if __name__=="__main__": station_delays = { 'CS002': 0.0, 'CS003': 1.40436380151e-06 , 'CS004': 4.31343360778e-07 , 'CS005': -2.18883924536e-07 , 'CS006': 4.33532992523e-07 , 'CS007': 3.99644095007e-07 , 'CS011': -5.85451477265e-07 , 'CS013': -1.81434735154e-06 , 'CS017': -8.4398374875e-06 , 'CS021': 9.23663075135e-07 , 'CS030': -2.74255354078e-06, 'CS032': -1.57305580305e-06, 'CS101': -8.17154277682e-06, 'CS103': -2.85194082718e-05, 'RS208': 6.97951240511e-06 , 'CS301': -7.15482701536e-07 , 'CS302': -5.35024064624e-06 , 'RS306': 7.04283154727e-06, 'RS307': 6.96315727897e-06 , 'RS310': 7.04140267551e-06, 'CS401': -9.5064990747e-07 , 'RS406': 6.96866309712e-06, 'RS409': 7.02251772331e-06, 'CS501': -9.61256584076e-06 , 'RS503': 6.93934919654e-06 , 'RS508': 6.98208245779e-06 , 'RS509': 7.01900854365e-06, } station_delays['CS002'] = 0.0 ## need to add referance station save_EventByLoc(timeID = "D20170929T202255.000Z", XYZT = [-16794.30127223 , 9498.38995127 , 3297.47036309, 1.2642410207364205 ], station_timing_delays = station_delays, pulse_index = 24, output_folder = "callibrator_fromLOC_intOut4", pulse_width=50, min_ant_amp=5, upsample_factor = 4, polarization_flips="polarization_flips.txt", bad_antennas="bad_antennas.txt", additional_antenna_delays = "ant_delays.txt")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 6706, 43, 3955, 13, 17529, 14967, 654, 13, 23736, 10606, 2411, 1352, 18, 62, 6738, 29701, 1330, 3613, 62, 9237, 3886, 33711, 198, 198, 2235, 777, 3951, 389, 281, 620, ...
1.840191
1,045
import numpy as np from pymatting import ( load_image, cf_laplacian, make_linear_system, cg, jacobi, ichol, vcycle, CounterCallback, )
[ 11748, 299, 32152, 355, 45941, 198, 6738, 279, 4948, 265, 889, 1330, 357, 198, 220, 220, 220, 3440, 62, 9060, 11, 198, 220, 220, 220, 30218, 62, 5031, 489, 330, 666, 11, 198, 220, 220, 220, 787, 62, 29127, 62, 10057, 11, 198, 220,...
2.04878
82
"""Maintains a cache in a file. In general, the idea is that cache acts as a map. However, any time a modification to the map is made, it is immediately saved to disk. The format of caches is considered an implementation detail. """ from pathlib import Path import pickle def _ensure_cache_file(path: Path): """Ensures that a file exists at the given path. Raises: ValueError: if the path exists but is not a file """ if path.exists(): if not path.is_file(): raise ValueError(f'{path} exists but is not a file.') else: path.parent.mkdir(mode=0o0750, parents=True, exist_ok=True) with path.open('xb') as stream: pickle.dump({}, stream) path.chmod(mode=0o0640) class Cache: """A persistent cache that synchronizes the memory state with that of a file on disk. Attributes: path: the path where the cache is persisted(read-only) """ def __init__(self, path): """Creates or opens a cache at the given path.""" self._path = Path(path) _ensure_cache_file(self._path) self._load() @property def path(self) -> Path: """Returns the path to which the cache is persisted.""" return self._path def get(self, key, default=None): """Gets the value of the key in the cache, or default if the key is not in the cache. Equivalent to:: if cache.hask_key(key): return cache.get(key) else: return default Args: key: they key to extract from the cache default: the value to return if the key is not in the cache (defaults to None) """ return self._data.get(key, default) def has_key(self, key): """Returns True if the cache holds the given key, otherwise False.""" return key in self._data def set(self, key, value): """Sets the value of key to value. Equivalent to:: cache[key] = value Note that this will save the value to the cache. """ self.__setitem__(key, value) def get_through(self, key, or_else): """Returns the value of key from the cache or else calculate a value using or_else and save it in the cache. This function call is equivalent to:: if cache.has_key(key): return cache.get(key) else: value = or_else(key) if value is not None: cache.set(key, value) return value Args: key: the key to retrieve or_else: a function to call to get a value if the key is not present in the cache """ if self.has_key(key): return self.get(key) value = or_else(key) if value is not None: self.__setitem__(key, value) return value def _load(self): """Loads the cache from disk and into the data attribute.""" with self._path.open('rb') as stream: self._data = pickle.load(stream) def _save(self): """Loads the cache from disk and into the data attribute.""" with self._path.open('wb') as stream: pickle.dump(self._data, stream)
[ 37811, 44, 2913, 1299, 257, 12940, 287, 257, 2393, 13, 198, 198, 818, 2276, 11, 262, 2126, 318, 326, 12940, 6529, 355, 257, 3975, 13, 220, 2102, 11, 597, 640, 257, 17613, 284, 262, 3975, 198, 271, 925, 11, 340, 318, 3393, 7448, 28...
2.336887
1,407
"""Tests for Yet Another Twitch Toolkit.""" from unittest import TestCase, mock from io import StringIO import datetime import sqlalchemy import server as s import model as m from model import connect_to_db, db from seed_testdb import sample_data import template_helpers as temp_help import twitch_helpers ############################################################################### # MODEL TESTS ############################################################################### class UserModelTestCase(TestCase): """Tests User class methods.""" def setUp(self): """Before each test...""" # Connect to test db connect_to_db(s.app, "postgresql:///testdb", False) # Create tables and add sample data db.create_all() db.session.commit() sample_data() def tearDown(self): """After every test...""" db.session.close() db.reflect() db.drop_all() def test_get_id(self): """Return a unicode string for flask-login.""" user_id = 4 user = m.User.get_user_from_id(user_id) str_id = user.get_id() self.assertEqual("4", str_id) def test_get_user_from_id(self): """Receive a User or None for given user id.""" user_id = 4 user = m.User.get_user_from_id(user_id) self.assertEqual(user.user_id, user_id) user_id = 500 user = m.User.get_user_from_id(user_id) self.assertIsNone(user) def test_get_users_from_email(self): """Receive a list of Users with given email.""" # Case 1: Email exists for at least one user. email = "testing@test.com" users = m.User.get_users_from_email(email) found_emails = [user.email for user in users] for found_email in found_emails: self.assertEqual(email, found_email) # Case 2: Email does not exist for any users. email_not_exist = "imnotauser@nope.com" users = m.User.get_users_from_email(email_not_exist) self.assertFalse(users) def test_get_users_from_twitch_id(self): """Receive a User from given Twitch id.""" # Case 1: Twitch id exists for a user. twitch_id = "29389795" user = m.User.get_user_from_twitch_id(twitch_id) self.assertEqual(twitch_id, user.twitch_id) # Case 2: Twitch id does not exist for any user. twitch_id = "1234" user = m.User.get_user_from_twitch_id(twitch_id) self.assertIsNone(user) def test_update_tweet_interval(self): """Checks if tweet interval setting is updated correctly.""" user = m.User.query.get(4) new_interval = 45 user.update_tweet_interval(new_interval) self.assertEqual(user.tweet_interval, new_interval) def test_remove_twitter_access_token(self): """Test: Remove twitter access token for user.""" user = m.User.query.get(4) # Case 1: User does not have a Twitter access token. user.remove_twitter_access_token() self.assertIsNone(user.twitter_token) # Case 2: User has a Twitter access token. # Add twitter token. new_token = m.TwitterToken(user_id=user.user_id, access_token="mytoken", access_token_secret="mysecret") db.session.add(new_token) db.session.commit() self.assertEqual(user.twitter_token.access_token, "mytoken") # Remove twitter token and test. user.remove_twitter_access_token() self.assertIsNone(user.twitter_token) def test_update_twitch_access_token(self): """Checks if Twitch Tokens were updated correctly.""" # Case 1: User does not have an existing Twitch token in db. current_user = m.User.query.first() access_token = "ThisIsAGreatToken" refresh_token = "RefreshMePlease" expires_in = 6000 current_user.update_twitch_access_token( access_token, refresh_token, expires_in ) token = m.TwitchToken.query.filter_by( user_id=current_user.user_id).one() self.assertEqual(access_token, token.access_token) self.assertEqual(refresh_token, token.refresh_token) self.assertEqual(expires_in, token.expires_in) # Case 2: Updating token for the same user. new_access_token = "ImANewAccessToken" new_refresh_token = "ImANewRefreshToken" new_expires_in = 9000 current_user.update_twitch_access_token( new_access_token, new_refresh_token, new_expires_in ) token = m.TwitchToken.query.filter_by( user_id=current_user.user_id).one() self.assertEqual(new_access_token, token.access_token) self.assertEqual(new_refresh_token, token.refresh_token) self.assertEqual(new_expires_in, token.expires_in) def test_update_twitter_access_token(self): """Checks if Twitter tokens are updated correctly.""" user = m.User.query.first() access_token = "ThisIsAGreatToken" token_secret = "ImAGoodSecret" # Case 1: User does not have a Twitter token in the db. user.update_twitter_access_token(access_token, token_secret) token = m.TwitterToken.query.filter_by(user_id=user.user_id).one() self.assertEqual(access_token, token.access_token) self.assertEqual(token_secret, token.access_token_secret) # Case 2: Updating token for the same user.abs new_access_token = "ImANewAccessToken" new_token_secret = "ImANewTokenSecret" user.update_twitter_access_token(new_access_token, new_token_secret) token = m.TwitterToken.query.filter_by(user_id=user.user_id).one() self.assertEqual(new_access_token, token.access_token) self.assertEqual(new_token_secret, token.access_token_secret) def test_delete_template(self): """Checks if user can delete a template they own and not some other.""" user = m.User.query.first() # Adding another user. other_user = m.User(twitch_id="0987") m.db.session.add(other_user) m.db.session.commit() # Adding a template for the other user. template = m.Template(user_id=other_user.user_id, contents="Hello!") m.db.session.add(template) m.db.session.commit() # Case 1: User deletes their own template. user.delete_template(10) is_template = m.Template.query.get(10) self.assertIsNone = is_template # Case 2: User tries to delete a template they don't own. self.assertRaises(sqlalchemy.orm.exc.NoResultFound, user.delete_template, template.template_id) # Case 3: User tries to delete a template that doesn't exist. self.assertRaises(sqlalchemy.orm.exc.NoResultFound, user.delete_template, 600) def test_edit_template(self): """Checks if a user can update a given template.""" new_contents = "I love cats." user = m.User.query.first() template_id = m.Template.query.filter_by( user_id=user.user_id).first().template_id user.edit_template(template_id, new_contents) edited_template = m.Template.query.get(template_id) self.assertEqual(new_contents, edited_template.contents) class TemplateModelTestCase(TestCase): """Tests Template class methods.""" def setUp(self): """Before each test...""" # Connect to test db connect_to_db(s.app, "postgresql:///testdb", False) # Create tables and add sample data db.create_all() db.session.commit() sample_data() def tearDown(self): """After every test...""" db.session.close() db.reflect() db.drop_all() def test_get_template_from_id(self): """Get a template object or None with given template id.""" # Case 1: Template exists. template = m.Template.get_template_from_id(10) self.assertEqual(10, template.template_id) # Case 2: Template doesn't exist template = m.Template.get_template_from_id(9000) self.assertIsNone(template) class SentTweetModelTestCase(TestCase): """Tests SentTweet class methods.""" def setUp(self): """Before each test...""" # Connect to test db connect_to_db(s.app, "postgresql:///testdb", False) # Create tables and add sample data db.create_all() db.session.commit() sample_data() def tearDown(self): """After every test...""" db.session.close() db.reflect() db.drop_all() def test_store_sent_tweet(self): """Checks to see if sent tweet was saved correctly.""" mock_id_str = "12345" mock_created_at = datetime.datetime(2017, 2, 14, 12, 30, 10) mock_text = "I tweeted a thing!" mock_user_id = "987" @mock.patch("template_helpers.tweepy.Status") mocked_status = get_mocked_status() user_id = 4 clip_id = 9 saved_tweet = m.SentTweet.store_sent_tweet(mocked_status, user_id, clip_id) self.assertEqual(saved_tweet.user_id, user_id) self.assertEqual(saved_tweet.permalink, "https://twitter.com/{}/status/{}".format( mock_user_id, mock_id_str )) self.assertEqual(saved_tweet.clip_id, clip_id) class StreamSessionModelTestCase(TestCase): """Tests Template class methods.""" def setUp(self): """Before each test...""" # Connect to test db connect_to_db(s.app, "postgresql:///testdb", False) # Create tables and add sample data db.create_all() db.session.commit() sample_data() def tearDown(self): """After every test...""" db.session.close() db.reflect() db.drop_all() def test_save_stream_session(self): """Checks to see if stream session and data was saved correctly.""" timestamp = datetime.datetime(2017, 2, 14, 12, 30, 10) stream_id = "1" streamer_id = "pixxeltesting" stream_title = "Best stream ever!" stream_viewer_count = 100 stream_started_at = datetime.datetime(2017, 2, 14, 12, 30, 10) stream_game_id = "1" stream_game_title = "Stardew Valley" stream_url = "https://twitch.tv/pixxeltesting" stream_data = {"timestamp": timestamp, "stream_id": stream_id, "twitch_id": streamer_id, "stream_title": stream_title, "viewer_count": stream_viewer_count, "started_at": stream_started_at, "game_id": stream_game_id, "game_name": stream_game_title, "url": stream_url} user = m.User.query.first() # Case 1: Stream session does not exist for user. twitch_session = m.StreamSession.save_stream_session( user=user, stream_data=stream_data ) new_data = m.StreamDatum.query.filter_by( stream_id=twitch_session.stream_id ).first() self.assertEqual(twitch_session.twitch_session_id, stream_id) self.assertEqual(new_data.timestamp, twitch_session.started_at) # Case 2: Stream session exists for user. repeat_twitch_session = m.StreamSession.save_stream_session( user=user, stream_data=stream_data ) num_data = len(m.StreamDatum.query.filter_by( stream_id=twitch_session.stream_id ).all()) self.assertEqual(repeat_twitch_session, twitch_session) self.assertEqual(num_data, 2) def test_end_stream_session(self): """Checks if an open session is closed.""" user = m.User.query.first() # Alter the most recent session so it's detected as 'open' last_session = user.sessions[-1] last_session.ended_at = None db.session.commit() # Case 1: Open session is found. end_session_time = datetime.datetime(2017, 2, 14, 12, 30, 10) ended_session = m.StreamSession.end_stream_session( user=user, timestamp=end_session_time ) self.assertEqual(last_session.ended_at, end_session_time) self.assertEqual(last_session, ended_session) # Case 2: Sessions are closed. self.assertIsNone(m.StreamSession.end_stream_session( user=user, timestamp=end_session_time )) def test_end_all_user_sessions_now(self): """Checks that all user's sessions are ended.""" user = m.User.query.first() # Alter the most recent session so it's detected as 'open' last_session = user.sessions[-1] last_session.ended_at = None db.session.commit() # Confirm a session is open. open_sessions = m.StreamSession.query.filter_by(user_id=user.user_id, ended_at=None).all() self.assertTrue(open_sessions) # Case 1: Open sessions are found. m.StreamSession.end_all_user_sessions_now(user) open_sessions = m.StreamSession.query.filter_by(user_id=user.user_id, ended_at=None).all() self.assertFalse(open_sessions) class TwitchClipModelTestCase(TestCase): """Tests TwitchClip class methods.""" def setUp(self): """Before each test...""" # Connect to test db connect_to_db(s.app, "postgresql:///testdb", False) # Create tables and add sample data db.create_all() db.session.commit() sample_data() def tearDown(self): """After every test...""" db.session.close() db.reflect() db.drop_all() def test_save_twitch_clip(self): """Checks if Twitch clip is saved correctly.""" user = m.User.query.first() user_id = user.user_id slug = "TotallyAwesomePandas" # Case 1: All sessions closed. Associated stream should be most recent. saved_clip = m.TwitchClip.save_twitch_clip( slug, user_id ) self.assertEqual(saved_clip.stream_id, user.sessions[-1].stream_id) # Case 2: Most recent session is open. # Alter the most recent session so it's detected as 'open' last_session = user.sessions[-1] last_session.ended_at = None db.session.commit() saved_clip = m.TwitchClip.save_twitch_clip( slug, user_id ) self.assertEqual(saved_clip.stream_id, last_session.stream_id) ############################################################################### # TEMPLATE HELPER TESTS ############################################################################### class TemplateHelpersTestCase(TestCase): """Tests for template helpers functions.""" def setUp(self): """Before each test...""" # Connect to test db connect_to_db(s.app, "postgresql:///testdb", False) # Create tables and add sample data db.create_all() db.session.commit() sample_data() def tearDown(self): """After every test...""" db.session.close() db.reflect() db.drop_all() def test_replace_nl_with_carriage(self): """Check if new lines are replaced with carriage returns.""" given_string = "Hi,\nI'm a cat.\nMeow!" expected_string = "Hi,\r\nI'm a cat.\r\nMeow!" self.assertEqual(temp_help.replace_nl_with_carriage(given_string), expected_string) def test_add_basic_templates(self): """Check if appropriate templates are associated with new user.""" mock_twitch_id = '123456' new_user = m.User(twitch_id=mock_twitch_id) db.session.add(new_user) db.session.commit() base_template_contents = [template.contents for template in m.BaseTemplate.query] temp_help.add_basic_templates(new_user) # Get the template contents for the newly added user. added_template_contents = [template.contents for template in m.Template.query .filter_by(user_id=new_user.user_id)] # Ensure the original base templates are found for the user for content in base_template_contents: self.assertIn(content, added_template_contents) def test_get_twitch_template_data(self): """Checks thats twitch data is being transformed correctly.""" user = m.User.query.first() timestamp = datetime.datetime(2017, 2, 14, 12, 30, 10) stream_id = "1" streamer_id = "pixxeltesting" stream_title = "Best stream ever!" stream_viewer_count = 100 stream_started_at = datetime.datetime(2017, 2, 14, 12, 30, 10) stream_game_id = "1" stream_game_title = "Stardew Valley" stream_url = "https://twitch.tv/pixxeltesting" # Case 1: Stream is online # Mocking data twitch_helpers.serialize_twitch_stream_data = mock.MagicMock( return_value={ "timestamp": timestamp, "stream_id": stream_id, "twitch_id": streamer_id, "stream_title": stream_title, "viewer_count": stream_viewer_count, "started_at": stream_started_at, "game_id": stream_game_id, "game_name": stream_game_title, "url": stream_url }) template_data = temp_help.get_twitch_template_data(user) self.assertEqual(template_data["url"], stream_url) self.assertEqual(template_data["game"], stream_game_title) self.assertEqual(template_data["stream_title"], stream_title) self.assertEqual(template_data["viewers"], stream_viewer_count) self.assertEqual(template_data["timestamp"], timestamp) # Case 2: Stream is offline twitch_helpers.serialize_twitch_stream_data = mock.MagicMock( return_value=None) offline_template_data = temp_help.get_twitch_template_data(user) self.assertIsNone(offline_template_data) def test_populate_tweet_template(self): """Checks if tweet template is filled correctly.""" # Case 1: Stream is online, received data. temp_help.get_twitch_template_data = mock.MagicMock( return_value=template_data ) template_contents = "${game} ${url} ${stream_title}" filled_template = temp_help.populate_tweet_template( template_contents, user.user_id ) self.assertEqual(filled_template, "{} {} {}".format( stream_game_title, stream_url, stream_title )) # Case 2: Stream is offline temp_help.get_twitch_template_data = mock.MagicMock( return_value=None ) offline_filled_template = temp_help.populate_tweet_template( template_contents, user.user_id ) self.assertIsNone(offline_filled_template) test_populate_tweet_template(self) def test_publish_to_twitter(self): """Tests creating and publishing a tweet.""" # Case 1: Function is given no contents. temp_help.tweepy.API.update_status = mock.MagicMock() self.assertIsNone(temp_help.publish_to_twitter(None, 4)) temp_help.tweepy.API.update_status.assert_not_called() ################################################################### # SET UP ################################################################### template_contents = "${game} ${url} ${stream_title}" # Mock populate_tweet_template function temp_help.populate_tweet_template = mock.MagicMock( return_value="Stardew Valley https://twitch.tv/pixxeltesting \ Best stream ever!" ) # Mock Twitter access token user.twitter_token = m.TwitterToken( access_token="myToken", access_token_secret="mySecret" ) # Mock new clip mock_clip = m.TwitchClip(slug="MyCuteCat", stream_id=18, clip_id=100) m.db.session.add(mock_clip) m.db.session.commit() # temp_help.tweepy.API = mock.MagicMock() temp_help.twitch.generate_twitch_clip = mock.MagicMock( return_value=(m.TwitchClip(slug="MyCuteCat", stream_id=18, clip_id=100), "https://clipurl") ) temp_help.tweepy.API.update_status = mock.MagicMock( return_value=mock.MagicMock( id_str="12345", created_at=datetime.datetime(2017, 2, 14, 12, 30, 10), text="I tweeted a thing!", user=mock.MagicMock( id_str="987" ) ) ) # Case 2: Twitter update posts successfully. temp_help.publish_to_twitter( template_contents, user.user_id ) saved_tweet = m.SentTweet.query.filter_by( message="I tweeted a thing!", clip_id=100 ).first() self.assertTrue(saved_tweet) temp_help.twitch.generate_twitch_clip.assert_called() temp_help.tweepy.API.update_status.assert_called() test_publish_to_twitter(self) if __name__ == "__main__": import unittest unittest.main()
[ 37811, 51, 3558, 329, 6430, 6023, 23835, 16984, 15813, 526, 15931, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 11, 15290, 198, 6738, 33245, 1330, 10903, 9399, 198, 11748, 4818, 8079, 198, 11748, 44161, 282, 26599, 198, 11748, 4382, 355, ...
2.15553
10,416
import os import numpy as np from scipy.spatial import distance from scipy.stats import skew from Bio.PDB.vectors import calc_dihedral from utils.structure import get_atoms_coords, get_bb_atoms_coords from utils.stride import SS_CODE_TO_INT, single_stride class Representation: """An abstract class to implement structure representation.""" def __init__(self): """ Initialize the class. Returns ------- None. """ pass @staticmethod def get_n_features(): """ Return the number of a single feature-vector. This method is meant to be overridden by subclasses. Returns ------- None. """ pass @staticmethod def get_similarity_score(features_1, features_2): """ Return the similarity score between two features. This method is meant to be overridden by subclasses. Parameters ---------- features_1 : numpy.ndarray The first feature-vector. features_2 : numpy.ndarray The second feature-vector. Returns ------- None. """ pass def get_features(self): """ Return the features. This method is meant to be overridden by subclasses. Returns ------- None. """ pass class USR(Representation): """ Implements Ultrafast Shape Recognition (USR). Source ------ Ultrafast shape recognition for similarity search in molecular databases (Pedro J. Ballester, W. Graham Richards) Attributes ---------- ctd : numpy.ndarray The coordinates of the centroid of the structure. Note that it is the average of the atoms, so very likely it does not correspond to a real atom. cst : numpy.ndarray The coordinates of the closest atom to the centroid. fct : numpy.ndarray The coordinates of the farthest atom to the centroid. ftf : numpy.ndarray The coordinates of the farthest atom to `fct`. momenta : numpy.ndarray The array containing the momenta for the previous four features. The array is organized in four blocks of (mean, varriance, skewness)_f, where each element in the tuple is computed relative to f, with f being `ctd`, `cst`, `fct`, and `ftf` respecitvely. _coords : numpy.ndarray The matrix of coordinates """ def __init__(self, structure, bb_atoms=False): """ Initialize the class. Parameters ---------- structure : Bio.PDB.Structure The structure to represent. bb_atoms : str, optional Whether to use only backbone atoms to compute the USR. The default is False. Returns ------- None. """ super(USR, self).__init__() if bb_atoms: self._coords = get_bb_atoms_coords(structure) else: self._coords = get_atoms_coords(structure) self.ctd = None self.cst = None self.fct = None self.ftf = None self.momenta = None @staticmethod def get_n_features(): """ Return the length of USR vector. Returns ------- int The length of USR vector. """ return 12 @staticmethod def get_similarity_score(features_1, features_2): """ Compute the similarity score between two momenta, as described in the source paper. Parameters ---------- features_1 : numpy.ndarray The USR momenta of the first structure. features_2 : TYPE The USR momenta of the second structure. size : int, optional The size of the momenta vector. The default is 12 Returns ------- float in (0,1) The similarity score. The higher the more similar. """ score = 0 for i in range(12): score += abs(features_1[i]-features_2[i]) score /= 12 score += 1 return 1/score def _get_ctd(self): """ Compute the coordinates of `ctd`. Returns ------- None. """ self.ctd = np.mean(self._coords, axis=0) def _get_cst(self): """ Compute the coordinates of `cst`. Returns ------- None. """ squared_dist = np.sqrt(np.sum((self._coords-self.ctd)**2, axis=1)) self.cst = self._coords[np.argmin(squared_dist),:] def _get_fct(self): """ Compute the coordinates of `fct`. Returns ------- None. """ squared_dist = np.sqrt(np.sum((self._coords-self.ctd)**2, axis=1)) self.fct = self._coords[np.argmax(squared_dist),:] def _get_ftf(self): """ Compute the coordinates of `ftf`. Returns ------- None. """ squared_dist = np.sqrt(np.sum((self._coords-self.fct)**2, axis=1)) self.ftf = self._coords[np.argmax(squared_dist),:] def _compute_momenta(self): """ Compute the momenta. Returns ------- None. """ # Initialize momenta self.momenta = np.zeros(shape=(12,)) # Compute distances dist_ctd = np.sqrt(np.sum((self._coords-self.ctd)**2, axis=1)) dist_cst = np.sqrt(np.sum((self._coords-self.cst)**2, axis=1)) dist_fct = np.sqrt(np.sum((self._coords-self.fct)**2, axis=1)) dist_ftf = np.sqrt(np.sum((self._coords-self.ftf)**2, axis=1)) # Mean self.momenta[0] = np.mean(dist_ctd) # ctd self.momenta[3] = np.mean(dist_cst) # cst self.momenta[6] = np.mean(dist_fct) # fct self.momenta[9] = np.mean(dist_ftf) # ftf # Variance self.momenta[1] = np.var(dist_ctd) # ctd self.momenta[4] = np.var(dist_cst) # cst self.momenta[7] = np.var(dist_fct) # fct self.momenta[10] = np.var(dist_ftf) # ftf # Skewness self.momenta[2] = skew(dist_ctd) # ctd self.momenta[5] = skew(dist_cst) # cst self.momenta[8] = skew(dist_fct) # fct self.momenta[11] = skew(dist_ftf) # ftf def _compute_all(self): """ Compute the features and their momenta. Returns ------- None. """ self._get_ctd() self._get_cst() self._get_fct() self._get_ftf() self._compute_momenta() def get_features(self): """ Return the USR-momenta. Returns ------- numpy.ndarray The USR-momenta. """ if self.momenta is None: self._compute_all() return self.momenta class FullStride(Representation): """ Representation of the protein by its secondary structures elements. The secondary structure includes the secondary structures frequencies and their average Phi, Psi, and solvent area values. The representation is obtained using the Stride tool. Attributes ---------- pdb_id : str The PDB ID. pdb : str The PDB file. features : numpy.ndarray The feature-vector, where each element holds the ratio at which a specific secondary structure appears. """ def __init__(self, stride_dir, pdb): """ Initialize the class. Parameters ---------- stride_dir : str The directory holding the Stride tool. pdb : str The PDB file holding the structure to represent. Returns ------- None. """ super(FullStride, self).__init__() self.pdb_id = os.path.basename(pdb)[:-4] self.pdb = pdb self.features = None full_desc = single_stride(stride_dir, pdb) if full_desc is not None: self._compute_features(full_desc) @staticmethod def get_similarity_score(features_1, features_2): """ Compute the similarity score between two feature-vectors. The similarity is computed as the cosine similarity. Parameters ---------- features_1 : numpy.ndarray The first feature-vector. features_2 : numpy.ndarray The second feature-vector. Returns ------- float in [0,1] The similarity score. """ return 1 - distance.cosine(features_1, features_2) @staticmethod def get_n_features(): """ Return the number of features. Returns ------- int The length of the feature-vector. """ return 28 def get_features(self): """ Return the features. Returns ------- numpy.ndarray The feature-vector. """ return self.features class MITResidue(Representation): """ Representation of individual residues belonging to a structure. Source ------ Generative models for graph-based protein design (John Ingraham, Vikas K. Garg, Regina Barzilay, Tommi Jaakkola) Attributes ---------- embeddings : numpy.ndarray The embeddings for each residue. Each embedding is a feature-vector with 8 entries (Psi, Phi, Omega, Ca_i-Ca_(i-1), Ca_(i+1)-Ca_i, ID_(i-1), ID_(i+1)). If any entry cannot be computed, it is set to 0. contact_map : numpy.ndarray A contact map representing distances between the alpha-Carbons of two residues. residues : list of Bio.PDB.Residue The list of residues in the structure, except water- and het-atoms. """ def __init__(self, structure): """ Initialize the class. Parameters ---------- structure : Bio.PDB.Structure. The structure to represent. Returns ------- None. """ super(MITResidue, self).__init__() self.residues = [] for residue in structure.get_residues(): r_id = residue.get_id() if r_id[0] == ' ': self.residues.append(residue) self.residues = sorted(self.residues, key=lambda x: x.get_id()[1]) self.embeddings = None self.contact_map = np.zeros(shape=(len(self.residues),len(self.residues))) @staticmethod def get_n_features(): """ Return the length of a single residue feature-vector. Returns ------- int The length of a single feature-vector. """ return 7 def compute_contact_map(self): """ Compute the contact map. Returns ------- None. """ n = len(self.residues) for i in range(n-1): ca_i = self.residues[i]['CA'].get_coord() for j in range(i+1, n): ca_j = self.residues[j]['CA'].get_coord() self.contact_map[i,j] = self.contact_map[j,i] = np.linalg.norm(ca_i-ca_j) def compute_representation(self): """ Compute the representation of each residue belonging to the structure. Returns ------- None. """ # Initilize embeddings self.embeddings = np.zeros(shape=(len(self.residues),7)) n = len(self.residues) # Residues [1,n-1] for i in range(1, n-1): # Representing i with i, i-1 with h, i+1 with j r_i, r_h, r_j = self.residues[i], self.residues[i-1], self.residues[i+1] # Atoms for residue i c_i = r_i['C'].get_vector() ca_i = r_i['CA'].get_vector() n_i = r_i['N'].get_vector() # Atoms for residue i-1 c_h = r_h['C'].get_vector() ca_h = r_h['CA'].get_vector() # Atoms for residue i+1 ca_j = r_j['CA'].get_vector() n_j = r_j['N'].get_vector() # Compute Phi phi = calc_dihedral(c_h, n_i, ca_i, c_i) # Compute Psi psi = calc_dihedral(n_i, ca_i, c_i, n_j) # Compute Omega omega = calc_dihedral(ca_i, c_i, n_j, ca_j) # Compute Ca distances dist_hi = np.linalg.norm(ca_i-ca_h) dist_ij = np.linalg.norm(ca_j-ca_i) # Compute neighbors codes neigh_h = int(''.join([str(ord(k)) for k in r_h.get_resname()])) neigh_j = int(''.join([str(ord(k)) for k in r_j.get_resname()])) # Set embeddings self.embeddings[i,:] = np.array([phi, psi, omega, dist_hi, dist_ij, neigh_h, neigh_j]) # Residue 0 if 'C' not in self.residues[0] or 'C' not in self.residues[0] or 'N' not in self.residues[0]: self.embeddings[0,:] = np.array([0, 0, 0, 0, 0, 0, 0]) else: c_0 = self.residues[0]['C'].get_vector() ca_0 = self.residues[0]['CA'].get_vector() n_0 = self.residues[0]['N'].get_vector() ca_1 = self.residues[1]['CA'].get_vector() n_1 = self.residues[1]['N'].get_vector() psi = calc_dihedral(n_0, ca_0, c_0, n_1) omega = calc_dihedral(ca_0, c_0, n_1, ca_1) dist_01 = np.linalg.norm(ca_1-ca_0) neigh_1 = int(''.join([str(ord(k)) for k in self.residues[1].get_resname()])) self.embeddings[0,:] = np.array([0, psi, omega, 0, dist_01, 0, neigh_1]) # Residue n if 'C' not in self.residues[n-1] or 'C' not in self.residues[n-1] or 'N' not in self.residues[n-1]: self.embeddings[n-1,:] = np.array([0, 0, 0, 0, 0, 0, 0]) else: c_n = self.residues[n-1]['C'].get_vector() ca_n = self.residues[n-1]['CA'].get_vector() n_n = self.residues[n-1]['N'].get_vector() c_nm1 = self.residues[n-2]['C'].get_vector() ca_nm1 = self.residues[n-2]['CA'].get_vector() phi = calc_dihedral(c_nm1, n_n, ca_n, c_n) dist_nm1n = np.linalg.norm(ca_n-ca_nm1) neigh_nm1 = int(''.join([str(ord(k)) for k in self.residues[n-2].get_resname()])) self.embeddings[n-1,:] = np.array([phi, 0, 0, dist_nm1n, 0, neigh_nm1, 0]) def get_features(self): """ Return the structure embeddings. Returns ------- numpy.ndarray The embeddings. """ if self.embeddings is None: self.compute_representation() return self.embeddings
[ 11748, 28686, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 629, 541, 88, 13, 2777, 34961, 1330, 5253, 198, 6738, 629, 541, 88, 13, 34242, 1330, 43370, 198, 198, 6738, 16024, 13, 5760, 33, 13, 303, 5217, 1330, 42302, 62, ...
2.012252
7,346
"""Class implementing the Key Management Entity (KME). """ import random from api import helper import configparser from typing import List from api import crawler class KME: """ Class for the KME on each node. This class also defines the related methods for manipulating the keys. Most of the configurations for the KME, such as the IP address of the web server hosting the API, IP address of the SAE etc. is stored in a ``config.ini`` file. Parameters ---------- config_path : str ABSOLUTE file path to config.ini that is contained in the etsi-qkd-api/api folder. Attributes ---------- source_KME_ID: str IP address of the source (master) KME. target_KME_ID: str IP address of the target (slave) KME master_SAE_ID: str IP address of the master SAE (user application that requests keys) slave_SAE_ID: str IP address of the slave SAE. key_size: int Size of each key in bits in the KME. max_key_per_request: int Maximum number of keys per request max_key_size: int Maximum size of each key in bits that can be requested. min_key_size: int Minimum size of each key in bits that can be requested. max_SAE_ID_count: int Maximum number of additional SAEs allowed (0 at the moment). status_extension: str Optional field for future use (unclear what it should be used for at the moment) rd: random (object, from random Python library) Object to initialize random seed and pass to UUID generator to generate UUIDs as the key IDs. """ def get_key(self, number: int, size: int) -> dict: """Master function that returns the key container of keys from KME. Function that handles the logic for retrieving the keys from qcrypto files. If the size of each key is a multiple of 32, then the keys need to be concatenated. The file retrieving is done by a helper function, :func:`~api.helper.retrieve_keys_from_file`, that actually opens the qcrypto file and retrieves the keys. Parameters ---------- number : int The number of keys requested. size : int The size of each key in bits. Returns ------- dict Key container containing the keys requested. Raises ------ ValueError Error if there are insufficient keys. """ if number is None: number = 1 if size is None: size = self.key_size num_key_in_each = int(size/self.key_size) # If insufficient keys raise ValueError if num_key_in_each*number > self.stored_key_count: raise ValueError # Pass to helper function to retrieve key from the qcrypto binary key files keys_retrieved = helper.retrieve_keys_from_file(number, num_key_in_each, self.key_file_path) # Each key in keys_retrieved is 32bits, so if you want longer keys then pass to # helper function to concatenate the keys # concatenated_keys will be an array of integers concatenated_keys = helper.concat_keys(keys_retrieved) # convert each key to base64 concatenated_keys = [helper.int_to_base64(x) for x in concatenated_keys] # create the keys object as per key container specification in API keys_array = [] for ind, val in enumerate(zip(concatenated_keys, keys_retrieved)): concat_key = val[0] constituent_keys = val[1] list_of_uuids = [helper.convert_int_to_uuid(x) for x in constituent_keys] separator = '+' key_ID = separator.join(list_of_uuids) # delimit each key with '+' temp_dict = {"key_ID": key_ID, "key": concat_key} keys_array.append(temp_dict) key_container = {'keys': keys_array} self.stored_key_count -= number*num_key_in_each # update how many keys retrieved from kme return key_container def get_key_with_id(self, key_ids: List[dict]) -> dict: """ Returns the key container of keys from KME given the key IDs. Function will be called by the 'slave' application requesting for keys. The actual retrieving of keys is passed to the helper function :func:`~api.helper.retrieve_keys_given_uuid`. Parameters --------- key_ids: List[dict] Array of dictionaries containing the key ids. Each dictionary contains one key id, in the format: { "key_id": <key_id> } Returns ------- dict Key container containing the keys requested. Raises ------ KeyError Error if the keys requested cannot be found. Thrown by :func:`~api.helper.retrieve_keys_given_uuid`. """ num_keys_retrieved = 0 uuid_array = [] # uuid_array is a 2D list, where each row contains the constituent key IDs (UUIDs) that make up each key for val in key_ids: concat_key_id = val["key_ID"] key_ids_arr = concat_key_id.split("+") # remember key IDs are concatenated with '+' # key_ids_arr = textwrap.wrap(concat_key_id, 36) num_keys_retrieved += len(key_ids_arr) uuid_array.append(key_ids_arr) # pass to helper keys_retrieved = helper.retrieve_keys_given_uuid(uuid_array, self.key_file_path) # rest of code is similar to retrieve_key_from_file concatenated_keys = helper.concat_keys(keys_retrieved) concatenated_keys = [helper.int_to_base64(x) for x in concatenated_keys] keys_array = [] for ind, val in enumerate(zip(concatenated_keys, keys_retrieved)): concat_key = val[0] constituent_keys = val[1] list_of_uuids = [helper.convert_int_to_uuid(x) for x in constituent_keys] separator = '+' key_ID = separator.join(list_of_uuids) # delimit each key with '+' temp_dict = {"key_ID": key_ID, "key": concat_key} keys_array.append(temp_dict) key_container = {'keys': keys_array} self.stored_key_count -= num_keys_retrieved # update how many keys retrieved from kme return key_container def get_status(self) -> dict: """Returns status of KME according to the ETSI specification. Calls :func:`~api.crawler.get_stored_key_count` and updates ``stored_key_count``. This is to ensure updated key figures if a new key file is added. Returns ------- dict Dictionary containing status properties of KME. """ # update stored key count when get_status is called self.stored_key_count = self.key_file_crawler.get_stored_key_count() status = { "source_KME_ID": self.source_KME_ID, "target_KME_ID": self.target_KME_ID, "master_SAE_ID": self.master_SAE_ID, "slave_SAE_ID": self.slave_SAE_ID, "key_size": self.key_size, "stored_key_count": self.stored_key_count, "max_key_count": self.max_key_count, "max_key_per_request": self.max_key_per_request, "max_key_size": self.max_key_size, "min_key_size": self.min_key_size, "max_SAE_ID_count": self.max_SAE_ID_count } return status
[ 37811, 9487, 15427, 262, 7383, 8549, 20885, 357, 42, 11682, 737, 198, 37811, 198, 11748, 4738, 198, 6738, 40391, 1330, 31904, 198, 11748, 4566, 48610, 198, 6738, 19720, 1330, 7343, 198, 6738, 40391, 1330, 27784, 1754, 628, 198, 4871, 509,...
2.383535
3,134
from __future__ import annotations import asyncio from asyncio import Queue from contextlib import contextmanager import logging from typing import ( Any, Callable, Dict, Sequence, overload, Generic, TypeVar, cast, TYPE_CHECKING, ) from typing_extensions import Literal from opentrons.commands import types if TYPE_CHECKING: from opentrons.api.dev_types import Message as SessionStateMessage from opentrons.api.calibration import Message as CalibrationStateMessage MODULE_LOG = logging.getLogger(__name__) UntypedMessage = Dict[str, Any] _HandledMessages = TypeVar("_HandledMessages")
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 11748, 30351, 952, 198, 6738, 30351, 952, 1330, 4670, 518, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 11748, 18931, 198, 6738, 19720, 1330, 357, 198, 220, 220, 220, 4377, 11, 198, 220, 220,...
2.985981
214
import abc class SortingAlgorithm(abc.ABC): """Base class for all sorting algorithms.""" @abc.abstractmethod def sort(self, unordered_list: list) -> list: """Sorts an unordered list of numbers. Parameters ---------- unordered_list: an unordered list of numbers that needs to be sorted in ascending order. Returns ------- list ordered version of the unordered_list provided """ pass class BubbleSort(SortingAlgorithm): """ A simple and inefficient sorting algorithm. Repeatedly switches adjacent values in the list that are out of order until the list is ordered. """
[ 11748, 450, 66, 628, 198, 4871, 311, 24707, 2348, 42289, 7, 39305, 13, 24694, 2599, 198, 220, 220, 220, 37227, 14881, 1398, 329, 477, 29407, 16113, 526, 15931, 628, 220, 220, 220, 2488, 39305, 13, 397, 8709, 24396, 198, 220, 220, 220,...
2.834025
241
import os import json import codecs sqljson_file = './sqljson.json' output_file = './commonnames.json' # the sqljson.json file holds a giant array that # looks like this: # [ # { "spp": "Abrothrix_andinus", # "commonNames": [ # "Andean Altiplano Mouse", # "Andean Akodont" # ] # }, # ... # ] # # What we're doing here is turning that into a giant # dict, with species names as keys, and the commonNames # list as that key's value; then saving that into # commonnames.json. # # { # "Abrothrix_andinus": [ # "Andean Altiplano Mouse", # "Andean Akodont" # ], # ... # } cnames = {} # try reading in the list of sci-to-common species names with open(sqljson_file) as f: sql_list = json.load(f) for item in sql_list: cnames[item['spp']] = list(set(item['commonNames'])) with open(output_file, 'wb') as out: # this is what you have to do to get utf8 on both Python 2 and 3 json.dump(cnames, codecs.getwriter('utf-8')(out), ensure_ascii=False, indent=4)
[ 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 40481, 82, 198, 198, 25410, 17752, 62, 7753, 796, 705, 19571, 25410, 17752, 13, 17752, 6, 198, 22915, 62, 7753, 796, 705, 19571, 11321, 14933, 13, 17752, 6, 198, 198, 2, 262, 44161, 17...
2.363229
446
import copy from sfcsim.classes.vnf import * class node(): ''' ************************************************************************************************ node类,表示网络中的一个节点,包含接入节点和服务器节点两种类型,详情见network基础类设计文档 属性值: id 节点id,节点唯一标识 atts 节点资源属性,可以有cpu、memory、stroage资源和access属性,表示是否为接入节点 vnfs 节点内部记录的vnf_type实例数组,包含资源(att),增加vnf占用节点资源 remian_resource 剩余资源,节点中的剩余资源 节点属性atts=节点剩余资源remian_resource+vnf属性atts 属性方法: 太多了,我不想写,主要包含get、set、show和针对vnf_type的add、delete方法 ************************************************************************************************ ''' #### class nodes(): ''' ************************************************************************************* nodes类,表示所有node的集合,全局只应该有一个nodes实例,详情见network基础类设计文档 属性值: number node数量 nodes node类的所有实例,表示网络中存储的所有node实例 __access_number 接入node数量 __access_nodes 接入node类的所有实例 __server_number 服务node数量 __server_nodes 服务node类的所有实例 属性方法: 太多了,我不想写,主要包含get、set、search、add、delete、show五类方法 ************************************************************************************* '''
[ 11748, 4866, 198, 6738, 264, 69, 6359, 320, 13, 37724, 13, 85, 77, 69, 1330, 1635, 198, 4871, 10139, 33529, 198, 220, 220, 220, 705, 7061, 198, 17174, 17174, 17174, 198, 220, 220, 220, 10139, 163, 109, 119, 11, 26193, 101, 163, 97, ...
1.276407
1,013
from django.db.models import Q from dal import autocomplete from django.core.exceptions import ObjectDoesNotExist from vocabs.models import SkosConcept, SkosTechnicalCollection
[ 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 1195, 198, 6738, 288, 282, 1330, 1960, 42829, 6677, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 12776, 8937, 13, 27530, 1330, 3661, 41...
3.58
50
from api import ma from api.models.SearchTeam import SearchTeam search_team_schema = SearchTeamSchema() search_teams_schema = SearchTeamSchema(many=True)
[ 6738, 40391, 1330, 17266, 198, 6738, 40391, 13, 27530, 13, 18243, 15592, 1330, 11140, 15592, 628, 198, 198, 12947, 62, 15097, 62, 15952, 2611, 796, 11140, 15592, 27054, 2611, 3419, 198, 12947, 62, 660, 4105, 62, 15952, 2611, 796, 11140, ...
3.204082
49
# This module is automatically generated by autogen.sh. DO NOT EDIT. from . import _IBM # Aliases
[ 2, 770, 8265, 318, 6338, 7560, 416, 1960, 6644, 13, 1477, 13, 8410, 5626, 48483, 13, 198, 198, 6738, 764, 1330, 4808, 9865, 44, 628, 198, 198, 2, 12104, 1386, 198 ]
3.290323
31
""" For detailed information please see http://shotgunsoftware.github.com/shotgunEvents/api.html ## shotgun_logArgs: Logs all events that occur and generates a logfile in the specified directory found in the shotgun_logging.conf file ## """ rootSoftwareDir = [r'\\intrepid\Server\Tools'] dffxModulesExists = '' configFilePathExists = '' import os __version__ = '0.9' __version_info__ = (0, 9) for dir in rootSoftwareDir: path_to_dffxModules=[os.path.join(dir,'modules\\shotgun')] path_to_dffxModules = getPath(path_to_dffxModules) if path_to_dffxModules != None: dffxModulesExists = path_to_dffxModules import sys if dffxModulesExists != '': sys.path.insert(1,dffxModulesExists) import dffx_configParser import logging def registerCallbacks(reg): """Register all necessary or appropriate callbacks for this plugin.""" # Specify who should recieve email notifications when they are sent out. # #reg.setEmails('me@mydomain.com') # Use a preconfigured logging.Logger object to report info to log file or # email. By default error and critical messages will be reported via email # and logged to file, all other levels are logged to file. # reg.logger.debug('Loading shotgun_TS_DSD plugin.') # Register a callback to into the event processing system. # # Arguments: # - Shotgun script name # - Shotgun script key # - Callable # - Argument to pass through to the callable # - A filter to match events to so the callable is only invoked when # appropriate # configInfo = parseConfig() shotgunScriptName = configInfo[0] shotgunScriptKey = configInfo[1] matchEvents = { 'Shotgun_Task_Change': ['sg_status_list'] } reg.registerCallback(shotgunScriptName, shotgunScriptKey, shotgun_TS_DSD, matchEvents, None) # Set the logging level for this particular plugin. Let error and above # messages through but block info and lower. This is particularly usefull # for enabling and disabling debugging on a per plugin basis. reg.logger.setLevel(logging.INFO) def shotgun_TS_DSD(sg, logger, event, args): """Flip downstream Tasks to 'rdy' if all of their upstream Tasks are 'fin'""" # we only care about Tasks that have been finalled if 'new_value' not in event['meta'] or event['meta']['new_value'] != 'fin': return else: ds_taskID = None change_status = False downstreamTasks = [] upstreamTasks = [] taskNotFinalList = [] ds_taskList = [] try: taskDict = event['entity'] ds_filters = [ ['upstream_tasks', 'is', taskDict], ['sg_status_list', 'is', 'wtg'] ] ds_fields = ['upstream_tasks'] downstreamTasks = sg.find("Task", ds_filters,ds_fields) for ds_task in downstreamTasks: ds_taskID = ds_task['id'] if ds_taskID not in ds_taskList: ds_taskList.append(ds_taskID) if 'upstream_tasks' in ds_task: upstreamTasks = ds_task['upstream_tasks'] if upstreamTasks != []: for us_task in upstreamTasks: us_taskID = us_task.get('id') us_filters = [['id','is',us_taskID]] us_fields = ['sg_status_list'] us_task_status = sg.find("Task", us_filters,us_fields)[0]['sg_status_list'] if us_task_status != 'fin': taskNotFinalList.append(us_taskID) if taskNotFinalList == [] or upstreamTasks == []: change_status = True else: change_status = False if change_status: if ds_taskList != []: for ds_taskID in ds_taskList: taskUpdateData = {'sg_status_list':'rdy'} taskUpdate = sg.update ("Task",ds_taskID,taskUpdateData) logger.info( "Set Task %s to 'rdy'" % ( ds_taskID ) ) except Exception as error: logger.error('%s' % (error))
[ 37811, 198, 1890, 6496, 1321, 3387, 766, 198, 198, 4023, 1378, 9442, 7145, 43776, 13, 12567, 13, 785, 14, 9442, 7145, 37103, 14, 15042, 13, 6494, 198, 198, 2235, 18607, 62, 6404, 42035, 25, 5972, 82, 477, 2995, 326, 3051, 290, 18616, ...
2.228631
1,907
# -*- coding: utf-8 -*- """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import base64 from enum import Enum from functools import wraps from typing import Any, List, Optional, Tuple, Union from Cryptodome import Util from Cryptodome.Cipher import PKCS1_OAEP from Cryptodome.Cipher import PKCS1_v1_5 as PKCS1_v1_5_cipher from Cryptodome.Hash import SHA1 from Cryptodome.PublicKey import RSA from Cryptodome.Signature import PKCS1_v1_5 # 默认编码 ENCODING = "utf-8" class CipherPadding(Enum): """填充标志""" PKCS1 = "PKCS1" PKCS1_OAEP = "PKCS1_OAEP" class KeyObjType(Enum): """密钥对象类型""" PRIVATE_KEY_OBJ = "private_key_obj" PUBLIC_KEY_OBJ = "public_key_obj" def key_obj_checker(key_obj_type: str): """ 密钥对象检查器 :param key_obj_type: KeyObjType :return: """ return decorate def generate_keys() -> Tuple[str, str]: """ 生成公私钥 :return: """ # In 2017, a sufficient length is deemed to be 2048 bits. # 具体参考 -> https://pycryptodome.readthedocs.io/en/latest/src/public_key/rsa.html private_key_obj = RSA.generate(2048) private_key = private_key_obj.exportKey() # publickey & exportKey 为兼容写法 # pycryptodomex > 3.9.7 提供 public_key & export_key,为了兼容 pycryptodome 和 Crypto 暂不采用 # 参考: https://stackoverflow.com/questions/48155294/ public_key = private_key_obj.publickey().exportKey() return private_key.decode(encoding=ENCODING), public_key.decode(encoding=ENCODING)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 24893, 1087, 14573, 15708, 318, 10607, 284, 1104, 262, 1280, 2723, 2055, 416, 1642, 5525, 241, 251, 165, 110, 116, 162, 247, 118, 12859, 239, 12, 164, 232, ...
2.448316
861
#Shape of capital D: def for_D(): """printing capital 'D' using for loop""" for row in range(5): for col in range(5): if col==1 or row in(0,4) and col!=4 or col==4 and row not in(0,4): print("*",end=" ") else: print(" ",end=" ") print() def while_D(): """printing capital 'D' using while loop""" i=0 while i<4: j=0 while j<5: if i==0 and j!=4 or i==3 and j!=4 or j==1 or j==4 and i not in(0,3): print("*",end=" ") else: print(" ",end=" ") j+=1 print() i+=1
[ 2, 33383, 286, 3139, 360, 25, 201, 198, 4299, 329, 62, 35, 33529, 201, 198, 220, 220, 220, 37227, 4798, 278, 220, 3139, 705, 35, 6, 1262, 329, 9052, 37811, 201, 198, 220, 220, 220, 329, 5752, 287, 2837, 7, 20, 2599, 201, 198, 22...
1.68059
407
# -*- coding: utf-8 -*- from django.apps import AppConfig
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628, 198, 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
2.541667
24
import binascii import hashlib import os import random import string import subprocess import sys import time import threading import Queue BIN_PATH = "./build/test_random_sha1" NTHREADS = 2 NTESTS = 10 NBYTES = 20 global still_making_input still_making_input = True tests = Queue.Queue() failures = list() # # Helper functions # def random_string(len): """ Returns a random string of length 'len' consisting of upper + lowercase letters and digits """ ret = list() rand = random.Random() for i in xrange(len): ret.append("%.02x" % rand.randint(0, 255)) return "".join(ret) #selector = string.ascii_uppercase + string.ascii_lowercase + string.digits #return ''.join(random.choice(selector) for _ in range(len)) def run_test(input_string, expected_output): """ Run the C test program, comparing the Python SHA1 implementation to the one in C """ return subprocess.call([BIN_PATH, input_string, expected_output]) # # Test driver # if __name__ == "__main__": # Read NTESTS from stdin if len(sys.argv) > 1: if sys.argv[1].isdigit(): NTESTS = int(sys.argv[1]) # Read NTHREADS from stdin if len(sys.argv) > 2: if sys.argv[2].isdigit(): NTHREADS = int(sys.argv[2]) # Read NBYTES from stdin if len(sys.argv) > 3: if sys.argv[3].isdigit(): NBYTES = int(sys.argv[3]) # Tell user what is going to happen print("") str_threads = "thread" if NTHREADS > 1: str_threads += "s" print("Running tests on %d %s SHA1-hashing %d random %d-byte strings," % (NTHREADS, str_threads, NTESTS, NBYTES)) print("comparing the results to the output of Python's hashlib.sha1().") print("") # Spawn thread to create test inputs in the background, instead of blocking here... t_mk_input = threading.Thread(target=make_test_input) t_mk_input.start() # Create new threads threadlist = list() for i in range(NTHREADS): threadlist.append(threading.Thread(target=run_tests)) # Run all threads for i, thread in enumerate(threadlist): thread.start() # Wait for input-creation to complete t_mk_input.join() still_making_input = False # Wait for threads to complete for i, thread in enumerate(threadlist): thread.join() print(" ") print(" ") print("%d/%d tests succeeded." % (NTESTS - len(failures), NTESTS)) print(" ") if len(failures) > 0: error_log = open("error_log.txt", "a") for fail_input, fail_output in failures: error_log.write("./build/test_random2 %s %s %s" % (fail_input, fail_output, os.linesep)) error_log.close()
[ 11748, 9874, 292, 979, 72, 198, 11748, 12234, 8019, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 4704, 278, 198, 11748, 4670, 518, 198, 198, 33, 1268, 62,...
2.682292
960
from django.conf import settings from django.shortcuts import render from djtools.decorators.auth import group_required @group_required(settings.ADMINISTRATORS_GROUP) def home(request): ''' Home page view ''' return render( request, 'home.html' )
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 198, 6738, 42625, 31391, 13, 12501, 273, 2024, 13, 18439, 1330, 1448, 62, 35827, 628, 198, 31, 8094, 62, 35827, 7, 33692, 13, 2885, ...
2.735294
102
# -*- coding: utf-8 -*- # formata os comandos em quádruplas e insere na tabela
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 220, 220, 220, 220, 198, 220, 220, 220, 1303, 1296, 1045, 28686, 401, 392, 418, 795, 627, 6557, 67, 622, 489, 292, 304, 287, 325, 260, 12385, 7400, 10304 ]
2.023256
43
from tkinter import Tk, StringVar, ttk, E, W, Event from typing import Callable from savings import SavingsObserver, PresentRequiredEarningsObserver
[ 6738, 256, 74, 3849, 1330, 309, 74, 11, 10903, 19852, 11, 256, 30488, 11, 412, 11, 370, 11, 8558, 198, 6738, 19720, 1330, 4889, 540, 198, 198, 6738, 10653, 1330, 40947, 31310, 18497, 11, 21662, 37374, 49725, 654, 31310, 18497, 628 ]
3.682927
41
from collections import defaultdict import re from this import d, s _zen = ''.join(d.get(c, c) for c in s) _zen_lines = _zen.splitlines()[2:] index = defaultdict(set) for line in _zen_lines: for word in line.split(): index[re.search(r'\w*', word.lower()).group()].add(line)
[ 6738, 17268, 1330, 4277, 11600, 198, 11748, 302, 198, 6738, 428, 1330, 288, 11, 264, 198, 198, 62, 4801, 796, 705, 4458, 22179, 7, 67, 13, 1136, 7, 66, 11, 269, 8, 329, 269, 287, 264, 8, 198, 62, 4801, 62, 6615, 796, 4808, 4801,...
2.539823
113
from tests.integration.integration_test_case import IntegrationTestCase
[ 6738, 5254, 13, 18908, 1358, 13, 18908, 1358, 62, 9288, 62, 7442, 1330, 38410, 14402, 20448, 628 ]
4.294118
17
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ x = 1 if x>= 5: print('verdadeiro porque {} >= 5'.format(x)) elif x == 3: print('{} == 3'.format(x)) else: print('{} é menor que 5'.format(x))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 3717, 12, 5539, 347, 39, 38, 2638, 1378, 65, 86, 13, 2398, 14, 198, 198, 87, 796, 352, 198, 198, 361, 2124, 29, 28, 642, 25, 198, 220, 220, 220, 3601, 10786, 332, ...
2.166667
102
from gpiozero import LED, Button import time #decoder inputs DEC_C = 17 DEC_B = 27 DEC_A = 22 #mux inputs MUX_C = 23 MUX_B = 24 MUX_A = 25 #mux outputs M1_OUT = 12 #output of multiplexer controlling columns 0-5 M2_OUT = 4 #output of multiplexer controlling columns 6-11 """ generally set an output to a value, 0 for off, otherwise on pin - a gpiozero LED variable """ """ read an input from a GPIO declared button, just a rename to make it more clear pin - a gpiozero Button variable """ """ set the values for a 3 bit control of a logic chip. pin0, pin1, pin2 - the LEDs/pins to control val - the value to write to these pins, 0 <= val <= 7 """ class Detection: """ init function, initialises the mux to zero """ """ initialise the mux to be all set as outputs """ """ initialise the decoder inputs to be set as outputs """ """ Set the mux inputs to a specific value, 0 <= val <= 7 """ """ Set the decoder inputs to a specific valu, 0 <= val <= 7 """ """ Read a specific square, for debugging purposes """ """ print the current detected board status """ """ Update the detected board storage """ if __name__ == "__main__": det = Detection() det.print_board() while(1): time.sleep(5) det.update_board() det.print_board()
[ 6738, 27809, 952, 22570, 1330, 12365, 11, 20969, 198, 11748, 640, 198, 198, 2, 12501, 12342, 17311, 198, 41374, 62, 34, 796, 1596, 198, 41374, 62, 33, 796, 2681, 198, 41374, 62, 32, 796, 2534, 198, 2, 76, 2821, 17311, 198, 44, 31235...
2.695906
513
ida = int(input()) vuelta = int(input()) print('Ana tiene un total de {0} euros'.format((ida+vuelta)))
[ 3755, 796, 493, 7, 15414, 28955, 198, 40939, 12514, 796, 493, 7, 15414, 28955, 198, 198, 4798, 10786, 2025, 64, 46668, 1734, 555, 2472, 390, 1391, 15, 92, 21138, 4458, 18982, 19510, 3755, 10, 40939, 12514, 22305, 198 ]
2.736842
38
import random from collections import deque, namedtuple import numpy as np from accel.replay_buffers.binary_tree import MinTree, SumTree Transition = namedtuple( 'Transition', ('state', 'action', 'next_state', 'reward', 'valid'))
[ 11748, 4738, 198, 6738, 17268, 1330, 390, 4188, 11, 3706, 83, 29291, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 936, 5276, 13, 260, 1759, 62, 36873, 364, 13, 39491, 62, 21048, 1330, 1855, 27660, 11, 5060, 27660, 198, 198...
3.090909
77
from app.views.observer import observer
[ 6738, 598, 13, 33571, 13, 672, 15388, 1330, 22890 ]
4.333333
9
import os import sys import torch import argparse import numpy as np from PIL import Image from mtcnn.mtcnn import MTCNN from torch.utils.data import DataLoader from torchvision import datasets, transforms from mtcnn.utils.align_trans import get_reference_facial_points, warp_and_crop_face def save_landmark(landmark, save_path): """Save Landmark to path Arguments: landmark {float} -- landmarks save_path {str} -- Save path for extracted face image. (default: {None}) Returns: None """ with open(save_path, 'w+') as f: for (x, y) in landmark: f.write('{}\t{}\n'.format(x, y)) return landmark if __name__ == "__main__": main(parse_args(sys.argv[1:]))
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 28034, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 285, 23047, 20471, 13, 16762, 66, 20471, 1330, 337, 4825, 6144, 198, 6738, 28034...
2.617857
280
plan = [] # replace stock one import sys sys.modules['atexit'] = sys.modules['aio.atexit']
[ 11578, 796, 17635, 628, 198, 198, 2, 6330, 4283, 530, 198, 11748, 25064, 198, 17597, 13, 18170, 17816, 378, 10198, 20520, 796, 220, 25064, 13, 18170, 17816, 64, 952, 13, 378, 10198, 20520, 198 ]
2.794118
34
#stock_screener.py from pandas_datareader import data as pdr from yahoo_fin import stock_info as si # import yahoo_fin #from pandas import ExcelWriter import yfinance as yf import pandas as pd # import requests import datetime import time from pprint import pprint from collections import OrderedDict import base64 # def calc_relative_strength(df): # ## relative gain and losses # df['close_shift'] = df['adj_close'].shift(1) # ## Gains (true) and Losses (False) # df['gains'] = df.apply(lambda x: x['adj_close'] if x['adj_close'] >= x['close_shift'] else 0, axis=1) # df['loss'] = df.apply(lambda x: x['adj_close'] if x['adj_close'] <= x['close_shift'] else 0, axis=1) # avg_gain = df['gains'].mean() # avg_losses = df['loss'].mean() # return avg_gain / avg_losses # def rs_rating(stock_rs_strange_value, index_rs_strange_value): # # print(f'Stock RS:{stock_rs_strange_value}, Index RS:{index_rs_strange_value}') # return 100 * ( stock_rs_strange_value / index_rs_strange_value ) # class Moving_avg: # # self.index_strange = index_strange # def __init__(self, stockname, df, index_strange, min_rs_rating=70): # self.stockname = stockname # self.df = df # # self.stock_data = get_stock(stockname) # self.df = self.calc_moving_avg(self.df) # self.price = self.df['adj_close'][-1] # self.sma50 = self.df["SMA_50"][-1] # self.sma150 = self.df["SMA_150"][-1] # self.sma200 = self.df["SMA_200"][-1] # self.index_rs_strange = index_strange # self.stock_rs_strange = calc_relative_strength(self.df) # self.rs_rating = rs_rating(self.stock_rs_strange, self.index_rs_strange) # self.min_rs_rating = min_rs_rating # self.low_of_52week = self.df["adj_close"][-260:].min() # self.high_of_52week = self.df["adj_close"][-260:].max() # try: # ## Need to double check this # ## should SMA trending up for at least 1 month (ideally 4-5 months) # self.sma200_20 = df["SMA_200"][-20] # except: # self.sma200_20 = 0 # def as_dict(self): # try: # company_name = yf.Ticker(self.stockname).info['longName'] # except: # company_name = self.stockname # # return self.__dict__ # return OrderedDict([ # ('Company Name', company_name), # ('Ticker', self.stockname), # ('Current Price', self.price), # ('RS Rating', self.rs_rating), # ('SMA 50 Day', self.sma50), # ('SMA 150 Day', self.sma150), # ('SMA 200 Day', self.sma200), # ('52 Week Low', self.low_of_52week), # ('52 Week High', self.high_of_52week), # ]) # def calc_moving_avg(self, df): # for x in [50,150,200]: # df["SMA_"+str(x)] = round(df['adj_close'].rolling(window=x).mean(), 2) # return df # def avg_volume(self): # return self.df['volume'].mean() # def condition1(self): # # Condition 1: Current Price > 150 SMA and > 200 SMA # if (self.price > self.sma150 and self.price > self.sma200): # return True # def condition2(self): # # Condition 2: 150 SMA and > 200 SMA # if (self.sma150 > self.sma200): # return True # def condition3(self): # # Condition 3: 200 SMA trending up for at least 1 month (ideally 4-5 months) # if self.sma200 > self.sma200_20: # return True # def condition4(self): # # Condition 4: 50 SMA> 150 SMA and 50 SMA> 200 SMA # if self.sma50 > self.sma150 > self.sma200: # return True # def condition5(self): # # Condition 5: Current Price > 50 SMA # if self.price > self.sma50: # return True # def condition6(self): # # Condition 6: Current Price is at least 30% above 52 week low (Many of the best are up 100-300% before coming out of consolidation) # if self.price >= (1.3 * self.low_of_52week): # return True # def condition7(self): # # Condition 7: Current Price is within 25% of 52 week high # if self.price >= (0.75 * self.high_of_52week): # return True # def condition8(self): # # Condiction 8: IBD RS_Rating greater than 70 # if self.rs_rating >=self.min_rs_rating: # return True # def all_conditions(self): # if all( # [self.condition1(), # self.condition2(), # self.condition3(), # self.condition4(), # self.condition5(), # self.condition6(), # self.condition7(), # self.condition8()]): # return True # def filedownload(df): # csv = df.to_csv(index=False) # b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions # href = f'<a href="data:file/csv;base64,{b64}" download="MM_stock_screener.csv">Download CSV File</a>' # return href # def stock_screener(index_tinker_name='S&P500', min_vol=5e6, min_price=0, days=365, min_rs_rating=70,): # # help(si) # ## fix for yahoo_fin # start_date, end_date = period(days) # yf.pdr_override() # index_tinker = { # 'DOW': 'DOW', # 'NASDAQ': '^IXIC', # "S&P500": '^GSPC' # } # index_list = { # 'DOW': si.tickers_sp500(), # 'NASDAQ': si.tickers_nasdaq(), # "S&P500": si.tickers_sp500() # } # # st.header(f'Stock Screener {index_tinker_name}') # # stocklist = si.tickers_sp500() # min_volume = min_vol # # index_name = '^GSPC' # SPY or S&P 500 # stocklist = index_list.get(index_tinker_name)[:] # index_rs_strange_value = calc_relative_strength( # get_stock( # index_tinker[index_tinker_name], days # ) # ) # final = [] # index = [] # exclude_list = [] # all_data = [] # latest_iteration = st.empty() # having_break = st.empty() # bar = st.progress(0) # total = len(stocklist) # for num, stock_name in enumerate(stocklist): # print(f"checking {num}:{stock_name}") # if stock_name in exclude_list: # continue # FAILED = False # df = get_stock(stock_name) # # print('**',df) # if df is False: # print(f'SKIPPED to download {stock_name} {num}') # continue # stock_meta = Moving_avg(stock_name, df, index_rs_strange_value, min_rs_rating) # time.sleep(0.2) # if stock_meta.all_conditions(): # print(f'Passed conditions: {stock_name}') # final.append(stock_meta.as_dict()) # else: # print(f'Failed conditions: {stock_name}') # # all_data.append(stock_meta.as_dict()) # latest_iteration.text(f'Stocks Processed: {(num+1)}/{total}') # bar.progress((num+1)/total) # if num == 0: # continue # if num % 10 == 0: # for i in list(range(5))[::-1]: # having_break.text(f'waiting for {i}sec') # time.sleep(1) # # having_break = st.empty() # if num % 100 == 0: # for i in list(range(3))[::-1]: # having_break.text(f'waiting for {i}min') # time.sleep(60) # # having_break = st.empty() # # time.sleep(5*60) # final_df = pd.DataFrame(final) # final_df['price_change_highest'] = 100 * ( 1- ( final_df["Curren t Price"]/final_df['52 Week High'] ) ) # # all_data_df = pd.DataFrame(all_data) # return final_df # # df_download(final_df), unsafe_allow_html=True # def df_download(df, filename='', index=False): # csv = df.to_csv(index=index) # b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions # href = f'<a href="data:file/csv;base64,{b64}" download="{filename}">Download CSV File</a>' # return href ########################################## # def df_download(df, filename, index=False): # path = Path('../exported') / filename # csv = df.to_csv(path, index=index) # # b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions # href = f'href="data:file/csv;base64,{b64}" download="{filename}"' # return href # TODO: add processing for UK stocks
[ 2, 13578, 62, 1416, 260, 877, 13, 9078, 198, 198, 6738, 19798, 292, 62, 19608, 533, 5067, 1330, 1366, 355, 279, 7109, 198, 6738, 331, 12992, 62, 15643, 1330, 4283, 62, 10951, 355, 33721, 198, 2, 1330, 331, 12992, 62, 15643, 198, 2, ...
2.208287
3,572
from flask import request from operator import or_ from zeus.models import FileCoverage, Revision from zeus.utils.builds import fetch_build_for_revision from .base_revision import BaseRevisionResource from ..schemas import FileCoverageSchema filecoverage_schema = FileCoverageSchema(many=True)
[ 6738, 42903, 1330, 2581, 198, 6738, 10088, 1330, 393, 62, 198, 198, 6738, 1976, 27650, 13, 27530, 1330, 9220, 7222, 1857, 11, 46604, 198, 6738, 1976, 27650, 13, 26791, 13, 11249, 82, 1330, 21207, 62, 11249, 62, 1640, 62, 260, 10178, 1...
3.465116
86
# License: Apache-2.0 from ..util import util from feature_gen_str import string_length from typing import List, Union import numpy as np import pandas as pd import databricks.koalas as ks from._base_string_feature import _BaseStringFeature pd.options.mode.chained_assignment = None class StringLength(_BaseStringFeature): """Create new columns based on the length of its elements. Parameters ---------- columns : List[str] List of columns. Examples --------- * fit & transform with `pandas` >>> import pandas as pd >>> from gators.feature_generation_str import StringLength >>> X = pd.DataFrame({'A': ['qwe', 'as', ''], 'B': [1, 22, 333]}) >>> obj = StringLength(columns=['A','B']) >>> obj.fit_transform(X) A B A__length B__length 0 qwe 1 3.0 1.0 1 as 22 2.0 2.0 2 333 0.0 3.0 * fit & transform with `koalas` >>> import databricks.koalas as ks >>> from gators.feature_generation_str import StringLength >>> X = ks.DataFrame({'A': ['qwe', 'as', ''], 'B': [1, 22, 333]}) >>> obj = StringLength(columns=['A','B']) >>> obj.fit_transform(X) A B A__length B__length 0 qwe 1 3.0 1.0 1 as 22 2.0 2.0 2 333 0.0 3.0 * fit with `pandas` & transform with `NumPy` >>> import pandas as pd >>> from gators.feature_generation_str import StringLength >>> X = pd.DataFrame({'A': ['qwe', 'as', ''], 'B': [1, 22, 333]}) >>> obj = StringLength(columns=['A','B']) >>> _ = obj.fit(X) >>> obj.transform_numpy(X.to_numpy()) array([['qwe', 1, 3.0, 1.0], ['as', 22, 2.0, 2.0], ['', 333, 0.0, 3.0]], dtype=object) * fit with `koalas` & transform with `NumPy` >>> import databricks.koalas as ks >>> from gators.feature_generation_str import StringLength >>> X = ks.DataFrame({'A': ['qwe', 'as', ''], 'B': [1, 22, 333]}) >>> obj = StringLength(columns=['A','B']) >>> _ = obj.fit(X) >>> obj.transform_numpy(X.to_numpy()) array([['qwe', 1, 3.0, 1.0], ['as', 22, 2.0, 2.0], ['', 333, 0.0, 3.0]], dtype=object) """ def fit(self, X: Union[pd.DataFrame, ks.DataFrame], y: Union[pd.Series, ks.Series] = None) -> 'StringLength': """Fit the transformer on the dataframe `X`. Parameters ---------- X : Union[pd.DataFrame, ks.DataFrame]. Input dataframe. y : None None. Returns ------- StringLength Instance of itself. """ self.check_dataframe(X) self.idx_columns = util.get_idx_columns( columns=X.columns, selected_columns=self.columns ) return self def transform( self, X: Union[pd.DataFrame, ks.DataFrame] ) -> Union[pd.DataFrame, ks.DataFrame]: """Transform the dataframe `X`. Parameters ---------- X : Union[pd.DataFrame, ks.DataFrame]. Input dataframe. Returns ------- Union[pd.DataFrame, ks.DataFrame] Transformed dataframe. """ self.check_dataframe(X) for col, name in zip(self.columns, self.column_names): X.loc[:, name] = X.loc[:, col].fillna('').astype(str).replace( {'nan': ''}).str.len().astype(np.float64) pass return X def transform_numpy(self, X: np.ndarray) -> np.ndarray: """Transform the NumPy array `X`. Parameters ---------- X : np.ndarray Input array. Returns ------- np.ndarray Transformed array. """ self.check_array(X) return string_length(X, self.idx_columns)
[ 2, 13789, 25, 24843, 12, 17, 13, 15, 198, 6738, 11485, 22602, 1330, 7736, 198, 6738, 3895, 62, 5235, 62, 2536, 1330, 4731, 62, 13664, 198, 6738, 19720, 1330, 7343, 11, 4479, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, ...
2.070745
1,880
"""This module gets a dataframe of seattle building permits checks column names""" import pandas as pd import collections def get_permits(data_frame=pd.read_csv("https://data.seattle.gov/api/views/76t5-zqzr/rows.csv?accessType=DOWNLOAD", usecols=["PermitClass", "PermitTypeDesc", "EstProjectCost"], dtype={"PermitClass": object, "PermitTypeDesc": object, "EstProjectCost":float})): """ Gets the building permits """ permits = data_frame permits = permits.dropna() check_col_names(permits) return permits def check_col_names(data_frame): """ Checks the dataframe column names """ df_cols_read = data_frame.columns df_cols_expect = ["PermitClass", "PermitTypeDesc", "EstProjectCost"] if len(df_cols_read) != len(df_cols_read): raise ValueError("Different numbers of columns!") for col in df_cols_expect: if col not in df_cols_read: raise ValueError("Column names not the same")
[ 37811, 1212, 8265, 3011, 257, 1366, 14535, 286, 384, 1999, 2615, 13892, 8794, 5721, 3891, 37811, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 17268, 628, 198, 4299, 651, 62, 16321, 896, 7, 7890, 62, 14535, 28, 30094, 13, 961, 62,...
2.404651
430
# This file is part of the CERN Indico plugins. # Copyright (C) 2014 - 2022 CERN # # The CERN Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; see # the LICENSE file for more details. from datetime import date, timedelta from flask import request from wtforms import SelectField, StringField from wtforms.fields import IntegerField from wtforms.fields.simple import TextAreaField from wtforms.validators import DataRequired, NumberRange, Optional from indico.modules.events.requests import RequestFormBase from indico.web.forms.base import IndicoForm, generated_data from indico.web.forms.fields import IndicoDateField from indico.web.forms.validators import Exclusive, IndicoRegexp from indico_vc_assistance import _
[ 2, 770, 2393, 318, 636, 286, 262, 327, 28778, 1423, 3713, 20652, 13, 198, 2, 15069, 357, 34, 8, 1946, 532, 33160, 327, 28778, 198, 2, 198, 2, 383, 327, 28778, 1423, 3713, 20652, 389, 1479, 3788, 26, 345, 460, 17678, 4163, 198, 2, ...
3.654378
217
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 27 08:17:57 2019 @author: ts-fernando.takada """ import numpy as np import pandas as pd import matplotlib.pyplot as plt consNumHc = 5 dataset = pd.read_csv("Mall_Customers.csv") x = dataset.iloc[:,[3, 4]].values # y = dataset.iloc[:,].values # Using dendrongram to find out the optimal number of clusters import scipy.cluster.hierarchy as sch dendrongram = sch.dendrogram(sch.linkage(x, method = 'ward')) plt.title('Dendrogram') plt.xlabel('Customers') plt.ylabel('Euclidean Distance') plt.show() # Fitting hierarchical clustering to the 'problem' dataset from sklearn.cluster import AgglomerativeClustering hc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward') yHc = hc.fit_predict(x) # Visualizing the clusters plt.scatter(x[yHc == 0, 0], x[yHc == 0, 1], s = 100, c = 'red', label = 'Carefull') plt.scatter(x[yHc == 1, 0], x[yHc == 1, 1], s = 100, c = 'blue', label = 'Standard') plt.scatter(x[yHc == 2, 0], x[yHc == 2, 1], s = 100, c = 'green', label = 'Target') plt.scatter(x[yHc == 3, 0], x[yHc == 3, 1], s = 100, c = 'black', label = 'Careless') plt.scatter(x[yHc == 4, 0], x[yHc == 4, 1], s = 100, c = 'orange', label = 'Sensible') plt.title('Cluster of clients') plt.xlabel('Annual Income (k$)') plt.ylabel('Spending score (1-100)') plt.legend() plt.show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 1526, 2681, 8487, 25, 1558, 25, 3553, 13130, 198, 198, 31, 9800, 25, 40379, 12, 69,...
2.378893
578
import os from unittest import TestCase from ievv_coderefactor.file_or_directory_renamer import FileOrDirectoryRenamer from ievv_coderefactor.replacer_registry import RegexReplacer from tests.directory_and_file_mixin import DirectoryAndFileMixin
[ 11748, 28686, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 220, 11203, 85, 62, 19815, 567, 31412, 13, 7753, 62, 273, 62, 34945, 62, 918, 2382, 1330, 9220, 5574, 43055, 26764, 2382, 198, 6738, 220, 11203, 85, 62, 19815,...
3.351351
74
from artron import _py6
[ 198, 6738, 1242, 1313, 1330, 4808, 9078, 21, 628, 628 ]
2.8
10
import time import sys # Meant to be used with client-adapter to enable communicating via stdin/stdout. seq = ["u"] * 3 + ["r"] * 20 + ["d"] * 5 + ["l"] * 5 print("seq_bot_txt") counter = 0 while True: data = input() if data in ["WIN", "LOSS", "TIE"]: print(data) break my_pos, their_pos = (int(i) for i in data.strip().split(" ")) print(seq[counter % len(seq)]) # This is how you might do print debugging: print("Moving", seq[counter % len(seq)], file=sys.stderr) counter += 1 time.sleep(0.05)
[ 11748, 640, 198, 11748, 25064, 198, 198, 2, 2185, 415, 284, 307, 973, 351, 5456, 12, 324, 3429, 284, 7139, 22889, 2884, 14367, 259, 14, 19282, 448, 13, 198, 198, 41068, 796, 14631, 84, 8973, 1635, 513, 1343, 14631, 81, 8973, 1635, 1...
2.454955
222
default_app_config ='profiles.apps.ProfilesConfig'
[ 12286, 62, 1324, 62, 11250, 796, 6, 5577, 2915, 13, 18211, 13, 15404, 2915, 16934, 6 ]
3.125
16
from docs_conf.conf import * #extensions = ['recommonmark']
[ 6738, 34165, 62, 10414, 13, 10414, 1330, 1635, 198, 198, 2, 2302, 5736, 796, 37250, 260, 11321, 4102, 20520 ]
3.157895
19
"""Python code/sdk/application/ApplicationConfig.py.""" from typing import Dict from ..common.constants import APPLICATION_MIN_TOKEN_LENGTH, DEFAULT_DOMAIN from ..common.exceptions import FDKInvalidCredentialError
[ 37811, 37906, 2438, 14, 21282, 74, 14, 31438, 14, 23416, 16934, 13, 9078, 526, 15931, 198, 198, 6738, 19720, 1330, 360, 713, 198, 198, 6738, 11485, 11321, 13, 9979, 1187, 1330, 39421, 6234, 62, 23678, 62, 10468, 43959, 62, 43, 49494, ...
3.444444
63
# load TTM model and checkpoint of choice # generate appropriate Ground-truth-aligned spectrograms from source dataset # (maybe) use Dynamic-Time-Warping for cases where Teacher-Forcing cannot be used. # write new "postnet_path|grapheme_transcript|phoneme_transcript|speaker_id|sample_rate|emotion_id|noise_level" octuplets for each clip
[ 198, 2, 3440, 309, 15972, 2746, 290, 26954, 286, 3572, 198, 198, 2, 7716, 5035, 13706, 12, 35310, 12, 41634, 5444, 3828, 9474, 422, 2723, 27039, 198, 198, 2, 357, 25991, 8, 779, 26977, 12, 7575, 12, 54, 5117, 278, 329, 2663, 810, ...
3.343137
102
from panther_base_helpers import deep_get # Remove any unapproved login methods APPROVED_LOGIN_TYPES = { "exchange", "google_password", "reauth", "saml", "unknown", }
[ 6738, 15857, 372, 62, 8692, 62, 16794, 364, 1330, 2769, 62, 1136, 198, 198, 2, 17220, 597, 555, 29137, 17594, 5050, 198, 2969, 41283, 1961, 62, 25294, 1268, 62, 9936, 47, 1546, 796, 1391, 198, 220, 220, 220, 366, 1069, 3803, 1600, 1...
2.435897
78
#!/usr/bin/env python from subprocess import call import os Import("env") # built in targets: (buildprog, size, upload, program, buildfs, uploadfs, uploadfsota) env.AddPreAction("buildprog", clean)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 850, 14681, 1330, 869, 198, 11748, 28686, 198, 20939, 7203, 24330, 4943, 198, 198, 2, 220, 3170, 287, 6670, 25, 357, 11249, 1676, 70, 11, 2546, 11, 9516, 11, 1430, 11, 1382, 95...
3.092308
65
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import io from pathlib import Path import testslide from ....tests import setup from ..async_server_connection import create_memory_text_reader from ..server_event import ( ServerException, ServerInitialized, SocketCreated, create_from_string, Waiter, EventParsingException, )
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, ...
3.394366
142
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Updates the Git cache zips for a project. Example invocation: ./run.py infra.tools.git_cache_updater --project <googlesource.com url> """ # This file is untested, keep as little code as possible in there. import argparse import logging import sys from infra.services.git_cache_updater import git_cache_updater import infra_libs.logs LOGGER = logging.getLogger(__name__) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
[ 2, 15069, 1853, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 37811, 493...
3.097938
194
# ------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ------------------------------------------------------------------------------------------- """High-level wrappers around pyBCKG. Exports: create_connection, a factory method for WetLabAzureConnection WetLabAzureConnection, a child class of pyBCKG's AzureConnection, introducing more functionalities experiment_to_dataframe, a high-level function, returns a data frame witch characterization results TODO: When pyBCKG is refactored, we may need to replace these utilities. """ from cellsig_pipeline.pybckg.connection import create_connection, WetLabAzureConnection # noqa: F401 from cellsig_pipeline.pybckg.core import experiment_to_dataframe # noqa: F401
[ 2, 16529, 22369, 6329, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 357, 36393, 737, 4091, 38559, 24290, 287, 262, 29924, 6808, 329, 5964, 1321, 13, 198, 2, 16529, 22369, ...
4.268519
216
# defining useful type aliases from typing import Tuple, Union # defining useful type aliases SimTime = Union[int, float] EventPriority = int EventID = int ProcessID = int ProcessName = str ResourceID = int ResourceName = str ResourceCapacity = Union[int, float] TimeInterval = Tuple[SimTime]
[ 2, 16215, 4465, 2099, 47217, 198, 6738, 19720, 1330, 309, 29291, 11, 4479, 628, 198, 2, 16215, 4465, 2099, 47217, 198, 8890, 7575, 796, 4479, 58, 600, 11, 12178, 60, 198, 9237, 22442, 414, 796, 493, 198, 9237, 2389, 796, 493, 198, 1...
3.511905
84
from twisted.trial.unittest import TestCase from twisted.internet.error import ConnectionDone from twisted.internet import protocol, defer, reactor from carnifex.endpoint import InductorEndpoint from .mocks import MockProcessInductor stdout, stderr = 1, 2 class InductorEndpointTest(TestCase): """Test connecting a twisted protocol to a process. """
[ 6738, 19074, 13, 45994, 13, 403, 715, 395, 1330, 6208, 20448, 198, 6738, 19074, 13, 37675, 13, 18224, 1330, 26923, 45677, 198, 6738, 19074, 13, 37675, 1330, 8435, 11, 29135, 11, 21905, 198, 6738, 18466, 901, 87, 13, 437, 4122, 1330, 1...
3.646465
99
# coding=utf-8 from os.path import join, dirname from typing import List import numpy as np from .config import load_config from .pose_detection.detections import extract_detections from .pose_detection.mscoco import MSCOCO from .pose_detection.nnet.predict import setup_pose_prediction, extract_cnn_output from .pose_detection.predict import SpatialModel, eval_graph, get_person_conf_multicut class ObjectDetector(object): """ Class for detecting figure parts on image. """ PERSON_CONF_HANDS_SELECTOR = slice(5, 8 + 1 - 2) def detect_objects(self, image: np.ndarray) -> List[np.ndarray]: """ For each figure on image returns np.array of [Lshoulder, Rshoulder, Lelbow, Relbow]. Each component has [x, y], for not found parts [0, 0] is placed. :param image: image to detect :return: all found parts """ image_batch = self._image_to_data(image) # Compute prediction with the CNN outputs_np = self._session.run(self._model_outputs, feed_dict={self._model_inputs: image_batch}) sc_map, loc_ref, pairwise_diff = extract_cnn_output(outputs_np, self._config, self._dataset.pairwise_stats) detections = extract_detections(self._config, sc_map, loc_ref, pairwise_diff) un_label, pos_array, unary_array, p_w_idx_array, pw_array = eval_graph(self._spatial_model, detections) return [ person[self.PERSON_CONF_HANDS_SELECTOR].astype(int) for person in get_person_conf_multicut(self._spatial_model, un_label, unary_array, pos_array) ] @staticmethod def _image_to_data(image): """ Expands image to data vector. :param image: image :return: reshaped """ return np.expand_dims(image, axis=0).astype(float) __all__ = ['ObjectDetector']
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 28686, 13, 6978, 1330, 4654, 11, 26672, 3672, 198, 6738, 19720, 1330, 7343, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 11250, 1330, 3440, 62, 11250, 198, 6738, 764, 3455, 62, ...
2.462151
753
import os from flask import Flask, flash, render_template, redirect, request, url_for APP_ROOT = os.path.dirname(os.path.abspath(__file__)) app = Flask(__name__) app.config['SECRET_KEY'] = "supertopsecretprivatekey1234" @app.route('/', methods=['GET', 'POST']) if __name__ == "__main__": app.run('127.0.0.1')
[ 11748, 28686, 198, 6738, 42903, 1330, 46947, 11, 7644, 11, 8543, 62, 28243, 11, 18941, 11, 2581, 11, 19016, 62, 1640, 198, 198, 24805, 62, 13252, 2394, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, ...
2.569106
123
#! /usr/bin/python # TODO: make chromedriver executable on linux systems # TODO: finish this doc string: """The first script to be run in this project. If this is the first time running in this directory, it should look something like this: penguin-website-colors/ examples/ ... .gitignore __init__.py license.txt penguin.py README.md setup.py In this case, the setup tool will build the necessary project structure. At each step, if the directory entity is already found, it will be skipped. """ import argparse import platform import sys import os import urllib import time from zipfile import ZipFile parser = argparse.ArgumentParser() parser.add_argument('--check-system', help='Validates system for dependency compatibility', action="store_true") parser.add_argument('--no-chromedriver', help='Skips local chromedriver installation', action="store_true") parser.add_argument('--no-uBlock0', help='Skips local uBlock0 installation', action="store_true") parser.add_argument('--no-websites', help='Skips local website list installation', action="store_true") args = parser.parse_args() STATIC_RESOURCES = {'chromedriver': {'latest': 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE', 'zip': 'https://chromedriver.storage.googleapis.com/%s/chromedriver_%s.zip'}, 'uBlock0': {'latest': 'https://github.com/gorhill/uBlock/releases/latest', 'zip': 'https://github.com/gorhill/uBlock/releases/download/%s/uBlock0.chromium.zip'}, 'websites': {'zip': 'http://s3.amazonaws.com/alexa-static/top-1m.csv.zip'}} def update_static_resources(operating_system, exclusions=None): """Resource handler, builds missing directories and calls respective resource update functions. Default behavior is to look for and create missing folders: ./static /chromedriver /uBlock0 /websites Serial calls to update functions for each resource in 'STATIC_RESOURCES'. Calls are hard-coded. Args: operating_system (str): System and architecture necessary to download Chromedriver. Without Chromedriver, this whole project is non-functional so there is no point in downloading any other resources without a supported os. exclusions (iterable, optional): Any keys in 'STATIC_RESOURCES' that should be ignored when updating. Defaults to None. Although 'STATIC_RESOURCES' is hard-coded, 'exclusions' is not checked for extraneous input. """ global STATIC_RESOURCES if exclusions is None: exclusions = [] # create static directory if not present if not os.path.exists('static'): os.makedirs('static') # create separate directories for each non-excluded resource for resource in STATIC_RESOURCES.keys(): if resource not in exclusions and not os.path.exists('static/%s' % resource): os.makedirs('static/%s' % resource) if 'chromedriver' not in exclusions: update_chromedriver(operating_system) if 'uBlock0' not in exclusions: update_uBlock0() if 'websites' not in exclusions: update_websites() def update_chromedriver(formatted_os): """Chromedriver version control and download handler. Looks in 'static/chromedriver' for currently installed versions. Looks at Google's api for latest release. If the last local version, ordered by version number in ascending order, matches the latest release, do nothing. Otherwise, download zip from Google, unzip and place into new version directory 'static/chromedriver/version_%s'. Will throw UserWarning if one of the file names in the zip folder contains either '/' at the beginning, or '..' anywhere as this allows for path manipulation and is most likely a sign of a malicious payload. Args: formatted_os (str): Correctly formatted system + architecture. Can be inserted straight into zip url. """ global STATIC_RESOURCES print '\nUPDATING CHROMEDRIVER ...' # list locally available versions installed_versions = os.listdir('static/chromedriver') print '\n Currently Installed Versions:' if len(installed_versions) == 0: print ' - (none)' else: for version in installed_versions[:-1]: print ' - %s' % version print ' - %s (newest)' % installed_versions[-1] # fetch latest release number from google content, header = urllib.urlretrieve(STATIC_RESOURCES['chromedriver']['latest']) with open(content, 'r') as release_file: latest_release = release_file.readline().strip() print '\n Latest Release Version:\n - version_%s' % latest_release if len(installed_versions) != 0 and 'version_%s' % latest_release == installed_versions[-1]: print '\n Latest chromedriver is already installed.' else: start = time.time() version_directory = 'static/chromedriver/version_%s' % latest_release zip_url = STATIC_RESOURCES['chromedriver']['zip'] % (latest_release, formatted_os) print '\n Downloading newest release from %s' % zip_url # retrieve zip file and load into ZipFile object content, header = urllib.urlretrieve(zip_url) with ZipFile(content, 'r') as zip_object: if any(f.startswith('/') or '..' in f for f in zip_object.namelist()): raise UserWarning('MALICIOUS DOWNLOAD DETECTED: %s\n contains suspicious path manipulation!\n%s' % (zip_url, '\n -> '.join(zip_object.namelist()))) # create new directory for the latest version os.makedirs(version_directory) # extract into new directory zip_object.extract(zip_object.namelist()[0], version_directory) print ' Chromedriver downloaded and unzipped in %.2f seconds' % (time.time() - start) def update_uBlock0(): """uBlock Origin version control and download handler. Looks in 'static/uBlock0' for currently installed versions. Looks at Gitbub's api for latest release. If the last local version, ordered by version number in ascending order, matches the latest release, do nothing. Otherwise, download zip from Github, unzip and place into new version directory 'static/uBlock0/version_%s'. Will throw UserWarning if one of the file names in the zip folder contains either '/' at the beginning, or '..' anywhere as this allows for path manipulation and is most likely a sign of a malicious payload. """ global STATIC_RESOURCES print '\nUPDATING UBLOCK ORIGIN ...' # list locally available versions installed_versions = os.listdir('static/uBlock0') print '\n Currently Installed Versions:' if len(installed_versions) == 0: print ' - (none)' else: for version in installed_versions[:-1]: print ' - %s' % version print ' - %s (newest)' % installed_versions[-1] # fetch latest release number from Github latest_redirect = urllib.urlopen(STATIC_RESOURCES['uBlock0']['latest']).geturl() # Github api redirects to latest latest_release = latest_redirect.split('/')[-1] print '\n Latest Release Version:\n - version_%s' % latest_release if len(installed_versions) != 0 and 'version_%s' % latest_release == installed_versions[-1]: print '\n Latest uBlock0 is already installed.' else: start = time.time() version_directory = 'static/uBlock0/version_%s' % latest_release zip_url = STATIC_RESOURCES['uBlock0']['zip'] % latest_release print '\n Downloading newest release from %s' % zip_url # retrieve zip file and load into ZipFile object content, header = urllib.urlretrieve(zip_url) with ZipFile(content, 'r') as zip_object: if any(f.startswith('/') or '..' in f for f in zip_object.namelist()): raise UserWarning('MALICIOUS DOWNLOAD DETECTED: %s\n contains suspicious path manipulation!\n%s' % (zip_url, '\n -> '.join(zip_object.namelist()))) # create new directory for the latest version os.makedirs(version_directory) # extract into new directory for f in zip_object.namelist(): zip_object.extract(f, version_directory) print ' uBlock0 downloaded and unzipped in %.2f seconds' % (time.time() - start) def update_websites(): """Alexa Top Million Websites version control and download handler. Looks in 'static/websites' for currently installed versions. Looks at the date for the 'latest release'. If the last local version, ordered by version number in ascending order, matches the latest release, do nothing. Otherwise, download zip from Alexa, unzip and place into new version directory 'static/websites/version_%s'. Will throw UserWarning if one of the file names in the zip folder contains either '/' at the beginning, or '..' anywhere as this allows for path manipulation and is most likely a sign of a malicious payload. """ global STATIC_RESOURCES print '\nUPDATING WEBSITES ...' # list locally available versions installed_versions = os.listdir('static/websites') print '\n Currently Installed Versions:' if len(installed_versions) == 0: print ' - (none)' else: for version in installed_versions[:-1]: print ' - %s' % version print ' - %s (newest)' % installed_versions[-1] # latest version is today's date latest_release = time.strftime('%Y.%m.%d') print '\n Latest Release Version:\n - version_%s' % latest_release if len(installed_versions) != 0 and 'version_%s' % latest_release == installed_versions[-1]: print '\n Latest website list is already installed.' else: start = time.time() version_directory = 'static/websites/version_%s' % latest_release new_csv_path = version_directory + '/websites.csv' zip_url = STATIC_RESOURCES['websites']['zip'] print '\n Downloading newest release from %s' % zip_url # retrieve zip file and load into ZipFile object content, header = urllib.urlretrieve(zip_url) with ZipFile(content, 'r') as zip_object: if any(f.startswith('/') or '..' in f for f in zip_object.namelist()): raise UserWarning('MALICIOUS DOWNLOAD DETECTED: %s\n contains suspicious path manipulation!\n%s' % (zip_url, '\n -> '.join(zip_object.namelist()))) # create new directory for the latest version os.makedirs(version_directory) with zip_object.open(zip_object.namelist()[0]) as pre_scrubbed_list: with open(new_csv_path, 'w') as scrubbed_list_as_csv: # use a dictionary to check overlapping domains collision_dictionary = dict() for pre_scrubbed_count, line in enumerate(pre_scrubbed_list): # '10,google.co.uk\n' -> 'google.co.uk', 'google' full_address = line.strip().split(',')[1] base_domain = full_address.split('.')[0] # check if base domain is already recorded if base_domain not in collision_dictionary: collision_dictionary[base_domain] = 0 scrubbed_list_as_csv.write(full_address + '\n') scrubbed_count = len(collision_dictionary) reduction = 100.0 * (1.0 - (1.0 * scrubbed_count / pre_scrubbed_count)) print ' Websites downloaded and unzipped in %.2f seconds' % (time.time() - start) print ' Condensed %d urls into %d (%.3f%% reduction)' % (pre_scrubbed_count, scrubbed_count, reduction) def check_os(): """Detect system and architecture of local system. Chromedriver runs platform specific, download urls look like: '... /2.29/chromedriver_win32.zip' '... /2.29/chromedriver_mac32.zip' '... /2.29/chromedriver_linux32.zip' '... /2.29/chromedriver_linux64.zip' Returns: tuple (bool, str, str): The first element is if the detected system and architecture is valid. The second is the properly formatted system and architecture for Chromedriver download url. The third is a 'user-friendly' representation of the system. """ operating_system = sys.platform if operating_system.startswith('linux'): # get system architecture, necessary only if linux architecture = platform.architecture()[0].rstrip('bit') return True, 'linux%s' % architecture, 'Linux' elif operating_system == 'win32': return True, 'win32', 'Windows' elif operating_system == 'darwin': return True, 'mac32', 'MacOS' else: return False, '', operating_system if __name__ == "__main__": if args.check_system: valid, url_format, detected_system = check_os() if valid: print 'VALID: Detected operating system \'%s\' is supported.' % detected_system else: print 'INVALID: Detected operating system \'%s\' is not supported.' % detected_system else: if args.no_chromedriver and args.no_uBlock0 and args.no_websites: import this quit() exclusions = [] if args.no_chromedriver: exclusions.append('chromedriver') if args.no_uBlock0: exclusions.append('uBlock0') if args.no_websites: exclusions.append('websites') print 'Running Setup\nExclusions = %s\n%s\n' % (str(exclusions), '*' * 50) valid, url_format, detected_system = check_os() if valid: print 'Detected operating system \'%s\' is supported.' % detected_system update_static_resources(url_format, exclusions)
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 198, 198, 2, 16926, 46, 25, 787, 15358, 276, 38291, 28883, 319, 32639, 3341, 198, 2, 16926, 46, 25, 5461, 428, 2205, 4731, 25, 198, 37811, 464, 717, 4226, 284, 307, 1057, 287, 428, 1628, 13,...
2.545943
5,583
from typing import Optional import torch from torch import nn, Tensor from torch.autograd import grad def vfga(model: nn.Module, inputs: Tensor, labels: Tensor, targeted: bool, max_iter: Optional[int] = None, n_samples: int = 10, large_memory: bool = False) -> Tensor: """Voting Folded Gaussian Attack (VFGA) attack from https://arxiv.org/abs/2011.12423. Parameters ---------- model : nn.Module Model to attack. inputs : Tensor Inputs to attack. Should be in [0, 1]. labels : Tensor Labels corresponding to the inputs if untargeted, else target labels. targeted : bool Whether to perform a targeted attack or not. max_iter : int Maximum number of iterations for the attack. If None is provided, the attack will run as long as adversarial examples are not found and non-modified pixels are left. n_samples : int Number of random samples to draw in each iteration. large_memory : bool If True, performs forward propagations on all randomly perturbed inputs in one batch. This is slightly faster for small models but also uses `n_samples` times more memory. This should only be used when working on small models. For larger models, the speed gain is negligible, so this option should be left to False. Returns ------- adv_inputs : Tensor Modified inputs to be adversarial to the model. """ batch_size, *input_shape = inputs.shape batch_view = lambda tensor: tensor.view(-1, *[1] * (inputs.ndim - 1)) input_view = lambda tensor: tensor.view(-1, *input_shape) device = inputs.device model_ = lambda t: model(t).softmax(dim=1) adv_inputs = inputs.clone() best_adv = inputs.clone() adv_found = torch.zeros(batch_size, device=device, dtype=torch.bool) max_iter = max_iter or inputs[0].numel() for i in range(max_iter): Γ = adv_inputs == inputs Γ_empty = ~Γ.flatten(1).any(1) if (Γ_empty | adv_found).all(): break to_attack = ~(Γ_empty | adv_found) inputs_, labels_, Γ_ = adv_inputs[to_attack], labels[to_attack], Γ[to_attack] batch_size_ = len(inputs_) inputs_.requires_grad_(True) Γ_inf = torch.zeros_like(Γ_, dtype=torch.float).masked_fill_(~Γ_, float('inf')) probs = model_(inputs_) label_probs = probs.gather(1, labels_.unsqueeze(1)).squeeze(1) grad_label_probs = grad(label_probs.sum(), inputs=inputs_, only_inputs=True)[0] inputs_.detach_() # find index of most relevant feature if targeted: i_plus = ((1 - inputs_) * grad_label_probs - Γ_inf).flatten(1).argmax(dim=1, keepdim=True) i_minus = (inputs_ * grad_label_probs + Γ_inf).flatten(1).argmin(dim=1, keepdim=True) else: i_plus = ((1 - inputs_) * grad_label_probs + Γ_inf).flatten(1).argmin(dim=1, keepdim=True) i_minus = (inputs_ * grad_label_probs - Γ_inf).flatten(1).argmax(dim=1, keepdim=True) # compute variance of gaussian noise θ_plus = 1 - inputs_.flatten(1).gather(1, i_plus) θ_minus = inputs_.flatten(1).gather(1, i_minus) # generate random perturbation from folded Gaussian noise S_plus = θ_plus.sqrt() * torch.randn(batch_size_, n_samples, device=device).abs() S_minus = -θ_minus.sqrt() * torch.randn(batch_size_, n_samples, device=device).abs() # add perturbation to inputs perturbed_inputs = inputs_.flatten(1).unsqueeze(1).repeat(1, 2 * n_samples, 1) i_plus_minus = torch.cat([i_plus, i_minus], dim=1).repeat_interleave(n_samples, dim=1) S_plus_minus = torch.cat([S_plus, S_minus], dim=1) perturbed_inputs.scatter_add_(2, i_plus_minus.unsqueeze(2), S_plus_minus.unsqueeze(2)) perturbed_inputs.clamp_(min=0, max=1) # get probabilities for perturbed inputs if large_memory: new_probs = model_(input_view(perturbed_inputs)) else: new_probs = [] for chunk in torch.chunk(input_view(perturbed_inputs), chunks=n_samples): new_probs.append(model_(chunk)) new_probs = torch.cat(new_probs, dim=0) new_probs = new_probs.view(batch_size_, 2 * n_samples, -1) new_preds = new_probs.argmax(dim=2) new_label_probs = new_probs.gather(2, labels_.view(-1, 1, 1).expand(-1, 2 * n_samples, 1)).squeeze(2) if targeted: # finding the index of max probability for target class. If a sample is adv, it will be prioritized. If # several are adversarial, taking the index of the adv sample with max probability. adv_found_ = new_preds == labels_.unsqueeze(1) best_sample_index = (new_label_probs + adv_found_.float() * new_label_probs.max()).argmax(dim=1) else: # finding the index of min probability for original class. If a sample is adv, it will be prioritized. If # several are adversarial, taking the index of the adv sample with min probability. adv_found_ = new_preds != labels_.unsqueeze(1) best_sample_index = (new_label_probs - adv_found_.float() * new_label_probs.min()).argmin(dim=1) # update trackers adv_inputs[to_attack] = input_view(perturbed_inputs[range(batch_size_), best_sample_index]) preds = new_preds.gather(1, best_sample_index.unsqueeze(1)).squeeze(1) is_adv = (preds == labels_) if targeted else (preds != labels_) adv_found[to_attack] = is_adv best_adv[to_attack] = torch.where(batch_view(is_adv), adv_inputs[to_attack], best_adv[to_attack]) return best_adv
[ 6738, 19720, 1330, 32233, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 11, 309, 22854, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 3915, 628, 198, 4299, 410, 69, 4908, 7, 19849, 25, 299, 77, 13, 26796, 11, 198, 220, 220...
2.325355
2,465
''' Problem 19 14 June 2002 You are given the following information, but you may prefer to do some research for yourself. - 1 Jan 1900 was a Monday. - Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? ---------------------------------------------------------- Created on 01.02.2012 @author: ahallmann ''' import unittest import timeit _days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # ----------------------------------------- if __name__ == '__main__': unittest.main() if __name__ == '__main__': t = timeit.Timer("run()", "from __main__ import run") count = 10000 print str(t.timeit(count)) + " seconds for " + str(count) + " runs"
[ 7061, 6, 201, 198, 40781, 678, 201, 198, 1415, 2795, 6244, 201, 198, 201, 198, 1639, 389, 1813, 262, 1708, 1321, 11, 475, 345, 743, 4702, 284, 466, 617, 2267, 329, 3511, 13, 201, 198, 201, 198, 220, 532, 352, 2365, 21489, 373, 257...
2.872727
385