content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def dict_recursive_update(existing_dict: dict, new_dict: dict):
"""
Recursively add values from new_dict to existing_dict.
:param existing_dict: existing dict to be updated
:param new_dict: new values to enter if an existing value does not already exist.
:return: udpated dict
"""
for key, va... | a4406d5e6212450dde98fb98ad5b37227c3cd435 | 629,560 |
def flatten(S):
""" Flattens a list of lists, but leaves tuples intact"""
flatlist = [val for sublist in S for val in sublist]
return flatlist | e6f7076832dba1fd1e962fbab8622efd23595e20 | 629,561 |
def sort_list_by_keys(values, sort_keys):
""" Sorts list values by a second list sort_keys
e.g. given ["a","c","b"], [1, 3, 2], returns ["a", "b", "c"]
Args:
values: a list of values to be sorted
sort_keys: a list of keys to sort values by
Returns:
list of values, sorte... | 59dfd2399d11c36f200f6b9b1186991f460f7004 | 629,562 |
import torch
def get_traversals(
vec: torch.Tensor,
dim_i: int,
min_value: float,
max_value: float,
n_samples: int
) -> torch.Tensor:
"""Given a single 1dim vector, get a batch of 1dim vectors by traversing
`dim_i`th dimension of `vec` linearly, from `min_value` to `max... | b17d316a913cea4e8c06039363e2becdfd9f88e4 | 629,564 |
def is_private_ip(ip_str):
""" return a quadruple if a given string is a private IP.
returns None if the input is invalid.
returns False if it is not private.
"""
arr = ip_str.split(".")
if len(arr) != 4: return None
try:
b1, b2, b3, b4 = int(arr[0]), int(arr[1]), int(arr[2])... | da70cd5edd17ddabe4f8c8badb20ae3b69aaa7da | 629,565 |
def leftshift(x, c):
""" Left shift the number x by c bytes."""
return x << c | dfb620c42c978b1737ebc2a2039e1285054727be | 629,566 |
def make_input_parameters(name,value,minimum,maximum):
"""
Outputs a parameter dictionary to be used in the fit_model function.
This dictionary has the following form:
{parameter_name1:{'value':X, 'min':Y, 'max':Z},
parameter_name2:{'value':A, 'min':B, 'max':C},
...
}
... | 38b60e10f63276d50c3a91840532e92a6bafa21c | 629,567 |
import argparse
def _parse_args() -> argparse.Namespace:
"""Parse the command-line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument("to", help="Who the message is to")
parser.add_argument("from_", help="Who the message is from")
parser.add_argument("body", help="The message body... | c1256496df6105ef07133e8e48ddb33071eef9ea | 629,568 |
import torch
def generate_softmax_labels(rois, keyps, label_h, label_w):
"""
Arguments:
rois (FloatTensor): [R, 4]
keyps (FloatTensor): [R, K, 3], (x, y, v)
label_w, label_h (int): label size
Returns:
labels (LongTensor): [R, K]
"""
assert (rois.shape[0] == keyps.s... | d0885eda07a4452ca12b687aaa79f0940e86f884 | 629,569 |
from typing import Optional
import binascii
def crc32(path) -> Optional[int]:
"""
Compute the CRC-32 checksum of the given *path*, consistent with
checksums stored in a ZIP file.
Returns None if *path* does not exist.
"""
if path.exists():
crc = 0
# Directories always return ... | 6abe3c9677df06c65bd9fec491fcb457dc073d0f | 629,570 |
import argparse
def parse_args():
"""This is directly copied from trainEBM.py"""
parser = argparse.ArgumentParser("trainEBM.py")
parser.add_argument(
"--train_from_scratch",
help="Whether to train from scratch (True) or resume (False)",
type=bool,
default=True,
)
#... | 18da64451838efaa01d9d3dafe703f2a5cf8e27a | 629,572 |
import re
def parse_hotkey(text):
"""
Extract a desired hotkey from the text. The format to enclose
the hotkey in square braces
as in Button_[1] which would assign the keyboard key 1 to that button.
The one will be included in the
button text. To hide they key, use double square braces as ... | f4fc4a28dcf9ae797b41f0e72226a5227f922060 | 629,573 |
def ten_sum_exists(matrix):
"""Calculate if the numbers provided can sum to 10.
:Parameter:
matrix: list
:Returns:
boolean, dict
"""
if not isinstance(matrix, list):
return
length = len(matrix)
count = 0
pointer = 0
ten_sum_count = 0
# Capture all the se... | 295d8ac047d359cc59bab8455b1d5b82dd22049e | 629,574 |
def ar_to_vaf(ar):
"""
Convert AR to VAF.
VAF (variant allele frequency) = V-AF
AR (allele ratio) = V-AF / WT-AF
V-AF + WT-AF = 100 (%)
Args:
ar (float): AR to convert.
Returns:
VAF (float)
"""
return ar/(ar + 1) * 100 | 681919548d827fcf551970e68545f37c89512e85 | 629,575 |
import os
def get_api_key():
"""
rtype: str
"""
key = os.environ.get('SHIPPABLE_KEY', None)
if key:
return key
path = os.path.join(os.environ['HOME'], '.shippable.key')
try:
with open(path, 'r') as key_fd:
return key_fd.read().strip()
except IOError:
... | d1eebdc35a0556364e6d425367564fb684164006 | 629,576 |
import torch
from typing import Tuple
def pack_right_padded_seq(seqs: torch.Tensor, lengths: torch.Tensor, device: str) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Function for packing a right-padded sequence, inspired by the functionality of
torch.nn.utils.rnn.pack_padded_sequence.
Instead of relying o... | 52f151174cc81a23ddbdbeddfd57d8e1d2ba11a2 | 629,577 |
def reward_lives_left(lives_left):
"""Returns rewards for number of lives left after beating the game."""
return lives_left + 1 | edc421f1388b44e97d00f8c382533a5d3756c547 | 629,578 |
def clean_attrib(value):
"""Cleans up value string.
Removes any trailing '_0' that randomly show up
Args:
value (str): attrib value to clean
Returns:
str: cleaned attribute value
"""
clean_value = value
if value.endswith("_0"):
clean_value = clean_value.strip('_0')... | b97bacf819260b9dce08fb0edcf68e0166838be2 | 629,579 |
def _remove_nones(**kwargs):
"""
Removes any kwargs whose values are `None`.
"""
final = kwargs.copy()
for k in kwargs:
if kwargs[k] is None:
final.pop(k)
return final | 787a3aba60a3651aa5b8fafcff359c9011f741b9 | 629,580 |
def scan_across_right(grid, row_i, col_i):
"""find the furtherst shaded cell diagonaly down right"""
array, height, width = grid
last_point = None
while row_i < height and col_i < width:
if array[row_i][col_i]:
last_point = (row_i, col_i)
row_i += 2
col_i += 2
... | 117a9bdfc2a02fbe8b01ee68d1f1a087fae443a9 | 629,581 |
import re
def get_xml_attrib(el, key):
"""Gets an Element attribute value without regard to namespace.
Returns:
Value of given key or None.
"""
for k in el.attrib.keys():
if key == re.sub("^{.*}", "", k):
return el.attrib[k] | 1e1bcf0325b8312cd19fb1a4f48781e8da964ea4 | 629,582 |
def GetValue(text, valname):
"""Primitive routine to retrieve a value from a string of this form:
'Santa Clara Valley - AQI: 80, Pollutant: PM2.5'
AQI: 0..500 http://www.sparetheair.org/understanding-air-quality/reading-the-air-quality-index
101+ in any district triggers a spair the air.
"""
fi... | 83e92b504d340775dc2c15067df5a6084978fb08 | 629,583 |
import copy
import numpy
def convolveAPLSF(model, data, lsf_array):
"""
Compute the LSF broadening based on apVisit header LSF coefficients.
"""
model2 = copy.deepcopy(model)
## use the middle LSF for each chip
kern_a = lsf_array[0]
kern_b = lsf_array[1]
kern_c = lsf_array[2]
## select the range of model... | fa0630a4da434f0c9465d1e53079026450bd08e8 | 629,585 |
def _merge_dicts(*dicts):
"""Merge any number of dictionaries, some of which may be None."""
final = {}
for dict in dicts:
if dict is not None:
final.update(dict)
return final | 1d8a4831bc9ccd2e8ff1b98c7db004312b21d32c | 629,586 |
from typing import Optional
import re
import click
def validate_version_string(ctx, param, value: Optional[str]) -> Optional[str]:
"""
Callback for click commands that checks that version string is valid
"""
if value is None:
return None
version_pattern = re.compile(r"\d+(?:\.\d+)+")
... | 22e084403cfa2ff72c003de53fe6b17c5dc03319 | 629,587 |
def inc(x):
"""
Increase
"""
return x + 1 | 2c8e4cc88bb802f345b2d70bce5bc093e22743e2 | 629,588 |
import os
def _CountChildDirectories(path):
"""Returns the number of child directories there are in the given |path|."""
for dummy_root, dirs, dummy_files in os.walk(path):
return len(dirs) | 798b5e0f71a778ad5472c7ad506f3dff761ee9eb | 629,589 |
def list_policies(iot_client, old_certificate_arn):
"""
Creates a list of all the policies attached to the old certificate
:param iot_client: the boto client to connect and execute
IoT APIs
:param old_certificate_arn: the old certificate arn
:return: list of policies
"""
policy_list = []... | 0d8ac00434bf57c1eca5d47c7decac0e594d51cd | 629,590 |
import hashlib
def _get_sha(sha_):
"""
Set HASH algorithm to use.
"""
hashlib_ = {
1: hashlib.sha1,
224: hashlib.sha224,
256: hashlib.sha256,
384: hashlib.sha384,
512: hashlib.sha512,
}
return hashlib_.get(sha_, hashlib.sha1) | 2396a78b4a575ac696faea9ea0a8355ead3db0b5 | 629,591 |
def get_ptr_regex():
""" Return regex matching C pointers
"""
return '(?:(?:\s*\*\s*|\s*\*\s*const\s+)+|\s+)' | 204de05a12c90d68acdb7e706f51f386d742de8a | 629,592 |
from numpy.random import RandomState
import numpy
def get_random_random(random = numpy.random):
"""
Get a randomly-initialized PRNG.
"""
return RandomState(random.randint(numpy.iinfo(int).max)) | 8ccbff56609db52fddbe2a35cf25c49b06f7dfc8 | 629,593 |
def initials(forename, surname, stream):
"""Print initials of the name
Method is memoized, so we show an actual call by writing to stream
"""
print(" ".join(("Call:", str(forename), str(surname))), file=stream)
return "%s%s" % (forename[0], surname[0]) | 0c54e0c34df6883b1f2ae75651c95245bcc8a363 | 629,595 |
from datetime import datetime
def execution_time(func):
"""Decorator to print in console the execution time of the 'func' function passed."""
def wrapper(*args, **kwargs):
t0 = datetime.now()
res = func(*args, **kwargs)
t1 = datetime.now()
print(f"\nExecution time of '{func.__n... | bd0d1b60ceddcdba7fa8562f3fdb691e23c946cf | 629,596 |
def invert_reduce_to_nonempty(objs, ids, objs_reduced):
"""Inverse of :func:`reduce_to_nonempty`."""
objs_inv = list(objs)
for idx, obj_from_reduced in zip(ids, objs_reduced):
objs_inv[idx] = obj_from_reduced
return objs_inv | 5478b325f9252e6c04498416b84975e1b4826a3c | 629,597 |
def args_from_constants(constants):
"""
>>> c = {
... "proof_of_work_nonce_size": 8,
... "nonce_length": 32,
... "max_anon_ops_per_block": 132,
... "max_operation_data_length": 32768,
... "max_proposals_per_delegate": 20,
... "max_micheline_node_count": 50000,
... | 2d460c57abae5e508c554bc9b36cddc603d71b3b | 629,598 |
def get_description_value(obj):
"""
Returns object description from LLDB value.
:param lldb.SBValue obj: LLDB value object.
:return: Object description from LLDB value.
:rtype: str | None
"""
desc = None if obj is None else obj.GetObjectDescription()
if desc == "<nil>":
desc = N... | d37541b82514a9beb06a393b6ee2743c2f495822 | 629,599 |
def pass_master_event(events, **kw):
"""Possible argument to attr_handler()"""
region_types = {e.attributes[kw['attr']['region_type']] for e in events}
if region_types == {'master'} and len(set(events)) == 1:
return events[0]
else:
return events | fb96dc02b53b6befc33f0f1a2769fa13556b9940 | 629,600 |
def _get_readable_id(id_name):
"""simplified an id to be more friendly for us people"""
pos = id_name.rfind('/')
if pos != -1:
return id_name[pos+1:]
else:
return id_name | 33d4ebadbc4e18128dca8c89ec1a3a8c5bbe4e59 | 629,601 |
def stack_allocate(type):
"""
Determine whether values of this type should be stack-allocated and partake
directly as values under composition.
"""
return type.impl.stackallocate | 7e13815f306646daca5e173ef70d4b03be9f7d34 | 629,602 |
import pathlib
import json
def get_archiver_index(config, archiver):
"""
Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
... | e6cf45201a3858effd25b3e2b83a0ab8e17af033 | 629,604 |
def clean_get_table(df):
"""Default table cleaner for get_table()"""
return df | ad3899f3481fba8b74392623b9772e68f18dfb57 | 629,605 |
import numpy
def spline_interp(h,yy,yy_diff2,x) :
"""
!subroutine splint(delt,ya,y2a,n,x,y,dydx)
!! Cubic Spline Interpolation.
!! Adapted from Numerical Recipes for a uniform grid.
implicit none
!! external
integer, intent(in) :: n
real(8), intent(in) :: delt, ya(n), y2a(n), x
real(8), intent(out) :: ... | b94150cbd31e7b118569a3f276e3f24fa55e3f8c | 629,606 |
import math
def calculate_euclideandistance(variable1, variable2, length):
"""
Used by 'k_nearest_neighbors' to determine the nearest distance between two positions (pixel-coördinates).
Keyword arguments:
variable1 -- First coördinate
variable2 -- Second coördinate
length -- Amount of cluster... | 0ec7db69006b3bb3c84ee18db3fff6f78fe9f8e8 | 629,607 |
def isInReverseAlphabeticalSequence(word):
"""
Checks if the string passed to it is in a reverse alphabetical sequence
"""
if len(word) == 1:
return False
else:
for i in range(len(word) - 1):
if ord(word[i]) != ord(word[i + 1]) - 1:
return False
re... | c1d2bd70c4acef369a54911bc5dad1301332762e | 629,608 |
def calcular_equacao_das_retas(linhas):
"""Não mude ou renomeie esta função
deve receber dois pontos que estejam em cada uma das faixas e retornar a equacao das duas retas. Onde y = h + m * x. Formato: [(m1,h1), (m2,h2)]
"""
equations = []
for linha in linhas:
point_1, point_2 = linha
... | ae12b0ae011397bfd77255e7ce0fac3085d27b6d | 629,609 |
def default_evaluation_params():
"""
default_evaluation_params: Default parameters to use for the validation and evaluation.
"""
return {
'IOU_CONSTRAINT' :0.5,
'AREA_PRECISION_CONSTRAINT' :0.5,
'GT_SAMPLE_NAME_2_ID':'gt_img_([0-9]+).txt',
... | 5ed1bd6e1ca9c689ca99e5c14708c380af49e521 | 629,610 |
def square_root_iterations(num, denom):
"""Returns next numerator and denominator is series"""
num += denom
num, denom = denom, num
num += denom
return num, denom | 3e4d4e2747ca93ac979bee056934773be98e8da1 | 629,611 |
import argparse
import os
def parse_command_line():
"""
Parses the command-line.
Returns
-------
args: namespace
Arguments parsed from the command-line.
"""
formatter_class = argparse.ArgumentDefaultsHelpFormatter
parser = argparse.ArgumentParser(description='Generates cartesianMesh.yaml '
... | 46d3dad0e2aba18d981cc8c2720f1f1123935183 | 629,612 |
def is_natural_number(number, include_zero: bool = False) -> bool:
"""
Returns True if `number` is the natural number.
Args:
number : an integer number to be checked.
include_zero (bool, optional): A flag to swith to include 0
in the natural numbers.
Defaults to Fals... | a137a074543a5b5e12ea7b6bc54f3842015d2a9b | 629,613 |
def exclude_keys(d, keys):
"""Return a new dictionary excluding all `keys`."""
return {k: v for k, v in d.items() if k not in keys} | d97c362f419403e0c413678a399b25b1e0208f34 | 629,614 |
def potencia(c):
"""Calcula y devuelve el conjunto potencia del
conjunto c.
Devuelve todas las combinaciones en una lista
"""
if len(c) == 0:
return [[]]
r = potencia(c[:-1])
return r + [s + [c[-1]] for s in r] | 26c766028fd82f98ac46fb2454edf0eacdf50244 | 629,615 |
import pandas
def get_pandas_frequency(ts):
""" Find a series' frequency integer
>>> ts = pandas.Series.from_csv('datasets/champagne_short.csv', index_col = 0, header = 0)
>>> int_frq = get_frequency(ts)
>>> int_frq
12
"""
try:
frq = pandas.infer_freq(ts.index)
... | 83390549740efea56c977f43d28275878e6ed436 | 629,616 |
def closed_range(start: int, stop: int, step=1) -> range:
"""
Creates a closed range that allows you to specify a case
from [start, stop] inclusively.
```
with switch(value) as s:
s.case(closed_range(1, 5), lambda: "1-to-5")
s.case(closed_range(6, 7), lambda: "6")
... | 03246d09649cd0e58378667ee1cf5e6b06215763 | 629,619 |
from typing import Dict
from typing import Any
from typing import Tuple
def global_average_precision_score(
y_true: Dict[Any, Any], y_pred: Dict[Any, Tuple[Any, float]]
) -> float:
"""
Compute Global Average Precision score (GAP)
Parameters
----------
y_true : Dict[Any, Any]
Dictionary... | 3cb7b97fa19ec63053b7b10668dd3d7a992b9fb9 | 629,620 |
def get_tag(commands):
"""Generates a preprocessor tag from a set of grid commands."""
# Extra line break prevents unclosed paragraphs in markdown HTML output
return "\n<!--grid:%s-->" % ';'.join([str(cmd) for cmd in commands]) | 2e5d3c099a10dd6175e94c609b88fa211b3cbe0d | 629,621 |
def flatten_dictionary(nested_dict, separator):
"""Flattens a nested dictionary.
New keys are concatenations of nested keys with the `separator` in between.
"""
flat_dict = {}
for key, val in nested_dict.items():
if isinstance(val, dict):
new_flat_dict = flatten_dictionary(val,... | f9975b2ec1cf523e1acaab57881e174b216ecac3 | 629,622 |
def _gnurl(clientID):
"""
Helper function to form URL to Gracenote service
"""
clientIDprefix = clientID.split('-')[0]
return 'https://c' + clientIDprefix + '.web.cddbp.net/webapi/xml/1.0/' | 2f6ba2a261da1920fda26c99e25c49f157e60576 | 629,623 |
def timeSortingFunction(tuple):
"""[summary]
:param tuple: [description]
:type tuple: [type]
:return: [description]
:rtype: [type]
"""
return int(tuple[1]["end_time"]) | a4a7ee1786ead0e4527fd0ce37483d472c5393fc | 629,624 |
import os
def environment_is_local() -> bool:
""" Returns true if running locally
"""
return os.getenv('PYTHON_ENV', 'LOCAL').lower() in ['local', 'dev'] | 984e422b848be2b53e5b2531670ea913f3cd5d17 | 629,625 |
import os
import subprocess
def run_external_test(path):
"""
Executes an external test by calling run.sh in the test directory.
:param path: Path where the test lives
:return: True if successful
"""
my_directory = os.getcwd()
os.chdir(path)
result = subprocess.run(['/bin/bash', './run.... | fef190e9a0ec62d52de95c4bbe2071d1243cb3bf | 629,626 |
import json
def load_json():
"""Loads .json file into backend"""
# f = open('./static/data/cannabis.json', 'r')
f = open('med-cabinet/static/data/cannabis.json', 'r')
cannabis = json.load(f)
f.close()
return cannabis | 485c0dc2ce2a7e1c4ea112c2cd47eee8a775d5f5 | 629,627 |
def hasManyOccurencies(elt, listx):
"""Find if a point has many similar occurences in a list.
This function is based on a threshold by default it is 80%.
Args:
elt: One element of the list.
listx: The list of elements
Returns:
True if it is a very frequent element, False other... | 617ee22d4dda70c8d82e82483677f768529155b3 | 629,628 |
import os
import json
import collections
def get_defaults_from_file(projectfiles, project, key=None):
"""Obtains values from the defaults.json file of the given project.
This can be called before a WSGIApplication object is created
since it uses the projectfiles information
If a key is give... | 3cffc17b88acda1f454a9af1a33211ed3216a6f2 | 629,629 |
def run_test(cfg, init_state):
"""
Run an execution given initial values for variables.
Arguments:
cfg -- control flow graph of the input program
init_state -- a test
Returns:
path -- path of the execution
state -- state after execution
"""
state = init... | 5534c5c29dae64faea62e540529c96ad87066f79 | 629,630 |
def get_platform_folder_to_keyword_map(ctx):
"""
Get the cached map of platforms to their PAL platform folder and keyword, so we can
attempt to search for platform-specific 3rd party fragments to combine with the input config file
:param ctx: Context
:return: Map of platform names to their keyword
... | 1f1fa691a51e1184238d9b949aaeb9179c0227df | 629,631 |
def tree_search(states, goal_reached, get_successors, combine_states):
"""
Given some initial states, explore a state space until reaching the goal.
`states` should be a list of initial states (which can be anything).
`goal_reached` should be a predicate, where `goal_reached(state)` returns
`True` ... | 5636b43df2da45c13569f4a9157f7df7a99aa10e | 629,632 |
def add_args_to_parser(arg_list, parser):
"""
Adds arguments from one of the argument lists above to a passed-in
arparse.ArgumentParser object. Formats helpstrings according to the
defaults, but does NOT set the actual argparse defaults (*important*).
Args:
arg_list (list) : A list of the s... | 7aad7ca5db343da6d6a6aa970b191ce8e508cfc3 | 629,633 |
def get_nsidc_url_files(response, search_str=None, file_ext=[]):
"""
Retrieve the NSIDC files based on the periods.
"""
files = []
# Parse data from the webpage on hrefs (e.g. all the sub folders)
for url in response.text.split('href='):
# Clean up any potential folder names
pot... | 50d50ba535bee64fa0cda0183b4c5394755da3d1 | 629,634 |
def updateTracker(idx,newChar,tracker,force=False):
"""Set final sequence value by column index if 'None'.
Optionally force overwrite of previously updated base."""
if tracker[idx].base and force:
# Note: Add alert when overwriting a previously set base
tracker[idx] = tracker[idx]._replace(base=newChar)
elif n... | 0b72e40af6d575ead2f585f020b6aca301076c7d | 629,635 |
def strSQLite(string):
"""
Sanitizes input for SQLite TEXT fields by converting to string and replacing
each single quote (') with two single quotes ('')
"""
return str(string).replace(r"'", "''") | 51ef66c05c55a2f3e07b8c090d763795a1175445 | 629,636 |
def add_group_cumcount(df, cols):
""" Extract sequential id in a group """
if isinstance(cols, str):
cols = [cols]
df["_".join([*cols, "cumcount"])] = df.groupby(cols).cumcount() + 1
return df | bcf15b1464419e0602cb130c6758227eeed1d131 | 629,637 |
def is_observable(v):
"""
Check whether given object should be considered as "observable" i.e. the object that manages notifiers internally
and returns observable objects from it's methods.
"""
return hasattr(v, '__notifier__') and hasattr(v, '__eval__') | d7fe05d7dfc16769b0feed43400ce59ef8e7606e | 629,638 |
def nl2br(s):
"""Related to string operation
>>> nl2br('abc\nxyz')
'abc<br/>xyz'
"""
return '<br/>'.join(s.split('\n')) | 9c5ac228d66f1b8a033fe8079cf3f1a22aff2225 | 629,639 |
import argparse
def set_arguments():
"""
set the command line arguments
"""
parser = argparse.ArgumentParser(
description='Script to Run Schedule, '
'SID uses this script to run schedule jobs')
# directories
parser.add_argument(
'--schedule_id', required=True,
... | f62dcb6c7db95089d982dc03cdbbc3627c7796c8 | 629,641 |
def inherit_docs(original):
"""A decorator that copies the docstring from a function to the decorated one"""
def wrapper(target):
target.__doc__ = original.__doc__
return target
return wrapper | 21501e506cbd211f61fbd17f7bcfd1242eb46523 | 629,642 |
def forecast_error(y, y_predicted):
"""Calculate the forecast error in a regression model.
Parameters
----------
y : array-like of shape = number_of_outputs
Represent the target values.
y_predicted : array-like of shape = number_of_outputs
Target values predicted by the model.
... | 4aede163ae2b1affbc533c9ef054ba789c8c53f0 | 629,643 |
def dehomogenize(vectors):
"""Dehomogenise a list of vectors.
Parameters
----------
vectors : list
A list of vectors.
Returns
-------
list
Dehomogenised vectors.
Examples
--------
>>>
"""
return [[x * w, y * w, z * w] for x, y, z, w in vectors] | 30a8ad582176951b609f4ba86857e2020774f784 | 629,644 |
import yaml
def read_yaml(fname):
"""Read a YAML file and return a list of Python dictionaries, one for each
document in the YAML file."""
stream = open(fname, 'r')
docs = [doc for doc in yaml.safe_load_all(stream)]
return docs | e09cb4b4236f46ab345a535f1d8a1682f30b3a1b | 629,645 |
def calculate_biased_length(segments):
""" Calculate biased segment length.
"""
# Normalize biases
segments['bias'] /= segments['bias'].sum()
# Calculate length as bias scaled by genome length
segments['length'] = segments['bias'] * float((segments['end'] - segments['start']).sum())
return... | 2e99aa566497b54ea8932a7404453fee29622fc9 | 629,647 |
def split(args):
""" This exists only for the mem request """
return {
'join' : {'__mem_gb': 10}
} | ab88b39773702efcd45738b839b1125b71930a5a | 629,648 |
def reverseWords(string):
""" reverse_words == PEP8 (forced mixedCase by CodeWars) """
return ' '.join(reversed(string.split())) | 3214cdd838b3819a9dfdc24c5f8cef877ec3577a | 629,649 |
import torch
import math
def generate_positional_encoding(seq_len, d_model):
"""
"""
pe = torch.zeros((seq_len, d_model))
position = torch.arange(0, seq_len).unsqueeze(1)
denominator = torch.exp(math.log(10000.0)*(-torch.arange(0, d_model, 2))/d_model)
pe[:, 0::2] = torch.sin(position*denomin... | fa26b81802635643667bdd6e979b7e1728743889 | 629,650 |
import os
def check_folder(output_dir):
"""Creates a new folder"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
return output_dir | 9c90ddd5b21925ed90ff8639a1b6204b80f32c3f | 629,651 |
def cos(x):
""" Approximation de cos(x) avec sa série calculée aux N=30 premiers termes."""
N = 30
n = 1
cos_x = 1.0
while n < N:
# pour l'instant cos_x = x**0/0! - x**1/1! +
# ... + (-1)**(n-1) x**(2*(n-1))/(2*(n-1))!
cos_x = ... # # /!\ à vous d'écrire quelque chose ici
... | 050e2c7ca2742e6678bc19707226b1fcf6b1d5fc | 629,652 |
def win_check(hidden_word, guessed_letters):
"""
hidden_word: string, the hidden word to guess
guessed_letters: list, with all letters user have used
return: boolean, True if all letters of hidden_word exist in guessed_letters otherwise False
"""
for letter in hidden_word:
if letter not ... | 6ea1c57897268c2ced84ad674fb1c8f078bce98a | 629,653 |
def _sugar(s):
"""Shorten strings that are too long for decency."""
# s = s.replace("{", "{{").replace("}", "}}")
if len(s) > 50:
return s[:20] + " ... " + s[-20:]
else:
return s | d38ad646c231337a19887b2f6eb2fa0271edd84e | 629,654 |
def pointer_offset(p):
"""
The offset is something like the top three nybbles of the packed bytes.
"""
# 4 bytes: a b c d
# offset is 0xcab, which is c << 12
# Ex. 0x0700 should return 15h.
return ((p & 0xF0) << 4) + (p >> 8) + 0x12 | bb76c82b684b67d198fdb045cec1c5f39238c9aa | 629,655 |
import torch
def macro_double_soft_f1(y, y_hat):
"""Compute the macro soft F1-score as a cost (average 1 - soft-F1 across all labels).
Use probability values instead of binary predictions.
This version uses the computation of soft-F1 for both positive and negative class for each label.
Args:
... | 567197cb76bec393d18604221b5a06a270cee8e4 | 629,656 |
def sumAvailable(value):
"""Sum available_in_bytes over all partitions."""
result = [x['available_in_bytes'] for x in value]
return sum(result) | d2f1ef9d7660005726d548f827d32e3b52101985 | 629,658 |
def is_palindrome(n, base=10):
"""
Is the given number n a palindrome in the given base?
"""
if base == 10:
n_str = str(n)
elif base == 2:
n_str = "{0:b}".format(n)
else:
raise RuntimeError("Only 2 and 10 bases supported")
for i in range(len(n_str) // 2):
... | 7e90c2122888d853850a84229ca3ca65074a8993 | 629,659 |
def formatSize(size_bytes):
"""
Get human readable size from number of bytes.
Args:
size_bytes (str): Size in number of bytes. Can be string or int.
"""
readable_size = int(size_bytes)
if readable_size < 1024:
return '%d Bytes' % (readable_size)
for prefix in ['', 'Ki', 'Mi',... | a36162f5c4f9156956fc5ce0c53af09326cd1e4a | 629,660 |
def find_place(lines, size_x):
"""
Finds the highest place at the left for a panel with size_x
:param lines:
:param size_x:
:return: line with row, col, len
"""
for line in lines:
if line['len'] >= size_x:
return line | 995ec1cd42526864ba80a8d8fb1991b7980b5c6e | 629,661 |
import re
def normalize(s):
""" Normalize a string """
return re.sub('[^a-z0-9_]', '_', re.sub('[()]', '', s.lower())) | dc64bb41deaf5534fdc214e806c3d04194de0ac4 | 629,662 |
import warnings
def _log_warnings_postprocess(response):
"""Logs warnings contained within the x-wf-warnings response header."""
# NOTE: .initial_metadata() will block.
for key, value in response.initial_metadata():
if key == "x-wf-warnings":
warnings.warn(value)
return response | 0207b4d37902a4a13f7cc914c64a90d3f0a0cfc2 | 629,663 |
import itertools
import pandas
def scan_mv_scores_pls(model, matrix, cv_set, inp):
"""
Extract PLS-DA scores.
Extract PLS-DA scores and provide dataframe.
Parameters
----------
model : object
PLS-DA object.
matrix : str
Predictor or response scores.
cv_set : str
... | 09e3d369817d8f3c3d21e86977160b9ee2c19aee | 629,664 |
import math
def _mapping_angle_distance(distance, origin_angle, angle):
"""
Args:
distance: 距离
origin_angle: 对应原点的角度
angle: 旋转角度
"""
_angle = origin_angle + angle
_y = distance * math.cos((math.pi * _angle) / 180)
_x = distance * math.sin((math.pi * _angle) / 180)
... | 18610c378d2b27bce465c945786b9a3019a7f520 | 629,665 |
def get_optuna_suggest(param_dict, name, trial):
"""
Returns a suggested value for the hyperparameter specified by 'name' from the range
of values in 'param_dict'
name: string specifying hyperparameter
trial: optuna trial
param_dict: dictionary containing information about the hyperparameter (r... | ac64ddf4c1dc5a252607cdb34464e358aeaeacdc | 629,666 |
def _find_min(tree):
"""Support function to find minimum node based on the key value.
This function returns node with minimum key value.
"""
if tree.has_left_child():
return _find_min(tree.left_child)
else:
return tree | de3547271cc589c94b966c0679e78b1b40842576 | 629,667 |
import re
def process_token(token: str):
"""Makes sure a given token is valid for usage within the Discord API.
Args:
token (:class:`str`): The token to be processed.
Returns:
:class:`str`: The modified, adapted token.
Examples:
.. testsetup::
from serpcord.util... | c42b58cb89e37d71f11beefd8654e3a9cf845054 | 629,668 |
def if_exception_type(*exception_types):
"""Creates a predicate to check if the exception is of a given type.
Args:
exception_types (Sequence[:func:`type`]): The exception types to check
for.
Returns:
Callable[Exception]: A predicate that returns True if the provided
... | 2384c3fc4f6f369c92c23f49f9dec40d365e2483 | 629,669 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.