content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _format_results(results: dict): """Return formatted dictionary containing term and relevance. Args: results (dict): JSON dictionary of Google Autocomplete results. Returns: suggestions (dict): Formatted dictionary containing term and relevance. """ if results: suggesti...
8f0a1431bbaeac2f6f5381d032a1a1d6d36a3e15
584,113
import textwrap def unindent(string): """ Unindent a block of text Alias for textwrap.dedent """ return textwrap.dedent(string)
e84da75c70ed7ca7fa0a5bb452191e3f3c0f29a5
584,117
def sql_like_decorate( pattern ): """ wrap the given string with '%' if it is not already there """ if '%' not in pattern: pattern = '%' + pattern + '%' return pattern
ed36ba3d307a20298eb765e78df120af45e5dd43
584,118
def get_longest_shortest_spans(s1, s2): """s1 and s2: spacy.tokens.span.Span Returns s1, s2 if s1 longer or equal length to s2, else, return s2, s1""" l1 = s1.end - s1.start l2 = s2.end - s2.start if l1 >= l2: return s1, s2 return s2, s1
0c876843a02e346675ede38dfbcb8cdeb57830f8
584,119
def get_range_upstream(pam_pos, guide_len): """ Get positions N bp upstream, i.e. for forward 3' PAMs or reverse 5' PAMs :param pam_pos: position of PAM, int. :return: sgRNA seed region positions, set of ints. """ sgrna = set(range(pam_pos - (guide_len + 1), pam_pos)) return sgrna
82e5e5f6a5e9cda703c7afa2e85e55536ceb5709
584,122
def guessGender(guesser, fullname, country=None): """Guess gender from name using the gender_guesser package Parameters ---------- guesser : detector.Detector Gender guesser object fullname : str Full name Returns ------- gname : str Guessed gender of name ...
18793f641c0c2cc95c4ae22da09a7f6b9d89cd07
584,123
import ast def read_primes(FnamePRIMES): """ Reads the prime implicants of a Boolean network that were previously stored as a *json* file. **arguments**: * *FnamePRIMES* (str): name of *json* file **returns**: * *Primes*: prime implicants **example**:: >>> primes = read...
bb6c8049f668f63f772b78ec91a9f378a2a1df7b
584,124
def comboValue(widget): """ Retrieve the value of a combo box as a python object """ index = widget.currentIndex() if index == -1: return None return widget.itemData(index)
d2299a7606763f23957bf742ca884ab70a80a25e
584,126
def fix_backspace(word): """ Replace ``\\`` with ``\\\\`` so that it will printed properly in the documentation. """ return word.replace('\\', '\\\\')
b3a98db39b8f85a43e8224288313a10a6eeaab94
584,129
def path_sort_key(ex): """Sort using the number of tokens in the sequence.""" if hasattr(ex, "tgt-pos"): return len(ex.src_pos[0]), len(ex.tgt_pos[0]) return len(ex.src_pos[0])
c86f023dfca8fdf3f5df7f24dc200135d490bd9b
584,130
def get_datatypes_from_ncell(ncell): """ Return the possible datatypes (cl_00, cl_0e, cl_0b, etc.) given a number of cells for a pair of tracers Parameters: ----------- ncell (int): Number of Cell for a pair of tracers Returns: -------- datatypes (list): List of data types...
0ec873ab7aac0731ecdfa3549b05ccf1d668c7ba
584,132
def is_non_ptr_variable_type(type): """ Determines whether or not the specified type is a non-pointer variable type. """ return type.isVar() and not type.isPtr()
1d95de0bbd996bec46332f24cc449d7b9f31e491
584,133
def reverse_words2(s): """ Reverse words in a string using split but no built-in reversing method. """ words = s.strip().split() n = len(words) - 1 out = words[n] n -= 1 while n >= 0: out = "{} {}".format(out, words[n]) n -= 1 return out
85fdceb62599107ae55e55e943294d1736204b96
584,134
def _calc_mse(data1, data2): """utility to calculate mean square error""" return ((data1 - data2) ** 2).mean()
eeaa0d505bc96aaecaae8f665f886c82c1633cf9
584,135
import math def generate_s_curve_profile(max_v, max_a, time_to_max_a, dt, goal): """Returns an s-curve profile with the given constraints. Returns: t_rec -- list of timestamps x_rec -- list of positions at each timestep v_rec -- list of velocities at each timestep a_rec -- list of acceleratio...
612c6b89937f360524aab89a7699a8a6901d4789
584,137
import re def get_file_original_name(name): """ Use this function to get the user's original filename. Filename is concatenated with <UUID>_sep_<FILE NAME>, to avoid collisions. Use this function on your models on an aditional function :: class ProjectFiles(Base): ...
d2d2e6607d217ca36040cf9458bec07ff4d266c0
584,138
def recursive_array_addition(l:list): """Sum an array of integers using recursion.""" if len(l) == 0: return 0 else: i = l.pop() return i + recursive_array_addition(l)
05b88afc8a2deadb9fafb4170aecc31128743cc3
584,139
def get_transitions(state_list, xml_transition_list): """Get transitions if state(s) from state_list are source/destination""" new_transition_list = set() for new_state in state_list: for transition in xml_transition_list: if new_state.id == transition.source: new_transit...
e6741759d77fade600edff63442f6e4aecdb5d14
584,145
from pathlib import Path def scrape_pyramid(path: Path) -> list[list[int]]: """Scrape pyramid from text file into nested list of integers.""" with path.open() as h: pyramid = [] for line in h: pyramid.append([int(node) for node in line.strip().split()]) return pyramid
891c07c505e09653db2dc404108c2ecc48cb8f83
584,150
import re def _name_for_copy(old_name,next_integer): """ Create a name to use for a copy of an object. - old_name is the name of the old object. - next_integer is the number to use at the end of the new name. """ # if old_name ends in '_copy#' where # is an integer, then # just replace # w...
43a77937450b79f28058887ffdba86e029306a8a
584,151
def get_db_engine(snapshot_response): """Function to parse snapshot response from AWS for DB engine. Args: snapshot_response (str): The snapshot identifier to parse. Returns: :obj:`str`: The DB engine of the snapshot. """ db_source_snapshot = snapshot_response['DBSnapshots'][0]['DBSn...
87370eb9dfc71f5b1a0776e8da691f72701af42e
584,152
def bytes_per_pixel(pixel_type): """ Return the number of bytes per pixel for the given pixel type @param pixel_type: The OMERO pixel type @type pixel_type: String """ if (pixel_type == "int8" or pixel_type == "uint8"): return 1 elif (pixel_type == "int16" or pixel_type == "uint1...
654b542d0a7cafa50c2f41e4456b19c62bb0efc3
584,153
def dir_exists(ssh, path): """Check whether a remote directory exists or not. Arguments: ssh: Established SSH connection instance. path (str): Path of the directory to check. Returns: Boolean indicating if the directory exists or not. """ stdin, stdout, stderr = ssh.exec_co...
160c3d9dfaf734a727bbdb4f02e2e437b82a22ad
584,157
def create_link(href, label, disabled=False): """ Creates a simple button to redirect the user to a given link Parameters: href (string): The link to redirect the user to label (string): The label to use as the button label disabled (boolean): ...
28607546ab38a9629e4d699c1cb8e8a29aa218eb
584,160
import torch def conv1x1(input: torch.Tensor, weight: torch.Tensor): """Do a convolution with a 1x1 kernel weights. Implemented with matmul, which can be faster than using conv.""" if weight is None: return input return torch.matmul(weight.view(weight.shape[0], weight.shape[1]), ...
1c61224e9f4f0ae031d4bec0a8a16d47f0d4c98e
584,162
def mkdata(title, description, icon='', variants=None, **kwargs): """Return a dictionary initialised for a Search.""" variants = variants or [] d = dict(title=title, description=description, variants=variants) if icon: d['icon'] = icon if 'jsonpath' in kwargs: d['jsonpa...
bea23a5337fd179db4ab59c7f891ac31fa9442af
584,166
def compute_saliency_per_grad(grad_type, grad, data, target_layer, target_class=None): """ Given the grad_type, computes saliency maps for a batch of images: data. :param grad_type: :param grad: :param data: :param target_layer: vgg: features, resnet: layer4 :param target_class: To visualize...
cddf4279d31dafb4eb88a193c8469ca80f975092
584,170
def count_common_peaks(peaks): """Returns the number of common peaks.""" n_common = 0 for chrom in peaks.chroms: for peak in peaks.fetch(chrom): if peak.iscommon: n_common += 1 return n_common
c7c9ffbc260072e152efefc9bccc2adf58ce90b9
584,174
def line(x, offset, slope ): """ calculation of a line """ y = slope * x + offset return(y)
61c0c27b60ac745aafcd307fbdbccfdfb8fb85ea
584,176
def normalize_prob(lst): """ Normalize a list of numbers so that the sum will be 1. """ total_sum = sum(lst) assert total_sum > 0,"sum should be positive" return [x/total_sum for x in lst]
df2f6c922bb5fef54f974f13f297d4fd2840f3cb
584,177
import ast def arg_list_to_map(arg_list, label): """ Convert an argument of the form -A foo=bar from the parsed result to a map. """ argument_map = {} for pair in arg_list: if '=' not in pair: raise ValueError( "error: {} arguments must be in the form key=value...
1c1054c11b1974c3616eea57a43f906492459801
584,179
def is_url(path): """ Check if given path is an url path. Arguments: path (string): Ressource path. Returns: bool: True if url path, else False. """ if path.startswith("http://") or path.startswith("https://"): return True return False
f6f7eda3b761029bdc6939f8ff2e43320dc78a21
584,185
def _merge_sorted_list(left_list, right_list): """合并两个已排序好的子列表。 """ result = [] i = j = 0 left_list_len = len(left_list) right_list_len = len(right_list) # 逐项比较左右两个列表,将较小的元素添加到 `result` while i < left_list_len and j < right_list_len: if left_list[i] < right_list[j]: r...
61a81ff936dbe5e181b0a67dae273ef1f35ae207
584,189
def bubble_sort(a): """ In this algo, the i-th pass starts at the first element and compare sequencially each element to the next, swapping them if necessary, up to n-i. The biggest element 'bubbles up' to the n-i position. This runs in O(n^2): n-1 passes of O(n) comparisons. Note the use of th...
8a23369398827c30250afadfc4348a327c29f531
584,192
def readline3(fid): """ Read a line from a binary file in Python3 and decode """ return fid.readline().decode('utf-8')
2a1de56c4f775c01882f58ede9556557ce3f2787
584,194
def format_day(value): """Format date object to a day string. Parameters ---------- value : date object The date to format. Returns ------- date The weekday as full name, e.g. Sunday. """ date = value.strftime('%A') return date
7dc292062895dc9ef4c4b089cfd155bb5eaedbfe
584,196
def _get_norm_batch(x, p): """ Returns the Lp norm of batch x. """ batch_size = x.size(0) return x.abs().pow(p).view(batch_size, -1).sum(dim=1).pow(1. / p)
764f122c8a266748fcb1834016a5b6176abda32d
584,197
def convert_times(times): """ Converts from Google Calendar events to busy times that include only start and end date times. :param times: is a list of Google Calendar events. :return: a list of busy time dicts with start and end date times. """ new_times = [] for time in times: ...
bebbeacb1a9bb40f872872b65e39aec9771e0fcb
584,201
import torch def tensor(data, **kwargs): """Returns a torch.DoubleTensor, unlike torch.tensor which returns FloatTensor by default""" return torch.DoubleTensor(data, **kwargs)
ba3995212e981062926096b61198495a24333610
584,203
def miller_rabin_test(n): """ Miller-Rabin Primality Test Returns 0 for composite, 1 for prime, and 2 for probably prime Deterministic for n less than 3,317,044,064,679,887,385,961,981 ≈ 2^81 For greater numbers about 99.9999985% accurate """ W = [2,3,5,7,11,13,17,19,23,29,31,37,41] ...
d3e6d025fbe03bf6dc9ad4d165c15a25df0c81dd
584,206
def get_column_formatters(df): """ Get the formatters for a dataframe. Parameters ---------- df : pandas dataframe table Returns ------- dict dictionary of formatters for columns. """ formatters = {} for p in df.columns: (a, b) = p if b.endsw...
b89e9bb19de78a37ec5f2f1151341b5561f73e56
584,208
def filter_short_segments(segments, threshold): """ Remove segments which duration is smaller than a threshold. """ res = set() for seg in segments: if seg[1] - seg[0] >= threshold: res.add(seg) return res
14b8c252d32184571e1f7145d7fe4b1352b3d90f
584,210
import typing def is_io_stream(obj: typing.Any) -> bool: """Is given object ``obj`` an IO stream, file or file-like object? """ return callable(getattr(obj, 'read', False))
94ceee21862b0b6fea94971683266b2d7d96a464
584,211
import requests def get_exchange_rate(TOKEN, ASSET_ID): """ Gets the current exchange rate for a cryptocurrency in USD using the CoinAPI. API Key is availble for free but limited to 100 request per day Args: TOKEN ([str]): API Key to authenticate CoinAPI GET request ASSET_ID ([str]): Cryptocu...
ac4e7d2294848a26e10801371e2630fa3e5fab99
584,212
def all_repeated_digits(num: int) -> bool: """ Tell if the number is made of all repeated digits. """ s_num = str(num) if len(s_num) > 1: return all([ch == s_num[0] for ch in s_num[1:]]) else: return False
c3d07b5dce967438482a2e37af244580114564a4
584,213
def wb_clean(wb): """ Clean the world bank data. Rename countries to match energy data set. """ wb['Country Name'] = (wb['Country Name'].str .replace('Korea, Rep.', 'South Korea')) wb['Country Name'] = (wb['Country Name'].str .replace('Iran, Is...
cdf3a0098a40761a7a70d3d02840006d21576de9
584,215
def NaiveSuffixArray(string): """Naive way to return a list of the starting positions of suffixes in a sorted order """ #Generate an Array with suffix pairs (Suffix String & Suffex Number) suffixes = [(string[i:], i) for i in range(len(string))] #Sort the list by the suffix string suffixes.sort(...
525b0cf30550741a208e353dbcef4b6c158a0a05
584,217
from typing import OrderedDict import json def application_summary_list_table_format(result): """Format application summary list as a table.""" table_output = [] for item in result: table_row = OrderedDict() table_row['Application Id'] = item['id'] table_row['Display Name'] = item[...
a4080f0e62b0e5520da36a9a68894babe3375e63
584,218
from typing import Dict from typing import Union def params_to_line(params: Dict[str, Union[str, int]]) -> str: """ Transforms a dictionary of parameters into a command line arguments. :param params: A dictionary of parameter names to values. :return: A executable python command. """ base = '...
d9bb0bc8d46c543b1c4dfe9fea0753812edcaac6
584,223
def merge(x, y, f): """ Merges two dictionaries. If a key appears in both dictionaries, the common values are merged using the function ``f``""" # Start with symmetric difference; keys either in A or B, but not both merged = {k: x.get(k, y.get(k)) for k in x.keys() ^ y.keys()} # Update with `f()` ap...
66e5f014d6b1b06686a3f64ca6e6945da0e664cf
584,225
def compute_energy_density(energy, x_dimension, y_dimension, chemical_potential): """Computes energy density from raw energy.""" return (energy / (x_dimension * y_dimension)) + chemical_potential
a79513912a7afe876454781879081de422f0018a
584,232
def azimuth_direction(azstart, azend): """ Direction for shortest distance between two azimuths Returns the direction and the distance """ delta_az = azend-azstart if delta_az > 180: return 'ccw', 360-delta_az elif delta_az < -180: return 'cw', 360+delta_az elif delta_az < 0: return 'ccw', ...
f0b120fc330a0e56d1a8581ab306ef79007fc08a
584,233
def get_shape(image): """Get the dimensions of an image.""" shape = image.shape height = shape[0] width = shape[1] return height, width
65355dc0c9eca7716e20866598da1b580d482a1e
584,234
def serialize_biomass_v2(analysis, type): """Convert the output of the biomass_loss analysis to json""" return { 'id': None, 'type': type, 'attributes': { 'biomassLoss': analysis.get('biomassLoss', None), 'biomassLossByYear': analysis.get('biomassLossByYear', None...
caf1518d8f318415fb0305c7cbc74d9280e97217
584,236
import binascii def bitarray_to_hex(b): """Convert a bitarray to a hexidecimal string.""" bytes_ = b.tobytes() s = binascii.hexlify(bytes_).decode('ascii') if b.length() % 8 and not (b.length() % 4): return s[:-1] return s
ef0a1ec2daabb78b00de045c627c6973307f9ce4
584,239
import yaml def get_appname(file): """Parse given docker-compose file and returns dict for AppName:CertType from environment :param file: Full path of docker-compose file. :type file: String """ dictApps = {} with open(file) as f: docs = yaml.load_all(f, Loader=yaml.FullLoader)...
a32eb257b0fb6a6392315720c192cd02c8b4fe16
584,241
def rnn_batch(data, batch_size): """Reshape data into (num_example, batch_size)""" nbatch = data.shape[0] // batch_size data = data[:nbatch * batch_size] data = data.reshape((batch_size, nbatch)).T return data
b6b0986cd95f85941d59a7c820adab29652bcf2a
584,242
def rotate_matrix(A, m, n): """ Rotates the given m by n matrix A 90 degrees clockwise. """ B = [[0] * m for i in range(n)] for i in range(m): for j in range(n): B[j][m - i - 1] = A[i][j] return B
3115a659ff3afe0c448e6736c5d3b165dc18d2bd
584,244
def byte_offset(x, byte_boundary): """Compute the byteOffset for glTF bufferView The bufferViews need to be aligned to a 4-byte boundary so the accessors can be aligned to them """ remainder = x % byte_boundary padding = byte_boundary - remainder if remainder > 0 else 0 res = x + padding re...
13cccbf04d4218dfd5c9151577e2d4583d121335
584,246
def uses_only(w, s): """ Check if the word consists only of the characters specified in a string. Return False if it does not """ for l in w: if s.find(l) == -1: return False return True
4b9e2b69296f50360cda4a28b38c18b51df95e3d
584,249
def get(config, name): """Get value from config with fallback to default""" # We assume the default fallback key in the config is `__default__` return config.get(name, config.get("__default__", None))
9cd403d2eaeb337899441bd3dc7b6966081d28d9
584,256
import requests def fetch_json(uri): """Perform an HTTP GET on the given uri, return the results as json. If there is an error fetching the data, raise it. """ data = requests.get(uri) # Raise an exception if the fetch failed. data.raise_for_status() return data.json()
57eddb85a89fbc0b21253b71484212585f575430
584,257
from itertools import chain, combinations def powerset(iterable): """ Computes the powerset (all possible 2^n subsets of given set). Parameters ---------- iterable : an iterable element (like a list, set) Returns: ---------- an itertor over the poweret to avoid memory overhead. ...
db49057fef3e95ede72f51fac0e9f651644206c3
584,262
def _make_extension_entry( name, description, url, enabled, core, latest_version, installed_version, status, pkg_type, installed=None, install=None, ): """Create an extension entry that can be sent to the client""" ret = dict( name=name, description=de...
6fdb7360d04e948c599bc965191c2ce8c02a0939
584,276
import uuid def request_headers(headers=None): """Return dictionary of default HTTP headers for Graph API calls. Optional argument is other headers to merge/override defaults.""" default_headers = {'SdkVersion': 'sample-python-flask', 'x-client-SKU': 'sample-python-flask', ...
7bec5220a98fe476589309cab73cf4b5ea88e166
584,277
def _make_valid_param_dicts(arg_dict): """Unpack dictionary of lists of numbers into dictionary of numbers. Ex: turn {'a': [0, 1], 'b':[2, 3]} into [{'a': 0, 'b': 2}, {'a': 1, 'b': 3}] """ return [dict(zip(arg_dict, val)) for val in zip(*arg_dict.values())]
6db150868ab463ca2cfd52a5c393dacb8f476e5b
584,279
def to_lowercase(words): """Convert all characters to lowercase from list of tokenized words""" new_words = [] for word in words: new_word = word.lower() new_words.append(new_word) return new_words
c15b7431771ca1772dce0b70cf448760f4524fd9
584,281
def norm_nonFara_Q_C(Rs, Q, n, L="none"): """ Normalziation of a non-faradaic interfacial capacitance (Blocking Electrode) Following Brug and Hirschorn's normalization of distribtuion of relaxation times Ref.: - G.J.Brug et al., J.Electroanal. Chem. Interfacial Electrochem., 176, 275 (1984) ...
221ea60b977dc0fd4423072b68e8d24b008c6e9f
584,282
import requests from bs4 import BeautifulSoup def ls(url, ext): """ Returns a list of url's having the given extension :param url: the url of which you want the url's :param ext: the extension of the files you want """ page = requests.get(url).text soup = BeautifulSoup(page, 'html.parser') ...
f6723dee876ce8bc0315e56204d0ad3c9bc5ceb7
584,283
def YamlObjectRepresenter(dumper, data): """The representer for a general object, output its attributes as as dict.""" return dumper.represent_dict(data.__dict__)
13511ad7ad09bd276c645d4ae4f3412a5a739c53
584,285
def make_string_pep440_compatible(raw_str): """ pep440 only allows a subset of characters in the version name: - alphanumeric - dots this will restrict the string to that set. """ final_chars = [] for r in raw_str: if "a" <= r <= "z" or "A" <= r <= "Z" or "0" <= r <= "9" or...
6176ab7b08a354f798c8c5f21a176befa9ec7e17
584,291
def get_names_list(item) -> list: """ Helper function to return the names of an object, searching through "alt_names", "name", and "names" attributes to get a single list of name strings. :param item: The item to assess for names :return: A list containing the found names of the object """ c...
7ca4b77721ae360c517c73633f30a73a8685bdf8
584,301
import random def get_int32(min_size=1): """returns a 32-bit positive integer""" return random.randint(min_size, 2**31-1)
ac5437c9d2bfc19ffe46449c8a1d40f9ceffabe4
584,302
def extract_tag_indexes(tag_seq, b_tag, i_tag): """ Returns index of B-LOC and I-LOC, I-LOC = -1 if no I-LOC exist """ i_tag_index = -1 # default value b_tag_index = tag_seq.index(b_tag) if b_tag_index == len(tag_seq) - 1: i_tag_index = b_tag_index return b_tag_index, i_tag_inde...
6432d66fff72d43da0783f0dfc909cb001f42929
584,304
import re def regex_extractor(text, url): """ Extracts RDF segments from a textblock; returns a list of strings. """ # compile the RegEx for extracting RDF rdf_regex = re.compile("<rdf:rdf.*?>.*?</rdf:rdf>", re.IGNORECASE|re.DOTALL|re.MULTILINE) # extract the RDF bi...
a9b4af2d989b3dc4b6a6903b99274c2cac2b3b09
584,305
import re def get_start_page(url): """Finds the start page. Args: url: Search URL. Returns: Start page number as integer. """ start_page = 1 if '/page/' in url: start_page = int(re.findall('\d+', url)[0]) return start_page
efeeef9fa76e9fd02ca2aa158d8243be513df06e
584,307
def calc_num_parameters(layers): """ Compute the total number of learnable parameters in the model Arguments: layers -- list of (n_uints, activations) pairs that define network structure, including input layer X Returns: ret -- total number of learnable parameters """ ret = 0 ...
7860a3e238c703759ac211bfa460db559efb0d85
584,308
def pmvAtomStrip(atom, mol_name = None): """ transform PDB(QT) atoms to PMV syntax "ATOM 455 N GLY A 48 -2.978 5.488 6.818 1.00 11.64 -0.351 N" (xJ1_xtal) | \./ ' xJ1_xtal:A:GLY48:N """ chain = atom[21].strip() res_name = atom[16:21]....
1b1b5b4bb15dc69eb5e7882cd002e0d3199d0da1
584,309
def strip_indicators(img): """ Removes the indicator bar from the observations to clear up the image. """ return img[:84, :, :]
5b1d2f24295d65f18c89123dbba31a7680cacc1a
584,312
def required_method(function_object): """ Decorator for required methods. The decorator wraps an *empty* method to raise an NotImplementedError with an appropriate error message. """ def proxy_function(self, *args, **kwargs): function_name = function_object.__name__ msg = ("Method ...
ce3d4533ebdfcf053ba8710b5c65a66d20bd2a29
584,317
import binascii def crc_srec(hexstr): """Calculate the CRC for given Motorola S-Record hexstring. """ crc = sum(binascii.unhexlify(hexstr)) crc &= 0xff crc ^= 0xff return crc
367d6079899b4cabc3cd3cb54472182cbe60e58b
584,319
def seconds_to_human(seconds, decimal=3): """ Convert seconds to HH:MM:SS[.SSS] If decimal==0 only full seconds are used. """ secs = int(seconds) fraction = seconds - secs mins = int(secs / 60) secs = secs % 60 hours = int(mins / 60) mins = mins % 60 ret = f"{hours:02d}:{...
8d1c205215f8c850b628d497f3c0fb9dbc01bd8d
584,321
def stats(x): """ Returns mean and std """ return x.mean(), x.std()
9ef5e99d68687d600b5b2978ed84a9e798ca6ed4
584,322
def finalize_timeseries(ts, start): """ Finalize timeseries. Drop all rows that have nan column values. Set timeseries to begin at start. Parameters ---------- ts : pd.DataFrame The timeseries of a symbol. start : datetime.datetime The start date for backtest. Ret...
aeab755e26ffd5b786b763b515c1f5d6c848899e
584,329
def coherenstimestring(s): """ Returns time string s in COHERENS model compatible format: YYYY/MM/DD;hh:mm:ss:fff """ ns = s[0:4] + "/" + s[5:7] +"/" + s[8:10] + ";" \ + s[11:13] + ":" + s[14:16] +":" + s[17:19] + ":" + s[20:23] return ns
5182e085af032bedc4f707ce7186863c9ec7d5f3
584,333
import torch def compute_gail_reward(discriminator_score: torch.Tensor): """Compute gail(imitation) reward of data generated by policy.""" return ( -torch.log(torch.sigmoid(discriminator_score) + 1e-8).detach().cpu().numpy()[0] )
c750dbfdc6d471a17b7d9f8438288222e043a92b
584,334
def onehot_simplify(expr): """Gets rid of extraneous args to OneHot.""" if expr[0] == '#OneHot' and len(expr) > 2: return expr[:2]
f9a10ad2f958a1e52b75b91b7acc444d008bd5eb
584,336
def in_frontier(new_node, frontier): """ this method checks if the new_node.label is already present in the frontier :param new_node: node :param frontier: priority queue :return: boolean """ frontier_list = frontier.queue for item in frontier_list: if item.label == new_node.labe...
a41ef18e4c3daabe9f5fa646ffc9e13ca949513c
584,337
def insert_document(collection, data): """ Function to insert a document into a collection and return the document's id. """ return collection.insert_one(data).inserted_id
d8c7b45f39748bd2e8263214da9ff97b816ea4b2
584,339
def _get_step_from_model_path(_path: str) -> int: """Parse the model path to obtain the Args: _path (str): path to the model. Returns: int: step for tracking the training of the agent. """ return int(_path.rsplit("/", 1)[-1].replace(".pt", "").rsplit("_", 1)[-1])
aa42ea3547a5d6b785403398f5df89d766eb4d4c
584,344
def _paren_groups(source): """Split a string into parenthesized groups.""" count = 0 start = 0 result = [] for pos in range(len(source)): if source[pos] == '(': if count == 0: start = pos count += 1 if source[pos] == ')': count -= 1...
13995c57a0a420be778f436440b535b6d29378a5
584,346
def _count_genes(pg_data: dict) -> dict: """ Calculate gene counts for a pangenome object Args: pg_data: workspace data object for the Pangenome Returns: Dict of counts with the GeneFamilyReport type in PanGenomeAPI.spec """ counts = { "genes_count": 0, "homolog_f...
632072a50c0c251535e9e504733880082ad23fc3
584,347
def update_parameters_with_gd(parameters, grads, learning_rate): """ Update parameters using one step of gradient descent Arguments: parameters -- python dictionary containing your parameters to be updated: parameters['W' + str(l)] = Wl parameters['b' + str(l)] =...
0c5e2a5e26e1f85216e3cd06f047decabba11595
584,349
def ip6_str_from16bytes(s: bytes) -> str: """ Convert bytestring to string representation of IPv6 address Args: s: source bytestring Returns: IPv6 address in traditional notation """ m = [f"{b:02x}" for b in s] r = "" for i in range(16): r = r + ":" + m[i] if (i % 2...
647d0db2bdc2f110bd6db983867207b5fc9246e5
584,352
def maze_insert_path(maze_ascii, path): """ Fills the walkable tiles that composes the given path on the maze. :param maze_ascii: The matrix with the ASCII representation of the maze. :param path: The path that should be inserted. :return: A matrix with the new ASCII representation of the maze. """...
59633cee991d96e1d7ef794574e984ac84d2ae5b
584,353
import re def normalise_text(s): """Normalise text for duplicate detection""" # simplistic pattern for URLs (doesn't have to be perfect) # the goal is to filter out duplicate spam messages that differ only in the URL s = re.sub(r'\bhttps?://[/?&%=@a-z0-9_.~-]+\b', ' URL ', s, flags=re.I) # simpl...
f9990e498c2fb08d7560110a5942f39542c5d7fd
584,356
def gather_parents(tree, elem, key='tokenized_inputs', include_root=True): """ Returns a list of attributes represented by key of all parents, of elem. """ lis=[] if 'parent_id' in elem: parent_id = elem['parent_id'] while parent_id != tree['id']: elem = tree['comment...
98c757714b8e5859df98aa8f65b0465ba1f4cbf0
584,357
from pathlib import Path from typing import Iterable def documentation(root: Path) -> Iterable[Path]: """Returns an iterator over all documentation files of the project""" docs = Path(root).glob("**/*.rst") def _deny_filter(path): return not ("venv" in path.parts) return filter(lambda path: ...
5550a1514b6d4ef3c19c317947ec81e9f8505a47
584,363
def app_info_icon_url(self): """Retrieves the application's icon_url if it exists. Empty string otherwise.""" if not self.icon: return '' return 'https://cdn.discordapp.com/app-icons/{0.id}/{0.icon}.jpg'.format(self)
8acf37d6fafa06a1a28b08f087ac7031bfdde228
584,364
import hashlib def hash_to_integer(binary_data: bytes) -> int: """Python's default hash returns different values depending on the process, so an alternative is needed. :param binary_data: An input (in bytes). For a string, use string.encode() :return: an integer hash """ digest = hashlib.blake2s(...
bf28153b4090b38a6224f58b7949799534644e00
584,366