hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
11 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
251
max_stars_repo_name
stringlengths
4
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
251
max_issues_repo_name
stringlengths
4
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
251
max_forks_repo_name
stringlengths
4
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.05M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.04M
alphanum_fraction
float64
0
1
13cde4f4ec9916ff8a799bc071fde32fd8bf29b3
2,461
py
Python
plotter.py
StrangeTcy/pathnet-pytorch
58c8088b992ad2f36b843186d93edc872d547c7b
[ "BSD-3-Clause" ]
86
2017-04-05T13:03:13.000Z
2022-03-28T12:38:48.000Z
plotter.py
StrangeTcy/pathnet-pytorch
58c8088b992ad2f36b843186d93edc872d547c7b
[ "BSD-3-Clause" ]
7
2017-04-30T20:59:46.000Z
2019-02-09T10:56:40.000Z
plotter.py
StrangeTcy/pathnet-pytorch
58c8088b992ad2f36b843186d93edc872d547c7b
[ "BSD-3-Clause" ]
21
2017-04-05T23:42:39.000Z
2021-11-17T21:17:22.000Z
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")
28.952941
95
0.603007
13ce074cf333bc82bde9c49d1dbfefb77ad96d57
715
py
Python
kindler/solver/optimizer.py
mingruimingrui/kindler
8a9c2278b607a167b0ce827b218e54949a1120e7
[ "MIT" ]
null
null
null
kindler/solver/optimizer.py
mingruimingrui/kindler
8a9c2278b607a167b0ce827b218e54949a1120e7
[ "MIT" ]
null
null
null
kindler/solver/optimizer.py
mingruimingrui/kindler
8a9c2278b607a167b0ce827b218e54949a1120e7
[ "MIT" ]
null
null
null
import torch
22.34375
67
0.601399
13ce147cc376d9100195efcbf75606622c35be95
2,805
py
Python
platypus/tests/test_operators.py
sctiwari/EZFF_ASE
94710d4cf778ff2db5e6df0cd6d10d92e1b98afe
[ "MIT" ]
2
2021-05-10T16:28:50.000Z
2021-12-15T04:03:34.000Z
platypus/tests/test_operators.py
sctiwari/EZFF_ASE
94710d4cf778ff2db5e6df0cd6d10d92e1b98afe
[ "MIT" ]
null
null
null
platypus/tests/test_operators.py
sctiwari/EZFF_ASE
94710d4cf778ff2db5e6df0cd6d10d92e1b98afe
[ "MIT" ]
null
null
null
# 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
35.961538
74
0.636364
13cea3eb1b8257abf1a1958d34086a311a9082d4
6,241
py
Python
fusion_net/bilinear_sampler.py
ClovisChen/LearningCNN
cd9102a3d71f602024558d818039f5b759c92fa5
[ "Apache-2.0" ]
null
null
null
fusion_net/bilinear_sampler.py
ClovisChen/LearningCNN
cd9102a3d71f602024558d818039f5b759c92fa5
[ "Apache-2.0" ]
null
null
null
fusion_net/bilinear_sampler.py
ClovisChen/LearningCNN
cd9102a3d71f602024558d818039f5b759c92fa5
[ "Apache-2.0" ]
null
null
null
#!/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
41.331126
155
0.497196
13cebdf8d097569317951da787d81aebd898d39b
7,125
py
Python
Supernovae.py
adamamiller/iptf16hvw-1
d674114e94b5b20398d2e4208b55eb8e2394dce9
[ "MIT" ]
null
null
null
Supernovae.py
adamamiller/iptf16hvw-1
d674114e94b5b20398d2e4208b55eb8e2394dce9
[ "MIT" ]
null
null
null
Supernovae.py
adamamiller/iptf16hvw-1
d674114e94b5b20398d2e4208b55eb8e2394dce9
[ "MIT" ]
1
2018-08-21T15:17:48.000Z
2018-08-21T15:17:48.000Z
#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
28.27381
108
0.629474
13cfe935b3ae2ffb5842e273c8ff7ca4cd002f6d
2,753
py
Python
userbot/plugins/alive.py
iraqis1/irqis
d95303c48b5f15dbe814454a48d847e838793713
[ "MIT" ]
null
null
null
userbot/plugins/alive.py
iraqis1/irqis
d95303c48b5f15dbe814454a48d847e838793713
[ "MIT" ]
null
null
null
userbot/plugins/alive.py
iraqis1/irqis
d95303c48b5f15dbe814454a48d847e838793713
[ "MIT" ]
null
null
null
"""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"
26.219048
123
0.521976
13d20c58618bae1fd9184241e64ff9b913dd727d
9,313
py
Python
connector/ADBConnector.py
qiutongxue/ArknightsAutoHelper
6b97b289e9ea4e5e3f39561ef8c2217657f6ff60
[ "MIT" ]
1
2020-12-16T06:19:02.000Z
2020-12-16T06:19:02.000Z
connector/ADBConnector.py
qiutongxue/ArknightsAutoHelper
6b97b289e9ea4e5e3f39561ef8c2217657f6ff60
[ "MIT" ]
null
null
null
connector/ADBConnector.py
qiutongxue/ArknightsAutoHelper
6b97b289e9ea4e5e3f39561ef8c2217657f6ff60
[ "MIT" ]
null
null
null
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__)
36.521569
163
0.57962
13d25057738843cced8f3d82852dabf41375fb9a
754
py
Python
redshift_upload/base_utilities.py
douglassimonsen/redshift_upload
e549c770538f022c0b90a983ca056f3e9c16c643
[ "MIT" ]
null
null
null
redshift_upload/base_utilities.py
douglassimonsen/redshift_upload
e549c770538f022c0b90a983ca056f3e9c16c643
[ "MIT" ]
1
2022-03-12T03:50:55.000Z
2022-03-12T03:50:55.000Z
redshift_upload/base_utilities.py
douglassimonsen/redshift_upload
e549c770538f022c0b90a983ca056f3e9c16c643
[ "MIT" ]
null
null
null
import inspect import os from pathlib import Path
30.16
98
0.624668
13d2e35293cf4b36df0d8aa584ec383e80a8a174
263
py
Python
main.py
Gloriel621/MgallManager
7d5c02ab6bdc2f6c6922d4a7e021faef33d868bb
[ "MIT" ]
9
2021-12-22T11:37:23.000Z
2022-03-09T02:25:35.000Z
main.py
Gloriel621/MgallManager
7d5c02ab6bdc2f6c6922d4a7e021faef33d868bb
[ "MIT" ]
4
2021-12-16T14:26:01.000Z
2022-02-16T02:05:41.000Z
main.py
Gloriel621/MgallManager
7d5c02ab6bdc2f6c6922d4a7e021faef33d868bb
[ "MIT" ]
1
2021-12-22T12:59:57.000Z
2021-12-22T12:59:57.000Z
import sys from PyQt5.QtWidgets import QApplication from gui import MgallManager if __name__ == "__main__": main()
16.4375
43
0.69962
13d3859368c4908cf2a507d1bd62d989795acc1a
54,009
py
Python
pysc2/lib/actions.py
javierrcc522/starcraft2_api_machineLear
5833ba1344ab5445c4f09fafc33e6058070ebe6c
[ "Apache-2.0" ]
2
2020-04-30T09:07:25.000Z
2021-03-21T22:58:22.000Z
pysc2/lib/actions.py
javierrcc522/starcraft2_api_machineLear
5833ba1344ab5445c4f09fafc33e6058070ebe6c
[ "Apache-2.0" ]
null
null
null
pysc2/lib/actions.py
javierrcc522/starcraft2_api_machineLear
5833ba1344ab5445c4f09fafc33e6058070ebe6c
[ "Apache-2.0" ]
null
null
null
# 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}
57.825482
100
0.750745
13d4be5ff6607a768ff6f008bc6f55355c95eab1
3,209
py
Python
pywick/meters/aucmeter.py
ashishpatel26/pywick
1afffd1c21c2b188836d3599e802146182757bb5
[ "MIT" ]
2
2020-11-28T07:56:09.000Z
2021-11-08T09:30:39.000Z
pywick/meters/aucmeter.py
ashishpatel26/pywick
1afffd1c21c2b188836d3599e802146182757bb5
[ "MIT" ]
null
null
null
pywick/meters/aucmeter.py
ashishpatel26/pywick
1afffd1c21c2b188836d3599e802146182757bb5
[ "MIT" ]
null
null
null
import numbers from . import meter import numpy as np import torch
38.662651
91
0.606108
13d5b4c27424ce3f3958c70f0a0828815649d42f
2,971
py
Python
homeassistant/components/zha/core/channels/lighting.py
liangleslie/core
cc807b4d597daaaadc92df4a93c6e30da4f570c6
[ "Apache-2.0" ]
30,023
2016-04-13T10:17:53.000Z
2020-03-02T12:56:31.000Z
homeassistant/components/zha/core/channels/lighting.py
liangleslie/core
cc807b4d597daaaadc92df4a93c6e30da4f570c6
[ "Apache-2.0" ]
24,710
2016-04-13T08:27:26.000Z
2020-03-02T12:59:13.000Z
homeassistant/components/zha/core/channels/lighting.py
liangleslie/core
cc807b4d597daaaadc92df4a93c6e30da4f570c6
[ "Apache-2.0" ]
11,956
2016-04-13T18:42:31.000Z
2020-03-02T09:32:12.000Z
"""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
33.382022
76
0.693369
13d60376951a923005fa671870c17c7889bfb96b
6,140
py
Python
pf/queue.py
PiRAT4/py-pf
7ffdd0a283d4a36fc4c473433d5f79a84eeb5d31
[ "BSD-3-Clause" ]
null
null
null
pf/queue.py
PiRAT4/py-pf
7ffdd0a283d4a36fc4c473433d5f79a84eeb5d31
[ "BSD-3-Clause" ]
null
null
null
pf/queue.py
PiRAT4/py-pf
7ffdd0a283d4a36fc4c473433d5f79a84eeb5d31
[ "BSD-3-Clause" ]
null
null
null
"""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"]
29.95122
79
0.548534
13d646c36a3c1b8a275d4d104aa95c23081163a3
2,378
py
Python
sdk/python/pulumi_azure_native/labservices/v20181015/__init__.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/labservices/v20181015/__init__.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/labservices/v20181015/__init__.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
# 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()
38.983607
102
0.710681
13d760267b20f874fc4b087de72759e81f401445
6,123
py
Python
servicedirectory/src/sd-api/users/tests/tests_serializers.py
ealogar/servicedirectory
fb4f4bfa8b499b93c03af589ef2f34c08a830b17
[ "Apache-2.0" ]
null
null
null
servicedirectory/src/sd-api/users/tests/tests_serializers.py
ealogar/servicedirectory
fb4f4bfa8b499b93c03af589ef2f34c08a830b17
[ "Apache-2.0" ]
null
null
null
servicedirectory/src/sd-api/users/tests/tests_serializers.py
ealogar/servicedirectory
fb4f4bfa8b499b93c03af589ef2f34c08a830b17
[ "Apache-2.0" ]
null
null
null
''' (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
52.784483
114
0.6634
13d7896d6d799cba6c0e766504d5f3eea5f2e531
3,124
py
Python
Web/notifyXAPI/app/src/users/views.py
abs0lut3pwn4g3/RootersCTF2019-challenges
397a6fad0b03e55541df06e5103172ae850cd4e5
[ "MIT" ]
14
2019-10-13T07:38:04.000Z
2022-02-13T09:03:50.000Z
Web/notifyXAPI/app/src/users/views.py
abs0lut3pwn4g3/RootersCTF2019-challenges
397a6fad0b03e55541df06e5103172ae850cd4e5
[ "MIT" ]
1
2019-10-13T07:35:13.000Z
2019-10-13T08:22:48.000Z
Web/notifyXAPI/app/src/users/views.py
abs0lut3pwn4g3/RootersCTF2019-challenges
397a6fad0b03e55541df06e5103172ae850cd4e5
[ "MIT" ]
4
2019-10-13T08:21:43.000Z
2022-01-09T16:39:33.000Z
''' 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')
40.571429
124
0.588348
13d7ee99520201ddee21c6a144be012df62e596b
14,211
py
Python
querybuilder/tests/window_tests.py
wesokes/django-query-builder
3cc53d33ee0a4ada515635e4be631167a774b457
[ "MIT" ]
110
2015-01-28T17:38:38.000Z
2022-02-17T02:51:55.000Z
querybuilder/tests/window_tests.py
wesokes/django-query-builder
3cc53d33ee0a4ada515635e4be631167a774b457
[ "MIT" ]
31
2015-02-17T19:57:29.000Z
2021-08-30T03:44:55.000Z
querybuilder/tests/window_tests.py
wesokes/django-query-builder
3cc53d33ee0a4ada515635e4be631167a774b457
[ "MIT" ]
33
2015-02-05T22:08:46.000Z
2021-12-06T08:12:49.000Z
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
33.916468
119
0.521779
13d92122cdb041cef0407b7567e1db27fbf5978f
676
py
Python
emoji/coffee.py
wbprice/ojimoji
7b1a8b5ed0062d1d52e151e7412e1131e3de7924
[ "MIT" ]
null
null
null
emoji/coffee.py
wbprice/ojimoji
7b1a8b5ed0062d1d52e151e7412e1131e3de7924
[ "MIT" ]
null
null
null
emoji/coffee.py
wbprice/ojimoji
7b1a8b5ed0062d1d52e151e7412e1131e3de7924
[ "MIT" ]
null
null
null
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]])
30.727273
39
0.426036
13d981ac5c1effe03cfb8f11663b3250b5130bd2
4,546
py
Python
dumpcode/npzbdt.py
gkfthddk/keras
46d96c65d69c39df298800336bbb4d867a2561fb
[ "MIT" ]
null
null
null
dumpcode/npzbdt.py
gkfthddk/keras
46d96c65d69c39df298800336bbb4d867a2561fb
[ "MIT" ]
null
null
null
dumpcode/npzbdt.py
gkfthddk/keras
46d96c65d69c39df298800336bbb4d867a2561fb
[ "MIT" ]
null
null
null
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))
38.525424
167
0.720853
13dbe7e355868c585eddb2ca7609fa83a2860aed
12,384
py
Python
rlenv/StockTradingEnv0.py
watchsea/RL-Stock
53bd13a1bd1760e082c6db2ad9b010adbc3a767b
[ "MIT" ]
null
null
null
rlenv/StockTradingEnv0.py
watchsea/RL-Stock
53bd13a1bd1760e082c6db2ad9b010adbc3a767b
[ "MIT" ]
null
null
null
rlenv/StockTradingEnv0.py
watchsea/RL-Stock
53bd13a1bd1760e082c6db2ad9b010adbc3a767b
[ "MIT" ]
null
null
null
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
41.69697
127
0.581476
13dd331f73864377a1d0952e862e552f50ab90bf
2,053
py
Python
processing/manager.py
mrfleap/us-population-heatmap
e3f1c5d8294716ff491c7b8b40adb77929f9aeee
[ "MIT" ]
null
null
null
processing/manager.py
mrfleap/us-population-heatmap
e3f1c5d8294716ff491c7b8b40adb77929f9aeee
[ "MIT" ]
null
null
null
processing/manager.py
mrfleap/us-population-heatmap
e3f1c5d8294716ff491c7b8b40adb77929f9aeee
[ "MIT" ]
null
null
null
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()
27.013158
103
0.632245
13ddb1c02b1ed46330b061450969494a2a48af52
794
py
Python
gen_data.py
kshoji6011/vehicleai
135de71cce65f4a61b42c49493ed356f2d512d6c
[ "MIT" ]
null
null
null
gen_data.py
kshoji6011/vehicleai
135de71cce65f4a61b42c49493ed356f2d512d6c
[ "MIT" ]
null
null
null
gen_data.py
kshoji6011/vehicleai
135de71cce65f4a61b42c49493ed356f2d512d6c
[ "MIT" ]
null
null
null
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)
24.8125
73
0.644836
13de3e4f691cb4b36cd9750b30e5106c02f72fb9
724
py
Python
app/main.py
immortel32/Sword_Sorcery_Story_Generator
7978dfc335813362b2d94c455b970f58421123c8
[ "MIT" ]
2
2021-04-01T00:50:22.000Z
2021-04-01T02:18:45.000Z
app/main.py
immortel32/Sword_Sorcery_Story_Generator
7978dfc335813362b2d94c455b970f58421123c8
[ "MIT" ]
1
2021-04-01T21:39:44.000Z
2021-04-01T21:39:44.000Z
app/main.py
immortel32/Sword_Sorcery_Story_Generator
7978dfc335813362b2d94c455b970f58421123c8
[ "MIT" ]
1
2021-04-01T01:03:33.000Z
2021-04-01T01:03:33.000Z
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 )
42.588235
84
0.809392
13ded3828a8c037ea4aa78b91386fb78512809eb
326
py
Python
tests/test-recipes/metadata/ignore_some_prefix_files/run_test.py
mbargull/conda-build
ebc56f48196774301863fecbe98a32a7ded6eb7e
[ "BSD-3-Clause" ]
null
null
null
tests/test-recipes/metadata/ignore_some_prefix_files/run_test.py
mbargull/conda-build
ebc56f48196774301863fecbe98a32a7ded6eb7e
[ "BSD-3-Clause" ]
null
null
null
tests/test-recipes/metadata/ignore_some_prefix_files/run_test.py
mbargull/conda-build
ebc56f48196774301863fecbe98a32a7ded6eb7e
[ "BSD-3-Clause" ]
null
null
null
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()
32.6
88
0.733129
13defa0932ab990d6739afd72d573b29bcd8a6e3
2,473
py
Python
distill.py
Lukeming-tsinghua/Interpretable-NN-for-IBD-diagnosis
5fb0fae774e010cdd6b63ff487a4528f0397647d
[ "MIT" ]
null
null
null
distill.py
Lukeming-tsinghua/Interpretable-NN-for-IBD-diagnosis
5fb0fae774e010cdd6b63ff487a4528f0397647d
[ "MIT" ]
null
null
null
distill.py
Lukeming-tsinghua/Interpretable-NN-for-IBD-diagnosis
5fb0fae774e010cdd6b63ff487a4528f0397647d
[ "MIT" ]
null
null
null
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)))
34.347222
89
0.632835
13df4c0e986f7c76ecd11c6a6721e985d305104d
7,597
py
Python
tests/TALTests/HTMLTests/TALAttributesTestCases.py
janbrohl/SimpleTAL
f5a3ddd9a74cf9af7356bb431513e3534717802d
[ "BSD-3-Clause" ]
5
2015-11-20T12:17:04.000Z
2021-03-19T13:49:33.000Z
tests/TALTests/HTMLTests/TALAttributesTestCases.py
mar10/SimpleTAL
f5a3ddd9a74cf9af7356bb431513e3534717802d
[ "BSD-3-Clause" ]
5
2015-09-20T12:55:23.000Z
2018-05-12T10:34:20.000Z
tests/TALTests/HTMLTests/TALAttributesTestCases.py
mar10/SimpleTAL
f5a3ddd9a74cf9af7356bb431513e3534717802d
[ "BSD-3-Clause" ]
1
2022-01-24T13:37:38.000Z
2022-01-24T13:37:38.000Z
#!/usr/bin/python # -*- coding: iso-8859-1 -*- # Copyright (c) 2016, Jan Brohl <[email protected]> # 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()
46.042424
162
0.65618
13dfb252487b62555c998999e6abd56dcb22612c
562
py
Python
iseq_prof/fasta.py
EBI-Metagenomics/iseq-prof
ca41a0f3aa1e70e59648bdc08b36da1ec76220ad
[ "MIT" ]
null
null
null
iseq_prof/fasta.py
EBI-Metagenomics/iseq-prof
ca41a0f3aa1e70e59648bdc08b36da1ec76220ad
[ "MIT" ]
null
null
null
iseq_prof/fasta.py
EBI-Metagenomics/iseq-prof
ca41a0f3aa1e70e59648bdc08b36da1ec76220ad
[ "MIT" ]
null
null
null
from pathlib import Path from typing import List from fasta_reader import FASTAItem, FASTAWriter, read_fasta __all__ = ["downsample"]
29.578947
71
0.715302
13e04df35258103610f99481901f9649956a3c76
209
py
Python
src/data_settings.py
DhruvSrikanth/TSLA-React
2ce4edb6b21ec1a301047124cfda5bb30deb3a90
[ "MIT" ]
null
null
null
src/data_settings.py
DhruvSrikanth/TSLA-React
2ce4edb6b21ec1a301047124cfda5bb30deb3a90
[ "MIT" ]
null
null
null
src/data_settings.py
DhruvSrikanth/TSLA-React
2ce4edb6b21ec1a301047124cfda5bb30deb3a90
[ "MIT" ]
null
null
null
# 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
20.9
81
0.732057
13e067146d5c409e953e8fe9a97ca674f7b0976f
2,217
py
Python
ymir/backend/src/ymir_controller/controller/utils/invoker_mapping.py
phoenix-xhuang/ymir
537d3ac389c4a365ce4daef431c95b42ddcd5b1b
[ "Apache-2.0" ]
64
2021-11-15T03:48:00.000Z
2022-03-25T07:08:46.000Z
ymir/backend/src/ymir_controller/controller/utils/invoker_mapping.py
phoenix-xhuang/ymir
537d3ac389c4a365ce4daef431c95b42ddcd5b1b
[ "Apache-2.0" ]
35
2021-11-23T04:14:35.000Z
2022-03-26T09:03:43.000Z
ymir/backend/src/ymir_controller/controller/utils/invoker_mapping.py
phoenix-xhuang/ymir
537d3ac389c4a365ce4daef431c95b42ddcd5b1b
[ "Apache-2.0" ]
57
2021-11-11T10:15:40.000Z
2022-03-29T07:27:54.000Z
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, }
43.470588
87
0.834461
13e0862967d39493794d0afe2c6e9020dad2d87c
777
py
Python
tests/utils/date_utils.py
asuol/worky
362257e77486af05941cc977055c01e49b09a2dd
[ "MIT" ]
null
null
null
tests/utils/date_utils.py
asuol/worky
362257e77486af05941cc977055c01e49b09a2dd
[ "MIT" ]
null
null
null
tests/utils/date_utils.py
asuol/worky
362257e77486af05941cc977055c01e49b09a2dd
[ "MIT" ]
null
null
null
from datetime import datetime, timedelta due_date_format = '%Y-%m-%d' datepicker_date_format = '%m%d%Y'
25.064516
78
0.776062
13e0ca25df4bf90f8ba82de1f47aa08f14078d33
5,304
py
Python
numba/roc/tests/hsapy/test_gufuncbuilding.py
luk-f-a/numba
3a682bd827e416335e3574bc7b10f0ec69adb701
[ "BSD-2-Clause", "BSD-3-Clause" ]
76
2020-07-06T14:44:05.000Z
2022-02-14T15:30:21.000Z
numba/roc/tests/hsapy/test_gufuncbuilding.py
luk-f-a/numba
3a682bd827e416335e3574bc7b10f0ec69adb701
[ "BSD-2-Clause", "BSD-3-Clause" ]
108
2020-08-17T22:38:26.000Z
2021-12-06T09:44:14.000Z
numba/roc/tests/hsapy/test_gufuncbuilding.py
luk-f-a/numba
3a682bd827e416335e3574bc7b10f0ec69adb701
[ "BSD-2-Clause", "BSD-3-Clause" ]
11
2020-07-12T16:18:07.000Z
2022-02-05T16:48:35.000Z
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()
31.951807
75
0.532805
13e10f247a53a809b100dc05b97804f51f30b05a
463
py
Python
server/form/mongo.py
SRM-IST-KTR/ossmosis
06e375dfdd67f91286ffbcb13e04b6543585d8ad
[ "MIT" ]
6
2021-07-04T07:59:17.000Z
2021-07-04T14:41:00.000Z
server/form/mongo.py
SRM-IST-KTR/ossmosis
06e375dfdd67f91286ffbcb13e04b6543585d8ad
[ "MIT" ]
null
null
null
server/form/mongo.py
SRM-IST-KTR/ossmosis
06e375dfdd67f91286ffbcb13e04b6543585d8ad
[ "MIT" ]
1
2022-02-15T13:31:46.000Z
2022-02-15T13:31:46.000Z
import os from pymongo import MongoClient from dotenv import load_dotenv if __name__ == "__main__": pass
21.045455
52
0.637149
13e1722808236b6aeebbdaf4b408b6e5d0b9cadb
738
py
Python
control-flow/solution/file_hosts.py
giserh/book-python
ebd4e70cea1dd56986aa8efbae3629ba3f1ba087
[ "MIT" ]
1
2019-01-02T15:04:08.000Z
2019-01-02T15:04:08.000Z
control-flow/solution/file_hosts.py
giserh/book-python
ebd4e70cea1dd56986aa8efbae3629ba3f1ba087
[ "MIT" ]
null
null
null
control-flow/solution/file_hosts.py
giserh/book-python
ebd4e70cea1dd56986aa8efbae3629ba3f1ba087
[ "MIT" ]
null
null
null
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)
19.421053
56
0.550136
13e172837fb61cdf3f4fe7914fb4c72959b8c9f8
497
py
Python
zindi/docs/utils/n_subimissions_per_day.py
eaedk/testing-zindi-package
5aef7375a629b328fa8ecf9c4559e2897611a1e9
[ "MIT" ]
6
2020-09-07T17:56:49.000Z
2021-12-09T12:34:01.000Z
zindi/docs/utils/n_subimissions_per_day.py
eaedk/testing-zindi-package
5aef7375a629b328fa8ecf9c4559e2897611a1e9
[ "MIT" ]
2
2021-02-24T11:56:48.000Z
2021-03-30T14:40:45.000Z
zindi/docs/utils/n_subimissions_per_day.py
eaedk/testing-zindi-package
5aef7375a629b328fa8ecf9c4559e2897611a1e9
[ "MIT" ]
4
2020-11-01T00:06:36.000Z
2021-11-19T19:20:52.000Z
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. """
35.5
84
0.629779
13e274ea10a3039f67d424845564d23d8affb74d
2,875
py
Python
algo/test/test_maximum_cut.py
ssavinash1/Algorithm_stanford
f2588b6bcac2b0858e78b819e6e8402109e80ee2
[ "MIT" ]
24
2016-03-21T07:53:54.000Z
2020-06-29T12:16:36.000Z
algo/test/test_maximum_cut.py
ssavinash1/Algorithm_stanford
f2588b6bcac2b0858e78b819e6e8402109e80ee2
[ "MIT" ]
5
2015-09-29T17:12:36.000Z
2020-03-26T20:51:56.000Z
algo/test/test_maximum_cut.py
ssavinash1/Algorithm_stanford
f2588b6bcac2b0858e78b819e6e8402109e80ee2
[ "MIT" ]
12
2016-05-24T16:48:32.000Z
2020-10-02T12:22:09.000Z
# -*- coding: utf-8 -*- import unittest from src.graph import Graph from src.maximum_cut import maximum_cut, maximum_cut_for_bipartite_graph
33.823529
79
0.420522
13e34fac65209ea50100d76fe6090282f3d8e3b4
5,788
py
Python
gdb/print-avs-rbtree.py
kemonats/avs_commons
ecce4edf5376d132e3686af227c9adf22ce1090e
[ "Apache-2.0" ]
4
2016-11-04T12:55:32.000Z
2019-03-21T15:07:58.000Z
gdb/print-avs-rbtree.py
kemonats/avs_commons
ecce4edf5376d132e3686af227c9adf22ce1090e
[ "Apache-2.0" ]
5
2015-02-11T09:34:36.000Z
2021-04-19T08:51:50.000Z
gdb/print-avs-rbtree.py
kemonats/avs_commons
ecce4edf5376d132e3686af227c9adf22ce1090e
[ "Apache-2.0" ]
17
2015-12-17T10:32:09.000Z
2022-02-14T10:58:39.000Z
# -*- coding: utf-8 -*- # # Copyright 2021 AVSystem <[email protected]> # # 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()
37.102564
146
0.593988
13e3573ef0ab92fc261e9835b12be4ef8345103f
1,372
py
Python
hour17/PythonGroup.py
sampx/mongodb-practice
0698b21b7da57693ba4146384c8ad65530b0066b
[ "MIT" ]
null
null
null
hour17/PythonGroup.py
sampx/mongodb-practice
0698b21b7da57693ba4146384c8ad65530b0066b
[ "MIT" ]
null
null
null
hour17/PythonGroup.py
sampx/mongodb-practice
0698b21b7da57693ba4146384c8ad65530b0066b
[ "MIT" ]
null
null
null
from pymongo import MongoClient if __name__=="__main__": mongo = MongoClient('mongodb://localhost:27017/') db = mongo['words'] collection = db['word_stats'] firstIsALastIsVowel(collection) firstLetterTotals(collection)
39.2
69
0.54519
13e4eede3d6e6a6be8776d50a9b969b677e1d046
5,115
py
Python
packnet_sfm/models/model_utils.py
pection/packnet-sfm
d5673567b649e6bfda292c894cacdeb06aa80913
[ "MIT" ]
1
2022-02-22T06:19:02.000Z
2022-02-22T06:19:02.000Z
packnet_sfm/models/model_utils.py
pection/packnet-sfm
d5673567b649e6bfda292c894cacdeb06aa80913
[ "MIT" ]
null
null
null
packnet_sfm/models/model_utils.py
pection/packnet-sfm
d5673567b649e6bfda292c894cacdeb06aa80913
[ "MIT" ]
null
null
null
# 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
28.259669
93
0.585728
13e58721f5e2c382c66ef605548dfd06ad0e1f44
1,363
py
Python
utils/stg/min_jerk_traj.py
dgerod/more-dmps
4dc886a138f289532b2672537f91ff857448ad27
[ "BSD-2-Clause" ]
7
2017-12-23T13:43:33.000Z
2021-08-21T14:50:55.000Z
utils/stg/min_jerk_traj.py
dgerod/more-dmps
4dc886a138f289532b2672537f91ff857448ad27
[ "BSD-2-Clause" ]
1
2016-08-21T05:05:32.000Z
2016-08-21T05:05:32.000Z
utils/stg/min_jerk_traj.py
dgerod/more-dmps
4dc886a138f289532b2672537f91ff857448ad27
[ "BSD-2-Clause" ]
2
2018-02-11T02:01:32.000Z
2019-09-16T01:43:43.000Z
''' Created on 25.07.2012 @author: karl '''
24.781818
96
0.533382
13e5f9585262ddf6bd1e3799d8611f18effa881a
40
py
Python
tests/__init__.py
karanrampal/triplet-loss
b62008dedbf8640ccf0dc359b5aadd5e8b0ab134
[ "MIT" ]
null
null
null
tests/__init__.py
karanrampal/triplet-loss
b62008dedbf8640ccf0dc359b5aadd5e8b0ab134
[ "MIT" ]
null
null
null
tests/__init__.py
karanrampal/triplet-loss
b62008dedbf8640ccf0dc359b5aadd5e8b0ab134
[ "MIT" ]
null
null
null
# To make directory as a python package
20
39
0.775
13e74a7f98e6571f4fc714e2743e38c7eafbf58e
2,607
py
Python
orthoexon/tests/test_util.py
jessicalettes/orthoexon
463ad1908364c602cf75dbddb0b16a42f4100a36
[ "BSD-3-Clause" ]
null
null
null
orthoexon/tests/test_util.py
jessicalettes/orthoexon
463ad1908364c602cf75dbddb0b16a42f4100a36
[ "BSD-3-Clause" ]
null
null
null
orthoexon/tests/test_util.py
jessicalettes/orthoexon
463ad1908364c602cf75dbddb0b16a42f4100a36
[ "BSD-3-Clause" ]
null
null
null
#!/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
23.917431
86
0.678558
13e8cb3c3e9246762451e5cb22ca74f1dccc3db7
2,656
py
Python
predict_recognition.py
yeyupiaoling/Kersa-Speaker-Recognition
7ccf42c006f42ff6074ad3937e44a0dfa68c6d33
[ "Apache-2.0" ]
42
2020-07-12T13:21:13.000Z
2021-07-01T01:06:12.000Z
predict_recognition.py
yeyupiaoling/VoiceprintRecognition-Keras
7ccf42c006f42ff6074ad3937e44a0dfa68c6d33
[ "Apache-2.0" ]
3
2020-08-19T06:16:02.000Z
2020-11-02T02:16:56.000Z
predict_recognition.py
yeyupiaoling/Kersa-Speaker-Recognition
7ccf42c006f42ff6074ad3937e44a0dfa68c6d33
[ "Apache-2.0" ]
12
2020-07-15T14:33:51.000Z
2021-05-24T03:55:04.000Z
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('')
28.255319
103
0.628765
13e90500b4879323474a6761d01dbd32906a8b6c
6,853
py
Python
cubedash/_product.py
vconrado/datacube-explorer
ccb9a9a42e5dd16e2b0325a1f881b080bb2806e6
[ "Apache-2.0" ]
null
null
null
cubedash/_product.py
vconrado/datacube-explorer
ccb9a9a42e5dd16e2b0325a1f881b080bb2806e6
[ "Apache-2.0" ]
null
null
null
cubedash/_product.py
vconrado/datacube-explorer
ccb9a9a42e5dd16e2b0325a1f881b080bb2806e6
[ "Apache-2.0" ]
null
null
null
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)
27.522088
86
0.620604
13e960260e528ba2d92aa2f22ba8b6f12cf5bbfe
1,923
py
Python
litex_boards/platforms/sipeed_tang_nano.py
ozbenh/litex-boards
f18b10d1edb4e162a77972e2e9c5bad54ca00788
[ "BSD-2-Clause" ]
null
null
null
litex_boards/platforms/sipeed_tang_nano.py
ozbenh/litex-boards
f18b10d1edb4e162a77972e2e9c5bad54ca00788
[ "BSD-2-Clause" ]
null
null
null
litex_boards/platforms/sipeed_tang_nano.py
ozbenh/litex-boards
f18b10d1edb4e162a77972e2e9c5bad54ca00788
[ "BSD-2-Clause" ]
null
null
null
# # This file is part of LiteX-Boards. # # Copyright (c) 2021 Florent Kermarrec <[email protected]> # 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 -----------------------------------------------------------------------------------------
32.05
115
0.573583
13eaaea3944207924e8d3d8e8f4c1a6a0ee51732
10,525
py
Python
nm_cavia/rl/metalearner.py
anon-6994/nm-metarl
45c8798c2139d8c200cc7a398331c1b98a0dccec
[ "MIT" ]
null
null
null
nm_cavia/rl/metalearner.py
anon-6994/nm-metarl
45c8798c2139d8c200cc7a398331c1b98a0dccec
[ "MIT" ]
null
null
null
nm_cavia/rl/metalearner.py
anon-6994/nm-metarl
45c8798c2139d8c200cc7a398331c1b98a0dccec
[ "MIT" ]
null
null
null
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)
40.171756
120
0.624323
13eac7b96baca5f54a52331a42d7e035d905943e
2,321
py
Python
request/management/commands/purgerequests.py
hramezani/django-request
4b9c7b22f26338d2c93110477aa44041b1c5ddb4
[ "BSD-2-Clause" ]
373
2016-04-22T21:18:41.000Z
2022-03-31T23:13:31.000Z
request/management/commands/purgerequests.py
hramezani/django-request
4b9c7b22f26338d2c93110477aa44041b1c5ddb4
[ "BSD-2-Clause" ]
128
2016-04-22T21:30:55.000Z
2022-03-08T20:24:44.000Z
request/management/commands/purgerequests.py
hramezani/django-request
4b9c7b22f26338d2c93110477aa44041b1c5ddb4
[ "BSD-2-Clause" ]
79
2016-04-25T08:44:56.000Z
2022-03-17T01:41:27.000Z
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
30.142857
88
0.623007
13ebac2480a38d6864e7de863e165c5d96c0e1f7
10,928
py
Python
tests/test_crypto.py
kimtaehong/PythonForWindows
d04eed1754e2e23474213b89580d68e1b73c3fe4
[ "BSD-3-Clause" ]
null
null
null
tests/test_crypto.py
kimtaehong/PythonForWindows
d04eed1754e2e23474213b89580d68e1b73c3fe4
[ "BSD-3-Clause" ]
null
null
null
tests/test_crypto.py
kimtaehong/PythonForWindows
d04eed1754e2e23474213b89580d68e1b73c3fe4
[ "BSD-3-Clause" ]
null
null
null
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="""
45.344398
132
0.811585
13ec7c22478f599c0c77b64f3478dbd3b142fa61
8,135
py
Python
cdci_data_analysis/analysis/plot_tools.py
andreatramacere/cdci_data_analysis
8ae34a7252d6baf011a3b99fbe4f6e624b63d7df
[ "MIT" ]
null
null
null
cdci_data_analysis/analysis/plot_tools.py
andreatramacere/cdci_data_analysis
8ae34a7252d6baf011a3b99fbe4f6e624b63d7df
[ "MIT" ]
null
null
null
cdci_data_analysis/analysis/plot_tools.py
andreatramacere/cdci_data_analysis
8ae34a7252d6baf011a3b99fbe4f6e624b63d7df
[ "MIT" ]
null
null
null
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
31.288462
132
0.547019
13edd551b75e71fd96ef5d443c0c54bbec028a56
844
py
Python
test/unit/test_testaid_unit_pathlist.py
RebelCodeBase/testaid
998c827b826fe4374ecf0a234fef61a975e2fcd7
[ "Apache-2.0" ]
17
2019-08-04T09:29:19.000Z
2020-05-16T02:25:20.000Z
test/unit/test_testaid_unit_pathlist.py
RebelCodeBase/testaid
998c827b826fe4374ecf0a234fef61a975e2fcd7
[ "Apache-2.0" ]
12
2019-07-19T22:20:42.000Z
2020-01-20T06:45:38.000Z
test/unit/test_testaid_unit_pathlist.py
RebelCodeBase/testaid
998c827b826fe4374ecf0a234fef61a975e2fcd7
[ "Apache-2.0" ]
3
2019-08-08T18:18:13.000Z
2019-10-07T13:46:03.000Z
from pathlib import Path from testaid.pathlist import PathList
29.103448
73
0.726303
13ee6c7b533dc2afb81ce7087fea00c547679671
22,147
py
Python
tests/unit/zhmcclient/test_hba.py
vkpro-forks/python-zhmcclient
eab2dca37cb417d03411450dabf72805214b5ca0
[ "Apache-2.0" ]
null
null
null
tests/unit/zhmcclient/test_hba.py
vkpro-forks/python-zhmcclient
eab2dca37cb417d03411450dabf72805214b5ca0
[ "Apache-2.0" ]
null
null
null
tests/unit/zhmcclient/test_hba.py
vkpro-forks/python-zhmcclient
eab2dca37cb417d03411450dabf72805214b5ca0
[ "Apache-2.0" ]
null
null
null
# 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
34.658842
77
0.557457
13ef6d428251649b315fbe8757c2d7336d7471a8
367
py
Python
compiler-rt/test/asan/TestCases/Windows/lit.local.cfg.py
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
compiler-rt/test/asan/TestCases/Windows/lit.local.cfg.py
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
compiler-rt/test/asan/TestCases/Windows/lit.local.cfg.py
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
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
24.466667
76
0.73842
13efdb45818b7da3afae845201256a86d37c940d
4,302
py
Python
Lib/test/libregrtest/utils.py
oskomorokhov/cpython
c0e11a3ceb9427e09db4224f394c7789bf6deec5
[ "0BSD" ]
5
2017-08-25T04:31:30.000Z
2022-03-22T15:01:56.000Z
Lib/test/libregrtest/utils.py
oskomorokhov/cpython
c0e11a3ceb9427e09db4224f394c7789bf6deec5
[ "0BSD" ]
20
2021-03-25T12:52:42.000Z
2022-03-01T02:02:03.000Z
Lib/test/libregrtest/utils.py
oskomorokhov/cpython
c0e11a3ceb9427e09db4224f394c7789bf6deec5
[ "0BSD" ]
3
2020-04-13T14:41:31.000Z
2022-03-02T18:56:32.000Z
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
22.761905
75
0.600418
13f22ca29da54a0f4486e1f8539ee236d259fc1e
5,960
py
Python
efetch_server/plugins/fa_sqlite/fa_sqlite_ajax.py
Syrkadian/efetch
120ac963507d54998beecfd8b8cd85ad123e6e54
[ "Apache-2.0" ]
38
2015-08-18T00:29:16.000Z
2021-12-06T15:53:47.000Z
efetch_server/plugins/fa_sqlite/fa_sqlite_ajax.py
Syrkadian/efetch
120ac963507d54998beecfd8b8cd85ad123e6e54
[ "Apache-2.0" ]
20
2016-03-18T02:20:27.000Z
2020-04-09T22:16:42.000Z
efetch_server/plugins/fa_sqlite/fa_sqlite_ajax.py
Syrkadian/efetch
120ac963507d54998beecfd8b8cd85ad123e6e54
[ "Apache-2.0" ]
8
2016-08-23T14:59:15.000Z
2020-04-09T21:43:25.000Z
""" AJAX for SQLite Viewer plugin """ from yapsy.IPlugin import IPlugin from flask import Response, jsonify import json import logging import sqlite3
35.266272
133
0.51896
13f2af320410f86bedc3a6ddc8c44eb547f14053
252
py
Python
raspagem/random/lista_cidades.py
sslppractice/propython
fa470c3bf0dcfbb26037146d77c7491596cabb26
[ "MIT" ]
null
null
null
raspagem/random/lista_cidades.py
sslppractice/propython
fa470c3bf0dcfbb26037146d77c7491596cabb26
[ "MIT" ]
null
null
null
raspagem/random/lista_cidades.py
sslppractice/propython
fa470c3bf0dcfbb26037146d77c7491596cabb26
[ "MIT" ]
null
null
null
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)
22.909091
57
0.734127
13f387c5b382d039623c959bbf8db86a94b8f10b
29
py
Python
mezzanine/__init__.py
startupgrind/mezzanine
23d24a07c69bf8f02d60148b0b8da6c76bc5061e
[ "BSD-2-Clause" ]
null
null
null
mezzanine/__init__.py
startupgrind/mezzanine
23d24a07c69bf8f02d60148b0b8da6c76bc5061e
[ "BSD-2-Clause" ]
3
2019-02-18T07:52:41.000Z
2021-03-31T03:51:11.000Z
mezzanine/__init__.py
startupgrind/mezzanine
23d24a07c69bf8f02d60148b0b8da6c76bc5061e
[ "BSD-2-Clause" ]
null
null
null
__version__ = "4.3.1.post1"
9.666667
27
0.655172
13f3a6d9012ba4c4473a1ffb1f1db1418326ee1f
7,566
py
Python
src/autonomous/purepursuit.py
Sloomey/DeepSpace2019
dda035c0ac100209b03a2ff04d86df09c6de9a85
[ "MIT" ]
null
null
null
src/autonomous/purepursuit.py
Sloomey/DeepSpace2019
dda035c0ac100209b03a2ff04d86df09c6de9a85
[ "MIT" ]
null
null
null
src/autonomous/purepursuit.py
Sloomey/DeepSpace2019
dda035c0ac100209b03a2ff04d86df09c6de9a85
[ "MIT" ]
null
null
null
import math from constants import Constants from utils import vector2d from wpilib import SmartDashboard as Dash from autonomous import pursuitpoint
50.10596
178
0.655432
13f4c5d6b839fc74a59e3720afa044833541c6ea
8,661
py
Python
esphome/voluptuous_schema.py
TheEggi/esphomeyaml
98e8cc1edc7b29891e8100eb484922e5c2d4fc33
[ "MIT" ]
null
null
null
esphome/voluptuous_schema.py
TheEggi/esphomeyaml
98e8cc1edc7b29891e8100eb484922e5c2d4fc33
[ "MIT" ]
null
null
null
esphome/voluptuous_schema.py
TheEggi/esphomeyaml
98e8cc1edc7b29891e8100eb484922e5c2d4fc33
[ "MIT" ]
null
null
null
import difflib import itertools import voluptuous as vol from esphome.py_compat import string_types # pylint: disable=protected-access, unidiomatic-typecheck
43.305
99
0.564831
13f5928fe05ccf64858c18af5eff2188153c32e0
20,738
py
Python
semisupervised/DensityPeaks.py
dpr1005/Semisupervised-learning-and-instance-selection-methods
646d9e729c85322e859928e71a3241f2aec6d93d
[ "MIT" ]
3
2021-12-10T09:04:18.000Z
2022-01-22T15:03:19.000Z
semisupervised/DensityPeaks.py
dpr1005/Semisupervised-learning-and-instance-selection-methods
646d9e729c85322e859928e71a3241f2aec6d93d
[ "MIT" ]
107
2021-12-02T07:43:11.000Z
2022-03-31T11:02:46.000Z
semisupervised/DensityPeaks.py
dpr1005/Semisupervised-learning-and-instance-selection-methods
646d9e729c85322e859928e71a3241f2aec6d93d
[ "MIT" ]
null
null
null
#!/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
35.268707
86
0.580384
13f713d62e74a1cd787ec98b134812d16f5287ea
933
py
Python
N-aryTreeLevelOrderTraversal429.py
Bit64L/LeetCode-Python-
64847cbb1adcaca4561b949e8acc52e8e031a6cb
[ "MIT" ]
null
null
null
N-aryTreeLevelOrderTraversal429.py
Bit64L/LeetCode-Python-
64847cbb1adcaca4561b949e8acc52e8e031a6cb
[ "MIT" ]
null
null
null
N-aryTreeLevelOrderTraversal429.py
Bit64L/LeetCode-Python-
64847cbb1adcaca4561b949e8acc52e8e031a6cb
[ "MIT" ]
null
null
null
""" # Definition for a Node. """ node2 = TreeNode(2, []) node3 = TreeNode(3, []) children = [node2, node3] node1 = TreeNode(1, children) solution = Solution() print(solution.levelOrder(node1))
20.733333
39
0.485531
13f7593938a4204f0e27844ca0c493ca0b47ec5f
16,444
py
Python
plugin.video.team.milhanos/websocket/_core.py
akuala/REPO.KUALA
ea9a157025530d2ce8fa0d88431c46c5352e89d4
[ "Apache-2.0" ]
2
2018-11-02T19:55:30.000Z
2020-08-14T02:22:20.000Z
venv/lib/python3.5/site-packages/websocket/_core.py
dukakisxyz/wifiportal21-map
1f1917c2f3c2987f7a88cc537d7c50449d144ea0
[ "MIT" ]
null
null
null
venv/lib/python3.5/site-packages/websocket/_core.py
dukakisxyz/wifiportal21-map
1f1917c2f3c2987f7a88cc537d7c50449d144ea0
[ "MIT" ]
3
2019-12-17T20:47:00.000Z
2021-02-11T19:03:59.000Z
""" 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
33.490835
90
0.589698
13f7ddb9a41846fb5799958db3fabf2ed4eeb64a
3,105
py
Python
vaccine_card/logistic/models.py
Unanimad/lais_046_2020_etapa_2
630efc6b25a580be44b6cd50be6744a01221a2c4
[ "Apache-2.0" ]
null
null
null
vaccine_card/logistic/models.py
Unanimad/lais_046_2020_etapa_2
630efc6b25a580be44b6cd50be6744a01221a2c4
[ "Apache-2.0" ]
null
null
null
vaccine_card/logistic/models.py
Unanimad/lais_046_2020_etapa_2
630efc6b25a580be44b6cd50be6744a01221a2c4
[ "Apache-2.0" ]
null
null
null
from django.db import models from vaccine_card.vaccination.models import Vaccine
36.104651
111
0.738808
13f954a55ebaa879400311cfe5c32a3993b29137
12,933
py
Python
test/test_rimuhosting.py
shenoyn/libcloud
bd902992a658b6a99193d69323e051ffa7388253
[ "Apache-2.0" ]
1
2015-11-08T12:59:27.000Z
2015-11-08T12:59:27.000Z
test/test_rimuhosting.py
shenoyn/libcloud
bd902992a658b6a99193d69323e051ffa7388253
[ "Apache-2.0" ]
null
null
null
test/test_rimuhosting.py
shenoyn/libcloud
bd902992a658b6a99193d69323e051ffa7388253
[ "Apache-2.0" ]
null
null
null
# 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
45.22028
380
0.540478
13f9663c3671ee791e1374fc1c550b7438edff48
1,033
py
Python
tests/base_tests/polygon_tests/test_contains.py
lycantropos/gon
b3f811ece5989d1623b17d633a84071fbff6dd69
[ "MIT" ]
10
2020-07-18T12:55:52.000Z
2022-03-20T07:09:10.000Z
tests/base_tests/polygon_tests/test_contains.py
lycantropos/gon
b3f811ece5989d1623b17d633a84071fbff6dd69
[ "MIT" ]
52
2019-07-11T16:59:01.000Z
2022-03-29T19:41:59.000Z
tests/base_tests/polygon_tests/test_contains.py
lycantropos/gon
b3f811ece5989d1623b17d633a84071fbff6dd69
[ "MIT" ]
1
2020-03-22T12:56:07.000Z
2020-03-22T12:56:07.000Z
from typing import Tuple from hypothesis import given from gon.base import (Point, Polygon) from tests.utils import (equivalence, implication) from . import strategies
26.487179
72
0.708616
b913259774170b0ae117752589cf379fac40286c
4,139
py
Python
easyidp/core/tests/test_class_reconsproject.py
HowcanoeWang/EasyIDP
0d0a0df1287e3c15cda17e8e4cdcbe05f21f7272
[ "MIT" ]
null
null
null
easyidp/core/tests/test_class_reconsproject.py
HowcanoeWang/EasyIDP
0d0a0df1287e3c15cda17e8e4cdcbe05f21f7272
[ "MIT" ]
null
null
null
easyidp/core/tests/test_class_reconsproject.py
HowcanoeWang/EasyIDP
0d0a0df1287e3c15cda17e8e4cdcbe05f21f7272
[ "MIT" ]
null
null
null
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")
42.234694
112
0.723846
b9139bb412d2bf193e04d2282744a0d621a61a94
2,413
py
Python
withings_api/const.py
tiloc/python_withings_api
64c9706ab70c93e4c54cc843a778ecd3f9960980
[ "MIT" ]
null
null
null
withings_api/const.py
tiloc/python_withings_api
64c9706ab70c93e4c54cc843a778ecd3f9960980
[ "MIT" ]
null
null
null
withings_api/const.py
tiloc/python_withings_api
64c9706ab70c93e4c54cc843a778ecd3f9960980
[ "MIT" ]
null
null
null
"""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,)
9.690763
50
0.390385
b9141fcf42d65abf107a484255f641db4d6e639b
3,249
py
Python
examples/canvas/bezier.py
sirpercival/kivy
29ef854a200e6764aae60ea29324379c69d271a3
[ "MIT" ]
2
2015-10-26T12:35:37.000Z
2020-11-26T12:06:09.000Z
examples/canvas/bezier.py
sirpercival/kivy
29ef854a200e6764aae60ea29324379c69d271a3
[ "MIT" ]
null
null
null
examples/canvas/bezier.py
sirpercival/kivy
29ef854a200e6764aae60ea29324379c69d271a3
[ "MIT" ]
3
2015-07-18T11:03:59.000Z
2018-03-17T01:32:42.000Z
#!/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()
33.84375
82
0.544783
b915c0a9f384ec67869ab91a6425fc1e66fbe2a2
2,698
py
Python
tests/bugs/core_6489_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
tests/bugs/core_6489_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
tests/bugs/core_6489_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
#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 """
32.902439
124
0.648258
b915eeed88fbfbe46318454fd21bc9db43d6d639
6,023
py
Python
utils/utils_bbox.py
MasoonZhang/FasterRConvMixer
a7a17d00f716a28a5b301088053e00840c222524
[ "MIT" ]
null
null
null
utils/utils_bbox.py
MasoonZhang/FasterRConvMixer
a7a17d00f716a28a5b301088053e00840c222524
[ "MIT" ]
null
null
null
utils/utils_bbox.py
MasoonZhang/FasterRConvMixer
a7a17d00f716a28a5b301088053e00840c222524
[ "MIT" ]
1
2022-03-14T05:29:42.000Z
2022-03-14T05:29:42.000Z
import numpy as np import torch from torch.nn import functional as F from torchvision.ops import nms
45.628788
136
0.381205
b9160a13d47cfdacbbfdb45a0590f6674809ddbe
96
py
Python
lib/python/test/__init__.py
woozhijun/cat
3d523202c38e37b1a2244b26d4336ebbea5db001
[ "Apache-2.0" ]
17,318
2015-01-03T03:02:07.000Z
2022-03-31T02:43:28.000Z
lib/python/test/__init__.py
MrCoderYu/cat
674bd9ab70267dd6fc74879e4344af77397f4acd
[ "Apache-2.0" ]
1,162
2015-01-04T08:23:49.000Z
2022-03-31T15:38:04.000Z
lib/python/test/__init__.py
MrCoderYu/cat
674bd9ab70267dd6fc74879e4344af77397f4acd
[ "Apache-2.0" ]
5,520
2015-01-03T03:02:07.000Z
2022-03-31T16:16:56.000Z
#!/usr/bin/env python # encoding: utf-8 import sys reload(sys) sys.setdefaultencoding("utf-8")
13.714286
31
0.729167
b918984647c67e09bce945847905654d35530277
15,886
py
Python
tests/test_pyclipper.py
odidev/pyclipper
3de54fa4c4d5b8efeede364fbe69336f935f88f2
[ "MIT" ]
null
null
null
tests/test_pyclipper.py
odidev/pyclipper
3de54fa4c4d5b8efeede364fbe69336f935f88f2
[ "MIT" ]
null
null
null
tests/test_pyclipper.py
odidev/pyclipper
3de54fa4c4d5b8efeede364fbe69336f935f88f2
[ "MIT" ]
null
null
null
#!/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()
34.914286
111
0.660078
b918bb151415e9d667f5286334be578684cceb18
10,754
py
Python
espoem_facts/facts.py
emre/espoem_facts
0d7164dcfe8a82e1f142929b1e00c3a85f29f101
[ "MIT" ]
null
null
null
espoem_facts/facts.py
emre/espoem_facts
0d7164dcfe8a82e1f142929b1e00c3a85f29f101
[ "MIT" ]
null
null
null
espoem_facts/facts.py
emre/espoem_facts
0d7164dcfe8a82e1f142929b1e00c3a85f29f101
[ "MIT" ]
1
2018-07-19T18:44:09.000Z
2018-07-19T18:44:09.000Z
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."]
102.419048
232
0.702343
b918c27f2b168efd69908773e44475244b686dd0
3,379
py
Python
imageproc_OE_IF_quant/2_annotate_extracted_cells.py
hshayya/2022_Shayya_UPR_Guidance
b9a305a147a105c3ac9c0173e06b94f66e4a6102
[ "MIT" ]
null
null
null
imageproc_OE_IF_quant/2_annotate_extracted_cells.py
hshayya/2022_Shayya_UPR_Guidance
b9a305a147a105c3ac9c0173e06b94f66e4a6102
[ "MIT" ]
null
null
null
imageproc_OE_IF_quant/2_annotate_extracted_cells.py
hshayya/2022_Shayya_UPR_Guidance
b9a305a147a105c3ac9c0173e06b94f66e4a6102
[ "MIT" ]
null
null
null
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.
40.710843
137
0.693992
b919ab13ac46e733a617fc950c062280033c20b8
439
py
Python
MAEnv/env_SingleCatchPigs/test_SingleCatchPigs.py
Abluceli/Multi-agent-Reinforcement-Learning-Algorithms
15810a559e2f2cf9e5fcb158c083f9e9dd6012fc
[ "MIT" ]
5
2020-05-25T03:08:09.000Z
2022-02-27T05:57:28.000Z
MAEnv/env_SingleCatchPigs/test_SingleCatchPigs.py
Abluceli/Multi-agent-Reinforcement-Learning-Algorithms
15810a559e2f2cf9e5fcb158c083f9e9dd6012fc
[ "MIT" ]
1
2020-12-22T01:35:36.000Z
2022-01-28T01:51:06.000Z
MAEnv/env_SingleCatchPigs/test_SingleCatchPigs.py
Abluceli/Multi-agent-Reinforcement-Learning-Algorithms
15810a559e2f2cf9e5fcb158c083f9e9dd6012fc
[ "MIT" ]
1
2020-05-06T01:56:55.000Z
2020-05-06T01:56:55.000Z
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)
24.388889
50
0.658314
b91c1523d70c0416c1afa5a4c6a25a3d2f1e426b
3,417
py
Python
eust/tables/data.py
rasmuse/eust
2138076d52c0ffa20fba10e4e0319dd50c4e8a91
[ "MIT" ]
1
2021-03-14T04:06:02.000Z
2021-03-14T04:06:02.000Z
eust/tables/data.py
rasmuse/eust
2138076d52c0ffa20fba10e4e0319dd50c4e8a91
[ "MIT" ]
9
2019-04-29T09:01:39.000Z
2021-11-15T17:48:36.000Z
eust/tables/data.py
rasmuse/eust
2138076d52c0ffa20fba10e4e0319dd50c4e8a91
[ "MIT" ]
1
2019-10-23T08:56:33.000Z
2019-10-23T08:56:33.000Z
# -*- 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"
26.695313
78
0.654375
b91ce0003a23729f5cf4b45b783933c9e0cd6696
22,196
py
Python
utils.py
fatemehtd/Echo-SyncNet
ebb280e83a67b31436c4cfa420f9c06a92ac8c12
[ "MIT" ]
6
2021-03-19T16:55:30.000Z
2022-03-15T08:41:56.000Z
utils.py
matiasmolinas/Echo-SyncNet
f7f81ead7a24d7574c0668df3765ef58fd71d54d
[ "MIT" ]
3
2021-10-01T22:15:44.000Z
2022-03-25T03:12:47.000Z
utils.py
matiasmolinas/Echo-SyncNet
f7f81ead7a24d7574c0668df3765ef58fd71d54d
[ "MIT" ]
3
2021-03-19T16:55:35.000Z
2022-02-03T10:40:48.000Z
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
36.748344
113
0.621193
b91d0a28a2d3c169f55ef3fbe14306db5438a499
8,468
py
Python
UnityPy/classes/Sprite.py
dblack2056/UnityPy
303291e46ddfbf266131237e59e6b1b5c46a9ca4
[ "MIT" ]
null
null
null
UnityPy/classes/Sprite.py
dblack2056/UnityPy
303291e46ddfbf266131237e59e6b1b5c46a9ca4
[ "MIT" ]
null
null
null
UnityPy/classes/Sprite.py
dblack2056/UnityPy
303291e46ddfbf266131237e59e6b1b5c46a9ca4
[ "MIT" ]
null
null
null
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()
34.563265
90
0.599906
b91e27e8ce2a32cb1f2fa0c55d35f35399d00f99
11,123
py
Python
eazy/filters.py
albertfxwang/eazy-py
bcfd8a1e49f077adc794202871345542ab29800b
[ "MIT" ]
null
null
null
eazy/filters.py
albertfxwang/eazy-py
bcfd8a1e49f077adc794202871345542ab29800b
[ "MIT" ]
null
null
null
eazy/filters.py
albertfxwang/eazy-py
bcfd8a1e49f077adc794202871345542ab29800b
[ "MIT" ]
null
null
null
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):
30.225543
134
0.507687
b91e9c056c9dab4c7981c513788ac7b746223cf5
672
py
Python
LeetCode/106.py
KevinTMtz/CompetitiveProgramming
0bf8a297c404073df707b6d7b06965b055ccd872
[ "MIT" ]
1
2020-12-08T02:01:18.000Z
2020-12-08T02:01:18.000Z
LeetCode/106.py
KevinTMtz/CompetitiveProgramming
0bf8a297c404073df707b6d7b06965b055ccd872
[ "MIT" ]
null
null
null
LeetCode/106.py
KevinTMtz/CompetitiveProgramming
0bf8a297c404073df707b6d7b06965b055ccd872
[ "MIT" ]
null
null
null
# # 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
24
97
0.651786
b91f064ec51160dd5a168a0ea9d44e81a3af31b7
44,880
py
Python
evalml/automl/automl_search.py
skvorekn/evalml
2cbfa344ec3fdc0fb0f4a0f1093811135b9b97d8
[ "BSD-3-Clause" ]
null
null
null
evalml/automl/automl_search.py
skvorekn/evalml
2cbfa344ec3fdc0fb0f4a0f1093811135b9b97d8
[ "BSD-3-Clause" ]
null
null
null
evalml/automl/automl_search.py
skvorekn/evalml
2cbfa344ec3fdc0fb0f4a0f1093811135b9b97d8
[ "BSD-3-Clause" ]
null
null
null
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)
50.145251
234
0.660561
b9206e8febc3abecc98cfdec65d8f8f8f61e43fc
782
py
Python
graphql_social_auth/mutations.py
deepsourcelabs/django-graphql-social-auth
a0cc7715144dc289ccb4d2430e7c3b94fc1dffba
[ "MIT" ]
1
2021-09-03T11:55:33.000Z
2021-09-03T11:55:33.000Z
graphql_social_auth/mutations.py
deepsourcelabs/django-graphql-social-auth
a0cc7715144dc289ccb4d2430e7c3b94fc1dffba
[ "MIT" ]
null
null
null
graphql_social_auth/mutations.py
deepsourcelabs/django-graphql-social-auth
a0cc7715144dc289ccb4d2430e7c3b94fc1dffba
[ "MIT" ]
null
null
null
import graphene from graphql_jwt.decorators import setup_jwt_cookie from . import mixins, types from .decorators import social_auth
25.225806
68
0.726343
b92225fd1fc48f3b53478df0ef2d1501b1d04475
1,625
py
Python
yellowbrick/regressor/base.py
Juan0001/yellowbrick-docs-zh
36275d9704fc2a946c5bec5f802106bb5281efd1
[ "Apache-2.0" ]
20
2018-03-24T02:29:20.000Z
2022-03-03T05:01:40.000Z
yellowbrick/regressor/base.py
Juan0001/yellowbrick-docs-zh
36275d9704fc2a946c5bec5f802106bb5281efd1
[ "Apache-2.0" ]
4
2018-03-20T12:01:17.000Z
2019-04-07T16:02:19.000Z
yellowbrick/regressor/base.py
Juan0001/yellowbrick-docs-zh
36275d9704fc2a946c5bec5f802106bb5281efd1
[ "Apache-2.0" ]
5
2018-03-17T08:18:57.000Z
2019-11-15T02:20:20.000Z
# yellowbrick.regressor.base # Base classes for regressor Visualizers. # # Author: Rebecca Bilbro <[email protected]> # Author: Benjamin Bengfort <[email protected]> # 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] [email protected] $ """ 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 ##########################################################################
30.660377
79
0.582154
b92247a49fd2631992a5eddee925c5305320a529
2,941
py
Python
contrib/stack/stripmapStack/crossmul.py
falkamelung/isce2
edea69d4b6216f4ac729eba78f12547807a2751a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
contrib/stack/stripmapStack/crossmul.py
falkamelung/isce2
edea69d4b6216f4ac729eba78f12547807a2751a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
contrib/stack/stripmapStack/crossmul.py
falkamelung/isce2
edea69d4b6216f4ac729eba78f12547807a2751a
[ "ECL-2.0", "Apache-2.0" ]
1
2021-06-05T16:39:25.000Z
2021-06-05T16:39:25.000Z
#!/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. '''
27.485981
102
0.682761
b92338655b37aa1b9646d78826676f4639eac7d3
550
py
Python
27. Remove Element/solution2.py
sunshot/LeetCode
8f6503201831055f1d49ed3abb25be44a13ec317
[ "MIT" ]
null
null
null
27. Remove Element/solution2.py
sunshot/LeetCode
8f6503201831055f1d49ed3abb25be44a13ec317
[ "MIT" ]
null
null
null
27. Remove Element/solution2.py
sunshot/LeetCode
8f6503201831055f1d49ed3abb25be44a13ec317
[ "MIT" ]
null
null
null
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])
23.913043
62
0.461818
b923cd998b5a122c2fa8e86b09305b2b291d6507
3,873
py
Python
platformio/commands/home/run.py
Granjow/platformio-core
71ae579bc07b2e11fec16acda482dea04bc3a359
[ "Apache-2.0" ]
4,744
2016-11-28T14:37:47.000Z
2022-03-31T12:35:56.000Z
platformio/commands/home/run.py
Granjow/platformio-core
71ae579bc07b2e11fec16acda482dea04bc3a359
[ "Apache-2.0" ]
3,424
2016-11-27T22:45:41.000Z
2022-03-31T21:40:03.000Z
platformio/commands/home/run.py
Granjow/platformio-core
71ae579bc07b2e11fec16acda482dea04bc3a359
[ "Apache-2.0" ]
576
2016-12-01T18:48:22.000Z
2022-03-30T02:27:35.000Z
# Copyright (c) 2014-present PlatformIO <[email protected]> # # 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", )
38.73
88
0.737155
b924107dfd6ae9e56411cce662afa3db86b021e5
11,450
py
Python
appengine/components/components/machine_provider/rpc_messages.py
stefb965/luci-py
e0a8a5640c4104e5c90781d833168aa8a8d1f24d
[ "Apache-2.0" ]
1
2017-10-30T15:08:10.000Z
2017-10-30T15:08:10.000Z
appengine/components/components/machine_provider/rpc_messages.py
stefb965/luci-py
e0a8a5640c4104e5c90781d833168aa8a8d1f24d
[ "Apache-2.0" ]
null
null
null
appengine/components/components/machine_provider/rpc_messages.py
stefb965/luci-py
e0a8a5640c4104e5c90781d833168aa8a8d1f24d
[ "Apache-2.0" ]
1
2020-07-05T19:54:40.000Z
2020-07-05T19:54:40.000Z
# 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 *
38.945578
79
0.773537
b925f7b3126896a3611797c97e1fa8d0eee2234c
564
py
Python
webscraping.py
carvalho-fdec/DesafioDSA
fec9742bd77ddc3923ed616b6511cce87de48968
[ "MIT" ]
null
null
null
webscraping.py
carvalho-fdec/DesafioDSA
fec9742bd77ddc3923ed616b6511cce87de48968
[ "MIT" ]
null
null
null
webscraping.py
carvalho-fdec/DesafioDSA
fec9742bd77ddc3923ed616b6511cce87de48968
[ "MIT" ]
null
null
null
# 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())
18.193548
74
0.687943
b9270600c4aae588202efc6c296f0228f4d2527a
21,441
py
Python
tensorboard/backend/event_processing/data_provider_test.py
hongxu-jia/tensorboard
98d4dadc61fd5a0580bed808653c59fb37748893
[ "Apache-2.0" ]
1
2021-01-07T14:58:47.000Z
2021-01-07T14:58:47.000Z
tensorboard/backend/event_processing/data_provider_test.py
hongxu-jia/tensorboard
98d4dadc61fd5a0580bed808653c59fb37748893
[ "Apache-2.0" ]
null
null
null
tensorboard/backend/event_processing/data_provider_test.py
hongxu-jia/tensorboard
98d4dadc61fd5a0580bed808653c59fb37748893
[ "Apache-2.0" ]
null
null
null
# 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()
39.559041
80
0.583741
b927180a3b55091e89983dcae5d96dd47f1373ae
4,172
py
Python
extras/amld/cloud/quickdraw_rnn/task.py
luyang1210/tensorflow
948324f4cafdc97ae51c0e44fc1c28677a6e2e8a
[ "Apache-2.0" ]
1
2019-04-28T15:46:45.000Z
2019-04-28T15:46:45.000Z
extras/amld/cloud/quickdraw_rnn/task.py
luyang1210/tensorflow
948324f4cafdc97ae51c0e44fc1c28677a6e2e8a
[ "Apache-2.0" ]
null
null
null
extras/amld/cloud/quickdraw_rnn/task.py
luyang1210/tensorflow
948324f4cafdc97ae51c0e44fc1c28677a6e2e8a
[ "Apache-2.0" ]
1
2020-11-18T04:43:33.000Z
2020-11-18T04:43:33.000Z
"""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)
28.972222
81
0.613375
b92725db4e0f08b5ebf9656b39a1e567c20d5ffb
150
py
Python
A/116A.py
johnggo/Codeforces-Solutions
4127ae6f72294b5781fb94c42b69cfef570aae42
[ "MIT" ]
1
2020-08-25T19:59:11.000Z
2020-08-25T19:59:11.000Z
A/116A.py
johnggo/Codeforces-Solutions
4127ae6f72294b5781fb94c42b69cfef570aae42
[ "MIT" ]
null
null
null
A/116A.py
johnggo/Codeforces-Solutions
4127ae6f72294b5781fb94c42b69cfef570aae42
[ "MIT" ]
null
null
null
# 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)
15
41
0.506667
b9299565a87f9a052852f5ae8225680eeeb2de61
1,923
py
Python
tests/test_serialize.py
aferrall/redner
be52e4105140f575f153d640ba889eb6e6015616
[ "MIT" ]
1,146
2018-11-11T01:47:18.000Z
2022-03-31T14:11:03.000Z
tests/test_serialize.py
Awcrr/redner
b4f57037af26b720d916bbaf26103a3499101a9f
[ "MIT" ]
177
2018-11-13T22:48:25.000Z
2022-03-30T07:19:29.000Z
tests/test_serialize.py
Awcrr/redner
b4f57037af26b720d916bbaf26103a3499101a9f
[ "MIT" ]
127
2018-11-11T02:32:17.000Z
2022-03-31T07:24:03.000Z
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')
34.339286
83
0.560582
b92a551001bac345f595f68ea0440f1231ad8e57
2,302
py
Python
src/zope/publisher/tests/test_requestdataproperty.py
Shoobx/zope.publisher
790e82045d7ae06146bd8c5e27139555b9ec1641
[ "ZPL-2.1" ]
3
2016-11-18T08:58:09.000Z
2021-02-01T06:13:45.000Z
src/zope/publisher/tests/test_requestdataproperty.py
Shoobx/zope.publisher
790e82045d7ae06146bd8c5e27139555b9ec1641
[ "ZPL-2.1" ]
42
2015-06-02T19:26:10.000Z
2022-03-15T07:24:03.000Z
src/zope/publisher/tests/test_requestdataproperty.py
Shoobx/zope.publisher
790e82045d7ae06146bd8c5e27139555b9ec1641
[ "ZPL-2.1" ]
7
2015-04-03T09:29:31.000Z
2021-06-07T14:47:45.000Z
############################################################################## # # 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)
27.404762
78
0.614683
b92a9fd2163ca676afa6df078248d3bd1b2d8259
146
py
Python
tools/scoring/dimensions/__init__.py
ahemphill/digitalbuildings
56a03b0055f9f771c3ed0a962f6bfb2b1d968947
[ "Apache-2.0" ]
null
null
null
tools/scoring/dimensions/__init__.py
ahemphill/digitalbuildings
56a03b0055f9f771c3ed0a962f6bfb2b1d968947
[ "Apache-2.0" ]
null
null
null
tools/scoring/dimensions/__init__.py
ahemphill/digitalbuildings
56a03b0055f9f771c3ed0a962f6bfb2b1d968947
[ "Apache-2.0" ]
null
null
null
""" Enable import """ from os import path import sys sys.path.append( path.abspath(path.join('tools', 'validators', 'instance_validator')))
18.25
73
0.69863
b92b002b9d57e933962f9291a749b365792c1b9a
1,444
py
Python
src/thornfield/caches/cache_compression_decorator.py
drorvinkler/thornfield
3c5bb8afaa96097bc71cccb119394a0f351d828f
[ "MIT" ]
2
2020-11-24T13:27:14.000Z
2020-11-24T13:29:40.000Z
src/thornfield/caches/cache_compression_decorator.py
drorvinkler/thornfield
3c5bb8afaa96097bc71cccb119394a0f351d828f
[ "MIT" ]
1
2020-11-24T13:33:45.000Z
2020-11-24T15:10:41.000Z
src/thornfield/caches/cache_compression_decorator.py
drorvinkler/thornfield
3c5bb8afaa96097bc71cccb119394a0f351d828f
[ "MIT" ]
null
null
null
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
29.469388
79
0.628809
b92be50c97841e71ffe31a7d7baa405cc9ba5537
38,846
py
Python
manim/mobject/vector_field.py
kdkasad/manim
249b1dcab0f18a43e953b5fda517734084c0a941
[ "MIT" ]
2
2021-12-07T14:25:07.000Z
2021-12-09T14:16:10.000Z
manim/mobject/vector_field.py
kdkasad/manim
249b1dcab0f18a43e953b5fda517734084c0a941
[ "MIT" ]
3
2021-09-15T08:11:29.000Z
2021-10-06T02:00:03.000Z
manim/mobject/vector_field.py
kdkasad/manim
249b1dcab0f18a43e953b5fda517734084c0a941
[ "MIT" ]
3
2020-04-10T20:38:06.000Z
2020-09-30T03:03:45.000Z
"""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
36.96099
185
0.57298
b92c7cbb70fbc4dd2dec20c24e021d0f6405bd12
19,900
py
Python
marshmallow_dataclass/__init__.py
dan-starkware/marshmallow_dataclass
25c3e041d8c6a87d740984e57a5bd29b768afbf8
[ "MIT" ]
null
null
null
marshmallow_dataclass/__init__.py
dan-starkware/marshmallow_dataclass
25c3e041d8c6a87d740984e57a5bd29b768afbf8
[ "MIT" ]
null
null
null
marshmallow_dataclass/__init__.py
dan-starkware/marshmallow_dataclass
25c3e041d8c6a87d740984e57a5bd29b768afbf8
[ "MIT" ]
null
null
null
""" 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="[email protected]") >>> ContactInfo.Schema().load({}) ContactInfo(mail='[email protected]') >>> 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)
34.133791
110
0.647538
b92e1fb5ed102dbd1d7dc2d4b0ef720e265a976f
1,045
py
Python
electrum_trc/scripts/txradar.py
TheSin-/electrum-trc
d2f5b15fd4399a9248cce0d63e20128f3f54e69c
[ "MIT" ]
1
2019-08-20T18:05:32.000Z
2019-08-20T18:05:32.000Z
electrum_trc/scripts/txradar.py
TheSin-/electrum-trc
d2f5b15fd4399a9248cce0d63e20128f3f54e69c
[ "MIT" ]
1
2022-03-14T19:45:31.000Z
2022-03-14T19:45:31.000Z
electrum_trc/scripts/txradar.py
TheSin-/electrum-trc
d2f5b15fd4399a9248cce0d63e20128f3f54e69c
[ "MIT" ]
null
null
null
#!/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)
28.243243
99
0.675598
b92ef9143bb84fe6d37501129ff559d015cf231e
1,091
py
Python
jp.atcoder/dp/dp_g/24586988.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-09T03:06:25.000Z
2022-02-09T03:06:25.000Z
jp.atcoder/dp/dp_g/24586988.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-05T22:53:18.000Z
2022-02-09T01:29:30.000Z
jp.atcoder/dp/dp_g/24586988.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
null
null
null
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()
13.810127
30
0.505041
b930187de467bdc99d38231d4b217f6589a62613
2,039
py
Python
starteMessung.py
jkerpe/TroubleBubble
813ad797398b9f338f136bcb96c6c92186d92ebf
[ "MIT" ]
null
null
null
starteMessung.py
jkerpe/TroubleBubble
813ad797398b9f338f136bcb96c6c92186d92ebf
[ "MIT" ]
null
null
null
starteMessung.py
jkerpe/TroubleBubble
813ad797398b9f338f136bcb96c6c92186d92ebf
[ "MIT" ]
1
2021-08-09T14:57:57.000Z
2021-08-09T14:57:57.000Z
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()
34.559322
169
0.703776
b93050ad4c3c78860eb79accbddb8566a673cb7e
3,211
py
Python
application/services/decart.py
Sapfir0/web-premier-eye
f060b01e98a923374ea60360ba133caaa654b6c7
[ "MIT" ]
null
null
null
application/services/decart.py
Sapfir0/web-premier-eye
f060b01e98a923374ea60360ba133caaa654b6c7
[ "MIT" ]
null
null
null
application/services/decart.py
Sapfir0/web-premier-eye
f060b01e98a923374ea60360ba133caaa654b6c7
[ "MIT" ]
1
2020-01-06T18:27:45.000Z
2020-01-06T18:27:45.000Z
import os import tempfile
28.927928
117
0.62753
b9312660991c249b5bd6faf4ead63f4150e99b7e
4,915
py
Python
pysnmp/EXTREME-RTSTATS-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/EXTREME-RTSTATS-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/EXTREME-RTSTATS-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # 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)
114.302326
713
0.790031