content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import random def coding_problem_15(sample_generator): """ Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. Example: >>> import random >>> random.seed(0xBADC0FFE) >>> >>> def sample_gen_fun(n): ... for x i...
a556f5ee96c0e174693ccc8021d5dc00817c33fa
627,195
def get_algo(mining_pool): """ Retrieves algo when passed mining pool URL. Very often the algo and coin are actually in the POOL URL. Returns: String """ # returns the algorithm string algo = None if mining_pool is not None: x = mining_pool.count('.') if x >=...
82e5657a72835b193cb7790f06774b3e31190c27
627,201
import torch def list2vec(z1_list): """Convert list of tensors to a vector""" bsz = z1_list[0].size(0) return torch.cat([elem.reshape(bsz, -1, 1) for elem in z1_list], dim=1)
41ad6557f92b5fe602dd1fd2ff81bd20155517d5
627,202
def conservation_of_momentum(p1, u1, rho1, rho2): """Solve conservation of momentum for pressure :param <float> p1: Pressure state 1 (Pa) :param <float> u1: Velocity state 1 (m/s) :param <float> rho1: Density state 1 (kg/m^3) :param <float> rho2: Density state 2 (kg/m^3) :return <float> p2: Pr...
1e33d7fedcf8c7f3d373bb0e7e21efb1474c000e
627,203
def get_shapes(n_features, n_responses): """ Gets the shapes of the coefficeint and intercept. Parameters ---------- n_features: int Number of features. n_responses: int Number of responses Output ------ coef_shape, intercept_shape coef_shape: tuple Sh...
484586c4ab0eb7f84ff8f66eb1ff0ce079d61047
627,204
def dlr_list(client_session): """ This function returns all DLR found in NSX :param client_session: An instance of an NsxClient Session :return: returns a tuple, the first item is a list of tuples with item 0 containing the DLR Name as string and item 1 containing the dlr id as string. The ...
a7cee3130bb5d178d3c254b998cb4ade1c7803fc
627,208
def score(word: str): """Calculate a simple "score" for a word for the sake of sorting candidate guesses. For this agent, the score is just the number of distinct letters in the word. For example, "taste" has a score of 4 while "tears" has a score of 5.""" return len(set(word))
bdd77f34a2ce9ee738a9f73b5122a163e979372c
627,212
from typing import Dict from typing import Any def prepare_dict_to_print(dict: Dict[str, Any]) -> str: """Helper function to create pretty string to print dictionary. Args: dict (Dict[str, Any]): Arbitrary dictionary. Returns: str: Pretty string to print dictionary. """ sorted_i...
db7c290d2569327683db39a60c6dbe612e00d652
627,216
def _get_geonames_country_url(land): """ returns geonames country url """ geonames_countries = { 'ad': 'https://www.geonames.org/3041565', 'al': 'https://www.geonames.org/783754', 'am': 'https://www.geonames.org/174982', 'at': 'https://www.geonames.org/2782113', '...
8875b5ae809a9a66df7a540e7cc74a90a0ebf9d2
627,223
def zot_collections(zot): """ Extracts collections from Zotero API """ collections = zot.collections() return collections
3b9f4451f41c90edc188083f5b5fdd04932d672f
627,224
def normalize(value, min_value, max_value, new_min, new_max): """Normalize a value between new Min and new Max Args: value (string): The actual value min_value (string): The min range max_value (string): The max range new_min (string): The new min range new_max (string):...
3fb22df075ee91edc5b032fa7a8ca2b7e563a60c
627,225
def PNT2TidalOcto_Pv14(XA,beta0PNT=0): """ TaylorT2 0PN Octopolar Tidal Coefficient, v^14 Phasing Term. XA = mass fraction of object beta0PNT = 0PN Octopole Tidal Flux coefficient """ return (5)/(9)*(520+beta0PNT)-(2600*XA)/(9)
a7b1e8fc75938164441b91bcb91e8ee5c631a94b
627,227
import torch def grad_fun(x_est,y): """ Defines the gradient function for a denoising problem with White Noise. This function demonstrates the use of Pytorch's autograd to calculate the gradient. In this example, the function is equivalent to def grad_fun(x_est,y): return x_est - y ...
415b4cafc63e290450d9ccba55e5b697fb085a8b
627,232
def get_trade_value(x, sum_use, sector, own_production_ratio=0.8): """Function to get the trade value between a certain origin and destination. Parameters - x - row in Origin-Destination dataframe - sum_use - total use in a certain destination - own_production_ratio - Specify how much s...
2f4edbf42138bb8fb36bdbfc72ce70006a1e3444
627,234
from math import sqrt def stats( ls ) : """ Calculate the mean and variance in a list. Returns mean, variance """ if len(ls) <= 0 : return [0.0, 0.0] avg = 1.0 * sum(ls) / len(ls) if len(ls) == 1 : return [avg, 0.0] s = sqrt(1.0*sum( [ (x - avg)**2 for x in ls ]...
a159834548024cb89562ccfe491eaf46ed970387
627,237
import itertools def variable_product(variables): """Take the Cartesian product of a number of Variables. Args: variables: A sequence of Variables. Returns: A list of lists of Values, where each sublist has one element from each of the given Variables. """ return itertools.product(*(v.values f...
1aac8f846b3db51ef380972a51071cfe0d46ee84
627,239
def name_from_req(req): """Get the name of the requirement""" if hasattr(req, "project_name"): # from pkg_resources, such as installed dists for pip-sync return req.project_name else: # from packaging, such as install requirements from requirements.txt return req.name
62a135d02552fc4e566978daa4d95d6e1207ece4
627,243
def solution(a: int, b: int, k: int) -> int: """ :return: The number of integers within the range [a..b] that are divisible by k. >>> solution(6, 11, 2) 3 >>> solution(3, 14, 7) 2 """ count = (b - a + 1) // k if b % k == 0: count += 1 return count
cd88085a63fcc4d33a06109ca272c1cb3480975b
627,245
def stations_by_river(stations): """Given list of MonitoringStation objects; returns dictionary mapping river names to a list of MonitoringStation objects, which lie on that river.""" output = {} for station in stations: if station.river not in output: output[station.river] = [stati...
2c2d71b37aea996c9c45003fb5c463e663f50b30
627,246
def get_order(lm): """Return the order of a given SRILM LM.""" order = 0 for line in open(lm): if line.startswith("ngram "): try: n = int(line[len("ngram "):].split('=')[0]) except: n = 0 if n > order: order = n if order and line.startswith("\\"): break retur...
a45eb80c2d8363a1dbbc6ad2c8065424b4615658
627,250
import warnings def _get_join_params(func_kwargs): """Extract and return any join parameters.""" # remove and save the join kw, if specified (so it doesn't interfere # with other operations and doesn't get sent to the function) join_type = func_kwargs.pop("join", None) if not join_type: re...
25960830986b1db4d00697bb453021c44156d447
627,251
def sel_time(ds, tslice, mean_time=True): """ Get a time slice `tslice` from xarray data object `ds`. If `mean_time` is True, result will be averaged over the time dimension after slicing """ ds_sliced = ds.sel({"time": tslice}) if mean_time is True: return ds_sliced.mean(dim="time") ...
a59f062a41b5e8bad2664f737d4fcae9d4e39731
627,254
def _unique_label(previous_labels,label): """Returns a unique name if label is already in previous_labels.""" while label in previous_labels: if label.split('.')[-1].startswith('copy'): label='.'.join(label.split('.')[:-1])+'.copy'+str(eval('0'+label.split('.')[-1][4:])+1) else: ...
75a07d308392f3f55764978386b5f90ef8d5afe0
627,255
from typing import List def split_mtext_string(s: str, size: int = 250) -> List[str]: """Split the MTEXT content string into chunks of max `size`.""" chunks = [] pos = 0 while True: chunk = s[pos : pos + size] if len(chunk): if len(chunk) < size: chunks.appe...
9eb80c08d999cf6952ca07e14298473cfd0f4288
627,256
def ping(request, s=None): """ Test integration. Returns ------- str String 'pong' """ return 'pong'
cfbaaf3fc4eeaabe6fc8302d7dcc63d233696e46
627,260
from typing import List def _onemax(x: List[int]) -> float: """onemax(x) is the most classical case of discrete functions, adapted to minimization. It is originally designed for lists of bits. It just counts the number of 1, and returns len(x) - number of ones.. It also works in the continuous case ...
48b3b1faa7ffbc75ded8fcf14aad11ff618a5d4a
627,263
def read_plain_byte_array_fixed(file_obj, fixed_length): """Read a byte array of the given fixed_length.""" return file_obj.read(fixed_length)
caf0d924043d05180cd0c7bb267dc1fd654ed644
627,270
from typing import Tuple def choices_from_enum(source: type) -> Tuple[Tuple[int, str], ...]: """ Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices`` """ resul...
3ce88cb307a2c881ceefda2393459d2a2bf1ca9d
627,271
def require_any(json, keys): """ Require that the given dict-from-json-object contains at least one of the given keys. """ for k in keys: if k in json: return True return False
93a37ee9a9ebe2267530bd6020b3c85ee4d7c918
627,272
def join_and(value): """ Given a list of strings, format them with commas and spaces, but with 'and' at the end. >>> join_and(['apples', 'oranges', 'pears']) "apples, oranges, and pears" """ # convert numbers to strings value = [str(item) for item in value] if len(value) == 0: ...
d63a0d6d26d775648943b3829c1918d08109af87
627,274
def format_colname(name): """ Convert the column name to a better formatted name """ cmcol = " [cm$^{-2}$]" mag = " [mag]" col_mag = " [cm$^{-2}$ mag$^{-1}$]" dic_pairs = { "AV": "$A(V)$" + mag, "RV": "$R(V)$", "EBV": "$E(B-V)$" + mag, "CAV1": "$C^{A(V)}_1$",...
8f7272dbaa39e8fbb249089807c8f18828c2657f
627,278
from typing import Union def is_integer(n: Union[int, str, float]) -> bool: """Check if the given value can be interpreted as an integer. Args: n (Union[int, str, float]): value to check. Returns: bool: can be the value be interpreted as an integer. """ try: int(n) ex...
9d6b9f42aebf40f381e4a19b641c72626b4d2d4e
627,279
import json def get_json_file(filename): """ The ``get_json_file`` function is a simple helper function that serves to open, load, and return the contents of the JSON file indicated in the input ``filename`` formal parameter. :param filename: A string indicating the location and name of the ...
1be427775d7ae32472872f9d0efb2387d0d3853b
627,281
def tsum(nums): """Sum an iterable of numbers""" return sum(nums)
20825e9e1a8161d58f394ffec718b6645bc9ac0a
627,282
def read_input_from_file(f): """From an open file f, reads each line and processes it, creating the problem input variables. Parameters ---------- f : file Opened input file (with the formatting given in the Mini-Project statement) Returns ------- A : dictionary Dictionary ...
b4abe5d0b7a05a56e18dfccad57a0e944dc03924
627,288
def _etag_write_match(incoming_etag, server_etag): """ Compare two tiddler etags for a satisfactory match for a PUT or DELETE. This means comparing without the content type that _may_ be on the end. """ incoming_etag = incoming_etag.split(':', 1)[0].strip('"') server_etag = server_etag.split...
1ce4df6d1165a815a1ed3820e6ee5f8d238c09e3
627,290
def relpath(repo_path): """Return a relative path to the given path within the repo. The path is relative to the infra/bots dir, where the compile.isolate file lives. """ repo_path = '../../' + repo_path repo_path = repo_path.replace('../../infra/', '../') repo_path = repo_path.replace('../bots/', '') ...
a21078411c332402c0a3e85847236ec0adedf138
627,292
def snake_to_header(string: str) -> str: """Converts a snake case string to a table header by replacing underscores with spaces and making uppercase. Args: string (str): The snake case string. Returns: str: The header. """ return string.replace('_', ' ').upper()
1f23e86113952a0f99a48b13c9e71203a313a18f
627,296
def string_to_boolean(string): """ Converts string representations of TRUE/FALSE to an boolean value. :param str string: the string to convert. :return: _result :rtype: bool """ _result = False _string = str(string) if(_string.lower() == 'true' or _string.lower() == 'yes' or ...
12d8287c23fbee08d12be08a20020878260589fa
627,303
def _verify_non_empty_string(value, field_name): """Ensures that a given proposed field value is a non-empty string. Args: value: proposed value for the field. field_name: string name of the field, e.g. `project`. Returns: The given value, provided that it passed the checks. Raises: ValueError...
e102e94b2f02ff84a7eb0d295660fbb9c65986e5
627,305
import random import string def get_random_string(k: int = 1) -> str: """Returns a random string of length k. Args: k: Length of a string (default: 1). Returns: A random string. """ return ''.join([random.choice(string.ascii_letters) for _ in range(k)])
c40b6ed689646e57a3bad291f218679dab77bf99
627,307
def leakyReLU(x): """ Leaky rectifier transfer function if x > 0, return x ; else return 0.1 * x """ return x * (x > 0) + (.1 * x) * (x < 0)
e625a2d3dc09b9bea5b2407537a1866cfdcccaf4
627,308
from typing import Optional import traceback def format_exc(exc: Optional[int] = None) -> str: """Format a traceback.""" return traceback.format_exc(exc)
3d3df2adaca14828f393a4cb0e6a5bfcbae158e8
627,310
def parse_prot_cntct_line(prot_cntct_line): """Returns a dictionary containing the info from a line of a protein contact report from MOE Usage: parse_prot_cntct_line(prot_cntct_line) where pc_line is a string from a protein contact line from a MOE protein contact report. Returns a d...
b6d54ceb121a4b3f45234beb269d3f578f67d8e7
627,312
def step_iterator(iterator, input_data=None): """Avanza un iterador un paso, enviándole un valor si es necesario. El iterador *no* debe producir valores 'None' en ninguno de sus pasos. Args: iterator (iterator): Iterador a avanzar. input_data (object): Valor a envíar al iterador. Retur...
3376c5db139836aad49e4e5e31801e5e2c6ffcfc
627,318
def parse_mappings(mapping_list): """Parse a list of mapping strings into a dictionary. Adapted from neutron_lib.utils.helpers.parse_mappings. :param mapping_list: A list of strings of the form '<key>:<value>'. :returns: A dict mapping keys to values or to list of values. :raises ValueError: Upon ...
04f5ca0d5f71712678700507973de92e728bde29
627,322
from typing import Any def ensure_one(**kwargs: Any) -> tuple[str, Any]: """Ensures that only one argument is set.""" if sum(value is not None for value in kwargs.values()) != 1: raise ValueError('Must specify exactly one of:', kwargs.keys()) for key, value in kwargs.items(): if value is...
d8cd369f9a474867e43f9618f8b91b8cdf2fafd5
627,323
def calculate_distance(pos1: tuple, pos2: tuple) -> int: """ Taxicab/Manhattan distance """ return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
d7d0aaaf6f04820a34f8ac9fba0f8b906c1f2a5a
627,328
def pick_bball_game(p): """ prob_game1 = p prob_game2 = P(make 1+2) + P(make 1+3) + P(make 2+3) + P(make 1+2+3) prob_game2 = p*p*(1-p) + p*(1-p)*p + (1-p)*p*p + p*p*p prob_game2 = p**2 - p**3 + p**2 - p**3 + p**2 - p**3 + p**3 prob_game2 = 3 * p ** 2 - 2 * p ** 3 prob_game1 > prob_game2 ...
2c262477ba409636d5563048228b4418bbf41e8d
627,340
def matching_files(directory, prefix=None, suffix=None, prepend=False): """Get a list of files that start with a specific prefix. Args: directory (pathlib.Path): The directory containing files. prefix (str): A prefix to match filenames against. suffix (str): A suffix (file extension) to ...
3dfd056156337da428c01ff3612c84bb8f6ac8d5
627,341
def get_indices(dataset, class_name): """Return indices of class_name in dataset.""" indices = [] for i in range(len(dataset.targets)): if dataset.targets[i] == class_name: indices.append(i) return indices
5cbe22ddfc61a67e0c754576b34b3dff3d1c6b05
627,346
def filter_article(event): """ Optionally filters original article text from response. Expects "original_text" and optional "filter_article" fields in event. """ if event.get("filter_article", True): del event["original_text"] return event
fe1bc8f0ab51787fa169654fef617dd32a899fcb
627,347
from typing import List def create_questionnaire_response_item(question_id: str, answers: List[dict]) -> dict: """ Create a questionnaire response answer item following the FHIR format (https://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResp...
4ef5d0647fc57d1310127cb980383ae4d07394b1
627,349
def __carta(soup): """ Gets the most read news from the Carta Capital page :param soup: the BeautifulSoup object :return: a list with the most read news from the Carta Capital Page """ news = [] container = soup.find('dd', id='fieldset-maisacessadas-semana') most_read = container.find_a...
867de5b58333cea3e84c811920b89135f1659f59
627,351
def analysis_get_wavelength(analysis): """Gets the wavelength value of a specific analysis. Parameters ---------- analysis: Any An OpticStudio Analysis. Returns ------- int | str Either the wavelength number, or 'All' if wavelength was set to 'All'. """ wl = analys...
440a56c23444f75b737a64de4e90687277d2106f
627,352
def Choose(Decision,TrueChoice,FalseChoice): """ Ternary IIF operator, returns TrueChoice or FalseChoice based on Decision. This function is handy for use inside Curly Brace Expressions (CBE's). Decision must evaluate to true or false (0 or 1, empty or full, etc). If TRUE then TrueChoice wi...
587ef86f024339a60e0dcfa0c66415aedbde8cab
627,360
from typing import List def date_from_path(path: str) -> List[str]: """ Takes a path like bla/number1/number2 and returns [number1, number2] """ parts = [p for p in path.split('/') if p.isnumeric()] return parts
f89f2925b8eab778710731faa32718d4124f61d4
627,363
from typing import List from typing import Dict from typing import Any def targets_to(targets: List[Dict[str, Any]], device): """Moves the target dicts to the given device.""" excluded_keys = [ "questionId", "tokens_positive", "tokens", "dataset_name", "sentence_id", ...
a5a1e258378aac8b63e362497b9d4bb415c31b0f
627,365
def regroupRDDs(rdd, numGroup=10): """ regroup an rdd using a new key added that is 0-numGtoup-1 :param rdd: input rdd as a (k,v) pairs :param numGroup: number of groups to concatenate to :return: a new rdd in the form of (groupNum, list of (k, v) in that group) pairs """ rdd = rdd.map(lambda k...
6f9692b2374adf881ca81b993856f4f33ddc16b5
627,367
def db_to_linear_gain(db_value): """ Parameters ---------- db_value : float Decibel value Examples -------- >>> db_to_linear_gain(db_value=-3) 0.5011872336272722 >>> db_to_linear_gain(db_value=10) 10.0 """ return 10 ** (db_value / 10)
aca4931b53d496b573d540b1d95b394f6d9929c9
627,369
from typing import List def calculate_diff_occurrence(joltages: List[int]) -> int: """Calculate diff occurrences for differences of 1 and 3. Args: joltages (List[int]): the joltages of the adapters on hand Returns: int: the product of numbers of diff of 1 and diff of 3 """ lowes...
f331fce8319d5cc367fb2e75c282955d93364fb5
627,375
def _reverse_second_list_dimension(layers): """Reverses each list within a list of lists, but not the outer list.""" return [layer[::-1] for layer in layers]
3612f8269bef4168cf10e7f9f0036780c3c1bfc1
627,381
def std_array(comment, valueType, ndim, **kwargs): """Description for standard array column with variable shape (used for smaller arrays).""" return dict(comment=comment, valueType=valueType, ndim=ndim, dataManagerType='StandardStMan', dataManagerGroup='StandardStMan', _c_order=True, option=0, m...
e7d5c2fd68b0de81d75739ee541a29034fe44103
627,384
def split_GL_string(GL_string): """splits GL-string into alleles; if it becomes too complicated, reduce to POS """ if "|" in GL_string: # pretyping contains phasing return [GL_string] # put everything into first field else: alleles = GL_string.split("+") if len(alleles) > 4: ...
fe2fae3bc605781b178975fe6a0a578ebfd0bc13
627,388
def get_source_files(source_ID, sofia_dir_path, name_base): """Return the full path of the files for a given source generated by SoFiA. The source ID is equivalent to the ID in the catalog generated by SoFiA. This code is minimalistic, and works on a 'standard' output of SoFiA see the code for the ...
a5cfc92941e96b33b5d75eb38284f3b946eaffa4
627,389
def rglen(ar): """shortcut for the iterator ``xrange(len(ar))``""" return range(len(ar))
6bd7ab6a7d2d961eeb71f8a303f19de720f21677
627,391
from operator import mod def is_arithmetic_persian_leap_year(p_year): """Return True if p_year is a leap year on the Persian calendar.""" y = (p_year - 474) if (0 < p_year) else (p_year - 473) year = mod(y, 2820) + 474 return mod((year + 38) * 31, 128) < 31
33da473ca27dd523c5cb16cb3f4dd073daa84e53
627,396
import requests import calendar import time def coindeskticker(currency='USD'): """ get current bitcoin exchange rate from Coindesk """ data = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json').json() dataprice = data['bpi'][currency]['rate'] datatime = calendar.timegm(time.strptime(dat...
8dba84be187060d6d7792be34656483bee434f4d
627,398
def combinations_nb(n): """Return number of (i, j) combinations with 0 <= i < j < n""" return (n * (n-1)) // 2
4bc3821f0696c4a7799209aa7f11e67ef45cadfa
627,399
def read128(f): """Read the next few bytes from file f as LEB128/7bit encoding and return an integer.""" result,i = 0,0 while 1: byte=ord(f.read(1)) result|=(byte&127)<<i if byte>>7==0: return result i+=7
02dde05996e25f02600c92f989e2309a1cb321cb
627,400
def decode_seat_string(seat): """ Test data BFFFBBFRRR: row 70, column 7, seat ID 567. FFFBBBFRRR: row 14, column 7, seat ID 119. BBFFBBFRLL: row 102, column 4, seat ID 820. Seat string is 10 bits binary B = 1 F = 0 R = 1 L = 0 """ bin_seat_number = seat.replace('B', '...
8de3852c2fa3c22c5b1f70b898bf0390365f0e51
627,401
def time2levels(tstamp): """Given a :class:`datetime.datetime` object, return a list of directory levels (as strings). For example, given "2013-09-08 13:01:44", return ['2013', '09', '08', '13', '01'] """ return [tstamp.strftime(xx) for xx in ('%Y', '%m', '%d', '%H', '%M')]
d4e83672b9dd613f16f1b34a4103584413621e09
627,405
def generate_fiscal_period(context): """ Generate fiscal period based on the date provided """ reporting_end_date = context.current_parameters['reporting_end_date'] period = 0 if reporting_end_date: period = (reporting_end_date.month + 3) % 12 period = 12 if period == 0 else period r...
f7c8be1bec930a4d73fda8a1d48c60637aa28f7c
627,407
def create_ngrams(corpus_tokens, n): """Funktion, die aus den gegebenen Token saemtliche Ngramme der Laenge n extrahiert und in einer Liste speichert. Input: 1. corpus_tokens (list): Text als Liste von Tokens 2. n (int): Laenge der Ngramme Return: 1. ngrams(list): Liste von Ngrammen"...
4f72d0c70036ef12ae7e950dfb54a811d613da42
627,409
def string_reverse(input_string): """Reverses a string. Parameters ---------- input_string : str Holds the string to be reversed Returns ---------- reversed_string : str The reversed string """ reversed_string = input_string[::-1] re...
9da711b18f43730d2d7275363829f92eac5fea6b
627,411
def extract_bounds(bounds): """ Extract coordinate tuples from bound objects. """ res = [] for bound in bounds: coords = [] for vertex in bound.vertices: coords.append((vertex.x, vertex.y)) res.append(coords) return res
08689797d0857f69b4cd2fae26aed43fe7e7fa11
627,414
def _GenerateDeviceKVMId(dev_type, dev): """Helper function to generate a unique device name used by KVM QEMU monitor commands use names to identify devices. Since the UUID is too long for a device ID (36 chars vs. 30), we choose to use only the part until the third '-' with a disk/nic prefix. For example if...
79c9924e0b56b8e5dd2572205db84c12ae6a587a
627,415
def f_pitch(p, pitch_ref=69, freq_ref=440.0): """Computes the center frequency/ies of a MIDI pitch Notebook: C3/C3S1_SpecLogFreq-Chromagram.ipynb Args: p (float): MIDI pitch value(s) pitch_ref (float): Reference pitch (default: 69) freq_ref (float): Frequency of reference pitch (de...
f9567016b1db983ab72d19c898c910a3cd4fed2a
627,416
def tailcuts_clean(geom, image, picture_thresh=7, boundary_thresh=5, keep_isolated_pixels=False): """Clean an image by selection pixels that pass a two-threshold tail-cuts procedure. The picture and boundary thresholds are defined with respect to the pedestal dispersion. All pixels that ...
9d1d288e969102fabde7a94635ad426fa638ade4
627,417
import click def validate_relay(context, param, value): """ Validates presence of relay by name. """ relays = context.obj.api.relays() relay = next((r for r in relays if r["name"] == value), None) if relay is None: error = "Relay \"%s\" does not exist" % value ...
644e12abed2e308209aa4d756b9e189a3b287d97
627,419
def summarize_consensus(consensus): """ Return 'high', 'medium' or 'low' as a rough indicator of consensus. """ cons = int(100 * consensus) if cons >= 70: return "high" elif cons >= 30: return "medium" else: return "low"
4ca0357f96376d5326ea1d629c1aeee2810729bf
627,420
def _build_tool_path(d): """Build the list of tool_path for the CROSSTOOL file.""" lines = [] for k in d: lines.append(" tool_path {name: \"%s\" path: \"%s\" }" % (k, d[k])) return "\n".join(lines)
5dc12a1089943dea384ec30cce39d0fd5db4df95
627,423
import torch def squash(x, dim): """ Non-linear activation, that squashes all vectors to have norm < 1 """ norm_sq = torch.sum(x ** 2, dim, keepdim=True) norm = torch.sqrt(norm_sq) return (norm_sq / (1.0 + norm_sq)) * (x / norm)
557199cf7761d0c1524de5e328ffaf5270c43a3e
627,428
def get_constraint(obj, name): """ Get a constraint vith the given name for the given object. If constraint is not specified for the object returns None. """ for c in obj.constraints: if c.type.name == name: return c
ef963f63a3a62f97a5c5d39b0f2944af6cd7c487
627,433
def has_possible_duplicates(results): """Returns True if it detects that there are possible duplicate records in the results i.e. identical full name.""" full_names = set() for result in results: if result.full_name in full_names: return True full_names.add(result.full_name) ...
6f96973fbb964ef4cfc8f2e5fe984640fd5d928d
627,434
def padding_size(num: int) -> int: """Calculates base64 padding size as per RFC4648.""" # according to https://tools.ietf.org/html/rfc4648#section-4 # only three cases can exist mapping = { 0: 0, # no padding 2: 2, # two padding characters 3: 1, # one padding character } ...
d6762621d3e92eee48e2dc9c2bb20f6993c58424
627,440
from datetime import datetime import calendar def string_fmt_time_to_seconds(string_format_time): """ utility function to convert a string format time to epoch seconds """ dt = datetime.strptime(string_format_time, "%Y-%m-%d %H:%M:%S") epoch_seconds = calendar.timegm(dt.utctimetuple()) return epoch_se...
4b63507ec4f47b3c571a1dffaba2dba8235ee971
627,445
def get_input_channels(shape): """ Helper for temporary issues with PyTorch shape inference. Args: shape (Tuple): Shape tuple. Returns: int: Num input channels. """ # Have batch rank from placeholder space reconstruction: if len(shape) == 4: # Batch rank and channel...
990948171024b1e6bfbc384c446ba5ada0fec663
627,446
def _push(node): """ Push load away from the current node if possible. If a neighboring node which is "closer" to the target can accept more load push it to the node. If no such node is found push fails meaning a relabel has to be executed. """ success = False for edge in node.outgoing_...
c654f2671fb4726525ae601807b551e0c74c6735
627,447
def _intents_from_messages(messages): """Return all intents that occur in at least one of the messages.""" # set of distinct intents distinct_intents = {m.data["intent"] for m in messages if "intent" in m.data} return distinct_intents
4b832585e0498111e1d15bd9ff6552526f9e9623
627,448
import copy def multiply_variable(self, c, i, in_place = False): """ Replace the variables `x_i` by `c*x_i` in the quadratic form (replacing the original form if the in_place flag is True). Here `c` must be an element of the base_ring defining the quadratic form. INPUT: `c` -- an el...
fccb5423e31fdc71db9e1d5864d66baf94cf5fe5
627,451
from pathlib import Path def has_tests(module: str): """Test if a module has tests. Module format: homeassistant.components.hue Test if exists: tests/components/hue """ path = Path(module.replace(".", "/").replace("homeassistant", "tests")) if not path.exists(): return False if n...
79c473e0732aff3bf43bebfd2de1bf939e98ee2f
627,452
def sales_velocity(units_sold_last_12m, number_of_days_in_stock, velocity_days=30): """Return the sales velocity of a product for a given number of days. Args: units_sold_last_12m (int): Total number of units sold in the past 12 months. number_of_days_in_stock (int): Total number of days in the...
517864c2e4f9286a3231f0ea622c77b5fdd703c6
627,453
import ast def applyTypeConversions(settingObj, value): """ Coerce value to proper type given a valid setting object. Useful in converting XML settings with no type info (all string) as well as in GUI operations. """ if settingObj.underlyingType == list and not isinstance(value, list): ...
5c959f448ac72eea99e44b5d9bf130a32bbc86ab
627,454
import re def first_match(regex, string): """Given a regex and a string to search, this function simply returns the first match, if there is one.""" match = re.search(regex, string) return match.group(0) if match else None
7b3ec6150297d34cb4002509f585881c4dd0e993
627,459
def type2str(cls): """Convert type to type name.""" return cls.__qualname__
391d9eb85e6693be87b682fb30166b06ae636936
627,462
def get_layer_idx_for_vit(name, num_layers): """ Assign a parameter with its layer id Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33 """ if name in ["cls_token", "pos_embed"]: return 0 elif name.startswith("patch_embed"): return 0 eli...
bf6f6a024aabf207918089fe3de6a454014a3c99
627,466
def AptGetServiceName(vm): """Returns the name of the mysql service.""" return 'mysql'
ba2899267fd2511a31e481acd6daf11020c7e44e
627,471
from typing import OrderedDict def _add_minmers(minmers: dict) -> dict: """ Read through minmer results and create column for top hit. Args: minmers (dict): Mash and Sourmash results against RefSeq and GenBank Returns: dict: Top hit description for each set of databases """ r...
3f381bed8d5f940c1f475230f217f6abfb024cf9
627,472
def join_overlapping(s, e): """Join overlapping intervals. Transforms a list of possible overlapping intervals into non-overlapping intervals. Parameters ---------- s : list List with start of interval sorted in ascending order e : list List with end of interval. Retur...
3a6379de72a17217e8e523d316046346ef409c19
627,476