content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python """Simple test client to call the debugger SOAP service""" import os import sys import base64 import getpass from suds.client import Client from suds.cache import NoCache from suds import WebFault, MethodNotFound from clfpy import AuthClient auth_endpoint = 'https://api.hetcomp.org/authManager/AuthManager?wsdl' extra_pars = "auth={},WFM=dummy,".format(auth_endpoint) def soap_call(wsdl_url, methodname, method_args): """Calls a SOAP webmethod at a given URL with given arguments.""" client = Client(wsdl_url, cache=NoCache()) try: method = getattr(client.service, methodname) except MethodNotFound as error: return(error) try: response = method(*method_args) except WebFault as error: return(error) return response if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 26437, 1332, 5456, 284, 869, 262, 49518, 12809, 2969, 2139, 37811, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 2779, 2414, 198, 11748, 651, 6603, 198, 198, 6738, 424, 9...
2.80198
303
#!/usr/bin/python3 # from time import time # from math import sqrt # with open("inp.txt", "r") as f: # a, b = list(i for i in f.read().split()) a, b = input().split() # print(a,b,c, type(a), type(int(a))) a = int(a) b = int(b) # st = time() # ----- s1 = a * (a - 1) // 2 cuoi = b - 2 dau = b - a s2 = (dau + cuoi) * (a - 1) // 2 result = s1 + s2 # ----- print(result) # print(time() - st)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 2, 422, 640, 1330, 640, 198, 2, 422, 10688, 1330, 19862, 17034, 198, 198, 2, 351, 1280, 7203, 259, 79, 13, 14116, 1600, 366, 81, 4943, 355, 277, 25, 198, 2, 220, 197, 64, 11, ...
2.124324
185
# import tcs # import daqctrl, inspect # ------------------------------------------------------------------ # install the script by: # cd $INTROOT/config/scripts # ln -s $guiInstalDir/ctaOperatorGUI/ctaGuiBack/ctaGuiBack/acs/guiACS_schedBlocks_script0.py # ------------------------------------------------------------------ # ------------------------------------------------------------------ from random import Random rndGen = Random(10987268332) waitTime = dict() waitTime['config_daq'] = rndGen.randint(1, 3) waitTime['config_camera'] = rndGen.randint(1, 5) waitTime['config_mount'] = rndGen.randint(2, 7) waitTime['finish_daq'] = rndGen.randint(1, 6) waitTime['finish_camera'] = rndGen.randint(1, 3) waitTime['finish_mount'] = rndGen.randint(1, 2) # ------------------------------------------------------------------ # # ------------------------------------------------------------------ __phases__ = [ "configuring", "config_daq", "config_camera", "config_mount", "take_data", "closing", "finish_daq", "finish_camera", "finish_mount", ] # ------------------------------------------------------------------ # # ------------------------------------------------------------------ # ------------------------------------------------------------------ # ------------------------------------------------------------------ # ------------------------------------------------------------------ # ------------------------------------------------------------------ # ------------------------------------------------------------------ # ------------------------------------------------------------------ # ------------------------------------------------------------------ # ------------------------------------------------------------------ # ------------------------------------------------------------------
[ 2, 1330, 256, 6359, 198, 2, 1330, 12379, 80, 44755, 11, 10104, 198, 198, 2, 16529, 438, 198, 2, 2721, 262, 4226, 416, 25, 198, 2, 220, 220, 22927, 720, 1268, 5446, 46, 2394, 14, 11250, 14, 46521, 198, 2, 220, 220, 300, 77, 532, ...
4.6725
400
""" Module to scan for empty folders and directories """ from time import time from msort.check import BaseCheck, CheckSkip
[ 37811, 198, 26796, 284, 9367, 329, 6565, 24512, 290, 29196, 198, 37811, 198, 6738, 640, 1330, 640, 198, 198, 6738, 13845, 419, 13, 9122, 1330, 7308, 9787, 11, 6822, 50232, 628 ]
4.064516
31
n = int(input()) a = input().split() a = [str(m) for m in a] for i in a: if i == "Y": print("Four") exit() print("Three")
[ 77, 796, 493, 7, 15414, 28955, 198, 64, 796, 5128, 22446, 35312, 3419, 198, 64, 796, 685, 2536, 7, 76, 8, 329, 285, 287, 257, 60, 198, 198, 1640, 1312, 287, 257, 25, 198, 220, 220, 220, 611, 1312, 6624, 366, 56, 1298, 198, 220, ...
2.014085
71
#!/usr/bin/env python3 # Copyright 2019 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """PackageManager provides an interface to the JSON FPM API. The PackageManager interface provides a simple way to retrieve data from the package manager. It combines this data with annotated data from the disk (which would be packages if not packaged in BootFS due to implementation details). It does minimal parsing on this data and passes it back to the user. """ import json import os import re import urllib.request from far.far_reader import far_read from server.util.url import strip_package_version, package_to_url from server.util.logging import get_logger def read_package(far_buffer): """Performs a raw_read then intelligently restructures known package structures.""" files = far_read(far_buffer) if "meta/contents" in files: content = files["meta/contents"].decode() files["meta/contents"] = dict( [tuple(e.rsplit("=", maxsplit=1)) for e in content.split("\n") if e]) if "meta/package" in files: files["meta/package"] = json.loads(files["meta/package"].decode()) json_extensions = [".cm", ".cmx"] for ext in json_extensions: for path in files.keys(): if path.endswith(ext): files[path] = json.loads(files[path]) return files
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 13130, 383, 376, 37533, 544, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198,...
3.038544
467
""" Solve 2021 Day 1: Sonar Sweep Problem """ def solver_problem1(inputs): """ Count the number of increasement from given list """ num_increased = 0 for i in range(1, len(inputs)): if inputs[i] > inputs[i - 1]: num_increased += 1 return num_increased def solver_problem2(inputs): """ Count the number of increasement from each sum of 3 number from give list """ num_increased = 0 for i in range(1, len(inputs) - 2): # sum_prev = inputs[i-1] + inputs[i] + inputs[i+1] # sum_curr = inputs[i] + inputs[i+1] + inputs[i+2] # (sum_curr - sum_prev) = inputs[i+2] - inputs[i-1] if inputs[i + 2] > inputs[i - 1]: num_increased += 1 return num_increased if __name__ == "__main__": with open("./input/d01.txt", encoding='UTF-8') as file: data = [int(line.strip()) for line in file] print(solver_problem1(data)) print(solver_problem2(data))
[ 37811, 4294, 303, 33448, 3596, 352, 25, 6295, 283, 42818, 20647, 37227, 201, 198, 4299, 1540, 332, 62, 45573, 16, 7, 15414, 82, 2599, 201, 198, 220, 220, 220, 37227, 2764, 262, 1271, 286, 1253, 292, 972, 422, 1813, 1351, 37227, 201, ...
2.230594
438
from smooth.components.component_power_converter import PowerConverter import oemof.solph as solph
[ 6738, 7209, 13, 5589, 3906, 13, 42895, 62, 6477, 62, 1102, 332, 353, 1330, 4333, 3103, 332, 353, 198, 11748, 267, 368, 1659, 13, 82, 10196, 355, 1540, 746, 628, 198 ]
3.258065
31
from demos.setup import np, plt from compecon import BasisChebyshev, BasisSpline from compecon.tools import nodeunif __author__ = 'Randall' # DEMAPP06 Chebychev and cubic spline derivative approximation errors # Function to be approximated # Set degree of approximation and endpoints of approximation interval a = -1 # left endpoint b = 1 # right endpoint n = 10 # order of interpolatioin # Construct refined uniform grid for error ploting x = nodeunif(1001, a, b) # Compute actual and fitted values on grid y, d, s = f(x) # actual # Construct and evaluate Chebychev interpolant C = BasisChebyshev(n, a, b, f=f) # chose basis functions yc = C(x) # values dc = C(x, 1) # first derivative sc = C(x, 2) # second derivative # Construct and evaluate cubic spline interpolant S = BasisSpline(n, a, b, f=f) # chose basis functions ys = S(x) # values ds = S(x, 1) # first derivative ss = S(x, 2) # second derivative # Plot function approximation error plt.figure() plt.subplot(2, 1, 1), plt.plot(x, y - yc[0]) plt.ylabel('Chebychev') plt.title('Function Approximation Error') plt.subplot(2, 1, 2) plt.plot(x, y - ys[0]) plt.ylabel('Cubic Spline') plt.xlabel('x') # Plot first derivative approximation error plt.figure() plt.subplot(2, 1, 1), plt.plot(x, d - dc[0]) plt.ylabel('Chebychev') plt.title('First Derivative Approximation Error') plt.subplot(2, 1, 2) plt.plot(x, d - ds[0], 'm') plt.ylabel('Cubic Spline') plt.xlabel('x') # Plot second derivative approximation error plt.figure() plt.subplot(2, 1, 1), plt.plot(x, s - sc[0]) plt.ylabel('Chebychev') plt.title('Second Derivative Approximation Error') plt.subplot(2, 1, 2) plt.plot(x, s - ss[0], 'm') plt.ylabel('Cubic Spline') plt.xlabel('x') plt.show()
[ 6738, 35551, 13, 40406, 1330, 45941, 11, 458, 83, 198, 6738, 9981, 1102, 1330, 6455, 271, 7376, 48209, 258, 85, 11, 6455, 271, 26568, 500, 198, 6738, 9981, 1102, 13, 31391, 1330, 10139, 403, 361, 198, 198, 834, 9800, 834, 796, 705, ...
2.176923
910
import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import Adam import tensorflow as tf import os import logging os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' logging.getLogger('tensorflow').disabled = True NUM_OF_AGENTS = 4 NUM_OF_EPISODES = 75 FRAMES_PER_EPISODE = 1000 BATCH_SIZE = 16 GAME_ID = "LunarLander-v2" if __name__ == "__main__": with tf.device('/device:CPU:0'): game = gym.make(GAME_ID) num_of_actions = game.action_space.n observation_size = game.observation_space.shape[0] npc = SimpleDqnNpcV3(observation_size, num_of_actions) is_done = False avgs = [] for model in range(NUM_OF_AGENTS): scores = [] for episode in range(NUM_OF_EPISODES): score = 0 current_state = np.reshape(game.reset(), [1, observation_size]) for frame in range(FRAMES_PER_EPISODE): # game.render() action = npc.act(current_state) new_state, gained_reward, is_done, info = game.step(action) new_state = np.reshape(new_state, [1, observation_size]) npc.retain(current_state, action, gained_reward, new_state, is_done) score += gained_reward current_state = new_state if len(npc.memory) > BATCH_SIZE: npc.replay(BATCH_SIZE) if is_done: print("episode: {0}/{1}; result: {2}; e: {3} used memory: {4}/{5}; time: {5}" .format(episode, NUM_OF_EPISODES, score, npc._exploration_rate, len(npc.memory), npc.memory.maxlen, frame)) break scores.append(score) if not is_done: print("episode: {0}/{1}; result: {2}; used memory: {3}/{4}; time: {5}" .format(episode, NUM_OF_EPISODES, score, len(npc.memory), npc.memory.maxlen, frame)) npc.save("evo_dqn_" + str(model) + ".h5") avgs.append(sum(scores) / len(scores)) for i, avg in enumerate(avgs): print("Model {} has avarage: {}".format(i, avg)) print("Overall avg: {}".format(sum(avgs) / len(avgs)))
[ 11748, 4738, 198, 11748, 11550, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 17268, 1330, 390, 4188, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 360, 1072, 11, 14258, 448, 198, 6738,...
1.940699
1,231
from .core import ACSDataset import collections __all__ = ["PerCapitaIncome"]
[ 6738, 764, 7295, 1330, 7125, 10305, 265, 292, 316, 198, 11748, 17268, 198, 198, 834, 439, 834, 796, 14631, 5990, 15610, 5350, 818, 2958, 8973, 628 ]
3.076923
26
""" Card games exercise """ def get_rounds(number): """ :param number: int - current round number. :return: list - current round and the two that follow. """ return [i + number for i in range(3)] def concatenate_rounds(rounds_1, rounds_2): """ :param rounds_1: list - first rounds played. :param rounds_2: list - second set of rounds played. :return: list - all rounds played. """ return rounds_1 + rounds_2 def list_contains_round(rounds, number): """ :param rounds: list - rounds played. :param number: int - round number. :return: bool - was the round played? """ return number in rounds def card_average(hand): """ :param hand: list - cards in hand. :return: float - average value of the cards in the hand. """ return sum(hand) / len(hand) def approx_average_is_average(hand): """ :param hand: list - cards in hand. :return: bool - if approximate average equals to the `true average`. """ return card_average(hand) in (hand[len(hand) // 2], (hand[0] + hand[-1]) / 2) def average_even_is_average_odd(hand): """ :param hand: list - cards in hand. :return: bool - are even and odd averages equal? """ even = [hand[index] for index in range(0, len(hand), 2)] odd = [hand[index] for index in range(1, len(hand), 2)] return card_average(even) == card_average(odd) def maybe_double_last(hand): """ :param hand: list - cards in hand. :return: list - hand with Jacks (if present) value doubled. """ if hand[-1] == 11: hand[-1] *= 2 return hand
[ 37811, 198, 220, 220, 220, 5172, 1830, 5517, 198, 37811, 198, 198, 4299, 651, 62, 744, 82, 7, 17618, 2599, 198, 220, 220, 220, 37227, 628, 220, 220, 220, 220, 1058, 17143, 1271, 25, 493, 532, 1459, 2835, 1271, 13, 198, 220, 220, 2...
2.687398
611
# Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import SavepointCase
[ 2, 15069, 13130, 24855, 37535, 311, 13, 43, 13, 198, 2, 13789, 13077, 6489, 12, 18, 13, 15, 393, 1568, 357, 4023, 1378, 2503, 13, 41791, 13, 2398, 14, 677, 4541, 14, 363, 489, 737, 198, 198, 6738, 16298, 2238, 13, 41989, 13, 11321...
2.897959
49
# -*- coding:utf-8 -*- states = ("B","M","E","S") test_input = "BBMESBMEBEBESSMEBBME" observations = [obs for obs in test_input] # start_prob = {"B":0.4,"M":0.2,"E":0.2,"S":0.2} # transit_prob = {"B": {"B": 0.1, "M": 0.4, "E": 0.4, "S": 0.1}, "M": {"B": 0.1, "M": 0.4, "E": 0.4, "S": 0.1}, "E": {"B": 0.4, "M": 0.1, "E": 0.1, "S": 0.4}, "S": {"B": 0.4, "M": 0.1, "E": 0.1, "S": 0.4}} # emission_prob = {'B': {"B": 0.4, "M": 0.2, "E": 0.2, "S": 0.2}, "M": {"B": 0.2, "M": 0.4, "E": 0.2, "S": 0.2}, "E": {"B": 0.2, "M": 0.2, "E": 0.4, "S": 0.2}, "S": {"B": 0.2, "M": 0.2, "E": 0.2, "S": 0.4}} if __name__=="__main__": print observations per,last = viterbi(observations,states, start_prob,transit_prob,emission_prob) print last print per
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 27219, 796, 5855, 33, 2430, 44, 2430, 36, 2430, 50, 4943, 198, 198, 9288, 62, 15414, 796, 366, 33, 12261, 1546, 33, 11682, 12473, 33, 7597, 11682, 15199, 11682, 1, 1...
1.608456
544
""" Path to CNS-related files. Most paths are defined by dictionaries that gather several related paths. Here, instead of defining the dictionaries with static paths, we have functions that create those dict-containing paths dynamically. The default values are defined by: - axis - tensors - translation_vectors - water_box But you can re-use the functions to create new dictionaries with updated paths. This is useful for those cases when the `cns/` folder is moved to a different folder. """ from pathlib import Path from haddock import toppar_path # exact file names as present in the cns/ scripts folder PARAMETERS_FILE = "haddock.param" TOPOLOGY_FILE = "haddock.top" LINK_FILE = "protein-allhdg5-4-noter.link" SCATTER_LIB = "scatter.lib" INITIAL_POSITIONS_DIR = "initial_positions" # default prepared paths parameters_file = Path(toppar_path, PARAMETERS_FILE) topology_file = Path(toppar_path, TOPOLOGY_FILE) link_file = Path(toppar_path, LINK_FILE) scatter_lib = Path(toppar_path, SCATTER_LIB) def get_translation_vectors(path): """ Generate paths for translation vectors. Parameters ---------- path : pathlib.Path If absolute, paths will be absolute, if relative paths will be relative. Adds the INITIAL_POSITIONS_DIR path before the file name. """ translation_vectors = {} for i in range(51): _s = f'trans_vector_{i}' _p = Path(path, INITIAL_POSITIONS_DIR, _s) translation_vectors[_s] = _p return translation_vectors def get_tensors(path): """Generate paths for tensors.""" tensors = { "tensor_psf": Path(path, "tensor.psf"), "tensor_pdb": Path(path, "tensor.pdb"), "tensor_para_psf": Path(path, "tensor_para.psf"), "tensor_para_pdb": Path(path, "tensor_para.pdb"), "tensor_dani_psf": Path(path, "tensor_dani.psf"), "tensor_dani_pdb": Path(path, "tensor_dani.pdb"), } return tensors def get_axis(path): """Generate paths for axis.""" axis = { "top_axis": Path(path, "top_axis.pro"), "par_axis": Path(path, "par_axis.pro"), "top_axis_dani": Path(path, "top_axis_dani.pro"), } return axis def get_water_box(path): """Generate paths for water box.""" water_box = { "boxtyp20": Path(path, "boxtyp20.pdb"), } return water_box axis = get_axis(toppar_path) tensors = get_tensors(toppar_path) translation_vectors = get_translation_vectors(toppar_path) water_box = get_water_box(toppar_path)
[ 37811, 198, 15235, 284, 48935, 12, 5363, 3696, 13, 198, 198, 6943, 13532, 389, 5447, 416, 48589, 3166, 326, 6431, 1811, 3519, 198, 6978, 82, 13, 3423, 11, 2427, 286, 16215, 262, 48589, 3166, 351, 9037, 13532, 11, 356, 198, 14150, 5499...
2.496552
1,015
""" Provides helper routines for reanalysis DBNs study. """ # License: MIT from __future__ import absolute_import from .computation import (calc_truncated_svd, downsample_data, meridional_mean, pattern_correlation, select_lat_band, select_latlon_box, select_lon_band, standardized_anomalies, zonal_mean) from .defaults import (get_coordinate_standard_name, get_default_coefficient_name, get_default_indicator_name, get_lat_name, get_level_name, get_lon_name, get_time_name) from .eofs import (eofs, reofs) from .preprocessing import (construct_lagged_data, get_offset_variable_name, remove_polynomial_trend, standardize_time_series) from .time_helpers import datetime_to_string from .validation import (check_array_shape, check_base_period, check_fixed_missing_values, check_max_memory, check_max_parents, check_number_of_chains, check_number_of_initializations, check_number_of_iterations, check_tolerance, check_warmup, detect_frequency, ensure_data_array, ensure_variables_in_data, has_fixed_missing_values, is_daily_data, is_dask_array, is_data_array, is_dataset, is_integer, is_monthly_data, is_pandas_dataframe, is_pandas_object, is_pandas_series, is_scalar, is_xarray_object, remove_missing_features, restore_missing_features) __all__ = [ 'calc_truncated_svd', 'check_array_shape', 'check_fixed_missing_values', 'check_base_period', 'check_max_memory', 'check_max_parents', 'check_number_of_chains', 'check_number_of_initializations', 'check_number_of_iterations', 'check_tolerance', 'check_warmup', 'construct_lagged_data', 'datetime_to_string', 'detect_frequency', 'downsample_data', 'ensure_data_array', 'ensure_variables_in_data', 'eofs', 'get_coordinate_standard_name', 'get_default_coefficient_name', 'get_default_indicator_name', 'get_lat_name', 'get_level_name', 'get_lon_name', 'get_offset_variable_name', 'get_time_name', 'get_valid_variables', 'has_fixed_missing_values', 'is_daily_data', 'is_dask_array', 'is_data_array', 'is_dataset', 'is_integer', 'is_monthly_data', 'is_pandas_dataframe', 'is_pandas_object', 'is_pandas_series', 'is_scalar', 'is_xarray_object', 'meridional_mean', 'pattern_correlation', 'remove_missing_features', 'remove_polynomial_trend', 'restore_missing_features', 'reofs', 'select_lat_band', 'select_latlon_box', 'select_lon_band', 'standardized_anomalies', 'standardize_time_series', 'zonal_mean' ]
[ 37811, 198, 15946, 1460, 31904, 31878, 329, 302, 20930, 360, 15766, 82, 2050, 13, 198, 37811, 198, 198, 2, 13789, 25, 17168, 628, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 764, 785, 1996, 341, 1330, 357, 994...
1.925635
1,654
from output.models.ms_data.regex.re_k14_xsd.re_k14 import ( Regex, Doc, ) __all__ = [ "Regex", "Doc", ]
[ 6738, 5072, 13, 27530, 13, 907, 62, 7890, 13, 260, 25636, 13, 260, 62, 74, 1415, 62, 87, 21282, 13, 260, 62, 74, 1415, 1330, 357, 198, 220, 220, 220, 797, 25636, 11, 198, 220, 220, 220, 14432, 11, 198, 8, 198, 198, 834, 439, 8...
1.833333
66
#!/usr/bin/python2.7 # Copyright 2012 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. """Support for simple JSON templates. A JSON template is a dictionary of JSON data in which string values may be simple templates in string.Template format (i.e., $dollarSignEscaping). By default, the template is expanded against its own data, optionally updated with additional context. """ import json from string import Template import sys __author__ = 'smulloni@google.com (Jacob Smullyan)' def ExpandJsonTemplate(json_data, extra_context=None, use_self=True): """Recursively template-expand a json dict against itself or other context. The context for string expansion is the json dict itself by default, updated by extra_context, if supplied. Args: json_data: (dict) A JSON object where string values may be templates. extra_context: (dict) Additional context for template expansion. use_self: (bool) Whether to expand the template against itself, or only use extra_context. Returns: A dict where string template values have been expanded against the context. """ if use_self: context = dict(json_data) else: context = {} if extra_context: context.update(extra_context) return RecursiveExpand(json_data) if __name__ == '__main__': if len(sys.argv) > 1: json_in = open(sys.argv[1]) else: json_in = sys.stdin data = json.load(json_in) expanded = ExpandJsonTemplate(data) json.dump(expanded, sys.stdout, indent=2)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 13, 22, 198, 2, 15069, 2321, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, ...
3.350906
607
from pyeventbus import * from timeit import default_timer as timer import numpy import sys from os import getcwd import json if __name__ == '__main__': tester = PerformanceTester() tester.register(tester) executer = PerformanceExecuter() executer.register(executer) print sys.argv[1:][0] arg = sys.argv[1:][0] if arg == 'startIOHeavyTestInMain': tester.startIOHeavyTestInMain() elif arg == 'startIOHeavyTestInBackground': tester.startIOHeavyTestInBackground() elif arg == 'startIOHeavyTestInGreenlet': tester.startIOHeavyTestInGreenlet() elif arg == 'startIOHeavyTestInParallel': tester.startIOHeavyTestInParallel() elif arg == 'startIOHeavyTestInConcurrent': tester.startIOHeavyTestInConcurrent() # tester.startIOHeavyTestInMain() # tester.startIOHeavyTestInBackground() # tester.startIOHeavyTestInGreenlet() # tester.startIOHeavyTestInParallel() # tester.startIOHeavyTestInConcurrent()
[ 6738, 279, 5948, 1151, 10885, 1330, 1635, 198, 6738, 640, 270, 1330, 4277, 62, 45016, 355, 19781, 198, 11748, 299, 32152, 198, 11748, 25064, 198, 6738, 28686, 1330, 651, 66, 16993, 198, 11748, 33918, 628, 198, 361, 11593, 3672, 834, 662...
2.878049
328
# Generated by Django 4.0 on 2021-12-15 09:04 from django.db import migrations, models import django.utils.timezone
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 319, 33448, 12, 1065, 12, 1314, 7769, 25, 3023, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 26791, 13, 2435, 11340, 628 ]
3.025641
39
hrs = input("Enter Hours:") rate=2.75 print ("Pay: " + str(float(rate) * hrs))
[ 71, 3808, 796, 5128, 7203, 17469, 19347, 25, 4943, 198, 4873, 28, 17, 13, 2425, 198, 4798, 5855, 19197, 25, 366, 1343, 965, 7, 22468, 7, 4873, 8, 1635, 36201, 4008, 198 ]
2.46875
32
from __future__ import absolute_import from __future__ import division from __future__ import print_function import _thread import sys import time from math import exp from random import random from typing import List, Tuple, Set from scipy import spatial import numpy as np import torch from torch import nn from torch.optim import optimizer from torch.utils import tensorboard from torch.utils.data import DataLoader import torch.nn.functional as F from dataloader import BidirectionalOneShotIterator from dataloader import TrainDataset from dataloader import TestDataset import tensorflow as tf import tensorboard as tb import logging tf.io.gfile = tb.compat.tensorflow_stub.io.gfile torch.random.manual_seed(123456) # region model # endregion # region def get_logger(filename): """ Return instance of logger """ logger = logging.getLogger('logger') logger.setLevel(logging.INFO) logging.basicConfig(format='%(message)s', level=logging.INFO) handler = logging.FileHandler(filename) handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) logging.getLogger().addHandler(handler) return logger logger = get_logger("./train.log") # endregion # region # endregion # region def get_hits2(self, Lvec, Rvec, top_k=(1, 10, 50, 100)): sim = spatial.distance.cdist(Lvec, Rvec, metric='cityblock') return self.get_hits(Lvec, Rvec, sim, top_k) def get_hits(self, Lvec, Rvec, sim, top_k=(1, 10, 50, 100)): # Lvec (m, d), Rvec (m, d) # LvecRvecdm # sim=distance(Lvec, Rvec) (m, m) # sim[i, j] Lvec i Rvec j top_lr = [0] * len(top_k) for i in range(Lvec.shape[0]): # KG1 rank = sim[i, :].argsort() # sim[i, :] Lvec i Rvec # argsort [6,3,5][0,1,2][3,5,6][1,2,0] rank_index = np.where(rank == i)[0][0] # np.where(rank == i) list(rank).index(i) i rank # i Lvec i Rvec i for j in range(len(top_k)): if rank_index < top_k[j]: # index 0 '<' top_lr[j] += 1 top_rl = [0] * len(top_k) for i in range(Rvec.shape[0]): rank = sim[:, i].argsort() rank_index = np.where(rank == i)[0][0] for j in range(len(top_k)): if rank_index < top_k[j]: top_rl[j] += 1 logger.info('For each left:') left = [] for i in range(len(top_lr)): hits = top_k[i] hits_value = top_lr[i] / len(self.test_seeds) * 100 left.append((hits, hits_value)) logger.info('Hits@%d: %.2f%%' % (hits, hits_value)) logger.info('For each right:') right = [] for i in range(len(top_rl)): hits = top_k[i] hits_value = top_rl[i] / len(self.test_seeds) * 100 right.append((hits, hits_value)) logger.info('Hits@%d: %.2f%%' % (hits, hits_value)) return { "left": left, "right": right, } # endregion # region _MODEL_STATE_DICT = "model_state_dict" _OPTIMIZER_STATE_DICT = "optimizer_state_dict" _EPOCH = "epoch" _STEP = "step" _BEST_SCORE = "best_score" _LOSS = "loss" def load_checkpoint(model: nn.Module, optim: optimizer.Optimizer, checkpoint_path="./result/fr_en/checkpoint.tar") -> Tuple[int, int, float, float]: """Loads training checkpoint. :param checkpoint_path: path to checkpoint :param model: model to update state :param optim: optimizer to update state :return tuple of starting epoch id, starting step id, best checkpoint score """ checkpoint = torch.load(checkpoint_path) model.load_state_dict(checkpoint[_MODEL_STATE_DICT]) optim.load_state_dict(checkpoint[_OPTIMIZER_STATE_DICT]) start_epoch_id = checkpoint[_EPOCH] + 1 step = checkpoint[_STEP] + 1 best_score = checkpoint[_BEST_SCORE] loss = checkpoint[_LOSS] return start_epoch_id, step, best_score, loss # endregion # region # endregion # train_model_for_fr_en() # train_model_for_ja_en() train_model_for_zh_en()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 4808, 16663, 198, 11748, 25064, 198, 11748, 640, 198, 6738, 10688, 1330, 1033, ...
2.189441
1,932
import discord import time import random import datetime import asyncio import json import config from discord.ext import commands from data.data_handler import data_handler from itertools import chain from collections import OrderedDict # Function to get a user's rank and remaining rp to next rank. # Takes current rp as parameter # Function to get profile pages (1 - 3) # get reaction with number + vice versa def get_reaction(number, reaction = None): reactions = { 1: "1\u20e3", 2: "2\u20e3", 3: "3\u20e3", 4: "4\u20e3", 5: "5\u20e3", 6: "6\u20e3", 7: "7\u20e3", 8: "8\u20e3", 9: "9\u20e3", 10: "10\u20e3" } if reaction is None: return reactions.get(number, 0) else: return list(reactions.keys())[list(reactions.values()).index(reaction)] # async handling of user reactions def setup(bot): bot.add_cog(Profiles(bot))
[ 11748, 36446, 198, 11748, 640, 198, 11748, 4738, 198, 11748, 4818, 8079, 198, 11748, 30351, 952, 198, 11748, 33918, 198, 11748, 4566, 198, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 1366, 13, 7890, 62, 30281, 1330, 1366, 62, 302...
2.325183
409
#!BPY """ Name: 'Follow Active (quads)' Blender: 242 Group: 'UVCalculation' Tooltip: 'Follow from active quads.' """ __author__ = "Campbell Barton" __url__ = ("blender", "blenderartists.org") __version__ = "1.0 2006/02/07" __bpydoc__ = """\ This script sets the UV mapping and image of selected faces from adjacent unselected faces. for full docs see... http://mediawiki.blender.org/index.php/Scripts/Manual/UV_Calculate/Follow_active_quads """ # ***** BEGIN GPL LICENSE BLOCK ***** # # Script copyright (C) Campbell J Barton # # This program 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 2 # of the License, or (at your option) any later version. # # This program 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 this program; if not, write to the Free Software Foundation, # Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # ***** END GPL LICENCE BLOCK ***** # -------------------------------------------------------------------------- from Blender import * import bpy import BPyMesh if __name__ == '__main__': main()
[ 2, 0, 20866, 56, 198, 37811, 198, 5376, 25, 705, 7155, 14199, 357, 421, 5643, 33047, 198, 3629, 2194, 25, 34353, 198, 13247, 25, 705, 31667, 9771, 14902, 6, 198, 25391, 22504, 25, 705, 7155, 422, 4075, 627, 5643, 2637, 198, 37811, 1...
3.511002
409
# Copyright 2020 Thomas Rogers # SPDX-License-Identifier: Apache-2.0 LOWER_LINK_TAG = 6 UPPER_LINK_TAG = 7 UPPER_WATER_TAG = 9 LOWER_WATER_TAG = 10 UPPER_STACK_TAG = 11 LOWER_STACK_TAG = 12 UPPER_GOO_TAG = 13 LOWER_GOO_TAG = 14 LOWER_LINK_TYPES = {LOWER_LINK_TAG, LOWER_WATER_TAG, LOWER_STACK_TAG, LOWER_GOO_TAG} UPPER_LINK_TYPES = {UPPER_LINK_TAG, UPPER_WATER_TAG, UPPER_STACK_TAG, UPPER_GOO_TAG} ROR_TYPE_LINK = "Link" ROR_TYPE_STACK = "Stack" ROR_TYPE_WATER = "Water" ROR_TYPE_GOO = "Goo" UPPER_TAG_MAPPING = { ROR_TYPE_LINK: UPPER_LINK_TAG, ROR_TYPE_STACK: UPPER_STACK_TAG, ROR_TYPE_WATER: UPPER_WATER_TAG, ROR_TYPE_GOO: UPPER_GOO_TAG, } UPPER_TAG_REVERSE_MAPPING = { UPPER_LINK_TAG: ROR_TYPE_LINK, UPPER_STACK_TAG: ROR_TYPE_STACK, UPPER_WATER_TAG: ROR_TYPE_WATER, UPPER_GOO_TAG: ROR_TYPE_GOO, } LOWER_TAG_MAPPING = { ROR_TYPE_LINK: LOWER_LINK_TAG, ROR_TYPE_STACK: LOWER_STACK_TAG, ROR_TYPE_WATER: LOWER_WATER_TAG, ROR_TYPE_GOO: LOWER_GOO_TAG, } ROR_TILE_MAPPING = { ROR_TYPE_LINK: 504, ROR_TYPE_STACK: 504, ROR_TYPE_WATER: 2915, ROR_TYPE_GOO: 1120, } ROR_TYPES_WITH_WATER = { ROR_TYPE_WATER, ROR_TYPE_GOO, }
[ 2, 15069, 12131, 5658, 15372, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 43, 36048, 62, 43, 17248, 62, 42197, 796, 718, 198, 8577, 18973, 62, 43, 17248, 62, 42197, 796, 767, 198, 198, 8577,...
1.84
650
from .common import * # NOQA import requests AUTH_PROVIDER = os.environ.get('RANCHER_AUTH_PROVIDER', "") ''' Prerequisite: Enable SBX without TLS, and using testuser1 as admin user. Description: In this test, we are testing the customized user and group search filter functionalities. 1) For customized user search filter: The filter looks like: (&(objectClass=person)(|(sAMAccountName=test*)(sn=test*)(givenName=test*)) [user customized filter]) Here, after we add userSearchFilter = (memberOf=CN=testgroup5,CN=Users,DC=tad,DC=rancher,DC=io) we will filter out only testuser40 and testuser41, otherwise, all users start with search keyword "testuser" will be listed out. 2) For customized group search filter: The filter looks like: (&(objectClass=group)(sAMAccountName=test)[group customized filter]) Here, after we add groupSearchFilter = (cn=testgroup2) we will filter out only testgroup2, otherwise, all groups has search keyword "testgroup" will be listed out. ''' # Config Fields HOSTNAME_OR_IP_ADDRESS = os.environ.get("RANCHER_HOSTNAME_OR_IP_ADDRESS") PORT = os.environ.get("RANCHER_PORT") CONNECTION_TIMEOUT = os.environ.get("RANCHER_CONNECTION_TIMEOUT") SERVICE_ACCOUNT_NAME = os.environ.get("RANCHER_SERVICE_ACCOUNT_NAME") SERVICE_ACCOUNT_PASSWORD = os.environ.get("RANCHER_SERVICE_ACCOUNT_PASSWORD") DEFAULT_LOGIN_DOMAIN = os.environ.get("RANCHER_DEFAULT_LOGIN_DOMAIN") USER_SEARCH_BASE = os.environ.get("RANCHER_USER_SEARCH_BASE") GROUP_SEARCH_BASE = os.environ.get("RANCHER_GROUP_SEARCH_BASE") PASSWORD = os.environ.get('RANCHER_USER_PASSWORD', "") CATTLE_AUTH_URL = \ CATTLE_TEST_URL + \ "/v3-public/"+AUTH_PROVIDER+"Providers/" + \ AUTH_PROVIDER.lower()+"?action=login" CATTLE_AUTH_PROVIDER_URL = \ CATTLE_TEST_URL + "/v3/"+AUTH_PROVIDER+"Configs/"+AUTH_PROVIDER.lower() CATTLE_AUTH_PRINCIPAL_URL = CATTLE_TEST_URL + "/v3/principals?action=search" CATTLE_AUTH_ENABLE_URL = CATTLE_AUTH_PROVIDER_URL + "?action=testAndApply" CATTLE_AUTH_DISABLE_URL = CATTLE_AUTH_PROVIDER_URL + "?action=disable"
[ 6738, 764, 11321, 1330, 1635, 220, 220, 1303, 8005, 48, 32, 198, 198, 11748, 7007, 198, 198, 32, 24318, 62, 41283, 41237, 796, 28686, 13, 268, 2268, 13, 1136, 10786, 49, 1565, 3398, 1137, 62, 32, 24318, 62, 41283, 41237, 3256, 366, ...
2.648964
772
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from CIM14.ENTSOE.Dynamics.IEC61970.Core.CoreIdentifiedObject import CoreIdentifiedObject
[ 2, 15069, 357, 34, 8, 3050, 12, 9804, 6219, 12406, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, 123...
3.805112
313
# Copyright 2021 Huawei Technologies Co., Ltd # # 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 argparse import numpy as np from src.options.general import opts from src.models.ADNet import adnet from mindspore import Tensor, export, context parser = argparse.ArgumentParser( description='ADNet test') parser.add_argument('--weight_file', default='', type=str, help='The pretrained weight file') parser.add_argument('--device_target', type=str, default="Ascend", choices=['Ascend', 'GPU', 'CPU']) parser.add_argument('--target_device', type=int, default=0) args = parser.parse_args() context.set_context(device_target=args.device_target, mode=context.PYNATIVE_MODE, device_id=args.target_device) opts['num_videos'] = 1 net, domain_specific_nets = adnet(opts, trained_file=args.weight_file) input_ = np.random.uniform(0.0, 1.0, size=[128, 3, 112, 112]).astype(np.float32) export(net, Tensor(input_), file_name='ADNet', file_format='MINDIR') print('export finished')
[ 2, 15069, 33448, 43208, 21852, 1766, 1539, 12052, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198...
3.423841
453
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 11748, 28686, 198 ]
3.217391
23
# Author: Milan Kubik, 2017 """Backend entry point manipulation""" import logging from pkg_resources import iter_entry_points RESOURCE_GROUP = "ipaqe_provision_hosts.backends" log = logging.getLogger(__name__) def load_backends(exclude=()): """Load all registered modules""" log.debug("Loading entry points from %s.", RESOURCE_GROUP) entry_points = { ep.name: ep.load() for ep in iter_entry_points(RESOURCE_GROUP) if ep.name not in exclude } log.debug("Loaded entry points: %s", entry_points.keys()) return entry_points
[ 2, 6434, 25, 21574, 24921, 1134, 11, 2177, 198, 37811, 7282, 437, 5726, 966, 17512, 37811, 198, 198, 11748, 18931, 198, 198, 6738, 279, 10025, 62, 37540, 1330, 11629, 62, 13000, 62, 13033, 198, 198, 19535, 31033, 62, 46846, 796, 366, ...
2.81592
201
from .exceptions import ( # noqa: F401 MissingCFPAttributes, MissingEnvironmentVariable, )
[ 6738, 764, 1069, 11755, 1330, 357, 220, 1303, 645, 20402, 25, 376, 21844, 198, 220, 220, 220, 25639, 22495, 4537, 926, 7657, 11, 198, 220, 220, 220, 25639, 31441, 43015, 11, 198, 8, 198 ]
2.941176
34
import urllib.request import os import subprocess import pandas as pd from tqdm import tqdm import sys sys.path.append("probefilter") sys.path.append("probefilter/libsvm-3.23/python") from sitesfinder.imads import iMADS from sitesfinder.imadsmodel import iMADSModel from sitesfinder.plotcombiner import PlotCombiner from sitesfinder.pbmescore import PBMEscore from sitesfinder.sequence import Sequence from sitesfinder.prediction.basepred import BasePrediction from cooperative import coopfilter ''' Summarize lab-archive -> note the result information about the data in the plot ''' chipname = "ets1_GM12878" chipurls = { "r1":"https://www.encodeproject.org/files/ENCFF477EHC/@@download/ENCFF477EHC.bam", "r2":"https://www.encodeproject.org/files/ENCFF371ZBY/@@download/ENCFF371ZBY.bam", "c1":"https://www.encodeproject.org/files/ENCFF963CVB/@@download/ENCFF963CVB.bam", "c2":"" } tagsize = 36 #bedpath = "/data/gordanlab/vincentius/cooperative_probe/hg19_0005_Ets1.bed" bedpath = "/Users/vincentiusmartin/Research/chip2gcPBM/resources/imads_preds/predictions/hg19_0005_Ets1_filtered.bed" # Analysis directory escore_short_path = "/Users/vincentiusmartin/Research/chip2gcPBM/resources/escores/ets1_escores.txt" escore_map_path = "/Users/vincentiusmartin/Research/chip2gcPBM/resources/escores/index_short_to_long.csv" # for iMADS, must specify cores and model files modelcores = ["GGAA", "GGAT"] modelpaths = ["/Users/vincentiusmartin/Research/chip2gcPBM/resources/imads_preds/models/ets1/ETS1_100nM_Bound_filtered_normalized_transformed_20bp_GGAA_1a2a3mer_format.model", "/Users/vincentiusmartin/Research/chip2gcPBM/resources/imads_preds/models/ets1/ETS1_100nM_Bound_filtered_normalized_transformed_20bp_GGAT_1a2a3mer_format.model"] modelwidth = 20 # TODO: confirm if we can get length without manually specifying it imads_cutoff = 0.2128 model_kmers = [1,2,3] escore_cutoff = 0.4 # ============================ outdir = "../result/%s" % chipname # From https://stackoverflow.com/questions/15644964/python-progress-bar-and-downloads if __name__=="__main__": if not os.path.exists(outdir): os.makedirs(outdir) chipdata_path = "%s/chipseq_data" % (outdir) if not os.path.exists(chipdata_path): os.makedirs(chipdata_path) chipdata = {} chip_info = "ChIP-seq data for %s:\n" % chipname # ===== Download ChIP-seq data ===== for key in chipurls: fname = os.path.basename(chipurls[key]) saveto = os.path.join(chipdata_path, fname) chipdata[key] = saveto chip_info += "%s: %s\n" % (key,fname) print("Downloading %s to %s:" % (key,saveto)) #download_url(chipurls[key], saveto) with open("%s/chipinfo.txt" % (outdir), 'w') as f: f.write(chip_info) macs_result_path = "%s/macs_result" % (outdir) if not os.path.exists(macs_result_path): os.makedirs(macs_result_path) print("Running macs...") subprocess.call(["./macs2.sh",chipdata["r1"],chipdata["r2"],chipdata["c1"],chipdata["c2"],"%s/%s" % (macs_result_path,chipname), str(tagsize)],shell=False) print("Finished running macs, results are saved in %s" % macs_result_path) idr_result_path = "%s/idr_result" % (outdir) if not os.path.exists(idr_result_path): os.makedirs(idr_result_path) print("Running idrs...") subprocess.call(["./idr.sh","%s/%s" % (macs_result_path,chipname),idr_result_path],shell=False) analysis_result_path = "%s/analysis_result" % (outdir) if not os.path.exists(analysis_result_path): os.makedirs(analysis_result_path) print("Running analysis...") pwd = os.path.dirname(os.path.realpath(__file__)) pu1_path = "%s/%s%s" % (macs_result_path,chipname,"_r1_treat_pileup.bdg") pu2_path = "%s/%s%s" % (macs_result_path,chipname,"_r2_treat_pileup.bdg") pu_both_path = "%s/%s%s" % (macs_result_path,chipname,"_bothrs_treat_pileup.bdg") nrwp_preidr_path = "%s/%s%s" % (macs_result_path,chipname,"_bothrs_peaks.narrowPeak") nrwp_postidr_path = "%s/%s" % (idr_result_path,"idr_001p_wlist.005i") args_rscript = [pu1_path, pu2_path, pu_both_path, nrwp_preidr_path, nrwp_postidr_path, bedpath, analysis_result_path, chipname] #print(["R_analysis/main.R",pwd] + args_rscript) #subprocess.call(["srun","Rscript","R_analysis/main.R",pwd] + args_rscript,shell=False) subprocess.call(["Rscript","R_analysis/main.R",pwd] + args_rscript,shell=False) # ============== PLOT AND FILTERING PART ============== # First, we can just load the models to avoid having to reload this on every iteration models = [iMADSModel(modelpath, modelcore, modelwidth, model_kmers) for modelpath, modelcore in zip(modelpaths, modelcores)] imads = iMADS(models, imads_cutoff) # 0.2128 is for the ETS1 cutoff escore = PBMEscore(escore_short_path, escore_map_path) sitelist_path = "%s/%s" % (analysis_result_path, "sitefiles_list.txt") with open(sitelist_path, 'r') as f: sitelist = [line.strip() for line in f.readlines()] for sitepath in sitelist: print(sitepath) filename = os.path.basename(os.path.splitext(sitepath)[0]) print("Making sites plot for %s" % filename) seqdf = pd.read_csv(sitepath, sep='\t') # Make Escore object es_preds = escore.predict_sequences(seqdf) eplots = escore.plot(es_preds) # Make iMADS plot imads_preds = imads.predict_sequences(seqdf) imadsplots = imads.plot(imads_preds) plots = [imadsplots, eplots] pc = PlotCombiner() # can do this just once but not a big deal plotpath = "%s/sitesplot_%s.pdf" % (analysis_result_path, filename) pc.plot_seq_combine(plots, filepath=plotpath) filtered_sites = {} print("Site filtering...") for key in es_preds: bs = Sequence(es_preds[key],imads_preds[key]) if bs.site_count() == 2: filtered_sites[key] = bs #site_list = [{**{"key":site, "sequence":es_preds[site].sequence},**filtered_sites[site].get_sites_dict()} for site in filtered_sites] #columns = ["key", "site_start_1", "site_start_2", "site_end_1", "site_end_2", "site_pos_1", "site_pos_2", "imads_score_1", "imads_score_2", "sequence"] #pd.DataFrame(site_list).to_csv("%s/sitelist_%s.pdf" % (analysis_result_path), index=False, columns=columns, float_format='%.4f') seqdict = {} funcdict = {} filtered_probes = [] # TODO: tmr look at 110,271 for key in filtered_sites: #for key in ["sequence11"]: # Visualization part seqdict["%s-wt" % key] = filtered_sites[key].sequence for idx,mut in enumerate([[0],[1],[0,1]]): mutseq = filtered_sites[key].abolish_sites(mut,escore) seqdict["%s-m%d" % (key,idx + 1)] = mutseq.sequence funcdict["%s-m%d" % (key,idx + 1)] = mutseq.plot_functions if coopfilter.filter_coopseq(seqdict["%s-wt"%key], seqdict["%s-m1"%key], seqdict["%s-m2"%key], seqdict["%s-m3"%key], filtered_sites[key].get_sites_dict(), escore): filtered_probes.append({"key":key, "wt":seqdict["%s-wt"%key], "m1":seqdict["%s-m1"%key], "m2":seqdict["%s-m2"%key], "m3":seqdict["%s-m3"%key]}) pp = escore.plot(escore.predict_sequences(seqdict),additional_functions=funcdict) pc.plot_seq_combine([pp], filepath="%s/plot_mut_%s.pdf" % (analysis_result_path,filename)) # probably should check here if filtered_probes is empty pd.DataFrame(filtered_probes).to_csv("%s/mutated_probes_%s.tsv" % (analysis_result_path,filename),sep="\t",index=False,columns=["key","wt","m1","m2","m3"]) #print(fname,header)
[ 11748, 2956, 297, 571, 13, 25927, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 16...
2.239192
3,516
import dagos.platform.platform_utils as platform_utils from .command_runner import CommandRunner from .command_runner import ContainerCommandRunner from .command_runner import LocalCommandRunner from .platform_domain import CommandNotAvailableIssue from .platform_domain import OperatingSystem from .platform_domain import PlatformIssue from .platform_domain import PlatformScope from .platform_domain import UnsupportedOperatingSystemIssue from .platform_exceptions import UnsupportedOperatingSystemException from .platform_exceptions import UnsupportedPlatformException from .platform_support_checker import PlatformSupportChecker
[ 11748, 288, 48215, 13, 24254, 13, 24254, 62, 26791, 355, 3859, 62, 26791, 198, 6738, 764, 21812, 62, 16737, 1330, 9455, 49493, 198, 6738, 764, 21812, 62, 16737, 1330, 43101, 21575, 49493, 198, 6738, 764, 21812, 62, 16737, 1330, 10714, 2...
4.723881
134
"""Finds Guids that do not have referents or that point to referents that no longer exist. E.g. a node was created and given a guid but an error caused the node to get deleted, leaving behind a guid that points to nothing. """ import sys from modularodm import Q from framework.guid.model import Guid from website.app import init_app from scripts import utils as scripts_utils import logging logger = logging.getLogger(__name__) def get_targets(): """Find GUIDs with no referents and GUIDs with referents that no longer exist.""" # Use a loop because querying MODM with Guid.find(Q('referent', 'eq', None)) # only catches the first case. ret = [] # NodeFiles were once a GuidStored object and are no longer used any more. # However, they still exist in the production database. We just skip over them # for now, but they can probably need to be removed in the future. # There were also 10 osfguidfile objects that lived in a corrupt repo that # were not migrated to OSF storage, so we skip those as well. /sloria /jmcarp for each in Guid.find(Q('referent.1', 'nin', ['nodefile', 'osfguidfile'])): if each.referent is None: logger.info('GUID {} has no referent.'.format(each._id)) ret.append(each) return ret if __name__ == '__main__': main()
[ 37811, 16742, 82, 1962, 2340, 326, 466, 407, 423, 6773, 429, 82, 393, 326, 966, 284, 6773, 429, 82, 326, 645, 2392, 2152, 13, 198, 198, 36, 13, 70, 13, 257, 10139, 373, 2727, 290, 1813, 257, 10103, 475, 281, 4049, 4073, 262, 10139...
3.034247
438
""" This script is for testing/calling in several different ways functions from QRColorChecker modules. @author: Eduard Cespedes Borrs @mail: eduard@iot-partners.com """ import unittest import hashlib import dateutil from chalicelib.server import Server import sys import json from datetime import datetime sys.path.append('../chalicelib')
[ 37811, 198, 1212, 4226, 318, 329, 4856, 14, 44714, 287, 1811, 1180, 2842, 198, 12543, 2733, 422, 42137, 10258, 9787, 263, 13103, 13, 628, 198, 31, 9800, 25, 40766, 446, 42518, 9124, 274, 12182, 3808, 198, 31, 4529, 25, 1225, 84, 446, ...
3.261682
107
#!/usr/bin/env python import os import json import unittest from collections import OrderedDict from spdown.config import Config TEST_CONFIG_PATHS = OrderedDict([ ('local', 'config.json'), ('home', os.path.join( os.path.expanduser('~'), '.config', 'spdown', 'config' )) ]) TEST_CONFIG = { 'download_directory': '~/TestMusic' } if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 555, 715, 395, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 6738, 599, 2902, 13, 11250, 1330, 17056, 198, 198, 51, 6465, 62, 109...
2.409357
171
from emulation._emulate.microphysics import TimeMask from emulation.config import ( EmulationConfig, ModelConfig, StorageConfig, _load_nml, _get_timestep, _get_storage_hook, get_hooks, ) import emulation.zhao_carr import datetime
[ 6738, 47065, 13557, 368, 5039, 13, 24055, 746, 23154, 1330, 3862, 45195, 198, 6738, 47065, 13, 11250, 1330, 357, 198, 220, 220, 220, 2295, 1741, 16934, 11, 198, 220, 220, 220, 9104, 16934, 11, 198, 220, 220, 220, 20514, 16934, 11, 198...
2.617647
102
from typing import List # O(n^2)
[ 6738, 19720, 1330, 7343, 628, 198, 2, 440, 7, 77, 61, 17, 8, 198 ]
2.5
14
from datetime import datetime from urllib.parse import urlsplit, parse_qs from dateutil.tz import tzutc import pystac import pytest from pystac_client import Client from pystac_client.conformance import ConformanceClasses from .helpers import STAC_URLS, TEST_DATA, read_data_file def test_invalid_url(self): with pytest.raises(TypeError): Client.open() def test_get_collections_with_conformance(self, requests_mock): """Checks that the "data" endpoint is used if the API published the collections conformance class.""" pc_root_text = read_data_file("planetary-computer-root.json") pc_collection_dict = read_data_file("planetary-computer-aster-l1t-collection.json", parse_json=True) # Mock the root catalog requests_mock.get(STAC_URLS["PLANETARY-COMPUTER"], status_code=200, text=pc_root_text) api = Client.open(STAC_URLS["PLANETARY-COMPUTER"]) assert api._stac_io.conforms_to(ConformanceClasses.COLLECTIONS) # Get & mock the collections (rel type "data") link collections_link = api.get_single_link("data") requests_mock.get(collections_link.href, status_code=200, json={ "collections": [pc_collection_dict], "links": [] }) _ = next(api.get_collections()) history = requests_mock.request_history assert len(history) == 2 assert history[1].url == collections_link.href def test_custom_request_parameters(self, requests_mock): pc_root_text = read_data_file("planetary-computer-root.json") pc_collection_dict = read_data_file("planetary-computer-collection.json", parse_json=True) requests_mock.get(STAC_URLS["PLANETARY-COMPUTER"], status_code=200, text=pc_root_text) init_qp_name = "my-param" init_qp_value = "some-value" api = Client.open(STAC_URLS['PLANETARY-COMPUTER'], parameters={init_qp_name: init_qp_value}) # Ensure that the the Client will use the /collections endpoint and not fall back # to traversing child links. assert api._stac_io.conforms_to(ConformanceClasses.COLLECTIONS) # Get the /collections endpoint collections_link = api.get_single_link("data") # Mock the request requests_mock.get(collections_link.href, status_code=200, json={ "collections": [pc_collection_dict], "links": [] }) # Make the collections request _ = next(api.get_collections()) history = requests_mock.request_history assert len(history) == 2 actual_qs = urlsplit(history[1].url).query actual_qp = parse_qs(actual_qs) # Check that the param from the init method is present assert init_qp_name in actual_qp assert len(actual_qp[init_qp_name]) == 1 assert actual_qp[init_qp_name][0] == init_qp_value def test_get_collections_without_conformance(self, requests_mock): """Checks that the "data" endpoint is used if the API published the collections conformance class.""" pc_root_dict = read_data_file("planetary-computer-root.json", parse_json=True) pc_collection_dict = read_data_file("planetary-computer-aster-l1t-collection.json", parse_json=True) # Remove the collections conformance class pc_root_dict["conformsTo"].remove( "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/oas30") # Remove all child links except for the collection that we are mocking pc_collection_href = next(link["href"] for link in pc_collection_dict["links"] if link["rel"] == "self") pc_root_dict["links"] = [ link for link in pc_root_dict["links"] if link["rel"] != "child" or link["href"] == pc_collection_href ] # Mock the root catalog requests_mock.get(STAC_URLS["PLANETARY-COMPUTER"], status_code=200, json=pc_root_dict) api = Client.open(STAC_URLS["PLANETARY-COMPUTER"]) assert not api._stac_io.conforms_to(ConformanceClasses.COLLECTIONS) # Mock the collection requests_mock.get(pc_collection_href, status_code=200, json=pc_collection_dict) _ = next(api.get_collections()) history = requests_mock.request_history assert len(history) == 2 assert history[1].url == pc_collection_href class TestAPISearch: def test_search_conformance_error(self, api): """Should raise a NotImplementedError if the API doesn't conform to the Item Search spec. Message should include information about the spec that was not conformed to.""" # Set the conformance to only STAC API - Core api._stac_io._conformance = [api._stac_io._conformance[0]] with pytest.raises(NotImplementedError) as excinfo: api.search(limit=10, max_items=10, collections='mr-peebles') assert str(ConformanceClasses.ITEM_SEARCH) in str(excinfo.value)
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 2956, 7278, 489, 270, 11, 21136, 62, 48382, 198, 198, 6738, 3128, 22602, 13, 22877, 1330, 256, 89, 315, 66, 198, 11748, 12972, 301, 330, 198, 11748, 12972...
2.269297
2,332
from setuptools import ( find_packages, setup, ) setup( name="text2qrcode", version="1.0-a1", description="Render a QR code image from input text", author="Matt Patey", packages=find_packages(), install_requires=["qrcode", "pillow"], entry_points={ "console_scripts": [ "t2qr=text2qrcode.main:main" ] } )
[ 6738, 900, 37623, 10141, 1330, 357, 198, 220, 220, 220, 1064, 62, 43789, 11, 198, 220, 220, 220, 9058, 11, 198, 220, 220, 220, 1267, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 5239, 17, 80, 6015, 1098, 1600, 198, 220, 220...
2.172414
174
import numpy as np import random from proyecto2.image import Image
[ 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 6738, 386, 88, 478, 78, 17, 13, 9060, 1330, 7412, 628 ]
3.4
20
from os import path import numpy as np import pytest import autofit as af import autolens as al from autolens.mock import mock pytestmark = pytest.mark.filterwarnings( "ignore:Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of " "`arr[seq]`. In the future this will be interpreted as an arrays index, `arr[np.arrays(seq)]`, which will result " "either in an error or a different result." ) directory = path.dirname(path.realpath(__file__))
[ 6738, 28686, 1330, 3108, 201, 198, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 12972, 9288, 201, 198, 201, 198, 11748, 1960, 1659, 270, 355, 6580, 201, 198, 11748, 1960, 349, 641, 355, 435, 201, 198, 6738, 1960, 349, 641...
2.901099
182
formats = {"KiB": 1024, "KB": 1000, "MiB": 1024**2, "MB": 1000**2, "GiB": 1024**3, "GB": 1000**3, "TiB": 1024**4, "TB": 1000**4} # Converts shorthand into number of bytes, ex. 1KiB = 1024 # Converts the number of bytes into shorthand expression, ex. 2500 = 2.5KB # Run tests only if file is ran as standalone. if __name__ == '__main__': # Tests import pytest assert shortToBytes("103kib") == 105472 assert shortToBytes("103GIB") == 110595407872 assert shortToBytes("0.5TB") == 500000000000 assert bytesToShort(105472) == "105.47KB" assert bytesToShort(110595407872) == "110.6GB" assert bytesToShort(500000000000) == "500.0GB" with pytest.raises(Exception): print(bytesToShort("k2jfzsk2")) with pytest.raises(Exception): print(shortToBytes("ad2wd2")) with pytest.raises(Exception): print(shortToBytes(25252))
[ 687, 1381, 796, 19779, 42, 72, 33, 1298, 28119, 11, 366, 22764, 1298, 8576, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 366, 41541, 33, 1298, 28119, 1174, 17, 11, 366, 10744, 1298, 8576, 1174, 17, 11, 198, 220, 220,...
2.395288
382
# The UI interface and analysis of the lofar solar beam from import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '..') from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon from PyQt5.uic import loadUi from PyQt5.QtCore import Qt import matplotlib from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar) import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import griddata from skimage import measure import matplotlib.dates as mdates import resource_rc from lofarSun.lofarData import LofarDataBF from pandas.plotting import register_matplotlib_converters import platform import matplotlib as mpl # try to use the precise epoch mpl.rcParams['date.epoch']='1970-01-01T00:00:00' try: mdates.set_epoch('1970-01-01T00:00:00') except: pass register_matplotlib_converters() if platform.system() != "Darwin": matplotlib.use('TkAgg') else: print("Detected MacOS, using the default matplotlib backend: " + matplotlib.get_backend()) app = QApplication([]) window = MatplotlibWidget() window.show() app.exec_()
[ 198, 2, 383, 12454, 7071, 290, 3781, 286, 262, 300, 1659, 283, 6591, 15584, 422, 198, 198, 11748, 25064, 198, 2, 7550, 379, 352, 11, 657, 318, 262, 4226, 3108, 357, 273, 10148, 287, 45285, 8, 198, 17597, 13, 6978, 13, 28463, 7, 16...
2.738499
413
""" """ __all__ = ["export_notebook", "grade_submission"] import os import sys import shutil import tempfile from contextlib import redirect_stdout try: from contextlib import nullcontext except ImportError: from .utils import nullcontext # nullcontext is new in Python 3.7 from .argparser import get_parser from .export import export_notebook from .run import main as run_grader PARSER = get_parser() ARGS_STARTER = ["run"] def grade_submission(ag_path, submission_path, quiet=False, debug=False): """ Runs non-containerized grading on a single submission at ``submission_path`` using the autograder configuration file at ``ag_path``. Creates a temporary grading directory using the ``tempfile`` library and grades the submission by replicating the autograder tree structure in that folder and running the autograder there. Does not run environment setup files (e.g. ``setup.sh``) or install requirements, so any requirements should be available in the environment being used for grading. Print statements executed during grading can be suppressed with ``quiet``. Args: ag_path (``str``): path to autograder zip file submission_path (``str``): path to submission file quiet (``bool``, optional): whether to suppress print statements during grading; default ``False`` debug (``bool``, optional): whether to run the submission in debug mode (without ignoring errors) Returns: ``otter.test_files.GradingResults``: the results object produced during the grading of the submission. """ dp = tempfile.mkdtemp() args_list = ARGS_STARTER.copy() args_list.extend([ "-a", ag_path, "-o", dp, submission_path, "--no-logo", ]) if debug: args_list.append("--debug") args = PARSER.parse_args(args_list) if quiet: f = open(os.devnull, "w") cm = redirect_stdout(f) else: cm = nullcontext() with cm: results = run_grader(**vars(args)) if quiet: f.close() shutil.rmtree(dp) return results
[ 37811, 198, 37811, 198, 198, 834, 439, 834, 796, 14631, 39344, 62, 11295, 2070, 1600, 366, 9526, 62, 7266, 3411, 8973, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 4423, 346, 198, 11748, 20218, 7753, 198, 198, 6738, 4732, 8019...
2.724874
796
from .pressureprofile import PressureProfile import numpy as np
[ 6738, 764, 36151, 13317, 1330, 30980, 37046, 220, 198, 11748, 299, 32152, 355, 45941, 198 ]
4.333333
15
#!/usr/bin/env python # This script is based on the example at: https://raw.githubusercontent.com/nf-core/test-datasets/viralrecon/samplesheet/samplesheet_test_illumina_amplicon.csv import os import sys import errno import argparse # TODO nf-core: Update the check_samplesheet function def check_samplesheet(file_in): """ This function checks that the samplesheet follows the following structure: sample,vcf SAMPLE1,sample1.vcf SAMPLE2,sample2.vcf For an example see: https://raw.githubusercontent.com/nf-core/test-datasets/viralrecon/samplesheet/samplesheet_test_illumina_amplicon.csv """ sample_mapping_dict = {} with open(file_in, "r") as fin: ## Check header MIN_COLS = 2 # TODO nf-core: Update the column names for the input samplesheet HEADER = ["sample", "vcf"] header = [x.strip('"') for x in fin.readline().strip().split(",")] if header[: len(HEADER)] != HEADER: print("ERROR: Please check samplesheet header -> {} != {}".format(",".join(header), ",".join(HEADER))) sys.exit(1) ## Check sample entries for line in fin: lspl = [x.strip().strip('"') for x in line.strip().split(",")] # Check valid number of columns per row if len(lspl) < len(HEADER): print_error( "Invalid number of columns (minimum = {})!".format(len(HEADER)), "Line", line, ) num_cols = len([x for x in lspl if x]) if num_cols < MIN_COLS: print_error( "Invalid number of populated columns (minimum = {})!".format(MIN_COLS), "Line", line, ) if __name__ == "__main__": sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 770, 4226, 318, 1912, 319, 262, 1672, 379, 25, 3740, 1378, 1831, 13, 12567, 43667, 13, 785, 14, 77, 69, 12, 7295, 14, 9288, 12, 19608, 292, 1039, 14, 85, 21093, 260, 1102, ...
2.162194
857
from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import random lol = pd.read_csv('./data/sample_SilverKDA.csv') lol.drop(['Unnamed: 0'],axis=1,inplace=True) print(lol) f, ax = plt.subplots(1, 2, figsize=(18, 8)) lol['gameResult'].value_counts().plot.pie(explode= [0, 0.1], autopct='%1.1f%%', ax=ax[0], shadow=True) ax[0].set_title('Pie plot - Game Result') ax[0].set_ylabel('') sns.countplot('gameResult', data=lol, ax=ax[1]) ax[1].set_title('Count plot - Game Result') pd.crosstab(lol['JUNGLE'], lol['gameResult'], margins=True) plt.show() x = range(0,50) print(x) randInt = random.randint(0,lol['gameResult'].count()-50) y0 = lol['gameResult'][randInt:randInt+50] plt.plot(x, y0, label="gameResult") y1 = lol['TOP'][randInt:randInt+50] plt.plot(x, y1, label="TOP") y2 = lol['JUNGLE'][randInt:randInt+50] plt.plot(x, y2, label="JUNGLE") y3 = lol['MIDDLE'][randInt:randInt+50] plt.plot(x, y3, label="MIDDLE") y4 = lol['BOTTOM'][randInt:randInt+50] plt.plot(x, y4, label="BOTTOM") y5 = lol['SUPPORT'][randInt:randInt+50] plt.plot(x, y5, label="SUPPORT") print(randInt) plt.xlabel('count') plt.ylabel('data') plt.legend() plt.show() print(lol.head()) print(lol.info()) X = lol[['TOP','JUNGLE','MIDDLE','BOTTOM','SUPPORT']] y = lol['gameResult'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=13) lr = LogisticRegression(random_state=13, solver='liblinear') lr.fit(X_train, y_train) pred = lr.predict(X_test) print(accuracy_score(y_test, pred)) import numpy as np thisPic = np.array([[1.43, 1.84, 1.92, 2.50, 3.92]]) winRate = lr.predict_proba(thisPic)[0,1] if winRate >= 0.5 and winRate <=0.6: print(".") elif winRate <0.5 and winRate >=0.3: print(" .") elif winRate <0.3: print(" .") else: print(" .") print(' : ',lr.predict_proba(thisPic)[0,1]*100,"%")
[ 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 198, 6738, 1341, 35720, 13, 29127, 62, 19849, 1330, 5972, 2569, 8081, 2234, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 9922, 62, 26675, 198, 11748, 19798, 292...
2.253333
900
from datadog import initialize, api options = { 'api_key': '16ff05c7af6ed4652a20f5a8d0c609ce', 'app_key': 'e6a169b9b337355eef90002878fbf9a565e9ee77' } initialize(**options) title = "Mymetric timeboard" description = "Mymetric Timeboard" graphs = [ { "definition": { "events": [], "requests": [ {"q": "avg:mymetric{host:ubuntu-xenial}"} ], "viz": "timeseries" }, "title": "mymetric in timeseries" }, { "definition": { "events": [], "requests": [ {"q": "anomalies(avg:postgres.connections.current{host:ubuntu-xenial}, 'basic', 2)"} ], "viz": "timeseries" }, "title": "PostgreSQL connections" }, { "definition": { "events": [], "requests": [ {"q": "avg:mymetric{host:ubuntu-xenial}.rollup(sum, 3600)"} ], "viz": "timeseries" }, "title": "Rollup function mymetric" }, ] template_variables = [{ "name": "ubuntu_xenial", "prefix": "host", "default": "host:my-host" }] read_only = True api.Timeboard.create(title=title,description=description,graphs=graphs,template_variables=template_variables)
[ 6738, 4818, 324, 519, 1330, 41216, 11, 40391, 198, 198, 25811, 796, 1391, 198, 220, 220, 220, 705, 15042, 62, 2539, 10354, 705, 1433, 487, 2713, 66, 22, 1878, 21, 276, 42018, 17, 64, 1238, 69, 20, 64, 23, 67, 15, 66, 31751, 344, ...
1.906158
682
#! /usr/bin/env python3 from subprocess import call r = call(["python3", "-m", "korali.rlview", "--help"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--test"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--maxObservations", "10000", "--test"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--maxReward", "20.0", "--test"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--minReward", "-1.0", "--test"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--showCI", "0.2", "--test"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--averageDepth", "30", "--test"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "abf2d_vracer2", "--test"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--output", "test.png", "--test"]) if r!=0: exit(r) exit(0)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 850, 14681, 1330, 869, 198, 198, 81, 796, 869, 7, 14692, 29412, 18, 1600, 27444, 76, 1600, 366, 74, 6864, 72, 13, 45895, 1177, 1600, 366, 438, 16794, 8973, 8, 198, 361,...
1.964413
562
def generated_file_staleness_test(name, outs, generated_pattern): """Tests that checked-in file(s) match the contents of generated file(s). The resulting test will verify that all output files exist and have the correct contents. If the test fails, it can be invoked with --fix to bring the checked-in files up to date. Args: name: Name of the rule. outs: the checked-in files that are copied from generated files. generated_pattern: the pattern for transforming each "out" file into a generated file. For example, if generated_pattern="generated/%s" then a file foo.txt will look for generated file generated/foo.txt. """ script_name = name + ".py" script_src = ":staleness_test.py" # Filter out non-existing rules so Blaze doesn't error out before we even # run the test. existing_outs = native.glob(include = outs) # The file list contains a few extra bits of information at the end. # These get unpacked by the Config class in staleness_test_lib.py. file_list = outs + [generated_pattern, native.package_name() or ".", name] native.genrule( name = name + "_makescript", outs = [script_name], srcs = [script_src], testonly = 1, cmd = "cat $(location " + script_src + ") > $@; " + "sed -i.bak -e 's|INSERT_FILE_LIST_HERE|" + "\\\n ".join(file_list) + "|' $@", ) native.py_test( name = name, srcs = [script_name], data = existing_outs + [generated_pattern % file for file in outs], deps = [ ":staleness_test_lib", ], )
[ 198, 4299, 7560, 62, 7753, 62, 7757, 9449, 62, 9288, 7, 3672, 11, 12198, 11, 7560, 62, 33279, 2599, 198, 220, 220, 220, 37227, 51, 3558, 326, 10667, 12, 259, 2393, 7, 82, 8, 2872, 262, 10154, 286, 7560, 2393, 7, 82, 737, 628, 22...
2.6288
625
from assets.lambdas.transform_findings.index import TransformFindings import boto3 from moto import mock_s3
[ 6738, 6798, 13, 2543, 17457, 292, 13, 35636, 62, 19796, 654, 13, 9630, 1330, 26981, 16742, 654, 198, 11748, 275, 2069, 18, 198, 6738, 285, 2069, 1330, 15290, 62, 82, 18, 628 ]
3.40625
32
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-01-10 16:35 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 19, 319, 2864, 12, 486, 12, 940, 1467, 25, 2327, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 1...
2.883117
77
# -*- coding: utf-8 -*- ################################################################################ # | # # | ______________________________________________________________ # # | :~8a.`~888a:::::::::::::::88......88:::::::::::::::;a8~".a88::| # # | ::::~8a.`~888a::::::::::::88......88::::::::::::;a8~".a888~:::| # # | :::::::~8a.`~888a:::::::::88......88:::::::::;a8~".a888~::::::| # # | ::::::::::~8a.`~888a::::::88......88::::::;a8~".a888~:::::::::| # # | :::::::::::::~8a.`~888a:::88......88:::;a8~".a888~::::::::::::| # # | :::::::::::: :~8a.`~888a:88 .....88;a8~".a888~:::::::::::::::| # # | :::::::::::::::::::~8a.`~888......88~".a888~::::::::::::::::::| # # | 8888888888888888888888888888......8888888888888888888888888888| # # | ..............................................................| # # | ..............................................................| # # | 8888888888888888888888888888......8888888888888888888888888888| # # | ::::::::::::::::::a888~".a88......888a."~8;:::::::::::::::::::| # # | :::::::::::::::a888~".a8~:88......88~888a."~8;::::::::::::::::| # # | ::::::::::::a888~".a8~::::88......88:::~888a."~8;:::::::::::::| # # | :::::::::a888~".a8~:::::::88......88::::::~888a."~8;::::::::::| # # | ::::::a888~".a8~::::::::::88......88:::::::::~888a."~8;:::::::| # # | :::a888~".a8~:::::::::::::88......88::::::::::::~888a."~8;::::| # # | a888~".a8~::::::::::::::::88......88:::::::::::::::~888a."~8;:| # # | # # | Rebirth Addon # # | Copyright (C) 2017 Cypher # # | # # | This program 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. # # | # # | This program 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. # # | # ################################################################################ try: from sqlite3 import dbapi2 as database except: from pysqlite2 import dbapi2 as database import datetime import json import os import re import sys import urllib import urlparse import xbmc from resources.lib.modules import control from resources.lib.modules import cleantitle
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 29113, 14468, 198, 2, 930, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.978009
1,637
import io import os import click import frappe from frappe.website.page_renderers.base_template_page import BaseTemplatePage from frappe.website.router import get_base_template, get_page_info from frappe.website.utils import ( cache_html, extract_comment_tag, extract_title, get_frontmatter, get_next_link, get_sidebar_items, get_toc, is_binary_file, ) WEBPAGE_PY_MODULE_PROPERTIES = ( "base_template_path", "template", "no_cache", "sitemap", "condition_field", ) COMMENT_PROPERTY_KEY_VALUE_MAP = { "no-breadcrumbs": ("no_breadcrumbs", 1), "show-sidebar": ("show_sidebar", 1), "add-breadcrumbs": ("add_breadcrumbs", 1), "no-header": ("no_header", 1), "add-next-prev-links": ("add_next_prev_links", 1), "no-cache": ("no_cache", 1), "no-sitemap": ("sitemap", 0), "sitemap": ("sitemap", 1), }
[ 11748, 33245, 198, 11748, 28686, 198, 198, 11748, 3904, 198, 198, 11748, 5306, 27768, 198, 6738, 5306, 27768, 13, 732, 12485, 13, 7700, 62, 10920, 19288, 13, 8692, 62, 28243, 62, 7700, 1330, 7308, 30800, 9876, 198, 6738, 5306, 27768, 13...
2.410029
339
# Copyright 2015 - Mirantis, Inc. # Copyright 2015 - StackStorm, Inc. # # 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 hashlib import json import sqlalchemy as sa from sqlalchemy import event from sqlalchemy.orm import backref from sqlalchemy.orm import relationship import sys from oslo_config import cfg from oslo_log import log as logging from mistral.db.sqlalchemy import model_base as mb from mistral.db.sqlalchemy import types as st from mistral import exceptions as exc from mistral.services import security from mistral import utils # Definition objects. LOG = logging.getLogger(__name__) def validate_long_type_length(cls, field_name, value): """Makes sure the value does not exceeds the maximum size.""" if value: # Get the configured limit. size_limit_kb = cfg.CONF.engine.execution_field_size_limit_kb # If the size is unlimited. if size_limit_kb < 0: return size_kb = int(sys.getsizeof(str(value)) / 1024) if size_kb > size_limit_kb: LOG.error( "Size limit %dKB exceed for class [%s], " "field %s of size %dKB.", size_limit_kb, str(cls), field_name, size_kb ) raise exc.SizeLimitExceededException( field_name, size_kb, size_limit_kb ) def register_length_validator(attr_name): """Register an event listener on the attribute. This event listener will validate the size every time a 'set' occurs. """ for cls in utils.iter_subclasses(Execution): if hasattr(cls, attr_name): event.listen( getattr(cls, attr_name), 'set', lambda t, v, o, i: validate_long_type_length(cls, attr_name, v) ) # There's no WorkbookExecution so we safely omit "Definition" in the name. # Execution objects. for cls in utils.iter_subclasses(Execution): event.listen( # Catch and trim Execution.state_info to always fit allocated size. # Note that the limit is 65500 which is less than 65535 (2^16 -1). # The reason is that utils.cut() is not exactly accurate in case if # the value is not a string, but, for example, a dictionary. If we # limit it exactly to 65535 then once in a while it may go slightly # beyond the allowed maximum size. It may depend on the order of # keys in a string representation and other things that are hidden # inside utils.cut_dict() method. cls.state_info, 'set', lambda t, v, o, i: utils.cut(v, 65500), retval=True ) # Many-to-one for 'ActionExecution' and 'TaskExecution'. ActionExecution.task_execution_id = sa.Column( sa.String(36), sa.ForeignKey(TaskExecution.id, ondelete='CASCADE'), nullable=True ) TaskExecution.action_executions = relationship( ActionExecution, backref=backref('task_execution', remote_side=[TaskExecution.id]), cascade='all, delete-orphan', foreign_keys=ActionExecution.task_execution_id, lazy='select' ) sa.Index( '%s_task_execution_id' % ActionExecution.__tablename__, 'task_execution_id' ) # Many-to-one for 'WorkflowExecution' and 'TaskExecution'. WorkflowExecution.task_execution_id = sa.Column( sa.String(36), sa.ForeignKey(TaskExecution.id, ondelete='CASCADE'), nullable=True ) TaskExecution.workflow_executions = relationship( WorkflowExecution, backref=backref('task_execution', remote_side=[TaskExecution.id]), cascade='all, delete-orphan', foreign_keys=WorkflowExecution.task_execution_id, lazy='select' ) sa.Index( '%s_task_execution_id' % WorkflowExecution.__tablename__, 'task_execution_id' ) # Many-to-one for 'TaskExecution' and 'WorkflowExecution'. TaskExecution.workflow_execution_id = sa.Column( sa.String(36), sa.ForeignKey(WorkflowExecution.id, ondelete='CASCADE') ) WorkflowExecution.task_executions = relationship( TaskExecution, backref=backref('workflow_execution', remote_side=[WorkflowExecution.id]), cascade='all, delete-orphan', foreign_keys=TaskExecution.workflow_execution_id, lazy='select' ) sa.Index( '%s_workflow_execution_id' % TaskExecution.__tablename__, TaskExecution.workflow_execution_id ) # Other objects. sa.Index( '%s_execution_time' % DelayedCall.__tablename__, DelayedCall.execution_time ) # Register all hooks related to secure models. mb.register_secure_model_hooks() # TODO(rakhmerov): This is a bad solution. It's hard to find in the code, # configure flexibly etc. Fix it. # Register an event listener to verify that the size of all the long columns # affected by the user do not exceed the limit configuration. for attr_name in ['input', 'output', 'params', 'published']: register_length_validator(attr_name) sa.UniqueConstraint(NamedLock.name)
[ 2, 15069, 1853, 532, 7381, 20836, 11, 3457, 13, 198, 2, 15069, 1853, 532, 23881, 32173, 11, 3457, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220,...
2.611748
2,094
"""Package list handling""" load(":private/set.bzl", "set") def pkg_info_to_ghc_args(pkg_info): """ Takes the package info collected by `ghc_info()` and returns the actual list of command line arguments that should be passed to GHC. """ args = [ # In compile.bzl, we pass this just before all -package-id # arguments. Not doing so leads to bizarre compile-time failures. # It turns out that equally, not doing so leads to bizarre # link-time failures. See # https://github.com/tweag/rules_haskell/issues/395. "-hide-all-packages", ] if not pkg_info.has_version: args.extend([ # Macro version are disabled for all packages by default # and enabled for package with version # see https://github.com/tweag/rules_haskell/issues/414 "-fno-version-macros", ]) for package in pkg_info.packages: args.extend(["-package", package]) for package_id in pkg_info.package_ids: args.extend(["-package-id", package_id]) for package_db in pkg_info.package_dbs: args.extend(["-package-db", package_db]) return args def expose_packages(build_info, lib_info, use_direct, use_my_pkg_id, custom_package_caches, version): """ Returns the information that is needed by GHC in order to enable haskell packages. build_info: is common to all builds version: if the rule contains a version, we will export the CPP version macro All the other arguments are not understood well: lib_info: only used for repl and linter use_direct: only used for repl and linter use_my_pkg_id: only used for one specific task in compile.bzl custom_package_caches: override the package_caches of build_info, used only by the repl """ has_version = version != None and version != "" # Expose all prebuilt dependencies # # We have to remember to specify all (transitive) wired-in # dependencies or we can't find objects for linking # # Set use_direct if build_info does not have a direct_prebuilt_deps field. packages = [] for prebuilt_dep in set.to_list(build_info.direct_prebuilt_deps if use_direct else build_info.prebuilt_dependencies): packages.append(prebuilt_dep.package) # Expose all bazel dependencies package_ids = [] for package in set.to_list(build_info.package_ids): # XXX: repl and lint uses this lib_info flags # It is set to None in all other usage of this function # TODO: find the meaning of this flag if lib_info == None or package != lib_info.package_id: # XXX: use_my_pkg_id is not None only in compile.bzl if (use_my_pkg_id == None) or package != use_my_pkg_id: package_ids.append(package) # Only include package DBs for deps, prebuilt deps should be found # auto-magically by GHC package_dbs = [] for cache in set.to_list(build_info.package_caches if not custom_package_caches else custom_package_caches): package_dbs.append(cache.dirname) ghc_info = struct( has_version = has_version, packages = packages, package_ids = package_ids, package_dbs = package_dbs, ) return ghc_info
[ 37811, 27813, 1351, 9041, 37811, 198, 198, 2220, 7, 1298, 19734, 14, 2617, 13, 65, 48274, 1600, 366, 2617, 4943, 198, 198, 4299, 279, 10025, 62, 10951, 62, 1462, 62, 456, 66, 62, 22046, 7, 35339, 62, 10951, 2599, 198, 220, 220, 220,...
2.65
1,240
import subprocess
[ 11748, 850, 14681, 628 ]
4.75
4
#!/usr/bin/python3 """ =============================================================================== =============================================================================== """ from models.base_model import BaseModel from models.state import State import unittest import json import pep8 import datetime
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 201, 198, 37811, 201, 198, 23926, 25609, 18604, 201, 198, 201, 198, 220, 220, 220, 220, 220, 220, 220, 201, 198, 220, 220, 220, 220, 201, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.407609
184
"""EESG.py Created by Latha Sethuraman, Katherine Dykes. Copyright (c) NREL. All rights reserved. Electromagnetic design based on conventional magnetic circuit laws Structural design based on McDonald's thesis """ from openmdao.api import Group, Problem, Component,ExecComp,IndepVarComp,ScipyOptimizer,pyOptSparseDriver from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver from openmdao.drivers import * import numpy as np from numpy import array,float,min,sign from math import pi, cos, sqrt, radians, sin, exp, log10, log, tan, atan import pandas ####################################################Cost Analysis####################################################################### ####################################################OPTIMISATION SET_UP ############################################################### def EESG_Opt_example(): opt_problem=Problem(root=EESG_Opt()) #Example optimization of an EESG for costs on a 5 MW reference turbine # add optimizer and set-up problem (using user defined input on objective function) # opt_problem.driver=pyOptSparseDriver() opt_problem.driver.options['optimizer'] = 'CONMIN' opt_problem.driver.add_objective('Costs') # Define Objective opt_problem.driver.opt_settings['IPRINT'] = 4 opt_problem.driver.opt_settings['ITRM'] = 3 opt_problem.driver.opt_settings['ITMAX'] = 10 opt_problem.driver.opt_settings['DELFUN'] = 1e-3 opt_problem.driver.opt_settings['DABFUN'] = 1e-3 opt_problem.driver.opt_settings['IFILE'] = 'CONMIN_EESG.out' opt_problem.root.deriv_options['type']='fd' # Specificiency target efficiency(%) Eta_Target = 93.0 # Set bounds for design variables for an EESG designed for a 5MW turbine opt_problem.driver.add_desvar('r_s',lower=0.5,upper=9.0) opt_problem.driver.add_desvar('l_s', lower=0.5, upper=2.5) opt_problem.driver.add_desvar('h_s', lower=0.06, upper=0.15) opt_problem.driver.add_desvar('tau_p', lower=0.04, upper=0.2) opt_problem.driver.add_desvar('N_f', lower=10, upper=300) opt_problem.driver.add_desvar('I_f', lower=1, upper=500) opt_problem.driver.add_desvar('n_r', lower=5.0, upper=15.0) opt_problem.driver.add_desvar('h_yr', lower=0.01, upper=0.25) opt_problem.driver.add_desvar('h_ys', lower=0.01, upper=0.25) opt_problem.driver.add_desvar('b_r', lower=0.1, upper=1.5) opt_problem.driver.add_desvar('d_r', lower=0.1, upper=1.5) opt_problem.driver.add_desvar('t_wr', lower=0.001, upper=0.2) opt_problem.driver.add_desvar('n_s', lower=5.0, upper=15.0) opt_problem.driver.add_desvar('b_st', lower=0.1, upper=1.5) opt_problem.driver.add_desvar('d_s', lower=0.1, upper=1.5) opt_problem.driver.add_desvar('t_ws', lower=0.001, upper=0.2) # set up constraints for the PMSG_arms generator opt_problem.driver.add_constraint('B_symax',upper=2.0-1.0e-6) #1 opt_problem.driver.add_constraint('B_rymax',upper=2.0-1.0e-6) #2 opt_problem.driver.add_constraint('B_tmax',upper=2.0-1.0e-6) #3 opt_problem.driver.add_constraint('B_gfm',lower=0.617031,upper=1.057768) #4 opt_problem.driver.add_constraint('B_g',lower=0.7,upper=1.2) #5 opt_problem.driver.add_constraint('B_pc',upper=2.0) #6 opt_problem.driver.add_constraint('E_s',lower=500.0,upper=5000.0) #7 opt_problem.driver.add_constraint('con_uAs',lower=0.0+1.0e-6) #8 opt_problem.driver.add_constraint('con_zAs',lower=0.0+1.0e-6) #9 opt_problem.driver.add_constraint('con_yAs',lower=0.0+1.0e-6) #10 opt_problem.driver.add_constraint('con_uAr',lower=0.0+1.0e-6) #11 opt_problem.driver.add_constraint('con_zAr',lower=0.0+1.0e-6) #12 opt_problem.driver.add_constraint('con_yAr',lower=0.0+1.0e-6) #13 opt_problem.driver.add_constraint('con_TC2',lower=0.0+1.0e-6) #14 opt_problem.driver.add_constraint('con_TC3',lower=0.0+1e-6) #15 opt_problem.driver.add_constraint('con_br',lower=0.0+1e-6) #16 opt_problem.driver.add_constraint('con_bst',lower=0.0-1e-6) #17 opt_problem.driver.add_constraint('A_1',upper=60000.0-1e-6) #18 opt_problem.driver.add_constraint('J_s',upper=6.0) #19 opt_problem.driver.add_constraint('J_f',upper=6.0) #20 opt_problem.driver.add_constraint('A_Cuscalc',lower=5.0,upper=300) #22 opt_problem.driver.add_constraint('A_Curcalc',lower=10,upper=300) #23 opt_problem.driver.add_constraint('K_rad',lower=0.2+1e-6,upper=0.27) #24 opt_problem.driver.add_constraint('Slot_aspect_ratio',lower=4.0,upper=10.0)#25 opt_problem.driver.add_constraint('gen_eff',lower=Eta_Target) #26 opt_problem.driver.add_constraint('n_brushes',upper=6) #27 opt_problem.driver.add_constraint('Power_ratio',upper=2-1.0e-6) #28 opt_problem.setup() # Specify Target machine parameters opt_problem['machine_rating']=5000000.0 opt_problem['Torque']=4.143289e6 opt_problem['n_nom']=12.1 # Initial design variables opt_problem['r_s']=3.2 opt_problem['l_s']=1.4 opt_problem['h_s']= 0.060 opt_problem['tau_p']= 0.170 opt_problem['I_f']= 69 opt_problem['N_f']= 100 opt_problem['h_ys']= 0.130 opt_problem['h_yr']= 0.120 opt_problem['n_s']= 5 opt_problem['b_st']= 0.470 opt_problem['n_r']=5 opt_problem['b_r']= 0.480 opt_problem['d_r']= 0.510 opt_problem['d_s']= 0.400 opt_problem['t_wr']=0.140 opt_problem['t_ws']=0.070 opt_problem['R_o']=0.43 #10MW: 0.523950817,#5MW: 0.43, #3MW:0.363882632 #1.5MW: 0.2775 0.75MW: 0.17625 # Costs opt_problem['C_Cu']=4.786 opt_problem['C_Fe']= 0.556 opt_problem['C_Fes']=0.50139 #Material properties opt_problem['rho_Fe']= 7700 #Magnetic Steel/iron density opt_problem['rho_Fes']= 7850 #structural Steel density opt_problem['rho_Copper']=8900 # Kg/m3 copper density opt_problem['main_shaft_cm']=np.array([0.0, 0.0, 0.0]) opt_problem['main_shaft_length'] =2.0 #Run optimization opt_problem.run() """Uncomment to print solution to screen/an excel file raw_data = {'Parameters': ['Rating','Stator Arms', 'Stator Axial arm dimension','Stator Circumferential arm dimension',' Stator arm Thickness' ,'Rotor Arms', 'Rotor Axial arm dimension','Rotor Circumferential arm dimension',\ 'Rotor Arm thickness', ' Rotor Radial deflection', 'Rotor Axial deflection','Rotor circum deflection', 'Stator Radial deflection',' Stator Axial deflection',' Stator Circumferential deflection','Air gap diameter', 'Stator length',\ 'l/D ratio', 'Pole pitch', 'Stator slot height','Stator slot width','Slot aspect ratio','Stator tooth width', 'Stator yoke height', 'Rotor yoke height', 'Rotor pole height', 'Rotor pole width', 'Average no load flux density', \ 'Peak air gap flux density','Peak stator yoke flux density','Peak rotor yoke flux density','Stator tooth flux density','Rotor pole core flux density','Pole pairs', 'Generator output frequency', 'Generator output phase voltage(rms value)', \ 'Generator Output phase current', 'Stator resistance', 'Synchronous inductance','Stator slots','Stator turns','Stator conductor cross-section','Stator Current density ','Specific current loading','Field turns','Conductor cross-section',\ 'Field Current','D.C Field resistance','MMF ratio at rated load(Rotor/Stator)','Excitation Power (% of Rated Power)','Number of brushes/polarity','Field Current density','Generator Efficiency', 'Iron mass', 'Copper mass','Mass of Arms','Total Mass','Total Cost'],\ 'Values': [opt_problem['machine_rating']/1e6,opt_problem['n_s'],opt_problem['d_s']*1000,opt_problem['b_st']*1000,opt_problem['t_ws']*1000,opt_problem['n_r'],opt_problem['d_r']*1000,opt_problem['b_r']*1000,opt_problem['t_wr']*1000,opt_problem['u_Ar']*1000,\ opt_problem['y_Ar']*1000,opt_problem['z_A_r']*1000,opt_problem['u_As']*1000,opt_problem['y_As']*1000,opt_problem['z_A_s']*1000,2*opt_problem['r_s'],opt_problem['l_s'],opt_problem['K_rad'],opt_problem['tau_p']*1000,opt_problem['h_s']*1000,opt_problem['b_s']*1000,\ opt_problem['Slot_aspect_ratio'],opt_problem['b_t']*1000,opt_problem['h_ys']*1000,opt_problem['h_yr']*1000,opt_problem['h_p']*1000,opt_problem['b_p']*1000,opt_problem['B_gfm'],opt_problem['B_g'],opt_problem['B_symax'],opt_problem['B_rymax'],opt_problem['B_tmax'],\ opt_problem['B_pc'],opt_problem['p'],opt_problem['f'],opt_problem['E_s'],opt_problem['I_s'],opt_problem['R_s'],opt_problem['L_m'],opt_problem['S'],opt_problem['N_s'],opt_problem['A_Cuscalc'],opt_problem['J_s'],opt_problem['A_1']/1000,opt_problem['N_f'],opt_problem['A_Curcalc'],\ opt_problem['I_f'],opt_problem['R_r'],opt_problem['Load_mmf_ratio'],opt_problem['Power_ratio'],opt_problem['n_brushes'],opt_problem['J_f'],opt_problem['gen_eff'],opt_problem['Iron']/1000,opt_problem['Copper']/1000,opt_problem['Structural_mass']/1000,\ opt_problem['Mass']/1000,opt_problem['Costs']/1000], 'Limit': ['','','',opt_problem['b_all_s']*1000,'','','',opt_problem['b_all_r']*1000,'',opt_problem['u_all_r']*1000,opt_problem['y_all']*1000,opt_problem['z_all_r']*1000,opt_problem['u_all_s']*1000,opt_problem['y_all']*1000,opt_problem['z_all_s']*1000,\ '','','(0.2-0.27)','','','','(4-10)','','','','','','(0.62-1.05)','1.2','2','2','2','2','','(10-60)','','','','','','','','(3-6)','<60','','','','','','<2%','','(3-6)',Eta_Target,'','','','',''], 'Units':['MW','unit','mm','mm','mm','unit','mm','mm','mm','mm','mm','mm','mm','mm','mm','m','m','','','mm','mm','mm','mm','mm','mm','mm','mm','T','T','T','T','T','T','-','Hz','V','A','om/phase',\ 'p.u','slots','turns','mm^2','A/mm^2','kA/m','turns','mm^2','A','ohm','%','%','brushes','A/mm^2','turns','%','tons','tons','tons','1000$']} df=pandas.DataFrame(raw_data, columns=['Parameters','Values','Limit','Units']) print df df.to_excel('EESG_'+str(opt_problem['machine_rating']/1e6)+'MW_1.7.x.xlsx') """ if __name__=="__main__": # Run an example optimization of EESG generator on cost EESG_Opt_example()
[ 37811, 36, 1546, 38, 13, 9078, 201, 198, 41972, 416, 406, 30921, 20194, 333, 10546, 11, 32719, 23524, 5209, 13, 201, 198, 15269, 357, 66, 8, 399, 16448, 13, 1439, 2489, 10395, 13, 201, 198, 19453, 398, 25145, 1486, 1912, 319, 10224, ...
2.311351
4,352
# Copyright 2020 DeepMind Technologies Limited. 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. # ============================================================================== """Tests whether modules produce similar output given np.ndarray inputs.""" import functools from typing import Tuple from absl.testing import absltest from absl.testing import parameterized import haiku as hk from haiku._src import test_utils from haiku._src.integration import descriptors import jax import jax.numpy as jnp import numpy as np ModuleFn = descriptors.ModuleFn if __name__ == '__main__': absltest.main()
[ 2, 15069, 12131, 10766, 28478, 21852, 15302, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 35...
3.865979
291
#!/usr/bin/env python """A more advanced Reducer, using Python iterators and generators.""" from itertools import groupby from operator import itemgetter import sys if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 32, 517, 6190, 2297, 48915, 11, 1262, 11361, 11629, 2024, 290, 27298, 526, 15931, 198, 198, 6738, 340, 861, 10141, 1330, 1448, 1525, 198, 6738, 10088, 1330, 2378, 1136, 353, 198, ...
3.285714
63
from pylps.core import * initialise(max_time=5) create_actions('say(_, _)', 'say_single(_)') create_events('member(_, _)') create_facts('inp(_, _)') create_variables('X', 'Y', 'F', 'Item', 'List', 'Tail') inp([], [[]]) inp('z', ['a', 'b', 'c', 'd', 'e']) inp('a', ['b', 'c', 'a']) inp(['b', 'c'], ['d', ['a', 'c']]) inp(['b', 'c'], ['d', ['a', 'c'], ['b', 'c']]) reactive_rule(inp(Item, List)).then( Item.is_in(List), say(Item, List), ) execute(debug=False) show_kb_log()
[ 6738, 279, 2645, 862, 13, 7295, 1330, 1635, 198, 198, 36733, 786, 7, 9806, 62, 2435, 28, 20, 8, 198, 198, 17953, 62, 4658, 10786, 16706, 28264, 11, 4808, 8, 3256, 705, 16706, 62, 29762, 28264, 8, 11537, 198, 17953, 62, 31534, 10786,...
2.025
240
import copy import logging import os from typing import Dict, List, Tuple import checksumdir import imageio import numpy as np import torch from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from ..adapter import download_object logger = logging.getLogger("fastface.dataset")
[ 11748, 4866, 198, 11748, 18931, 198, 11748, 28686, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 11, 309, 29291, 198, 198, 11748, 8794, 388, 15908, 198, 11748, 2939, 952, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 2...
3.318681
91
from typing import Optional from typing import Tuple import attr
[ 6738, 19720, 1330, 32233, 198, 6738, 19720, 1330, 309, 29291, 198, 198, 11748, 708, 81, 628 ]
4.1875
16
import pygame import math coef_turn = 0.3 coef_drift = 0.07 # adhrence au sol coef_vel = 10
[ 11748, 12972, 6057, 198, 11748, 10688, 198, 198, 1073, 891, 62, 15344, 796, 657, 13, 18, 198, 1073, 891, 62, 7109, 2135, 796, 657, 13, 2998, 1303, 512, 71, 6784, 35851, 1540, 198, 1073, 891, 62, 626, 796, 838 ]
2.358974
39
import pytest import numpy from grunnur import ( cuda_api_id, opencl_api_id, StaticKernel, VirtualSizeError, API, Context, Queue, MultiQueue, Array, MultiArray ) from grunnur.template import DefTemplate from .mock_base import MockKernel, MockDefTemplate, MockDefTemplate from .mock_pycuda import PyCUDADeviceInfo from .mock_pyopencl import PyOpenCLDeviceInfo from .test_program import _test_constant_memory SRC = """ KERNEL void multiply(GLOBAL_MEM int *dest, GLOBAL_MEM int *a, GLOBAL_MEM int *b) { ${static.begin}; const int i = ${static.global_id}(0); const int j = ${static.global_id}(1); const int idx = ${static.global_flat_id}(); dest[idx] = a[i] * b[j]; } """
[ 11748, 12972, 9288, 198, 11748, 299, 32152, 198, 198, 6738, 1036, 20935, 333, 1330, 357, 198, 220, 220, 220, 269, 15339, 62, 15042, 62, 312, 11, 1280, 565, 62, 15042, 62, 312, 11, 198, 220, 220, 220, 36125, 42, 7948, 11, 15595, 1069...
2.570397
277
ipint2str = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)]) ipstr2int = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])]) src_ip = dict() dst_ip = dict() i =0 with open('hash_key_value') as f: for line in f: i += 1 # if i==8424720: if i==328: break ip = int(line.split(',')[0], 16) dir = int(line.split(',')[1]) if dir==1: src_ip.setdefault(ip, dir) elif dir ==0: dst_ip.setdefault(ip, dir) print len(src_ip) for key in src_ip: print ipint2str(key)+' ' , print '=======' print len(dst_ip) for key in dst_ip: print ipint2str(key)+' ' , # keys = src_ip.items() # keys.sort() # for key in keys: # print ipint2str(key[0]) # keys = dst_ip.items() # keys.sort() # for key in keys: # print ipint2str(key[0])
[ 198, 541, 600, 17, 2536, 796, 37456, 2124, 25, 705, 2637, 13, 22179, 26933, 2536, 7, 87, 29006, 11645, 1174, 72, 8, 4, 11645, 8, 329, 1312, 287, 2837, 7, 18, 12095, 16, 12095, 16, 8, 12962, 198, 541, 2536, 17, 600, 796, 37456, 2...
1.839604
505
import os import sys import string #/c/Program Files (x86)/Windows Phone Kits/8.1/lib/ARM/WindowsPhoneCore.lib
[ 198, 198, 11748, 28686, 198, 198, 11748, 25064, 198, 11748, 4731, 628, 628, 198, 2, 14, 66, 14, 15167, 13283, 357, 87, 4521, 20679, 11209, 14484, 40297, 14, 23, 13, 16, 14, 8019, 14, 33456, 14, 11209, 6132, 14055, 13, 8019, 198 ]
2.809524
42
# Copyright 2015-2017 FUJITSU LIMITED # # 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 mock from webob import response from monasca_log_api.middleware import role_middleware as rm from monasca_log_api.tests import base
[ 2, 15069, 1853, 12, 5539, 376, 52, 41, 2043, 12564, 40880, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 137...
3.686869
198
import logging
[ 11748, 18931, 628, 628, 628, 198 ]
3.5
6
from bast import Route route = Route() route.get('/', 'HelloController.index')
[ 6738, 19918, 1330, 18956, 198, 198, 38629, 796, 18956, 3419, 198, 38629, 13, 1136, 10786, 14, 3256, 705, 15496, 22130, 13, 9630, 11537, 198 ]
3.333333
24
from paradrop.base.output import out from paradrop.lib.utils import uci from . import configservice, uciutils def getOSWirelessConfig(update): """ Read settings from networkInterfaces for wireless interfaces. Store wireless configuration settings in osWirelessConfig. """ # old code under lib.internal.chs.chutelxc same function name interfaces = update.new.getCache('networkInterfaces') if interfaces is None: return wifiIfaces = list() for iface in interfaces: # Only look at wifi interfaces. if iface['netType'] != "wifi": continue config = {'type': 'wifi-iface'} options = { 'device': iface['device'], 'network': iface['externalIntf'], 'mode': iface.get('mode', 'ap') } # Required for AP and client mode but not monitor mode. if 'ssid' in iface: options['ssid'] = iface['ssid'] # Optional encryption settings if 'encryption' in iface: options['encryption'] = iface['encryption'] if 'key' in iface: options['key'] = iface['key'] # Add extra options. options.update(iface['options']) wifiIfaces.append((config, options)) update.new.setCache('osWirelessConfig', wifiIfaces) def setOSWirelessConfig(update): """ Write settings from osWirelessConfig out to UCI files. """ changed = uciutils.setConfig(update.new, update.old, cacheKeys=['osWirelessConfig'], filepath=uci.getSystemPath("wireless"))
[ 6738, 11497, 1773, 13, 8692, 13, 22915, 1330, 503, 198, 6738, 11497, 1773, 13, 8019, 13, 26791, 1330, 334, 979, 198, 198, 6738, 764, 1330, 4566, 15271, 11, 334, 979, 26791, 198, 198, 4299, 651, 2640, 29451, 1203, 16934, 7, 19119, 2599...
2.373723
685
import taichi as ti import numpy as np from functools import reduce # from sph_base import SPHBase # ti.init(arch=ti.cpu) # Use GPU for higher peformance if available ti.init(arch=ti.gpu, device_memory_GB=4, packed=True) # # res = (720,720) res = (512,512) dim = 2 assert dim > 1 screen_to_world_ratio = 50 bound = np.array(res) / screen_to_world_ratio print(bound) # Material material_boundary = 0 particle_radius = 0.05 # particle radius particle_diameter = 2 * particle_radius support_radius = particle_radius * 4.0 # support radius m_V = 0.8 * particle_diameter ** dim particle_max_num = 2 ** 15 particle_max_num_per_cell = 100 particle_max_num_neighbor = 200 particle_num = ti.field(int, shape=()) # gravity = -98.0 # viscosity = 0.05 # density_0 = 1000.0 # mass = m_V * density_0 dt =3e-4 exponent = 7.0 stiffness = 50.0 # x = ti.Vector.field(dim, dtype=float) v = ti.Vector.field(dim, dtype=float) d_velocity = ti.Vector.field(dim, dtype=float) density = ti.field(dtype=float) pressure = ti.field(dtype=float) material = ti.field(dtype=int) color = ti.field(dtype=int) particle_neighbors = ti.field(int) particle_neighbors_num = ti.field(int) particles_node = ti.root.dense(ti.i, particle_max_num) particles_node.place(x,v,d_velocity, density, pressure, material, color,particle_neighbors_num) # Grid related properties grid_size = support_radius grid_num = np.ceil(np.array(res) / grid_size).astype(int) print(grid_num) grid_particles_num = ti.field(int) grid_particles = ti.field(int) padding = grid_size particle_node = particles_node.dense(ti.j, particle_max_num_neighbor) particle_node.place(particle_neighbors) index = ti.ij if dim == 2 else ti.ijk grid_node = ti.root.dense(index, grid_num) grid_node.place(grid_particles_num) cell_index = ti.k if dim == 2 else ti.l cell_node = grid_node.dense(cell_index, particle_max_num_per_cell) cell_node.place(grid_particles) # ======================================== # # boundary particle # circular_max_num=1000 circular_num= ti.field(int, shape=()) circular_node = ti.root.dense(ti.i, circular_max_num) c_x=ti.Vector.field(dim, dtype=float) c_v=ti.Vector.field(dim, dtype=float) c_f=ti.Vector.field(dim, dtype=float) c_r=ti.field(float) c_m=ti.field(float) fixed = ti.field(int) circular_node.place(c_x,c_v,c_f,c_r,c_m,fixed) Young_modulus=2000000 # rest_length = ti.field(dtype=float, shape=(circular_max_num, circular_max_num)) Young_modulus_spring=921000 dashpot_damping=300# =0.2# def substep(): grid_particles_num.fill(0) particle_neighbors.fill(-1) solve() =0 =[0,0] def (): if [0]==0 and [1]==0 : for i in range(,particle_num[None]): if(material[i]==2): material[i] = 1 else: for i in range([0],[1]): material[i] = 1 # @ti.kernel def add_particle_cube(pos,size,material,color_): li=(int)(size[0]*10) lj=(int)(size[1]*10) for i in range(li): for j in range(lj): pass add_particle(pos[0]+i/18,pos[1]+j/18,0,0,material,color_) if(==0):_=1 num=circular_num[None] c_x[num] = ti.Vector([pos_x, pos_y]) # x c_v[num]=ti.Vector([vx, vy]) fixed[num]=fix c_r[num]=r1 c_m[num]=r1*r1 circular_num[None] += 1 # if(spring==1): for i in range(num): # , if(c_x[num]-c_x[i]).norm() < _: # 0.15 rest_length[num, i] = _ # rest_length[i, num] = _ #,, #p_bond #, = ti.field(int, shape=()) # buff=[0,0] def revocation_a_cirulars(): circular_num[None] -= 1 num=circular_num[None] # c_x[num] = ti.Vector([0, 0]) c_v[num]=ti.Vector([0, 0]) c_r[num]=0 c_m[num]=0 fixed[num]=0 for i in range(num): # rest_length[i, num] = 0 rest_length[num, i] = 0 # # if __name__ == "__main__": main()
[ 11748, 20486, 16590, 355, 46668, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 6738, 1257, 310, 10141, 1330, 4646, 201, 198, 201, 198, 2, 422, 599, 71, 62, 8692, 1330, 6226, 39, 14881, 201, 198, 201, 198, 2, 46668, 13, 15003, 7...
1.964635
2,149
import inspect from fnmatch import fnmatchcase from ..sched import meta from .base import BaseFactory
[ 11748, 10104, 198, 6738, 24714, 15699, 1330, 24714, 15699, 7442, 198, 198, 6738, 11485, 1416, 704, 1330, 13634, 198, 6738, 764, 8692, 1330, 7308, 22810, 198 ]
3.961538
26
# Beispielprogramm fr das Buch "Python Challenge" # # Copyright 2020 by Michael Inden if __name__ == "__main__": main()
[ 2, 1355, 8802, 8207, 23065, 76, 1216, 288, 292, 23670, 366, 37906, 13879, 1, 198, 2, 198, 2, 15069, 12131, 416, 3899, 1423, 268, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, ...
2.888889
45
import vstruct from vstruct.primitives import * EI_NIDENT = 4 EI_PADLEN = 7
[ 11748, 410, 7249, 198, 6738, 410, 7249, 13, 19795, 20288, 1330, 1635, 198, 198, 36, 40, 62, 45, 25256, 796, 604, 198, 36, 40, 62, 47, 2885, 43, 1677, 796, 767, 628 ]
2.4375
32
__all__ = ["UserAccount"] _user_root = "identity/users" def _encode_username(username): """This function returns an encoded (sanitised) version of the username. This will ensure that the username is valid (must be between 3 and 50 characters). The sanitised username is the encoded version, meaning that a user can use a unicode (emoji) username if they so desire """ if username is None: return None if len(username) < 3 or len(username) > 150: from Acquire.Identity import UsernameError raise UsernameError("The username must be between 3 and 150 characters!") from Acquire.ObjectStore import string_to_encoded as _string_to_encoded return _string_to_encoded(username) def name(self): """Return the name of this account""" return self._username def username(self): """Synonym for 'name'""" return self.name() def encoded_name(self): """Return the encoded (sanitised) username""" return _encode_username(self._username) def uid(self): """Return the globally unique ID for this account""" return self._uid def login_root_url(self): """Return the root URL used to log into this account""" from Acquire.Service import get_this_service as _get_this_service return _get_this_service().canonical_url() def is_valid(self): """Return whether or not this is a valid account""" return not (self._status is None) def is_active(self): """Return whether or not this is an active account""" if self._status is None: return False else: return self._status == "active" def public_key(self): """Return the lines of the public key for this account""" return self._privkey.public_key() def private_key(self): """Return the lines of the private key for this account""" return self._privkey def status(self): """Return the status for this account""" if self._status is None: return "invalid" return self._status def to_data(self, passphrase, mangleFunction=None): """Return a data representation of this object (dictionary)""" if self._username is None: return None data = {} data["username"] = self._username data["status"] = self._status data["uid"] = self._uid data["private_key"] = self._privkey.to_data(passphrase=passphrase, mangleFunction=mangleFunction) return data
[ 834, 439, 834, 796, 14631, 12982, 30116, 8973, 198, 198, 62, 7220, 62, 15763, 796, 366, 738, 414, 14, 18417, 1, 628, 198, 4299, 4808, 268, 8189, 62, 29460, 7, 29460, 2599, 198, 220, 220, 220, 37227, 1212, 2163, 5860, 281, 30240, 357...
2.689906
961
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from saharaclient.api import base # NOTE(jfreud): keep this around for backwards compatibility JobBinariesManager = JobBinariesManagerV1
[ 2, 15069, 357, 66, 8, 2211, 7381, 20836, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, ...
3.69898
196
# -*- coding: utf-8 -*- import pytest
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 12972, 9288, 628 ]
2.105263
19
# generate 900k word and 900k query to test the runtime from main import TrieTree import time import random vocal = list(range(26)) trie = TrieTree() words = [[random.choice(vocal) for _ in range(random.randrange(1, 11))] for _ in range(100000)] queries = [[random.choice(vocal) for _ in range(random.randrange(1, 11))] for _ in range(100000)] begin = time.time() for word in words: trie.insert(word) insert_end = time.time() for query in queries: trie.query(query) end = time.time() print("insert time used:", insert_end - begin, 's') print("query time used:", end - insert_end, 's') print("time used:", end - begin, 's')
[ 2, 7716, 15897, 74, 1573, 290, 15897, 74, 12405, 284, 1332, 262, 19124, 198, 198, 6738, 1388, 1330, 309, 5034, 27660, 198, 11748, 640, 198, 11748, 4738, 198, 198, 85, 4374, 796, 1351, 7, 9521, 7, 2075, 4008, 198, 198, 83, 5034, 796,...
2.799127
229
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from openvino.tools.mo.ops.mvn import MVNOnnx from openvino.tools.mo.front.common.partial_infer.utils import int64_array from openvino.tools.mo.front.extractor import FrontExtractorOp from openvino.tools.mo.front.onnx.extractors.utils import onnx_attr
[ 2, 15069, 357, 34, 8, 2864, 12, 1238, 2481, 8180, 10501, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 6738, 1280, 85, 2879, 13, 31391, 13, 5908, 13, 2840, 13, 76, 85, 77, 1330, 32947, 45, ...
2.8
120
""" Module for managing enemies. """ import random import constants as const import pygame import random import platforms from spritesheet_functions import SpriteSheet
[ 37811, 198, 26796, 329, 11149, 5775, 13, 198, 37811, 198, 11748, 4738, 198, 11748, 38491, 355, 1500, 198, 11748, 12972, 6057, 198, 11748, 4738, 198, 11748, 9554, 220, 198, 220, 198, 6738, 42866, 25473, 62, 12543, 2733, 1330, 33132, 3347, ...
2.830986
71
import argparse import inspect import logging import sys from .__main__ import setup_logging log = logging.getLogger() DESCRIPTION = """ hic-internal is used for automation, not intend to be used by end user. Use hicluster instead. """ EPILOG = ''
[ 11748, 1822, 29572, 198, 11748, 10104, 198, 11748, 18931, 198, 11748, 25064, 198, 6738, 764, 834, 12417, 834, 1330, 9058, 62, 6404, 2667, 198, 198, 6404, 796, 18931, 13, 1136, 11187, 1362, 3419, 198, 198, 30910, 40165, 796, 37227, 198, ...
3.234568
81
import asyncio import socket import pytest from mock import AsyncMock, MagicMock, patch import aioatomapi.host_resolver as hr from aioatomapi.core import APIConnectionError
[ 11748, 30351, 952, 198, 11748, 17802, 198, 198, 11748, 12972, 9288, 198, 6738, 15290, 1330, 1081, 13361, 44, 735, 11, 6139, 44, 735, 11, 8529, 198, 198, 11748, 257, 952, 37696, 15042, 13, 4774, 62, 411, 14375, 355, 39436, 198, 6738, 2...
3.083333
60
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from .. import models
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 16529, 35937, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321...
5.100917
109
import numpy as np import os, cv2 imgs = np.load('test_set_ck_extended_no_resize.npy') lbls = np.load('test_labels_ck_extended_no_resize.npy') for i in range(imgs.shape[0]): print (lbls[i]) cv2.imshow('img', imgs[i]) cv2.waitKey(0)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 11, 269, 85, 17, 198, 198, 9600, 82, 796, 45941, 13, 2220, 10786, 9288, 62, 2617, 62, 694, 62, 2302, 1631, 62, 3919, 62, 411, 1096, 13, 77, 9078, 11537, 198, 75, 2436, 82, 796, 459...
2.043103
116
from pydantic import BaseModel import typing as t ### SCHEMAS FOR USERS ###
[ 6738, 279, 5173, 5109, 1330, 7308, 17633, 198, 11748, 19720, 355, 256, 628, 198, 21017, 22374, 3620, 1921, 7473, 1294, 4877, 44386, 628, 628, 628, 628 ]
3.269231
26
import asyncio import json import logging import re import homeassistant.helpers.config_validation as cv import voluptuous as vol from discord import ActivityType, Spotify, Game, Streaming, CustomActivity, Activity, Member, User from homeassistant.components.notify import PLATFORM_SCHEMA from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_START) from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) REQUIREMENTS = ['discord.py==1.5.1'] CONF_TOKEN = 'token' CONF_MEMBERS = 'members' CONF_IMAGE_FORMAT = 'image_format' DOMAIN = 'sensor' ENTITY_ID_FORMAT = "sensor.discord_{}" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_MEMBERS, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_IMAGE_FORMAT, default='webp'): vol.In(['png', 'webp', 'jpeg', 'jpg']), })
[ 11748, 30351, 952, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 302, 198, 198, 11748, 1363, 562, 10167, 13, 16794, 364, 13, 11250, 62, 12102, 341, 355, 269, 85, 198, 11748, 2322, 37623, 5623, 355, 2322, 198, 6738, 36446, 1330, 2464...
2.675516
339
""" Escreva um programa que converta uma temperatura, digitando em graus Celsius e converta para graus Fahrenheit. """ celsius = int(input('Digite a temperatura: ')) fahrenheit = (celsius / 5) * 9 + 32 Kelvin = celsius + 273 print(f'A temperatura {celsius}C em Fahrenheit {fahrenheit}F') print(f'E em Kevin fica {Kelvin} K')
[ 37811, 198, 47051, 260, 6862, 23781, 1430, 64, 8358, 10385, 64, 334, 2611, 4124, 2541, 64, 11, 198, 27003, 25440, 795, 7933, 385, 34186, 304, 10385, 64, 31215, 7933, 385, 35935, 13, 198, 37811, 198, 5276, 82, 3754, 796, 493, 7, 15414,...
2.716667
120
from .crpapi import CRP
[ 6738, 764, 6098, 79, 15042, 1330, 8740, 47, 198 ]
2.666667
9
from fumblr.keys import IMGUR_SECRET, IMGUR_ID from imgurpython import ImgurClient, helpers import os import base64 API_URL = 'https://api.imgur.com/3/' def get_client(): """ Get an API client for Imgur Returns: Imgur client if it is available """ try: return ImgurClient(IMGUR_ID, IMGUR_SECRET) except helpers.error.ImgurClientError: print(f'Error: imgur client error - id: {IMGUR_ID} secret: {IMGUR_SECRET}') def delete_image(deletehash): """ Delete image from Imgur with given deletehash Args: deletehash: Hash id of image to delete Returns: Response from Imgur of image deletion if successful, otherwise False """ client = get_client() if client: try: return client.delete_image(deletehash) except: return False def upload_image(path): """ Upload image at system path to Imgur Example of response data from Imgur upload: {'size': 3527, 'title': None, 'animated': False, 'deletehash': 'YkK79ucEtDDn1b9', 'views': 0, 'width': 187, 'account_url': None, 'in_gallery': False, 'name': '', 'section': None, 'account_id': 0, 'type': 'image/png', 'datetime': 1473926225, 'description': None, 'height': 242, 'bandwidth': 0, 'id': 'AEvnA7h', 'favorite': False, 'nsfw': None, 'link': 'http://i.imgur.com/AEvnA7h.png', 'is_ad': False, 'vote': None} Args: path: System path of image Returns: Response from Imgur """ client = get_client() if client: image_path = os.path.abspath(path) upload = client.upload_from_path(image_path) return upload def upload(image): """ Upload image to Imgur from file Args: image: File object Returns: Imgur response object """ client = get_client() if client: contents = image.read() b64 = base64.b64encode(contents) data = { 'image': b64, 'type': 'base64' } return client.make_request('POST', 'upload', data, True) def upload_from_url(url): """ Upload image to Imgur from url Args: url: URL of image Returns: Imgur Response object if successful, otherwise False """ client = get_client() if client: try: return client.upload_from_url(url) except helpers.error.ImgurClientError: print('Error: imgur client error') return False def get_image(id): """ Return image data for image with given id Args: id: Imgur image id Returns: Response from Imgur """ client = get_client() if client: image_data = client.get_image(id) return image_data
[ 6738, 277, 15566, 13, 13083, 1330, 8959, 38, 4261, 62, 23683, 26087, 11, 8959, 38, 4261, 62, 2389, 198, 6738, 33705, 333, 29412, 1330, 1846, 45073, 11792, 11, 49385, 198, 11748, 28686, 198, 11748, 2779, 2414, 198, 198, 17614, 62, 21886,...
2.195359
1,336
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import boto3 import botocore import os import logging import time import json import datetime log = logging.getLogger() log.setLevel('INFO') bucket = os.environ['BUCKET'] region = os.environ['AWS_REGION'] solution_version = os.environ.get('SOLUTION_VERSION', 'v1.0.0') solution_id = os.environ.get('SOLUTION_ID') user_agent_config = { 'user_agent_extra': f'AwsSolution/{solution_id}/{solution_version}', 'region_name': region } default_config = botocore.config.Config(**user_agent_config) athena_client = boto3.client('athena', config=default_config)
[ 2, 15069, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 11748, 275, 2069, 18, 198, 11748, 10214, 420, 382, 198, 11748, ...
2.71371
248
import json import logging from django.core.management.base import BaseCommand from django.db import transaction from osf.models import AbstractProvider, PreprintProvider, Preprint, Subject from osf.models.provider import rules_to_subjects from scripts import utils as script_utils from osf.models.validators import validate_subject_hierarchy from website.preprints.tasks import on_preprint_updated logger = logging.getLogger(__name__) BEPRESS_PROVIDER = None
[ 11748, 33918, 198, 11748, 18931, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 198, 6738, 42625, 14208, 13, 9945, 1330, 8611, 198, 198, 6738, 267, 28202, 13, 27530, 1330, 27741, 29495, 11, 3771, 4798, 2...
3.576923
130
# pylint: disable=not-callable, no-member, invalid-name, missing-docstring, line-too-long import math import os import subprocess import argparse import shutil import tqdm import plotly.graph_objs as go import torch from e3nn import o3, rsh if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--lmax", type=int, default=2) parser.add_argument("--resolution", type=int, default=500) parser.add_argument("--steps", type=int, default=30) args = parser.parse_args() main(args.lmax, args.resolution, args.steps)
[ 2, 279, 2645, 600, 25, 15560, 28, 1662, 12, 13345, 540, 11, 645, 12, 19522, 11, 12515, 12, 3672, 11, 4814, 12, 15390, 8841, 11, 1627, 12, 18820, 12, 6511, 198, 11748, 10688, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 182...
2.826733
202
# E_LEN = "No es posible operar vectores de diferente mdulo"
[ 2, 198, 36, 62, 43, 1677, 796, 366, 2949, 1658, 1426, 856, 1515, 283, 1569, 310, 2850, 390, 288, 361, 9100, 68, 45243, 43348, 1, 198 ]
2.346154
26
import torch.utils.data as data import os import os.path import numpy as np from numpy.random import randint import torch from colorama import init from colorama import Fore, Back, Style import random from os import listdir from os.path import join, splitext import numpy as np import torch import torch.nn.functional as F import torchvision.transforms.functional as TF from PIL import Image, ImageFilter, ImageFile from torch.utils.data import DataLoader, Dataset from torchvision import transforms init(autoreset=True)
[ 11748, 28034, 13, 26791, 13, 7890, 355, 1366, 198, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 13, 25120, 1330, 43720, 600, 198, 11748, 28034, 198, 198, 6738, 3124, 1689, 13...
3.609589
146
# -*- coding: utf-8 -*- from django.http import HttpResponseForbidden from django.template import loader from django.utils.translation import ugettext_lazy as _ # _msg = _(u'30s(Request too often)') limitip_requred_forbid = _requred_forbid(_msg)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 1890, 37978, 198, 6738, 42625, 14208, 13, 28243, 1330, 40213, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 3...
2.758242
91
from apogee.aspcap import aspcap from apogee.aspcap import mask els=aspcap.elems() for el in els[0]: mask.mkmask(el,globalmask='mask_v02_aspcap.txt')
[ 6738, 2471, 78, 29622, 13, 5126, 11128, 1330, 355, 79, 11128, 198, 6738, 2471, 78, 29622, 13, 5126, 11128, 1330, 9335, 198, 198, 1424, 28, 5126, 11128, 13, 11129, 907, 3419, 198, 1640, 1288, 287, 1288, 82, 58, 15, 5974, 9335, 13, 76...
2.435484
62
""" Unit tests for Random CP optimiser on Cartesian product domains. -- kandasamy@cs.cmu.edu """ # pylint: disable=invalid-name # pylint: disable=abstract-class-little-used import os from . import random_multiobjective_optimiser from ..exd.cp_domain_utils import get_raw_point_from_processed_point, \ load_config_file from ..exd.experiment_caller import get_multifunction_caller_from_config from ..exd.worker_manager import SyntheticWorkerManager # Local imports from ..test_data.multiobjective_hartmann.multiobjective_hartmann \ import objectives as moo_hartmann from ..test_data.multiobjective_park.multiobjective_park \ import objectives as moo_park from ..utils.base_test_class import BaseTestClass, execute_tests from ..utils.reporters import get_reporter def _test_optimiser_results(self, raw_prob_funcs, pareto_vals, pareto_points, history, dcf): """ Tests optimiser results. """ config = load_config_file(dcf) multi_func_caller = get_multifunction_caller_from_config(raw_prob_funcs, config) raw_pareto_points = [get_raw_point_from_processed_point(pop, config.domain, config.domain_orderings.index_ordering, config.domain_orderings.dim_ordering) for pop in pareto_points] self.report('Pareto opt point [-1]: proc=%s, raw=%s.' % (pareto_points[-1], raw_pareto_points[-1])) saved_in_history = [key for key, _ in list(history.__dict__.items()) if not key.startswith('__')] self.report('Stored in history: %s.' % (saved_in_history), 'test_result') assert len(history.curr_pareto_vals) == len(history.curr_pareto_points) for val in pareto_vals: assert len(val) == multi_func_caller.num_funcs for pt in pareto_points: assert len(pt) == config.domain.num_domains self.report('Pareto optimal points: %s.' % (pareto_points)) self.report('Pareto optimal values: %s.' % (pareto_vals)) def test_optimisation_single(self): """ Test optimisation with a single worker. """ self.report('') self.report('Testing %s with one worker.' % (type(self))) for idx, (dcf, (raw_prob_funcs,)) in enumerate(self.opt_problems): self.report('[%d/%d] Testing optimisation with 1 worker on %s.' % ( idx + 1, len(self.opt_problems), dcf), 'test_result') self.worker_manager_1.reset() pareto_vals, pareto_points, history = self._run_optimiser(raw_prob_funcs, dcf, self.worker_manager_1, self.max_capital, 'asy') self._test_optimiser_results(raw_prob_funcs, pareto_vals, pareto_points, history, dcf) self.report('') def test_optimisation_asynchronous(self): """ Testing random optimiser with three asynchronous workers. """ self.report('') self.report('Testing %s with three asynchronous workers.' % (type(self))) for idx, (dcf, (raw_prob_funcs,)) in enumerate(self.opt_problems): self.report('[%d/%d] Testing optimisation with 3 asynchronous workers on %s.' % ( idx + 1, len(self.opt_problems), dcf), 'test_result') self.worker_manager_3.reset() pareto_vals, pareto_points, history = self._run_optimiser(raw_prob_funcs, dcf, self.worker_manager_3, self.max_capital, 'asy') self._test_optimiser_results(raw_prob_funcs, pareto_vals, pareto_points, history, dcf) self.report('') class CPRandomMultiObjectiveOptimiserTestCase( CPMultiObjectiveOptimiserBaseTestCase, BaseTestClass): """ Unit tests for random multi-objective optimisation. """ if __name__ == '__main__': execute_tests()
[ 37811, 198, 220, 11801, 5254, 329, 14534, 16932, 6436, 5847, 319, 13690, 35610, 1720, 18209, 13, 198, 220, 1377, 479, 392, 292, 14814, 31, 6359, 13, 11215, 84, 13, 15532, 198, 37811, 198, 198, 2, 279, 2645, 600, 25, 15560, 28, 259, ...
2.105048
1,961