content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import argparse import os import pickle import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--mnist', action='store_true', default=False, help='open mnist result') args = parser.parse_args() try: if args.mnist: f = open(os.path.join('./result/result_mnist.pickle')) result = pickle.load(f) f.close() pathnet_first = [] pathnet_second = [] for res in result: pathnet_first.append(res[2]) pathnet_second.append(res[3]) subplot('111', pathnet_first, pathnet_second,'MNIST') plt.show() else: f = open(os.path.join('./result/result_cifar_svhn.pickle')) result = pickle.load(f) f.close() cifar_first = [] cifar_second = [] svhn_first = [] svhn_second = [] for res in result: if res[0] == 'pathnet_cifar_first': cifar_first.append(res[2]) svhn_second.append(res[3]) else: svhn_first.append(res[2]) cifar_second.append(res[3]) subplot('211', cifar_first, cifar_second,'CIFAR-10') subplot('212', svhn_first, svhn_second,'cSVHN') plt.show() except IOError: print("Result file does not exist")
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 489, 83, 13, 7635, 13, 1904, 10786, 1130, 29487, 11537, 198, 198, 48610...
2.015896
692
import torch
[ 11748, 28034, 628 ]
4.666667
3
# Copyright 2015-2018 David Hadka # # This file is part of Platypus, a Python module for designing and using # evolutionary algorithms (EAs) and multiobjective evolutionary algorithms # (MOEAs). # # Platypus is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Platypus is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Platypus. If not, see <http://www.gnu.org/licenses/>. import unittest from mock import patch from ..core import Problem, Solution from ..types import Permutation from ..operators import Swap
[ 2, 15069, 1853, 12, 7908, 3271, 11161, 4914, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 32715, 4464, 385, 11, 257, 11361, 8265, 329, 18492, 290, 1262, 198, 2, 16673, 16113, 357, 36, 1722, 8, 290, 5021, 15252, 425, 16673, 16113, 198, ...
3.850806
248
#!/usr/bin/env python # -*- coding: utf-8 -*-are not covered by the UCLB ACP-A Licence, from __future__ import absolute_import, division, print_function import tensorflow as tf def bilinear_sampler_1d_h(input_images, x_offset, wrap_mode='border', name='bilinear_sampler', **kwargs): ''' : x_offset--X : x, , , exsamples:[1,2,3] --> [1,1,2,2,3,3] ''' # get_disp,. def _transform(input_images, x_offset): ''' meshgridXY exsamples: _width=3linspace(0.0,_width_f-1.0,_width)[ 0., 1., 2.]height >>> x = tf.linspace(0.0, 2.0, 3) >>> sess.run(x) array([0., 1., 2. ], dtype = float32) >>> x = tf.linspace(0.0, 2.0, 3) >>> y = tf.linspace(0.0, 4.0, 5) >>> x_t, y_t = tf.meshgrid(x, y) >>> sess.run(x_t) array([0., 1., 2.], [0., 1., 2.], [0., 1., 2.], [0., 1., 2.], [0., 1., 2.]], dtype=float32) >>> sess.run(y_t) array([0., 0., 0.], [1., 1., 1.], [2., 2., 2.], [3., 3., 3.], [4., 4., 4.]], dtype=float32) >>> x_t_flat = tf.reshape(x_t, (1, -1)) >>> y_t_flat = tf.reshape(y_t, (1, -1)) >>> sess.run(x_t_flat) array([[0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.]], dtype=float32) >>> sess.run(y_t_flat) array([[0., 0., 0., 1., 1., 1., 2., 2., 2., 3., 3., 3., 4., 4., 4.]], dtype=float32) >>> x_t_flat = tf.tile(x_t_flat, tf.stack([2,1])) >>> sess.run(x_t_flat) arraay([[0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.], [0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.]], dtype=float32) >>> x_t_flat = tf.reshape(x_t_flat, (1, -1)) >>> sess.run(x_t_flat) array([[0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2., 0., 1., 2.]], dtype=float32) ''' with tf.variable_scope('transform'): # grid of (x_t, y_t, 1), eq (1) in ref [1] x_t, y_t = tf.meshgrid(tf.linspace(0.0, _width_f - 1.0, _width), tf.linspace(0.0 , _height_f - 1.0 , _height)) x_t_flat = tf.reshape(x_t, (1, -1)) y_t_flat = tf.reshape(y_t, (1, -1)) x_t_flat = tf.tile(x_t_flat, tf.stack([_num_batch, 1])) y_t_flat = tf.tile(y_t_flat, tf.stack([_num_batch, 1])) x_t_flat = tf.reshape(x_t_flat, [-1]) y_t_flat = tf.reshape(y_t_flat, [-1]) x_t_flat = x_t_flat + tf.reshape(x_offset, [-1]) * _width_f input_transformed = _interpolate(input_images, x_t_flat, y_t_flat) output = tf.reshape( input_transformed, tf.stack([_num_batch, _height, _width, _num_channels])) return output with tf.variable_scope(name): ''' [num_batch, height, width, num_channels] ''' _num_batch = tf.shape(input_images)[0] _height = tf.shape(input_images)[1] _width = tf.shape(input_images)[2] _num_channels = tf.shape(input_images)[3] _height_f = tf.cast(_height, tf.float32) _width_f = tf.cast(_width, tf.float32) _wrap_mode = wrap_mode output = _transform(input_images, x_offset) return output
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 533, 407, 5017, 416, 262, 471, 5097, 33, 7125, 47, 12, 32, 10483, 594, 11, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, ...
1.786807
1,895
#import relevant libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from astropy.io import ascii import json from IPython.display import display, Image from specutils import Spectrum1D from astropy import units from scipy.optimize import curve_fit from scipy.interpolate import interp1d import scipy.integrate as integrate from astropy.time import Time from Supernovae import * #speed of light (km/s) c = 3e5 #Define class to hold releveant information for spectra data #Create Supernovae class to store Spectral objects #define function that converts wavlengths to restframe and corrects flux for redshift, and normalizes flux def Unpack_Spectra(Spectra, z, normalization = [5000,6000]): ''' Args: Spectra - one epoch of spectral data in JSON format from OSN z (float) - redshift of SN normalizationn (list) - 2 item list containing boundaries of region used for normalization Returns: Pandas DataFrame - 2 column dataframe: wavelength and flux Flux is corrected for redshift and normalized Wavelength is converted to SN restframe ''' #Extract Wavelengths wavelengths = [float(x[0]) for x in Spectra] #Extract Fluxes fluxes = [float(x[1]) for x in Spectra] #correct fluxes for redshift fluxes = [correct_flux(flux, z) for flux in fluxes] #Extract fluxes in normalization range rel_flux_range = [x for x in Spectra if (float(x[0])>normalization[0]) & (float(x[0])<normalization[1])] #Make sure there rel_flux_range isnt empty if len(rel_flux_range) == 0: #print('No wavelengths in normalization region, not including spectra') return None #Calculate average flux in this range flux_sum = 0 for x in rel_flux_range: flux_sum += float(x[1]) average_flux = flux_sum / float(len(rel_flux_range)) #Normalize flux fluxes = [float(flux) / average_flux for flux in fluxes] #convert wavelength to restframe wavelengths = [wavelength / float(1 + z) for wavelength in wavelengths] #store in pandas dataframe df = pd.DataFrame() df['Flux'] = fluxes df['Wavelength'] = wavelengths return df def correct_flux(flux_obs, z): ''' Args: flux_obs (int) - observed flux z (int) - redshift Returns: int - redshift corrected flux ''' flux_emit = (z * flux_obs) + flux_obs return flux_emit #Define function to get relevant spectra from OSN JSON data file def create_SN_object(JSON, MJD_max, z): ''' Function to create Supernovae object for given JSON data file from OSN Args: JSON (str) - path to OSN JSON file of interest MJD_max (int) - number of days past maximum brightness phase (int) - phase for spectra of interest Returns: Supernovae - Supernovae object with spectra list filled ''' supernovae = Supernovae(str(JSON[0:-5]), z, MJD_max) #Load OSN json data file = open('../Data/OSN_data/' + str(JSON)) json_data = json.load(file) spectra_data = json_data[JSON[0:-5]]['spectra'] spectra_data = np.array(spectra_data) for i in range(len(spectra_data)): spectra = Spectra(spectra_data[i]['data'], float(spectra_data[i]['time']) / (1+z), z, MJD_max) if spectra.data is None: continue else: supernovae.store_spectra(spectra) return supernovae #Define function to convert calendar date to MJD def convert_date_toMJD(date): ''' Args: date (str) - string of calendar date (e.g. '2002-8-17') Returns: float - MJD value of given calendar date ''' t = Time(date) t.format = 'mjd' return t.value #Define function to calculate absorption velocities def calc_abs_velc(restframe, dopplershifted): ''' Args: restframe (float) - restframe wavelength of absorption dopplershifted (float) - dopplershifted wavelength of absorption Returns: float - corresponding absorption velocity ''' velocity = ((restframe - dopplershifted) / np.float(restframe))* c return velocity
[ 2, 11748, 5981, 12782, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 6468, 28338, 13, 952, 1330, 355, 979, 72, 198, 11748, 33918, 198...
2.492999
1,714
"""Check if userbot alive. If you change these, you become the gayest gay such that even the gay world will disown you.""" import asyncio from telethon import events from telethon.tl.types import ChannelParticipantsAdmins from platform import uname from userbot import ALIVE_NAME from userbot.utils import admin_cmd DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "No name set yet nibba, check pinned in @XtraTgBot"
[ 37811, 9787, 611, 2836, 13645, 6776, 13, 1002, 345, 1487, 777, 11, 345, 1716, 262, 5650, 395, 5650, 884, 326, 772, 262, 5650, 995, 481, 595, 593, 345, 526, 15931, 201, 198, 11748, 30351, 952, 201, 198, 6738, 5735, 400, 261, 1330, 29...
3.354331
127
import os import logging.config from random import randint import zlib import struct import socket import time from PIL import Image import config # from config import ADB_ROOT, ADB_HOST, SCREEN_SHOOT_SAVE_PATH, ShellColor, CONFIG_PATH,enable_adb_host_auto_detect, ADB_SERVER from .ADBClientSession import ADBClientSession from util.socketutil import recvall from . import revconn # from numpy import average, dot, linalg logger = logging.getLogger(__name__)
[ 11748, 28686, 198, 11748, 18931, 13, 11250, 198, 6738, 4738, 1330, 43720, 600, 198, 11748, 1976, 8019, 198, 11748, 2878, 198, 11748, 17802, 198, 11748, 640, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 11748, 4566, 198, 2, 422, 4566...
3.099338
151
import inspect import os from pathlib import Path
[ 11748, 10104, 201, 198, 11748, 28686, 201, 198, 6738, 3108, 8019, 1330, 10644, 201, 198, 201, 198 ]
3.235294
17
import sys from PyQt5.QtWidgets import QApplication from gui import MgallManager if __name__ == "__main__": main()
[ 11748, 25064, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 23416, 198, 198, 6738, 11774, 1330, 337, 39580, 13511, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 13...
2.733333
45
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Define the static list of types and actions for SC2.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numbers import six from pysc2.lib import point from s2clientprotocol import spatial_pb2 as sc_spatial from s2clientprotocol import ui_pb2 as sc_ui def move_camera(action, minimap): """Move the camera.""" minimap.assign_to(action.action_feature_layer.camera_move.center_minimap) def select_point(action, select_point_act, screen): """Select a unit at a point.""" select = action.action_feature_layer.unit_selection_point screen.assign_to(select.selection_screen_coord) select.type = select_point_act def select_rect(action, select_add, screen, screen2): """Select units within a rectangle.""" select = action.action_feature_layer.unit_selection_rect out_rect = select.selection_screen_coord.add() screen_rect = point.Rect(screen, screen2) screen_rect.tl.assign_to(out_rect.p0) screen_rect.br.assign_to(out_rect.p1) select.selection_add = bool(select_add) def select_idle_worker(action, select_worker): """Select an idle worker.""" action.action_ui.select_idle_worker.type = select_worker def select_army(action, select_add): """Select the entire army.""" action.action_ui.select_army.selection_add = select_add def select_warp_gates(action, select_add): """Select all warp gates.""" action.action_ui.select_warp_gates.selection_add = select_add def select_larva(action): """Select all larva.""" action.action_ui.select_larva.SetInParent() # Adds the empty proto field. def select_unit(action, select_unit_act, select_unit_id): """Select a specific unit from the multi-unit selection.""" select = action.action_ui.multi_panel select.type = select_unit_act select.unit_index = select_unit_id def control_group(action, control_group_act, control_group_id): """Act on a control group, selecting, setting, etc.""" select = action.action_ui.control_group select.action = control_group_act select.control_group_index = control_group_id def unload(action, unload_id): """Unload a unit from a transport/bunker/nydus/etc.""" action.action_ui.cargo_panel.unit_index = unload_id def build_queue(action, build_queue_id): """Cancel a unit in the build queue.""" action.action_ui.production_panel.unit_index = build_queue_id def cmd_quick(action, ability_id, queued): """Do a quick command like 'Stop' or 'Stim'.""" action_cmd = action.action_feature_layer.unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued def cmd_screen(action, ability_id, queued, screen): """Do a command that needs a point on the screen.""" action_cmd = action.action_feature_layer.unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued screen.assign_to(action_cmd.target_screen_coord) def cmd_minimap(action, ability_id, queued, minimap): """Do a command that needs a point on the minimap.""" action_cmd = action.action_feature_layer.unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued minimap.assign_to(action_cmd.target_minimap_coord) def autocast(action, ability_id): """Toggle autocast.""" action.action_ui.toggle_autocast.ability_id = ability_id # The list of known types. TYPES = Arguments.types( screen=ArgumentType.point(), minimap=ArgumentType.point(), screen2=ArgumentType.point(), queued=ArgumentType.enum([False, True]), # (now vs add to queue) control_group_act=ArgumentType.enum([ sc_ui.ActionControlGroup.Recall, sc_ui.ActionControlGroup.Set, sc_ui.ActionControlGroup.Append, sc_ui.ActionControlGroup.SetAndSteal, sc_ui.ActionControlGroup.AppendAndSteal, ]), control_group_id=ArgumentType.scalar(10), select_point_act=ArgumentType.enum([ sc_spatial.ActionSpatialUnitSelectionPoint.Select, sc_spatial.ActionSpatialUnitSelectionPoint.Toggle, sc_spatial.ActionSpatialUnitSelectionPoint.AllType, sc_spatial.ActionSpatialUnitSelectionPoint.AddAllType, ]), select_add=ArgumentType.enum([False, True]), # (select vs select_add) select_unit_act=ArgumentType.enum([ sc_ui.ActionMultiPanel.SingleSelect, sc_ui.ActionMultiPanel.DeselectUnit, sc_ui.ActionMultiPanel.SelectAllOfType, sc_ui.ActionMultiPanel.DeselectAllOfType, ]), select_unit_id=ArgumentType.scalar(500), # Depends on current selection. select_worker=ArgumentType.enum([ sc_ui.ActionSelectIdleWorker.Set, sc_ui.ActionSelectIdleWorker.Add, sc_ui.ActionSelectIdleWorker.All, sc_ui.ActionSelectIdleWorker.AddAll, ]), build_queue_id=ArgumentType.scalar(10), # Depends on current build queue. unload_id=ArgumentType.scalar(500), # Depends on the current loaded units. ) # Which argument types do each function need? FUNCTION_TYPES = { no_op: [], move_camera: [TYPES.minimap], select_point: [TYPES.select_point_act, TYPES.screen], select_rect: [TYPES.select_add, TYPES.screen, TYPES.screen2], select_unit: [TYPES.select_unit_act, TYPES.select_unit_id], control_group: [TYPES.control_group_act, TYPES.control_group_id], select_idle_worker: [TYPES.select_worker], select_army: [TYPES.select_add], select_warp_gates: [TYPES.select_add], select_larva: [], unload: [TYPES.unload_id], build_queue: [TYPES.build_queue_id], cmd_quick: [TYPES.queued], cmd_screen: [TYPES.queued, TYPES.screen], cmd_minimap: [TYPES.queued, TYPES.minimap], autocast: [], } # Which ones need an ability? ABILITY_FUNCTIONS = {cmd_quick, cmd_screen, cmd_minimap, autocast} # Which ones require a point? POINT_REQUIRED_FUNCS = { False: {cmd_quick, autocast}, True: {cmd_screen, cmd_minimap, autocast}} always = lambda _: True def str(self, space=False): """String version. Set space=True to line them all up nicely.""" return "%s/%s (%s)" % (str(self.id).rjust(space and 4), self.name.ljust(space and 50), "; ".join(str(a) for a in self.args)) class Functions(object): """Represents the full set of functions. Can't use namedtuple since python3 has a limit of 255 function arguments, so build something similar. """ # pylint: disable=line-too-long FUNCTIONS = Functions([ Function.ui_func(0, "no_op", no_op), Function.ui_func(1, "move_camera", move_camera), Function.ui_func(2, "select_point", select_point), Function.ui_func(3, "select_rect", select_rect), Function.ui_func(4, "select_control_group", control_group), Function.ui_func(5, "select_unit", select_unit, lambda obs: obs.ui_data.HasField("multi")), Function.ui_func(6, "select_idle_worker", select_idle_worker, lambda obs: obs.player_common.idle_worker_count > 0), Function.ui_func(7, "select_army", select_army, lambda obs: obs.player_common.army_count > 0), Function.ui_func(8, "select_warp_gates", select_warp_gates, lambda obs: obs.player_common.warp_gate_count > 0), Function.ui_func(9, "select_larva", select_larva, lambda obs: obs.player_common.larva_count > 0), Function.ui_func(10, "unload", unload, lambda obs: obs.ui_data.HasField("cargo")), Function.ui_func(11, "build_queue", build_queue, lambda obs: obs.ui_data.HasField("production")), # Everything below here is generated with gen_actions.py Function.ability(12, "Attack_screen", cmd_screen, 3674), Function.ability(13, "Attack_minimap", cmd_minimap, 3674), Function.ability(14, "Attack_Attack_screen", cmd_screen, 23, 3674), Function.ability(15, "Attack_Attack_minimap", cmd_minimap, 23, 3674), Function.ability(16, "Attack_AttackBuilding_screen", cmd_screen, 2048, 3674), Function.ability(17, "Attack_AttackBuilding_minimap", cmd_minimap, 2048, 3674), Function.ability(18, "Attack_Redirect_screen", cmd_screen, 1682, 3674), Function.ability(19, "Scan_Move_screen", cmd_screen, 19, 3674), Function.ability(20, "Scan_Move_minimap", cmd_minimap, 19, 3674), Function.ability(21, "Behavior_BuildingAttackOff_quick", cmd_quick, 2082), Function.ability(22, "Behavior_BuildingAttackOn_quick", cmd_quick, 2081), Function.ability(23, "Behavior_CloakOff_quick", cmd_quick, 3677), Function.ability(24, "Behavior_CloakOff_Banshee_quick", cmd_quick, 393, 3677), Function.ability(25, "Behavior_CloakOff_Ghost_quick", cmd_quick, 383, 3677), Function.ability(26, "Behavior_CloakOn_quick", cmd_quick, 3676), Function.ability(27, "Behavior_CloakOn_Banshee_quick", cmd_quick, 392, 3676), Function.ability(28, "Behavior_CloakOn_Ghost_quick", cmd_quick, 382, 3676), Function.ability(29, "Behavior_GenerateCreepOff_quick", cmd_quick, 1693), Function.ability(30, "Behavior_GenerateCreepOn_quick", cmd_quick, 1692), Function.ability(31, "Behavior_HoldFireOff_quick", cmd_quick, 3689), Function.ability(32, "Behavior_HoldFireOff_Ghost_quick", cmd_quick, 38, 3689), Function.ability(33, "Behavior_HoldFireOff_Lurker_quick", cmd_quick, 2552, 3689), Function.ability(34, "Behavior_HoldFireOn_quick", cmd_quick, 3688), Function.ability(35, "Behavior_HoldFireOn_Ghost_quick", cmd_quick, 36, 3688), Function.ability(36, "Behavior_HoldFireOn_Lurker_quick", cmd_quick, 2550, 3688), Function.ability(37, "Behavior_PulsarBeamOff_quick", cmd_quick, 2376), Function.ability(38, "Behavior_PulsarBeamOn_quick", cmd_quick, 2375), Function.ability(39, "Build_Armory_screen", cmd_screen, 331), Function.ability(40, "Build_Assimilator_screen", cmd_screen, 882), Function.ability(41, "Build_BanelingNest_screen", cmd_screen, 1162), Function.ability(42, "Build_Barracks_screen", cmd_screen, 321), Function.ability(43, "Build_Bunker_screen", cmd_screen, 324), Function.ability(44, "Build_CommandCenter_screen", cmd_screen, 318), Function.ability(45, "Build_CreepTumor_screen", cmd_screen, 3691), Function.ability(46, "Build_CreepTumor_Queen_screen", cmd_screen, 1694, 3691), Function.ability(47, "Build_CreepTumor_Tumor_screen", cmd_screen, 1733, 3691), Function.ability(48, "Build_CyberneticsCore_screen", cmd_screen, 894), Function.ability(49, "Build_DarkShrine_screen", cmd_screen, 891), Function.ability(50, "Build_EngineeringBay_screen", cmd_screen, 322), Function.ability(51, "Build_EvolutionChamber_screen", cmd_screen, 1156), Function.ability(52, "Build_Extractor_screen", cmd_screen, 1154), Function.ability(53, "Build_Factory_screen", cmd_screen, 328), Function.ability(54, "Build_FleetBeacon_screen", cmd_screen, 885), Function.ability(55, "Build_Forge_screen", cmd_screen, 884), Function.ability(56, "Build_FusionCore_screen", cmd_screen, 333), Function.ability(57, "Build_Gateway_screen", cmd_screen, 883), Function.ability(58, "Build_GhostAcademy_screen", cmd_screen, 327), Function.ability(59, "Build_Hatchery_screen", cmd_screen, 1152), Function.ability(60, "Build_HydraliskDen_screen", cmd_screen, 1157), Function.ability(61, "Build_InfestationPit_screen", cmd_screen, 1160), Function.ability(62, "Build_Interceptors_quick", cmd_quick, 1042), Function.ability(63, "Build_Interceptors_autocast", autocast, 1042), Function.ability(64, "Build_MissileTurret_screen", cmd_screen, 323), Function.ability(65, "Build_Nexus_screen", cmd_screen, 880), Function.ability(66, "Build_Nuke_quick", cmd_quick, 710), Function.ability(67, "Build_NydusNetwork_screen", cmd_screen, 1161), Function.ability(68, "Build_NydusWorm_screen", cmd_screen, 1768), Function.ability(69, "Build_PhotonCannon_screen", cmd_screen, 887), Function.ability(70, "Build_Pylon_screen", cmd_screen, 881), Function.ability(71, "Build_Reactor_quick", cmd_quick, 3683), Function.ability(72, "Build_Reactor_screen", cmd_screen, 3683), Function.ability(73, "Build_Reactor_Barracks_quick", cmd_quick, 422, 3683), Function.ability(74, "Build_Reactor_Barracks_screen", cmd_screen, 422, 3683), Function.ability(75, "Build_Reactor_Factory_quick", cmd_quick, 455, 3683), Function.ability(76, "Build_Reactor_Factory_screen", cmd_screen, 455, 3683), Function.ability(77, "Build_Reactor_Starport_quick", cmd_quick, 488, 3683), Function.ability(78, "Build_Reactor_Starport_screen", cmd_screen, 488, 3683), Function.ability(79, "Build_Refinery_screen", cmd_screen, 320), Function.ability(80, "Build_RoachWarren_screen", cmd_screen, 1165), Function.ability(81, "Build_RoboticsBay_screen", cmd_screen, 892), Function.ability(82, "Build_RoboticsFacility_screen", cmd_screen, 893), Function.ability(83, "Build_SensorTower_screen", cmd_screen, 326), Function.ability(84, "Build_SpawningPool_screen", cmd_screen, 1155), Function.ability(85, "Build_SpineCrawler_screen", cmd_screen, 1166), Function.ability(86, "Build_Spire_screen", cmd_screen, 1158), Function.ability(87, "Build_SporeCrawler_screen", cmd_screen, 1167), Function.ability(88, "Build_Stargate_screen", cmd_screen, 889), Function.ability(89, "Build_Starport_screen", cmd_screen, 329), Function.ability(90, "Build_StasisTrap_screen", cmd_screen, 2505), Function.ability(91, "Build_SupplyDepot_screen", cmd_screen, 319), Function.ability(92, "Build_TechLab_quick", cmd_quick, 3682), Function.ability(93, "Build_TechLab_screen", cmd_screen, 3682), Function.ability(94, "Build_TechLab_Barracks_quick", cmd_quick, 421, 3682), Function.ability(95, "Build_TechLab_Barracks_screen", cmd_screen, 421, 3682), Function.ability(96, "Build_TechLab_Factory_quick", cmd_quick, 454, 3682), Function.ability(97, "Build_TechLab_Factory_screen", cmd_screen, 454, 3682), Function.ability(98, "Build_TechLab_Starport_quick", cmd_quick, 487, 3682), Function.ability(99, "Build_TechLab_Starport_screen", cmd_screen, 487, 3682), Function.ability(100, "Build_TemplarArchive_screen", cmd_screen, 890), Function.ability(101, "Build_TwilightCouncil_screen", cmd_screen, 886), Function.ability(102, "Build_UltraliskCavern_screen", cmd_screen, 1159), Function.ability(103, "BurrowDown_quick", cmd_quick, 3661), Function.ability(104, "BurrowDown_Baneling_quick", cmd_quick, 1374, 3661), Function.ability(105, "BurrowDown_Drone_quick", cmd_quick, 1378, 3661), Function.ability(106, "BurrowDown_Hydralisk_quick", cmd_quick, 1382, 3661), Function.ability(107, "BurrowDown_Infestor_quick", cmd_quick, 1444, 3661), Function.ability(108, "BurrowDown_InfestorTerran_quick", cmd_quick, 1394, 3661), Function.ability(109, "BurrowDown_Lurker_quick", cmd_quick, 2108, 3661), Function.ability(110, "BurrowDown_Queen_quick", cmd_quick, 1433, 3661), Function.ability(111, "BurrowDown_Ravager_quick", cmd_quick, 2340, 3661), Function.ability(112, "BurrowDown_Roach_quick", cmd_quick, 1386, 3661), Function.ability(113, "BurrowDown_SwarmHost_quick", cmd_quick, 2014, 3661), Function.ability(114, "BurrowDown_Ultralisk_quick", cmd_quick, 1512, 3661), Function.ability(115, "BurrowDown_WidowMine_quick", cmd_quick, 2095, 3661), Function.ability(116, "BurrowDown_Zergling_quick", cmd_quick, 1390, 3661), Function.ability(117, "BurrowUp_quick", cmd_quick, 3662), Function.ability(118, "BurrowUp_autocast", autocast, 3662), Function.ability(119, "BurrowUp_Baneling_quick", cmd_quick, 1376, 3662), Function.ability(120, "BurrowUp_Baneling_autocast", autocast, 1376, 3662), Function.ability(121, "BurrowUp_Drone_quick", cmd_quick, 1380, 3662), Function.ability(122, "BurrowUp_Hydralisk_quick", cmd_quick, 1384, 3662), Function.ability(123, "BurrowUp_Hydralisk_autocast", autocast, 1384, 3662), Function.ability(124, "BurrowUp_Infestor_quick", cmd_quick, 1446, 3662), Function.ability(125, "BurrowUp_InfestorTerran_quick", cmd_quick, 1396, 3662), Function.ability(126, "BurrowUp_InfestorTerran_autocast", autocast, 1396, 3662), Function.ability(127, "BurrowUp_Lurker_quick", cmd_quick, 2110, 3662), Function.ability(128, "BurrowUp_Queen_quick", cmd_quick, 1435, 3662), Function.ability(129, "BurrowUp_Queen_autocast", autocast, 1435, 3662), Function.ability(130, "BurrowUp_Ravager_quick", cmd_quick, 2342, 3662), Function.ability(131, "BurrowUp_Ravager_autocast", autocast, 2342, 3662), Function.ability(132, "BurrowUp_Roach_quick", cmd_quick, 1388, 3662), Function.ability(133, "BurrowUp_Roach_autocast", autocast, 1388, 3662), Function.ability(134, "BurrowUp_SwarmHost_quick", cmd_quick, 2016, 3662), Function.ability(135, "BurrowUp_Ultralisk_quick", cmd_quick, 1514, 3662), Function.ability(136, "BurrowUp_Ultralisk_autocast", autocast, 1514, 3662), Function.ability(137, "BurrowUp_WidowMine_quick", cmd_quick, 2097, 3662), Function.ability(138, "BurrowUp_Zergling_quick", cmd_quick, 1392, 3662), Function.ability(139, "BurrowUp_Zergling_autocast", autocast, 1392, 3662), Function.ability(140, "Cancel_quick", cmd_quick, 3659), Function.ability(141, "Cancel_AdeptPhaseShift_quick", cmd_quick, 2594, 3659), Function.ability(142, "Cancel_AdeptShadePhaseShift_quick", cmd_quick, 2596, 3659), Function.ability(143, "Cancel_BarracksAddOn_quick", cmd_quick, 451, 3659), Function.ability(144, "Cancel_BuildInProgress_quick", cmd_quick, 314, 3659), Function.ability(145, "Cancel_CreepTumor_quick", cmd_quick, 1763, 3659), Function.ability(146, "Cancel_FactoryAddOn_quick", cmd_quick, 484, 3659), Function.ability(147, "Cancel_GravitonBeam_quick", cmd_quick, 174, 3659), Function.ability(148, "Cancel_LockOn_quick", cmd_quick, 2354, 3659), Function.ability(149, "Cancel_MorphBroodlord_quick", cmd_quick, 1373, 3659), Function.ability(150, "Cancel_MorphGreaterSpire_quick", cmd_quick, 1221, 3659), Function.ability(151, "Cancel_MorphHive_quick", cmd_quick, 1219, 3659), Function.ability(152, "Cancel_MorphLair_quick", cmd_quick, 1217, 3659), Function.ability(153, "Cancel_MorphLurker_quick", cmd_quick, 2333, 3659), Function.ability(154, "Cancel_MorphLurkerDen_quick", cmd_quick, 2113, 3659), Function.ability(155, "Cancel_MorphMothership_quick", cmd_quick, 1848, 3659), Function.ability(156, "Cancel_MorphOrbital_quick", cmd_quick, 1517, 3659), Function.ability(157, "Cancel_MorphOverlordTransport_quick", cmd_quick, 2709, 3659), Function.ability(158, "Cancel_MorphOverseer_quick", cmd_quick, 1449, 3659), Function.ability(159, "Cancel_MorphPlanetaryFortress_quick", cmd_quick, 1451, 3659), Function.ability(160, "Cancel_MorphRavager_quick", cmd_quick, 2331, 3659), Function.ability(161, "Cancel_MorphThorExplosiveMode_quick", cmd_quick, 2365, 3659), Function.ability(162, "Cancel_NeuralParasite_quick", cmd_quick, 250, 3659), Function.ability(163, "Cancel_Nuke_quick", cmd_quick, 1623, 3659), Function.ability(164, "Cancel_SpineCrawlerRoot_quick", cmd_quick, 1730, 3659), Function.ability(165, "Cancel_SporeCrawlerRoot_quick", cmd_quick, 1732, 3659), Function.ability(166, "Cancel_StarportAddOn_quick", cmd_quick, 517, 3659), Function.ability(167, "Cancel_StasisTrap_quick", cmd_quick, 2535, 3659), Function.ability(168, "Cancel_Last_quick", cmd_quick, 3671), Function.ability(169, "Cancel_HangarQueue5_quick", cmd_quick, 1038, 3671), Function.ability(170, "Cancel_Queue1_quick", cmd_quick, 304, 3671), Function.ability(171, "Cancel_Queue5_quick", cmd_quick, 306, 3671), Function.ability(172, "Cancel_QueueAddOn_quick", cmd_quick, 312, 3671), Function.ability(173, "Cancel_QueueCancelToSelection_quick", cmd_quick, 308, 3671), Function.ability(174, "Cancel_QueuePasive_quick", cmd_quick, 1831, 3671), Function.ability(175, "Cancel_QueuePassiveCancelToSelection_quick", cmd_quick, 1833, 3671), Function.ability(176, "Effect_Abduct_screen", cmd_screen, 2067), Function.ability(177, "Effect_AdeptPhaseShift_screen", cmd_screen, 2544), Function.ability(178, "Effect_AutoTurret_screen", cmd_screen, 1764), Function.ability(179, "Effect_BlindingCloud_screen", cmd_screen, 2063), Function.ability(180, "Effect_Blink_screen", cmd_screen, 3687), Function.ability(181, "Effect_Blink_Stalker_screen", cmd_screen, 1442, 3687), Function.ability(182, "Effect_ShadowStride_screen", cmd_screen, 2700, 3687), Function.ability(183, "Effect_CalldownMULE_screen", cmd_screen, 171), Function.ability(184, "Effect_CausticSpray_screen", cmd_screen, 2324), Function.ability(185, "Effect_Charge_screen", cmd_screen, 1819), Function.ability(186, "Effect_Charge_autocast", autocast, 1819), Function.ability(187, "Effect_ChronoBoost_screen", cmd_screen, 261), Function.ability(188, "Effect_Contaminate_screen", cmd_screen, 1825), Function.ability(189, "Effect_CorrosiveBile_screen", cmd_screen, 2338), Function.ability(190, "Effect_EMP_screen", cmd_screen, 1628), Function.ability(191, "Effect_Explode_quick", cmd_quick, 42), Function.ability(192, "Effect_Feedback_screen", cmd_screen, 140), Function.ability(193, "Effect_ForceField_screen", cmd_screen, 1526), Function.ability(194, "Effect_FungalGrowth_screen", cmd_screen, 74), Function.ability(195, "Effect_GhostSnipe_screen", cmd_screen, 2714), Function.ability(196, "Effect_GravitonBeam_screen", cmd_screen, 173), Function.ability(197, "Effect_GuardianShield_quick", cmd_quick, 76), Function.ability(198, "Effect_Heal_screen", cmd_screen, 386), Function.ability(199, "Effect_Heal_autocast", autocast, 386), Function.ability(200, "Effect_HunterSeekerMissile_screen", cmd_screen, 169), Function.ability(201, "Effect_ImmortalBarrier_quick", cmd_quick, 2328), Function.ability(202, "Effect_ImmortalBarrier_autocast", autocast, 2328), Function.ability(203, "Effect_InfestedTerrans_screen", cmd_screen, 247), Function.ability(204, "Effect_InjectLarva_screen", cmd_screen, 251), Function.ability(205, "Effect_KD8Charge_screen", cmd_screen, 2588), Function.ability(206, "Effect_LockOn_screen", cmd_screen, 2350), Function.ability(207, "Effect_LocustSwoop_screen", cmd_screen, 2387), Function.ability(208, "Effect_MassRecall_screen", cmd_screen, 3686), Function.ability(209, "Effect_MassRecall_Mothership_screen", cmd_screen, 2368, 3686), Function.ability(210, "Effect_MassRecall_MothershipCore_screen", cmd_screen, 1974, 3686), Function.ability(211, "Effect_MedivacIgniteAfterburners_quick", cmd_quick, 2116), Function.ability(212, "Effect_NeuralParasite_screen", cmd_screen, 249), Function.ability(213, "Effect_NukeCalldown_screen", cmd_screen, 1622), Function.ability(214, "Effect_OracleRevelation_screen", cmd_screen, 2146), Function.ability(215, "Effect_ParasiticBomb_screen", cmd_screen, 2542), Function.ability(216, "Effect_PhotonOvercharge_screen", cmd_screen, 2162), Function.ability(217, "Effect_PointDefenseDrone_screen", cmd_screen, 144), Function.ability(218, "Effect_PsiStorm_screen", cmd_screen, 1036), Function.ability(219, "Effect_PurificationNova_screen", cmd_screen, 2346), Function.ability(220, "Effect_Repair_screen", cmd_screen, 3685), Function.ability(221, "Effect_Repair_autocast", autocast, 3685), Function.ability(222, "Effect_Repair_Mule_screen", cmd_screen, 78, 3685), Function.ability(223, "Effect_Repair_Mule_autocast", autocast, 78, 3685), Function.ability(224, "Effect_Repair_SCV_screen", cmd_screen, 316, 3685), Function.ability(225, "Effect_Repair_SCV_autocast", autocast, 316, 3685), Function.ability(226, "Effect_Salvage_quick", cmd_quick, 32), Function.ability(227, "Effect_Scan_screen", cmd_screen, 399), Function.ability(228, "Effect_SpawnChangeling_quick", cmd_quick, 181), Function.ability(229, "Effect_SpawnLocusts_screen", cmd_screen, 2704), Function.ability(230, "Effect_Spray_screen", cmd_screen, 3684), Function.ability(231, "Effect_Spray_Protoss_screen", cmd_screen, 30, 3684), Function.ability(232, "Effect_Spray_Terran_screen", cmd_screen, 26, 3684), Function.ability(233, "Effect_Spray_Zerg_screen", cmd_screen, 28, 3684), Function.ability(234, "Effect_Stim_quick", cmd_quick, 3675), Function.ability(235, "Effect_Stim_Marauder_quick", cmd_quick, 253, 3675), Function.ability(236, "Effect_Stim_Marauder_Redirect_quick", cmd_quick, 1684, 3675), Function.ability(237, "Effect_Stim_Marine_quick", cmd_quick, 380, 3675), Function.ability(238, "Effect_Stim_Marine_Redirect_quick", cmd_quick, 1683, 3675), Function.ability(239, "Effect_SupplyDrop_screen", cmd_screen, 255), Function.ability(240, "Effect_TacticalJump_screen", cmd_screen, 2358), Function.ability(241, "Effect_TimeWarp_screen", cmd_screen, 2244), Function.ability(242, "Effect_Transfusion_screen", cmd_screen, 1664), Function.ability(243, "Effect_ViperConsume_screen", cmd_screen, 2073), Function.ability(244, "Effect_VoidRayPrismaticAlignment_quick", cmd_quick, 2393), Function.ability(245, "Effect_WidowMineAttack_screen", cmd_screen, 2099), Function.ability(246, "Effect_WidowMineAttack_autocast", autocast, 2099), Function.ability(247, "Effect_YamatoGun_screen", cmd_screen, 401), Function.ability(248, "Hallucination_Adept_quick", cmd_quick, 2391), Function.ability(249, "Hallucination_Archon_quick", cmd_quick, 146), Function.ability(250, "Hallucination_Colossus_quick", cmd_quick, 148), Function.ability(251, "Hallucination_Disruptor_quick", cmd_quick, 2389), Function.ability(252, "Hallucination_HighTemplar_quick", cmd_quick, 150), Function.ability(253, "Hallucination_Immortal_quick", cmd_quick, 152), Function.ability(254, "Hallucination_Oracle_quick", cmd_quick, 2114), Function.ability(255, "Hallucination_Phoenix_quick", cmd_quick, 154), Function.ability(256, "Hallucination_Probe_quick", cmd_quick, 156), Function.ability(257, "Hallucination_Stalker_quick", cmd_quick, 158), Function.ability(258, "Hallucination_VoidRay_quick", cmd_quick, 160), Function.ability(259, "Hallucination_WarpPrism_quick", cmd_quick, 162), Function.ability(260, "Hallucination_Zealot_quick", cmd_quick, 164), Function.ability(261, "Halt_quick", cmd_quick, 3660), Function.ability(262, "Halt_Building_quick", cmd_quick, 315, 3660), Function.ability(263, "Halt_TerranBuild_quick", cmd_quick, 348, 3660), Function.ability(264, "Harvest_Gather_screen", cmd_screen, 3666), Function.ability(265, "Harvest_Gather_Drone_screen", cmd_screen, 1183, 3666), Function.ability(266, "Harvest_Gather_Mule_screen", cmd_screen, 166, 3666), Function.ability(267, "Harvest_Gather_Probe_screen", cmd_screen, 298, 3666), Function.ability(268, "Harvest_Gather_SCV_screen", cmd_screen, 295, 3666), Function.ability(269, "Harvest_Return_quick", cmd_quick, 3667), Function.ability(270, "Harvest_Return_Drone_quick", cmd_quick, 1184, 3667), Function.ability(271, "Harvest_Return_Mule_quick", cmd_quick, 167, 3667), Function.ability(272, "Harvest_Return_Probe_quick", cmd_quick, 299, 3667), Function.ability(273, "Harvest_Return_SCV_quick", cmd_quick, 296, 3667), Function.ability(274, "HoldPosition_quick", cmd_quick, 18), Function.ability(275, "Land_screen", cmd_screen, 3678), Function.ability(276, "Land_Barracks_screen", cmd_screen, 554, 3678), Function.ability(277, "Land_CommandCenter_screen", cmd_screen, 419, 3678), Function.ability(278, "Land_Factory_screen", cmd_screen, 520, 3678), Function.ability(279, "Land_OrbitalCommand_screen", cmd_screen, 1524, 3678), Function.ability(280, "Land_Starport_screen", cmd_screen, 522, 3678), Function.ability(281, "Lift_quick", cmd_quick, 3679), Function.ability(282, "Lift_Barracks_quick", cmd_quick, 452, 3679), Function.ability(283, "Lift_CommandCenter_quick", cmd_quick, 417, 3679), Function.ability(284, "Lift_Factory_quick", cmd_quick, 485, 3679), Function.ability(285, "Lift_OrbitalCommand_quick", cmd_quick, 1522, 3679), Function.ability(286, "Lift_Starport_quick", cmd_quick, 518, 3679), Function.ability(287, "Load_screen", cmd_screen, 3668), Function.ability(288, "Load_Bunker_screen", cmd_screen, 407, 3668), Function.ability(289, "Load_Medivac_screen", cmd_screen, 394, 3668), Function.ability(290, "Load_NydusNetwork_screen", cmd_screen, 1437, 3668), Function.ability(291, "Load_NydusWorm_screen", cmd_screen, 2370, 3668), Function.ability(292, "Load_Overlord_screen", cmd_screen, 1406, 3668), Function.ability(293, "Load_WarpPrism_screen", cmd_screen, 911, 3668), Function.ability(294, "LoadAll_quick", cmd_quick, 3663), Function.ability(295, "LoadAll_CommandCenter_quick", cmd_quick, 416, 3663), Function.ability(296, "Morph_Archon_quick", cmd_quick, 1766), Function.ability(297, "Morph_BroodLord_quick", cmd_quick, 1372), Function.ability(298, "Morph_Gateway_quick", cmd_quick, 1520), Function.ability(299, "Morph_GreaterSpire_quick", cmd_quick, 1220), Function.ability(300, "Morph_Hellbat_quick", cmd_quick, 1998), Function.ability(301, "Morph_Hellion_quick", cmd_quick, 1978), Function.ability(302, "Morph_Hive_quick", cmd_quick, 1218), Function.ability(303, "Morph_Lair_quick", cmd_quick, 1216), Function.ability(304, "Morph_LiberatorAAMode_quick", cmd_quick, 2560), Function.ability(305, "Morph_LiberatorAGMode_screen", cmd_screen, 2558), Function.ability(306, "Morph_Lurker_quick", cmd_quick, 2332), Function.ability(307, "Morph_LurkerDen_quick", cmd_quick, 2112), Function.ability(308, "Morph_Mothership_quick", cmd_quick, 1847), Function.ability(309, "Morph_OrbitalCommand_quick", cmd_quick, 1516), Function.ability(310, "Morph_OverlordTransport_quick", cmd_quick, 2708), Function.ability(311, "Morph_Overseer_quick", cmd_quick, 1448), Function.ability(312, "Morph_PlanetaryFortress_quick", cmd_quick, 1450), Function.ability(313, "Morph_Ravager_quick", cmd_quick, 2330), Function.ability(314, "Morph_Root_screen", cmd_screen, 3680), Function.ability(315, "Morph_SpineCrawlerRoot_screen", cmd_screen, 1729, 3680), Function.ability(316, "Morph_SporeCrawlerRoot_screen", cmd_screen, 1731, 3680), Function.ability(317, "Morph_SiegeMode_quick", cmd_quick, 388), Function.ability(318, "Morph_SupplyDepot_Lower_quick", cmd_quick, 556), Function.ability(319, "Morph_SupplyDepot_Raise_quick", cmd_quick, 558), Function.ability(320, "Morph_ThorExplosiveMode_quick", cmd_quick, 2364), Function.ability(321, "Morph_ThorHighImpactMode_quick", cmd_quick, 2362), Function.ability(322, "Morph_Unsiege_quick", cmd_quick, 390), Function.ability(323, "Morph_Uproot_quick", cmd_quick, 3681), Function.ability(324, "Morph_SpineCrawlerUproot_quick", cmd_quick, 1725, 3681), Function.ability(325, "Morph_SporeCrawlerUproot_quick", cmd_quick, 1727, 3681), Function.ability(326, "Morph_VikingAssaultMode_quick", cmd_quick, 403), Function.ability(327, "Morph_VikingFighterMode_quick", cmd_quick, 405), Function.ability(328, "Morph_WarpGate_quick", cmd_quick, 1518), Function.ability(329, "Morph_WarpPrismPhasingMode_quick", cmd_quick, 1528), Function.ability(330, "Morph_WarpPrismTransportMode_quick", cmd_quick, 1530), Function.ability(331, "Move_screen", cmd_screen, 16), Function.ability(332, "Move_minimap", cmd_minimap, 16), Function.ability(333, "Patrol_screen", cmd_screen, 17), Function.ability(334, "Patrol_minimap", cmd_minimap, 17), Function.ability(335, "Rally_Units_screen", cmd_screen, 3673), Function.ability(336, "Rally_Units_minimap", cmd_minimap, 3673), Function.ability(337, "Rally_Building_screen", cmd_screen, 195, 3673), Function.ability(338, "Rally_Building_minimap", cmd_minimap, 195, 3673), Function.ability(339, "Rally_Hatchery_Units_screen", cmd_screen, 212, 3673), Function.ability(340, "Rally_Hatchery_Units_minimap", cmd_minimap, 212, 3673), Function.ability(341, "Rally_Morphing_Unit_screen", cmd_screen, 199, 3673), Function.ability(342, "Rally_Morphing_Unit_minimap", cmd_minimap, 199, 3673), Function.ability(343, "Rally_Workers_screen", cmd_screen, 3690), Function.ability(344, "Rally_Workers_minimap", cmd_minimap, 3690), Function.ability(345, "Rally_CommandCenter_screen", cmd_screen, 203, 3690), Function.ability(346, "Rally_CommandCenter_minimap", cmd_minimap, 203, 3690), Function.ability(347, "Rally_Hatchery_Workers_screen", cmd_screen, 211, 3690), Function.ability(348, "Rally_Hatchery_Workers_minimap", cmd_minimap, 211, 3690), Function.ability(349, "Rally_Nexus_screen", cmd_screen, 207, 3690), Function.ability(350, "Rally_Nexus_minimap", cmd_minimap, 207, 3690), Function.ability(351, "Research_AdeptResonatingGlaives_quick", cmd_quick, 1594), Function.ability(352, "Research_AdvancedBallistics_quick", cmd_quick, 805), Function.ability(353, "Research_BansheeCloakingField_quick", cmd_quick, 790), Function.ability(354, "Research_BansheeHyperflightRotors_quick", cmd_quick, 799), Function.ability(355, "Research_BattlecruiserWeaponRefit_quick", cmd_quick, 1532), Function.ability(356, "Research_Blink_quick", cmd_quick, 1593), Function.ability(357, "Research_Burrow_quick", cmd_quick, 1225), Function.ability(358, "Research_CentrifugalHooks_quick", cmd_quick, 1482), Function.ability(359, "Research_Charge_quick", cmd_quick, 1592), Function.ability(360, "Research_ChitinousPlating_quick", cmd_quick, 265), Function.ability(361, "Research_CombatShield_quick", cmd_quick, 731), Function.ability(362, "Research_ConcussiveShells_quick", cmd_quick, 732), Function.ability(363, "Research_DrillingClaws_quick", cmd_quick, 764), Function.ability(364, "Research_ExtendedThermalLance_quick", cmd_quick, 1097), Function.ability(365, "Research_GlialRegeneration_quick", cmd_quick, 216), Function.ability(366, "Research_GraviticBooster_quick", cmd_quick, 1093), Function.ability(367, "Research_GraviticDrive_quick", cmd_quick, 1094), Function.ability(368, "Research_GroovedSpines_quick", cmd_quick, 1282), Function.ability(369, "Research_HiSecAutoTracking_quick", cmd_quick, 650), Function.ability(370, "Research_HighCapacityFuelTanks_quick", cmd_quick, 804), Function.ability(371, "Research_InfernalPreigniter_quick", cmd_quick, 761), Function.ability(372, "Research_InterceptorGravitonCatapult_quick", cmd_quick, 44), Function.ability(373, "Research_MagFieldLaunchers_quick", cmd_quick, 766), Function.ability(374, "Research_MuscularAugments_quick", cmd_quick, 1283), Function.ability(375, "Research_NeosteelFrame_quick", cmd_quick, 655), Function.ability(376, "Research_NeuralParasite_quick", cmd_quick, 1455), Function.ability(377, "Research_PathogenGlands_quick", cmd_quick, 1454), Function.ability(378, "Research_PersonalCloaking_quick", cmd_quick, 820), Function.ability(379, "Research_PhoenixAnionPulseCrystals_quick", cmd_quick, 46), Function.ability(380, "Research_PneumatizedCarapace_quick", cmd_quick, 1223), Function.ability(381, "Research_ProtossAirArmor_quick", cmd_quick, 3692), Function.ability(382, "Research_ProtossAirArmorLevel1_quick", cmd_quick, 1565, 3692), Function.ability(383, "Research_ProtossAirArmorLevel2_quick", cmd_quick, 1566, 3692), Function.ability(384, "Research_ProtossAirArmorLevel3_quick", cmd_quick, 1567, 3692), Function.ability(385, "Research_ProtossAirWeapons_quick", cmd_quick, 3693), Function.ability(386, "Research_ProtossAirWeaponsLevel1_quick", cmd_quick, 1562, 3693), Function.ability(387, "Research_ProtossAirWeaponsLevel2_quick", cmd_quick, 1563, 3693), Function.ability(388, "Research_ProtossAirWeaponsLevel3_quick", cmd_quick, 1564, 3693), Function.ability(389, "Research_ProtossGroundArmor_quick", cmd_quick, 3694), Function.ability(390, "Research_ProtossGroundArmorLevel1_quick", cmd_quick, 1065, 3694), Function.ability(391, "Research_ProtossGroundArmorLevel2_quick", cmd_quick, 1066, 3694), Function.ability(392, "Research_ProtossGroundArmorLevel3_quick", cmd_quick, 1067, 3694), Function.ability(393, "Research_ProtossGroundWeapons_quick", cmd_quick, 3695), Function.ability(394, "Research_ProtossGroundWeaponsLevel1_quick", cmd_quick, 1062, 3695), Function.ability(395, "Research_ProtossGroundWeaponsLevel2_quick", cmd_quick, 1063, 3695), Function.ability(396, "Research_ProtossGroundWeaponsLevel3_quick", cmd_quick, 1064, 3695), Function.ability(397, "Research_ProtossShields_quick", cmd_quick, 3696), Function.ability(398, "Research_ProtossShieldsLevel1_quick", cmd_quick, 1068, 3696), Function.ability(399, "Research_ProtossShieldsLevel2_quick", cmd_quick, 1069, 3696), Function.ability(400, "Research_ProtossShieldsLevel3_quick", cmd_quick, 1070, 3696), Function.ability(401, "Research_PsiStorm_quick", cmd_quick, 1126), Function.ability(402, "Research_RavenCorvidReactor_quick", cmd_quick, 793), Function.ability(403, "Research_RavenRecalibratedExplosives_quick", cmd_quick, 803), Function.ability(404, "Research_ShadowStrike_quick", cmd_quick, 2720), Function.ability(405, "Research_Stimpack_quick", cmd_quick, 730), Function.ability(406, "Research_TerranInfantryArmor_quick", cmd_quick, 3697), Function.ability(407, "Research_TerranInfantryArmorLevel1_quick", cmd_quick, 656, 3697), Function.ability(408, "Research_TerranInfantryArmorLevel2_quick", cmd_quick, 657, 3697), Function.ability(409, "Research_TerranInfantryArmorLevel3_quick", cmd_quick, 658, 3697), Function.ability(410, "Research_TerranInfantryWeapons_quick", cmd_quick, 3698), Function.ability(411, "Research_TerranInfantryWeaponsLevel1_quick", cmd_quick, 652, 3698), Function.ability(412, "Research_TerranInfantryWeaponsLevel2_quick", cmd_quick, 653, 3698), Function.ability(413, "Research_TerranInfantryWeaponsLevel3_quick", cmd_quick, 654, 3698), Function.ability(414, "Research_TerranShipWeapons_quick", cmd_quick, 3699), Function.ability(415, "Research_TerranShipWeaponsLevel1_quick", cmd_quick, 861, 3699), Function.ability(416, "Research_TerranShipWeaponsLevel2_quick", cmd_quick, 862, 3699), Function.ability(417, "Research_TerranShipWeaponsLevel3_quick", cmd_quick, 863, 3699), Function.ability(418, "Research_TerranStructureArmorUpgrade_quick", cmd_quick, 651), Function.ability(419, "Research_TerranVehicleAndShipPlating_quick", cmd_quick, 3700), Function.ability(420, "Research_TerranVehicleAndShipPlatingLevel1_quick", cmd_quick, 864, 3700), Function.ability(421, "Research_TerranVehicleAndShipPlatingLevel2_quick", cmd_quick, 865, 3700), Function.ability(422, "Research_TerranVehicleAndShipPlatingLevel3_quick", cmd_quick, 866, 3700), Function.ability(423, "Research_TerranVehicleWeapons_quick", cmd_quick, 3701), Function.ability(424, "Research_TerranVehicleWeaponsLevel1_quick", cmd_quick, 855, 3701), Function.ability(425, "Research_TerranVehicleWeaponsLevel2_quick", cmd_quick, 856, 3701), Function.ability(426, "Research_TerranVehicleWeaponsLevel3_quick", cmd_quick, 857, 3701), Function.ability(427, "Research_TunnelingClaws_quick", cmd_quick, 217), Function.ability(428, "Research_WarpGate_quick", cmd_quick, 1568), Function.ability(429, "Research_ZergFlyerArmor_quick", cmd_quick, 3702), Function.ability(430, "Research_ZergFlyerArmorLevel1_quick", cmd_quick, 1315, 3702), Function.ability(431, "Research_ZergFlyerArmorLevel2_quick", cmd_quick, 1316, 3702), Function.ability(432, "Research_ZergFlyerArmorLevel3_quick", cmd_quick, 1317, 3702), Function.ability(433, "Research_ZergFlyerAttack_quick", cmd_quick, 3703), Function.ability(434, "Research_ZergFlyerAttackLevel1_quick", cmd_quick, 1312, 3703), Function.ability(435, "Research_ZergFlyerAttackLevel2_quick", cmd_quick, 1313, 3703), Function.ability(436, "Research_ZergFlyerAttackLevel3_quick", cmd_quick, 1314, 3703), Function.ability(437, "Research_ZergGroundArmor_quick", cmd_quick, 3704), Function.ability(438, "Research_ZergGroundArmorLevel1_quick", cmd_quick, 1189, 3704), Function.ability(439, "Research_ZergGroundArmorLevel2_quick", cmd_quick, 1190, 3704), Function.ability(440, "Research_ZergGroundArmorLevel3_quick", cmd_quick, 1191, 3704), Function.ability(441, "Research_ZergMeleeWeapons_quick", cmd_quick, 3705), Function.ability(442, "Research_ZergMeleeWeaponsLevel1_quick", cmd_quick, 1186, 3705), Function.ability(443, "Research_ZergMeleeWeaponsLevel2_quick", cmd_quick, 1187, 3705), Function.ability(444, "Research_ZergMeleeWeaponsLevel3_quick", cmd_quick, 1188, 3705), Function.ability(445, "Research_ZergMissileWeapons_quick", cmd_quick, 3706), Function.ability(446, "Research_ZergMissileWeaponsLevel1_quick", cmd_quick, 1192, 3706), Function.ability(447, "Research_ZergMissileWeaponsLevel2_quick", cmd_quick, 1193, 3706), Function.ability(448, "Research_ZergMissileWeaponsLevel3_quick", cmd_quick, 1194, 3706), Function.ability(449, "Research_ZerglingAdrenalGlands_quick", cmd_quick, 1252), Function.ability(450, "Research_ZerglingMetabolicBoost_quick", cmd_quick, 1253), Function.ability(451, "Smart_screen", cmd_screen, 1), Function.ability(452, "Smart_minimap", cmd_minimap, 1), Function.ability(453, "Stop_quick", cmd_quick, 3665), Function.ability(454, "Stop_Building_quick", cmd_quick, 2057, 3665), Function.ability(455, "Stop_Redirect_quick", cmd_quick, 1691, 3665), Function.ability(456, "Stop_Stop_quick", cmd_quick, 4, 3665), Function.ability(457, "Train_Adept_quick", cmd_quick, 922), Function.ability(458, "Train_Baneling_quick", cmd_quick, 80), Function.ability(459, "Train_Banshee_quick", cmd_quick, 621), Function.ability(460, "Train_Battlecruiser_quick", cmd_quick, 623), Function.ability(461, "Train_Carrier_quick", cmd_quick, 948), Function.ability(462, "Train_Colossus_quick", cmd_quick, 978), Function.ability(463, "Train_Corruptor_quick", cmd_quick, 1353), Function.ability(464, "Train_Cyclone_quick", cmd_quick, 597), Function.ability(465, "Train_DarkTemplar_quick", cmd_quick, 920), Function.ability(466, "Train_Disruptor_quick", cmd_quick, 994), Function.ability(467, "Train_Drone_quick", cmd_quick, 1342), Function.ability(468, "Train_Ghost_quick", cmd_quick, 562), Function.ability(469, "Train_Hellbat_quick", cmd_quick, 596), Function.ability(470, "Train_Hellion_quick", cmd_quick, 595), Function.ability(471, "Train_HighTemplar_quick", cmd_quick, 919), Function.ability(472, "Train_Hydralisk_quick", cmd_quick, 1345), Function.ability(473, "Train_Immortal_quick", cmd_quick, 979), Function.ability(474, "Train_Infestor_quick", cmd_quick, 1352), Function.ability(475, "Train_Liberator_quick", cmd_quick, 626), Function.ability(476, "Train_Marauder_quick", cmd_quick, 563), Function.ability(477, "Train_Marine_quick", cmd_quick, 560), Function.ability(478, "Train_Medivac_quick", cmd_quick, 620), Function.ability(479, "Train_MothershipCore_quick", cmd_quick, 1853), Function.ability(480, "Train_Mutalisk_quick", cmd_quick, 1346), Function.ability(481, "Train_Observer_quick", cmd_quick, 977), Function.ability(482, "Train_Oracle_quick", cmd_quick, 954), Function.ability(483, "Train_Overlord_quick", cmd_quick, 1344), Function.ability(484, "Train_Phoenix_quick", cmd_quick, 946), Function.ability(485, "Train_Probe_quick", cmd_quick, 1006), Function.ability(486, "Train_Queen_quick", cmd_quick, 1632), Function.ability(487, "Train_Raven_quick", cmd_quick, 622), Function.ability(488, "Train_Reaper_quick", cmd_quick, 561), Function.ability(489, "Train_Roach_quick", cmd_quick, 1351), Function.ability(490, "Train_SCV_quick", cmd_quick, 524), Function.ability(491, "Train_Sentry_quick", cmd_quick, 921), Function.ability(492, "Train_SiegeTank_quick", cmd_quick, 591), Function.ability(493, "Train_Stalker_quick", cmd_quick, 917), Function.ability(494, "Train_SwarmHost_quick", cmd_quick, 1356), Function.ability(495, "Train_Tempest_quick", cmd_quick, 955), Function.ability(496, "Train_Thor_quick", cmd_quick, 594), Function.ability(497, "Train_Ultralisk_quick", cmd_quick, 1348), Function.ability(498, "Train_VikingFighter_quick", cmd_quick, 624), Function.ability(499, "Train_Viper_quick", cmd_quick, 1354), Function.ability(500, "Train_VoidRay_quick", cmd_quick, 950), Function.ability(501, "Train_WarpPrism_quick", cmd_quick, 976), Function.ability(502, "Train_WidowMine_quick", cmd_quick, 614), Function.ability(503, "Train_Zealot_quick", cmd_quick, 916), Function.ability(504, "Train_Zergling_quick", cmd_quick, 1343), Function.ability(505, "TrainWarp_Adept_screen", cmd_screen, 1419), Function.ability(506, "TrainWarp_DarkTemplar_screen", cmd_screen, 1417), Function.ability(507, "TrainWarp_HighTemplar_screen", cmd_screen, 1416), Function.ability(508, "TrainWarp_Sentry_screen", cmd_screen, 1418), Function.ability(509, "TrainWarp_Stalker_screen", cmd_screen, 1414), Function.ability(510, "TrainWarp_Zealot_screen", cmd_screen, 1413), Function.ability(511, "UnloadAll_quick", cmd_quick, 3664), Function.ability(512, "UnloadAll_Bunker_quick", cmd_quick, 408, 3664), Function.ability(513, "UnloadAll_CommandCenter_quick", cmd_quick, 413, 3664), Function.ability(514, "UnloadAll_NydasNetwork_quick", cmd_quick, 1438, 3664), Function.ability(515, "UnloadAll_NydusWorm_quick", cmd_quick, 2371, 3664), Function.ability(516, "UnloadAllAt_screen", cmd_screen, 3669), Function.ability(517, "UnloadAllAt_minimap", cmd_minimap, 3669), Function.ability(518, "UnloadAllAt_Medivac_screen", cmd_screen, 396, 3669), Function.ability(519, "UnloadAllAt_Medivac_minimap", cmd_minimap, 396, 3669), Function.ability(520, "UnloadAllAt_Overlord_screen", cmd_screen, 1408, 3669), Function.ability(521, "UnloadAllAt_Overlord_minimap", cmd_minimap, 1408, 3669), Function.ability(522, "UnloadAllAt_WarpPrism_screen", cmd_screen, 913, 3669), Function.ability(523, "UnloadAllAt_WarpPrism_minimap", cmd_minimap, 913, 3669), ]) # pylint: enable=line-too-long # Some indexes to support features.py and action conversion. ABILITY_IDS = collections.defaultdict(set) # {ability_id: {funcs}} for func in FUNCTIONS: if func.ability_id >= 0: ABILITY_IDS[func.ability_id].add(func) ABILITY_IDS = {k: frozenset(v) for k, v in six.iteritems(ABILITY_IDS)} FUNCTIONS_AVAILABLE = {f.id: f for f in FUNCTIONS if f.avail_fn}
[ 2, 15069, 2177, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
2.669173
17,825
import numbers from . import meter import numpy as np import torch
[ 11748, 3146, 198, 6738, 764, 1330, 16430, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 628 ]
4
17
"""Lighting channels module for Zigbee Home Automation.""" from __future__ import annotations from contextlib import suppress from zigpy.zcl.clusters import lighting from .. import registries from ..const import REPORT_CONFIG_DEFAULT from .base import ClientChannel, ZigbeeChannel
[ 37811, 15047, 278, 9619, 8265, 329, 24992, 20963, 5995, 17406, 341, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 4732, 8019, 1330, 18175, 198, 198, 6738, 1976, 328, 9078, 13, 89, 565, 13, 565, 13654, 1330, 1201...
3.931507
73
"""Classes to represent Packet Filter's queueing schedulers and statistics.""" import pf._struct from pf._base import PFObject from pf.constants import * from pf._utils import rate2str __all__ = ["ServiceCurve", "FlowQueue", "PFQueue", "PFQueueStats"]
[ 37811, 9487, 274, 284, 2380, 6400, 316, 25853, 338, 16834, 278, 6038, 377, 364, 290, 7869, 526, 15931, 198, 198, 11748, 279, 69, 13557, 7249, 198, 6738, 279, 69, 13557, 8692, 1330, 28223, 10267, 198, 6738, 279, 69, 13, 9979, 1187, 133...
2.59292
113
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** # Export this package's modules as members: from ._enums import * from .environment import * from .environment_setting import * from .gallery_image import * from .get_environment import * from .get_environment_setting import * from .get_gallery_image import * from .get_global_user_environment import * from .get_global_user_operation_batch_status import * from .get_global_user_operation_status import * from .get_global_user_personal_preferences import * from .get_lab import * from .get_lab_account import * from .get_lab_account_regional_availability import * from .get_user import * from .lab import * from .lab_account import * from .list_global_user_environments import * from .list_global_user_labs import * from .user import * from ._inputs import * from . import outputs _register_module()
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
3.514493
276
''' (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved. The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only with the express written consent of Telefonica I+D or in accordance with the terms and conditions stipulated in the agreement/contract under which the program(s) have been supplied. ''' from unittest import TestCase from mock import MagicMock, patch from commons.json_schema_validator.schema_reader import SchemaField from commons.json_schema_validator.schema_reader import SchemaReader from users.serializers import UserCollectionSerializer
[ 7061, 6, 198, 7, 66, 8, 15069, 2211, 14318, 69, 32752, 11, 314, 10, 35, 13, 38482, 287, 8602, 357, 16112, 737, 1439, 6923, 198, 4965, 8520, 13, 198, 198, 464, 6634, 284, 262, 3788, 1430, 7, 82, 8, 318, 3119, 286, 14318, 69, 3275...
3.672316
177
''' User views ''' from datetime import timedelta from flask import request, jsonify, make_response, redirect, json, render_template from flask_jwt_extended import (create_access_token, jwt_required) from flask_restful import Resource from flask_login import login_user, current_user from sqlalchemy.exc import IntegrityError, InvalidRequestError from src import db, api from .models import User from .schemas import UserSchema api.add_resource(UserLoginResource, '/login/', endpoint='login') api.add_resource(UserRegisterResource, '/register/', endpoint='register')
[ 7061, 6, 11787, 5009, 705, 7061, 198, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, 42903, 1330, 2581, 11, 33918, 1958, 11, 787, 62, 26209, 11, 18941, 11, 33918, 11, 8543, 62, 28243, 198, 6738, 42903, 62, 73, 46569, 62, 2302, ...
2.762712
236
from querybuilder.fields import ( RankField, RowNumberField, DenseRankField, PercentRankField, CumeDistField, NTileField, LagField, LeadField, FirstValueField, LastValueField, NthValueField, NumStdDevField ) from querybuilder.query import QueryWindow, Query from querybuilder.tests.models import Order from querybuilder.tests.query_tests import QueryTestCase, get_comparison_str
[ 6738, 12405, 38272, 13, 25747, 1330, 357, 198, 220, 220, 220, 10916, 15878, 11, 11314, 15057, 15878, 11, 360, 1072, 27520, 15878, 11, 22512, 27520, 15878, 11, 327, 2454, 20344, 15878, 11, 24563, 576, 15878, 11, 21003, 15878, 11, 198, 22...
3.504505
111
import numpy h = .25 s = 1 bitmap = numpy.array([ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0], [0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0], [0,0,1,1,1,0,1,0,1,1,1,0,0,1,0,0], [0,0,1,1,0,1,0,1,0,1,1,0,0,1,0,0], [0,0,1,1,1,0,1,0,1,1,1,0,1,0,0,0], [0,0,1,1,0,1,0,1,0,1,1,1,0,0,0,0], [0,0,1,1,1,0,1,0,1,1,1,0,0,0,0,0], [0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0], [0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]])
[ 11748, 299, 32152, 198, 198, 71, 796, 764, 1495, 198, 82, 796, 352, 198, 2545, 8899, 796, 299, 32152, 13, 18747, 26933, 198, 220, 220, 220, 685, 15, 11, 15, 11, 15, 11, 15, 11, 15, 11, 15, 11, 15, 11, 15, 11, 15, 11, 15, 11,...
1.097403
616
import numpy as np from sklearn.model_selection import RandomizedSearchCV, GridSearchCV from sklearn.metrics import roc_auc_score from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import KFold import scipy.stats as sts import xgboost as xgb from xiter import * import pandas as pd import argparse from datetime import datetime parser=argparse.ArgumentParser() parser.add_argument("--end",type=float,default=100000.,help='end ratio') parser.add_argument("--save",type=str,default="test_",help='save name') parser.add_argument("--network",type=str,default="rnn",help='network name on symbols/') parser.add_argument("--right",type=str,default="/scratch/yjdata/gluon100_img",help='which train sample (qq,gg,zq,zg)') parser.add_argument("--pt",type=int,default=200,help='pt range pt~pt*1.1') parser.add_argument("--ptmin",type=float,default=0.,help='pt range pt~pt*1.1') parser.add_argument("--ptmax",type=float,default=2.,help='pt range pt~pt*1.1') parser.add_argument("--epochs",type=int,default=10,help='num epochs') parser.add_argument("--batch_size",type=int,default=100000,help='batch_size') parser.add_argument("--loss",type=str,default="categorical_crossentropy",help='network name on symbols/') parser.add_argument("--gpu",type=int,default=0,help='gpu number') parser.add_argument("--isz",type=int,default=0,help='0 or z or not') parser.add_argument("--eta",type=float,default=0.,help='end ratio') parser.add_argument("--etabin",type=float,default=1,help='end ratio') parser.add_argument("--unscale",type=int,default=0,help='end ratio') args=parser.parse_args() import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]=str(args.gpu) batch_size=args.batch_size params = { 'max_depth': sts.randint(1,6), 'learning_rate': sts.uniform(0.0010,0.500), 'n_estimators': sts.randint(10,101) } model=xgb.XGBClassifier(objective='binary:logistic',tree_method="gpu_hist") if(args.isz==1): if(args.etabin==1): loaded=np.load("zqmixed{}pteta.npz".format(args.pt)) print("zqmixed{}pteta.npz".format(args.pt)) else: loaded=np.load("zqmixed{}pt.npz".format(args.pt)) print("zqmixed{}pt.npz".format(args.pt)) elif(args.isz==-1): if(args.etabin==1): loaded=np.load("qqmixed{}pteta.npz".format(args.pt)) print("qqmixed{}pteta.npz".format(args.pt)) else: loaded=np.load("qqmixed{}pt.npz".format(args.pt)) print("qqmixed{}pt.npz".format(args.pt)) elif(args.isz==0): if(args.etabin==1): if(args.unscale==1): loaded=np.load("unscalemixed{}pteta.npz".format(args.pt)) else: loaded=np.load("mixed{}pteta.npz".format(args.pt)) print("etabin 1") else: if(args.unscale==1): loaded=np.load("unscalemixed{}pt.npz".format(args.pt)) else: loaded=np.load("mixed{}pt.npz".format(args.pt)) print("etabin 2.4") data=loaded["bdtset"][:,:5] label=loaded["label"] line=int(30000) endline=int(40000) if(len(label)<40000): line=int(len(label)*3./4.) endline=len(label) X=data[0:line] vx=data[line:endline] Y=label[0:line] vy=label[line:endline] Y=np.array(Y)[:,0] folds = 3 param_comb = 100 skf = KFold(n_splits=folds, shuffle = True, random_state = 173) #skf = StratifiedKFold(n_splits=folds, shuffle = True, random_state = 1001) random_search = RandomizedSearchCV(model, param_distributions=params, n_iter=param_comb, scoring='log_loss', n_jobs=6, cv=skf.split(X,Y), verbose=3, random_state=173 ) # Here we go start_time = timer(None) # timing starts from this point for "start_time" variable random_search.fit(X, Y) timer(start_time) #print(random_search.predict(X[:10])) #print('\n All results:') #print(random_search.cv_results_) #print('\n Best estimator:') #print(random_search.best_estimator_) print('\n Best normalized gini score for %d-fold search with %d parameter combinations:' % (folds, param_comb)) print(random_search.best_score_ * 2 - 1) #print('\n Best hyperparameters:') #print(random_search.best_params_) results = pd.DataFrame(random_search.cv_results_) results.to_csv('xgb/{}-{}.csv'.format(args.save,args.pt), index=False) #random_search.best_estimator_.save_model("bdt-{}.dat".format(args.pt))
[ 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 14534, 1143, 18243, 33538, 11, 24846, 18243, 33538, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 686, 66, 62, 14272, 62, 26675, 198, 6738, 1341, 35720, ...
2.472813
1,692
import random import json import gym from gym import spaces import pandas as pd import numpy as np MAX_ACCOUNT_BALANCE = 2147483647 MAX_NUM_SHARES = 2147483647 MAX_SHARE_PRICE = 5000 MAX_VOLUME = 1000e8 MAX_AMOUNT = 3e10 MAX_OPEN_POSITIONS = 5 MAX_STEPS = 20000 MAX_DAY_CHANGE = 1 INITIAL_ACCOUNT_BALANCE = 10000 DATA_HIS_PERIOD = 5 # position constant FLAT = 0 # no position LONG = 1 # buy position SHORT = 2 # sell position # action constant HOLD = 0 BUY = 1 SELL = 2
[ 11748, 4738, 198, 11748, 33918, 198, 11748, 11550, 198, 6738, 11550, 1330, 9029, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 628, 198, 22921, 62, 26861, 28270, 62, 33, 1847, 19240, 796, 362, 20198, 2780, 26...
2.492308
195
import json import os import pathlib import time from tqdm import tqdm from aggregator import aggregate from download import DOWNLOAD_PATH, download_files, unzip_files from tqdm.contrib.concurrent import process_map if __name__ == "__main__": main()
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 3108, 8019, 198, 11748, 640, 198, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 6738, 13262, 1352, 1330, 19406, 198, 6738, 4321, 1330, 30320, 35613, 62, 34219, 11, 4321, 62, 16624, 11...
3.222222
81
from PIL import Image import os, glob import numpy as np from sklearn import model_selection classes = ["car", "bycycle", "motorcycle", "pedestrian"] num_class = len(classes) image_size = 50 # X = [] Y = [] for index, classlabel in enumerate(classes): photos_dir = "./" + classlabel files = glob.glob(photos_dir + "/*.jpg") for i, file in enumerate(files): if i >=237: break image = Image.open(file) image = image.convert("RGB") image = image.resize((image_size, image_size)) data = np.asarray(image) / 255 X.append(data) Y.append(index) X = np.array(X) Y = np.array(Y) X_train, X_test, y_train, y_test = model_selection.train_test_split(X, Y) xy = (X_train, X_test, y_train, y_test) np.save("./vehicle.npy", xy)
[ 6738, 350, 4146, 1330, 7412, 198, 11748, 28686, 11, 15095, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 1330, 2746, 62, 49283, 198, 198, 37724, 796, 14631, 7718, 1600, 366, 1525, 13696, 1600, 366, 76, 20965, 13696, 1600, ...
2.335312
337
from services import waypoint_scenarios, quest_scenarios from services.build_campaign import Campaign from log_setup import log if __name__ == "__main__": number_waypoint_scenario = waypoint_scenarios.get_number_of_waypoint_scenarios() log.info(f"We have {number_waypoint_scenario} waypoint available") number_quests_available = quest_scenarios.get_number_of_quest_scenarios() log.info(f"We have {number_quests_available} quests available") random_waypoint_scenario = waypoint_scenarios.get_random_scenario(10) random_quest = quest_scenarios.get_random_scenario(1) campaign = Campaign() campaign.build_campaign( waypoint_list=random_waypoint_scenario, quest_list=random_quest )
[ 6738, 2594, 1330, 835, 4122, 62, 1416, 268, 13010, 11, 1235, 62, 1416, 268, 13010, 198, 6738, 2594, 13, 11249, 62, 35012, 1330, 13718, 198, 6738, 2604, 62, 40406, 1330, 2604, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834...
2.839216
255
import os pkgs = os.path.join(os.environ["ROOT"], "pkgs") info_dir = os.path.join(pkgs, "conda-build-test-ignore-some-prefix-files-1.0-0", "info") has_prefix_file = os.path.join(info_dir, "has_prefix") print(info_dir) assert os.path.isfile(has_prefix_file) with open(has_prefix_file) as f: assert "test2" not in f.read()
[ 11748, 28686, 198, 198, 35339, 82, 796, 28686, 13, 6978, 13, 22179, 7, 418, 13, 268, 2268, 14692, 13252, 2394, 33116, 366, 35339, 82, 4943, 198, 10951, 62, 15908, 796, 28686, 13, 6978, 13, 22179, 7, 35339, 82, 11, 366, 66, 13533, 12...
2.379562
137
import os from collections import namedtuple import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import classification_report from torch.optim import Adam from tqdm import tqdm from data import DataIteratorDistill from loss import FocalLoss from model import CNN from torchtext import data, vocab from args import get_args, print_args from config import ConfigBinaryClassification from config import ConfigBinaryClassificationDistill from config import ConfigTripleClassification if __name__ == "__main__": args = get_args() print_args(args) if args.class_num == 2: cfg = ConfigBinaryClassificationDistill() elif args.class_num == 3: cfg = ConfigTripleClassification() else: raise ValueError("wrong class num") device = torch.device("cuda:%d" % args.cuda) Data = DataIteratorDistill(config=cfg, train_batchsize=args.batch_size) model = torch.load("checkpoints/CNN-29", map_location=device) optimizer = Adam(model.parameters(), lr=args.lr) criterion = FocalLoss(classes=args.class_num, device=device).to(device) criterion_kv = nn.KLDivLoss().to(device) alpha = 0.2 T = 2 for epoch in range(args.epoch_num): print(epoch) for sample in Data.train_iter: model.train() optimizer.zero_grad() output = model(sample.text.permute(1, 0).to(device)) loss_f = criterion(output, sample.label.to(device)) output = F.log_softmax(output/T, 1) score = torch.cat((sample.pred0.unsqueeze(1).to(device), sample.pred1.unsqueeze(1).to(device)), dim=1) score = F.softmax(score/T,1) loss_kv = criterion_kv(output, score.to(device)) * T * T loss = alpha * loss_f + (1 - alpha) * loss_kv #print(loss_f.item(), loss_kv.item()) loss.backward() optimizer.step() with torch.no_grad(): model.eval() preds = [] labels = [] for sample in Data.valid_iter: output = model(sample.text.permute(1, 0).to(device)) p = output.argmax(1).cpu().tolist() l = sample.label.tolist() preds += p labels += l report = classification_report(preds, labels) print(report) torch.save(model, os.path.join(args.save_dir, args.save_config + str(epoch)))
[ 11748, 28686, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 17923, 62, 1311...
2.272978
1,088
#!/usr/bin/python # -*- coding: iso-8859-1 -*- # Copyright (c) 2016, Jan Brohl <janbrohl@t-online.de> # All rights reserved. # See LICENSE.txt # Copyright (c) 2004 Colin Stewart (http://www.owlfish.com/) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # If you make any bug fixes or feature enhancements please let me know! """ Unit test cases. """ from __future__ import unicode_literals import unittest import os import io import logging import logging.config from simpletal import simpleTAL, simpleTALES if (os.path.exists("logging.ini")): logging.config.fileConfig("logging.ini") else: logging.basicConfig() if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 47279, 12, 3459, 3270, 12, 16, 532, 9, 12, 198, 198, 2, 220, 220, 220, 15069, 357, 66, 8, 1584, 11, 2365, 2806, 18519, 1279, 13881, 7957, 18519, 31, 83, 12, ...
3.05036
695
from pathlib import Path from typing import List from fasta_reader import FASTAItem, FASTAWriter, read_fasta __all__ = ["downsample"]
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 3049, 64, 62, 46862, 1330, 376, 1921, 5603, 7449, 11, 376, 1921, 5603, 34379, 11, 1100, 62, 7217, 64, 198, 198, 834, 439, 834, 796, 14631, 30371, 1403, 8973,...
3.186047
43
# API keys # YF_API_KEY = "YRVHVLiFAt3ANYZf00BXr2LHNfZcgKzdWVmsZ9Xi" # yahoo finance api key TICKER = "TSLA" INTERVAL = "1m" PERIOD = "1d" LOOK_BACK = 30 # hard limit to not reach rate limit of 100 per day
[ 2, 7824, 8251, 198, 2, 575, 37, 62, 17614, 62, 20373, 796, 366, 38162, 53, 39, 53, 32304, 37, 2953, 18, 31827, 57, 69, 405, 33, 55, 81, 17, 43, 39, 45, 69, 57, 66, 70, 42, 89, 67, 54, 53, 907, 57, 24, 42528, 1, 1303, 331, ...
2.069307
101
from controller.invoker import ( invoker_cmd_branch_checkout, invoker_cmd_branch_commit, invoker_cmd_branch_create, invoker_cmd_branch_delete, invoker_cmd_branch_list, invoker_cmd_evaluate, invoker_cmd_filter, invoker_cmd_gpu_info, invoker_cmd_inference, invoker_cmd_init, invoker_cmd_label_add, invoker_cmd_label_get, invoker_cmd_log, invoker_cmd_merge, invoker_cmd_pull_image, invoker_cmd_repo_check, invoker_cmd_repo_clear, invoker_cmd_sampling, invoker_cmd_terminate, invoker_cmd_user_create, invoker_task_factory, ) from proto import backend_pb2 RequestTypeToInvoker = { backend_pb2.CMD_BRANCH_CHECKOUT: invoker_cmd_branch_checkout.BranchCheckoutInvoker, backend_pb2.CMD_BRANCH_CREATE: invoker_cmd_branch_create.BranchCreateInvoker, backend_pb2.CMD_BRANCH_DEL: invoker_cmd_branch_delete.BranchDeleteInvoker, backend_pb2.CMD_BRANCH_LIST: invoker_cmd_branch_list.BranchListInvoker, backend_pb2.CMD_COMMIT: invoker_cmd_branch_commit.BranchCommitInvoker, backend_pb2.CMD_EVALUATE: invoker_cmd_evaluate.EvaluateInvoker, backend_pb2.CMD_FILTER: invoker_cmd_filter.FilterBranchInvoker, backend_pb2.CMD_GPU_INFO_GET: invoker_cmd_gpu_info.GPUInfoInvoker, backend_pb2.CMD_INFERENCE: invoker_cmd_inference.InferenceCMDInvoker, backend_pb2.CMD_INIT: invoker_cmd_init.InitInvoker, backend_pb2.CMD_LABEL_ADD: invoker_cmd_label_add.LabelAddInvoker, backend_pb2.CMD_LABEL_GET: invoker_cmd_label_get.LabelGetInvoker, backend_pb2.CMD_LOG: invoker_cmd_log.LogInvoker, backend_pb2.CMD_MERGE: invoker_cmd_merge.MergeInvoker, backend_pb2.CMD_PULL_IMAGE: invoker_cmd_pull_image.ImageHandler, backend_pb2.CMD_TERMINATE: invoker_cmd_terminate.CMDTerminateInvoker, backend_pb2.CMD_REPO_CHECK: invoker_cmd_repo_check.RepoCheckInvoker, backend_pb2.CMD_REPO_CLEAR: invoker_cmd_repo_clear.RepoClearInvoker, backend_pb2.REPO_CREATE: invoker_cmd_init.InitInvoker, backend_pb2.TASK_CREATE: invoker_task_factory.CreateTaskInvokerFactory, backend_pb2.USER_CREATE: invoker_cmd_user_create.UserCreateInvoker, backend_pb2.CMD_SAMPLING: invoker_cmd_sampling.SamplingInvoker, }
[ 6738, 10444, 13, 16340, 11020, 1330, 357, 198, 220, 220, 220, 800, 11020, 62, 28758, 62, 1671, 3702, 62, 9122, 448, 11, 198, 220, 220, 220, 800, 11020, 62, 28758, 62, 1671, 3702, 62, 41509, 11, 198, 220, 220, 220, 800, 11020, 62, ...
2.276181
974
from datetime import datetime, timedelta due_date_format = '%Y-%m-%d' datepicker_date_format = '%m%d%Y'
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 23301, 62, 4475, 62, 18982, 796, 705, 4, 56, 12, 4, 76, 12, 4, 67, 6, 198, 198, 4475, 79, 15799, 62, 4475, 62, 18982, 796, 705, 4, 76, 4, 67, 4, 56, 6, 628, 628...
2.285714
49
import numpy as np from numba.roc.vectorizers import HsaGUFuncVectorize from numba.roc.dispatch import HSAGenerializedUFunc from numba import guvectorize import unittest if __name__ == '__main__': unittest.main()
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 997, 7012, 13, 12204, 13, 31364, 11341, 1330, 367, 11400, 38, 36820, 19524, 38469, 1096, 198, 6738, 997, 7012, 13, 12204, 13, 6381, 17147, 1330, 367, 4090, 8645, 498, 1143, 36820, 19524, 19...
2.858974
78
import os from pymongo import MongoClient from dotenv import load_dotenv if __name__ == "__main__": pass
[ 11748, 28686, 198, 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1208, 198 ]
2.947368
38
FILE = r'../src/etc-hosts.txt' hostnames = [] try: with open(FILE, encoding='utf-8') as file: content = file.readlines() except FileNotFoundError: print('File does not exist') except PermissionError: print('Permission denied') for line in content: if line.startswith('#'): continue if line.isspace(): continue line = line.strip().split() ip = line[0] hosts = line[1:] for record in hostnames: if record['ip'] == ip: record['hostnames'].update(hosts) break else: hostnames.append({ 'hostnames': set(hosts), 'protocol': 'IPv4' if '.' in ip else 'IPv6', 'ip': ip, }) print(hostnames)
[ 25664, 796, 374, 6, 40720, 10677, 14, 14784, 12, 4774, 82, 13, 14116, 6, 198, 4774, 14933, 796, 17635, 628, 198, 28311, 25, 198, 220, 220, 220, 351, 1280, 7, 25664, 11, 21004, 11639, 40477, 12, 23, 11537, 355, 2393, 25, 198, 220, ...
2.164223
341
def n_subimissions_per_day( url, headers ): """Get the number of submissions we can make per day for the selected challenge. Parameters ---------- url : {'prize', 'points', 'knowledge' , 'all'}, default='all' The reward of the challenges for top challengers. headers : dictionary , The headers of the request. Returns ------- n_sub : int, default=0 : Means error during info retrieval. The number of submissions we can make per day. """
[ 4299, 299, 62, 7266, 320, 7717, 62, 525, 62, 820, 7, 19016, 11, 24697, 15179, 198, 220, 220, 220, 37227, 3855, 262, 1271, 286, 22129, 356, 460, 787, 583, 1110, 329, 262, 6163, 4427, 13, 628, 220, 220, 220, 40117, 198, 220, 220, 22...
3.030488
164
# -*- coding: utf-8 -*- import unittest from src.graph import Graph from src.maximum_cut import maximum_cut, maximum_cut_for_bipartite_graph
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 12351, 13, 34960, 1330, 29681, 198, 6738, 12351, 13, 47033, 62, 8968, 1330, 5415, 62, 8968, 11, 5415, 62, 8968, 62, 1640, 62...
2.769231
52
# -*- coding: utf-8 -*- # # Copyright 2021 AVSystem <avsystem@avsystem.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # installation: append "source PATH_TO_THIS_SCRIPT" to ~/.gdbinit import gdb PrintAvsRbtreeSubtree() PrintAvsRbtree() PrintAvsRbtreeNode()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 33448, 14661, 11964, 1279, 615, 10057, 31, 615, 10057, 13, 785, 29, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 116...
3.355263
228
from pymongo import MongoClient if __name__=="__main__": mongo = MongoClient('mongodb://localhost:27017/') db = mongo['words'] collection = db['word_stats'] firstIsALastIsVowel(collection) firstLetterTotals(collection)
[ 6738, 279, 4948, 25162, 1330, 42591, 11792, 201, 198, 361, 11593, 3672, 834, 855, 1, 834, 12417, 834, 1298, 201, 198, 220, 220, 220, 285, 25162, 796, 42591, 11792, 10786, 31059, 375, 65, 1378, 36750, 25, 1983, 29326, 14, 11537, 201, 1...
2.595745
94
# Copyright 2020 Toyota Research Institute. All rights reserved. from packnet_sfm.utils.image import flip_lr, interpolate_scales from packnet_sfm.utils.misc import filter_dict from packnet_sfm.utils.types import is_tensor, is_list, is_numpy def flip(tensor, flip_fn): """ Flip tensors or list of tensors based on a function Parameters ---------- tensor : torch.Tensor or list[torch.Tensor] or list[list[torch.Tensor]] Tensor to be flipped flip_fn : Function Flip function Returns ------- tensor : torch.Tensor or list[torch.Tensor] or list[list[torch.Tensor]] Flipped tensor or list of tensors """ if not is_list(tensor): return flip_fn(tensor) else: if not is_list(tensor[0]): return [flip_fn(val) for val in tensor] else: return [[flip_fn(v) for v in val] for val in tensor] def merge_outputs(*outputs): """ Merges model outputs for logging Parameters ---------- outputs : tuple of dict Outputs to be merged Returns ------- output : dict Dictionary with a "metrics" key containing a dictionary with various metrics and all other keys that are not "loss" (it is handled differently). """ ignore = ['loss'] # Keys to ignore combine = ['metrics'] # Keys to combine merge = {key: {} for key in combine} for output in outputs: # Iterate over all keys for key, val in output.items(): # Combine these keys if key in combine: for sub_key, sub_val in output[key].items(): assert sub_key not in merge[key].keys(), \ 'Combining duplicated key {} to {}'.format(sub_key, key) merge[key][sub_key] = sub_val # Ignore these keys elif key not in ignore: assert key not in merge.keys(), \ 'Adding duplicated key {}'.format(key) merge[key] = val return merge def stack_batch(batch): """ Stack multi-camera batches (B,N,C,H,W becomes BN,C,H,W) Parameters ---------- batch : dict Batch Returns ------- batch : dict Stacked batch """ # If there is multi-camera information if len(batch['rgb'].shape) == 5: assert batch['rgb'].shape[0] == 1, 'Only batch size 1 is supported for multi-cameras' # Loop over all keys for key in batch.keys(): # If list, stack every item if is_list(batch[key]): if is_tensor(batch[key][0]) or is_numpy(batch[key][0]): batch[key] = [sample[0] for sample in batch[key]] # Else, stack single item else: batch[key] = batch[key][0] return batch def flip_batch_input(batch): """ Flip batch input information (copies data first) Parameters ---------- batch : dict Batch information Returns ------- batch : dict Flipped batch """ # Flip tensors for key in filter_dict(batch, [ 'rgb', 'rgb_context', 'input_depth', 'input_depth_context', ]): batch[key] = flip(batch[key], flip_lr) # Flip intrinsics for key in filter_dict(batch, [ 'intrinsics' ]): batch[key] = batch[key].clone() batch[key][:, 0, 2] = batch['rgb'].shape[3] - batch[key][:, 0, 2] # Return flipped batch return batch def flip_output(output): """ Flip output information Parameters ---------- output : dict Dictionary of model outputs (e.g. with keys like 'inv_depths' and 'uncertainty') Returns ------- output : dict Flipped output """ # Flip tensors for key in filter_dict(output, [ 'uncertainty', 'logits_semantic', 'ord_probability', 'inv_depths', 'inv_depths_context', 'inv_depths1', 'inv_depths2', 'pred_depth', 'pred_depth_context', 'pred_depth1', 'pred_depth2', 'pred_inv_depth', 'pred_inv_depth_context', 'pred_inv_depth1', 'pred_inv_depth2', ]): output[key] = flip(output[key], flip_lr) return output def upsample_output(output, mode='nearest', align_corners=None): """ Upsample multi-scale outputs to full resolution. Parameters ---------- output : dict Dictionary of model outputs (e.g. with keys like 'inv_depths' and 'uncertainty') mode : str Which interpolation mode is used align_corners: bool or None Whether corners will be aligned during interpolation Returns ------- output : dict Upsampled output """ for key in filter_dict(output, [ 'inv_depths', 'uncertainty' ]): output[key] = interpolate_scales( output[key], mode=mode, align_corners=align_corners) for key in filter_dict(output, [ 'inv_depths_context' ]): output[key] = [interpolate_scales( val, mode=mode, align_corners=align_corners) for val in output[key]] return output
[ 2, 15069, 12131, 20182, 4992, 5136, 13, 220, 1439, 2489, 10395, 13, 198, 198, 6738, 2353, 3262, 62, 28202, 76, 13, 26791, 13, 9060, 1330, 14283, 62, 14050, 11, 39555, 378, 62, 1416, 2040, 198, 6738, 2353, 3262, 62, 28202, 76, 13, 26...
2.325
2,200
''' Created on 25.07.2012 @author: karl '''
[ 7061, 6, 198, 41972, 319, 1679, 13, 2998, 13, 6999, 198, 198, 31, 9800, 25, 479, 7063, 198, 7061, 6, 628 ]
2.190476
21
# To make directory as a python package
[ 2, 1675, 787, 8619, 355, 257, 21015, 5301, 198 ]
4.444444
9
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_orthoexon ---------------------------------- Tests for `orthoexon` module. """ import os import pytest def test_separate_with_quotes(exon_id_with_quotes): from orthoexon.util import separate test = separate(exon_id_with_quotes) true = "ENSE00001229068" assert test == true def test_separate(exon_id): from orthoexon.util import separate test = separate(exon_id) true = "ENSE00001229068" assert test == true def test_translate(exon_id, human_fasta, human_gtf_database): from orthoexon.util import translate from orthoexon.util import separate for index, species1gene in enumerate(human_gtf_database.features_of_type('gene')): species1gffutilsgeneid = str(species1gene['gene_id']) species1geneid = separate(species1gffutilsgeneid) for exon in human_gtf_database.children(species1geneid, featuretype='CDS', order_by='start'): if exon_id == exon: test = translate(exon, human_fasta) break break true = 'MAEDADMRNELEEMQRRADQLADE' assert test == true # def test_getsequence(exon, human_gtf_database): # from orthoexon.util import getsequence # # test = getsequence(exon, human_gtf_database) # true = 'ATGGCCGAAGACGCAGACATGCGCAATGAGCTGGAGGAGATGCAGCGAAGGGCTGACCAGTT' \ # 'GGCTGATGAG' # # assert test == true # def test_make_sequence_array(finalsequencedf): # from orthoexon.util import make_sequence_array # # test = make_sequence_array(finalsequencedf) # true = ...... # # assert test == true
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 9288, 62, 1506, 78, 1069, 261, 198, 3880, 438, 198, 198, 51, 3558, 329, 4600, 1506, 78, 1069, 261, ...
2.203325
782
import argparse import os import shutil import time import numpy as np from utils import model, utils from utils.record import RecordAudio parser = argparse.ArgumentParser() parser.add_argument('--audio_db', default='audio_db/', type=str, help='') parser.add_argument('--threshold', default=0.7, type=float, help='') parser.add_argument('--model_path', default=r'models/resnet34-56.h5', type=str, help='') args = parser.parse_args() person_feature = [] person_name = [] # network_eval = model.vggvox_resnet2d_icassp(input_dim=(257, None, 1), mode='eval') # network_eval.load_weights(os.path.join(args.model_path), by_name=True) print('==> successfully loading model {}.'.format(args.model_path)) # # # # if __name__ == '__main__': load_audio_db(args.audio_db) record_audio = RecordAudio() while True: select_fun = int(input("01")) if select_fun == 0: audio_path = record_audio.record() name = input("") if name == '': continue register(audio_path, name) elif select_fun == 1: audio_path = record_audio.record() name, p = recognition(audio_path) if p > args.threshold: print("%s%f" % (name, p)) else: print("") else: print('')
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 640, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 3384, 4487, 1330, 2746, 11, 3384, 4487, 198, 6738, 3384, 4487, 13, 22105, 1330, 13266, 21206, 198, 1...
2.171924
634
import logging from datetime import timedelta from flask import Blueprint, Response, abort, redirect, url_for from cubedash import _model, _utils, _utils as utils _LOG = logging.getLogger(__name__) bp = Blueprint("product", __name__) def _iso8601_duration(tdelta: timedelta): """ Format a timedelta as an iso8601 duration >>> _iso8601_duration(timedelta(seconds=0)) 'PT0S' >>> _iso8601_duration(timedelta(seconds=1)) 'PT1S' >>> _iso8601_duration(timedelta(seconds=23423)) 'PT6H30M23S' >>> _iso8601_duration(timedelta(seconds=4564564556)) 'P52830DT14H35M56S' """ all_secs = tdelta.total_seconds() secs = int(all_secs % 60) h_m_s = ( int(all_secs // 3600 % 24), int(all_secs // 60 % 60), secs if secs % 1 != 0 else int(secs), ) parts = ["P"] days = int(all_secs // 86400) if days: parts.append(f"{days}D") if any(h_m_s): parts.append("T") if all_secs: for val, name in zip(h_m_s, ["H", "M", "S"]): if val: parts.append(f"{val}{name}") else: parts.append("T0S") return "".join(parts)
[ 11748, 18931, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 198, 6738, 42903, 1330, 39932, 11, 18261, 11, 15614, 11, 18941, 11, 19016, 62, 1640, 198, 198, 6738, 13617, 276, 1077, 1330, 4808, 19849, 11, 4808, 26791, 11, 4808, 26791, 35...
2.124324
555
# # This file is part of LiteX-Boards. # # Copyright (c) 2021 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause # Board diagram/pinout: # https://user-images.githubusercontent.com/1450143/133655492-532d5e9a-0635-4889-85c9-68683d06cae0.png # http://dl.sipeed.com/TANG/Nano/HDK/Tang-NANO-2704(Schematic).pdf from migen import * from litex.build.generic_platform import * from litex.build.gowin.platform import GowinPlatform from litex.build.openfpgaloader import OpenFPGALoader # IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk / Rst ("clk24", 0, Pins("35"), IOStandard("LVCMOS33")), # Leds ("user_led", 0, Pins("16"), IOStandard("LVCMOS33")), ("user_led", 1, Pins("17"), IOStandard("LVCMOS33")), ("user_led", 2, Pins("18"), IOStandard("LVCMOS33")), # Buttons. ("user_btn", 0, Pins("15"), IOStandard("LVCMOS33")), ("user_btn", 0, Pins("14"), IOStandard("LVCMOS33")), # Serial ("serial", 0, Subsignal("tx", Pins("8")), Subsignal("rx", Pins("9")), IOStandard("LVCMOS33") ), ] # Connectors --------------------------------------------------------------------------------------- _connectors = [] # Platform -----------------------------------------------------------------------------------------
[ 2, 198, 2, 770, 2393, 318, 636, 286, 27395, 55, 12, 16635, 1371, 13, 198, 2, 198, 2, 15069, 357, 66, 8, 33448, 23347, 429, 17337, 3876, 8344, 1279, 2704, 382, 429, 31, 268, 2633, 12, 34725, 13, 8310, 29, 198, 2, 30628, 55, 12, ...
2.715976
507
import torch from torch.distributions.kl import kl_divergence from torch.nn.utils.convert_parameters import (vector_to_parameters, parameters_to_vector) from rl_utils.optimization import conjugate_gradient from rl_utils.torch_utils import (weighted_mean, detach_distribution, weighted_normalize)
[ 11748, 28034, 198, 6738, 28034, 13, 17080, 2455, 507, 13, 41582, 1330, 479, 75, 62, 67, 1428, 12745, 198, 6738, 28034, 13, 20471, 13, 26791, 13, 1102, 1851, 62, 17143, 7307, 1330, 357, 31364, 62, 1462, 62, 17143, 7307, 11, 198, 220, ...
2.5
138
from datetime import timedelta from dateutil.relativedelta import relativedelta from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from ...models import Request DURATION_OPTIONS = { 'hours': lambda amount: timezone.now() - timedelta(hours=amount), 'days': lambda amount: timezone.now() - timedelta(days=amount), 'weeks': lambda amount: timezone.now() - timedelta(weeks=amount), 'months': lambda amount: timezone.now() + relativedelta(months=-amount), 'years': lambda amount: timezone.now() + relativedelta(years=-amount), } try: # to keep backward Python 2 compatibility input = raw_input except NameError: pass
[ 6738, 4818, 8079, 1330, 28805, 12514, 198, 198, 6738, 3128, 22602, 13, 2411, 265, 1572, 12514, 1330, 48993, 1572, 12514, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 11, 9455, 12331, 198, 6738, 42625, 14208, ...
3.187215
219
import pytest import windows.crypto import windows.generated_def as gdef import windows.crypto.generation from .pfwtest import * pytestmark = pytest.mark.usefixtures('check_for_gc_garbage') TEST_CERT = b""" MIIBwTCCASqgAwIBAgIQG46Uyws+67ZBOfPJCbFrRjANBgkqhkiG9w0BAQsFADAfMR0wGwYDVQQD ExRQeXRob25Gb3JXaW5kb3dzVGVzdDAeFw0xNzA0MTIxNDM5MjNaFw0xODA0MTIyMDM5MjNaMB8x HTAbBgNVBAMTFFB5dGhvbkZvcldpbmRvd3NUZXN0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQCRHwC/sRfXh5pc4poc85aidrudbPdya+0OeonQlf1JQ1ekf7KSfADV5FLkSQu2BzgBK9DIWTGX XknBJIzZF03UZsVg5D67V2mnSClXucc0cGFcK4pDDt0tHeabA2GPinVe7Z6qDT4ZxPR8lKaXDdV2 Pg2hTdcGSpqaltHxph7G/QIDAQABMA0GCSqGSIb3DQEBCwUAA4GBACcQFdOlVjYICOIyAXowQaEN qcLpN1iWoL9UijNhTY37+U5+ycFT8QksT3Xmh9lEIqXMh121uViy2P/3p+Ek31AN9bB+BhWIM6PQ gy+ApYDdSwTtWFARSrMqk7rRHUveYEfMw72yaOWDxCzcopEuADKrrYEute4CzZuXF9PbbgK6""" ## Cert info: # Name: PythonForWindowsTest # Serial: '1b 8e 94 cb 0b 3e eb b6 41 39 f3 c9 09 b1 6b 46' TEST_PFX_PASSWORD = "TestPassword" TEST_PFX = b""" MIIGMwIBAzCCBe8GCSqGSIb3DQEHAaCCBeAEggXcMIIF2DCCA7AGCSqGSIb3DQEHAaCCA6EEggOd MIIDmTCCA5UGCyqGSIb3DQEMCgECoIICtjCCArIwHAYKKoZIhvcNAQwBAzAOBAhoE8r3qUJeTQIC B9AEggKQT7jm7ppgH64scyJ3cFW50BurqpMPtxgYyYCCtjdmHMlLPbUoujXOZVYi3seAEERE51BS TXUi5ydHpY8cZ104nU4iEuJBAc+TZ7NQSTkjLKwAY1r1jrIikkQEmewLVlWQnj9dvCwD3lNkGXG8 zJdWusta5Lw1Hz5ftsRXvN9UAvH8gxYviVRVmkZA33rI/BiyPZCulu2EBC0MeDBQHLLONup2xVGy +YgU4Uf7khJIftWCgdrkyJIaMuB7vGUl014ZBV+XWaox+bS71qFQXUP2WnyTeeBVIaTJtggk+80X fStWwvvzl02LTwGV3kJqWbazPlJkevfRQ7DNh1xa42eO57YEcEl3sR00anFWbL3J/I0bHb5XWY/e 8DYuMgIlat5gub8CTO2IViu6TexXFMXLxZdWAYvJ8ivc/q7mA/JcDJQlNnGof2Z6jY8ykWYloL/R XMn2LeGqrql/guyRQcDrZu0LGX4sDG0aP9dbjk5fQpXSif1RUY4/T3HYeL0+1zu86ZKwVIIX5YfT MLheIUGaXy/UJk361vAFKJBERGv1uufnqBxH0r1bRoytOaZr1niEA04u+VJa0DXOZzKBwxNhQRom x4ffrsP2VnoJX+wnfYhPOjkiPiHyhswheG0VITTkqD+2uF54M5X2LLdzQuJpu0MZ5HOAHck/ZEpa xV7h+kNse4p7y17b12H6tJNtVoJOlqP0Ujugc7vh4h8ZaPkSqVSV1nEvHzXx0c7gf038jv1+8WlN 4EgHp09FKU7sbSgcPY9jltElgaAr6J8a+rDGtk+055UeUYxM43U8naBiEOL77LP9FA0y8hKLKlJz 0GBCp4bJrLuZJenXHVb1Zme2EXO0jnQ9nB9OEyI3NpYTbZQxgcswEwYJKoZIhvcNAQkVMQYEBAEA AAAwRwYJKoZIhvcNAQkUMToeOABQAHkAdABoAG8AbgBGAG8AcgBXAGkAbgBkAG8AdwBzAFQATQBQ AEMAbwBuAHQAYQBpAG4AZQByMGsGCSsGAQQBgjcRATFeHlwATQBpAGMAcgBvAHMAbwBmAHQAIABF AG4AaABhAG4AYwBlAGQAIABDAHIAeQBwAHQAbwBnAHIAYQBwAGgAaQBjACAAUAByAG8AdgBpAGQA ZQByACAAdgAxAC4AMDCCAiAGCSqGSIb3DQEHAaCCAhEEggINMIICCTCCAgUGCyqGSIb3DQEMCgED oIIB3TCCAdkGCiqGSIb3DQEJFgGgggHJBIIBxTCCAcEwggEqoAMCAQICEBuOlMsLPuu2QTnzyQmx a0YwDQYJKoZIhvcNAQELBQAwHzEdMBsGA1UEAxMUUHl0aG9uRm9yV2luZG93c1Rlc3QwHhcNMTcw NDEyMTQzOTIzWhcNMTgwNDEyMjAzOTIzWjAfMR0wGwYDVQQDExRQeXRob25Gb3JXaW5kb3dzVGVz dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAkR8Av7EX14eaXOKaHPOWona7nWz3cmvtDnqJ 0JX9SUNXpH+yknwA1eRS5EkLtgc4ASvQyFkxl15JwSSM2RdN1GbFYOQ+u1dpp0gpV7nHNHBhXCuK Qw7dLR3mmwNhj4p1Xu2eqg0+GcT0fJSmlw3Vdj4NoU3XBkqampbR8aYexv0CAwEAATANBgkqhkiG 9w0BAQsFAAOBgQAnEBXTpVY2CAjiMgF6MEGhDanC6TdYlqC/VIozYU2N+/lOfsnBU/EJLE915ofZ RCKlzIddtblYstj/96fhJN9QDfWwfgYViDOj0IMvgKWA3UsE7VhQEUqzKpO60R1L3mBHzMO9smjl g8Qs3KKRLgAyq62BLrXuAs2blxfT224CujEVMBMGCSqGSIb3DQEJFTEGBAQBAAAAMDswHzAHBgUr DgMCGgQU70h/rEXLQOberGvgJenggoWU5poEFCfdE1wNK1M38Yp3+qfjEqNIJGCPAgIH0A== """ PFW_TEST_TMP_KEY_CONTAINER = "PythonForWindowsTMPContainerTest" RANDOM_CERTIF_NAME = b"PythonForWindowsGeneratedRandomCertifTest" RANDOM_PFX_PASSWORD = "PythonForWindowsGeneratedRandomPFXPassword" # str(windows.crypto.encrypt(TEST_CERT, "Hello crypto")).encode("base64") # Target serial == TEST_CERT.Serial == 1b 8e 94 cb 0b 3e eb b6 41 39 f3 c9 09 b1 6b 46 TEST_CRYPTMSG = b"""MIIBJAYJKoZIhvcNAQcDoIIBFTCCARECAQAxgc0wgcoCAQAwMzAfMR0wGwYDVQQDExRQeXRob25G b3JXaW5kb3dzVGVzdAIQG46Uyws+67ZBOfPJCbFrRjANBgkqhkiG9w0BAQcwAASBgA1fwFY8w4Bb fOMer94JhazbJxaUnV305QzF27w4GwNQ2UIpl9KWJoJJaF7azU3nVhP33agAxlxmr9fP48B6DeE1 pbu1jX9tEWlTJC6O0TmKcRPjblEaU6VJXXlpKlKZCmwCUuHR9VtcXGnxEU1Hy7FmHM96lvDRmYQT Y0MnRJLyMDwGCSqGSIb3DQEHATAdBglghkgBZQMEASoEEEdEGEzKBrDO/zC8z6q6HLaAEGbjGCay s6u32YhUxQ4/QhI="""
[ 11748, 12972, 9288, 198, 198, 11748, 9168, 13, 29609, 78, 198, 11748, 9168, 13, 27568, 62, 4299, 355, 308, 4299, 198, 11748, 9168, 13, 29609, 78, 13, 20158, 198, 198, 6738, 764, 79, 44482, 9288, 1330, 1635, 198, 198, 9078, 9288, 4102,...
1.471445
2,679
from __future__ import absolute_import, division, print_function from builtins import (bytes, str, open, super, range, zip, round, input, int, pow, object, map, zip) __author__ = "Andrea Tramacere" import numpy as np from astropy import wcs from bokeh.layouts import row, widgetbox,gridplot from bokeh.models import CustomJS, Slider,HoverTool,ColorBar,LinearColorMapper,LabelSet,ColumnDataSource from bokeh.embed import components from bokeh.plotting import figure from bokeh.palettes import Plasma256
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 6738, 3170, 1040, 1330, 357, 33661, 11, 965, 11, 1280, 11, 2208, 11, 2837, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.928962
183
from pathlib import Path from testaid.pathlist import PathList
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 1332, 1698, 13, 6978, 4868, 1330, 10644, 8053, 628, 628 ]
3.882353
17
# Copyright 2016-2017 IBM Corp. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for _hba module. """ from __future__ import absolute_import, print_function import pytest import re import copy from zhmcclient import Client, Hba, HTTPError, NotFound from zhmcclient_mock import FakedSession from tests.common.utils import assert_resources # Object IDs and names of our faked HBAs: HBA1_OID = 'hba 1-oid' HBA1_NAME = 'hba 1' HBA2_OID = 'hba 2-oid' HBA2_NAME = 'hba 2' # URIs and Object IDs of elements referenced in HBA properties: FCP1_OID = 'fake-fcp1-oid' PORT11_OID = 'fake-port11-oid' PORT11_URI = '/api/adapters/{}/storage-ports/{}'.format(FCP1_OID, PORT11_OID) def test_hba_delete_create_same_name(self): """Test Hba.delete() followed by Hba.create() with same name.""" # Add a faked HBA to be tested and another one faked_hba = self.add_hba1() hba_name = faked_hba.name self.add_hba2() # Construct the input properties for a third HBA with same name part3_props = copy.deepcopy(faked_hba.properties) part3_props['description'] = 'Third HBA' # Set the status of the faked partition self.faked_partition.properties['status'] = 'stopped' # deletable hba_mgr = self.partition.hbas hba = hba_mgr.find(name=hba_name) # Execute the deletion code to be tested. hba.delete() # Check that the HBA no longer exists with pytest.raises(NotFound): hba_mgr.find(name=hba_name) # Execute the creation code to be tested. hba_mgr.create(part3_props) # Check that the HBA exists again under that name hba3 = hba_mgr.find(name=hba_name) description = hba3.get_property('description') assert description == 'Third HBA' def test_hba_update_name(self): """Test Hba.update_properties() with 'name' property.""" # Add a faked HBA faked_hba = self.add_hba1() hba_name = faked_hba.name # Set the status of the faked partition self.faked_partition.properties['status'] = 'stopped' # updatable hba_mgr = self.partition.hbas hba = hba_mgr.find(name=hba_name) new_hba_name = "new-" + hba_name # Execute the code to be tested hba.update_properties(properties={'name': new_hba_name}) # Verify that the resource is no longer found by its old name, using # list() (this does not use the name-to-URI cache). hbas_list = hba_mgr.list( filter_args=dict(name=hba_name)) assert len(hbas_list) == 0 # Verify that the resource is no longer found by its old name, using # find() (this uses the name-to-URI cache). with pytest.raises(NotFound): hba_mgr.find(name=hba_name) # Verify that the resource object already reflects the update, even # though it has not been refreshed yet. assert hba.properties['name'] == new_hba_name # Refresh the resource object and verify that it still reflects the # update. hba.pull_full_properties() assert hba.properties['name'] == new_hba_name # Verify that the resource can be found by its new name, using find() new_hba_find = hba_mgr.find(name=new_hba_name) assert new_hba_find.properties['name'] == new_hba_name # Verify that the resource can be found by its new name, using list() new_hbas_list = hba_mgr.list( filter_args=dict(name=new_hba_name)) assert len(new_hbas_list) == 1 new_hba_list = new_hbas_list[0] assert new_hba_list.properties['name'] == new_hba_name
[ 2, 15069, 1584, 12, 5539, 19764, 11421, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
2.481503
1,703
root = getRoot(config) # We only run a small set of tests on Windows for now. # Override the parent directory's "unsupported" decision until we can handle # all of its tests. if root.host_os in ['Windows']: config.unsupported = False else: config.unsupported = True
[ 198, 15763, 796, 651, 30016, 7, 11250, 8, 198, 198, 2, 775, 691, 1057, 257, 1402, 900, 286, 5254, 319, 3964, 329, 783, 13, 198, 2, 3827, 13154, 262, 2560, 8619, 338, 366, 403, 15999, 1, 2551, 1566, 356, 460, 5412, 198, 2, 477, 2...
3.4
80
import math import os.path import sys import textwrap from test import support def printlist(x, width=70, indent=4, file=None): """Print the elements of iterable x to stdout. Optional arg width (default 70) is the maximum line length. Optional arg indent (default 4) is the number of blanks with which to begin each line. """ blanks = ' ' * indent # Print the sorted list: 'x' may be a '--random' list or a set() print(textwrap.fill(' '.join(str(elt) for elt in sorted(x)), width, initial_indent=blanks, subsequent_indent=blanks), file=file) orig_unraisablehook = None
[ 11748, 10688, 198, 11748, 28686, 13, 6978, 198, 11748, 25064, 198, 11748, 2420, 37150, 198, 6738, 1332, 1330, 1104, 628, 628, 198, 198, 4299, 3601, 4868, 7, 87, 11, 9647, 28, 2154, 11, 33793, 28, 19, 11, 2393, 28, 14202, 2599, 198, ...
2.722689
238
""" AJAX for SQLite Viewer plugin """ from yapsy.IPlugin import IPlugin from flask import Response, jsonify import json import logging import sqlite3
[ 37811, 198, 32, 41, 25922, 329, 16363, 578, 3582, 263, 13877, 198, 37811, 198, 198, 6738, 331, 1686, 88, 13, 40, 37233, 1330, 314, 37233, 198, 6738, 42903, 1330, 18261, 11, 33918, 1958, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, ...
3.355556
45
import requests, json url = 'http://educacao.dadosabertosbr.com/api/cidades/ce' cidades = requests.get(url).content cidades = cidades.decode('utf-8') cidades = json.loads(cidades) for cidade in cidades: codigo, nome = cidade.split(':') print(nome)
[ 11748, 7007, 11, 33918, 198, 198, 6371, 796, 705, 4023, 1378, 18123, 330, 5488, 13, 67, 22484, 397, 861, 418, 1671, 13, 785, 14, 15042, 14, 66, 312, 2367, 14, 344, 6, 198, 66, 312, 2367, 796, 7007, 13, 1136, 7, 6371, 737, 11299, ...
2.333333
108
__version__ = "4.3.1.post1"
[ 198, 834, 9641, 834, 796, 366, 19, 13, 18, 13, 16, 13, 7353, 16, 1, 198 ]
1.8125
16
import math from constants import Constants from utils import vector2d from wpilib import SmartDashboard as Dash from autonomous import pursuitpoint
[ 11748, 10688, 198, 6738, 38491, 1330, 4757, 1187, 198, 6738, 3384, 4487, 1330, 15879, 17, 67, 198, 6738, 266, 79, 22282, 1330, 10880, 43041, 3526, 355, 16189, 198, 6738, 18284, 1330, 14748, 4122, 628 ]
4.411765
34
import difflib import itertools import voluptuous as vol from esphome.py_compat import string_types # pylint: disable=protected-access, unidiomatic-typecheck
[ 11748, 814, 8019, 198, 11748, 340, 861, 10141, 198, 198, 11748, 2322, 37623, 5623, 355, 2322, 198, 198, 6738, 1658, 746, 462, 13, 9078, 62, 5589, 265, 1330, 4731, 62, 19199, 628, 628, 198, 2, 279, 2645, 600, 25, 15560, 28, 24326, 12...
3.153846
52
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Filename: DensityPeaks.py # @Author: Daniel Puente Ramrez # @Time: 5/3/22 09:55 # @Version: 4.0 import math from collections import defaultdict import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier, NearestNeighbors from sklearn.preprocessing import LabelEncoder from sklearn.semi_supervised import SelfTrainingClassifier from sklearn.svm import SVC from instance_selection import ENN from .utils import split
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 2488, 35063, 25, 220, 220, 220, 360, 6377, 6435, 4730, 13, 9078, 198, 2, 2488, 13838, 25, 220, 220, 220, 220, 220, ...
2.910112
178
""" # Definition for a Node. """ node2 = TreeNode(2, []) node3 = TreeNode(3, []) children = [node2, node3] node1 = TreeNode(1, children) solution = Solution() print(solution.levelOrder(node1))
[ 37811, 198, 2, 30396, 329, 257, 19081, 13, 198, 37811, 628, 198, 198, 17440, 17, 796, 12200, 19667, 7, 17, 11, 685, 12962, 198, 17440, 18, 796, 12200, 19667, 7, 18, 11, 685, 12962, 198, 17197, 796, 685, 17440, 17, 11, 10139, 18, 6...
2.648649
74
""" websocket - WebSocket client library for Python Copyright (C) 2010 Hiroki Ohtani(liris) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA """ from __future__ import print_function import six import socket if six.PY3: from base64 import encodebytes as base64encode else: from base64 import encodestring as base64encode import struct import threading # websocket modules from ._exceptions import * from ._abnf import * from ._socket import * from ._utils import * from ._url import * from ._logging import * from ._http import * from ._handshake import * from ._ssl_compat import * """ websocket python client. ========================= This version support only hybi-13. Please see http://tools.ietf.org/html/rfc6455 for protocol. """ def create_connection(url, timeout=None, class_=WebSocket, **options): """ connect to url and return websocket object. Connect to url and return the WebSocket object. Passing optional timeout parameter will set the timeout on the socket. If no timeout is supplied, the global default timeout setting returned by getdefauttimeout() is used. You can customize using 'options'. If you set "header" list object, you can set your own custom header. >>> conn = create_connection("ws://echo.websocket.org/", ... header=["User-Agent: MyProgram", ... "x-custom: header"]) timeout: socket timeout time. This value is integer. if you set None for this value, it means "use default_timeout value" class_: class to instantiate when creating the connection. It has to implement settimeout and connect. It's __init__ should be compatible with WebSocket.__init__, i.e. accept all of it's kwargs. options: "header" -> custom http header list or dict. "cookie" -> cookie value. "origin" -> custom origin url. "host" -> custom host header string. "http_proxy_host" - http proxy host name. "http_proxy_port" - http proxy port. If not set, set to 80. "http_no_proxy" - host names, which doesn't use proxy. "http_proxy_auth" - http proxy auth information. tuple of username and password. default is None "enable_multithread" -> enable lock for multithread. "sockopt" -> socket options "sslopt" -> ssl option "subprotocols" - array of available sub protocols. default is None. "skip_utf8_validation" - skip utf8 validation. "socket" - pre-initialized stream socket. """ sockopt = options.pop("sockopt", []) sslopt = options.pop("sslopt", {}) fire_cont_frame = options.pop("fire_cont_frame", False) enable_multithread = options.pop("enable_multithread", False) skip_utf8_validation = options.pop("skip_utf8_validation", False) websock = class_(sockopt=sockopt, sslopt=sslopt, fire_cont_frame=fire_cont_frame, enable_multithread=enable_multithread, skip_utf8_validation=skip_utf8_validation, **options) websock.settimeout(timeout if timeout is not None else getdefaulttimeout()) websock.connect(url, **options) return websock
[ 37811, 198, 732, 1443, 5459, 532, 5313, 39105, 5456, 5888, 329, 11361, 198, 198, 15269, 357, 34, 8, 3050, 25940, 4106, 3966, 83, 3216, 7, 75, 29616, 8, 628, 220, 220, 220, 770, 5888, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, ...
2.7
1,510
from django.db import models from vaccine_card.vaccination.models import Vaccine
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 6738, 12319, 62, 9517, 13, 37839, 1883, 13, 27530, 1330, 31749, 500, 628, 628, 628, 198 ]
3.52
25
# 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. # libcloud.org 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. # Copyright 2009 RedRata Ltd from libcloud.drivers.rimuhosting import RimuHostingNodeDriver from test import MockHttp from test import MockHttp, TestCaseMixin import unittest import httplib
[ 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 393, 517, 198, 2, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 9387, 351, 198, 2, 428, 670, 329, 3224, 1321, 5115, 6634, 9238, 13, 198, 2, 9195, 17721, 13...
4.012295
244
from typing import Tuple from hypothesis import given from gon.base import (Point, Polygon) from tests.utils import (equivalence, implication) from . import strategies
[ 6738, 19720, 1330, 309, 29291, 198, 198, 6738, 14078, 1330, 1813, 198, 198, 6738, 35140, 13, 8692, 1330, 357, 12727, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.417582
91
import os import numpy as np import pytest import easyidp from easyidp.core.objects import ReconsProject, Points from easyidp.io import metashape module_path = os.path.join(easyidp.__path__[0], "io/tests")
[ 11748, 28686, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 11748, 2562, 312, 79, 198, 6738, 2562, 312, 79, 13, 7295, 13, 48205, 1330, 3311, 684, 16775, 11, 11045, 198, 6738, 2562, 312, 79, 13, 952, 1330, 1138...
2.853333
75
"""Constant values.""" STATUS_SUCCESS = (0,) STATUS_AUTH_FAILED = (100, 101, 102, 200, 401) STATUS_INVALID_PARAMS = ( 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 216, 217, 218, 220, 221, 223, 225, 227, 228, 229, 230, 234, 235, 236, 238, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 254, 260, 261, 262, 263, 264, 265, 266, 267, 271, 272, 275, 276, 283, 284, 285, 286, 287, 288, 290, 293, 294, 295, 297, 300, 301, 302, 303, 304, 321, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 380, 381, 382, 400, 501, 502, 503, 504, 505, 506, 509, 510, 511, 523, 532, 3017, 3018, 3019, ) STATUS_UNAUTHORIZED = (214, 277, 2553, 2554, 2555) STATUS_ERROR_OCCURRED = ( 215, 219, 222, 224, 226, 231, 233, 237, 253, 255, 256, 257, 258, 259, 268, 269, 270, 273, 274, 278, 279, 280, 281, 282, 289, 291, 292, 296, 298, 305, 306, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 322, 370, 371, 372, 373, 374, 375, 383, 391, 402, 516, 517, 518, 519, 520, 521, 525, 526, 527, 528, 529, 530, 531, 533, 602, 700, 1051, 1052, 1053, 1054, 2551, 2552, 2556, 2557, 2558, 2559, 3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3020, 3021, 3022, 3023, 3024, 5000, 5001, 5005, 5006, 6000, 6010, 6011, 9000, 10000, ) STATUS_TIMEOUT = (522,) STATUS_BAD_STATE = (524,) STATUS_TOO_MANY_REQUESTS = (601,)
[ 37811, 3103, 18797, 3815, 526, 15931, 198, 198, 35744, 2937, 62, 12564, 4093, 7597, 796, 357, 15, 35751, 198, 198, 35744, 2937, 62, 32, 24318, 62, 7708, 4146, 1961, 796, 357, 3064, 11, 8949, 11, 15143, 11, 939, 11, 22219, 8, 198, 19...
1.524321
1,583
#!/usr/bin/env python from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.slider import Slider from kivy.graphics import Color, Bezier, Line if __name__ == '__main__': Main().run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 479, 452, 88, 13, 1324, 1330, 2034, 198, 6738, 479, 452, 88, 13, 84, 844, 13, 22468, 39786, 1330, 48436, 32517, 198, 6738, 479, 452, 88, 13, 84, 844, 13, 6649, 1304, 1330, 34...
2.662651
83
#coding:utf-8 # # id: bugs.core_6489 # title: User without ALTER ANY ROLE privilege can use COMMENT ON ROLE # decription: # Test creates two users: one of them has no any rights, second is granted with 'alter any role' privilege. # First user ('junior') must not have ability to add comment to rdb$admin role, but second ('senior') must # be able to set comment to any string and make it null. # # Confirmed bug on 4.0.0.2384, 3.0.8.33425 # Checked on: 4.0.0.2387, 3.0.8.33426 -- all OK. # # NOTE: # phrase '-Effective user is ...' presents only in FB 4.x and is suppressed here. # # tracker_id: CORE-6489 # min_versions: ['3.0.8'] # versions: 3.0.8 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0.8 # resources: None substitutions_1 = [('ROLE_DESCR_BLOB_ID .*', ''), ('[\t ]+', ' '), ('(-)?Effective user is.*', '')] init_script_1 = """""" db_1 = db_factory(sql_dialect=3, init=init_script_1) test_script_1 = """ create or alter user tmp$c6489_junior password '123' using plugin Srp; create or alter user tmp$c6489_senior password '456' using plugin Srp; commit; grant alter any role to user tmp$c6489_senior; commit; connect '$(DSN)' user tmp$c6489_junior password '123'; comment on role rdb$admin is 'Comment by tmp$c6489_junior'; commit; connect '$(DSN)' user tmp$c6489_senior password '456'; comment on role rdb$admin is 'Comment by tmp$c6489_senior'; commit; set list on; select r.rdb$description as role_descr_blob_id from rdb$roles r where r.rdb$role_name = upper('rdb$admin'); commit; comment on role rdb$admin is null; commit; connect '$(DSN)' user 'SYSDBA' password 'masterkey'; drop user tmp$c6489_junior using plugin Srp; drop user tmp$c6489_senior using plugin Srp; commit; """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ Comment by tmp$c6489_senior """ expected_stderr_1 = """ Statement failed, SQLSTATE = 28000 unsuccessful metadata update -COMMENT ON RDB$ADMIN failed -no permission for ALTER access to ROLE RDB$ADMIN -Effective user is TMP$C6489_JUNIOR """
[ 2, 66, 7656, 25, 40477, 12, 23, 198, 2, 198, 2, 4686, 25, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 11316, 13, 7295, 62, 2414, 4531, 198, 2, 3670, 25, 220, 220, 220, 220, 220, 220, 220, 11787, 1231, 8355, 5781, 15529, ...
2.285171
1,052
import numpy as np import torch from torch.nn import functional as F from torchvision.ops import nms
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 20471, 1330, 10345, 355, 376, 198, 6738, 28034, 10178, 13, 2840, 1330, 299, 907, 628, 220, 220, 220, 220, 220, 220, 220, 220, 198 ]
3.083333
36
#!/usr/bin/env python # encoding: utf-8 import sys reload(sys) sys.setdefaultencoding("utf-8")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 11748, 25064, 198, 198, 260, 2220, 7, 17597, 8, 198, 17597, 13, 2617, 12286, 12685, 7656, 7203, 40477, 12, 23, 4943 ]
2.461538
39
#!/usr/bin/python """ Tests for Pyclipper wrapper library. """ from __future__ import print_function from unittest2 import TestCase, main import sys if sys.version_info < (3,): integer_types = (int, long) else: integer_types = (int,) import pyclipper # Example polygons from http://www.angusj.com/delphi/clipper.php PATH_SUBJ_1 = [[180, 200], [260, 200], [260, 150], [180, 150]] # square, orientation is False PATH_SUBJ_2 = [[215, 160], [230, 190], [200, 190]] # triangle PATH_CLIP_1 = [[190, 210], [240, 210], [240, 130], [190, 130]] # square PATH_SIGMA = [[300, 400], [100, 400], [200, 300], [100, 200], [300, 200]] # greek letter sigma PATTERN = [[4, -6], [6, -6], [-4, 6], [-6, 6]] INVALID_PATH = [[1, 1], ] # less than 2 vertices def test_execute(self): solution = self.pc.Execute(*self.default_args) self.assertEqual(len(solution), 2) def test_execute2(self): solution = self.pc.Execute2(*self.default_args) self.assertIsInstance(solution, pyclipper.PyPolyNode) self.check_pypolynode(solution) def test_execute_empty(self): pc = pyclipper.Pyclipper() with self.assertRaises(pyclipper.ClipperException): pc.Execute(pyclipper.CT_UNION, pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO) def test_clear(self): self.pc.Clear() with self.assertRaises(pyclipper.ClipperException): self.pc.Execute(*self.default_args) def test_exact_results(self): """ Test whether coordinates passed into the library are returned exactly, if they are not affected by the operation. """ pc = pyclipper.Pyclipper() # Some large triangle. path = [[[0, 1], [0, 0], [15 ** 15, 0]]] pc.AddPaths(path, pyclipper.PT_SUBJECT, True) result = pc.Execute(pyclipper.PT_CLIP, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD) assert result == path def check_pypolynode(self, node): self.assertTrue(len(node.Contour) == 0 or len(node.Contour) > 2) # check vertex coordinate, should not be an iterable (in that case # that means that node.Contour is a list of paths, should be path if node.Contour: self.assertFalse(hasattr(node.Contour[0][0], '__iter__')) for child in node.Childs: self.check_pypolynode(child) class TestPyclipperOffset(TestCase): class TestScalingFactorWarning(TestCase): class TestScalingFunctions(TestCase): scale = 2 ** 31 path = [(0, 0), (1, 1)] paths = [path] * 3 class TestNonStandardNumbers(TestCase): def _do_solutions_match(paths_1, paths_2, factor=None): if len(paths_1) != len(paths_2): return False paths_1 = [_modify_vertices(p, multiplier=factor, converter=round if factor else None) for p in paths_1] paths_2 = [_modify_vertices(p, multiplier=factor, converter=round if factor else None) for p in paths_2] return all(((p_1 in paths_2) for p_1 in paths_1)) def _modify_vertices(path, addend=0.0, multiplier=1.0, converter=None): path = path[:] return [[convert_coordinate(c) for c in v] for v in path] def run_tests(): main() if __name__ == '__main__': run_tests()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 37811, 198, 51, 3558, 329, 9485, 565, 14710, 29908, 5888, 13, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 555, 715, 395, 17, 1330, 6208, 20448, 11, 1388, ...
2.353957
1,390
FACTS = ['espoem multiplied by zero still equals espoem.', 'There is no theory of evolution. Just a list of creatures espoem has allowed to live.', 'espoem does not sleep. He waits.', 'Alexander Graham Bell had three missed calls from espoem when he invented the telephone.', 'espoem is the reason why Waldo is hiding.', 'espoem can slam a revolving door.', "espoem isn't lifting himself up when doing a pushup; he's pushing the earth down.", "espoem' hand is the only hand that can beat a Royal Flush.", 'espoem made a Happy Meal cry.', "espoem doesn't need Twitter; he's already following you.", 'espoem once won an underwater breathing contest with a fish.While urinating, espoem is easily capable of welding titanium.', 'In an act of great philanthropy, espoem made a generous donation to the American Cancer Society. He donated 6,000 dead bodies for scientific research.', 'espoem once one a game of connect four in 3 moves.', "Google won't search for espoem because it knows you don't find espoem, he finds you.", 'espoem? favourite cut of meat is the roundhouse.', 'It is scientifically impossible for espoem to have had a mortal father. The most popular theory is that he went back in time and fathered himself.', 'espoem had to stop washing his clothes in the ocean. The tsunamis were killing people.', 'Pluto is actually an orbiting group of British soldiers from the American Revolution who entered space after the espoem gave them a roundhouse kick to the face.', 'In the Words of Julius Caesar, Veni, Vidi, Vici, espoem. Translation: I came, I saw, and I was roundhouse-kicked inthe face by espoem.', "espoem doesn't look both ways before he crosses the street... he just roundhouses any cars that get too close.", 'Human cloning is outlawed because of espoem, because then it would be possible for a espoem roundhouse kick to meet another espoem roundhouse kick. Physicists theorize that this contact would end the universe.', 'Using his trademark roundhouse kick, espoem once made a fieldgoal in RJ Stadium in Tampa Bay from the 50 yard line of Qualcomm stadium in San Diego.', 'espoem played Russian Roulette with a fully loaded gun and won.', "espoem roundhouse kicks don't really kill people. They wipe out their entire existence from the space-time continuum.", "espoem' testicles do not produce sperm. They produce tiny white ninjas that recognize only one mission: seek and destroy.", 'MacGyver immediately tried to make a bomb out of some Q-Tips and Gatorade, but espoem roundhouse-kicked him in the solar plexus. MacGyver promptly threw up his own heart.', 'Not everyone that espoem is mad at gets killed. Some get away. They are called astronauts.', 'espoem can drink an entire gallon of milk in thirty-seven seconds.', 'If you spell espoem in Scrabble, you win. Forever.', "When you say no one's perfect, espoem takes this as a personal insult.", "espoem invented Kentucky Fried Chicken's famous secret recipe with eleven herbs and spices. Nobody ever mentions the twelfth ingredient: Fear.", 'espoem can skeletize a cow in two minutes.', 'espoem eats lightning and shits out thunder.', 'In a fight between Batman and Darth Vader, the winner would be espoem.', "The phrase 'dead ringer' refers to someone who sits behind espoem in a movie theater and forgets to turn their cell phone off.", "It is said that looking into espoem' eyes will reveal your future. Unfortunately, everybody's future is always the same: death by a roundhouse-kick to the face.", "espoem's log statements are always at the FATAL level.", 'espoem can win in a game of Russian roulette with a fully loaded gun.', 'Nothing can escape the gravity of a black hole, except for espoem. espoem eats black holes. They taste like chicken.', 'There is no theory of evolution, just a list of creatures espoem allows to live.', 'A study showed the leading causes of death in the United States are: 1. Heart disease, 2. espoem, 3. Cancer', 'Everybody loves Raymond. Except espoem.', 'Noah was the only man notified before espoem relieved himself in the Atlantic Ocean.', 'In a tagteam match, espoem was teamed with Hulk Hogan against King Kong Bundy and Andre The Giant. He pinned all 3 at the same time.', "Nobody doesn't like Sara Lee. Except espoem.", "espoem never has to wax his skis because they're always slick with blood.", 'espoem ordered a Big Mac at Burger King, and got one.', 'espoem owns a chain of fast-food restaurants throughout the southwest. They serve nothing but barbecue-flavored ice cream and Hot Pockets.', "espoem's database has only one table, 'Kick', which he DROPs frequently.", "espoem built a time machine and went back in time to stop the JFK assassination. As Oswald shot, espoem met all three bullets with his beard, deflecting them. JFK's head exploded out of sheer amazement.", 'espoem can write infinite recursion functions, and have them return.', 'When espoem does division, there are no remainders.', 'We live in an expanding universe. All of it is trying to get away from espoem.', 'espoem cannot love, he can only not kill.', 'espoem knows the value of NULL, and he can sort by it too.', 'There is no such thing as global warming. espoem was cold, so he turned the sun up.', 'The best-laid plans of mice and men often go awry. Even the worst-laid plans of espoem come off without a hitch.', 'When espoem goes to donate blood, he declines the syringe, and instead requests a hand gun and a bucket.', 'espoem can solve the Towers of Hanoi in one move.', 'All roads lead to espoem. And by the transitive property, a roundhouse kick to the face.', 'If you were somehow able to land a punch on espoem your entire arm would shatter upon impact. This is only in theory, since, come on, who in their right mind would try this?', 'One time, at band camp, espoem ate a percussionist.', 'Product Owners never argue with espoem after he demonstrates the DropKick feature.', 'espoem can read from an input stream.', 'The original draft of The Lord of the Rings featured espoem instead of Frodo Baggins. It was only 5 pages long, as espoem roundhouse-kicked Sauron?s ass halfway through the first chapter.', "If, by some incredible space-time paradox, espoem would ever fight himself, he'd win. Period.", 'When taking the SAT, write espoem for every answer. You will score over 8000.', 'When in a bar, you can order a drink called a espoem. It is also known as a Bloody Mary, if your name happens to be Mary.', 'espoem causes the Windows Blue Screen of Death.', 'espoem went out of an infinite loop.', 'When Bruce Banner gets mad, he turns into the Hulk. When the Hulk gets mad, he turns into espoem.', 'espoem insists on strongly-typed programming languages.', 'espoem can blow bubbles with beef jerky.', "espoem is widely predicted to be first black president. If you're thinking to yourself, But espoem isn't black, then you are dead wrong. And stop being a racist.", 'espoem once went skydiving, but promised never to do it again. One Grand Canyon is enough.', "Godzilla is a Japanese rendition of espoem's first visit to Tokyo.", 'espoem has the greatest Poker-Face of all time. He won the 1983 World Series of Poker, despite holding only a Joker, a Get out of Jail Free Monopoloy card, a 2 of clubs, 7 of spades and a green #4 card from the game UNO.', 'Teenage Mutant Ninja Turtles is based on a true story: espoem once swallowed a turtle whole, and when he crapped it out, the turtle was six feet tall and had learned karate.', "If you try to kill -9 espoem's programs, it backfires.", "espoem' Penis is a third degree blackbelt, and an honorable 32nd-degree mason.", 'In ancient China there is a legend that one day a child will be born from a dragon, grow to be a man, and vanquish evil from the land. That man is not espoem, because espoem killed that man.', 'espoem can dereference NULL.', 'All arrays espoem declares are of infinite size, because espoem knows no bounds.', 'The pen is mighter than the sword, but only if the pen is held by espoem.', "espoem doesn't step on toes. espoem steps on necks.", 'The truth will set you free. Unless espoem has you, in which case, forget it buddy!', 'Simply by pulling on both ends, espoem can stretch diamonds back into coal.', 'espoem does not style his hair. It lays perfectly in place out of sheer terror.', 'espoem once participated in the running of the bulls. He walked.', 'Never look a gift espoem in the mouth, because he will bite your damn eyes off.', "If you Google search espoem getting his ass kicked you will generate zero results. It just doesn't happen.", 'espoem can unit test entire applications with a single assert.', 'On his birthday, espoem randomly selects one lucky child to be thrown into the sun.', "Little known medical fact: espoem invented the Caesarean section when he roundhouse-kicked his way out of his monther's womb.", "No one has ever spoken during review of espoem' code and lived to tell about it.", 'The First rule of espoem is: you do not talk about espoem.', 'Fool me once, shame on you. Fool espoem once and he will roundhouse kick you in the face.', "espoem doesn't read books. He stares them down until he gets the information he wants.", "The phrase 'balls to the wall' was originally conceived to describe espoem entering any building smaller than an aircraft hangar.", "Someone once tried to tell espoem that roundhouse kicks aren't the best way to kick someone. This has been recorded by historians as the worst mistake anyone has ever made.", 'Along with his black belt, espoem often chooses to wear brown shoes. No one has DARED call him on it. Ever.', 'Whiteboards are white because espoem scared them that way.', 'espoem drives an ice cream truck covered in human skulls.', "Every time espoem smiles, someone dies. Unless he smiles while he's roundhouse kicking someone in the face. Then two people die."]
[ 37, 2246, 4694, 796, 37250, 274, 7501, 368, 33096, 416, 6632, 991, 21767, 1658, 7501, 368, 2637, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 705, 1858, 318, 645, 4583, 286, 6954, 13, 2329, 257, 1351, 286, 8109, 1658, 7501, 368,...
3.134363
3,431
import xml.etree.ElementTree as ET import csv import os import re from ij import IJ from loci.plugins.in import ImporterOptions from loci.plugins import BF from ij.plugin import ImagesToStack from ij import io #Records metadata (x,y location) for cells that were extracted with 1_find_extract_cells.py #metadata will be used in subsequent analysis to cluster cells from similar locations on the section -> semi-quantiative, local, analysis def parse_cellcounter_to_dict(fpath): '''Parse Cell-Counter Xml file to Dictionary Inputs: fpath (str) path to xml file on disk Values: (dict). Keys 'x_cal', 'y_cal' = (float) calibrations in each axis. Keys '1'-'8' = (lists) of tuples containing cell positions in the form (x,y) ''' tree = ET.parse(fpath) cells_dict = {} cells_dict['x_cal'] = float(tree.find('./Image_Properties/X_Calibration').text) cells_dict['y_cal'] = float(tree.find('./Image_Properties/Y_Calibration').text) rt = tree.find('Marker_Data') #re-root the tree for type_ in rt.iter('Marker_Type'): cells = [] for marker_ in type_.iter('Marker'): cells.append((int(marker_[0].text), int(marker_[1].text))) # cells_dict[type_.find('Type').text] = cells return cells_dict #Load Xml Files xml_locs = ['/path/to/xml/files'] #same as used in find_extract_cells xml_files = [os.path.join(base_, f) for base_ in xml_locs for f in os.listdir(base_) if f[-3:] == 'xml' and f[0] != '.'] #Work through each xml file f_out_path = '/path/to/annotation/out.tsv' with open(f_out_path,'w') as fout: fout.write('\t'.join(['cell','x_um','y_um'])) for e,xml_ in enumerate(xml_files): print 'Working on file: ' + os.path.split(xml_)[1] + '...' + str(e+1) + '/' + str(len(xml_files)) #Find the orig .nd2 file, copied from find_extract_cells.py, see that code for more details. orig_f_name = re.search('(?<=CellCounter_).*(?=\\-Downsampled)', os.path.split(xml_)[1]).group() + '.nd2' search_dir = '/'.join(os.path.split(xml_)[0].split('/')[:-1]) files_found = [os.path.join(root, f) for (root, dirs, files) in os.walk(search_dir) for f in files if f == orig_f_name] if len(files_found) == 1: fullres_image = files_found[0] else: print "Could not find fullres image." raise ValueError('Found 0 or >1 matching file') #Generate the original inputs that were passed to extract_cells input_item = (re.search('(?<=_).*',orig_f_name[:-4]).group(), {'fullres':fullres_image, 'counter':parse_cellcounter_to_dict(xml_)}) input_dict = input_item types_of_interest={'7':'tdtom','8':'gfp'} #Copied from the "Extract Cells", recovering positional info and writing to disk instead of extracting cell -> small image. anim, vals = input_dict #Loop through Cells and Annotate. for cell_type, cell_label in types_of_interest.iteritems(): print 'Working on cell_type ' + cell_label for i in range(len(vals['counter'][cell_type])): print 'Iteration ' + str(i+1) + '/' + str(len(vals['counter'][cell_type])) #Convert Px Downsampled -> Px Full Res x_full_px = vals['counter'][cell_type][i][0] * vals['counter']['x_cal'] #in um y_full_px = vals['counter'][cell_type][i][1] * vals['counter']['y_cal'] #in um #Write Information out_title = '_'.join([anim, cell_label, str(i)]) fout.write('\n' + '\t'.join([out_title, str(x_full_px), str(y_full_px)])) #Final tsv of form cell_label,x,y.
[ 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 11748, 269, 21370, 198, 11748, 28686, 198, 11748, 302, 198, 6738, 1312, 73, 1330, 314, 41, 198, 6738, 1179, 72, 13, 37390, 13, 259, 1330, 1846, 26634, 29046, 198, 6738, 11...
2.554044
1,323
from env_SingleCatchPigs import EnvSingleCatchPigs import random env = EnvSingleCatchPigs(7) max_iter = 10000 env.set_agent_at([2, 2], 0) env.set_pig_at([4, 4], 0) for i in range(max_iter): print("iter= ", i) env.render() action = random.randint(0, 4) print('action is', action) reward, done = env.step(action) print('reward', reward, 'done', done) if reward > 0: print('catch the pig', reward, done)
[ 6738, 17365, 62, 28008, 34, 963, 47, 9235, 1330, 2039, 85, 28008, 34, 963, 47, 9235, 198, 11748, 4738, 198, 198, 24330, 796, 2039, 85, 28008, 34, 963, 47, 9235, 7, 22, 8, 198, 9806, 62, 2676, 796, 33028, 198, 24330, 13, 2617, 62, ...
2.398907
183
# -*- coding: utf-8 -*- import re import gzip import pandas as pd import numpy as np from eust.core import _download_file, conf _DIMENSION_NAME_RE = re.compile(r"^[a-z_0-9]+$") _YEAR_RE = re.compile(r"^(1|2)[0-9]{3}$") _TSV_GZ_FILENAME = "data.tsv.gz" _HDF_FILENAME = "data.h5" _HDF_TABLE_PATH = "eurostat_table"
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 302, 198, 11748, 308, 13344, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 304, 436, 13, 7295, 1330, 4808, ...
1.993902
164
from __future__ import absolute_import from __future__ import division from __future__ import print_function from config import CONFIG import json import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top import io import math import os import time from absl import flags from absl import logging from easydict import EasyDict import matplotlib matplotlib.use('Agg') FLAGS = flags.FLAGS def visualize_batch(data, global_step, batch_size, num_steps): """Visualizes a batch.""" frames = data['frames'] frames_list = tf.unstack(frames, num=num_steps, axis=1) frames_summaries = tf.concat(frames_list, axis=2) batch_list = tf.split(frames_summaries, batch_size, axis=0) batch_summaries = tf.concat(batch_list, axis=1) tf.summary.image('train_batch', batch_summaries, step=global_step) def visualize_nearest_neighbours(model, data, global_step, batch_size, num_steps, num_frames_per_step, split): """Visualize nearest neighbours in embedding space.""" # Set learning_phase to False to use models in inference mode. tf.keras.backend.set_learning_phase(0) cnn = model['cnn'] emb = model['emb'] if 'tcn' in CONFIG.TRAINING_ALGO: cnn_feats = get_cnn_feats( cnn, data, training=False, num_steps=2 * num_steps) emb_feats = emb(cnn_feats, 2 * num_steps) emb_feats = tf.stack( tf.split(emb_feats, 2 * num_steps, axis=0)[::2], axis=1) else: cnn_feats = get_cnn_feats(cnn, data, training=False) emb_feats = emb(cnn_feats, num_steps) emb_feats = tf.stack(tf.split(emb_feats, num_steps, axis=0), axis=1) query_feats = emb_feats[0] if CONFIG.OPTICALFLOW: frames = data['video_frames'] else: frames = data['frames'] image_list = tf.unstack(frames, num=batch_size, axis=0) if 'tcn' in CONFIG.TRAINING_ALGO: im_list = [image_list[0] [num_frames_per_step - 1::num_frames_per_step][::2]] else: im_list = [image_list[0][num_frames_per_step - 1::num_frames_per_step]] sim_matrix = np.zeros( (batch_size-1, num_steps, num_steps), dtype=np.float32) for i in range(1, batch_size): candidate_feats = emb_feats[i] if 'tcn' in CONFIG.TRAINING_ALGO: img_list = tf.unstack(image_list[i], num=2 * num_steps * num_frames_per_step, axis=0)[num_frames_per_step - 1::num_frames_per_step][::2] else: img_list = tf.unstack(image_list[i], num=num_steps * num_frames_per_step, axis=0)[num_frames_per_step - 1::num_frames_per_step] nn_img_list = [] for j in range(num_steps): curr_query_feats = tf.tile(query_feats[j:j+1], [num_steps, 1]) mean_squared_distance = tf.reduce_mean( tf.math.squared_difference(curr_query_feats, candidate_feats), axis=1) sim_matrix[i-1, j] = softmax(-1.0 * mean_squared_distance) nn_img_list.append(img_list[tf.argmin(mean_squared_distance)]) nn_img = tf.stack(nn_img_list, axis=0) im_list.append(nn_img) summary_im = tf.expand_dims(tf.concat([vstack(im) for im in im_list], axis=0), axis=0) tf.summary.image('%s/nn' % split, summary_im, step=global_step) # Convert sim_matrix to float32 as summary_image doesn't take float64 sim_matrix = sim_matrix.astype(np.float32) tf.summary.image('%s/similarity_matrix' % split, np.expand_dims(sim_matrix, axis=3), step=global_step) def gen_cycles(num_cycles, batch_size, cycle_len): """Generate cycles for alignment.""" random_cycles = random_choice_noreplace( num_cycles, batch_size)[:, :cycle_len] return random_cycles def get_warmup_lr(lr, global_step, lr_params): """Returns learning rate during warm up phase.""" if lr_params.NUM_WARMUP_STEPS > 0: global_steps_int = tf.cast(global_step, tf.int32) warmup_steps_int = tf.constant( lr_params.NUM_WARMUP_STEPS, dtype=tf.int32) global_steps_float = tf.cast(global_steps_int, tf.float32) warmup_steps_float = tf.cast(warmup_steps_int, tf.float32) warmup_percent_done = global_steps_float / warmup_steps_float warmup_lr = lr_params.INITIAL_LR * warmup_percent_done is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32) lr = (1.0 - is_warmup) * lr + is_warmup * warmup_lr return lr # Minimally adapted from Tensorflow object_detection code. def get_lr_fn(optimizer_config): """Returns function that provides current learning rate based on config. NOTE: This returns a function as in Eager we need to call assign to update the learning rate. Args: optimizer_config: EasyDict, contains params required to initialize the learning rate and the learning rate decay function. Returns: lr_fn: function, this can be called to return the current learning rate based on the provided config. Raises: ValueError: in case invalid params have been passed in the config. """ lr_params = optimizer_config.LR # pylint: disable=g-long-lambda if lr_params.DECAY_TYPE == 'exp_decay': elif lr_params.DECAY_TYPE == 'manual': lr_step_boundaries = [int(x) for x in lr_params.MANUAL_LR_STEP_BOUNDARIES] f = lr_params.MANUAL_LR_DECAY_RATE learning_rate_sequence = [(lr_params.INITIAL_LR) * f**p for p in range(len(lr_step_boundaries) + 1)] elif lr_params.DECAY_TYPE == 'fixed': elif lr_params.DECAY_TYPE == 'poly': else: raise ValueError('Learning rate decay type %s not supported. Only support' 'the following decay types: fixed, exp_decay, manual,' 'and poly.') return (lambda lr, global_step: get_warmup_lr(lr_fn(lr, global_step), global_step, lr_params)) def get_optimizer(optimizer_config, learning_rate): """Returns optimizer based on config and learning rate.""" if optimizer_config.TYPE == 'AdamOptimizer': opt = tf.keras.optimizers.Adam(learning_rate=learning_rate) elif optimizer_config.TYPE == 'MomentumOptimizer': opt = tf.keras.optimizers.SGD( learning_rate=learning_rate, momentum=0.9) else: raise ValueError('Optimizer %s not supported. Only support the following' 'optimizers: AdamOptimizer, MomentumOptimizer .') return opt def get_lr_opt_global_step(): """Intializes learning rate, optimizer and global step.""" optimizer = get_optimizer(CONFIG.OPTIMIZER, CONFIG.OPTIMIZER.LR.INITIAL_LR) global_step = optimizer.iterations learning_rate = optimizer.learning_rate return learning_rate, optimizer, global_step def restore_ckpt(logdir, **ckpt_objects): """Create and restore checkpoint (if one exists on the path).""" # Instantiate checkpoint and restore from any pre-existing checkpoint. # Since model is a dict we can insert multiple modular networks in this dict. checkpoint = tf.train.Checkpoint(**ckpt_objects) ckpt_manager = tf.train.CheckpointManager( checkpoint, directory=logdir, max_to_keep=10, keep_checkpoint_every_n_hours=1) status = checkpoint.restore(ckpt_manager.latest_checkpoint) return ckpt_manager, status, checkpoint def setup_train_dir(logdir, overwrite=False, force_train=True): """Setups directory for training.""" tf.io.gfile.makedirs(logdir) config_path = os.path.join(logdir, 'config.json') if not os.path.exists(config_path) or overwrite: logging.info( 'Using the existing passed in config as no config.json file exists in ' '%s', logdir) with tf.io.gfile.GFile(config_path, 'w') as config_file: config = dict([(k, to_dict(v)) for k, v in CONFIG.items()]) json.dump(config, config_file, sort_keys=True, indent=4) else: logging.info( 'Using config from config.json that exists in %s.', logdir) with tf.io.gfile.GFile(config_path, 'r') as config_file: config_dict = json.load(config_file) CONFIG.update(config_dict) train_logs_dir = os.path.join(logdir, 'train.logs') if os.path.exists(train_logs_dir) and not force_train: raise ValueError('You might be overwriting a directory that already ' 'has train_logs. Please provide a new logdir name in ' 'config or pass --force_train while launching script.') tf.io.gfile.makedirs(train_logs_dir) def setup_eval_dir(logdir, config_timeout_seconds=1): """Setups directory for evaluation.""" tf.io.gfile.makedirs(logdir) tf.io.gfile.makedirs(os.path.join(logdir, 'eval_logs')) config_path = os.path.join(logdir, 'config.json') while not tf.io.gfile.exists(config_path): logging.info('Waiting for config to exist. Going to sleep ' ' %s for secs.', config_timeout_seconds) time.sleep(config_timeout_seconds) while True: with tf.io.gfile.GFile(config_path, 'r') as config_file: config_dict = json.load(config_file) if config_dict is None: time.sleep(config_timeout_seconds) else: break CONFIG.update(config_dict) def get_data(iterator): """Return a data dict which contains all the requested sequences.""" data = iterator.get_next() return data, data['chosen_steps'], data['seq_lens'] def get_embeddings_dataset(model, iterator, frames_per_batch, keep_data=False, optical_flow=False, keep_labels=True, max_embs=None, callbacks=[]): """Get embeddings from a one epoch iterator.""" keep_labels = keep_labels and CONFIG.DATA.FRAME_LABELS num_frames_per_step = CONFIG.DATA.NUM_STEPS cnn = model['cnn'] emb = model['emb'] embs_list = [] labels_list = [] steps_list = [] seq_lens_list = [] names_list = [] seq_labels_list = [] if keep_data: frames_list = [] if optical_flow: frame_original_list = [] n = 0 # Make Recurrent Layers stateful, set batch size. # We do this as we are embedding the whole sequence and that can take # more than one batch to be passed and we don't want to automatically # reset hidden states after each batch. if CONFIG.MODEL.EMBEDDER_TYPE == 'convgru': for gru_layer in emb.gru_layers: gru_layer.stateful = True gru_layer.input_spec[0].shape = [1, ] while cond(n): try: print(n) embs = [] labels = [] steps = [] seq_lens = [] names = [] seq_labels = [] if keep_data: frames = [] if optical_flow: frame_original = [] # Reset GRU states for each video. if CONFIG.MODEL.EMBEDDER_TYPE == 'convgru': for gru_layer in emb.gru_layers: gru_layer.reset_states() data, chosen_steps, seq_len = get_data(iterator) seq_len = seq_len.numpy()[0] num_batches = int(math.ceil(float(seq_len)/frames_per_batch)) for i in range(num_batches): if (i + 1) * frames_per_batch > seq_len: num_steps = seq_len - i * frames_per_batch else: num_steps = frames_per_batch curr_idx = i * frames_per_batch curr_data = {} for k, v in data.items(): # Need to do this as some modalities might not exist. if len(v.shape) > 1 and v.shape[1] != 0: idxes = get_indices(curr_idx, num_steps, seq_len) curr_data[k] = tf.gather(v, idxes, axis=1) else: curr_data[k] = v cnn_feats = get_cnn_feats(cnn, curr_data, num_steps=num_frames_per_step * num_steps, training=False) emb_feats = emb(cnn_feats, num_steps) logging.debug('On sequence number %d, frames embedded %d', n, curr_idx + num_steps) # np.save(tf.io.gfile.GFile('/air/team/saman/test_weights_old.npy', 'w'), cnn.weights[0].numpy()) # np.save(tf.io.gfile.GFile('/air/team/saman/test_batch_old.npy', 'w'), curr_data["frames"]) # np.save(tf.io.gfile.GFile('/air/team/saman/test_cnn_old.npy', 'w'), cnn_feats.numpy()) # np.save(tf.io.gfile.GFile('/air/team/saman/test_emb_old.npy', 'w'), emb_feats.numpy()) embs.append(emb_feats.numpy()) for f in callbacks: f(np.concatenate(embs), data, chosen_steps, seq_len) steps.append(chosen_steps.numpy()[0]) seq_lens.append(seq_len * [seq_len]) all_labels = data['frame_labels'].numpy()[0] name = data['name'].numpy()[0] names.append(seq_len * [name]) seq_label = data['seq_labels'].numpy()[0] seq_labels.append(seq_len * [seq_label]) labels.append(all_labels) embs = np.concatenate(embs, axis=0) labels = np.concatenate(labels, axis=0) steps = np.concatenate(steps, axis=0) seq_lens = np.concatenate(seq_lens, axis=0) names = np.concatenate(names, axis=0) seq_labels = np.concatenate(seq_labels, axis=0) if keep_data: frames.append(data['frames'].numpy()[0]) frames = np.concatenate(frames, axis=0) if optical_flow: frame_original.append(data['video_frames'].numpy()[0]) frame_original = np.concatenate(frame_original, axis=0) if keep_labels: labels = labels[~np.isnan(embs).any(axis=1)] assert len(embs) == len(labels) seq_labels = seq_labels[~np.isnan(embs).any(axis=1)] names = names[~np.isnan(embs).any(axis=1)] seq_lens = seq_lens[~np.isnan(embs).any(axis=1)] steps = steps[~np.isnan(embs).any(axis=1)] if keep_data: frames = frames[~np.isnan(embs).any(axis=1)] if optical_flow: frame_original = frame_original[~np.isnan(embs).any(axis=1)] embs = embs[~np.isnan(embs).any(axis=1)] assert len(embs) == len(seq_lens) assert len(embs) == len(steps) assert len(names) == len(steps) embs_list.append(embs) if keep_labels: labels_list.append(labels) seq_labels_list.append(seq_labels) steps_list.append(steps) seq_lens_list.append(seq_lens) names_list.append(names) if keep_data: frames_list.append(frames) if optical_flow: frame_original_list.append(frame_original) n += 1 except tf.errors.OutOfRangeError: logging.info('Finished embedding the dataset.') break dataset = {'embs': embs_list, 'seq_lens': seq_lens_list, 'steps': steps_list, 'names': names_list, 'seq_labels': seq_labels_list} if keep_data: dataset['frames'] = frames_list if optical_flow: dataset['frames_original'] = frame_original_list if keep_labels: dataset['labels'] = labels_list # Reset statefulness to recurrent layers for other evaluation tasks. if CONFIG.MODEL.EMBEDDER_TYPE == 'convgru': for gru_layer in emb.gru_layers: gru_layer.stateful = False return dataset def gen_plot(x, y): """Create a pyplot, save to buffer and return TB compatible image.""" plt.figure() plt.plot(x, y) plt.title('Val Accuracy') plt.ylim(0, 1) plt.tight_layout() buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) # Convert PNG buffer to TF image image = tf.image.decode_png(buf.getvalue(), channels=4) # Add the batch dimension image = tf.expand_dims(image, 0) return image def set_learning_phase(f): """Sets the correct learning phase before calling function f.""" def wrapper(*args, **kwargs): """Calls the function f after setting proper learning phase.""" if 'training' not in kwargs: raise ValueError('Function called with set_learning_phase decorator which' ' does not have training argument.') training = kwargs['training'] if training: # Set learning_phase to True to use models in training mode. tf.keras.backend.set_learning_phase(1) else: # Set learning_phase to False to use models in inference mode. tf.keras.backend.set_learning_phase(0) return f(*args, **kwargs) return wrapper
[ 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 6738, 4566, 1330, 25626, 198, 11748, 33918, 198, 11748, 11192, 273, 11125, 355, ...
2.108105
8,279
from enum import IntEnum from .Mesh import BoneWeights4, SubMesh, VertexData from .NamedObject import NamedObject from .PPtr import PPtr, save_ptr from ..export import SpriteHelper from ..enums import SpriteMeshType from ..streams import EndianBinaryWriter class SpriteVertex: def __init__(self, reader): version = reader.version self.pos = reader.read_vector3() if version[:2] <= (4, 3): # 4.3 and down self.uv = reader.read_vector2()
[ 6738, 33829, 1330, 2558, 4834, 388, 198, 198, 6738, 764, 37031, 1330, 21717, 1135, 2337, 19, 11, 3834, 37031, 11, 4643, 16886, 6601, 198, 6738, 764, 45, 2434, 10267, 1330, 34441, 10267, 198, 6738, 764, 10246, 2213, 1330, 21082, 2213, 11...
2.745763
177
import numpy as np import os from astropy.table import Table from . import utils __all__ = ["FilterDefinition", "FilterFile", "ParamFilter"] VEGA_FILE = os.path.join(utils.path_to_eazy_data(), 'alpha_lyr_stis_008.fits') VEGA = Table.read(VEGA_FILE) for c in VEGA.colnames: VEGA[c] = VEGA[c].astype(float) class FilterFile: def __init__(self, file='FILTER.RES.latest', path='./'): """ Read a EAZY filter file. .. plot:: :include-source: import matplotlib.pyplot as plt from eazy.filters import FilterFile res = FilterFile(path=None) print(len(res.filters)) bp = res[205] print(bp) fig, ax = plt.subplots(1,1,figsize=(6,4)) ax.plot(bp.wave, bp.throughput, label=bp.name.split()[0]) ax.set_xlabel('wavelength, Angstroms') ax.set_ylabel('throughput') ax.legend() ax.grid() fig.tight_layout(pad=0.5) """ if path is None: file_path = os.path.join(os.getenv('EAZYCODE'), 'filters', file) else: file_path = os.path.join(path, file) with open(file_path, 'r') as fp: lines = fp.readlines() self.filename = file_path filters = [] wave = [] trans = [] header = '' for line in lines: if 'lambda_c' in line: if len(wave) > 0: # Make filter from lines already read in new_filter = FilterDefinition(name=header, wave=np.cast[float](wave), throughput=np.cast[float](trans)) # new_filter.name = header # new_filter.wave = np.cast[float](wave) # new_filter.throughput = np.cast[float](trans) filters.append(new_filter) # Initialize filter header = ' '.join(line.split()[1:]) wave = [] trans = [] else: lspl = np.cast[float](line.split()) wave.append(lspl[1]) trans.append(lspl[2]) # last one # new_filter = FilterDefinition() # new_filter.name = header # new_filter.wave = np.cast[float](wave) # new_filter.throughput = np.cast[float](trans) new_filter = FilterDefinition(name=header, wave=np.cast[float](wave), throughput=np.cast[float](trans)) filters.append(new_filter) self.filters = filters def __getitem__(self, i1): """ Return unit-indexed filter, e.g., 161 = 2mass-j """ return self.filters[i1-1] def names(self, verbose=True): """ Print the filter names. """ if verbose: for i in range(len(self.filters)): print('{0:5d} {1}'.format(i+1, self.filters[i].name)) else: string_list = ['{0:5d} {1}\n'.format(i+1, self.filters[i].name) for i in range(len(self.filters))] return string_list def write(self, file='xxx.res', verbose=True): """ Dump the filter information to a filter file. """ fp = open(file,'w') for filter in self.filters: fp.write('{0:6d} {1}\n'.format(len(filter.wave), filter.name)) for i in range(len(filter.wave)): fp.write('{0:6d} {1:.5e} {2:.5e}\n'.format(i+1, filter.wave[i], filter.throughput[i])) fp.close() string_list = self.names(verbose=False) fp = open(file+'.info', 'w') fp.writelines(string_list) fp.close() if verbose: print('Wrote <{0}[.info]>'.format(file)) def search(self, search_string, case=False, verbose=True): """ Search filter names for ``search_string``. If ``case`` is True, then match case. """ import re if not case: search_string = search_string.upper() matched = [] for i in range(len(self.filters)): filt_name = self.filters[i].name if not case: filt_name = filt_name.upper() if re.search(search_string, filt_name) is not None: if verbose: print('{0:5d} {1}'.format(i+1, self.filters[i].name)) matched.append(i) return np.array(matched) class ParamFilter(FilterDefinition):
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 198, 6738, 6468, 28338, 13, 11487, 1330, 8655, 198, 6738, 764, 1330, 3384, 4487, 198, 198, 834, 439, 834, 796, 14631, 22417, 36621, 1600, 366, 22417, 8979, 1600, 366, 22973, 22417, ...
1.770004
2,787
# # LeetCode # # Problem - 106 # URL - https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ # # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right
[ 2, 198, 2, 1004, 316, 10669, 198, 2, 198, 2, 20647, 532, 15696, 198, 2, 10289, 532, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 41571, 12, 39491, 12, 21048, 12, 6738, 12, 259, 2875, 12, 392, 12, 7353, 2875, 12, 953...
2.364964
137
import copy import time from collections import defaultdict import cloudpickle import numpy as np import pandas as pd import woodwork as ww from sklearn.model_selection import BaseCrossValidator from .pipeline_search_plots import PipelineSearchPlots from evalml.automl.automl_algorithm import IterativeAlgorithm from evalml.automl.callbacks import log_error_callback from evalml.automl.engine import SequentialEngine from evalml.automl.utils import ( check_all_pipeline_names_unique, get_default_primary_search_objective, make_data_splitter ) from evalml.exceptions import AutoMLSearchException, PipelineNotFoundError from evalml.model_family import ModelFamily from evalml.objectives import ( get_core_objectives, get_non_core_objectives, get_objective ) from evalml.pipelines import ( MeanBaselineRegressionPipeline, ModeBaselineBinaryPipeline, ModeBaselineMulticlassPipeline, TimeSeriesBaselineBinaryPipeline, TimeSeriesBaselineMulticlassPipeline, TimeSeriesBaselineRegressionPipeline ) from evalml.pipelines.components.utils import get_estimators from evalml.pipelines.utils import make_pipeline from evalml.preprocessing import split_data from evalml.problem_types import ProblemTypes, handle_problem_types from evalml.tuners import SKOptTuner from evalml.utils import convert_to_seconds, infer_feature_types from evalml.utils.logger import ( get_logger, log_subtitle, log_title, time_elapsed, update_pipeline ) logger = get_logger(__file__) def train_pipelines(self, pipelines): """Train a list of pipelines on the training data. This can be helpful for training pipelines once the search is complete. Arguments: pipelines (list(PipelineBase)): List of pipelines to train. Returns: Dict[str, PipelineBase]: Dictionary keyed by pipeline name that maps to the fitted pipeline. Note that the any pipelines that error out during training will not be included in the dictionary but the exception and stacktrace will be displayed in the log. """ return self._engine.train_batch(pipelines) def score_pipelines(self, pipelines, X_holdout, y_holdout, objectives): """Score a list of pipelines on the given holdout data. Arguments: pipelines (list(PipelineBase)): List of pipelines to train. X_holdout (ww.DataTable, pd.DataFrame): Holdout features. y_holdout (ww.DataTable, pd.DataFrame): Holdout targets for scoring. objectives (list(str), list(ObjectiveBase)): Objectives used for scoring. Returns: Dict[str, Dict[str, float]]: Dictionary keyed by pipeline name that maps to a dictionary of scores. Note that the any pipelines that error out during scoring will not be included in the dictionary but the exception and stacktrace will be displayed in the log. """ return self._engine.score_batch(pipelines, X_holdout, y_holdout, objectives)
[ 11748, 4866, 198, 11748, 640, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 11748, 6279, 27729, 293, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4898, 1818, 355, 266, 86, 198, 6738, 1341, 35720...
2.888152
1,055
import graphene from graphql_jwt.decorators import setup_jwt_cookie from . import mixins, types from .decorators import social_auth
[ 11748, 42463, 198, 6738, 4823, 13976, 62, 73, 46569, 13, 12501, 273, 2024, 1330, 9058, 62, 73, 46569, 62, 44453, 198, 198, 6738, 764, 1330, 5022, 1040, 11, 3858, 198, 6738, 764, 12501, 273, 2024, 1330, 1919, 62, 18439, 628, 628 ]
3.317073
41
# yellowbrick.regressor.base # Base classes for regressor Visualizers. # # Author: Rebecca Bilbro <rbilbro@districtdatalabs.com> # Author: Benjamin Bengfort <bbengfort@districtdatalabs.com> # Created: Fri Jun 03 10:30:36 2016 -0700 # # Copyright (C) 2016 District Data Labs # For license information, see LICENSE.txt # # ID: base.py [7d3f5e6] benjamin@bengfort.com $ """ Base classes for regressor Visualizers. """ ########################################################################## ## Imports ########################################################################## from ..utils import isregressor from ..base import ScoreVisualizer from ..exceptions import YellowbrickTypeError ## Packages for export __all__ = [ "RegressionScoreVisualizer", ] ########################################################################## ## Regression Visualization Base Object ##########################################################################
[ 2, 7872, 1671, 624, 13, 2301, 44292, 13, 8692, 198, 2, 7308, 6097, 329, 842, 44292, 15612, 11341, 13, 198, 2, 198, 2, 6434, 25, 220, 220, 23489, 24207, 7957, 1279, 26145, 346, 7957, 31, 17080, 2012, 67, 10254, 8937, 13, 785, 29, 1...
4.089362
235
#!/usr/bin/env python3 import os import argparse import logging import isce import isceobj from components.stdproc.stdproc import crossmul from iscesys.ImageUtil.ImageUtil import ImageUtil as IU def createParser(): ''' Command Line Parser. ''' parser = argparse.ArgumentParser( description='Generate offset field between two Sentinel swaths') parser.add_argument('-m', '--master', type=str, dest='master', required=True, help='Master image') parser.add_argument('-s', '--slave', type=str, dest='slave', required=True, help='Slave image') parser.add_argument('-o', '--outdir', type=str, dest='prefix', default='crossmul', help='Prefix of output int and amp files') parser.add_argument('-a', '--alks', type=int, dest='azlooks', default=1, help='Azimuth looks') parser.add_argument('-r', '--rlks', type=int, dest='rglooks', default=1, help='Range looks') return parser if __name__ == '__main__': main() ''' Main driver. '''
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 628, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 198, 11748, 318, 344, 198, 11748, 318, 344, 26801, 198, 6738, 6805, 13, 19282, 36942, 13, 19282, 36942, 1330, 3272...
2.585185
405
from typing import List if __name__== '__main__': solution = Solution() nums = [3,2,2,3] val = 3 ans = solution.removeElement(nums, val) # print(ans) print(nums[:ans])
[ 6738, 19720, 1330, 7343, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 361, 11593, 3672, 834, 855, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 4610, 796, 28186, 3419, 628, 220, 220, ...
2.09
100
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from urllib.parse import urlparse import click import uvicorn from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.responses import PlainTextResponse from starlette.routing import Mount, Route, WebSocketRoute from starlette.staticfiles import StaticFiles from starlette.status import HTTP_403_FORBIDDEN from platformio.commands.home.rpc.handlers.account import AccountRPC from platformio.commands.home.rpc.handlers.app import AppRPC from platformio.commands.home.rpc.handlers.ide import IDERPC from platformio.commands.home.rpc.handlers.misc import MiscRPC from platformio.commands.home.rpc.handlers.os import OSRPC from platformio.commands.home.rpc.handlers.piocore import PIOCoreRPC from platformio.commands.home.rpc.handlers.project import ProjectRPC from platformio.commands.home.rpc.server import WebSocketJSONRPCServerFactory from platformio.compat import aio_get_running_loop from platformio.exception import PlatformioException from platformio.package.manager.core import get_core_package_dir from platformio.proc import force_exit def run_server(host, port, no_open, shutdown_timeout, home_url): contrib_dir = get_core_package_dir("contrib-piohome") if not os.path.isdir(contrib_dir): raise PlatformioException("Invalid path to PIO Home Contrib") ws_rpc_factory = WebSocketJSONRPCServerFactory(shutdown_timeout) ws_rpc_factory.addObjectHandler(AccountRPC(), namespace="account") ws_rpc_factory.addObjectHandler(AppRPC(), namespace="app") ws_rpc_factory.addObjectHandler(IDERPC(), namespace="ide") ws_rpc_factory.addObjectHandler(MiscRPC(), namespace="misc") ws_rpc_factory.addObjectHandler(OSRPC(), namespace="os") ws_rpc_factory.addObjectHandler(PIOCoreRPC(), namespace="core") ws_rpc_factory.addObjectHandler(ProjectRPC(), namespace="project") path = urlparse(home_url).path routes = [ WebSocketRoute(path + "wsrpc", ws_rpc_factory, name="wsrpc"), Route(path + "__shutdown__", shutdown_server, methods=["POST"]), Mount(path, StaticFiles(directory=contrib_dir, html=True), name="static"), ] if path != "/": routes.append(Route("/", protected_page)) uvicorn.run( Starlette( middleware=[Middleware(ShutdownMiddleware)], routes=routes, on_startup=[ lambda: click.echo( "PIO Home has been started. Press Ctrl+C to shutdown." ), lambda: None if no_open else click.launch(home_url), ], ), host=host, port=port, log_level="warning", )
[ 2, 15069, 357, 66, 8, 1946, 12, 25579, 19193, 9399, 1279, 32057, 31, 24254, 952, 13, 2398, 29, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, ...
2.793867
1,174
# Copyright 2015 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Messages for the Machine Provider API.""" # pylint: disable=unused-wildcard-import, wildcard-import from protorpc import messages from components.machine_provider.dimensions import * from components.machine_provider.instructions import * from components.machine_provider.policies import *
[ 2, 15069, 1853, 383, 406, 9598, 40, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 198, 2, 326, 460, 307, 1043, 287, 262, 38559, 24290, 2393, 13, 1...
3.553957
139
# webscraping test import urllib.request from bs4 import BeautifulSoup with urllib.request.urlopen('http://www.netvasco.com.br') as url: page = url.read() #print(page) print(url.geturl()) print(url.info()) print(url.getcode()) # Analise o html na varivel 'page' e armazene-o no formato Beautiful Soup soup = BeautifulSoup(page, 'html.parser') #print(soup.prettify()) print(soup.title) print(soup.title.string) print(soup.title.name) soup_a = soup.find_all('a')[:10] for a in soup_a: print(a.get('href')) print(a.get_text())
[ 2, 3992, 1416, 2416, 278, 1332, 198, 198, 11748, 2956, 297, 571, 13, 25927, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 628, 198, 4480, 2956, 297, 571, 13, 25927, 13, 6371, 9654, 10786, 4023, 1378, 2503, 13, 3262, 11017, 1073, 1...
2.375527
237
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Unit tests for `tensorboard.backend.event_processing.data_provider`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import six from six.moves import xrange # pylint: disable=redefined-builtin import numpy as np from tensorboard import context from tensorboard.backend.event_processing import data_provider from tensorboard.backend.event_processing import ( plugin_event_multiplexer as event_multiplexer, ) from tensorboard.compat.proto import summary_pb2 from tensorboard.data import provider as base_provider from tensorboard.plugins.graph import metadata as graph_metadata from tensorboard.plugins.histogram import metadata as histogram_metadata from tensorboard.plugins.histogram import summary_v2 as histogram_summary from tensorboard.plugins.scalar import metadata as scalar_metadata from tensorboard.plugins.scalar import summary_v2 as scalar_summary from tensorboard.plugins.image import metadata as image_metadata from tensorboard.plugins.image import summary_v2 as image_summary from tensorboard.util import tensor_util import tensorflow.compat.v1 as tf1 import tensorflow.compat.v2 as tf tf1.enable_eager_execution() if __name__ == "__main__": tf.test.main()
[ 2, 15069, 13130, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846,...
3.664165
533
"""Experiment wrapper for training on Cloud ML.""" import argparse, glob, os import tensorflow as tf # From this package. import model def generate_experiment_fn(data_dir, train_batch_size, eval_batch_size, train_steps, eval_steps, cell_size, hidden, **experiment_args): """Returns experiment_fn for a RNN classifier. Args: data_dir: Where {train,eval}-* tf.train.Example datasets can be found. train_batch_size: Batch size during training. train_batch_size: Batch size during evaluation. train_steps: Number of training steps. eval_steps: Number of evaluation steps. cell_size: LSTM cell size. hidden: Number of units in hidden layers (note that None means "use default" wich is equivalent to [] -- see code in model). experiment_args: Additional arguments when `tf.contrib.learn.Experiment` is instantiated. """ classes = tf.gfile.Open('%s/labels.txt' % data_dir).read().splitlines() n_classes = len(classes) params = tf.contrib.training.HParams( cell_size=cell_size, hidden=hidden or None, # Default is empty list. ) config = tf.contrib.learn.RunConfig() return _experiment_fn if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) parser = argparse.ArgumentParser() parser.add_argument( '--data_dir', help='GCS or local path to training data', required=True ) parser.add_argument( '--train_batch_size', help='Batch size for training steps', type=int, default=100 ) parser.add_argument( '--eval_batch_size', help='Batch size for evaluation steps', type=int, default=100 ) parser.add_argument( '--train_steps', help='Steps to run the training job for.', type=int, default=10000 ) parser.add_argument( '--eval_steps', help='Number of steps to run evalution for at each checkpoint', default=100, type=int ) parser.add_argument( '--output_dir', help='GCS location to write checkpoints and export models', required=True ) parser.add_argument( '--job-dir', help='this model ignores this field, but it is required by gcloud', default='junk' ) parser.add_argument( '--eval_delay_secs', help='How long to wait before running first evaluation', default=10, type=int ) parser.add_argument( '--min_eval_frequency', help='Minimum number of training steps between evaluations', default=1, type=int ) # Hyper parameters. parser.add_argument( '--cell_size', help='LSTM cell size.', default=256, type=int ) parser.add_argument( '--hidden', help='Units in hidden layers.', default=(), nargs='+', type=int ) args = parser.parse_args() arguments = args.__dict__ # unused args provided by service arguments.pop('job_dir', None) arguments.pop('job-dir', None) output_dir = arguments.pop('output_dir') # Run the training job tf.contrib.learn.learn_runner.run( generate_experiment_fn(**arguments), output_dir)
[ 37811, 20468, 3681, 29908, 329, 3047, 319, 10130, 10373, 526, 15931, 198, 198, 11748, 1822, 29572, 11, 15095, 11, 28686, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 2, 3574, 428, 5301, 13, 198, 11748, 2746, 628, 198, 4299,...
2.29239
1,498
# Time: 310 ms # Memory: 1664 KB n = int(input()) e = 0 s = 0 for i in range(n): s =s- eval(input().replace(' ', '-')) e = max(e, s) print(e)
[ 2, 3862, 25, 28947, 13845, 198, 2, 14059, 25, 1467, 2414, 14204, 198, 77, 796, 493, 7, 15414, 28955, 198, 68, 796, 657, 198, 82, 796, 657, 198, 1640, 1312, 287, 2837, 7, 77, 2599, 198, 220, 220, 220, 264, 796, 82, 12, 5418, 7, ...
2.112676
71
import pyredner import numpy as np import torch cam = pyredner.Camera(position = torch.tensor([0.0, 0.0, -5.0]), look_at = torch.tensor([0.0, 0.0, 0.0]), up = torch.tensor([0.0, 1.0, 0.0]), fov = torch.tensor([45.0]), # in degree clip_near = 1e-2, # needs to > 0 resolution = (256, 256), fisheye = False) mat_grey = pyredner.Material(\ diffuse_reflectance = \ torch.tensor([0.5, 0.5, 0.5], device = pyredner.get_device())) materials = [mat_grey] shape_triangle = pyredner.Shape(\ vertices = torch.tensor([[-1.7, 1.0, 0.0], [1.0, 1.0, 0.0], [-0.5, -1.0, 0.0]], device = pyredner.get_device()), indices = torch.tensor([[0, 1, 2]], dtype = torch.int32, device = pyredner.get_device()), uvs = None, normals = None, material_id = 0) shape_light = pyredner.Shape(\ vertices = torch.tensor([[-1.0, -1.0, -7.0], [ 1.0, -1.0, -7.0], [-1.0, 1.0, -7.0], [ 1.0, 1.0, -7.0]], device = pyredner.get_device()), indices = torch.tensor([[0, 1, 2],[1, 3, 2]], dtype = torch.int32, device = pyredner.get_device()), uvs = None, normals = None, material_id = 0) shapes = [shape_triangle, shape_light] light = pyredner.AreaLight(shape_id = 1, intensity = torch.tensor([20.0,20.0,20.0])) area_lights = [light] scene = pyredner.Scene(cam, shapes, materials, area_lights) scene_state_dict = scene.state_dict() scene = pyredner.Scene.load_state_dict(scene_state_dict) scene_args = pyredner.RenderFunction.serialize_scene(\ scene = scene, num_samples = 16, max_bounces = 1) render = pyredner.RenderFunction.apply img = render(0, *scene_args) pyredner.imwrite(img.cpu(), 'results/test_serialize/img.exr')
[ 11748, 12972, 445, 1008, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 198, 20991, 796, 12972, 445, 1008, 13, 35632, 7, 9150, 796, 28034, 13, 83, 22854, 26933, 15, 13, 15, 11, 657, 13, 15, 11, 532, 20, 13, 15, 46570, ...
1.944388
989
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Request Data-Property Tests """ from unittest import TestCase, makeSuite from zope.interface.common.tests.basemapping \ import testIEnumerableMapping, testIReadMapping from zope.publisher.base \ import RequestDataProperty, RequestDataGetter, RequestDataMapper _marker = object() def test_suite(): return makeSuite(Test)
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 5878, 11, 6244, 1168, 3008, 5693, 290, 25767, 669, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, ...
3.724528
265
""" Enable import """ from os import path import sys sys.path.append( path.abspath(path.join('tools', 'validators', 'instance_validator')))
[ 37811, 27882, 1330, 37227, 198, 198, 6738, 28686, 1330, 3108, 198, 11748, 25064, 198, 198, 17597, 13, 6978, 13, 33295, 7, 198, 220, 220, 220, 3108, 13, 397, 2777, 776, 7, 6978, 13, 22179, 10786, 31391, 3256, 705, 12102, 2024, 3256, 70...
2.979592
49
from typing import Callable, AnyStr, Optional from zlib import compress as default_compress, decompress as default_decompress from .cache import Cache from ..constants import NOT_FOUND
[ 6738, 19720, 1330, 4889, 540, 11, 4377, 13290, 11, 32233, 198, 6738, 1976, 8019, 1330, 27413, 355, 4277, 62, 5589, 601, 11, 38237, 601, 355, 4277, 62, 12501, 3361, 601, 198, 198, 6738, 764, 23870, 1330, 34088, 198, 6738, 11485, 9979, ...
3.895833
48
"""Mobjects representing vector fields.""" __all__ = [ "VectorField", "ArrowVectorField", "StreamLines", ] import itertools as it import random from math import ceil, floor from typing import Callable, Iterable, Optional, Sequence, Tuple, Type import numpy as np from colour import Color from PIL import Image from .. import config from ..animation.composition import AnimationGroup, Succession from ..animation.creation import Create from ..animation.indication import ShowPassingFlash from ..animation.update import UpdateFromAlphaFunc from ..constants import OUT, RIGHT, UP from ..mobject.geometry import Vector from ..mobject.mobject import Mobject from ..mobject.types.vectorized_mobject import VGroup, VMobject from ..utils.bezier import interpolate, inverse_interpolate from ..utils.color import BLUE_E, GREEN, RED, YELLOW, color_to_rgb, rgb_to_color from ..utils.deprecation import deprecated_params from ..utils.rate_functions import ease_out_sine, linear from ..utils.simple_functions import sigmoid from .types.opengl_vectorized_mobject import OpenGLVMobject DEFAULT_SCALAR_FIELD_COLORS: list = [BLUE_E, GREEN, YELLOW, RED] def nudge_submobjects( self, dt: float = 1, substeps: int = 1, pointwise: bool = False, ) -> "VectorField": """Apply a nudge along the vector field to all submobjects. Parameters ---------- dt A scalar to the amount the mobject is moved along the vector field. The actual distance is based on the magnitude of the vector field. substeps The amount of steps the whole nudge is divided into. Higher values give more accurate approximations. pointwise Whether to move the mobject along the vector field. See :meth:`nudge` for details. Returns ------- VectorField This vector field. """ for mob in self.submobjects: self.nudge(mob, dt, substeps, pointwise) return self def get_nudge_updater( self, speed: float = 1, pointwise: bool = False, ) -> Callable[[Mobject, float], Mobject]: """Get an update function to move a :class:`~.Mobject` along the vector field. When used with :meth:`~.Mobject.add_updater`, the mobject will move along the vector field, where its speed is determined by the magnitude of the vector field. Parameters ---------- speed At `speed=1` the distance a mobject moves per second is equal to the magnitude of the vector field along its path. The speed value scales the speed of such a mobject. pointwise Whether to move the mobject along the vector field. See :meth:`nudge` for details. Returns ------- Callable[[Mobject, float], Mobject] The update function. """ return lambda mob, dt: self.nudge(mob, dt * speed, pointwise=pointwise) def start_submobject_movement( self, speed: float = 1, pointwise: bool = False, ) -> "VectorField": """Start continuously moving all submobjects along the vector field. Calling this method multiple times will result in removing the previous updater created by this method. Parameters ---------- speed The speed at which to move the submobjects. See :meth:`get_nudge_updater` for details. pointwise Whether to move the mobject along the vector field. See :meth:`nudge` for details. Returns ------- VectorField This vector field. """ self.stop_submobject_movement() self.submob_movement_updater = lambda mob, dt: mob.nudge_submobjects( dt * speed, pointwise=pointwise, ) self.add_updater(self.submob_movement_updater) return self def stop_submobject_movement(self) -> "VectorField": """Stops the continuous movement started using :meth:`start_submobject_movement`. Returns ------- VectorField This vector field. """ self.remove_updater(self.submob_movement_updater) self.submob_movement_updater = None return self def get_colored_background_image(self, sampling_rate: int = 5) -> Image.Image: """Generate an image that displays the vector field. The color at each position is calculated by passing the positing through a series of steps: Calculate the vector field function at that position, map that vector to a single value using `self.color_scheme` and finally generate a color from that value using the color gradient. Parameters ---------- sampling_rate The stepsize at which pixels get included in the image. Lower values give more accurate results, but may take a long time to compute. Returns ------- Image.Imgae The vector field image. """ if self.single_color: raise ValueError( "There is no point in generating an image if the vector field uses a single color.", ) ph = int(config["pixel_height"] / sampling_rate) pw = int(config["pixel_width"] / sampling_rate) fw = config["frame_width"] fh = config["frame_height"] points_array = np.zeros((ph, pw, 3)) x_array = np.linspace(-fw / 2, fw / 2, pw) y_array = np.linspace(fh / 2, -fh / 2, ph) x_array = x_array.reshape((1, len(x_array))) y_array = y_array.reshape((len(y_array), 1)) x_array = x_array.repeat(ph, axis=0) y_array.repeat(pw, axis=1) # TODO why not y_array = y_array.repeat(...)? points_array[:, :, 0] = x_array points_array[:, :, 1] = y_array rgbs = np.apply_along_axis(self.pos_to_rgb, 2, points_array) return Image.fromarray((rgbs * 255).astype("uint8")) def get_vectorized_rgba_gradient_function( self, start: float, end: float, colors: Iterable, ): """ Generates a gradient of rgbas as a numpy array Parameters ---------- start start value used for inverse interpolation at :func:`~.inverse_interpolate` end end value used for inverse interpolation at :func:`~.inverse_interpolate` colors list of colors to generate the gradient Returns ------- function to generate the gradients as numpy arrays representing rgba values """ rgbs = np.array([color_to_rgb(c) for c in colors]) return func class ArrowVectorField(VectorField): """A :class:`VectorField` represented by a set of change vectors. Vector fields are always based on a function defining the :class:`~.Vector` at every position. The values of this functions is displayed as a grid of vectors. By default the color of each vector is determined by it's magnitude. Other color schemes can be used however. Parameters ---------- func The function defining the rate of change at every position of the vector field. color The color of the vector field. If set, position-specific coloring is disabled. color_scheme A function mapping a vector to a single value. This value gives the position in the color gradient defined using `min_color_scheme_value`, `max_color_scheme_value` and `colors`. min_color_scheme_value The value of the color_scheme function to be mapped to the first color in `colors`. Lower values also result in the first color of the gradient. max_color_scheme_value The value of the color_scheme function to be mapped to the last color in `colors`. Higher values also result in the last color of the gradient. colors The colors defining the color gradient of the vector field. x_range A sequence of x_min, x_max, delta_x y_range A sequence of y_min, y_max, delta_y z_range A sequence of z_min, z_max, delta_z three_dimensions Enables three_dimensions. Default set to False, automatically turns True if z_range is not None. length_func The function determining the displayed size of the vectors. The actual size of the vector is passed, the returned value will be used as display size for the vector. By default this is used to cap the displayed size of vectors to reduce the clutter. opacity The opacity of the arrows. vector_config Additional arguments to be passed to the :class:`~.Vector` constructor kwargs : Any Additional arguments to be passed to the :class:`~.VGroup` constructor Examples -------- .. manim:: BasicUsage :save_last_frame: class BasicUsage(Scene): def construct(self): func = lambda pos: ((pos[0] * UR + pos[1] * LEFT) - pos) / 3 self.add(ArrowVectorField(func)) .. manim:: SizingAndSpacing class SizingAndSpacing(Scene): def construct(self): func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT vf = ArrowVectorField(func, x_range=[-7, 7, 1]) self.add(vf) self.wait() length_func = lambda x: x / 3 vf2 = ArrowVectorField(func, x_range=[-7, 7, 1], length_func=length_func) self.play(vf.animate.become(vf2)) self.wait() .. manim:: Coloring :save_last_frame: class Coloring(Scene): def construct(self): func = lambda pos: pos - LEFT * 5 colors = [RED, YELLOW, BLUE, DARK_GRAY] min_radius = Circle(radius=2, color=colors[0]).shift(LEFT * 5) max_radius = Circle(radius=10, color=colors[-1]).shift(LEFT * 5) vf = ArrowVectorField( func, min_color_scheme_value=2, max_color_scheme_value=10, colors=colors ) self.add(vf, min_radius, max_radius) """ def get_vector(self, point: np.ndarray): """Creates a vector in the vector field. The created vector is based on the function of the vector field and is rooted in the given point. Color and length fit the specifications of this vector field. Parameters ---------- point The root point of the vector. kwargs : Any Additional arguments to be passed to the :class:`~.Vector` constructor """ output = np.array(self.func(point)) norm = np.linalg.norm(output) if norm != 0: output *= self.length_func(norm) / norm vect = Vector(output, **self.vector_config) vect.shift(point) if self.single_color: vect.set_color(self.color) else: vect.set_color(self.pos_to_color(point)) return vect class StreamLines(VectorField): """StreamLines represent the flow of a :class:`VectorField` using the trace of moving agents. Vector fields are always based on a function defining the vector at every position. The values of this functions is displayed by moving many agents along the vector field and showing their trace. Parameters ---------- func The function defining the rate of change at every position of the vector field. color The color of the vector field. If set, position-specific coloring is disabled. color_scheme A function mapping a vector to a single value. This value gives the position in the color gradient defined using `min_color_scheme_value`, `max_color_scheme_value` and `colors`. min_color_scheme_value The value of the color_scheme function to be mapped to the first color in `colors`. Lower values also result in the first color of the gradient. max_color_scheme_value The value of the color_scheme function to be mapped to the last color in `colors`. Higher values also result in the last color of the gradient. colors The colors defining the color gradient of the vector field. x_range A sequence of x_min, x_max, delta_x y_range A sequence of y_min, y_max, delta_y z_range A sequence of z_min, z_max, delta_z three_dimensions Enables three_dimensions. Default set to False, automatically turns True if z_range is not None. noise_factor The amount by which the starting position of each agent is altered along each axis. Defaults to :code:`delta_y / 2` if not defined. n_repeats The number of agents generated at each starting point. dt The factor by which the distance an agent moves per step is stretched. Lower values result in a better approximation of the trajectories in the vector field. virtual_time The time the agents get to move in the vector field. Higher values therefore result in longer stream lines. However, this whole time gets simulated upon creation. max_anchors_per_line The maximum number of anchors per line. Lines with more anchors get reduced in complexity, not in length. padding The distance agents can move out of the generation area before being terminated. stroke_width The stroke with of the stream lines. opacity The opacity of the stream lines. Examples -------- .. manim:: BasicUsage :save_last_frame: class BasicUsage(Scene): def construct(self): func = lambda pos: ((pos[0] * UR + pos[1] * LEFT) - pos) / 3 self.add(StreamLines(func)) .. manim:: SpawningAndFlowingArea :save_last_frame: class SpawningAndFlowingArea(Scene): def construct(self): func = lambda pos: np.sin(pos[0]) * UR + np.cos(pos[1]) * LEFT + pos / 5 stream_lines = StreamLines( func, x_range=[-3, 3, 0.2], y_range=[-2, 2, 0.2], padding=1 ) spawning_area = Rectangle(width=6, height=4) flowing_area = Rectangle(width=8, height=6) labels = [Tex("Spawning Area"), Tex("Flowing Area").shift(DOWN * 2.5)] for lbl in labels: lbl.add_background_rectangle(opacity=0.6, buff=0.05) self.add(stream_lines, spawning_area, flowing_area, *labels) """ def create( self, lag_ratio: Optional[float] = None, run_time: Optional[Callable[[float], float]] = None, **kwargs ) -> AnimationGroup: """The creation animation of the stream lines. The stream lines appear in random order. Parameters ---------- lag_ratio The lag ratio of the animation. If undefined, it will be selected so that the total animation length is 1.5 times the run time of each stream line creation. run_time The run time of every single stream line creation. The runtime of the whole animation might be longer due to the `lag_ratio`. If undefined, the virtual time of the stream lines is used as run time. Returns ------- :class:`~.AnimationGroup` The creation animation of the stream lines. Examples -------- .. manim:: StreamLineCreation class StreamLineCreation(Scene): def construct(self): func = lambda pos: (pos[0] * UR + pos[1] * LEFT) - pos stream_lines = StreamLines( func, color=YELLOW, x_range=[-7, 7, 1], y_range=[-4, 4, 1], stroke_width=3, virtual_time=1, # use shorter lines max_anchors_per_line=5, # better performance with fewer anchors ) self.play(stream_lines.create()) # uses virtual_time as run_time self.wait() """ if run_time is None: run_time = self.virtual_time if lag_ratio is None: lag_ratio = run_time / 2 / len(self.submobjects) animations = [ Create(line, run_time=run_time, **kwargs) for line in self.stream_lines ] random.shuffle(animations) return AnimationGroup(*animations, lag_ratio=lag_ratio) def start_animation( self, warm_up=True, flow_speed: float = 1, time_width: float = 0.3, rate_func: Callable[[float], float] = linear, line_animation_class: Type[ShowPassingFlash] = ShowPassingFlash, **kwargs ) -> None: """Animates the stream lines using an updater. The stream lines will continuously flow Parameters ---------- warm_up : bool, optional If `True` the animation is initialized line by line. Otherwise it starts with all lines shown. flow_speed At `flow_speed=1` the distance the flow moves per second is equal to the magnitude of the vector field along its path. The speed value scales the speed of this flow. time_width The proportion of the stream line shown while being animated rate_func The rate function of each stream line flashing line_animation_class The animation class being used Examples -------- .. manim:: ContinuousMotion class ContinuousMotion(Scene): def construct(self): func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT stream_lines = StreamLines(func, stroke_width=3, max_anchors_per_line=30) self.add(stream_lines) stream_lines.start_animation(warm_up=False, flow_speed=1.5) self.wait(stream_lines.virtual_time / stream_lines.flow_speed) """ for line in self.stream_lines: run_time = line.duration / flow_speed line.anim = line_animation_class( line, run_time=run_time, rate_func=rate_func, time_width=time_width, **kwargs, ) line.anim.begin() line.time = random.random() * self.virtual_time if warm_up: line.time *= -1 self.add(line.anim.mobject) self.add_updater(updater) self.flow_animation = updater self.flow_speed = flow_speed self.time_width = time_width def end_animation(self) -> AnimationGroup: """End the stream line animation smoothly. Returns an animation resulting in fully displayed stream lines without a noticeable cut. Returns ------- :class:`~.AnimationGroup` The animation fading out the running stream animation. Raises ------ ValueError if no stream line animation is running Examples -------- .. manim:: EndAnimation class EndAnimation(Scene): def construct(self): func = lambda pos: np.sin(pos[0] / 2) * UR + np.cos(pos[1] / 2) * LEFT stream_lines = StreamLines( func, stroke_width=3, max_anchors_per_line=5, virtual_time=1, color=BLUE ) self.add(stream_lines) stream_lines.start_animation(warm_up=False, flow_speed=1.5, time_width=0.5) self.wait(1) self.play(stream_lines.end_animation()) """ if self.flow_animation is None: raise ValueError("You have to start the animation before fading it out.") max_run_time = self.virtual_time / self.flow_speed creation_rate_func = ease_out_sine creation_staring_speed = creation_rate_func(0.001) * 1000 creation_run_time = ( max_run_time / (1 + self.time_width) * creation_staring_speed ) # creation_run_time is calculated so that the creation animation starts at the same speed # as the regular line flash animation but eases out. dt = 1 / config["frame_rate"] animations = [] self.remove_updater(self.flow_animation) self.flow_animation = None for line in self.stream_lines: create = Create( line, run_time=creation_run_time, rate_func=creation_rate_func, ) if line.time <= 0: animations.append( Succession( UpdateFromAlphaFunc( line, hide_and_wait, run_time=-line.time / self.flow_speed, ), create, ), ) self.remove(line.anim.mobject) line.anim.finish() else: remaining_time = max_run_time - line.time / self.flow_speed animations.append( Succession( UpdateFromAlphaFunc( line, finish_updater_cycle, run_time=remaining_time, ), create, ), ) return AnimationGroup(*animations) # TODO: Variant of StreamLines that is able to respond to changes in the vector field function
[ 37811, 44, 48205, 10200, 15879, 7032, 526, 15931, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 366, 38469, 15878, 1600, 198, 220, 220, 220, 366, 3163, 808, 38469, 15878, 1600, 198, 220, 220, 220, 366, 12124, 43, 1127, 1600, ...
2.303941
9,515
""" This library allows the conversion of python 3.7's :mod:`dataclasses` to :mod:`marshmallow` schemas. It takes a python class, and generates a marshmallow schema for it. Simple example:: from marshmallow import Schema from marshmallow_dataclass import dataclass @dataclass class Point: x:float y:float point = Point(x=0, y=0) point_json = Point.Schema().dumps(point) Full example:: from marshmallow import Schema from dataclasses import field from marshmallow_dataclass import dataclass import datetime @dataclass class User: birth: datetime.date = field(metadata= { "required": True # A parameter to pass to marshmallow's field }) website:str = field(metadata = { "marshmallow_field": marshmallow.fields.Url() # Custom marshmallow field }) Schema: ClassVar[Type[Schema]] = Schema # For the type checker """ import inspect from enum import EnumMeta from functools import lru_cache from typing import ( Any, Callable, Dict, List, Mapping, Optional, Set, Tuple, Type, TypeVar, Union, cast, overload, ) import dataclasses import marshmallow import typing_inspect __all__ = ["dataclass", "add_schema", "class_schema", "field_for_schema", "NewType"] NoneType = type(None) _U = TypeVar("_U") # Whitelist of dataclass members that will be copied to generated schema. MEMBERS_WHITELIST: Set[str] = {"Meta"} # Max number of generated schemas that class_schema keeps of generated schemas. Removes duplicates. MAX_CLASS_SCHEMA_CACHE_SIZE = 1024 # _cls should never be specified by keyword, so start it with an # underscore. The presence of _cls is used to detect if this # decorator is being called with parameters or not. def dataclass( _cls: Type[_U] = None, *, repr: bool = True, eq: bool = True, order: bool = False, unsafe_hash: bool = False, frozen: bool = False, base_schema: Optional[Type[marshmallow.Schema]] = None, ): """ This decorator does the same as dataclasses.dataclass, but also applies :func:`add_schema`. It adds a `.Schema` attribute to the class object :param base_schema: marshmallow schema used as a base class when deriving dataclass schema >>> @dataclass ... class Artist: ... name: str >>> Artist.Schema <class 'marshmallow.schema.Artist'> >>> from typing import ClassVar >>> from marshmallow import Schema >>> @dataclass(order=True) # preserve field order ... class Point: ... x:float ... y:float ... Schema: ClassVar[Type[Schema]] = Schema # For the type checker ... >>> Point.Schema().load({'x':0, 'y':0}) # This line can be statically type checked Point(x=0.0, y=0.0) """ # dataclass's typing doesn't expect it to be called as a function, so ignore type check dc = dataclasses.dataclass( # type: ignore _cls, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen ) if _cls is None: return lambda cls: add_schema(dc(cls), base_schema) return add_schema(dc, base_schema) def add_schema(_cls=None, base_schema=None): """ This decorator adds a marshmallow schema as the 'Schema' attribute in a dataclass. It uses :func:`class_schema` internally. :param type cls: The dataclass to which a Schema should be added :param base_schema: marshmallow schema used as a base class when deriving dataclass schema >>> class BaseSchema(marshmallow.Schema): ... def on_bind_field(self, field_name, field_obj): ... field_obj.data_key = (field_obj.data_key or field_name).upper() >>> @add_schema(base_schema=BaseSchema) ... @dataclasses.dataclass ... class Artist: ... names: Tuple[str, str] >>> artist = Artist.Schema().loads('{"NAMES": ["Martin", "Ramirez"]}') >>> artist Artist(names=('Martin', 'Ramirez')) """ return decorator(_cls) if _cls else decorator def class_schema( clazz: type, base_schema: Optional[Type[marshmallow.Schema]] = None ) -> Type[marshmallow.Schema]: """ Convert a class to a marshmallow schema :param clazz: A python class (may be a dataclass) :param base_schema: marshmallow schema used as a base class when deriving dataclass schema :return: A marshmallow Schema corresponding to the dataclass .. note:: All the arguments supported by marshmallow field classes can be passed in the `metadata` dictionary of a field. If you want to use a custom marshmallow field (one that has no equivalent python type), you can pass it as the ``marshmallow_field`` key in the metadata dictionary. >>> import typing >>> Meters = typing.NewType('Meters', float) >>> @dataclasses.dataclass() ... class Building: ... height: Optional[Meters] ... name: str = dataclasses.field(default="anonymous") ... class Meta: ... ordered = True ... >>> class_schema(Building) # Returns a marshmallow schema class (not an instance) <class 'marshmallow.schema.Building'> >>> @dataclasses.dataclass() ... class City: ... name: str = dataclasses.field(metadata={'required':True}) ... best_building: Building # Reference to another dataclasses. A schema will be created for it too. ... other_buildings: List[Building] = dataclasses.field(default_factory=lambda: []) ... >>> citySchema = class_schema(City)() >>> city = citySchema.load({"name":"Paris", "best_building": {"name": "Eiffel Tower"}}) >>> city City(name='Paris', best_building=Building(height=None, name='Eiffel Tower'), other_buildings=[]) >>> citySchema.load({"name":"Paris"}) Traceback (most recent call last): ... marshmallow.exceptions.ValidationError: {'best_building': ['Missing data for required field.']} >>> city_json = citySchema.dump(city) >>> city_json['best_building'] # We get an OrderedDict because we specified order = True in the Meta class OrderedDict([('height', None), ('name', 'Eiffel Tower')]) >>> @dataclasses.dataclass() ... class Person: ... name: str = dataclasses.field(default="Anonymous") ... friends: List['Person'] = dataclasses.field(default_factory=lambda:[]) # Recursive field ... >>> person = class_schema(Person)().load({ ... "friends": [{"name": "Roger Boucher"}] ... }) >>> person Person(name='Anonymous', friends=[Person(name='Roger Boucher', friends=[])]) >>> @dataclasses.dataclass() ... class C: ... important: int = dataclasses.field(init=True, default=0) ... # Only fields that are in the __init__ method will be added: ... unimportant: int = dataclasses.field(init=False, default=0) ... >>> c = class_schema(C)().load({ ... "important": 9, # This field will be imported ... "unimportant": 9 # This field will NOT be imported ... }, unknown=marshmallow.EXCLUDE) >>> c C(important=9, unimportant=0) >>> @dataclasses.dataclass ... class Website: ... url:str = dataclasses.field(metadata = { ... "marshmallow_field": marshmallow.fields.Url() # Custom marshmallow field ... }) ... >>> class_schema(Website)().load({"url": "I am not a good URL !"}) Traceback (most recent call last): ... marshmallow.exceptions.ValidationError: {'url': ['Not a valid URL.']} >>> @dataclasses.dataclass ... class NeverValid: ... @marshmallow.validates_schema ... def validate(self, data, **_): ... raise marshmallow.ValidationError('never valid') ... >>> class_schema(NeverValid)().load({}) Traceback (most recent call last): ... marshmallow.exceptions.ValidationError: {'_schema': ['never valid']} >>> # noinspection PyTypeChecker >>> class_schema(None) # unsupported type Traceback (most recent call last): ... TypeError: None is not a dataclass and cannot be turned into one. >>> @dataclasses.dataclass ... class Anything: ... name: str ... @marshmallow.validates('name') ... def validates(self, value): ... if len(value) > 5: raise marshmallow.ValidationError("Name too long") >>> class_schema(Anything)().load({"name": "aaaaaargh"}) Traceback (most recent call last): ... marshmallow.exceptions.ValidationError: {'name': ['Name too long']} """ return _proxied_class_schema(clazz, base_schema) def _field_by_supertype( typ: Type, default: marshmallow.missing, newtype_supertype: Type, metadata: dict, base_schema: Optional[Type[marshmallow.Schema]], ) -> marshmallow.fields.Field: """ Return a new field for fields based on a super field. (Usually spawned from NewType) """ # Add the information coming our custom NewType implementation typ_args = getattr(typ, "_marshmallow_args", {}) # Handle multiple validators from both `typ` and `metadata`. # See https://github.com/lovasoa/marshmallow_dataclass/issues/91 new_validators: List[Callable] = [] for meta_dict in (typ_args, metadata): if "validate" in meta_dict: if marshmallow.utils.is_iterable_but_not_string(meta_dict["validate"]): new_validators.extend(meta_dict["validate"]) elif callable(meta_dict["validate"]): new_validators.append(meta_dict["validate"]) metadata["validate"] = new_validators if new_validators else None metadata = {"description": typ.__name__, **typ_args, **metadata} field = getattr(typ, "_marshmallow_field", None) if field: return field(**metadata) else: return field_for_schema( newtype_supertype, metadata=metadata, default=default, base_schema=base_schema, ) def field_for_schema( typ: type, default=marshmallow.missing, metadata: Mapping[str, Any] = None, base_schema: Optional[Type[marshmallow.Schema]] = None, ) -> marshmallow.fields.Field: """ Get a marshmallow Field corresponding to the given python type. The metadata of the dataclass field is used as arguments to the marshmallow Field. :param typ: The type for which a field should be generated :param default: value to use for (de)serialization when the field is missing :param metadata: Additional parameters to pass to the marshmallow field constructor :param base_schema: marshmallow schema used as a base class when deriving dataclass schema >>> int_field = field_for_schema(int, default=9, metadata=dict(required=True)) >>> int_field.__class__ <class 'marshmallow.fields.Integer'> >>> int_field.default 9 >>> field_for_schema(str, metadata={"marshmallow_field": marshmallow.fields.Url()}).__class__ <class 'marshmallow.fields.Url'> """ metadata = {} if metadata is None else dict(metadata) if default is not marshmallow.missing: metadata.setdefault("default", default) # 'missing' must not be set for required fields. if not metadata.get("required"): metadata.setdefault("missing", default) else: metadata.setdefault("required", True) # If the field was already defined by the user predefined_field = metadata.get("marshmallow_field") if predefined_field: return predefined_field # Generic types specified without type arguments if typ is list: typ = List[Any] elif typ is dict: typ = Dict[Any, Any] # Base types field = _field_by_type(typ, base_schema) if field: return field(**metadata) if typ is Any: metadata.setdefault("allow_none", True) return marshmallow.fields.Raw(**metadata) # Generic types origin = typing_inspect.get_origin(typ) if origin: arguments = typing_inspect.get_args(typ, True) # Override base_schema.TYPE_MAPPING to change the class used for generic types below type_mapping = base_schema.TYPE_MAPPING if base_schema else {} if origin in (list, List): child_type = field_for_schema(arguments[0], base_schema=base_schema) list_type = type_mapping.get(List, marshmallow.fields.List) return list_type(child_type, **metadata) if origin in (tuple, Tuple): children = tuple( field_for_schema(arg, base_schema=base_schema) for arg in arguments ) tuple_type = type_mapping.get(Tuple, marshmallow.fields.Tuple) return tuple_type(children, **metadata) elif origin in (dict, Dict): dict_type = type_mapping.get(Dict, marshmallow.fields.Dict) return dict_type( keys=field_for_schema(arguments[0], base_schema=base_schema), values=field_for_schema(arguments[1], base_schema=base_schema), **metadata, ) elif typing_inspect.is_optional_type(typ): subtyp = next(t for t in arguments if t is not NoneType) # type: ignore # Treat optional types as types with a None default metadata["default"] = metadata.get("default", None) metadata["missing"] = metadata.get("missing", None) metadata["required"] = False return field_for_schema(subtyp, metadata=metadata, base_schema=base_schema) elif typing_inspect.is_union_type(typ): from . import union_field return union_field.Union( [ ( subtyp, field_for_schema( subtyp, metadata=metadata, base_schema=base_schema ), ) for subtyp in arguments ], **metadata, ) # typing.NewType returns a function with a __supertype__ attribute newtype_supertype = getattr(typ, "__supertype__", None) if newtype_supertype and inspect.isfunction(typ): return _field_by_supertype( typ=typ, default=default, newtype_supertype=newtype_supertype, metadata=metadata, base_schema=base_schema, ) # enumerations if isinstance(typ, EnumMeta): import marshmallow_enum return marshmallow_enum.EnumField(typ, **metadata) # Nested marshmallow dataclass nested_schema = getattr(typ, "Schema", None) # Nested dataclasses forward_reference = getattr(typ, "__forward_arg__", None) nested = ( nested_schema or forward_reference or class_schema(typ, base_schema=base_schema) ) return marshmallow.fields.Nested(nested, **metadata) def _base_schema( clazz: type, base_schema: Optional[Type[marshmallow.Schema]] = None ) -> Type[marshmallow.Schema]: """ Base schema factory that creates a schema for `clazz` derived either from `base_schema` or `BaseSchema` """ # Remove `type: ignore` when mypy handles dynamic base classes # https://github.com/python/mypy/issues/2813 return BaseSchema def _get_field_default(field: dataclasses.Field): """ Return a marshmallow default value given a dataclass default value >>> _get_field_default(dataclasses.field()) <marshmallow.missing> """ # Remove `type: ignore` when https://github.com/python/mypy/issues/6910 is fixed default_factory = field.default_factory # type: ignore if default_factory is not dataclasses.MISSING: return default_factory elif field.default is dataclasses.MISSING: return marshmallow.missing return field.default def NewType( name: str, typ: Type[_U], field: Optional[Type[marshmallow.fields.Field]] = None, **kwargs, ) -> Callable[[_U], _U]: """NewType creates simple unique types to which you can attach custom marshmallow attributes. All the keyword arguments passed to this function will be transmitted to the marshmallow field constructor. >>> import marshmallow.validate >>> IPv4 = NewType('IPv4', str, validate=marshmallow.validate.Regexp(r'^([0-9]{1,3}\\.){3}[0-9]{1,3}$')) >>> @dataclass ... class MyIps: ... ips: List[IPv4] >>> MyIps.Schema().load({"ips": ["0.0.0.0", "grumble grumble"]}) Traceback (most recent call last): ... marshmallow.exceptions.ValidationError: {'ips': {1: ['String does not match expected pattern.']}} >>> MyIps.Schema().load({"ips": ["127.0.0.1"]}) MyIps(ips=['127.0.0.1']) >>> Email = NewType('Email', str, field=marshmallow.fields.Email) >>> @dataclass ... class ContactInfo: ... mail: Email = dataclasses.field(default="anonymous@example.org") >>> ContactInfo.Schema().load({}) ContactInfo(mail='anonymous@example.org') >>> ContactInfo.Schema().load({"mail": "grumble grumble"}) Traceback (most recent call last): ... marshmallow.exceptions.ValidationError: {'mail': ['Not a valid email address.']} """ new_type.__name__ = name new_type.__supertype__ = typ # type: ignore new_type._marshmallow_field = field # type: ignore new_type._marshmallow_args = kwargs # type: ignore return new_type if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
[ 37811, 198, 1212, 5888, 3578, 262, 11315, 286, 21015, 513, 13, 22, 338, 1058, 4666, 25, 63, 19608, 330, 28958, 63, 198, 1462, 1058, 4666, 25, 63, 76, 5406, 42725, 63, 3897, 5356, 13, 198, 198, 1026, 2753, 257, 21015, 1398, 11, 290, ...
2.579798
6,742
#!/usr/bin/env python3 import sys import asyncio from electrum_trc.network import filter_protocol, Network from electrum_trc.util import create_and_start_event_loop, log_exceptions try: txid = sys.argv[1] except: print("usage: txradar txid") sys.exit(1) loop, stopping_fut, loop_thread = create_and_start_event_loop() network = Network() network.start() asyncio.run_coroutine_threadsafe(f(), loop)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 25064, 198, 11748, 30351, 952, 198, 198, 6738, 1742, 6582, 62, 2213, 66, 13, 27349, 1330, 8106, 62, 11235, 4668, 11, 7311, 198, 6738, 1742, 6582, 62, 2213, 66, 13, 22602, ...
2.701299
154
import sys import typing import numpy as np OJ = 'ONLINE_JUDGE' if sys.argv[-1] == OJ: from numba import i8, njit from numba.pycc import CC cc = CC('my_module') fn = solve signature = (i8, i8[:, :]) cc.export( fn.__name__, signature, )(fn) cc.compile() exit(0) from my_module import solve main()
[ 11748, 25064, 198, 11748, 19720, 198, 198, 11748, 299, 32152, 355, 45941, 628, 628, 198, 198, 46, 41, 796, 705, 1340, 24027, 62, 41, 8322, 8264, 6, 198, 361, 25064, 13, 853, 85, 58, 12, 16, 60, 6624, 440, 41, 25, 198, 220, 422, ...
2.285714
147
from datetime import datetime from pypylon import pylon import nimmAuf import smbus2 import os import argparse import bestimmeVolumen from threading import Thread import time programmstart = time.time() # Argumente parsen (bei Aufruf im Terminal z.B. 'starteMessung.py -n 100' eingeben) ap = argparse.ArgumentParser(description="""Skript zum Aufnehmen von Bildern der Teststrecke und der Volumenbestimmung von Luftblasen""") ap.add_argument("-n", "--number", default=400, type=int, help="Anzahl an Frames die aufgenommen werden sollen. Default: 400 Bilder") ap.add_argument("-fr", "--framerate", default=100, type=int, help="Framerate in fps. Richtwerte: <Flow 3 ml/s:50 fps, 3-6ml/s:100 fps, >6ml/s:200 fps; Default: 100 fps") args = vars(ap.parse_args()) # Argumente des Parsers extrahieren numberOfImagesToGrab = args['number'] framerate = args['framerate'] if __name__ == '__main__': startzeit = time.time() #Test ob Kamera angeschlossen ist devices = pylon.TlFactory.GetInstance().EnumerateDevices() if len(devices) == 0: print("Keine Kamera angeschlossen oder Kamera woanders geffnet.") return False # Test ob Drucksensor angeschlossen ist try: bus = smbus2.SMBus(0) bus.read_i2c_block_data(0x40, 0, 2) # 2 Bytes empfangen except OSError: print("Kein Drucksensor angeschlossen") exit() # Aus der aktuellen Zeit und den Parametern einen individuellen Ordnernamen generieren dirname = f'{datetime.now().strftime("%Y-%m-%d-%H-%M-%S")}' os.mkdir(dirname) # Ordner erstellen print(f"Ordnername: {dirname}") beginn = time.time()-programmstart # Threads zum Aufnehmen und Verarbeiten starten t_aufnahme = Thread(target=nimmAuf.starte, args=(dirname, numberOfImagesToGrab, framerate, startzeit)) t_tracke = Thread(target=bestimmeVolumen.tracke, args=(dirname, numberOfImagesToGrab)) t_aufnahme.start() t_tracke.start() t_aufnahme.join() t_tracke.join()
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 279, 4464, 15158, 1330, 279, 15158, 198, 11748, 299, 8608, 32, 3046, 198, 11748, 895, 10885, 17, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 1266, 320, 1326, 16598, 20080, 198, ...
2.389215
853
import os import tempfile
[ 11748, 28686, 198, 11748, 20218, 7753, 628, 628, 628, 198 ]
3.2
10
# # PySNMP MIB module EXTREME-RTSTATS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-BASE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:53:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection") extremeAgent, = mibBuilder.importSymbols("EXTREME-BASE-MIB", "extremeAgent") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Unsigned32, iso, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Bits, MibIdentifier, ModuleIdentity, Counter64, Counter32, NotificationType, Integer32, IpAddress, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "iso", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Bits", "MibIdentifier", "ModuleIdentity", "Counter64", "Counter32", "NotificationType", "Integer32", "IpAddress", "TimeTicks") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") extremeRtStats = ModuleIdentity((1, 3, 6, 1, 4, 1, 1916, 1, 11)) if mibBuilder.loadTexts: extremeRtStats.setLastUpdated('9906240000Z') if mibBuilder.loadTexts: extremeRtStats.setOrganization('Extreme Networks, Inc.') extremeRtStatsTable = MibTable((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1), ) if mibBuilder.loadTexts: extremeRtStatsTable.setStatus('current') extremeRtStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1), ).setIndexNames((0, "EXTREME-RTSTATS-MIB", "extremeRtStatsIndex")) if mibBuilder.loadTexts: extremeRtStatsEntry.setStatus('current') extremeRtStatsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsIndex.setStatus('current') extremeRtStatsIntervalStart = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 2), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsIntervalStart.setStatus('current') extremeRtStatsCRCAlignErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsCRCAlignErrors.setStatus('current') extremeRtStatsUndersizePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsUndersizePkts.setStatus('current') extremeRtStatsOversizePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsOversizePkts.setStatus('current') extremeRtStatsFragments = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsFragments.setStatus('current') extremeRtStatsJabbers = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsJabbers.setStatus('current') extremeRtStatsCollisions = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsCollisions.setStatus('current') extremeRtStatsTotalErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsTotalErrors.setStatus('current') extremeRtStatsUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 11, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 10000))).setMaxAccess("readonly") if mibBuilder.loadTexts: extremeRtStatsUtilization.setStatus('current') mibBuilder.exportSymbols("EXTREME-RTSTATS-MIB", extremeRtStatsEntry=extremeRtStatsEntry, extremeRtStatsOversizePkts=extremeRtStatsOversizePkts, extremeRtStatsUndersizePkts=extremeRtStatsUndersizePkts, extremeRtStatsTable=extremeRtStatsTable, extremeRtStatsTotalErrors=extremeRtStatsTotalErrors, extremeRtStats=extremeRtStats, PYSNMP_MODULE_ID=extremeRtStats, extremeRtStatsCollisions=extremeRtStatsCollisions, extremeRtStatsCRCAlignErrors=extremeRtStatsCRCAlignErrors, extremeRtStatsJabbers=extremeRtStatsJabbers, extremeRtStatsIndex=extremeRtStatsIndex, extremeRtStatsUtilization=extremeRtStatsUtilization, extremeRtStatsIntervalStart=extremeRtStatsIntervalStart, extremeRtStatsFragments=extremeRtStatsFragments)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 27489, 2200, 11682, 12, 14181, 2257, 33586, 12, 8895, 33, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, 2723, 2393, 1378, 14, 14490,...
2.75196
1,786