content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def raises(callable, args, kwargs): """ A function that returns whatever exception is raised by a Callable. Returns None if no exception is raised Parameters ---------- Callable callable: any callable (e.g., function, class, etc.) list args: list of positional arguments to pass to calla...
46cfca31c8ca12eda7ce569caccc252334d464c2
610,753
def l2_reg_loss(model, scale=1e-5): """Get L2 loss for model weights.""" loss = 0.0 for w in model.get_weights(): loss += w.pow(2.).sum() return loss * scale
082358c1791c1113f28269769747f7486a5f90bc
610,760
def bed_convert_coords(reg_s, reg_e, ref_s, ref_e, pol): """ Convert BED coordinates derived from a region within a subsequence of the reference (chromsome or transcript) to chromosome or transcript reference coordinates. Return start + end (BED format) positions. reg_s: Region within s...
f1291aa57afffaa7850249bed8ffc1f74f15fef8
610,761
def parse_ipopt_output(file_name): """Returns a dictionary with the IPOPT summary results. Notes ----- This is an example of the summary at the end of the file: Number of Iterations....: 1013 (scaled) (unscaled) Objective...............:...
e846a122881008fdbcdd33455d12142ff547b462
610,768
def create_name(prefix, size, start=0): """ Create a list of names. If the prefix is "a" and size is 2, the created name list will be ["a0", "a1"]. Args: prefix: Prefix of name. size: Size of names. start: If given, the fiest id will be set to it. (Default: 0) Returns: List of...
45b5fa47426b727eb9f4e6c00b2477b9a3eb8714
610,771
import functools import asyncio def iscoro(func): """Check if the function is a coroutine or if the function is a ``functools.partial``, check the wrapped function for the same. """ if isinstance(func, functools.partial): func = func.func return asyncio.iscoroutinefunction(func)
82a16013ad4606c143268e71e3942d908dd5d9cc
610,775
def make_sequence(seq, name="S"): """ Make unique nodes for sequence graph. """ return ["{}_{}_{}".format(name, i, x) for i, x in enumerate(seq)]
a96bdf456c42cd3aae970b2518e16c448693a182
610,778
def depth2tiles(depth): """Return the total number of tiles in a WWT tile pyramid of depth *depth*.""" return (4 ** (depth + 1) - 1) // 3
1246824e8df04a8ce5d7569d7f8c6c5d65cb1951
610,779
def merge_logfiles(log1, log2): """Merge two log files. If log1 overlaps with log2, the overlapping entries in log1 are discarded. """ first_in_2 = log2['time'][0] keep_from_1 = log1['time'] < first_in_2 for key in log1.keys(): log1[key] = log1[key][keep_from_1] log1.timeseries_...
e169edd3cc7617a20bb96b9b41deea8748f3c56e
610,784
def _bbox_encode(F, ex_rois, gt_rois, means=[0., 0., 0., 0.], stds=[1., 1., 1., 1.]): """ decode bbox inputs: F: symbol or ndarray ex_rois: F, (#img, ..., 4) gt_rois: F, (#img, ..., 4) means: list, (4,) stds: list, (4,) outputs: targets: symbol or ndarray, (#i...
db4ea63835cb0e0a3ab93b0c930c1147787aca6a
610,787
def get_input_dims(grid, y_args, grid_in_dims): """ Returns input dimensions Args: grid np.array((n_samples, n_grid)) or (np.array(n_xgrid), np.array(n_tgrid)) np.array((n_samples, n_tgrid, n_x1grid, n_x2grid, ..., dim_grid)): grid for 1D, 2D, or ND input, respectively ...
579f735d76cdb4a3193a725734307d8e1c584fd8
610,791
def sum_regular(data): """ Sums all elements in passed sequence. You may assume that all elements in passed argument is numeric >>> sum_regular([3, 6, 9]) 18 >>> sum_regular(range(10)) 45 >>> sum_regular((8.2, 6.3, 13.1)) 27.6 >>> sum_regular([]) 0 Args: data: i...
01fe402eea117fcf81f031ec87236b549966c9f5
610,792
def escape_path(path): """Returns path with escaped space and apostrophe""" return path.replace("'", "\\'").replace(" ", "\ ")
5d878d78523a71d2af3a9455bedb2641ce004639
610,794
import re def cc_type(cc_number): """ Function determines type of CC by the given number. WARNING: Creditcard numbers used in tests are NOT valid credit card numbers. You can't buy anything with these. They are random numbers that happen to conform to the MOD 10 algorithm! >>> # ...
9f5c99504f0c7b4ce3c21dac15b8fbb616b0b1c1
610,797
from typing import List def seg_classes() -> List[str]: """ Returns the segmentation class names. """ return ["background", "can", "carton", "milk_bottle", "water_bottle"]
243571bab15410f805b5f269e155211ff36d4490
610,806
def adjacentDiag(x1, y1, x2, y2): """Adjacency including diagonals.""" if 1 >= x1 - x2 >= -1 and 1 >= y1 - y2 >= -1: return True return False
35a5120da9a423fad321b5576bdedde0ddd314af
610,807
def trigger_exists(cursor, trigger_name, schema_name='public'): """ Returns whether or not the trigger function exists in the DB. """ cursor.execute(""" SELECT EXISTS (SELECT 1 FROM information_schema.triggers WHERE trigger_schema = %s AND trigger_name = %s) """, (schema_name, trigger_name))...
2247b81cac61c6a361a41fadb1bdca24ba53484c
610,810
def last(iterable, *default): """Return the last item of an iterable or 'default' if there's none.""" try: iterable = reversed(iterable) except TypeError: pass else: return next(iterable, *default) iterable = iter(iterable) x = next(iterable, *default) for x in iterable: pass return x
4a05ee102dc8c6911587da58ca1abc04bd0ced82
610,813
import six def update_if_changed(obj, values): """ Update fields if changed. :param obj: Document instance :type obj: Document :param values: New values :type values: dict :returns: List of changed (key, value) :rtype: list """ changes = [] for k, v in six.iteritems(values)...
a1ca6d14968f2e78f767a788f611dd9c01f86abf
610,815
import torch def accuracy(y_pred, y_true): """ Computes the accuracy between 2 class tensors """ y_pred = torch.round(y_pred) y_true = torch.round(y_true) right = (y_pred == y_true) return (torch.sum(right) / len(right)).item()
fc2ce821da470ffe19143f00e31021a5e9571c27
610,817
def maybe_shorten_name(powerline, name): """If the user has asked for each directory name to be shortened, will return the name up to their specified length. Otherwise returns the full name.""" max_size = powerline.segment_conf("cwd", "max_dir_size") if max_size: return name[:max_size] r...
7eabebd90b803a0b0fba24d09efa07f8139a6e74
610,819
from typing import TextIO def read_until(f: TextIO, char: str) -> str: """ Returns the text from the current position in the file up to and including the given char. If we hit the end of the file before finding our character, a ValueError is raised. """ buf = "" cur = "" while cur != ...
9750131df37c936d35403fb6c984435d870182e9
610,820
def step_count(peak_times): """ Count total number of steps in the signal. This is simply the number of peaks detected in the signal. Parameters ---------- peak_times : ndarray Times of the peaks detected by :func:`sensormotion.peak.find_peaks`. Returns ------- step_count ...
6f66abf4778c1885067867549748ad4d75dc194c
610,822
import base64 def get_download_link_df_to_csv(df, filename): """Returns a link allowing given pandas dataframe to be downloaded as csv. Args: df: pandas dataframe filename: str, name of file downloaded file will be <filename>.csv Returns: url href for us...
aee563b4d4bb62d8d18d4e02a02dbfcaa49bb83d
610,826
def GetStdHandle(handle): # real signature unknown; restored from __doc__ """ GetStdHandle(handle) -> integer Return a handle to the specified standard device (STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE). The integer associated with the handle object is returned. """ return 0
d9ac3448a7f17c21837af38ea2296f7b426239b7
610,827
def hash_file(hash_object, filepath, blk_size = 8192): """ Run a the contents of a file though a hash generator. :param hash_object: hash object (from :py:mod:`hashlib`) :param filepath: path to the file to feed :type filepath: str :param blk_size: read the file in chunks of that size (in bytes...
d07fe7db3be24c2a37cda0d5de7919f01cdd37bd
610,828
def submatrix(M, idxs): """Return the outer-index product submatrix, `M[idxs, :][:, idxs]`. Parameters ---------- M : scipy.sparse.spmatrix Input (square) matrix idxs : array of int The indices to subset. No index in `idxs` should exceed the number of rows of `M`. Retur...
5b38cf241f3cf6c43e1456b7281c7b4604f49167
610,833
def getcropbox(button): """Given a selenium WebElement, return a PIL friendly (left, top, right, bottom) crop box including the top frame and padding offsets""" topframe = 95 padding = 6 xoffset = padding yoffset = topframe + padding return ( xoffset + button.location['x'], ...
98148e8489dee9d41aa4079195cb541e4b68a777
610,835
def clean_dict(d: dict) -> dict: """ Returns a new dict from the original dict, with all the keys that have None, empty dict and empty list values removed from the dict """ return { k: v for k, v in d.items() if v }
887da5d54f665fd248781134f8df29843f66d173
610,836
def fake_login(value: str) -> bool: """ Check a login / name / mail for a test format """ if value is None: return False value = value.lower() return any( fake in value for fake in ( 'test', 'тест', 'check', 'asd', 'qwe', 'rty', 'sdf', 'sfg', 'sfd', 'hg...
d20fa5044e5a0da2560be01abe48e32185fb5ae2
610,837
def get_required_params(preprocess_config): """ Create a dictionary with required parameters for preprocessing from the preprocessing config. Required parameters are: 'input_dir': Directory containing input image data 'output_dir': Directory to write preprocessed data 'slice_ids': Sl...
b9bfe84e90a7ec7af308982cd61043bc26438aa8
610,838
def _parse_qsub_job_id(qsub_out): """Parse job id from qsub output string. Assume format: "Your job <job_id> ("<job_name>") has been submitted" """ return int(qsub_out.split()[2])
6af319f93cc5ab06fb81597196675e87e3719f5f
610,839
def get_prime_numbers_for_range(num_range): """ Get Prime numbers series Function to take num_range as integer and return prime numbers till number Parameters ---------- num_range : int Range of number Returns ------- list Author ------ Prabodh M Date ...
c243d46258ce0d8e4961fd8387895dbdc3886c4e
610,840
def get_parts(synset): """ Look up and return the part meronyms of a given synset. """ parts = synset.part_meronyms() parts = sorted(lemma.name() for synset in parts for lemma in synset.lemmas()) return parts
0f8b7b563322a1e5f287124dfd3b6f3f56e4d39d
610,844
import re def modify_list(values=[], pattern="", replacement="", ignorecase=False): """ Perform a `re.sub` on every item in the list""" if ignorecase: flags = re.I else: flags = 0 _re = re.compile(pattern, flags=flags) return [_re.sub(replacement, value) for value in values]
c993f6471bba47c82fc8168ebac09baca4549d10
610,845
def compare_spell_results(r1, r2): """ Compares two spellcheck search results to see if they are equal. r1 and r2 are lists of search results, where each result contains a term, selection start, and selection end. """ if not len(r1) == len(r2): return False for idx in range(len(r1)): ...
3a52b32604f2ac3bb3cff4b6dda5ea74426dbab3
610,849
def _is_blank(line): """Return true if `line` is blank.""" return len(line.split())==0
36ecf817278395e5006e9b1746aeaa9851401c04
610,851
def count_n_grams(data, n, start_token='<s>', end_token = '<e>'): """ Count all n-grams in the data Args: data: List of lists of words n: number of words in a sequence Returns: A dictionary that maps a tuple of n-words to its frequency """ # Initialize dict...
43ec77bbb9e25eac080f93eb5333de69b0046eb6
610,854
def get_num_eval_images(hparams): """Returns the number of eval images according to the dataset.""" num_images_map = { 'imagenet': 50000, 'cifar10': 10000, } if hparams.input_data.input_fn not in num_images_map: raise ValueError( f'Unknown dataset size for input_fn {hparams.input_data.in...
50b2a15099d408b69e6a3f41a3091449666fe482
610,857
def get_badge_path(label, value, color): """Return a string representing the expected badge filename. Returns something like 'Training Name|Supported' or 'Training Name|Unsupported'.""" safe_label = label.replace('@', '%40').replace(' ', '%20').replace('-', '--').replace('/', '%2F') safe_value = value.repla...
8b6f32b98adf57e6357ac58c2fdb76aa71413415
610,858
def count_matches(a: str, b: str) -> int: """Returns the number of locations where the two strings are equal.""" assert len(a) == len(b) return sum(int(i == j) for i, j in zip(a, b))
9c901f8c8303f58989db466f0a728bac3f93eb67
610,859
def calc_I_square(height: float) -> float: """Calculate the second moment of square centered on and level with an axis.""" return height**4 / 12
44307193b83809fd4d4f570aee939bc2296fa3df
610,861
import re def parse_modified_output(outfile): """Parse solving statistics from the given file, which contains the stdout from the solver run. """ info = {} with open(outfile) as f: for line in f: line = line.rstrip() m = re.search(r'\| (\S+):\s+(\d+\.\d+|\d+)', line...
f1c01d4da1915e920ea8ec528cfe30be911458ca
610,867
def label_encode_columns(df, cat_cols, mappings): """ Label encode a dataframe categorical columns. Parameters ---------- df : pandas.DataFrame Dataframe with columns to be encoded. cat_cols: list of str Column names to be encoded. mappings: dict of dict Dictionary c...
04414eea8aef761af32954a6c3d09d60bca66a86
610,872
def sort_key(model): """key function for case-insensitive sort by name and type""" iname = model['data']['name'].lower() type_key = { 'directory' : '0', 'notebook' : '1', 'file' : '2', }.get(model['data']['type'], '9') return u'%s%s' % (type_key, iname)
6e6591c48bf6b6ba3525f8b0e078b272260be8ee
610,873
import hashlib def md5(str): """Utility method to get md5 of string. """ hash_md5 = hashlib.md5(str.encode()) return hash_md5.hexdigest()[:7]
734ccd385ae04a9bbca3195e69404a2be4c3e797
610,877
def play_and_train(env, agent, t_max=10 ** 4): """ - run a full game, actions given by agent's e-greedy policy - train agent using agent.update(...) whenever it is possible - return total reward """ total_reward = 0.0 s = env.reset() for t in range(t_max): # get agent to pick ac...
858e516d7ea55c6b0996b16dbf86e536540361a4
610,880
def module_exists(module_name): """Test if a module is importable.""" try: __import__(module_name) except ImportError: return False else: return True
742f1ba27b9638c4ec265e9f4903226c05229fdd
610,884
def with_weighted_lookup(old_fn, lookup, freq): """ Wrap a similarity function, looking up all preds for the given lemmas, weightings the pairwise similarities by frequency, and returning 0 if the lemma was not found :param old_fn: function taking two indices and returning a similarity score :pa...
ff3e109960015ff2e2ec64cdbdfd851b5eada789
610,892
def subreddit_in_grouping(subreddit: str, grouping_key: str) -> bool: """ :param subreddit: subreddit name :param grouping_key: example: "askreddit~-~blackburn" :return: if string is within the grouping range """ bounds = grouping_key.split("~-~") if len(bounds) == 1: print(subreddit...
9aa8a646f5a21753c1971404b3d7355b0cadf190
610,894
import base64 def convert_to_base64(image_file): """Open image and convert it to base64""" print('Converting Image to Base64') with open(image_file, 'rb') as f: return base64.b64encode(f.read()).decode('utf-8')
8013b297db36f71eadf9b6cdec685f984abf2a1e
610,897
import re def clean_doc(s): """ Clean docstring. Args: s (str): Raw docstring Returns: str: Cleaned docstring """ # // Create an instance of {@link RepresentationBaseType } and {@link RepresentationBaseType }. # // Create an instance of RepresentationBaseType and Repres...
fadd41d06515286c912d2596f6a5f4cc6ce5a830
610,905
from typing import OrderedDict def list2orderdict(key_list, val_list): """Return a ordered dict with two lists.""" return OrderedDict(zip(key_list, val_list))
68919e1c5c473121d56df69493ebea9107fe4c77
610,906
def is_sorted(array): """ Helper function to check if the given array is sorted. :param array: Array to check if sorted :return: True if sorted in ascending order, else False """ for i in range(len(array) - 1): if array[i] > array[i + 1]: return False return True
bdc24182fb463d3c38614bcf89c6d0f6866872cb
610,909
def get_default_settings(cfg): """Get default configuration settings.""" cfg.setdefault('all_data_label', 'all') cfg.setdefault('confidence_level', 0.66) cfg.setdefault('merge_identical_pred_input', True) cfg.setdefault('savefig_kwargs', { 'bbox_inches': 'tight', 'dpi': 600, ...
117292f86e51e054dd98413e4bf9d8d84c644c73
610,912
from typing import List def has_name(rr_list: List) -> bool: """Determines if the list contains a label for the resource record.""" return all((len(rr_list) > 2, not rr_list[0].isdigit(), rr_list[0] not in ('IN', 'CS', 'CH', 'HS')))
3c711c08168f9a12180507b46c49270c75ff680b
610,914
import re def parse_title(title): """ Return the title without the year """ return re.sub(r'\s*\(\d{4}\)','', title)
07f3f35ae9dcbb226b327349ffab05ebedbda14c
610,916
def s3_key_for_revision_content(wiki, pageid, revid): """Computes the key for the S3 object storing gzipped revision content.""" return '{:s}page_{:08d}/rev_{:08d}_data.gz'.format( wiki['s3_prefix'], pageid, revid )
dcb270e8edf18cdcb4bec2c9e8f1cff204b5d898
610,921
def rest_get_pr_diff(script, project_key, repo_slug, pr_id, filename, with_markup=True, whitespace='', context_lines=-1, with_comments=True): """ Gets a diff for a particular file in a PR :param script: a TestScript instance :type script: TestScript :param project_key: the proje...
ee8177d6311293f8d3e6ede92b36678e05f09897
610,924
def get_intersection(features_list1: list, features_list2: list) -> list: """ Get intersection between two list of features as strings list :param features_list1: first list of features :param features_list2: second list of features :return: a list of string, composed of all elements both in feature...
d3a2947cfd76d3e949ab748500cb3331d563241c
610,927
def bold(s): """Returns the string s, bolded.""" return f'\x02{s}\x02'
a471ae9de5e222a07eeb3e2eb8e2a840820472a9
610,932
import re def _parse_abbreviation(uri_link): """ Returns a team's abbreviation. A school or team's abbreviation is generally embedded in a URI link which contains other relative link information. For example, the URI for the New England Patriots for the 2017 season is "/teams/nwe/2017.htm". This ...
2444b8d42657b73cc1dcfd054b333a3bf954de7e
610,933
def circulator(circList, entry, limit): """ This method will wrap a list overwriting at the beginning when limit is reached. Args ---- circList: list initial list entry: any item to add to list limit: int size limit for circular list Returns ------- ...
5722cc81f67f3c782203b247c7c651acbbd7b927
610,938
import importlib def is_python_package_installed(python_pkg): """Indicates if a Python package is importable in the current environment.""" try: importlib.import_module(python_pkg) return True except ImportError: return False
98cf3d9bee62ad96e052d70a091214d2baf90412
610,939
import torch def get_position_encoding_expectation(pos_prob, embed_matrix): """ Args: pos_prob: (FloatTensor) [batch_size,seq_len,max_len] embed_matrix: (FloatTensor) [max_len.hidden_size] w/o requires_grad Returns: expectation position encoding """ return torch.matmul(pos_prob,...
a72f9dcaf0759aa6a491e779e0de04b0765cf25f
610,940
import six def to_camel_case_name(name): """ Converts a string from snake_case to camelCase :param name: the string to convert :return: the name converted to camelCase >>> to_camel_case_name(22) 22 >>> to_camel_case_name("hello_world") 'helloWorld' >>> to_camel_case_name("_hello_...
383b53526ade7ea50cd5b8ceaa3d6d38975931b7
610,947
def getMatch(birthdays): """Returns the date object of a birthday that occurs more than once in the birthdays list.""" if len(birthdays) == len(set(birthdays)): return None for a, birthdayA in enumerate(birthdays): for b, birthdayB in enumerate(birthdays[a+1:]): if birthdayA...
6afbc9bfe6df5c1dc06c85688147cdf522d23354
610,950
def norm(x1,x2=None): """ Normalizes x1. If also given as input x2, then normalizes x1 to x2. :param x1: input array :param x2: optional :returns: normalized x1 """ if x2 is None: return x1/x1.max() else: return x1*x2.max()/x1.max()
26a76b485b81dcc34d67a0b9879deda92d8f4035
610,955
from warnings import warn def bounding_box(vol): """ Compute the bounding box of nonzero intensity voxels in the volume. Parameters ---------- vol : ndarray Volume to compute bounding box on. Returns ------- npmins : list Array containg minimum index of each dimension ...
ac24b404e78cb4d47a4a990d6187afe59ccf36ff
610,956
def github_html_url_to_api(url): """ Convert https://github.com links to https://api.gitub.com """ if url.startswith('https://github.com/'): return "https://api.github.com/repos/" + url[19:] else: return None
1ec97c17058991fe8db067136523efc6cfe6aa7d
610,959
def SuiteLikelihood(suite, data): """Computes the weighted average of likelihoods for sub-hypotheses. suite: Suite that maps sub-hypotheses to probability data: some representation of the data returns: float likelihood """ total = 0 for hypo, prob in suite.Items(): like = suite....
a04fd8a2946371092438845813cb051acf2b2304
610,960
def switch_animation_message(name, **params): """ Used to switch an animation params is a dictionary of animation parameters """ return ["animation", { "name": name, "params": params }]
2af7267669dc14ff97df612567046eafd3129a00
610,961
def LQRInput(t, x, fx, fu, fK): """ Function for computing the input commanded by the finite-time horizon LQR controller at time t. Arguments t: Time in [s]. x: State of the three-link robot. x[0]: angular position of link 1 relative to the horizontal in [rad]. x[1...
31a6e81b3eeb87de53965d709d457ba70592e00b
610,966
def pairwise(iterable): """This function returns all contiguous pairs of elements in an iterator """ return list(zip(iterable, iterable[1:]))
b43b97c1ef591cad5f468ca76c62b5154530981d
610,980
def bool_to_str(boolean: bool) -> str: """Bool to str.""" return str(boolean)
d67aaf110f850108b0503e8731aabb28a4fbc89c
610,983
def _get_src_file(build_args): """ Get source file from the build command line. :param build_args: list of build args :return: file being compiled. """ return build_args[-1]
4abe4bc00ea1fc1076c4edc248a8042bd05e7214
610,987
import re def inline_arg_compile(args): """ Using regex to load inline arguments. Arguments: ------ `args` (string): '--func(condition, input)' or '--func' or combined Output: ------ dictionary: `{'func_name': {'condition': function_condition, 'input': input}}` """ # initiate ...
37d8519cfb34cad5db561ce93d647849a594c134
610,989
def binary_step(n: float) -> int: """ Binary Step (Unipolar Binary) Activation Function """ if n >= 0: return 1 return 0
edc86bd63182bf4f152a7746bae8860addc569cf
610,991
def cut_tree(G, depth): """ Gets the internal nodes at the depth specified in the tree. :param G: input tree :param depth: Depth at which to cut the tree. :return: List of internal nodes at the depth specified. """ nodes = [] for n in G.nodes: if G...
5d12e9929301a2a6fd2e67f0ff0518da83efeadf
610,994
def is_subset_of_dicts(src_dict, dest_dict): """Check is all items of one dictionary 'src_dict' is subset of items of another dictionary 'dest_dict', where 'src_dict' should has same or less length then 'dest_dict'. Examples: ({"b": 2, "a": 1}, {"a": 1, "b": 2, "c": 4}) = True ({"a": 1, "b": 2, "c": 4}, {"b...
993991d1322bf7da0ae0972aa454992f6f9e7ce6
610,996
import re import string def clean_string(text): """ Performs basic string cleaning: - Clear pdf conversion md strings - Remove weird symbols - Reduce redundant white spaces Parameters ---------- text : list list of strings to clean Returns ------- text : list ...
afa2fea6dbed2a2fc11b8c71203dbdd6188f4c81
610,999
import torch def to_cuda(x): """Load tensor into GPU """ if torch.cuda.is_available(): x = x.cuda() return x
e212b52fb54101a22c431b7d88a8a90b87ce1798
611,000
def indexAvg(ser): """ This function is used to calculate average point. It used to the agree/disagree multiple choice. Args: ser (pandas.Series): Source data Returns: double: average point precision is 2. """ length = ser.size indexSum = 0 for i in ...
b0bd293ea8be6015f567ed1299f7489ceb93760a
611,001
def get_k_bit_prefixes(k): """Return list of prefix lengths using k-bit precision.""" return list(range(k, -1, -1))
11b8f4bde68521dfcc5d8903d0d066232cf864fa
611,004
def merge_bbox(bbox1, bbox2): """ Merge two bboxes. >>> merge_bbox((-10, 20, 0, 30), (30, -20, 90, 10)) (-10, -20, 90, 30) """ minx = min(bbox1[0], bbox2[0]) miny = min(bbox1[1], bbox2[1]) maxx = max(bbox1[2], bbox2[2]) maxy = max(bbox1[3], bbox2[3]) return (minx, miny, maxx, m...
02cd53b0a62f666ff977a21072ea66f7643e448d
611,005
def is_frequency(label: str) -> bool: """Detect if label is a frequency label""" return '_' in label and label.index('_') == 2 and len(label) == 10
9130c4b565f86cd581e1c06c166dd64837ff1faf
611,006
def are_batches_broadcastable(tt_a, tt_b): """Returns the result of compatibility check of 2 tensors' batches: `True` if batches are compatible and `False` otherwise. The batch sizes should be equal otherwise at least one of them should equal to 1 for broadcasting to be available. :type tt_a: `TT-Tensor`...
46d44712e74dd53625533e62cd7243cca292607f
611,007
def repr_stripe_error(e): """Given a `StripeError` exception, return an error message suitable for display. """ msg = e.user_message or e.code return '%s (request ID: %s)' % (msg, e.request_id)
253dcf29d6caa85478958f0f11fe6b4cb5660c7c
611,010
import torch def _apply_similarity_transform( X: torch.Tensor, R: torch.Tensor, T: torch.Tensor, s: torch.Tensor ) -> torch.Tensor: """ Applies a similarity transformation parametrized with a batch of orthonormal matrices `R` of shape `(minibatch, d, d)`, a batch of translations `T` of shape `(min...
4fdc941d6de9df9434d018e0b2e34cfa8f94565d
611,011
from pathlib import Path def dotpath_to_path(dotpath): """Return a dot-separated pathstring as a path.""" return Path("/".join(dotpath.split(".")))
8ca88ad2083ee40fc9c0aea17801d211fc6a01e5
611,014
def step(x: float, objective: str, upper: float, lower: float, **kwargs): """ Transform values using a step transformer (threshold) :param x: Input value :param objective: 'maximize', 'minimize' or 'range' :param upper: Upper bound for transforming values ('range' and 'maximize' only) :param low...
394687c66f364852810ecd62c4ce2d46194c50b6
611,017
def convertTags(tags_str, table): """Convert a string of tags into a string of integer trough table.""" # Split str tags_l = tags_str.split() # Loop of convertion tags_int_l = [str(table[tag]) for tag in tags_l] # Convert as a string result = " ".join(tags_int_l) return result
8188dd0ba6ae938b407ffa008ea7e453242d8a92
611,018
def _get_sids(soup): """ Find all story links in the soup. :param soup: Soup containing a page from FanFiction.Net :type soup: bs4.BeautifulSoup class :returns: A list of story-ids, up to 25. :rtype: list of strings. """ stories = soup.find_all('a', {'class': 'stitle'}, href=True) ...
3326cd820a926ce185709138b8b97a99793b7c69
611,019
import csv def readFile(filename): """ Parameters ---------- [filename]: .csv The csv file that is being read. Returns ------- [rows] : string Array of the rows in the csv file. [fields] : string Array of the headers in the csv file. """ # initializin...
fa5bc2c0b7ac6bafc0b5d7990064a730781ba705
611,022
def make_text(text, i18n_texts=None): """ make text. reference - `Common Message Property <https://developers.worksmobile.com/jp/document/100500801?lang=en>`_ :return: text content. """ if i18n_texts is not None: return {"type": "text", "text": text, "i18nTexts": i18n_texts...
36d53f8190ecce5147c3ae9920e8c84c3ce57b5a
611,028
import json def loadjson(filename): """ Load a python object saved with savejson.""" fh = open(filename, 'rb') obj = json.load(fh) fh.close() return obj
1271f658a9d6ff9e4c50f299a233cb0cb82a927f
611,029
def severity_class(severity): """Return a CSS class for a validation error severity""" if severity == 'error': return 'severity_error' elif severity == 'warning': return 'severity_warning' else: return 'severity_info'
bd62a8acacd0ccd1cd34df57bd963a8c7cc1725a
611,033
def generateD3Object(wordCounts, objectLabel, wordLabel, countLabel): """ Generates a properly formatted JSON object for d3 use. Args: objectLabel: The label to identify this object. wordLabel: A label to identify all "words". countLabel: A label to identify all counts. Returns...
46895d25b2e713023f2cbebbd08e8683a32e7f31
611,034
def capitalise(string: str) -> str: """Capitalises the first character of a string""" if not len(string): return '' return string[0].upper() + string[1:]
f8cb687d61dd60ac068cac724b88e0ed04cbe51c
611,040
import json def get_connnection_info_from_args(args, raise_if_none=True): """ Returns a dict with the connection info from the arguments. """ conn_info = None raw_conn_info = None if args.connection: raw_conn_info = args.connection elif args.connection_file: with args.connection_fi...
581252721efe1169b0b1bbd3c5ef16a05efc3acf
611,045