content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def platform_parameters(parser): """exmaple platform""" parser.add_argument("--example", type=str, default="example", help="The exmaple parser of sub plugin parsers.") parser.add_argument("--enable_rt_lib", type=str, default="RT_AI_USE_Example", help="Enabel R...
37ae72a2605e48b5319d4bb1d7fc80ea7a63ecda
643,440
import torch def sinc3(t): """ sinc3: t -> (t - sin(t)) / (t**3) """ e = 0.01 r = torch.zeros_like(t) a = torch.abs(t) s = a < e c = (s == 0) t2 = t[s] ** 2 r[s] = 1/6*(1-t2/20*(1-t2/42*(1-t2/72))) # Taylor series O(t^8) r[c] = (t[c]-torch.sin(t[c]))/(t[c]**3) return r
211f44157edc90ef6e6974d85a02c6bcf2837777
643,441
import random import socket def find_unbound_port(start=None, increment=False, port_range=(10000, 50000), verbose=False, logger=None): """ Find a unbound port. Parameters ---------- start : int The por...
e1fe772c054887ada0744e9764e166365eb6165b
643,442
def get_class(kls): """ Load class from module path :type kls: string :param kls: module + class path :rtype: class instance :return: Instance of the class """ parts = kls.split('.') module_path = ".".join(parts[:-1]) module = __import__(module_path, fromlist=[]) ...
e8eeff955010a04200db8068e2531db835fe13a6
643,443
def war_winner(p_1, p_2, lpc_1, lpc_2, game_cards): """ Check who wins the current war and make necessary adjustments. """ if lpc_1.value > lpc_2.value: p_1.add_cards(game_cards) return True if lpc_1.value < lpc_2.value: p_2.add_cards(game_cards) return True return False
ce3bb92e3f5d78796f25e17ce08169622eb8079d
643,444
import csv def read_csv_file(file_path, delimiter, remove_header=False): """ Reads a csv file with records separated by delimiter""" rows = [] with open(file_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=delimiter) for row in csv_reader: rows.append(row) if...
3d108d5613c18bd9ae77e8ab7283d7dff0a821af
643,446
def size_in_bytes(size): """Converts the string `size` to an integer (size in bytes). The string `size` can be suffixed with *b* (bytes), *k* (kilobytes), *M* (megabytes) or *G* (gigabytes). """ if not isinstance(size, str) or not size: raise TypeError("size must be a non empty string.") ...
163ab6921bd9797087f34550841a134dce2eb14d
643,447
def make_distribution(function, *pars): """ The distribution factory""" def distribution(): return function(*pars) return distribution
d21026d8cb8c9348d4791b9a269c0f5878fe159b
643,448
def map_reads(read_seq, mate_seq, ref): """ Maps a pair of reads and returns their insert size Returns None if no exact match for the pairs """ aln1 = ref.find(read_seq) if aln1.matches != 1: aln1 = ref.find(read_seq.rev_comp()) if aln1.matches != 1: return None ...
a072387088ffa511e0ef1ca1142931337504ddae
643,449
def _mask_for_bits(i): """Helper function for read_bitpacked to generage a mask to grab i bits.""" return (1 << i) - 1
252381ddfe00663675280db89ef03034a4e32239
643,450
def remove_all_gap_columns( texts ): """ Remove any columns containing only gaps from alignment texts """ seqs = [ list( t ) for t in texts ] i = 0 text_size = len( texts[0] ) while i < text_size: all_gap = True for seq in seqs: if seq[i] not in ( '-', '#', '*', '...
24325cba09cfd0bb97f7f57db58ce42eb85369df
643,451
def to_float(val, sub_val): """Try to convert 'val' to a float. If it fails, return 'sub_val' instead. Remove any commas before trying to convert. """ try: if isinstance(val, str): # remove any commas before converting. val = val.replace(',', '') return float(val...
8082ab3e1838ecfd76d7ea18fd46ec50ae9b9232
643,452
def compose_list(n): """first adding the numbers that are multiples of 3 and 5""" list = [] for i in range(0, n): if (i % 3 == 0) or (i % 5 == 0): list.append(i) return list
2230da3d2cea7ee161f49a28ec247e7ecfbb1ff4
643,453
def get_make_targets(benchmarks, fuzzer): """Return pull and build targets for |fuzzer| and each benchmark in |benchmarks| to pass to make.""" return [('pull-%s-%s' % (fuzzer, benchmark), 'build-%s-%s' % (fuzzer, benchmark)) for benchmark in benchmarks]
e614f4655bffe80f69584f76a6a86b3fe654ccee
643,454
def getIODecl(external_io_name_2_dir_and_width): """ the IO of the wrapper. Special treatment for ap_clk. Add a BUFGCE. """ io_decl = [] for io_name, dir_and_width in external_io_name_2_dir_and_width.items(): io_decl.append(f' {" ".join(dir_and_width)} {io_name},') io_decl[-1] = io_decl[-1].replace(...
003627229908042f3a310b63918685633cf8eda3
643,456
def binary_search_recur(array, low, high, val): """ Worst-case Complexity: O(log(n)) reference: https://en.wikipedia.org/wiki/Binary_search_algorithm """ if low > high: # error case return -1 mid = (low + high) // 2 if val < array[mid]: return binary_search_recur(arra...
c6573d976d7e8e8d6ad8a6179d70ee3f182cdc92
643,458
import os def make_empty_pqrxml(directory, filename="empty.pqrxml"): """ Create an empty pqrxml which is used in the Extraction phase to generate new ligand encounter complex PQRs. Returns ------- empty_pqrxml_path: str Generated path of empty pqrxml file. """ empty_...
747d3d07e98ec8aeb3445b7de4a0d4571fc85dd0
643,459
def _pack(address): """ Adds the memory address to the data entry """ def _pack_entry(entry): return address, entry return _pack_entry
ec3f348a8178d37c502bed6159fba7d36006f627
643,463
import subprocess def capture(args, env=None): """capture(command) - Run the given command (or argv list) in a shell and return the standard output.""" p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out,_ = p.communicate() return out
72298d10e5c458e5998086cb88d0ea6ed933805f
643,464
import subprocess def is_pipenv_present(): """Returns True if a virtual environment can be accessed through Pipenv and False if it can't.""" try: process = subprocess.run( ['pipenv', '--venv'], universal_newlines=True, stdout=subprocess.PIPE, stderr=sub...
296cdfbdc8a202e6de6f687af84da913b5ad5fc5
643,465
def avg_relative_error(ground_truth, predictions): """calculate the relative error between ground truth and predictions Args: ground_truth (dict): the ground truth, with keys and values predictions (dict): the predictions, with keys and values Returns: float: the average relative e...
193e2d933f1f091f8f64e913aa84c7075c63a5c3
643,466
def stripExtension(path): """Return the part of the path before the extension. @param path: The path to split. @type path: string @return: The part of the path before the extension. @rtype: string """ end = path.rfind("\\") end = max(path.rfind("/", end + 1), end) + 1 # We search in the substrin...
20ecab3a036ab5ab9f57926438f5a71f66222447
643,467
def _resolve_next(o): """returns the next element if an iterable or return itself otherwise. list should be passed using cycle(list)""" if hasattr(o, '__next__'): return next(o) return o
728a56f380ddaf81a7d14f0ff259661c8877a79e
643,468
def get_optimal(opt_file, optimisation): """Returns the optimal value given the specified optimisation. Args: opt_file: The file with optimal results. optimisation: The optimisation value to return. Returns: Optimal value. """ f = open(opt_file, "r") profile = '' for lin...
09a8d91fadeed236b5e9fc6eeb53474ed3ebc6ad
643,469
import json def to_json(obj: object, *args, **kwargs): """Serialize a nested object to json. Tries to call `to_json` attribute on object first.""" def serialize(obj: object): return getattr(obj, 'to_json', getattr(obj, '__dict__') if hasattr(obj, '__dict__') else str(obj)) return json.dumps(obj, ...
7798bc28196f9598645751803f81fe711836ada9
643,470
import json def dict_to_json_str(dictionary, jsons_output): """ Converts a dictionary to a json string :param dictionary: :param jsons_output: :return: """ jsons_output = json.dumps(dictionary, sort_keys=True, indent=4) return...
2643bc2fbc16d78aedc22a0c59ff4bd1735ddded
643,472
import socket import time def scan_bridges(version=4, sock=None): """Scan for bridges on the network Returns a list of available bridges. Each bridge is a tuple of host and mac address. >>> scan_bridges() ('192.168.1.100', 'af:12:d4:ee:90:38') Attributes: | version: Which version to ...
277a7c8a71427ec459fddb91618efa97b1c5f8b4
643,473
def get_context(seq, pos, n=1, s=1): """ Gets context from a sequence at a given position. :param seq: the sequence :param pos: target position :param n: context size (each side) :param s: size of the target region, displaces the position of right context :return: a string matching [ACTG]*[....
c7b9b09ddea2037e10539c129851734105ad70b6
643,474
import torch def compute_detection_accuracy(detected_bbox: torch.Tensor, gt_y: torch.Tensor, gt_batch: torch.LongTensor, threshold: float = 0.5) -> float: """Compute the recognition accuracy for a detection task over a batch. The recognition accuracy is determined by iterating ...
1ef828cac7c51e30134818794464159bc02dfac9
643,475
import os import sys import yaml def parse_config_file(configlocation=None): """ Reads config data from the config file the config file must be called config.yml. Parameters ---------- configlocation : str the path on the filesystem to the config file. Optional. If not spec...
2480d35decb30eb54703ec8443e13feff81aee78
643,476
def get_host_batchid_map(workspec_list): """ Get a dictionary of submissionHost: list of batchIDs from workspec_list return {submissionHost_1: {batchID_1_1, ...}, submissionHost_2: {...}, ...} """ host_batchid_map = {} for workspec in workspec_list: host = workspec.submissionHost ...
8a0e1565b439137fce77d49811a828931a07aaa1
643,479
def keygen(params): """ generate a key pair for signature """ (G, o, g1, hs, g2, e) = params (x, y) = o.random(), o.random() sk = (x, y) vk = (g2, x*g2, y*g2) return (sk, vk)
d60569a84e31a8146621560c0963151e27a6f60d
643,480
def libcxx_flag(compiler, libcxx): """ returns flag specific to the target C++ standard library """ if not compiler or not libcxx: return "" if str(compiler) in ['clang', 'apple-clang']: if str(libcxx) in ['libstdc++', 'libstdc++11']: return '-stdlib=libstdc++' el...
b2cef0ce0b6a7166ce31b39e2ba2819e146268fe
643,481
def decExponential(agent,state): """ Implements a decreasing-epsilon method which starts with a high exploration rate and then decreases exponentially with time """ return (0.5 ** (agent.episodesSoFar + state.trial))
ba40c91e4b8410b8e99f7d0f0fb9e25d1c5f32a1
643,482
import re def parse_number(message): """ This function accepts a message (String), which has a phone number inside. If it finds a phone number, it parses it then returns the phone number. """ # Check for at least two numbers countryCode = '+1' if bool(re.search(r'\d{2}', message)): # Replace %2B wit...
47d18acc52dc16f2f8160ea603a936774aa366fb
643,483
def consistent_typical_range_stations(stations): """ returns the stations that have consistent typical range data Inputs ------ stations: list of MonitoringStation objects Returns ------ a list of stations that have consistent typical range data """ consistent_station_list = [...
fd8192088665d7f37943b1376a681104f1f0d6c2
643,484
import math def get_direction(x, y): """Gets a direction from two differences in coordinates""" return math.atan2(y, x)
12face987142c897add55da3c9e7a2dee5b702b7
643,485
def weighted_sum(df, var, wt="s006"): """ Return the weighted sum of specified variable Parameters ---------- df: Pandas DataFrame data overwhich to compute weighted sum var: str variable name from df for which to computer weighted sum wt: str name of weight variable...
c312131f57150dba3dc5d4d401136b3ec2c2420c
643,486
def _axes_all_finite_sized(fig): """Return whether all axes in the figure have a finite width and height.""" for ax in fig.axes: if ax._layoutbox is not None: newpos = ax._poslayoutbox.get_rect() if newpos[2] <= 0 or newpos[3] <= 0: return False return True
37a4501a445df5e4c3c69c1e3a5300fa5d049d49
643,487
def getsum(strlist): """ Sum of strings (as ints) @type strlist: list(str) @param strlist: SAM line @rtype: int @return: MD tag calculation. """ return(sum([int(i) for i in strlist]))
12b9933e831c74f67f51adf22434208ac47293f0
643,489
import re def splitName(string): """ string of full skin name -> name, weapon, star, wear """ string = string.replace(" ","") # remove spacing # star star = "★" in string string = string.replace("★","") # stattrak stattrak = "StatTrak™" in string string = string.repla...
543a7adcfe939181a6789802d60907f5a1853eae
643,490
def validate_rule_association_id(value): """Raise exception if resolver rule association id has invalid length.""" if value and len(value) > 64: return "have length less than or equal to 64" return ""
7e654db71df168096774e15bb8966b036ee25f1d
643,492
from typing import Counter def compute_state_distribution(interactions): """ Returns the count of each state for a set of interactions. Parameters ---------- interactions : list of tuples A list containing the interactions of the match as shown at the top of this file. Return...
71015ba279b291a580e41fcfe3b106dc61fea138
643,493
import hashlib def calculahash(cadena): """Devuelve el hash SHA256 de una cadena dada como entrada :param cadena: texto de entrada para calcular su hash :return: el hash calculado con SHA256 """ return hashlib.sha256(cadena.encode()).hexdigest()
6b2e04c00b13471e470ba52ab6c5e500b84c15c3
643,494
def add_value_in_param(parameters, key, value): """ """ if '.' not in key: parameters[key] = value else: key_split = key.split('.') parameters[key_split[0]] = add_value_in_param(parameters[key_split[0]], '.'.join(key_split[1:]), value) return parameters
97ef21b7ac183b3b2f929ba32bdef95c22b75486
643,495
def f_k(dataSet, Labels, d, q): """ :param dataSet: 某一个样本的特征集 :param Labels: 某一个样本的标签集 :param d: 样本的维度,即一个样本含有的特征数 :param q: 标签的维度,即标签集中标签的个数 :return: 返回的是fk(x,y) """ F_k = [] for l in range(d): for j in range(q): if Labels[j] == 1: F_k.append(dat...
f90851af14cb928f40462a76d73a57dce59d33d5
643,496
def combine_gaussian_bumps(gaussian_bumps, baseline): """ This functions takes a list of gaussian_bumps and returns the appropriate sum subtracting the """ sum_g = gaussian_bumps.pop() for gb in gaussian_bumps: sum_g += gb sum_g -= baseline return sum_g
cd95fb1ad569750121e54bd7c54e7f5ac64becf7
643,497
def modify_df(df, sentence_length): """ Convert the columns STB_Text from a string of list to a list. Gather length of STB_Text/Ref_Text list and filter based on sentence length argument. Explode STB_Text and Ref_Text as separate dataframes. Filter repetitive sentences within a topic. Create a c...
c049566164e21a367bcb5017089083dbee1ed0fb
643,498
def add_custom_options(options): """Wraps a defined function with global parameters""" def _add_options(func): for option in reversed(options): func = option(func) return func return _add_options
4c4ab810329cbbdfa1fe53ac6dc9ba5dc6b8d2c2
643,499
import requests from bs4 import BeautifulSoup def get_definition(search): """ Get the first definition of the word using merriam-webster dictionary online. :param search: Word to find the definition of. :return: Definition of search. """ # Read HTML website req = requests.get("https://merr...
7bc375736f9c0cc8c0a64f06926fbade8681518a
643,500
def absolutelyNonDecreasing(buffer,item,attempts): """ Stops after the buffer has seen an absolute value larger than the one being searched for. The example halting condition given in the documentation. """ if abs(buffer._cache[-1])>abs(item): return True return False
c96f593b47b2d4c695959b7ca494ffd757bada63
643,501
import subprocess def is_github_repo(url): """Check if it is a valid github repo. Returns True, or False. """ cmd = ['git', 'ls-remote', url] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() if err: ...
364e170cfd3444b16fc62c16988a0379f7734feb
643,502
import re def parse_quicklook_key(key): """ Parse quicklook key and return dictionary with relevant fields. Input: key(string): quicklook key Output: dict with the following keys: satellite(string): e.g. CBERS4 camera(string): e.g. MUX path(string): 0 padded path, 3 dig...
6138b5a680e39bc5af3dfeaf8826bec81ab928cb
643,503
def qobj_to_dict_current_version(qobj): """ Return a dictionary representation of the QobjItem, recursively converting its public attributes. Args: qobj (Qobj): input Qobj. Returns: dict: dictionary representing the qobj. """ return qobj.as_dict()
d7f71f853441e1c338872333340e534825f80cd9
643,504
def get_batch_appliance_tunnels_config( self, ne_pk: str, tunnel_id_list: list, ) -> bool: """Get appliance tunnel configuration for specified tunnels .. note:: This API Call is not in current Swagger as of Orch 9.0.3 .. list-table:: :header-rows: 1 * - Swagger Section ...
58886650e1c6c330771f129a0a39e684324f12b0
643,506
import os from urllib.request import urlopen def trump_tokens(path='trumptweets.txt', url='http://pastebin.com/raw/nWvFKcH7'): """Return the words found in tweets of Trump as a list.""" if os.path.exists(path): return open('trumptweets.txt', encoding='ascii').read().split() else: trump = u...
5bc03fb698b28bb95a3cd9a0c1114244d676916f
643,507
def escape_jsonpointer_part(part: str) -> str: """convert path-part according to the json-pointer standard""" return str(part).replace("~", "~0").replace("/", "~1")
f30776c6ae620b892165bc9e6d7b51b889483a70
643,508
def get_nested_expression(adders): """Return a string representing the addition of all the input bitvectors. Args: adders: An integer, the number of nested addition operations. Returns: The full addition string. """ nested_expressions = [] for i in range(adders): rhs = "x_0" if i == 0 else nes...
206bfb2e4f842b35acd4db66d08ad7035e612585
643,509
def sigma_bins(pref): """ Some pre-defined density bin options. Add to here as appropriate Inputs: pref = a reference depth Outputs: bins = a dictionary with some entries """ if int(pref) == 0: bins = {"pref" : int(pref), "nbins" : 52, "sigmin" : 23.0, ...
9ea3d19b4757ab2aabd839ab73959a2f34587e3d
643,510
def soil_heat_conductivity(w, T, ro, soil_type): """ Heat conductivity of a soil, W/(m2*K) :param w: humidity, % :param T: temperature, K :param ro: density of a soil, kg/m3 :param soil_type: (str) type of a soil :return: heat conductivity of a soil, W/(m2*K) """ ro = ro / 1000 r...
da1b20e58bad1825fb23e69c08c2d55d9db53d7c
643,511
def gcdist(x1,y1,x2,y2,Rearth,units='degrees'): """ Compute the great circle distance on the earth between points (x1,y1) and (x2,y2), where: x = longitude, y = latitude Taken from Clawpack 4.x. """ from numpy import pi,sin,cos,arccos,arcsin,sqrt if units=='degrees': # convert ...
1f2cd8b9778fbf0108d6f1283e4a7d685523a81c
643,512
import requests def get_nombre_pages(url) -> int: """ Permet d'avoir le nombre de pages sur le site lessurligneurs dans la partie article surlignage. :param url : url du site les surligneurs. :return : le nombre de pages. """ numero_page = 1 while requests.get(f"{url}page/{numero_page...
7ed1e411f44e35ee25901c349d9438657c42f5ba
643,513
def flat_metric_dict(metric_dict): """Flatten the dict""" dict_flatten = {} dict_flatten['steps'] = list(metric_dict.keys()) for _key, value in metric_dict.items(): for sub_key, sub_value in value.items(): if sub_key not in dict_flatten: dict_flatten[sub_key] = [sub_v...
903e6dcbb6a4fcfa5c22eeb4595a882bf4fd0d8e
643,514
import math def split_equally(lst, nparts): """Splits equally list into nparts. If length of the list cannot be devided without residue the functions splits list in the way when some parts have n items and some n-1, so lengths of them are almost equal. """ data_size = len(lst) ratio...
d93c7de166812727739f2b16f18141e0c1ed9f59
643,515
import re def version_parts(version): """ Split a version string into numeric X.Y.Z part and the rest (milestone). """ m = re.match(r'(\d+(?:\.\d+)*)([.%]|$)(.*)', version) if m: numver = m.group(1) rest = m.group(2) + m.group(3) return numver, rest else: return...
e67d205552cfa09c01cd7209fc591a6214172fef
643,516
def is_cmp(op): """ Tests whether an operation requires comparing two types. """ return op in ['<', '<=', '==', '!=', '>', '>=']
44c80ef8b2da0ea46e8cf21d36706c09d5be0f63
643,517
import requests def consultar_precio_BTC(url): """ Requests BTC price from Binance API """ query = "api/v3/ticker/price?symbol=BTCUSDT" r = requests.get(url + query) r = r.json() return int(float(r["price"]))
326849da4654e1041b03d2917b1f0c3c142be77c
643,518
def datetime_to_text(datetime_object): """ covert python3 datetime object to text string to store in sqlite3 database :param datetime_object: python3 datetime object :return: string containing datetime in format MM-DD-YYYY HH:MM:SS """ return str(datetime_object)
519ac8f01f48e3a69eaa56a7a217c22c2f374011
643,519
import string import random def getRandomString(): """ Generate a random string consisting of characters + digits """ char_set = string.ascii_uppercase + string.digits return ''.join(random.sample(char_set * 6, 6))
c77d2991a1b5bc786514a78232a256089c04f3ff
643,520
def which_one_in(l, f): """ returns which one element of list l is in f, otherwise None """ included = [i for i in l if str(i) in f] if len(included) == 1: return included[0] elif len(included) > 1: return False else: return None
77533eb31781154dc2ca892dde28e27633b5cd4d
643,521
def subst_variables_in_str(line: str, values: dict, start_char: str = "%") -> object: """ Replace variables inside the specified string :param line: String to replace the variables in. :param values: Dictionary, holding variables and their values. :param start_char: Character used to i...
adbf0f2b37488d58fff98732ab46e9efef62577a
643,522
def calc_distance(original, closest): """ Parameters ---------- original : Numpy array The coordinates where you want to know the distance to the closest surface closest : TYPE The closest point to the points of interest Returns ------- distance : Numpy array ...
9c55f3a23bc12aa44e3557cdd3889e5d7d61b833
643,523
import os def get_file_from_dir(directory, hosts_dirs, dir_num, keyword): """ Func which find file by keyword in specific directory. :param directory: specific directory :param hosts_dirs: list of directories in specific directory :param dir_num: required directory number :param keyword: keywo...
d2e0a888916feb1858158fd0fbd82330de23d6b0
643,524
def alt2ambiguousnucleotide(alts): """Translate list of alt nucleotides to single IUPAC abmiguity symbol Uses http://www.dnabaser.com/articles/IUPAC%20ambiguity%20codes.html Args: alts: List of alternate nucleotides of a SNP Raises: KeyError: when multi alt is not in translation map ...
052cc8188d257cf02a6e109d1edd092f9c76bd81
643,526
def input_subject_id() -> str: """Request an identifier for the subject. Returns ------- str Subject identifier. """ return input('Please enter subject ID: ')
acd0cfbc090ee22e7702e8fdfc234b50f1984db0
643,527
def lt_log_determinant(L): """ Log-determinant of a triangular matrix Args: L (Variable): Lower-triangular matrix to take log-determinant of. """ return L.diag().log().sum()
dc7e0a75e71eddb2b284c1cb511d4b9902559371
643,528
import os def filenames(path): """ Returns all filenames in specified directory. Input arguments: path = Name of the folder or directory from which filenames are to be read Usage: names = filenames('drive:/directory') """ return os.listdir(path) # To get name of all the files s...
ab9e0226ca9e7bca0537b36c7eb0cfbf705fd3df
643,529
def copy_data_into_dir(source_path, dest_path, data, cliutils): """ This function will be use to copy file which we dont wanr to process :param source_path: :param dest_path: :param data: dict of file_name: pdb_info object :param cliutils: :return: """ cliutils.verbose("Start copy da...
216c85ccec1b606003f077ada635ba6c547b51fe
643,531
def append_lines(file, lines, encoding=None, errors=None): """Append the lines to a file. :param file: path to file or file descriptor :type file: :term:`path-like object` or int :param list(str) lines: list of strings w/o newline :param str encoding: name of the encoding :param str errors: err...
a63d987414d5cc253aeda8aaeedcb865a6eebd73
643,533
def get_update_author_profile(d_included, base_url): """Parse a dict and returns, if present, the URL corresponding the profile :param d_included: a dict, as returned by res.json().get("included", {}) :type d_raw: dict :param base_url: site URL :type d_raw: str :return: URL with either company...
e50254c60a552bffa87e3c1913e1884e2aabad7f
643,534
def isLucky(n): """ isLucky takes in an integer and return True if the sum of its right half == sum of the right half :param n: :return: """ # l = list(map(int, str(n))) # return sum(l[0:len(l) // 2]) == sum(l[len(l) // 2:]) s = str(n) return sum(map(int, s[: len(s) // 2])) == ...
255a19b1047f4a8c317aae656b5c5ad69aa2b750
643,535
def get_area(pos): """ Args pos: [B, N, 4] (x1, x2, y1, y2) Return area : [B, N] """ # [B, N] height = pos[:, :, 3] - pos[:, :, 2] width = pos[:, :, 1] - pos[:, :, 0] area = height * width return area
aa65cfb7313f5cdf204592a51ba17115709a2e6c
643,536
def convert_lowercase_to_camecase(name: str) -> str: """ >>> convert_lowercase_to_camecase('') '' >>> convert_lowercase_to_camecase('close') 'close' >>> convert_lowercase_to_camecase('get_title') 'getTitle' >>> convert_lowercase_to_camecase('set_array_value') 'setArrayValue' >>> ...
2237b5ffe740cb3eb5910c978a9c6902268b131c
643,537
import json def to_json(output): """Output is a single record""" return f"{json.dumps(output)}\n"
f8ffddcc1e0d28aa95310445d6b9c889670846cf
643,539
def inHg2atm(x): """inHg -> atm""" return 0.0334172218*x
814fd17d97005e03b692616827747948fc0bff2f
643,540
import torch def aggregate_dir_dx(h, eig_s, eig_d, h_in, eig_idx): """directional derivative aggregation""" eig_w = (( eig_s[:, :, eig_idx] - eig_d[:, :, eig_idx]) / (torch.sum( torch.abs(eig_s[:, :, eig_idx] - eig_d[:, :, eig_idx]), keepdim=True, dim=1) + 1e-30 ...
c967bd0da45752214fc41ad6072bec41306ce1eb
643,541
import re def cache_key(query): """Make filesystem-friendly cache key""" key = query key = key.lower() key = re.sub(r"[^a-z0-9-_;.]", "-", key) key = re.sub(r"-+", "-", key) return key
7d98352bb0c04666e175b6cd748b49c612838084
643,542
async def _get_post_id(db, author, permlink): """Get post_id from hive db.""" sql = "SELECT id FROM hive_posts WHERE author = :a AND permlink = :p" return await db.query_one(sql, a=author, p=permlink)
be64e63c81ebf9e70c5e8f97b1d57256ed756cd5
643,543
def make_binary(dat): """Simple serialize function Basically, Type-Length-Value format is created for each item. """ ret = bytearray() if isinstance(dat, list) or isinstance(dat, tuple): ret.extend(int(3).to_bytes(4, "big")) # data type = list total_len = 0 array_dat = byte...
ba05304fce5c97b238e14eb9e789a02c1a2f1875
643,544
def sum(a: int, b: int) -> int: """ Let's sum two integers! >>> sum(1,2) 3 :param a: An integer :param b: Another integer :return: the sum of both parameters """ return a + b
595b50ca6445d325a9c17b31b15e0352caa16fa0
643,545
def samples_indexes(collection, sample_size=20000, truncate=True): """ return the sample indexes for the given data :param collection: data :param sample_size: size of each sample :param truncate: get only the samples of the same size :return: """ collection_size = len(collection) #...
29167f9cf4c84b88b47d0d848395d0b509882ed0
643,546
def five_twos_trans(): """Five Twos with any grouping: +-*/""" global S S = [] def five_twos_inner(st,depth): # Allow for concatenation of a 2 with another 2 for pos in range(0,len(st)): if st[pos:pos+1] == "2": S.append(st[:pos] + "2"*(6-de...
55eafcb16e3660fd88f2c1b7661af428369de7aa
643,547
def busca_binaria(seq, procurado): """ Deve retornar o índice onde o elemento deveriar ser inserido em lista ordenada :param procurado: elemento a ser procurado :param seq: sequencia a ser pesquisada :return: int """ # Memória: O de 1 #Tempo: O de n if len(seq) == 0: return 0 ini...
a6cf64f8043e8c57a7844692d096b694fda26526
643,548
def fixdotslashspacehyphen(to_translate): """for paths, . and / to _, also space to _ """ dotslash = u'./ ' translate_to = u'-' translate_table = dict((ord(char), translate_to) for char in dotslash) return to_translate.translate(translate_table)
8242721a123e5f5eca9aa83f7c96d8dcaeaf5f59
643,549
def find_header(path: str) -> int: """find_header this function counts the lines of the header (i.e. how many lines there are until the first line with doesn't start with a '#' is encountered) Parameters ---------- path : str file path Returns ------- int number of ...
6bfd83f82762f4292f605917dc034e10d2850bd4
643,550
def fix_format(df, index_var=None): """ """ if index_var is None: index_var = df.index.levels[0].name return df.reset_index().set_index(index_var).iloc[:, 1:]
889328c7cf5769b2d1876905effc9ea1a43aa111
643,553
def split_addresses(email_string_list): """ Converts a string containing comma separated email addresses into a list of email addresses. """ return filter(None, [s.strip() for s in email_string_list.split(",")])
4fab1508179d2d974f285cec517a6fc322ac4ada
643,554
def order(replay1, replay2): """ An ordered tuple of the given replays. The first element is the earlier replay, and the second element is the later replay. Parameters ---------- replay1: Replay The first replay to order. replay2: Replay The second replay to order. Retu...
0f85dd8c56eae59caed8d5efff33f744a2f8dc17
643,555
import os def get_lib_filename(category, name): """ Get a filename of a built-in library file. """ base_dir = os.path.dirname(os.path.abspath(__file__)) if category == 'js': filename = os.path.join('js', '{0}.js'.format(name)) elif category == 'css': filename = os.path.join('css', '{0}...
7863d8931f1e67041f83c4b5bea9996c42ec41a9
643,556
def software_and_version(path): """ return 'corda-os', '4.4' """ dirs = str(path).split("/") # locate 'docs' while dirs[0] != "docs": dirs.pop(0) return dirs[1], dirs[2]
99afdbc78e2c5431c697aae83f966ab349ee9bc5
643,557