content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import math def longitude_to_utm_epsg(longitude): """ Return Proj4 EPSG for a given longitude in degrees """ zone = int(math.floor((longitude + 180) / 6) + 1) epsg = '+init=EPSG:326%02d' % (zone) return epsg
f17a03514cc9caf99e1307c0382d7b9fa0289330
3,791
def compute_node_depths(tree): """Returns a dictionary of node depths for each node with a label.""" res = {} for leaf in tree.leaf_node_iter(): cnt = 0 for anc in leaf.ancestor_iter(): if anc.label: cnt += 1 res[leaf.taxon.label] = cnt return res
a633f77d0fff1f29fe95108f96ccc59817179ddd
3,792
import hashlib def calc_sign(string): """str/any->str return MD5. From: Biligrab, https://github.com/cnbeining/Biligrab MIT License""" return str(hashlib.md5(str(string).encode('utf-8')).hexdigest())
3052e18991b084b3a220b0f3096d9c065cf4661c
3,794
def remove_prefix(utt, prefix): """ Check that utt begins with prefix+" ", and then remove. Inputs: utt: string prefix: string Returns: new utt: utt with the prefix+" " removed. """ try: assert utt[: len(prefix) + 1] == prefix + " " except AssertionError as e: ...
fa6717e34c6d72944636f6b319b98574f2b41a69
3,795
def format_ucx(name, idx): """ Formats a name and index as a collider """ # one digit of zero padding idxstr = str(idx).zfill(2) return "UCX_%s_%s" % (name, idxstr)
c3365bf66bca5fe7ab22bd642ae59dfb618be251
3,796
from typing import List def _k_hot_from_label_names(labels: List[str], symbols: List[str]) -> List[int]: """Converts text labels into symbol list index as k-hot.""" k_hot = [0] * len(symbols) for label in labels: try: k_hot[symbols.index(label)] = 1 except IndexError: raise ValueError( ...
e074b55e9dae2f8aec6beb14d863f7356035705d
3,798
def eval_add(lst): """Evaluate an addition expression. For addition rules, the parser will return [number, [[op, number], [op, number], ...]] To evaluate that, we start with the first element of the list as result value, and then we iterate over the pairs that make up the rest of the list, adding or subtracti...
5d6972ccc7a0857da224e30d579b159e89fb8dce
3,799
def validate_target_types(target_type): """ Target types validation rule. Property: SecretTargetAttachment.TargetType """ VALID_TARGET_TYPES = ( "AWS::RDS::DBInstance", "AWS::RDS::DBCluster", "AWS::Redshift::Cluster", "AWS::DocDB::DBInstance", "AWS::DocDB::DB...
db33903e36849fb8f97efecb95f1bbfa8150ed6f
3,800
def cprint(*objects, **kwargs): """Apply Color formatting to output in terminal. Same as builtin print function with added 'color' keyword argument. eg: cprint("data to print", color="red", sep="|") available colors: black red green yellow blue pink cyan white no-colo...
42d0f2357da7f84404a888cf717a737d86609aa4
3,801
def auth_code(): """ Функция для обработки двухфакторной аутентификации :return: Код для двухфакторной аутентификации :rtype: tuple(str, bool) """ tmp = input('Введи код: ') return tmp, True
8b0ae26cfdd1aa9f7b9c7a0433075494fe354185
3,805
def decConvert(dec): """ This is a number-word converter, but for decimals. Parameters ----- dec:str This is the input value numEngA: dict A dictionary of values that are only up to single digits frstDP: int The first decimal place scndDP: int The second decimal place Returns...
dedfb67448e4bd2402acb4c561ebb4669d7bc58d
3,807
import json def json_get(cid, item): """gets item from json file with user settings""" with open('data/%s.json' %cid) as f: user = json.load(f) return user[item]
dedb369aba555ca5359e291bc39504dd4b14a790
3,808
def fov_geometry(release='sva1',size=[530,454]): """ Return positions of each CCD in PNG image for a given data release. Parameters: release : Data release name (currently ['sva1','y1a1'] size : Image dimensions in pixels [width,height] Returns: list : A list of [id, x...
a7e118ed223a91d5e939b24baa8bbfb0858064b9
3,811
def HHMMSS_to_seconds(string): """Converts a colon-separated time string (HH:MM:SS) to seconds since midnight""" (hhs,mms,sss) = string.split(':') return (int(hhs)*60 + int(mms))*60 + int(sss)
f7a49ad5d14eb1e26acba34946830710384780f7
3,812
def _replace_token_range(tokens, start, end, replacement): """For a range indicated from start to end, replace with replacement.""" tokens = tokens[:start] + replacement + tokens[end:] return tokens
2848a3ad2d448e062facf78264fb1d15a1c3985c
3,813
def center_crop(im, size, is_color=True): """ Crop the center of image with size. Example usage: .. code-block:: python im = center_crop(im, 224) :param im: the input image with HWC layout. :type im: ndarray :param size: the cropping size. :type size: int :param is...
ac280efd4773613f08632fe836eecc16be23adf8
3,815
def num(value): """Parse number as float or int.""" value_float = float(value) try: value_int = int(value) except ValueError: return value_float return value_int if value_int == value_float else value_float
a2ea65c2afa0005dbe4450cb383731b029cb68df
3,816
def __format_event_start_date_and_time(t): """Formats datetime into e.g. Tue Jul 30 at 5PM""" strftime_format = "%a %b %-d at %-I:%M %p" return t.strftime(strftime_format)
4db0b37351308dfe1e7771be9a9ad8b98f2defa6
3,817
from typing import List from typing import MutableMapping def parse_template_mapping( template_mapping: List[str] ) -> MutableMapping[str, str]: """Parses a string template map from <key>=<value> strings.""" result = {} for mapping in template_mapping: key, value = mapping.split("=", 1) result[key] ...
49eb029a842be7c31d33444235452ecad4701476
3,818
import os def isGZ(fn): """ Tests whether a file is gz-compressed. :param fn: a filename :type fn: str :returns: True if fn is gz-compressed otherwise False """ assert os.path.exists(fn) with open(fn, 'rb') as fi: b1, b2 = fi.read(1), fi.read(1) return b1 == b'\x1f' a...
d71fe08a10554eae2909287a1c19dadf795a4592
3,819
import os def _file_extension(filename): """Return file extension without the dot""" # openbabel expects the extension without the dot, but os.path.splitext # returns the extension with it dotext = os.path.splitext(filename)[1] return dotext[1:]
10c328d3b4670aef021c90a28f704b154be8ca5e
3,820
import numpy def integrate_sed(wavelength, flambda, wlmin=None, wlmax=None): """ Calculate the flux in an SED by direct integration. A direct trapezoidal rule integration is carried out on the flambda values and the associated wavelength values. Parameters ---------- wavelength: A ...
e2fd2c3905bba104f8d4bc376cd56585b40332bf
3,822
def test_cache_memoize_ttl(cache, timer): """Test that cache.memoize() can set a TTL.""" ttl1 = 5 ttl2 = ttl1 + 1 @cache.memoize(ttl=ttl1) def func1(a): return a @cache.memoize(ttl=ttl2) def func2(a): return a func1(1) func2(1) assert len(cache) == 2 key1,...
87d274517c6166db6d174281e6785809e45609b8
3,823
def shorten_str(string, length=30, end=10): """Shorten a string to the given length.""" if string is None: return "" if len(string) <= length: return string else: return "{}...{}".format(string[:length - end], string[- end:])
d52daec3058ddced26805f259be3fc6139b5ef1f
3,824
def Max(data): """Returns the maximum value of a time series""" return data.max()
0d4781da4384eae65de4e13860995848ae8de678
3,827
def parse_healing_and_target(line): """Helper method that finds the amount of healing and who it was provided to""" split_line = line.split() target = ' '.join(split_line[3:split_line.index('for')]) target = target.replace('the ', '') amount = int(split_line[split_line.index('for')+1]) return...
3f11c0807ab87d689e47a79fc7e12b32c00dbd95
3,828
import torch def as_mask(indexes, length): """ Convert indexes into a binary mask. Parameters: indexes (LongTensor): positive indexes length (int): maximal possible value of indexes """ mask = torch.zeros(length, dtype=torch.bool, device=indexes.device) mask[indexes] = 1 r...
0235d66f9ee5bdc7447819122b285d29efd238c9
3,830
def check_pass(value): """ This test always passes (it is used for 'checking' things like the workshop address, for which no sensible validation is feasible). """ return True
aa3a5f536b5bc729dc37b7f09c3b997c664b7481
3,831
def is_valid_charts_yaml(content): """ Check if 'content' contains mandatory keys :param content: parsed YAML file as list of dictionary of key values :return: True if dict contains mandatory values, else False """ # Iterate on each list cell for chart_details in content: # If one ...
cc68ba6bc9166f8d2f8c37da756accec667f471a
3,832
def get_trader_fcas_availability_agc_status_condition(params) -> bool: """Get FCAS availability AGC status condition. AGC must be enabled for regulation FCAS.""" # Check AGC status if presented with a regulating FCAS offer if params['trade_type'] in ['L5RE', 'R5RE']: # AGC is active='1', AGC is ina...
fa73ae12a0934c76f12c223a05161280a6dc01f1
3,833
def normalize_field_names(fields): """ Map field names to a normalized form to check for collisions like 'coveredText' vs 'covered_text' """ return set(s.replace('_','').lower() for s in fields)
55bdac50fd1fcf23cfec454408fbcbbae96e507e
3,836
def rounder(money_dist: list, pot: int, to_coin: int = 2) -> list: """ Rounds the money distribution while preserving total sum stolen from https://stackoverflow.com/a/44740221 """ def custom_round(x): """ Rounds a number to be divisible by to_coin specified """ return int(to_coin *...
f315027def4646252aa7d4ee7c05ca3085625583
3,837
def remove_comments(s): """ Examples -------- >>> code = ''' ... # comment 1 ... # comment 2 ... echo foo ... ''' >>> remove_comments(code) 'echo foo' """ return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#"))
1d3e1468c06263d01dd204c5ac89235a17f50972
3,840
import pathlib def is_dicom(path: pathlib.Path) -> bool: """Check if the input is a DICOM file. Args: path (pathlib.Path): Path to the file to check. Returns: bool: True if the file is a DICOM file. """ path = pathlib.Path(path) is_dcm = path.suffix.lower() == ".dcm" is_...
1e20ace9c645a41817bf23a667bd4e1ac815f63f
3,842
def axLabel(value, unit): """ Return axis label for given strings. :param value: Value for axis label :type value: int :param unit: Unit for axis label :type unit: str :return: Axis label as \"<value> (<unit>)\" :rtype: str """ return str(value) + " (" + str(unit) + ")"
cc553cf4334222a06ae4a2bcec5ec5acb9668a8f
3,844
def extract_tag(inventory, url): """ extract data from sphinx inventory. The extracted datas come from a C++ project documented using Breathe. The structure of the inventory is a dictionary with the following keys - cpp:class (class names) - cpp:function (functions or class methods)...
dcda1869fb6a44bea3b17f1d427fe279ebdc3a11
3,847
import requests import json def package_search(api_url, org_id=None, params=None, start_index=0, rows=100, logger=None, out=None): """ package_search: run the package_search CKAN API query, filtering by org_id, iterating by 100, starting with 'start_index' perform package_search by owner_org: https://...
642a869931d45fe441a146cb8e931dc530170c37
3,849
def get_atten(log, atten_obj): """Get attenuator current attenuation value. Args: log: log object. atten_obj: attenuator object. Returns: Current attenuation value. """ return atten_obj.get_atten()
22d69d326846105491b1fa90f319eb9e0da69a20
3,853
def is_prime(n): """Given an integer n, return True if n is prime and False if not. """ return True
17d2d7bdf95a9d3e037e911a3271688013413fb7
3,854
import os def path_to_newname(path, name_level=1): """ Takes one path and returns a new name, combining the directory structure with the filename. Parameters ---------- path : String name_level : Integer Form the name using items this far back in the path. E.g. if path = ...
e0d8fc09a8809bf8dfee26e208570b0e3c5a4d02
3,855
from collections import Counter from typing import Iterable def sock_merchant(arr: Iterable[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([6, 5, 2, 3, 5, 2, 2, 1, 1, 5, 1, 3, 3, 3, 5]) 6 """ count = Counter(arr).values() ret = sum(n // 2 ...
1b3b8d37ccb3494ed774e26a41ebba32c87a632c
3,857
def int_from_bin_list(lst): """Convert a list of 0s and 1s into an integer Args: lst (list or numpy.array): list of 0s and 1s Returns: int: resulting integer """ return int("".join(str(x) for x in lst), 2)
a41b2578780019ed1266442d76462fb89ba2a0fb
3,858
import json def read_config(path=None): """ Function for reading in the config.json file """ #create the filepath if path: if "config.json" in path: file_path = path else: file_path = f"{path}/config.json" else: file_path = "config.json" ...
3e3612879645509acb74f184085f7e584afbf822
3,860
def get_number_of_tickets(): """Get number of tickets to enter from user""" num_tickets = 0 while num_tickets == 0: try: num_tickets = int(input('How many tickets do you want to get?\n')) except: print ("Invalid entry for number of tickets.") return num_tickets
3703a4ed64867a9884328c09f0fd32e763265e95
3,862
def sort_ipv4_addresses_with_mask(ip_address_iterable): """ Sort IPv4 addresses in CIDR notation | :param iter ip_address_iterable: An iterable container of IPv4 CIDR notated addresses | :return list : A sorted list of IPv4 CIDR notated addresses """ return sorted( ip_address_iterable, ...
97517b2518b81cb8ce4cfca19c5512dae6bae686
3,864
def script_with_queue_path(tmpdir): """ Pytest fixture to return a path to a script with main() which takes a queue and procedure as arguments and adds procedure process ID to queue. """ path = tmpdir.join("script_with_queue.py") path.write( """ def main(queue, procedure): queue.put...
7c2c2b4c308f91d951496c53c9bdda214f64c776
3,866
def secret_add(secret): """ Return a lambda that adds the argument from the lambda to the argument passed into secret_add. :param secret: secret number to add (integer) :return: lambda that takes a number and adds it to the secret """ return lambda addend: secret + addend
151f1cff9f0e0bbb43650d63592ba0c2cb05611e
3,867
import re def parseCsv(file_content): """ parseCsv ======== parser a string file from Shimadzu analysis, returning a dictonary with current, livetime and sample ID Parameters ---------- file_content : str shimadzu output csv content Returns ------- dic ...
cc20a906c23093994ce53358d92453cd4a9ab459
3,869
import json def write_to_disk(func): """ decorator used to write the data into disk during each checkpoint to help us to resume the operation Args: func: Returns: """ def wrapper(*args, **kwargs): func(*args, **kwargs) with open("checkpoint.json", "r") as f: ...
d3614b7b75adf40021c31263fbbcdfdda025d1a3
3,871
def _get_ref_init_error(dpde, error, **kwargs): """ Function that identifies where the continuous gyro begins, initiates and then carries the static errors during the continuous modes. """ temp = [0.0] for coeff, inc in zip(dpde[1:, 2], error.survey.inc_rad[1:]): if inc > kwargs['header'...
45f4072139f007f65872223c624581b7433ea2aa
3,872
import re def matchatleastone(text, regexes): """Returns a list of strings that match at least one of the regexes.""" finalregex = "|".join(regexes) result = re.findall(finalregex, text) return result
1e0775413189931fc48a3dc82c23f0ffe28b333e
3,874
def get_keys(mapping, *keys): """Return the values corresponding to the given keys, in order.""" return (mapping[k] for k in keys)
e3b8bdbdff47c428e4618bd4ca03c7179b9f4a2b
3,876
def total_examples(X): """Counts the total number of examples of a sharded and sliced data object X.""" count = 0 for i in range(len(X)): for j in range(len(X[i])): count += len(X[i][j]) return count
faf42a940e4413405d97610858e13496eb848eae
3,877
def create_preference_branch(this, args, callee): """Creates a preference branch, which can be used for testing composed preference names.""" if args: if args[0].is_literal: res = this.traverser.wrap().query_interface('nsIPrefBranch') res.hooks['preference_branch'] = args[0]...
6e6cc013b9d6c645a6a94087fe63b3a186582003
3,878
import traceback def no_recurse(f): """Wrapper function that forces a function to return True if it recurse.""" def func(*args, **kwargs): for i in traceback.extract_stack(): if i[2] == f.__name__: return True return f(*args, **kwargs) return func
cce02b5e8fff125040e457c66c7cc9c344e209cb
3,879
def make_linear_colorscale(colors): """ Makes a list of colors into a colorscale-acceptable form For documentation regarding to the form of the output, see https://plot.ly/python/reference/#mesh3d-colorscale """ scale = 1.0 / (len(colors) - 1) return [[i * scale, color] for i, color in enum...
dabd2a2a9d6bbf3acfcabcac52246048332fae73
3,884
def mapTypeCategoriesToSubnetName(nodetypecategory, acceptedtypecategory): """This function returns a name of the subnet that accepts nodetypecategory as child type and can be created in a container whose child type is acceptedtypecategory. Returns None if these two categories are the same (i...
c9a31c571807cd2592340ce685b1f130f99da156
3,885
def odd_occurrence_parity_set(arr): """ A similar implementation to the XOR idea above, but more naive. As we iterate over the passed list, a working set keeps track of the numbers that have occurred an odd number of times. At the end, the set will only contain one number. Though the worst...
57f9362e05786724a1061bef07e49635b1b2b142
3,886
import copy def _merge_meta(base, child): """Merge the base and the child meta attributes. List entries, such as ``indexes`` are concatenated. ``abstract`` value is set to ``True`` only if defined as such in the child class. Args: base (dict): ``meta`` attribute from the base...
ba219b8091244a60658bee826fbef5003d3f7883
3,887
import subprocess def retrieve_email() -> str: """ Uses the Git command to retrieve the current configured user email address. :return: The global configured user email. """ return subprocess.run( ["git", "config", "--get", "user.email"], capture_output=True, text=True, ...
4d2308f3b9376b9b7406f9594c52b8a8ebba04f5
3,888
def trunc(x, y, w, h): """Truncates x and y coordinates to live in the (0, 0) to (w, h) Args: x: the x-coordinate of a point y: the y-coordinate of a point w: the width of the truncation box h: the height of the truncation box. """ return min(max(x, 0), w - 1), min...
3edecdfbd9baf24f8b4f3f71b9e35a222c6be1ea
3,889
import os import sys def testInputLog(log_file): """ Test the user input for issues in the DNS query logs """ # if the path is a file if os.path.isfile(log_file): pass else: print("WARNING: Bad Input - Use a DNS (text) log file which has one domain per row without any other data or punctuation.") print("Ex...
c50900dbef8d978e3f7b8349a7ae072c2bab3415
3,890
import typing def check_datatype(many: bool): """Checks if data/filter to be inserted is a dictionary""" def wrapper(func): def inner_wrapper(self, _filter={}, _data=None, **kwargs): if _data is None: # statements without two args - find, insert etc if many: # statements...
c5300507936db04b2ae5e4190421cc354f6ac2d4
3,892
import subprocess def berks(berks_bin, path, action='update'): """ Execute various berks commands :rtype : tuple :param berks_bin: path to berks bin :param path: path to change directory to before running berks commands (berks is a dir context aware tool) :param action: berks action to run, e....
c0f20cccc3a9be747f45f6253a61b455bef69f2c
3,893
def param_to_secopt(param): """Convert a parameter name to INI section and option. Split on the first dot. If not dot exists, return name as option, and None for section.""" sep = '.' sep_loc = param.find(sep) if sep_loc == -1: # no dot in name, skip it section = None opt...
7d7e2b03cb67ed26d184f85f0328236674fa6497
3,894
def rotate_char(c, n): """Rotate a single character n places in the alphabet n is an integer """ # alpha_number and new_alpha_number will represent the # place in the alphabet (as distinct from the ASCII code) # So alpha_number('a')==0 # alpha_base is the ASCII code for the first letter of ...
b1259722c7fb2a60bd943e86d87163866432539f
3,896
def split_parentheses(info): """ make all strings inside parentheses a list :param s: a list of strings (called info) :return: info list without parentheses """ # if we see the "(" sign, then we start adding stuff to a temp list # in case of ")" sign, we append the temp list to the new_info ...
37006936d52abe31e6d5e5d264440ab4950d874b
3,897
import re def add_target_to_anchors(string_to_fix, target="_blank"): """Given arbitrary string, find <a> tags and add target attributes""" pattern = re.compile("<a(?P<attributes>.*?)>") def repl_func(matchobj): pattern = re.compile("target=['\"].+?['\"]") attributes = matchobj.group("...
4650dcf933e9b6e153646c6b7f3535881e4db1f8
3,898
import itertools def _get_indices(A): """Gets the index for each element in the array.""" dim_ranges = [range(size) for size in A.shape] if len(dim_ranges) == 1: return dim_ranges[0] return itertools.product(*dim_ranges)
dc2e77c010a6cfd7dbc7b7169f4bd0d8da62b891
3,899
def update_visit_counter(visit_counter_matrix, observation, action): """Update the visit counter Counting how many times a state-action pair has been visited. This information can be used during the update. @param visit_counter_matrix a matrix initialised with zeros @param observation the state...
418097d34f194c81e38e3d6b122ae743c7b73452
3,901
def slices(series, length): """ Given a string of digits, output all the contiguous substrings of length n in that string in the order that they appear. :param series string - string of digits. :param length int - the length of the series to find. :return list - List of substrings of specif...
ea2d1caf26a3fc2e2a57858a7364b4ebe67297d6
3,902
def textToTuple(text, defaultTuple): """This will convert the text representation of a tuple into a real tuple. No checking for type or number of elements is done. See textToTypeTuple for that. """ # first make sure that the text starts and ends with brackets text = text.strip() if t...
89fed32bff39ad9e69513d7e743eb05a3bf7141a
3,903
import time def time_func(func): """Times how long a function takes to run. It doesn't do anything clever to avoid the various pitfalls of timing a function's runtime. (Interestingly, the timeit module doesn't supply a straightforward interface to run a particular function.) """ def timed(*a...
3506ad28c424434402f3223a43daff4eb51b7763
3,904
from typing import Tuple def get_subpixel_indices(col_num: int) -> Tuple[int, int, int]: """Return a 3-tuple of 1-indexed column indices representing subpixels of a single pixel.""" offset = (col_num - 1) * 2 red_index = col_num + offset green_index = col_num + offset + 1 blue_index = col_num + of...
cb4a1b9a4d27c3a1dad0760267e6732fe2d0a0da
3,905
def _get_field_names(field: str, aliases: dict): """ Override this method to customize how :param field: :param aliases: :return: """ trimmed = field.lstrip("-") alias = aliases.get(trimmed, trimmed) return alias.split(",")
cb732c07018c33a546bf42ab1bf3516d2bd6c824
3,906
import numpy def undiskify(z): """Maps SL(2)/U(1) poincare disk coord to Lie algebra generator-factor.""" # Conventions match (2.13) in https://arxiv.org/abs/1909.10969 return 2* numpy.arctanh(abs(z)) * numpy.exp(1j * numpy.angle(z))
9ac4cd521ca64decd082a34e35e0d080d3190e13
3,907
def to_null(string): """ Usage:: {{ string|to_null}} """ return 'null' if string is None else string
1868ca2c7474a8134f2dbb0b0e542ca659bf4940
3,908
def get_table_8(): """表 8 主たる居室の照明区画݅に設置された照明設備の調光による補正係数 Args: Returns: list: 表 8 主たる居室の照明区画݅に設置された照明設備の調光による補正係数 """ table_8 = [ (0.9, 1.0), (0.9, 1.0), (1.0, 1.0) ] return table_8
89470f0242982755104dbb2afe0198e2f5afa5f4
3,909
import requests import warnings def query_epmc(query): """ Parameters ---------- query : Returns ------- """ url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=" page_term = "&pageSize=999" ## Usual limit is 25 request_url = url + query + page_term r =...
a8da1ee3253d51738f1d556548f6bccf17b32b53
3,910
import pickle def read_doc_labels(input_dir): """ :param input_dir: :return: doc labels """ with open(input_dir + "doc_labels.pkl", 'rb') as fin: labels = pickle.load(fin) return labels
c0246f8e09441782a7437177877cc1e4d83ecb40
3,912
def compute_t(i, automata_list, target_events): """ Compute alphabet needed for processing L{automata_list}[i-1] in the sequential abstraction procedure. @param i: Number of the automaton in the L{automata_list} @type i: C{int} in range(1, len(automata_list)+1) @param automata_list: List of a...
88fc64aaf917d23a29e9400cf29705e6b20665c3
3,914
def strip_new_line(str_json): """ Strip \n new line :param str_json: string :return: string """ str_json = str_json.replace('\n', '') # kill new line breaks caused by triple quoted raw strings return str_json
f2faaa80dca000586a32a37cdf3dff793c0a2d9b
3,915
import torch def cosine_beta_schedule(timesteps, s = 0.008, thres = 0.999): """ cosine schedule as proposed in https://openreview.net/forum?id=-NEXDKk8gZ """ steps = timesteps + 1 x = torch.linspace(0, timesteps, steps, dtype = torch.float64) alphas_cumprod = torch.cos(((x / timesteps) + s...
a1969deafdb282955a53b15978a055d15f0678a0
3,918
import os def check_directories(directories): """Checks if all given directories are really directories and on the same device. Parameters: directories (list of strings) - The directories to check. Returns: The tuple (ok, ok_dirs) where ok is a boolean and ok_dirs a list o...
779195d7509beb4b13ed237fec654514c6226586
3,920
from datetime import datetime def parseYear(year, patterns): """"This function returns a string representing a year based on the input and a list of possible patterns. >>> parseYear('2021', ['%Y']) '2021' >>> parseYear('2021', ['(%Y)', '%Y']) '2021' >>> parseYear('(2021)', ['%Y', '(%Y)']) '2021' """ ...
743378c868a2439f721e428f676092f9da0a2e7a
3,921
def multiply(t1,t2): """ Multiplies (expands) two binary expressions t1 and t2 based on the distributive rule Args: t1 (str): first binary expression t2 (str): second binary expression Returns: A string representing the expansion of the boolean algebraic...
0078ee94420722600be31edc74a86b1932c4d2f2
3,922
import re def sanitize_value(val): """Remove crap from val string and then convert it into float""" val = re.sub(u"(\xa0|\s)", '', val) val = val.replace(',', '.') # positive or negative multiplier mult = 1 if '-' in val and len(val) > 1: mult = -1 val = val.replace('-', '') ...
0fc67bf519674575451f4fc029bee658ea2bd2da
3,923
def getObjectInfo(fluiddb, about): """ Gets object info for an object with the given about tag. """ return fluiddb.about[about].get()
8614edaf44944fcc11882ac2fcaa31ba31d48d30
3,924
import argparse def cli_to_args(): """ converts the command line interface to a series of args """ cli = argparse.ArgumentParser(description="") cli.add_argument('-input_dir', type=str, required=True, help='The input directory that contains pngs and svgs o...
db9502472d1cab92b7564abde2969daa06dbc4aa
3,925
import os def get_walkthrought_dir(dm_path): """ return 3 parameter: file_index[0]: total path infomation file_index[1]: file path directory file_index[2]: file name """ file_index = [] for dirPath, dirName, fileName in os.walk(dm_path): for ...
74ecef62531001c27e05ab42b731739120656695
3,927
from typing import Dict def flatten_dict(d: Dict): """Recursively flatten dictionaries, ordered by keys in ascending order""" s = "" for k in sorted(d.keys()): if d[k] is not None: if isinstance(d[k], dict): s += f"{k}|{flatten_dict(d[k])}|" else: ...
26663b52ccda2a695aa2367cbaf324698a47d56a
3,928
def is_iterable(obj): """ Return true if object has iterator but is not a string :param object obj: Any object :return: True if object is iterable but not a string. :rtype: bool """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
c7a1353f7f62a567a65d0c4752976fefde6e1904
3,932
def get_operator_module(operator_string): """ Get module name """ # the module, for when the operator is not a local operator operator_path = ".".join(operator_string.split(".")[:-1]) assert len(operator_path) != 0, ( "Please specify a format like 'package.operator' to specify your opera...
82b4ddc419b09b5874debbe64262b4a4f414cb8f
3,934
import os import re def in_incident_root(current_dir_path): """ Helper function to determine if a sub directory is a child of an incident directory. This is useful for setting default params in tools that has an incident directory as an input :param current_dir_path: String of the path being evaluated...
62b8f9d9bddcc8ecfa232a65f205bd8414320928
3,935
def f_all(predicate, iterable): """Return whether predicate(i) is True for all i in iterable >>> is_odd = lambda num: (num % 2 == 1) >>> f_all(is_odd, []) True >>> f_all(is_odd, [1, 3, 5, 7, 9]) True >>> f_all(is_odd, [2, 1, 3, 5, 7, 9]) False """ return all(predicate(i) for i i...
c0a0e52587a7afc9da143ac936aab87ad531b455
3,938
from typing import List from typing import Tuple from typing import Set from typing import Dict def _recursive_replace(data): """Searches data structure and replaces 'nan' and 'inf' with respective float values""" if isinstance(data, str): if data == "nan": return float("nan") if d...
b5c21d806b462070b2d1eec7d91a5dc700f6b0ed
3,939
def audio_sort_key(ex): """Sort using duration time of the sound spectrogram.""" return ex.src.size(1)
ec940df6bf2b74962f221b84717f51beba5c4f5f
3,942
from pathlib import Path def _filename_to_title(filename, split_char="_"): """Convert a file path into a more readable title.""" filename = Path(filename).with_suffix("").name filename_parts = filename.split(split_char) try: # If first part of the filename is a number for ordering, remove it ...
f62ae56901f0a58e53e84e63423bcb9f2ccf4c5a
3,943
def is_versioned(obj): """ Check if a given object is versioned by inspecting some of its attributes. """ # before any heuristic, newer versions of RGW will tell if an obj is # versioned so try that first if hasattr(obj, 'versioned'): return obj.versioned if not hasattr(obj, 'Versio...
7f5ad90ffce6a8efde50dba47cdc63673ec79f60
3,944
def merge_on_empty_fields(base, tomerge): """Utility to quickly fill empty or falsy field of $base with fields of $tomerge """ has_merged_anything = False for key in tomerge: if not base.get(key): base[key] = tomerge.get(key) has_merged_anything = True return has...
f8cb14047d2e17e2155beb1ab86eab7cdf531af0
3,945