content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def guess_provider_name(controller_name): """Guess provider name from the controller name. If connection to the juju_client fails, no way to know the actual cloud provider name. This can be used to guess the provider name. :param controller_name: Controller name """ controller_name = controller...
f5dcc1dfa1f2273b993d6ef86223e35ccb6cbe03
673,294
import subprocess def _serve_logs(env, skip_serve_logs=False): """Starts serve_logs sub-process""" if skip_serve_logs is False: sub_proc = subprocess.Popen(['airflow', 'serve_logs'], env=env, close_fds=True) return sub_proc return None
1cd95c58ec04921ac697e4e0cb1a6c863032cb32
673,295
def set_initial_params(size: int) -> tuple: """ Set initial parameters: line, spiral, direction, coordinate, done :param size: :return: """ spiral: list = list() while len(spiral) != size: line: list = [0] * size spiral.append(line) direction: str = 'right' coordinate: dict = { ...
8340b96e39f78c242cbef88971bd46065031deb1
673,296
import math def cal_entropy(reformed_labeled_dataset_list): """ :param label_count_dict: {'label 0' : 8, 'label 1': 3, ...} :return: the entropy of this node (before any division) """ label_count_dict = {} for reformed_labeled_data_list in reformed_labeled_dataset_l...
c10a1e4e719590ab64e64f4430987fb27c5f88f5
673,297
import re import time def wait_for_logs(container, predicate, timeout=None, interval=1): """ Wait for the container to emit logs satisfying the predicate. Parameters ---------- container : DockerContainer Container whose logs to wait for. predicate : callable or str Predicate ...
f067485b6681e4b00e2b70a93a39e38b1119df92
673,298
def terminate_connections(connections): """ Kill existing running instances. """ for k, v in connections.iteritems(): kill_list = [] for i in v['instances']: if i.state == 'running': kill_list.append(i.id) if len(kill_list) > 0: print('Terminating...
460b4bf0bb0b5eb92856cae24ed3b8c4e9a70d0d
673,299
import shutil def prepare_empty_dirs(dirs: list): """ 建立空目录。若已经存在,则删除后创建。 parents=True Args: dirs: Path list Returns: dirs 中各个目录的句柄 """ result = [] for d in dirs: if d.exists(): shutil.rmtree(d.as_posix()) d.mkdir(parents=True, exist_ok=Fal...
a672542576ea7eeff8b99aa43d223cfe48069ecc
673,300
def parse_image(image): """Parse image Args: image (object): object from DICOMDIR level 3 object (children of series) Returns: appending_keys """ relative_path = "/".join(image.ReferencedFileID) sop_class = image.ReferencedSOPClassUIDInFile syntax = image.ReferencedTrans...
2eb8381b3978114826e4d7ec79671612bd0b158e
673,301
def char_range(first, last): """ Set of characters first..last. """ return set(chr(c) for c in range(ord(first), ord(last) + 1))
3c2299aef3cc1e562afe85cdd680f7b7116aa77b
673,302
def time(present_t, start_t, lap): """ calculates the starting time of the present lap :param present_t: present time :param start_t: starting time of the lap :param lap: duration of the lap :return: starting time of the present lap """ if present_t - start_t >= lap: start_t = pr...
9ca2984fe607264023e9aa48802e625209e506ee
673,303
def update_header(login_response, call_header): """Function to process and update the header after login""" token = str(login_response).split()[2] + " " + str(login_response).split()[3] call_header['Authorization'] = token return call_header
5af2fef622bcf76339ac6b968af61ecb0000093c
673,304
def invertAry(ary): """ Add color of the given hue to an RGB image. By default, set the saturation to 1 so that the colors pop! """ ary = 255 - ary return ary
644da5586f834e88c91d0c0d5c5607e42471c2a0
673,305
def split_header(name): """ split fasta header to id and description :param name: :return: """ parts = name.split(None, 1) if len(parts) == 1: parts.append("") return parts
48a7b657cd180c4e6112b6e7e014b1ad567e9abb
673,306
import pandas as pd def read_geneset(filepath): """ Function to read in a custom csv file containing the up or down regulated genes for each cell type Inputs: - path to correct csv file. File should have columns named for each cell type, and rows should contain ...
9c0834ddbd02434ac2b26702fb5bf308392f1029
673,307
from datetime import datetime from subprocess import call def run_tests(tests): """ Run a series of test. Produce timing for each :return: dictionary of test timings keyed by test id. """ test_timings = {} for test_id in tests: start = datetime.now() try: rc = cal...
01f92aae22de951c8988d1c1cb35780e5ce3d777
673,308
def xor(message: bytes, key: bytes) -> bytes: """A method that takes two hex strings and returns their XOR combination. The length of the key relevant to the plaintext does not matter, but the order of the parameters do. :param message: The bytes which make up the message to be encrypted/decrypted. :pa...
3665405251fa1586833ccee8d3a4c37fb0de2695
673,309
import torch def log2(input, *args, **kwargs): """ Returns a new tensor with the logarithm to the base 2 of the elements of ``input``. Examples:: >>> import torch >>> import treetensor.torch as ttorch >>> ttorch.log2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0])) tensor([...
32064dc7409d35b794df5a7a23894a574c4902bf
673,310
import os import yaml def parse_yaml(confpath): """ Loads yaml from a config file path does not support arbitrary code in yaml """ try: filepath = os.path.abspath(confpath) except Exception: raise TypeError("config not string type required to specify path: %s" % confpath) with ...
3cc569e509aa2dae264eb03c9601a4fcd82be484
673,311
def binary_search(array, x): """ Binary search :param array: array: Must be sorted :param x: value to search :return: position where it is found, -1 if not found """ lower = 0 upper = len(array) while lower < upper: # use < instead of <= mid = lower + (upper - lower) // 2 ...
087e2f5178bebf8f8e14aa7a92df905bd9da08ba
673,312
def insert_position(player, ship, starting): """Insert a valid position (e.g. B2).""" while True: if starting: position = input(player.name + ", where do you want to place your " + ship[0] + "(" + str(ship[1]) + ")? ").upper() else: position = input(player.name + ", whe...
d5fd397295661816f3ffb512cab9a45f701a56c1
673,313
def select_longest_utr3_exonic_content(transcripts): """Select transcript(s) with longest UTR3 exonic content""" ret = [transcripts[0]] longest = transcripts[0].utr3_exonic_content_length for i in range(1, len(transcripts)): t = transcripts[i] exonic_content_length = t.utr3_exonic_conte...
46b9fd36b766871169cee7783927934ee356ca6f
673,314
import torch def _moments(a, b, n): """ Computes nth moment of Kumaraswamy using using torch.lgamma """ arg1 = 1 + n / a log_value = torch.lgamma(arg1) + torch.lgamma(b) - torch.lgamma(arg1 + b) return b * torch.exp(log_value)
00e38aedd21e7e2ed89bde68b5f6464d4be5a707
673,315
import re def shvarok(s): """!Returns True if the specified environment variable name is a valid POSIX sh variable name, and False otherwise. @param s an environment variable name""" if re.search(r'\A[A-Za-z][A-Za-z0-9_]*\z',s): return True else: return False
15dfb72f81a51021e6271158e17a341bccac7c00
673,317
def single_byte_xor(byte_array, key_byte): """XOR every byte in 'byte_array' with the 'key_byte'""" result = bytearray() for i in range(0, len(byte_array)): result.append(byte_array[i] ^ key_byte) return result
8f7857f8572a493129fa87ec525c687137deec91
673,318
def get_region_for_chip(x, y, level=3): """Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the sp...
3b018413e57fc7baa3d36e816b47b545c9d8c1e5
673,321
def get_rem_matches(games): """ Returns list of tuples of all the match instances. """ rem_matches = [] for key, value in games.items(): rem_games = [(key, k) for k, v in value.items() for _ in range(2-v)] rem_matches.extend(rem_games) return rem_matches
f45cba1e0ae614bc1096a4a14718ff52c86e0116
673,322
from datetime import datetime def transform_time_to_hour(time_str: str) -> int: """ Read the visum formatted time and return the number of minutes :param time_str: the visum formatted time string :return: the minutes """ return datetime.strptime(time_str, "%H:%M:%S").hour
914eac5869d1648e9423c04d6607f699d1b222be
673,324
def get_calendar_event_id(user, block_key, date_type, hostname): """ Creates a unique event id based on a user and a course block key Parameters: user (User): The user requesting a calendar event block_key (str): The block key containing the date for the calendar event date_type (st...
0286a74d04a377d8033a901fe394ef2eb8389c1f
673,325
def dnn_activation(data, model, layer_loc, channels=None): """ Extract DNN activation from the specified layer Parameters: ---------- data[tensor]: input stimuli of the model with shape as (n_stim, n_chn, height, width) model[model]: DNN model layer_loc[sequence]: a sequence of keys to find...
516a643b049df7f0b9d4a6be74af6998001eb303
673,326
from typing import Any def expected(request) -> Any: """Expected test case result.""" return request.param
e7d889f0111fc711b92a8fbdd3d0d4985a166729
673,327
def _get_option_margin(quote, last_price, underlying_last_price): """返回每张期权占用保证金,只有空头持仓占用保证金""" # 期权保证金计算公式参考深交所文档 http://docs.static.szse.cn/www/disclosure/notice/general/W020191207433397366259.pdf if quote["option_class"] == "CALL": # 认购期权义务仓开仓保证金=[合约最新价 + Max(12% × 合约标的最新价 - 认购期权虚值, 7% × 合约标的最新价)...
466147a0add61b712c5f420e11d58a8e71884178
673,328
def _adjust_n_years(other, n, month, reference_day): """Adjust the number of times an annual offset is applied based on another date, and the reference day provided""" if n > 0: if other.month < month or (other.month == month and other.day < reference_day): n -= 1 else: if ot...
75e6df6af52f674bdcf53e17692b69a4e7233ada
673,329
def server(request): """ server param. """ return request.config.getoption("--server")
fee09b276453b9e70b58b5d98302401f3f31f436
673,330
def get_data_type_from_url(url): """ Guess and return the data_type based on the url """ data_type = None valid_data_types = ["scoreboard", "recap", "boxscore", "playbyplay", "conversation", "gamecast"] for valid_data_type in valid_data_types: if valid_data_type in url: data_type = v...
6e6749e3dd4efac8fe4b5b0960fd32d564d97cb5
673,331
def project_scales(project): """Read the project settings about project scales. It might be an empty list if the checkbox is not checked. Only for QGIS < 3.10. :param project: The QGIS project. :type project: QgsProject :return: Boolean if we use project scales and list of scales. :rtype:...
c3ec7851fd0ce1af21b2dd20fdbfcc8fb492bdf7
673,333
import os def GetAvailableFilename(suggestion, suggestGiven = True): """GetAvailableFilename(suggestion) -> str Gets the next available filename given the suggestion. It returns suggestion if suggestion does not correspond to a file and suggestGiven is True. Othewise it will return the next file...
78f1c0da8d5c2467135766e3f60e18f05c82b789
673,334
def getDate(splitmem): """ """ attr = splitmem[1] return(attr[0].split('"')[3])
1c30273c649e14175322a8fdb4cd26230aa18b51
673,335
def clean_path(path): """ Add ws:///@user/ prefix if necessary """ if path[0:3] != "ws:": while path and path[0] == "/": path = path[1:] path = "ws:///@user/" + path return path
df4b2f73560121bcc7ba9c14eb7c6035afd3b27d
673,336
def strip_comments(s): """Strips the comments from a multi-line string. >>> strip_comments('hello ;comment\\nworld') 'hello \\nworld' """ COMMENT_CHAR = ';' lines = [] for line in s.split('\n'): if COMMENT_CHAR in line: lines.append(line[:line.index(COMMENT_CHAR)]) ...
06674a5e84c9b8e397009d4fac93c76a1b4e07d7
673,337
import os import glob def get_examples(selector=''): """Returns the filenames of examples bundled with this version. A number of example models are included with the distribution. This method returns the filenames to those examples. Filtered by the argument. :param selector: a filter expression to b...
ea751aef8400beff72afc1f1595cbf2e65508819
673,338
def translate_p_vals(pval, as_emoji=True): """ Translates ambiguous p-values into more meaningful emoji. Parameters ---------- pval : float as_emoji : bool (default = True) Represent the p-vals as emoji. Otherwise, words will be used. Returns ------- interpreted : string "...
993df8319c2bc6bb201864909289f7efca0aa681
673,339
def get_f_2p(var1, var2): """ """ f = var1 / var2 return f
4399153ad8345b2c124a8dc73250f08d14df1a60
673,340
import os import stat def get_filesize(filename): """Get the size of a file in bytes""" mode = os.stat(filename) return mode[stat.ST_SIZE]
bb60ffa7519347e1dbb5212295f846fa06b128a1
673,341
from typing import Union def convert_type(num: str) -> Union[int, float, str]: """ This function is used to convert string to int or float depending on the value """ try: int(num) return int(num) except ValueError: try: float(num) return float(nu...
bf774136c180474e53ca061506b6e44066696c06
673,342
def str2LaTeX(python_string): """ Function that solves the underscore problem in a python string to :math:`\LaTeX` string. Parameters ---------- python_string : `str` String that needs to be changed. Returns ------- LaTeX_string : `str` String with the new underscor...
79fca8841215880cd1ff47862672f8d685485ff1
673,343
import argparse def parse_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser(description='DSNT human pose model evaluator') parser.add_argument( '--search-dir', type=str, default='out/', metavar='PATH', help='base directory to search for models in (default="out/"...
26e3b354ab1a629f02a947fe279d484ab82ec9f9
673,344
def generate_next_number(previous, factor, multiple): """Generates next number in sequence""" while True: value = (previous * factor) % 2147483647 if value % multiple == 0: return value previous = value
b5331eab88f8e369f6de666f4b9b3326896ac6bb
673,345
from pathlib import Path import subprocess def compare_content_of_files(file_a: Path, file_b: Path) -> bool: """Compares the content of two files. Returns True if matching and False if missmatching. """ with subprocess.Popen( args=["diff", file_a.absolute(), file_b.absolute()], stdout...
b11d9e01574df3a2bd3663d8e96cd911aec6ae23
673,347
def gridlist(a, b): """ As for gridarray(), but for Python lists - only 1d input lists allowed. """ ab = [] for aa in a: for bb in b: ab.append([aa, bb]) return ab
6b946b0fdf9d4f6cd4bafb80461ef8e769850ce9
673,348
import copy def merger(a, b): """ Merges two, potentially deep, objects into a new one and returns the result. Conceptually, 'a' is layered over 'b' and is dominant when necessary. The output is 'c'. 1. if 'a' specifies a primitive value, regardless of depth, 'c' will contain that value. 2. if...
9e3578268ae0acc13df8aa274bb996645e550610
673,349
import telnetlib import socket import logging import errno def connect_telnet(router, port): """ Establish a telnet connection to a router on a given port """ # # Establish a telnet connection to the router try: # Init telnet telnet_conn = telnetlib.Telnet(router, port, 3) ...
758b7c32944580415a277ac05a97a74d78a69d12
673,350
def ip_range(network): """Return tuple of low, high IP address for given network""" num_addresses = network.num_addresses if num_addresses == 1: host = network[0] return host, host elif num_addresses == 2: return network[0], network[-1] else: return network[1], networ...
b0c4f17e6a8646a92e7141828efc7e364b5a547d
673,351
import argparse def _get_args(): """Get arguments from the user.""" parser = argparse.ArgumentParser( prog='seafood-boil', description='Calculate seafood boil ratios.') parser.add_argument('-i', '--input', type=str, required=True, help='Meal plan to parse. Detailed ...
c7dad246007540319e505da9a6cc22a2bf340921
673,354
import numpy def _exp_2D_data0(params, times=None, cont=None): """Returns a residue between time dependent matrix data and a matrix multipled by a sum of exponentials """ if times is None: raise Exception("Times have to be supplied") if cont is None: raise Exception("S...
386f13d51dbc8bedcdb39b562aff6b34a09d1530
673,355
def none_split(val): """Handles calling split on a None value by returning the empty list.""" return val.split(', ') if val else ()
13be5a7ad226c07b70dc566027c17cc19c120510
673,356
def part1(moons, steps): """ >>> part1([Moon(-1, 0, 2), Moon(2, -10, -7), Moon(4, -8, 8), Moon(3, 5, -1)], 10) 179 """ for s in range(steps): #print(f"{moons[2]} - Step {s}") for moon in moons: moon.apply_gravity(moons) for moon in moons: moon.apply_ve...
df366e5684b098a60a347a97d7bd12cf9b930418
673,357
import os def get_key(): """Get application key.""" return os.environ.get('key')
13f74d2ded33e4312d2eeeb83be94db99b2e6824
673,358
import os def get_data_dir(): """Returns the directory of the package. """ return os.path.join(os.path.dirname(__file__), 'examples', 'data')
0c05cee7cba4fe906eca18c470a6843bc3ec949f
673,359
import io def render_bytes(f): """Call f(buf) and contruct a BytesIO buf object. Example: render_bytes(f=lambda buf: plt.savefig(buf)) Returns: buf io.BytesIO object """ buf = io.BytesIO() f(buf) buf.seek(0) return buf
75a22037564b970ee3b2662759c15fccd81bf9f6
673,360
def group_tokens( maptokenslist, token_padding, group_padding, align='bottom'): """adjust token positions to group them at the top of the map takes a list of token_dicts returns a position padded combined token dict """ print("\nRELOCATING TOKENS") def get_aligned_pos(alignment, index,...
0c717a0e300a4e16bb609323cbe71eb629545f48
673,361
def distinct_terms(n): """Finds number of distinct terms a^b for 2<=a<=n, 2<=b<=n""" return len(set([a**b for a in range(2, n+1) for b in range(2, n+1)]))
8200593f3966cf04127984311110404402b7847b
673,362
import os def ModuleToPath(module_name): """Converts the supplied python module into corresponding python file. Args: module_name: (str) A python module name (separated by dots) Returns: A string representing a python file path. """ return module_name.replace('.', os.path.sep) + '.py'
c8481ebd1da0cae76774a020101086850bbcf013
673,363
def t01_SimpleGetPut(C, pks, crypto, server): """Uploads a single file and checks the downloaded version is correct.""" alice = C("alice") alice.upload("a", "b") return float(alice.download("a") == "b")
6f58d83a48856e339a4698f1717a8b464127e02a
673,364
def _find_visible_landmarks(nodeID, global_landmarks, sight_lines_to_global_landmarks): """ The function finds the set of visibile buildings from a certain node, on the basis of pre-computed 3d sight_lines. Only global landmarks, namely buildings with global landmarkness higher than threshold, are considere...
d42d96725ede57be192da25650b4e5521ea64683
673,365
import os def _get_file_name(url_link): """ Return a file name based on url_link, only if file not found. """ # os.rmdir('html_files/') dir_name = "html_files/" if not os.path.isdir(dir_name): os.mkdir(dir_name) fname = url_link.replace("/", "#") fname = os.path.join(dir_name, ...
03021db2ba1a600d44e113837af0b7fa2095c903
673,366
def get_as_list(base: dict, target): """Helper function that returns the target as a list. :param base: dictionary to query. :param target: target key. :return: base[target] as a list (if it isn't already). """ if target not in base: return list() if not isinstance(base[target], l...
1b286f90e04fe025ffc63dca41b4c38c920d1fb4
673,367
from fractions import Fraction from functools import reduce def nCk(n, k): """Simple binomial function, so we don't have to import anything""" from operator import mul # or mul=lambda x,y:x*y return int(reduce(mul, (Fraction(n - i, i + 1) for i in range(k)), 1))
8abd75dda86a17e0e0aee48f886364bb6fbda21a
673,368
def pod_equals(x, y): """ equality for plain-old-data types """ return type(x) == type(y) and x.__dict__ == y.__dict__
e8b1c51210ebfc2011ba75db7e3567c64ccf2558
673,369
import os def create_tech_subfolders(out_scen_path, techs, out_subfolders): """ Creates subfolders for results of each specified technology Parameters ---------- **out_scen_path** : 'directory' Path for the scenario folder to send results **techs** : 'string' Technology ty...
526c2ec968fef55b023dd1a2c93bcd92213ec80d
673,371
def intget(integer, default=None): """Returns `integer` as an int or `default` if it can't.""" try: return int(integer) except (TypeError, ValueError): return default
d40bb6d2c1689f4a76b63ac25e86687149a2e120
673,372
import re def drop_sting_int(l: list, rtype: str) -> list: """ 去掉纯字母或纯数字 :param l: list, 密码列表 :param rtype: 可选str或int :return: 去掉纯字母或纯数字密码列表 """ if rtype not in ['str', 'int']: return l pattern = '^[a-zA-Z]*$' if rtype == 'str' else '^[0-9]*$' return [i for i in l if re.mat...
781eede9e325808de35eb614a3382c5f662d8b1d
673,373
def hexagonal(n): """Returns the n-th hexagonal number""" return n*(2*n-1)
baed71c64f6a0e56f6ad4c4079ea4d217177566d
673,374
def isSubListInListWithIndex(sublist, alist): """ Predicates that checks if a list is included in another one Args: sublist (list): a (sub)-list of elements. alist (list): a list in which to look if the sublist is included in. Result: (True, Index) if the sublist is included in the l...
4870f77deaa1837192bd1e217b9dd7ef58935c51
673,375
import itertools def flatten(lst): """ Impemenation of ramda flatten :param lst: :return: """ return list(itertools.chain.from_iterable(lst))
b205f4391107375786a9133cc2685b8ef54d1ad3
673,376
def add_location_postfix(token_seq, tag_seq, phrase, i_tag_index, i_tag): """ Create token sequence and tag sequence for postfix perturbation """ word_list = phrase.strip().split(" ") if len(word_list) == 1: token_seq.insert(i_tag_index + 1, phrase) tag_seq.insert(i_tag_index + 1, i_...
b7de8df53c9b64912b4af8f7432fb0ccf165a260
673,377
import requests import json def getLastPostOnHabr(): """ Get last post on Habr """ url = "https://m.habr.com/kek/v2/articles/" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0' } params = { "date": "day", "sort": "date...
14416550a4ec608c89d4c5021ffce96905c7bed2
673,379
import signal def timeout(seconds=30, error_message="Test timed out."): """ Timeout decorator to ensure a test doesn't run for too long. adapted from https://stackoverflow.com/a/2282656""" def decorator(func): def _handle_timeout(signum, frame): raise Exception(error_message) def wrapper(*args, **kwargs)...
ab7b9156f88db3d8c7a3c0e6f81c9fd8699ea4d3
673,380
def gcd(x: int, y: int) -> int: """ Euclidean GCD algorithm (Greatest Common Divisor) >>> gcd(0, 0) 0 >>> gcd(23, 42) 1 >>> gcd(15, 33) 3 >>> gcd(12345, 67890) 15 """ return x if y == 0 else gcd(y, x % y)
8e8f51f703085aabf2bd22bccc6b00f0ded4e9ca
673,381
def quick_sort(values): """simple quick sort implementation""" if len(values) == 0: return [] elif len(values) == 1: return values elif len(values) == 2: if values[0] > values[1]: return values[::-1] else: return values pivot = values[0] le...
0415613be200425eca95b43185ca6582c84be4ec
673,382
from glob import glob def list_files_local(path): """ Get file list form local folder. """ return glob(path)
e965d76baadba61ffe8c5314396ef9191b7b886d
673,384
def combine(background_img, figure_img): """ :param background_img: SimpleImage, the background image :param figure_img: SimpleImage, the green screen figure image :return: SimpleImage, the green screen pixels are replaced with pixels of background image """ # (x, y) represent every pixel in the...
07ae5d988fa3c7e5132ad9a50173a682be6cc840
673,385
import numpy as np import time def ackley(x: np.ndarray, a=20, b=0.2, c=2 * np.pi, mean_rt=0, std_rt=0.1) -> np.ndarray: """The Ackley function (http://www.sfu.ca/~ssurjano/ackley.html) Args: x (ndarray): Points to be evaluated. Can be a single or list of points a (float): Parameter of the Ac...
faa0e1bee4b33864f3a9910ccf14854d07aac639
673,386
import socket import struct def ip2long(ip): """ Convert IPv4 address in string format into an integer :param str ip: ipv4 address :return: ipv4 address :rtype: integer """ packed_ip = socket.inet_aton(ip) return struct.unpack("!L", packed_ip)[0]
f80a0b9a72ae74543941b082d600201aa793c6ea
673,387
import os def _find_sub_directory(path, sub_directory): """Reverse walks `path` to find `sub_directory`. Args: path: Path to look for sub_directory in. sub_directory: Name of subdirectory to search for. Returns: Returns full path to `sub_directory` if found otherwise None. """ while path: ...
a5662cb3327d2c83ee79bdd7c92ca4a2f7df903a
673,388
def __pyexpander_helper(*args, **kwargs): """a helper function needed at runtime. This evaluates named arguments. """ if len(args)==1: fn= args[0] elif len(args)>1: raise ValueError("only one unnamed argument is allowed") else: fn= None return(fn, kwargs)
c58deaa68f67d075e47384169283ff7318f49b80
673,389
def _format_result(criterion_name, success, detail): """Returns the SLA result dict corresponding to the current state.""" return {"criterion": criterion_name, "success": success, "detail": detail}
48d08f7e45bcd006052e5835dc9a972212d370ad
673,391
def json_parameter_validation(json_data, required_parameters): """ Check parameter is available in json or not :parameter: json_data: dict, required A dictionary that should be validate by parameter are available or not required_params: list, required Those list of params...
cab97b49c90fe473efac4fd495da1cd65affc53a
673,392
def find_or_create_attr(location_id, attr_type_id, value, db): """Find or create the attr""" cur = db.cursor() find_sql = ('select attr_id from attr ' 'where location_id=? ' 'and attr_type_id=?') insert_sql = ('insert into attr ' '(location_id, attr_...
4ae2ab014ba0c761d2b469c8d81fa7dfd9673906
673,393
import functools def bind_instruction(type_instruction): """ Converter decorator method. Pulse instruction converter is defined for each instruction type, and this decorator binds converter function to valid instruction type. Args: type_instruction (Instruction): valid pulse instruction clas...
bdcfaa050149c420edf4cc79e882f9b3de36dc33
673,394
from pathlib import Path import os def is_dir(path: Path) -> bool: """ 1. It exists 2. It's a dir 3. We can read it """ try: if not path.is_dir(): return False except OSError: return False if not os.access(str(path), os.R_OK): return False return...
3e17d67959cad7a2c771229229f14bb4661d1a9d
673,396
from typing import List import re def split_string(AnyStr: str) -> List[str]: """ Split the Given site codes with comma(,) semi-colon(;) backslash(/) forwardslash(\\) hipen(-) string """ _PATTERN = r'([A-Z]{5}(?:(?:[A-Z0-9][0-9])|(?:[0-9][A-Z0-9])))' _list_of_sites: List[str] = re.findall(_PATTERN, AnyStr...
0e189adf8d787c1ae260fed210498326d59a5b68
673,397
import torch def custom_pca_image(img): """ MUST BE IN (ROWS, COLS, CHANNELS) Parameters ---------- img Returns ------- """ nr, nc, p = img.shape # y_w -> h x w X c im1 = torch.reshape(img, (nr * nc, p)) u, s, v_pca = torch.linalg.svd(im1, full_matrices=False) # ...
e7760db92783aab7552d6d58ef246b32b47f2238
673,398
def transform(data,model): """ Note: This hook may not have to be implemented for your model. In this case implemented for the model used in the example. Modify this method to add data transformation before scoring calls. For example, this can be used to implement one-hot encoding for models that do...
04a6ca4373d738a101ed6cfefbb9dfdce635a045
673,399
import tempfile import os import subprocess import shutil def checkOpenmpSupport(): """ Adapted from https://stackoverflow.com/questions/16549893/programatically-testing-for-openmp-support-from-a-python-setup-script """ ompTest = \ r""" #include <omp.h> #include <stdio.h> int main() { ...
29d2c03c19ffce527b93b7aac7cebef696a3225d
673,400
import torch def sparse_project(M, density): """Return a sparse mask of the largest entries of M in magnitude. """ nparams = int(density * M.numel()) # Implementation 1 # sorted_idx = torch.argsort(M.abs().flatten(), descending=True) # threashold = M.abs().flatten()[sorted_idx[nparams]] # ...
fb79574844d14dd1a9ffed7afeae2532e9dbac1e
673,401
def invert(record): """ Invert (ID, tokens) to a list of (token, ID) Args: record: a pair, (ID, token vector) Returns: pairs: a list of pairs of token to ID """ return [(k,record[0]) for k,v in record[1].iteritems()]
d4deb41f1572824d2a5c6dfcde12d68df8944f70
673,402
import re def filter_quote_numeric(input, fields): """ Quotes a numeric value for graphql insertion :param input: :param fields: :return: """ output = input for field in fields: output = re.sub(r"%s: ([0-9\.]+)(,?)" % field, r'%s: "\1"\2' % field, output) return output
fcdf194b6833b6c3dcb201bf94adfafb2c3a8dc2
673,403
def inv_map(dictionary: dict): """ creates a inverse mapped dictionary of the provided dict :param dictionary: dictionary to be reverse mapped :return: inverse mapped dict """ return {v: k for k, v in dictionary.items()}
2182f0537c8a317ec6332a4be03efee5da6b5837
673,404
import re def is_quote_artifact(orig_text, span): """ Distinguish between quotes and units. """ res = False cursor = re.finditer(r'["\'][^ .,:;?!()*+-].*?["\']', orig_text) for item in cursor: if span[0] <= item.span()[1] <= span[1]: res = item break retu...
3c3f96ca4fb2b302029a80633f33ef906db20bb7
673,405
def subarray(a: list, b: list) -> int: """ Time Complexity: O(n) """ l: int = len(a) hash_table: dict = {a[0] - b[0]: 0} length: int = 0 for i in range(1, l): a[i] += a[i - 1] b[i] += b[i - 1] diff = a[i] - b[i] if diff == 0: length = i + 1 ...
535f8fd77d345a9f672d6b3e7cd04cb0a469ff8c
673,406