content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def naive(data, **kwargs): """The naive forecast for the next point is the value of the previous point. In most forecasting situations, the naive model is a good baseline due to it's simplicity and low computational overhead. Args: data (np.array): Observed data, presumed to be ordered in t...
5410fb5d79c02ae8a0c2e035f677bc996889d87f
641,861
def str_responder(*args, **kwargs): """Responds with an empty string""" return ''
159199ccb5bc2223e9add22e181e494ab2143d57
641,862
def quickRevComp(dna): """A simple reverse complement function for DNA sequences; no error checking""" table = {"A":"T", "T":"A", "G":"C", "C":"G"} ret = "" for c in dna.upper(): if c in table: ret += table[c] else: ret += c return ret[::-1]
67d8f6379f884b1034be5356359997361c1f5f77
641,864
import hashlib def get_hash(filepath): """ Generates unique ID based on hash of the file Args: filepath (str) path to file to read Returns hash of file """ filehash = hashlib.md5() with open(filepath, 'rb') as fobj: for chunk in iter(lambda: fobj.read(2097152), b""): filehash.update...
b66b793bc2152de4042cf3b0567e8d24e00f5cba
641,865
def _group_to_cyclic(group, limit=None): """Determines the degeneracy of each r-cycle in the specified group operations. Args: group (list): The a list of the symmetry group operations. limit (list, optional): The the start and finishing indices of the desired group. Deafult None. ...
2b05dbed610bf9fda9c747ee461d00bab9dd7d02
641,866
def port_status_change(port, original): """ Checks whether a port update is being called for a port status change event. Port activation events are triggered by our own action: if the only change in the port dictionary is activation state, we don't want to do any processing. """ # Be de...
1561ab5c2310f3dc8d8bda1e09bf88b8cf20778f
641,867
def importName( moduleName, name, default_func=None, verbose=False ): """ At run time, dynamically import 'name' from 'moduleName'. """ if verbose: print("Loading %s from %s." % (name, moduleName)) func = default_func try: print("WARNING: VERY SUSPICIOUS WAY OF IMPORTING") ...
3f4964f2c5e3b7f30055b312df6c20620018a1dc
641,868
def get_long_description(): """ Read the long description from the README.md file. """ with open('README.md') as descfile: return descfile.read()
4e86703ba5da486bb3ba6a3207f37d6801ac9664
641,870
def mergesort(unsorted_list): """Sort a list.""" if len(unsorted_list) > 1: mid = len(unsorted_list) // 2 left_half = unsorted_list[:mid] right_half = unsorted_list[mid:] mergesort(left_half) mergesort(right_half) i = 0 j = 0 k = 0 while...
7306234766bba764f233a2770f7c9195e3b99288
641,871
import torch def linp(x, y, steps=5): """ Produces a spherical linear interpolation between two points :param x: :param y: :param steps: :return: """ assert x.size(0) == y.size(0) n = x.size(0) d = torch.linspace(0, 1, steps) return x.unsqueeze(0).expand(steps, n) * d.un...
56fa705acb848776448e5c97769453aa6b941a09
641,872
def biggest(a, b): """ This function returns the biggest of the numbers (but it does checks for None). Input: a: int, first number; b: int, second number. Output: biggest: int, the biggest number of the passed numbers (the non-None number, if one of the ...
8d43f3bb488dd3afe749873a32f091ca399da6ae
641,873
def unflatten(tensor, batch_size, num_rounds): """Unflatten a tensor based on batch_size(B) and num_rounds(N). Args: tensor: Size [B*N, D1, D2, D3, ...] batch_size: B num_rounds = N Returns: unflat_tensor: Size [B, N, D1, D2, ...] """ old_size = tensor.shape expected_fi...
bb09d5dc027798bb87aad4b254d93564d76ac251
641,874
def from_733(u: bytes) -> int: """Convert from ISO 9660 7.3.3 format to uint32_t Return the little-endian part always, to handle non-specs-compliant images """ return u[0] | (u[1] << 8) | (u[2] << 16) | (u[3] << 24)
bc7a47e57ff164b3628049fbeb446f1075a1d35c
641,876
import torch def pocrank_loss(dist_mat, margin,alpha,tval): """ Args: dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N] labels: pytorch LongTensor, with shape [N] """ assert len(dist_mat.size()) == 2 assert dist_mat.size(0) == dist_mat.size(1) N = ...
d022d192f3843ea0dce1c991eaebd69a7c6f34a9
641,878
def lstrip_keep(text): """ Like lstrip, but also returns the whitespace that was stripped off """ text_length = len(text) new_text = text.lstrip() prefix = text[0 : (text_length - len(new_text))] return new_text, prefix
cb1667eb0f5189fbae0d00dcaf0e1f761e1cf3f2
641,879
import numpy import logging def _gather_token_embedding(tensor_names, name2var_dict, tn_pattern): """use pattern to diff source and target.""" target_tn = [] for tn in tensor_names: if (tn_pattern in tn) and ("emb/weights" in tn or "shared/weights" in tn): target_tn.append(tn) # ta...
febed7079732ce26ed90f44b17d3d5c2b5efaf4a
641,880
import torch def ridge_regularize(network, lam): """Apply ridge penalty at all subsequent layers.""" return lam * sum([torch.sum(fc.weight**2) for fc in network.layers[1:]])
d9d6de648991534f710fc1ac26e443fa99c3619e
641,882
from typing import Union def sep_digits(number: Union[int, float, str], precision: int = 2) -> str: """Return number as string with separated thousands. >>> sep_digits('12345678') '12345678' >>> sep_digits(12345678) '12 345 678' >>> sep_digits(1234.5678) '1 234.57' >>> sep_digits(1...
5e928e008aed33b71e6cd5713d4234396276dca7
641,883
def special_mul(x, y): """ :param x: =(x0, x1) :param y: =(y0, y1) :return: (x0y0, x1y2+x2) """ return x[0] * y[0], x[0] * y[1] + x[1]
008b6acec3e62b5f4b57bc17b29081cf596b043a
641,885
import re def get_track_quirk(quirks, cro_track_id): """Return Spotify track id for given CRo track id from quirks.""" q = quirks["tracks"].get(cro_track_id) if q: m = re.search(r"(?:track.)?([0-9a-zA-Z]{22})", q) if m: return m.group(1)
c5a37d3eb84a467ea37efd1c1f7cd7a532cae7b4
641,886
def generate_sns_event(message, topic, subject): """ Generates a SNS Event :param str message: Message sent to the topic :param str topic: Name of the Topic :param str subject: Subject of the Topic :return dict: Dictionary representing the SNS Event """ return { "Records": [{ ...
53e3a4b97032539236d091535e7f746e2e239eed
641,887
import time def Timer(): """Returns a Single representing the number of seconds elapsed since midnight""" ltime = time.localtime() h, m, s = ltime[3:6] return h * 3600.0 + m * 60.0 + s
5df1a0a93fb6974a78c12df81fb9aa7a28752aac
641,888
import time def FunctionTimer(on_done=None): """ To check execution time of a function borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d >>> def logger(details, args, kwargs): #some function that uses the time output ... print(d...
3066beb22b589d1a25175a8fa423399cf33d3209
641,889
from typing import Tuple def split_namespace(s: str) -> Tuple[str, str]: """ Splits a namespace and name into their parts Parameters ---------- s: str string to be split Returns ------- (tuple) namespace: str name: str """ split = s.spl...
118f48dfa3ef560c766efa81bf042762245a6218
641,890
def smart_round(digit, base=None): """change digit to a multiple of base""" if base is None: if digit > 32 * 8: round_base = 32 elif digit > 16 * 8: round_base = 16 else: round_base = 8 else: round_base = base return max(round_base, ro...
29e9bb7f4b8a5373ebb1acfd359780e6fc44fe96
641,891
from operator import mul def compute_mul(tree): """ Compute the Variable that is the output of a multiplication tree. This is the inverse of the operation performed by `parse_mul_tree`, i.e. compute_mul(parse_mul_tree(tree)) == tree. Parameters ---------- tree A multiplication tr...
ad479d3dd44fc9db3eabea9a9dd7d9c38beffcd0
641,892
def doc_string(docstring: str = "default doc"): """Set a documentation string for `function`. Helpful if several functions have the same doc""" def wrapper(function): function.__doc__ += docstring return function return wrapper
5b9957f22b588fb5868a03a2f4e852f19889a84d
641,893
import numpy def d1(S, K, t, r, sigma): # see Hull, page 292 """Calculate the d1 component of the Black-Scholes PDE. :param S: underlying asset price :type S: float :param K: strike price :type K: float :param sigma: annualized standard deviation, or volatility :type sigma: float :pa...
baaf4a7e162c8ce729ad599eba1942a117333b67
641,894
import uuid def get_id(): """Returns a random UUID as a hex string.""" return uuid.uuid4().hex
f7bb88e3bbe1b8eb35c1670e70091e6415995db5
641,895
def drop_unneeded_vars(df): """Drop unneeded variables.""" # vars = ['auto_tag', 'manual_tag', 'up_tag'] vars = ['auto_tag', 'manual_tag'] return df.drop(columns=vars)
38717705494521c1bb44c4aae0950dbb88315c0d
641,896
def local_temp(A, albedo, T, q=30): """Calculate local temperature experienced by a particular daisy type or ground cover. This is a simplified version of the original. q*(A-albedo)+T Arguments --------- A : float Planetary albedo alpha : float Albedo of daisy type T : f...
a0e92e2ae3fbf1226eebed2b19c8d221cf5a267a
641,897
from typing import Any def is_char(*objs: Any, allow_none=False) -> bool: """ Checks if the object is a character. :obj: The object to be checked. :return: True if the object is a character, False otherwise. """ return all( (isinstance(obj, str) and len(obj) == 1) or (allow_no...
952dbc54e047236e4274b5767bd146c2f0e2e931
641,898
def exists_gene_id(db, gene_id): """ Search bar MongoDB: db.genes.find({'gene_id': 'ENSG00000107404'}, fields={'_id': False}) SciDB: aggregate( filter(gene_index, gene_id = 'ENSG00000198734'), count(*)); SciDBnew: ## needs to be updated res = bb.get_genes(gene...
19767a550488d442fe0c034becb2198ae02988be
641,899
def cdn_cache_control(val): """Translate cdn_cache into a Cache-Control HTTP header.""" if val is None: return 'max-age=3600, s-max-age=3600' elif type(val) is str: return val elif type(val) is bool: if val: return 'max-age=3600, s-max-age=3600' else: return 'no-cache' elif type(va...
af3e01ac7c32a406caca105f4fb34b2dd7ea5e4e
641,900
def to_bool(boolean: bool): """ Checks if an argument is of type bool: - If argument is type bool, simply returns argument - If argunent is type str, attempts to convert to type bool - Raises TypeError otherwise :param boolean: bool, str argument to be converted to type bool...
da0848703887ae403934e2d16ddd7634d8348d57
641,901
import torch def get_disaligned_ar_batch(ar_iteration, batch_dict, dict_Y_predicted, device = 'cpu', asyncronous_gpu_transfer = True): """ar_batch_fun that return a dictionary and Y Torch Tensors for...
973a6c0ecc5029646c0cfe5ae682f2bc873b7a43
641,902
from datetime import datetime import os def get_timestamp(path: str) -> datetime: """ returns datetime timestamp of path_item """ return datetime.fromtimestamp(os.path.getmtime(path))
b9930cafba6908fa980090c0d865545d6cb0d36f
641,903
from datetime import datetime def get_current_season(): """ Gets the year of the current fantasy football season. If March or later, return this calendar year. Otherwise, return last year. :return: the year of the current fantasy football season """ now = datetime.now() if now.month > 2: ...
f59589c459131ba127e6f7c0ae55e20b03fecdcd
641,904
def add_star(string): """Add '*' to string >>> assert add_star('fred') == 'fred*' """ return f"{string}*"
180a4f6dd674b275337cd5c3d1ba1c8ad02031b7
641,905
import math def power_of_2_ge(number): """This finds the integer greater than 'number' which is a power of two. It could be useful for zero-filling a data array to be processed with a fast Fourier transform.""" exponent = math.log(number,2) if exponent != int(exponent): int_exp = int(exponent+1) ret...
6ef6efebfc115d78d05d7deafbbe56d3e2cc3fb7
641,907
import torch def compute_ce_loss(asv_predictions, cm_predictions, targets, is_spoof, args): """ Yer standard cross-entropy loss: Just try to get asv and cm predictions individually towards the targets. NOTE: This is not quite right, as the target label does not tell separately should asv pa...
cdb9f9c0195e30aa82edd5b714fb18f630fb7461
641,908
def deep_update(original, updated): """ Attempts to update deeply nested dictionaries + lists :param original/the object to be updated: :param updated/changes to be applied: :return: """ def match_shallow_structure(dictionary_1, dictionary_2): """ utility function to check i...
eed185207c7908cad1ebb1be54f8be27c86ae170
641,909
import click def _cb_bbox(ctx, param, value): """ Click callback to validate a bounding box. Returns ------- tuple (x_min, y_min, x_max, y_max) """ x_min, y_min, x_max, y_max = value if (x_min > y_max) or (y_min > y_max): raise click.BadParameter('self-intersection: ...
c190ebb8b670336ef0fede0528fc033acda82ff3
641,910
def construct_string_literal(input_string, language_tag=""): """ Constructs an English (@en) string literal in turtle format. :param input_string: The string to be formatted as turtle sting literal. :return: English string literal in turtle format :example: construct_string_literal(current...
5692168db888243207300a902db51f29188a70f6
641,911
import os def batch_dir(backend, job_name, remote=False): """ Return a directory from the backend/job_name/remote. """ if remote: new_dir = os.path.join("batch."+backend+".remote", job_name) else: new_dir = os.path.join("batch."+backend, job_name) return os.path.abspath(new_dir)
00db8466c0e263f6c4f3c9700337c0d78d137e5f
641,912
def accuracy_ratio(train_accuracy, test_accuracy): """Calculate the ratio between the train and test accuracy. The ratio is calculated by dividing the test accuracy from thee train accuracy. The result is higher than 1 if the train accuracy is higher than the test accuracy and smaller than 1 if the train a...
b9da1e799eaa93206844d2a0f97344febd51ce62
641,913
import re def _strip_blanks(table): """ Remove blank lines from table (included for "human readability" but useless to us... returns a single string joined by \n newlines Parameters ---------- table : str table to strip as a string Returns ------- single string joined ...
28cbe4e8ef2c94fc43db3928a194a5724b39187b
641,915
def epsf_title(title): """ :param title: :return: """ title.replace(' ', '_') return title
d68e46b9e48358f822f8da1705aeb222860499dc
641,916
def cropped_positions_arcface(annotation_type="eyes-center"): """ Returns the 112 x 112 crop used in iResnet based models The crop follows the following rule: - In X --> (112/2)-1 - In Y, leye --> 16+(112/2) --> 72 - In Y, reye --> (112/2)-16 --> 40 This will leave 16 pixels be...
b7ea37990ca1bc48224fcd44a9f746174d60922e
641,917
from operator import xor def hmac(key: bytes, message: bytes, mac, block_size): """ see https://en.wikipedia.org/wiki/HMAC see https://datatracker.ietf.org/doc/html/rfc2202 """ # Keys longer than blockSize are shortened by hashing them if len(key) > block_size: key = mac.digest(key) #...
59edbb342fcc81d64401be9e999d73a0dc11467b
641,918
def is_parans_exp(istr): """ Determines if an expression is a valid function "call" """ fxn = istr.split('(')[0] if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')': return False plevel = 1 for c in '('.join(istr[:-1].split('(')[1:]): if c == '(': plevel += 1...
3b161e92e43afe5035a96595ad2c94a437b4d972
641,919
import inspect def inherit_docstring(c, meth): """Since Python 3.5, inspect.getdoc is supposed to return the docstring from a parent class if a class has none. However this doesn't seem to work for Cython classes. """ doc = None for ancestor in inspect.getmro(c): try: ancest...
657934baaabfb72888a1e8301ec8809103ee23d9
641,920
from typing import Callable import importlib def get_method(pkg_path: str) -> Callable: """ Returns a method given the full package path of the method, e.g. given the string ``oedtools.schema.get_schema`` it will return the actual method ``get_schema`` from the ``oedtools.schema`` module. :param ...
324baedaed4cb7f5d217afb7645891a6f6eef16a
641,921
def epsg_from_utm_zone(zone): """ Returns the WGS-84 EPSG for a given UTM zone Input: zone(int): Zone, positive values for North Output: epsg code(int). """ if zone > 0: epsg = 32600 + zone else: epsg = 32700 - zone return epsg
85dd9eb4548124591768ed1f316337c3fdabfa05
641,922
import os import json def load_words() -> list: """ Load the word dictionary file and return a set of all words. :rtype: list[str] """ dir = os.path.dirname(os.path.realpath(__file__)) with open('{}/words_dictionary.json'.format(dir)) as word_file: valid_words = list(json.load(word_fil...
3835c833e722911f6ad5b5a8301246f10d38ece2
641,923
import subprocess import shlex def script_cmd(arg_string, working_dir): """Execute command in working_dir and return output""" output = subprocess.call(shlex.split(arg_string), stderr=subprocess.STDOUT, cwd=working_dir) return output
694f9759685b9960f83040e7b0c5abdf22c94535
641,924
def liveobj_valid(obj): """ Check whether obj represents a valid Live API obj. This will return False both if obj represents a lost weakref or is None. It's important that Live API objects are not checked using "is None", since this would treat lost weakrefs as valid. """ return obj != None
ba241abeac835711a1dfc2984c5128e11ae865bf
641,925
def value_for_dsd_ref(kind, args, kwargs): """Maybe replace a string 'value_for' in *kwargs* with a DSD reference.""" try: dsd = kwargs.pop("dsd") descriptor = getattr(dsd, kind + "s") kwargs["value_for"] = descriptor.get(kwargs["value_for"]) except KeyError: pass return ...
ccd95a430a2c0daee644f09b5d32c7ff6f9e6cd0
641,926
from functools import reduce import operator def prod(factors): """ The product of the given factors (iterable) :param factors: :return: """ return reduce(operator.mul, factors, 1.0)
bb9e1659edb684c0ddda6dab0aa07ccc2ed3cd8d
641,927
import re def paragraphs(corpus): """ >>> text = 'P1\n\nP2\nP2\n \t \n\n\n \t\nP3' >>> paragraphs(text) '<p>P1</p>\n<p>P2\nP2</p>\n<p>P3</p>' """ inner_paras_added = re.sub(r'\n\s*\n', '</p>\n<p>', corpus) all_paras_added = f'<p>{inner_paras_added}</p>' return all_paras_added
da365a0a129b9090f98bb1874f309b42acc1e725
641,928
def smart_unicode(_str) -> str: """ Util function from ARAra project. Website: https://github.com/sparcs-kaist/arara/blob/master/libs/__init__.py """ if isinstance(_str, str): return _str else: try: return str(_str, 'utf-8') except UnicodeDecodeError: ...
86710c709104e3c5eed759cd6993d6e7e75e26cc
641,929
import random import logging def get_random_route(rs_api) -> int: """Gets a random route id used for testing""" routes = rs_api.get_routes() index = random.randint(1, len(routes) - 1) route_id = routes[index]['RouteID'] logging.getLogger().info("Selecting RouteID %s", route_id) return route_id
0319dc99fe1357752ef5a5c215a2859b9a94b252
641,930
def prepareDFgeneral(dfAllCancerData): """ Given that the entire PSP cancer data is passed as a dataframe, it i) separates the genes (features) from the target variables, that is: CancerStatus, Project, TumorStage, Race, and Gender ii) asks the user to chose one of them as the class variable i...
b007bd63f44157fd5f941e64eb54d5fc0892e55b
641,931
import pathlib import os def universal_relpath(path: str, context: str) -> str: """Tries to give relative path""" if "/" in path: p = pathlib.PurePosixPath(path) try: return str(p.relative_to(context)) except ValueError: return path else: return os....
7949f4f3ee6d8d5c7e776df80b6dfa73dc8ff706
641,932
def _NameToIndex(name, L): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately,...
10b0a501f199c0a12ec303b8b087ce45c7de1574
641,933
def nm_004333v6_g(): """Create test fixture for NM_004333.6 genomic data.""" return { 'gene': 'BRAF', 'tx_ac': 'NM_004333.6', 'tx_pos_range': (1967, 2086), 'alt_ac': 'NC_000007.14', 'alt_pos_change_range': (140753336, 140753334), 'alt_pos_range': (140753274, 14075...
f8e47ebb47b8dd9ee1e2b7dabf9f33a346028745
641,935
def rhist(ax, data, **keywords): """Creates a histogram with default style parameters to look like ggplot2 Is equivalent to calling ax.hist and accepts the same keyword parameters. If style parameters are explicitly defined, they will not be overwritten """ defaults = { 'facecol...
59cf798b0787cfba9f8cb807b622d491f4b3add3
641,936
def _format_kwargs(kwargs): """Returns a dictionary as key value pairs to be used in tags Usage: >>> _format_kwargs({a:1, b:"2"}) a="1" b="2" """ element_as_str = [] for key, value in kwargs.items(): element_as_str.append('{}="{}"'.format(key, value)) return ' '.join(elem...
a8238c521e78ab25550c323b9b40bf71dcd971b9
641,937
def flatten_arguments(arg_dict): """Flattens a dict of options into an argument list. Parameters ---------- arg_dict : Dict[Str, Any] Dictionary of arguments. Keys should be strings, values may be lists or tuples (for multiple values), booleans (for flags) or any other value tha...
7088ac7d5d4ac7906b9baf526a7d14f90efed832
641,938
import stat def file_groupreadable(path): """Check whether a given path has bad permissons.""" if not bool(stat.S_IRGRP & path.stat().mode): return 'PROB_FILE_NOT_GRPRD'
66138dea25e80344f70f1eec6d72662e0ad453ff
641,939
def computeColorIndex(coverage, cutoffs, numColors) : """Computes index into color list from coverage. Keyword arguments: coverage - The coverage percentage. cutoffs - The thresholds for each color. """ numIntervals = min(numColors, len(cutoffs)+1) for c in range(numIntervals-1) : i...
ff20048541d3df13a98435239202e840429de1e3
641,940
def GetPortStatus(chameleond, port_id): """Gets port status with port_id through chameleond proxy.""" if not chameleond.IsPhysicalPlugged(port_id): return 'Not connected\n' if chameleond.IsPlugged(port_id): return 'Connected\nPlugged\n' return 'Connected\nNot plugged\n'
2d2225c556ce3de4bad6269fa4f73b5a0da4ce13
641,941
def get_low_high_cells(methylation_df, patient, percentage): """ For the given patient calculate the percentage high and low cells, excluding normal cells. :param methylation_df: df containing the average methylation levels for each cell. :param patient: The patient to calculate cells for. :param pe...
d884790e0bf3713ac04748547e3095b917b73cfd
641,942
def _ch(x: int, y: int, z: int): """As defined in the specification.""" return (x & y) ^ (~x & z)
6f63ce6a4ee484581d10809593ca4ed6cafc3118
641,943
def input_data(list_images): """ images are alwyas NHWC. """ assert type(list_images) == list return list_images
8a0b2b9d74577e31ee1c3205a14a6fe186e2df54
641,944
import uuid def generate_barcode_string(length: int = 12) -> str: """Generate a string that can serve as a barcoded identifier. Barcodes will begin with V and end with a checksum integer. """ if length < 12: raise ValueError("length must be >= 12") if length > 25: raise ValueError...
0b7b0dfaa739aa3cd8e6cc3dfe11a6dd7057074b
641,945
def get_colseparators(races: list) -> list: """Responsive design - determine column-arrangement.""" colseparators = [] i = 0 icolcount = 1 for heat in races: i += 1 if heat["round"] == "S" and icolcount == 1: icolcount += 1 colseparators.append(heat["order"]) ...
5a048191d8aa60cc648bbcad4ed156ea0b170f37
641,946
def Windows_pathname(pathname): """Translate between UNIX-style to Windows-style pathnames E.g. "//id14bxf/data" to "\\id14bxf\data""" pathname = pathname.replace("/","\\") return pathname
bc15e0a2263c0320ff83cb42a8a8dbd3b6a2f287
641,947
import os def consistent_slash(path): """ Ensure we're always testing against the '/' os separator (otherwise tests fail against Windows). """ if os.sep != '/': path = path.replace(os.sep, '/') return path
1c2dbc1fec2d0d371c0246c1fcb1980761873c41
641,948
import socket def get_free_port(host: str = "localhost") -> int: """ detect free port and reserve until exit the context """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((host, 0)) port: int = sock.getsockname()[1] sock.close() return port
ad9c0f9e8a46993782faf3a21d86f4d9a2ca686a
641,949
def TransformSplit(r, sep='/', undefined=''): """Splits a string by the value of sep. Args: r: A string. sep: The separator value to use when splitting. undefined: Returns this value if the result after splitting is empty. Returns: A new array containing the split components of the resource. ...
c9288fe011f0f1a45992cfca5e9b4f409d8fe45d
641,950
import argparse def float_range(value): """Ensures that the provided value is a float integer in the range (0., 1.); throws an exception otherwise Parameters ---------- value: float The number to evaluate Returns ------- value: float Returns a float in the range (0., 1.) ...
2f264e74552eea2a36881e493d4c40c9f95bdca7
641,951
def ping(): """Simple route to see if server is alive. Used by tests to poll on server creation.""" return "pong", 200
69e9725e54b72c7758b9073e44d479cadafea7b0
641,952
import torch def MIoU(pred, gt): """ Description: Mean Intersection over Union Params: pred -- the predicted label, tensor of shape (N,H,W,C) gt -- the ground_truth label, tensor of shape (N,H,W,C) Tips: gt needs to be transformed to one_hot form """ intersectio...
c4da0cb179d200ed342e061abea8e06e3d38ba0a
641,953
import torch def default_orientation(num: int, device: str) -> torch.Tensor: """Returns identity rotation transform.""" quat = torch.zeros((num, 4,), dtype=torch.float, device=device) quat[..., -1] = 1.0 return quat
5eddc23ece4e98a264ce8592e95af8c36f2bf9bd
641,955
def th_flatten(x): """Flatten tensor""" return x.contiguous().view(-1)
615e726cb5322cae1ca2faa3a1442667a66e2da4
641,956
def serialize_primitive(primitive): """build a dictionary with the data necessary to construct the given primitive""" args_dict = {name: val for name, val in primitive.get_arguments()} cls = type(primitive) return { 'type': cls.__name__, 'module': cls.__module__, 'arguments': arg...
c06a8472f8f5bfc0d0039c3ea0780837b121171e
641,957
import argparse def get_args() -> argparse.Namespace: """Setup the argument parser Returns: argparse.Namespace: """ parser = argparse.ArgumentParser( description='A playground repo for the DSE-512 course..', add_help=False) # Required Args required_args = parser.add_ar...
1bba7413dad2cf9d060da813e123c5862bfd9bcb
641,958
import functools import string import unicodedata def unaccent(text): """Translate accented characters to their non-accented equivalents""" @functools.cache def unaccent_c(char): if char in string.printable: return char elif unicodedata.combining(char): return None else: return unicodedata.normalize...
1d49eb2089335692d3fb6c28b4a9a8575341945a
641,959
import os def create_database(): """ Ceate database for tiny-ImageNet. @input: NA @output: train_dict: A dictionay contains internal-encoding and its corresponding label. e.g. {'n01443537': [0, 'goldfish, Carassius auratus']} db: A dictionay contains inter...
abe871b116cdb987aa64935170fed848749188b6
641,960
import torch def sample_batch(data, length, batch_size): """ Takes the data (a single sequence of tokens) and slices out a batch of subsequences to provide as input to the model. For each input instance, it also slices out the sequence that is shofted one position to the right, to provide as a target...
d35643d6e3be8a3fc37c010d0de3ff9ec00ec9f4
641,961
def italic(text: str) -> str: """ Return the *text* surrounded by italic HTML tags. >>> italic("foo") '<i>foo</i>' """ return f"<i>{text}</i>"
5439c9d7d3c82c63d9f3ca5980a3d3c360b607d4
641,962
def carddir(deg): """Returns the cardinal direction string from degrees (0° = N, 90° = E, ...) """ return ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'][int(((deg+11.25)%360)/22.5)]
77367c74f9593d173271a6f33e5f84f0bb8ee17a
641,964
def get_primary_registry_uid(service_uid): """Return the primary registry uid of the service with passed service_uid. """ try: root = service_uid.split("-")[0] return "%s-%s" % (root, root) except: return "a0-a0"
b38ad2cf1773781806c4baba6ce480510d4a4a65
641,965
def normalize_name(name): """ When looking up a language-code component by name, we would rather ignore distinctions of case and certain punctuation. "Chinese (Traditional)" should be matched by "Chinese Traditional" and "chinese traditional". """ name = name.casefold() name = name.replace("...
94739eea4963c6b119f1a49c3d72861bf7ad3d4b
641,966
def authenticated_client(client, user): """ Returns an authenticated client """ client.force_login(user) return client
fef1b9076093384c0b1fc2ef3d2ba9e7bee81987
641,967
def filter_dataframe_by_dates(df, start_year, end_year): """ """ filtered_df = df[(df['year'] >= start_year) & (df['year'] <= end_year)] return filtered_df
3a6bd7507de6e036b06d8351888a402cc2c46e7d
641,970
def exchange_info(self): """ | | **Exchange Information** | *Current exchange trading rules and symbol information* :API endpoint: ``GET /dapi/v1/exchangeInfo`` :API doc: https://binance-docs.github.io/apidocs/delivery/en/#exchange-information | """ url_path = "/dapi/v1/exchangeInf...
5f49e1f1bd5cb623a82f072aac8ebd32179f8dde
641,972
def empty_text(_str): """Returns true if null string""" return not _str.strip()
b8c3f852d3cd0a49a951a7c89f0f51932a3f9f91
641,973
def chunk_array(array, num_chunks, len_array): """ Chunk a given list into a given number of smaller lists. :param array: :param num_chunks: :return: """ # return [array[i:i + num_chunks] for i in range(0, len(array), num_chunks)] if len_array > num_chunks: if len_array % num_chu...
8cc4451fd5c6a8360024cbeeebe79448d1d5ed0c
641,974