content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _lab_transform_inv(t): """ Returns the inverse of the cube root tranformation function from xyz color space to lab color space. """ if t > 6. / 29.: return t * t * t return 108. / 841. * (t - 4. / 29.)
d38a4f77ebbab1cb8c91022ed3c14f96f64cf92a
662,637
def count_string_characters(str1, str2): """ Return a dictionary for each string: keys are the characters; values are the number of repetitions """ letters_and_count_str1 = {} letters_and_count_str2 = {} for char in str1: letters_and_count_str1[char] = letters_and_count_str1.get(cha...
5069ebe706ffb7d2d09fd345a6aa8994acfaeebb
662,638
def _is_max_limit_reached(current: int, maximum: int = -1) -> bool: """Check if the limit has been reached (if enabled). Args: current: the current value maximum: the maximum value (or -1 to disable limit) Returns: bool: whether the limit has been reached """ return maximum...
ddf459277651837f6f0b2787dd23896dd6a38cda
662,640
import os def is_running_in_openpai() -> bool: """ Returns: bool: True if run in OpenPAI platform, False otherwise. """ # refer to 'https://openpai.readthedocs.io/en/latest/manual/cluster-user/how-to-use-advanced-job-settings.html#environmental-variables-and-port-reservation' return "PAI_...
2e37628a848a523941a8509aa9c38e24a5b8d826
662,641
def oo_selector_to_string_list(user_dict): """Convert a dict of selectors to a key=value list of strings Given input of {'region': 'infra', 'zone': 'primary'} returns a list of items as ['region=infra', 'zone=primary'] """ selectors = [] for key in user_dict: selectors.append("{}={}".format(key...
6c46d87d57c63869a2c4caf980fd064b37bd71b0
662,642
from pathlib import Path import os def rename_original_file(file: str, bucket_name: str, order_name: str) -> str: """Renames original file.""" new_name = file.replace(Path(file).stem, f'{bucket_name}{order_name}aaaa') os.rename(file, file.replace(Path(file).stem, f'{bucket_name}{o...
e981b0f8701990ebceeb5d2aa46f0508a1fa1e94
662,643
def cpu_units(value): """Converts CPU string into numeric in BMIPS""" norm = str(value).upper().strip() if norm.endswith('%'): return int(norm[:-1]) else: return int(norm)
d947e3c55ad3c922957459e7f53fe9b00d6b0ca4
662,645
import random def randomseq(length, letters): """ Returns a sequence of a certain length with a composition of letters given as input. Args: length (int): Length of the sequence letters (string): A string containing all the possible letters Returns: Sequence (string): A seque...
c744ca81ae23c53a381cfd157447310118fef6bb
662,646
import pandas def get_benchmark_dataframe(logFile): """ Get pandas dataframe with benchmark results stored in the given log file. :param logFile: path to the log file :returns: pandas.DataFrame instance """ print(f"Parsing input file {logFile}") df = pandas.read_json(open(logFile, "r"), o...
5046f1555e2afc0d17db5558a07027ff926b809b
662,647
import os def update(id): """Function for id detection""" lst = os.listdir("./markers") for i in lst: id.append(int(i.split('_')[1].split('.')[0])) return id
49c9a9a36a8ada5edd80b59cbb5efc079c6a6841
662,648
import hmac import hashlib def derivePwdHash(pwdhash, userSID, digest='sha1'): """Internal use. Computes the encryption key from a user's password hash""" return hmac.new(pwdhash, (userSID + "\0").encode("UTF-16LE"), digestmod=lambda: hashlib.new(digest)).digest()
fd298491ab336c426ae11d6d36fc5526f6b26a32
662,649
from typing import Dict def split_entry(entry: str) -> Dict[str, str]: """ Splits a given entry into a dictionary of parameters :param entry: An entry as a formatted string :return: A dictionary of key value pairs """ entries = entry.split(" ") return {key: value for key, value in [entry....
4dfe41869a5a8b3191a17d9140f0b0da450823d7
662,650
def inverse_linked_list(list_to_inverse, next_node_property_name="next"): """ A linked list inversor. No new nodes are created. @param list_to_inverse: The linked list to inverse. @param next_node_property_name: The name of property pointing to the next node. @return: The head of the inversed l...
4fa6075cb3e61fac6aa2e814262d2f7062587126
662,651
def free_slots(slots): """With planned slots as 18 return available slots""" return 18 - slots
465cf74e6599d9b4beedce15e6042f935f0373b5
662,652
def replot(self, label="", **kwargs): """Automatically reissues the last display command for convenience. APDL Command: /REPLOT Parameters ---------- label Controls the type of replot. RESIZE - Issued internally when a graphics window resize occurs (Default). FAST - Only ...
f07e5632f9a32a17a0bff98ef7937e7db0185d4e
662,653
def linked_types(): """ linked_types Get a list of types and # of instances in the knowledge source, and a link to the API call for the list of equivalent terminology :rtype: List[InlineResponse200] """ return 'do some magic!'
98cca01a91606ad8f3b3ed6c2610c2ec4ca071d3
662,654
def _make_graph_plus(G, U, V, M, e): """ """ Gplus = G.copy() # remove the two endpoints and all adjacent edges Gplus.remove_node(e[0]) Gplus.remove_node(e[1]) Uplus = set(U) Vplus = set(V) if e[0] in U: Uplus.remove(e[0]) Vplus.remove(e[1]) else: Uplus.r...
449c011d464b170cffd8d8596ee8c469ed0eda39
662,656
def mean(interactions, _): """Computes the mean interaction of the user (if user_based == true) or the mean interaction of the item (item user_based == false). It simply sums the interaction values of the neighbours and divides by the total number of neighbours.""" count, interaction_sum = 0, 0 for...
ba402c9c0a10b491855995047daf932a3556925f
662,657
import subprocess def is_bridge_setup(): """ Returns (bool) True if the rascsi_bridge network interface exists """ process = subprocess.run( ["brctl", "show"], capture_output=True, check=True, ) output = process.stdout.decode("utf-8") if "rascsi_...
3fd24377ffef29554b95e5450e2910b18746ba50
662,658
def addToFile(path: str, encoding: str = "utf-8"): """ addToFile(path: str, encoding: str = "utf-8") ---- It is decorator. Return function that add to file (path) returning of decorated callable object. """ def wrapper(function): def arguments(*args, **kwargs): with open(file = path,...
158b2db15db69ca4c5de21a5c0de4d3430d65d36
662,659
import math def lonlat_to_mercator_tile_indices( longitude: float, latitude: float, zoom: int, tile_size: int = 512, flip_y: bool = False ): """ Conversion of lon-lat coordinates to (web)Mercator tile indices :param longitude: :param latitude: :param zoom: zoom level (0, 1, ...) ...
51ecc212ca50cc47aedd1a94a3e4f04454b75e52
662,660
import os def getFileNamesFromString(s=""): """ Return a list from the input string Ex. s = "a+b+c+", return: [a,b,c] """ list = [] if len(s) > 0: # remove any trailing + sign if s[-1] == "+": s = s[:-1] # create the list list = s.split("+") ...
d1154c17207d934777046c595d4901028fef627b
662,661
def within_tolerance(value, expected): """ Verify that all values of the color tuple are within a range of tolerance. """ t = 0.01 return ((expected[0] - t) <= value[0] <= (expected[0] + t) and (expected[1] - t) <= value[1] <= (expected[1] + t) and (expected[2] - t) <= value[...
845960ee673319030ec65f0f13c206f337f687a2
662,664
def res2(a_list, start, end): """ version_2 of res, 反转数组 >>> res2([1,2,3,4,5,6,7,8,9,10], 0, 9) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] >>> res2([1,2], 0, 1) [2, 1] >>> res2([1], 0, 0) [1] """ if len(a_list) < 2 or start >= end: return a_list while end-start > 0: a_li...
21d5d3f111de2c6ca1483533be47afb2dca1ee74
662,665
def node2geoff(node_name, properties, encoder): """converts a NetworkX node into a Geoff string. Parameters ---------- node_name : str or int the ID of a NetworkX node properties : dict a dictionary of node attributes encoder : json.JSONEncoder an instance of a JSON enco...
461b2f8c3df9f6db8ba0161765f72f8cb77d8f38
662,666
def fix_filename(filename): """Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg :param filename: :type filename: str :return: :rtype: str """ parts = filename.split('.') ...
7453ef5e2bc57258ae3056ac78ab9729c4d1bd02
662,667
def children(node, selectable=None): """ Builds a filter criterion to select all direct children of the parent node. """ selectable = node.__class__ return selectable.parent_id == node.id
be9f127d7d3323159fa3b167a5a03c5cbd81b190
662,668
import re def compare_no_whitespace(a, b): """Compare two base strings, disregarding whitespace.""" return re.sub('\s*"*', '', a) == re.sub('\s*"*', '', b)
ce1672ee9244e1cfc37914184cc42e13dbe57652
662,669
import logging def make_log_record_output(category, level, message, format=None, datefmt=None, **kwargs): """ Create the output for a log record, like performed by :mod:`logging` module. :param category: Name of the logger (as string or None). :param level: Log lev...
7bf1ea588c6bb7374218def8edf40c7c5753931a
662,670
import base64 def _decode_endpoints(crypt: str) -> str: """Decode a GE endpoint.""" return base64.b64decode(crypt).decode('ascii')
c98378cb639948207fcaa22e63f7a15d01943b52
662,671
import os def get_abs_path(*args): """ Concatenates path's parts sent through args and returns the absolute path to the file """ return os.path.abspath(os.path.join(os.path.join(os.path.dirname(__file__), os.pardir), *args))
c6aeb56ba41c9aaf64baf19ca056d184d1e7d35e
662,672
import mimetypes def guess_mimetype(filepath): """Try to guess the mimetype of a file given its filename :param filepath: The name of the file we try to guess :type filepath: str :return: a mimetype :rtype: str """ type_, enc_ = mimetypes.guess_type(filepath) if not type_:...
190298b925bb463d488e13038854d2443e61528b
662,673
import torch def get_n_correct(batch, answer): """get number of correct predictions (float)""" return (torch.max(answer, 1)[1].view( batch.label.size()) == batch.label).float().sum().item()
bf8a59afcb0b5de7ccd127729b194ad0fb5ee649
662,674
def per_user_hourly_data(data_per_month_gb, percentage_share): """ Estimate the per user data demand in Mbps. """ per_user_mbps = ( data_per_month_gb * 1000 * 8 * (1/30) * (percentage_share/100) * (1/3600) ) return per_user_mbps
43630d6911a3cd0a72d06d46fa23d7fe82bb9d8d
662,675
def byte_with_unit_readable(value): """ 将byte转为可读的单位 :param value: 数据存储大小,int或float :return: 带单位的可视化大小,str """ list_unit = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'] i = 0 while True: b = 1024 ** i t = float(value) / b if 0 < t < 1000: break i += 1...
070cb28936391c6a99572918aaf0ce2d19a484db
662,676
def raised_to(x): """ Raise the input to the power of itself """ if x == 0: return 0 else: return x**x
56df21fd5eac7ce0db7c7b9731314b3f7002af3e
662,677
from datetime import datetime def m_get_max_month_to_now(seq): """ 计算时间字符串列表中时间距离今天的最长月数 计算逻辑为天数除以30 时间字符串'999999'代表当前 做去除处理 :param seq: 时间列表 :return: 传入列表中距离当前时间最长的月数 """ if '999999' in seq: seq.remove('999999') today = datetime.today() days_list = [] for str_dat...
e691d192cdc3ab06c25a900eb37e1a4c5edf13ac
662,678
def banner_data(): """Fixture with minimal required data to create a banner""" return { "name": "Sample Banner", "text": "This should be the correct text", "link_url": "https://samplebanner.com", "end": "2021-07-30", }
8d3fc5b961d0bee83cf7cd0f9e81533a50cc085d
662,679
def get_center(im): """ Given image, returns the location of center pixel Returns ------- (int, int): center of the image """ center_x = float(im.size[0]) / 2 center_y = float(im.size[1]) / 2 return int(center_x), int(center_y)
ee4f445cc9fab709c9c713e0c71380d26532c800
662,680
def create_shared_vpc(context): """ Configure the project Shared VPC properties. """ resources = [] properties = context.properties service_project = properties.get('sharedVPC') if service_project: resources.append( { 'name': '{}-attach-xpn-service-{}'.format(co...
cd6b1c6c83892e7b3254aa38847788f23628e3ff
662,681
import json def captureCardTransactionPayload(amount, capture_reference): """ Create JSON payload for capture transaction API call :param amount: Integer - Amount of currency's smallest denomination to be moved :param capture_reference: String - A reference specified by the merchant to identify the tr...
690a59f4d18fb1218bbbd34853b6809357d146e2
662,682
def get_team_player_links(league_soup): """NPBのsoupを解いてリンク集を取り出す関数 Args: league_soup(BeautifulSoup): NPB leagueの一覧表 Return: Dict: { 2019:{ chunichi dragons: URL, yokohama ba...
9ae9e614934d3d5fb9550ef38d973d5c3a277b73
662,683
from os.path import splitext def description(name): """Descriptive comment of a counter, motor or EPICS record name: string, name of EPICS process variable or name of Python variable """ desc = "" if desc == "": try: desc = eval(name).name except: pass if desc == "": tr...
5696fd8a43870bb984a40cc9eb904b744973c91a
662,684
def check_horizontale(grille, x, y): """Alignements horizontaux""" symbole = grille.grid[y][x] # Alignement horizontal de trois jetons consécutifs, le noeud (x,y) étant le plus à droite if grille.is_far_from_left(x): if all(symbole == grille.grid[y][x - i - 1] for i in range(2)): my_...
81872cca744cdbf9ad54d6831cf12a838ad0b743
662,685
def get_chunks(t_start, t_stop, n_chunks): """Group frame indices into given number of 'chunks'. Args: t_start (int): Frame index to start at (inclusive) t_stop (int): Frame index to stop at (exclusive) n_chunks (int): Number of chunks Returns: List of 2-tuples containing (...
b7477723cd35753699fce913f966618b882cdf21
662,686
from datetime import datetime def dt(txt, fmt='%Y-%m-%d'): """ Parse a text in YYYY-mm-dd format and returns a datetime.date. """ return datetime.strptime(txt, fmt).date()
3f1e8aa04dd1bbc86e937c11409495f295483725
662,687
def getTempValue(): """ This method read the file containing the value from sensor, and parse a 3-digit float value. :return: float type temperature value in Celsius """ # Where the initial value stored at. # often the file is located under /sys/bus/w1/["a string you need to obtain from the sys...
1d2cb61a3eb33ac78d626f51cf19041789be4546
662,688
def vrtc_center(viewport_size, cursor_size): """Puts the cursor at the center of the viewport""" return int((viewport_size - cursor_size) / -2)
918972d10a07e48c9f6c77f2937ca2053d800fe5
662,690
import re def _at_notification(username, _sub=re.compile(r"[^\w'.-]*").sub): """Produce the @DisplayName notification normazilation form""" return "@" + _sub("", username)
ded3bf46a1b95dc0c7840aad324276b794d0ccd1
662,691
def update_particle(position_update, velocity_update, state, nbest_topology, idx_particle): """ Update function for a particle. Calculates and updates the velocity and position of a particle for a single iteration of the PSO algorithm. Social best particle is determined by the state...
6512c5ef337dbf411b7bd84987b52abba991a075
662,693
import re def parse_graphicspath(fname): """Parse "\grapchicspath" and return the result as a list object.""" with open(fname) as f: s = f.read() l = re.findall('.*graphicspath.*', s) graphicspath = ['./'] if l: for i in re.sub('(^.*?{)|(\s*}$)', '', l[-1]).split(','): ...
6e91d6fbbedd50d1cdc17e3c17b71656044ee12b
662,694
import math def cos_helicity(top, parent_top, ttbar, lepton, sign): """ Function to calculate the helicity angle top = the top qaurk 4 vector parent_top = the parent t or tbar of the lepton 4 vector ttbar = the 4 vector of the ttbar system (i.e. t + tbar) lepton = the 4 vector fo ...
1dffd2b1d164fd5692fa4a99c014bc054a871f24
662,695
import math def hard_negative_mining(loss, labels, neg_pos_ratio): """ It used to suppress the presence of a large number of negative prediction. It works on image level not batch level. For any example/image, it keeps all the positive predictions and cut the number of negative predictions to mak...
a05f5f8614936e4860a11d4a16b7f0d37fe756d3
662,696
def takes_arguments(function): """ A decorator for a decorator that should take arguments. With the purpose to make other decorator that use arguments less complicated. more info: https://stackoverflow.com/questions/5929107/decorators-with-parameters :param function: The decorator that should ...
33823b5a0445d16e329ccb4f9210e0e647fdb937
662,697
import numpy def where_op(condition_array, if_true_array, else_array): """Select from `if true array` if condition true, `else array`.""" result = numpy.copy(else_array) mask = condition_array == 1 result[mask] = if_true_array[mask] return result
9ef8acfa3c5ba855ceec6cb18f628886aa568ef8
662,698
import pathlib def list_dirs(directory): """Returns all directories in a train directory """ return [folder for folder in pathlib.Path(directory).iterdir() if folder.is_dir()]
181861ce01583149e7479109d14963dfff50c871
662,699
def twosum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ reversed_data = {} for i, v in enumerate(nums): if v in reversed_data: return [reversed_data[v], i] else: reversed_data[target - v] = i
9284b40841bfe42d3f7eff18a4bda7e08a1055a0
662,700
import torch def compute_PCA(points: torch.Tensor): """ compute the eigenvalues and eigenvectors points: torch.Tensor of size N x 3 """ assert len(points.shape) == 2 assert points.shape[1] == 3 assert points.shape[0] > 0 mean = points.mean(0) covariance_matrix = ((points - mean)....
28db8c1e5023470e6ef5ead5081629dfa3a3214d
662,701
def consumer_multi(sdc_builder, topic, cluster, confluent): """Multithreaded threaded Kafka consumer configured to read schema from the registry.""" builder = sdc_builder.get_pipeline_builder() builder.add_error_stage('Discard') kafka_consumer = builder.add_stage('Kafka Multitopic Consumer') kafka_...
02de0d03fb145d7fa3b166d29a9425b4b0f1e918
662,702
import torch def gelu_fused_grad(grad_output, x): """Gradients of gelu_fwd w.r.t. input""" tanh = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)) jac = 0.5 * x * ((1 - tanh * tanh) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh) return jac * grad_output
2694ffc88dc4f2c3b2d29c8337b95c6561502e52
662,703
def nofirst(l): """ Returns a collection without its first element. Examples -------- >>> nofirst([0, 1, 2]) [1, 2] >>> nofirst([]) [] """ return l[1:]
adf86fe85f8173be173ee94479dac1ceb7a38813
662,704
def clean_code(code): """Escape newlines.""" return code.replace('\n', '\\n')
2535cb97d9c42391fb43d7b8cca4281742f39526
662,705
import argparse def defineArgParser(): """Creates parser for command line arguments""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument( "-f", "--force", help="Get data even if it is not new", action="sto...
43a994e2bf2133309736b384e415bee7a5a8d25d
662,706
def find_first1(l, pred): """ Find first occurrence in list satisfying predicate. :param l: list. :param pred: predicate on the list elements. :return: index of first occurrence in list satisfying predicate; length of the list if not found. """ length = len(l) index = length for i in...
c02823d9f27f79e714cfa2f8237363f96927189e
662,707
def pack(x: int, y: int, z: int) -> int: """ Pack x, y, and z into fields of an 8-bit unsigned integer. x: bits 4..7 (4 bits) y: bits 2..3 (2 bits) z: bits 0..1 (2 bits) """ word = (x << 4) | (y << 2) | z return word
88ec4e3940a55bd10f0f1f12c968000ea945a529
662,708
import os def resolve_file_path(bundle_filepath): """ Reversive function to prepare_file_path """ path = bundle_filepath[1:] if os.name != 'posix': path = path.replace('/', '\\') return os.path.abspath(path)
0b219a5a281f4b82be76efb4f622fa9a20ebed90
662,709
def insert_text(original, new, after): """Inserts the new text into the original""" ret = list() for line in original.split('\n'): ret.append(line) if line == after: for new_line in new.split('\n'): ret.append(new_line) return '\n'.join(ret)
6e62fdd493e57e78f3489f9b593cfd0266775feb
662,710
def array_union(x,y): """Union x and y""" return [x or y for x,y in zip(x,y)]
68bd33f051399e0a969c418c36254fbd826647a5
662,711
import sys def return_page_range(page_range): """Parse argument args.range, and returns page ranges to scrape.""" if not '-' in page_range: page_start = 1 page_end = int(page_range) elif '-' in page_range: page = page_range.split('-') page_start = page[0] page_end =...
88cb9e347ea9629fe3da10844411835beea64e92
662,712
def prodtypes_oval(rule_obj): """ For a rule object, check if the prodtypes match between the YAML and the OVALs. """ rule_id = rule_obj['id'] rule_products = set(rule_obj['products']) if not rule_products: return oval_products = set() for oval in rule_obj['ovals']: ...
4eeabad30ec9199b62df59824d66a33108bb2c71
662,713
import traceback def format_tb(tb, name): """Format traceback (if present) into descriptive human format.""" if tb is None: return "" msg = "Traceback from %s (most recent call last):\n" % name for i in range(len(tb)): stack = tb[i] if stack[0].endswith("libpb/event.py") and st...
1c10129c4f55303e380e6ac018e8e5bf688751f5
662,714
def formatList(line): """Format mangled text into a list. Take any line and remove any incorrect characters, convert it to lowercase and transform the string into a list based on the commas. """ # Regex Version # cleaned = re.sub("'|\[|\]|\s|\n", "", line) # cleaned = cleaned.split(',')...
5e40979634880b3fc8d43a36e5ec54daaed86a57
662,715
import os def get_current_dir(current_file): """Get the current path""" current_dir = os.path.dirname(current_file) return current_dir
6db51406afc8bce81c085048915a480acecfd4d7
662,716
def feature_specific_mode(mode,i,flags): """in mode 'counts', only the default Moses features can be recomputed from raw frequencies; all other features are interpolated by default. This fucntion mostly serves optical purposes (i.e. normalizing a single weight vector for logging), since normal...
23f1f423d6c577e8cf69c8907dc3c5371edbdb28
662,717
def no_replace(f): """ Method decorator to indicate that a method definition shall silently be ignored if it already exists in the target class. """ f.__no_replace = True return f
d9a0f8caaf6b05542c98f66a9e863f5470441b2a
662,718
import re import os def FindModules(path): """Build a dict that maps paths to modules""" pathToModule = dict() fileProg = re.compile(r"itk-module.cmake") moduleProg = re.compile('.*itk_module[^(]*\(([^ \n]*)',re.S) for root, dirs, files in os.walk(path): for f in files: if fil...
cbd888c6eb5c8b60ced1191168177bfae215c5f6
662,719
def _testOverlaps(tableDirectory): """ >>> test = [ ... dict(tag="aaaa", offset=0, length=100), ... dict(tag="bbbb", offset=1000, length=100), ... ] >>> bool(_testOverlaps(test)) False >>> test = [ ... dict(tag="aaaa", offset=0, length=100), ... dict(tag="bbbb", o...
00b5fe8a08d647a0ab844a1de8489ed52132aea9
662,720
def read_centers(file='year_centers.txt'): """ Read text file of array centers. three numbers per line: year of coverage, longitude, latitude. Returns dict of lon,lat pairs (list) indexed by integer year. """ centers={} # More elegant method is to use with, but not necessary # for ...
b1b5a87953a869fd46ae55dfb8bdd3e68ff51335
662,721
import re def remove_duplicates(db): """Remove duplicates by various categories""" # Delete rows with same title and platform db = db.drop_duplicates(subset=['title', 'platform'], keep='last').reset_index(drop=True) # Delete rows with same title in 'Other' Platform dup = db[db.duplicated(subset=[...
ff2f4e752afeee1973cfbf40042308fb8c398455
662,722
from typing import Tuple def interval_overlap(a: Tuple[int, int], b: Tuple[int, int]) -> int: """ Calculate the overlap between two intervals Example: a=(10, 30) and b=(20, 40) gives an overlap of 10 """ return max(0, min(a[1], b[1]) - max(a[0], b[0]))
ba27c08344ac8990bae208bed63d74bb7051019b
662,723
def update_config(original, update, override=True): """ Recursively update a dict. Subdict's won't be overwritten but also updated. """ for key, value in update.items(): if key not in original or (not isinstance(value, dict) and override): original[key] = value else: ...
40229801ee6fd974a874b9e83d66dc201b50c812
662,724
from datetime import datetime def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'): """Converts a unix timestamp into a formatted string.""" return datetime.fromtimestamp(t).strftime(fmt)
8d299125fb9ed6611f047c5c65b97685ea7d994f
662,725
from typing import Iterable import math from functools import reduce def least_common_multiple(seq: Iterable[int]) -> int: """ Least common multiple of positive integers. :param seq: sequence of numbers :return: LCM """ def lcm(num1: int, num2: int) -> int: return num1 * num2 // math....
89db10dc1f0ed8ea618a8a61e09056622c86c157
662,726
import os def fullfile(*args): """Join one or more file path components, assuming the last is the extension. Parameters ---------- ``*args`` : list, optional Components to concatenate. Returns ------- fpath : str The concatenated file path. """ nb = len(args...
bf3036270e59fd133194363a1a1f7dbeb65de0d6
662,728
def generate_flake8_command(file: str) -> str: """ Generate the flake8 command for a file. Parameters ---------- file : str The file to fix. Returns ------- str The flake8 command. """ cmd = f"flake8 {file}" return cmd
d5358d30e27c54ae9e38110c63497755e223826a
662,729
import os def branch_name(): """Return the name of the branch under test.""" # See https://graysonkoonce.com/getting-the-current-branch-name-during-a-pull-request-in-travis-ci/ if os.environ["TRAVIS_PULL_REQUEST"] == "false": return os.environ["TRAVIS_BRANCH"] else: return os.environ["...
3599e2d308cfe545cebcbfaa56872c9c465f4fbb
662,730
def cal_l2_loss(model, weight_decay, method): """Calculate l2 penalty.""" loss = 0.0 if method == 'slimmable': for params in model.parameters(): # all depthwise convolution (N, 1, x, x) has no weight decay # weight decay only on normal conv and fc ps = list(params...
b5f59e92ba1c194e1e50504f6a68a1e580e53676
662,733
def decomp(val): """ Returns the absolute value of a one's complement negative number """ c = 1 while val * 2 > c: val = val ^ c c = c << 1 return val
117b84a83671e9a19af59617bfb0cfba78773c57
662,734
def extract_id(object_or_id): """Return an id given either an object with an id or an id.""" try: id = object_or_id.id except AttributeError: id = object_or_id return id
db25673515fda0f98bf42f14f4da676c5ff2fec7
662,735
import argparse def parse_args(): """ 处理脚本参数 """ parser = argparse.ArgumentParser(description='检查TRT模型') parser.add_argument('-m', dest='model_path', required=True, help='TRT模型路径', type=str) parser.add_argument('-s', dest='image_size', required=False, help='图像尺寸,如336', type=int, default=336) ...
a008e1b0410a2a9521035fb2f5cb0075d02e07a6
662,736
import binascii def name_to_id(name): """convert player name to ID""" # This is fairly unsophisticated, just does a CRC32 on the name. Can be # optimized both for compute requirements and collision frequency using # another hashing algorithm. return binascii.crc32(name) & 0xFFFFFFFF
c2285bd2816370c0706aba839dce9657074be464
662,737
def validate_header(fields, required): """ Validate the header line in a source file. Parameters ---------- fields : list of str Each element is the name of a field from a header line required : set of str Each element is the name of a required field Returns --...
c8c1bf28aeb691f5fd414d32120561a4914d4d53
662,738
def cli(ctx, library_id, folder_id="", name=""): """Get all the folders in a library, or select a subset by specifying a folder name for filtering. Output: list of dicts each containing basic information about a folder """ return ctx.gi.libraries.get_folders(library_id, folder_id=folder_id, name=name)
5f26edec545913c3961bf8cffd2c33e7f58a21e4
662,739
def lexists(path): """Return ``True`` if *path* refers to an existing path. Returns ``True`` for broken symbolic links. Equivalent to :func:`exists` on platforms lacking :func:`os.lstat`.""" return False
c4330b031059e041ba0cecd2a7de7b419f3a4a53
662,740
def lap(gr, phi): """ compute the Laplacian of phi """ lapphi = gr.scratchArray() ib = gr.ilo ie = gr.ihi lapphi[ib:ie+1] = (phi[ib-1:ie] - 2.0*phi[ib:ie+1] + phi[ib+1:ie+2])/gr.dx**2 return lapphi
a42f3e616442d199632477c81c643e1de2097822
662,742
def int_if_digit(s: str): """Iterpret as integer if `s` represents a digit string.""" try: if s.isdigit(): return int(s) except AttributeError: pass return s
dbac97a3751415785c228169399fbf848608a55a
662,743
def _levenshtein_compute(source, target, rd_flag): """Computes the Levenshtein (https://en.wikipedia.org/wiki/Levenshtein_distance) and restricted Damerau-Levenshtein (https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) distances between two Unicode strings with given lengths using t...
2ac9b2637498794de7b162b675ef754efd62a550
662,744
import hashlib def check_hash(hashedText, providedText): """Check for the text in the hashed text.""" _hashedText, salt = hashedText.split(':') return _hashedText == hashlib.sha256(salt.encode() + providedText.encode()).hexdigest()
8fe722d2918a371d6b71a3b8c10a0fde37a16bd9
662,745
def input_transpose(sents, pad_token): """ transform the input List[sequence] of size (batch_size, max_sent_len) into a list of size (max_sent_len, batch_size), with proper padding """ max_len = max(len(s) for s in sents) batch_size = len(sents) seqs_t = [] masks = [] for i in range...
7fa330a1413084a07527d2e2db8ad1d0af20037c
662,747
def fill_with_neg_inf(t): """FP16-compatible function that fills a tensor with -inf.""" return t.float().fill_(float('-inf')).type_as(t)
a1f1c6abb6f7e3cc2db6eb4cf3499b64bf5fdbe0
662,748