content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def extract_10x(alignment):
"""Given a 10x BAM entry as a pysam.AlignedSegment, extract the barcode,
UMI, and sequence.
:param alignment: a single BAM entry
:type alignment: pysam.AlignedSegment
:return: a 3-tuple containing (barcodes, umis, sequence)
:rtype: tuple
"""
barcode = alignm... | fbe5e439c6b1f004ef59f13633472df9185aaac4 | 418,849 |
def SelectSpecies(Species):
"""
convert various alternatives to standard species name: electron or proton
"""
if Species.lower() in ('e','e-','electron','beta'):
Species = 'electron'
elif Species.lower() in ('p','p+','h+','proton','h','hydrogen'):
Species = 'proton'
else:
... | 6be53c82b801dfd55ddc6e0d02a891c6ea989319 | 533,635 |
def Passthrough(*args):
""" A method that returns the argument list or the only value """
if len(args) == 1:
return args[0]
else:
return args | ab61f95a15a9370e2808ec3758ce3af127f33f8c | 164,873 |
def hello(text: str, caps: bool) -> str:
""" Returns text in all caps if caps = True, else returns text capitalised."""
if caps:
return text.upper()
else:
return text.capitalize() | c991b84a2806f1a4dd4d6560352e4d91313bc0a4 | 348,968 |
from typing import Tuple
def _split_environ(string: str) -> Tuple[str, str]:
"""
split environment string into name and value
:param string: original string
:return: name, value
"""
_name, _value = string.split('=', 2)
return _name, _value | 626278228ff6331a0f6fca80e32afab99272e4bb | 542,646 |
def kmh_from_mps(mps):
"""Helper function that converts meters per second (mps) to km/h."""
return str(mps * 3.6) | 0d4cfd54472f3e6cfbab7022ead380f8ef68c074 | 555,973 |
def clip(x, a, b):
"""Return the nearest point of x in the interval [a, b]"""
if a > b:
return None
return min(max(x, a), b) | 86bcb7c0e0f6810a97f3694b6a09f1cb1a0982e4 | 604,141 |
def minmax(array):
"""
This function performs a MinMax rescaling on an array
"""
return((array-min(array))/(max(array)-min(array))) | 8cdf690c942bb7f813a71330635555d2a31e09a6 | 386,599 |
def is_snapshot_version(version):
"""
Check whether the given version is a snapshot version
:param version: The version to check
:return: whether the given version is a snapshot version
"""
return version.endswith("-SNAPSHOT") | 72fd47434b4490770d4b408ad7f579886f9f9fdc | 598,460 |
from typing import List
from typing import Tuple
def check_intervals(intervals: List[Tuple[int, int]]) -> bool:
"""
Check intervals to make sure that they are sorted and non-intersecting.
:param intervals: a list of intervals, represented as tuples (a,b)
:return: True if the list is non-overlapping, a... | 91f5fb057981b90ee0db4349fcbceaf2c0bf41ec | 502,498 |
import bisect
def find_le(array, x):
"""Find rightmost value less than or equal to x.
Example::
>>> find_le([0, 1, 2, 3], 2.0)
2
**中文文档**
寻找最大的小于等于x的数。
"""
i = bisect.bisect_right(array, x)
if i:
return array[i - 1]
raise ValueError | dfa67df6fadbdead10821c4aceb027b0c5f5d90a | 35,440 |
def parse_element(tx, size):
""" Parses a given transaction to extract an element of a given size.
:param tx: Transaction where the element will be extracted.
:type tx: TX
:param size: Size of the parameter to be extracted.
:type size: int
:return: The extracted element.
:rtype: hex str
... | 131d0480af24a532a97c062d19275e2c22066792 | 176,582 |
def filter_ctrl_pert(gse_gsm_info):
"""
Filter the GSE that do not contain both control and perturbation samples
Args:
gse_gsm_info: the GSE and GSM info tuple
Returns:
True if there are both control and perturbation samples, False otherwise
"""
gse_id, gsm_info = gse_gsm_info
... | 491fd23723a026ddf68fe3a56d98e097a0732e63 | 15,728 |
from pathlib import Path
from typing import Dict
import yaml
def _load_yaml_doc(path: Path) -> Dict:
"""Load a yaml document."""
with open(path, "r") as src:
doc = yaml.load(src, Loader=yaml.FullLoader)
return doc | 4b049909c5e6eac6e7772b3311f928ccd6cf528c | 700,222 |
import re
def _skopeo_inspect_failure(result):
"""
Custom processing of skopeo error messages for user friendly description.
:param result: SkopeoResults object
:return: Message to display
"""
lines = result.stderr.split("\n")
for line in lines:
if re.match(".*Error reading manif... | 08568bf383990433b60a62fae5750a13858fe4f7 | 154,385 |
import re
def fix_whitespace(code: str) -> str:
"""Perform basic whitespace post-processing.
This corrects a couple of formatting issues that Jinja templates
may struggle with (particularly blank line count, which is tough to
get consistently right when ``if`` or ``for`` are involved).
Args:
... | 36fc6844e15892378a17bd9103e619d860f5f359 | 107,456 |
def fitness(fighter):
"""Fitness of a fighter."""
# minimum is 1 because of the way 'get_probable_fit_fighter' is implemented
return max(fighter.hits - fighter.damage, 1) | d751752cfe679e5161e5434f6070db4a05f9edd4 | 226,122 |
def listi(list_, elem, default=None):
"""
Return the elem component in a list of lists, or list of tuples, or list of dicts.
If default is non-None then if the key is missing return that.
Examples:
l = [("A", "B"), ("C", "D")]
listi(l, 1) == ["B", "D"]
l = [{"A":1, "B":2}, {"A"... | ac2866ddfd794a6bf4b02a4d1079963979d3f2d1 | 642,982 |
def is_iterable(value, allow_str=False):
"""Return if iterable."""
try:
if isinstance(value, str) and not allow_str:
return False
iter(value)
return True
except(ValueError, TypeError, Exception):
return False | 2bb20910fbec9bb83a78f983385db4504e569dfe | 137,177 |
def check_hostgroup(zapi, region_name, cluster_id):
"""check hostgroup from region name if exists
:region_name: region name of hostgroup
:returns: true or false
"""
return zapi.hostgroup.exists(name="Region [%s %s]" % (region_name, cluster_id)) | b237b544ac59331ce94dd1ac471187a60d527a1b | 2,448 |
def tax2015(income):
"""
15% on the first $44,701 of taxable income, +
22% on the next $44,700 of taxable income (on the portion of taxable income over $44,701 up to $89,401), +
26% on the next $49,185 of taxable income (on the portion of taxable income over $89,401 up to $138,586), +
29% of taxable... | b56dc3960f93e6b573c392c1490b35c43a202950 | 549,222 |
def Double_list (list_genomes):
"""
Create the new headers of the contig/s of the individual genomes and save the
headers and sequences in different lists. In the same position in a list
it will be the header and in the other its respective nucleotide sequence.
"""
# Create the lists:
heade... | d981f27ad4d95c43010ea408fef83f982cd19959 | 654,272 |
import itertools
def dict_product(d):
"""Like itertools.product, but works with dictionaries.
"""
return (dict(zip(d, x))
for x in itertools.product(*d.values())) | 150e20455dfec3b72ad771ece04096866fa46e42 | 478,174 |
import types
def normaliseArgs(func: types.FunctionType, args: list, kwargs: dict) -> dict:
"""
Merges args and kwargs into a single dict.
:param func: Function whose arguments to match against.
:param args: Positional arguments that coincide with func's parameters.
:param kwargs: Keyword argumen... | b8660eb6fd99b7bbf096b82340d5d5bf1626df35 | 307,908 |
def get_average_fluxden(input_spec, dispersion, width=10, redshift=0):
"""
Calculate the average flux density of a spectrum in a window centered at
the specified dispersion and with a given width.
The central dispersion and width can be specified in the rest-frame and
then are redshifted to the obs... | a8a968d903248ce744ce7324788576eee5c34f5a | 120,911 |
import re
def isVerilog(file):
"""Return true if the file has the .v extension."""
return re.search("\.v$", file) != None | 1a56c3d414967305fd5765fdbb9283461dff6c61 | 267,176 |
def selection_sort(arr):
"""
My Python implementation of selection sort
Sorts a list of numbers and returns the sorted list
Time complexity: O(n^2)
Space complexity: O(1)
"""
for i in range(len(arr)):
# Initialize current value as min
min = i
for j in range(i + 1,... | 1db88c0b3637376e9405abfbd143b505c7e16c4b | 571,035 |
import click
def ensure_valid_type(node_type_choices: click.Choice, node_type: str) -> str:
"""Uses click's convert_type function to check the validity of the
specified node_type. Re-raises with a custom error message to ensure
consistency across click versions.
"""
try:
click.types.conver... | 27d0b57931690066c64fb2343d419dfe8a104d8e | 660,248 |
def loop_gain(reference_range, reference_rcs, reference_snr):
"""
Calculate the loop gain given the reference range information.
:param reference_range: Reference range for the radar (m).
:param reference_rcs: Reference radar cross section for the radar (m^2).
:param reference_snr: Reference signal ... | 8f1a8874850001b5350b8d76ab1d5ef60fb057ed | 159,235 |
def sanitize_strings(txt):
"""
Removes newlines from a piece of text
:param txt: a string.
:return: a string without new lines.
"""
if not txt:
return ""
if len(txt) > 0:
return "".join(txt.splitlines())
else:
return "" | 946c615ca058229f6f9ea3d46c74287067c43dbf | 432,179 |
from datetime import datetime
def format_event(event, fmt, datefmt=None):
"""Format the received event using the provided format.
:param theia.model.Event event: the event to format.
:param str fmt: the format string. This is compatibile with :func:`str.format`.
:param str datefmt: alternative date f... | 399e07258a318ebdb0f459ca56a36463c968faef | 432,025 |
def build_scenario_evidence_map(utterances):
"""Builds a map from scenario to evidence"""
scenario_evidence_map = dict()
for utterance in utterances:
scenario = utterance['scenario']
evidence = utterance['evidence']
scenario_evidence_map[scenario] = evidence
return scenario_evide... | 3fcf935edef1e1872afea18df0c82e3b6f5cf421 | 474,865 |
from typing import Dict
from typing import Any
from typing import Optional
def create_search(
access_key: str,
url: str,
owner: str,
dataset: str,
*,
commit_id: str,
sheet: str,
criteria: Dict[str, Any],
offset: Optional[int] = None,
limit: Optional[int] = None,
) -> Dict[str, ... | 8107da04de4ecd63dfa2ed2283e0e719feafe44d | 434,996 |
import math
def logit(x: float) -> float:
"""Logit function."""
return math.log(x / (1 - x)) | 07faf3ab505bfb60596e4ceef874fe83889af652 | 116,516 |
def calc_conf_from_node(node_idx, point_idx) -> int:
"""
Calculates the configuration from a node index
:param node_idx: Integer value for the node index
:param point_idx: Index of the point that the node belongs to within the trajectory.
:return: Integer value for the robot configuration of the nod... | 995fb67d1b1ecc4281a89ea553a898352022084e | 296,818 |
def clip_float(low: float, high: float, x: float) -> float:
"""Clips a float to a range.
Args:
low: The lower bound of the range (inclusive).
high: The upper bound of the range (inclusive).
Returns:
x clipped to the specified range.
"""
return max(min(x, high), low) | b16ea89e3cb21d33d1f223d4f3e9f9b70f30e494 | 260,616 |
def validate_coin_selection(selection):
"""Validation function that checks if 'selection' arugment is an int 1-5"""
switcher = {
1: (True, "Quarter"),
2: (True, "Dime"),
3: (True, "Nickel"),
4: (True, "Penny"),
5: (True, "Done")
}
return switcher.get(selection, (F... | 8ad2561cc69448787bc51b75d50df41967a428b3 | 598,204 |
def add_selfie_to_queue(db,img_id,mural_id):
"""
@brief Adds a selfie to AdminSelfie's queue.
@param db The main database
@param img_id The amazon web service image url
@param mural_id The image identifier (links selfie to specific mural)
@return None, add... | 2e64c193d7617c88a4831a9632c5ccef29286ef5 | 414,119 |
def lorentzian_function(x_L, sigma_L, amplitude_L):
"""Compute a Lorentzian function used for fitting data."""
return amplitude_L * sigma_L**2 / (sigma_L**2 + x_L ** 2) | e26fa0e2213ff999e6691fc780fbf1f6dc48cb32 | 99,340 |
def is_getter(attribute):
"""
Test if a method is a getter.
It can be `get` or `get_*`.
"""
return attribute.startswith('get') | 0f03a45671866b09d9cfa23766a8a33c16760e5c | 649,455 |
def get_enum_strings(enum_strings, enum_dict):
"""Get enum strings from either `enum_strings` or `enum_dict`."""
if enum_dict:
max_value = max(enum_dict)
return [enum_dict.get(idx, '')
for idx in range(max_value + 1)]
return enum_strings | f7cb8238d0cc7c3c6824ef1c160b01ec213cdd29 | 628,163 |
def parse_detail_page(soup):
"""
read the week-by-week player data from the parsed html
return a dict keyed by gameweek.
"""
player_detail = []
for row in soup.find_all("tr", attrs={"class": "ng-scope"}):
gameweek_dict = {}
gameweek_dict["gameweek"] = row.find(
"td", ... | 6c46d0b21046afa80d99c06880ed7547a88230af | 321,250 |
def calc_accuracy(y_test, prediction):
"""Accuracy of the prediction.
Args:
y_test (pandas.DataFrame): Actual classes of test set.
prediction (list): Predicted classes of test set.
Returns:
Accuracy of the prediction.
"""
count = 0
length = len(y_test)
for i in rang... | 4dd8d8921d15abd72e4b4f8e080d5399279021b4 | 85,068 |
def _read_file(filename: str, binary: bool = False) -> str:
"""Read a file and return its content."""
if binary:
mode = "rb"
encoding = None
else:
mode = "r"
encoding = "utf-8"
with open(filename, mode, encoding="utf-8") as f:
return f.read() | 86bd9d533a8fa8b7a29e584052b35cb7e5c3571b | 481,758 |
def dict_loudassign(d, key, val):
"""
Assign a key val pair in a dict, and print the result
"""
print(key + ": " + str(val), flush=True)
d[key] = val
return d | 0ab1800ad81c68e1aaad5c0ad29731c2c24c26ce | 514,842 |
def unflatten_images(input_batch, depth, height, width):
"""
Take a batch of images and unflatten into a DxHxW grid.
Nearly an inverse of `flatten_images`. (`flatten_images` assumes a list of tensors, not a tensor.)
Args:
* input_batch: a tensor of dtype=float and shape (bsz, d*h*w).
* dept... | ba9cf8e6712338db2f422e7e0974e6df499dad4c | 280,997 |
def default_predictor_scoring_fun(cls):
"""Return scores of how important a feature is to the prediction
Most predictors score output coefficients in the variable
cls.feature_importances_ and others may use another name for scores, so
this function bridges the gap
Parameters
----------
cls... | f73530d3ff117dd2902280c94959361478cbd03a | 130,135 |
def is_significant_arg(arg):
"""
None and empty string are deemed insignificant.
"""
return (
arg is not None and
arg != ''
) | 816183d481aa0e3a378fe2cf6132dc14cc46f232 | 79,368 |
def chunky_file_name() -> str:
"""Return a static string to allow safely removing file after test runs."""
return 'chunky_file_test.txt' | 8451585dfc2cfbee2f504ad6bb19132e11aabae4 | 535,746 |
def esc(string):
"""
Escape strings for SQLite queries
"""
return string.replace("'", "''") | 54b2faffaba7b5b9cdccc4b6ca31d289e542105f | 636,691 |
def flatten(items):
"""Flattens a potentially nested sequence into a flat list.
:param items: the sequence to flatten
>>> flatten((1, 2))
[1, 2]
>>> flatten([1, (2, 3), 4])
[1, 2, 3, 4]
>>> flatten([1, (2, [3, 4]), 5])
[1, 2, 3, 4, 5]
"""
retval = []
for item in ite... | be48b6481bf47c9d80902b0f3df7f25a533d6814 | 642,121 |
def require_source(method):
"""Decorator that ensures source is set on the object the called
method belongs to."""
def wrapped(self, *args, **kwargs):
if self.source is None:
raise ValueError("source hasn't been set")
return method(self, *args, **kwargs)
return wrapped | 0fd544ff996d1ff73001a9d9fc044a951eeb0a35 | 163,069 |
import re
def str_contains_numbers(str):
"""
Check if a string contains at least one number.
:param str: the string to check.
:return: true if the string contains at least one number, false else.
"""
return bool(re.search(r'\d', str)) | aaaeb38f3a40db4610ce27db1bed8e0966b88d37 | 607,696 |
def clean_line(line: str) -> str:
"""Removes extra spaces and comments from the input."""
if isinstance(line, bytes):
line = line.decode() # convert bytes to strings if needed
if '//' in line:
line = line.split('//', 1)[0]
return line.strip() | dde90c6ef7ae388b493452a8ee03b8b1bf2992e6 | 223,395 |
def copy_to_len_whole(s, l):
"""Returns the maximum length string made of copies of `s` with the length
at most `l`.
Parameters
----------
s : string
String to be copied.
l : int
how many times `s` should be copied.
Returns
-------
output : string
Copies of ... | b13e0ddf60f9d0c16200b1737a180f4dd3e55ab6 | 295,828 |
import pickle
def loads(string):
"""
Wraps pickle.loads.
Parameters
----------
string : str
Returns
-------
object
Examples
--------
>>> from libtbx.easy_pickle import dumps, loads
>>> print loads(dumps([1, 2, 3])
[1, 2, 3]
"""
return pickle.loads(string) | c49992ade74561fa7f60472a9e27ba36c471f370 | 92,645 |
def is_nfs_have_host_with_host_obj(nfs_details):
""" Check whether nfs host is already added using host obj
:param nfs_details: nfs details
:return: True if nfs have host already added with host obj else False
:rtype: bool
"""
host_obj_params = ('no_access_hosts', 'read_only_hosts',
... | 8beac82c761ca71456a627c5a34db241daf3059d | 628,483 |
def _init_imago_dict(fields):
"""Initialize imago dictionary
for collection
:fields: List: List of fields for dict keys
:returns: Dict: Imago collection dictionary
"""
imago_dict = {}
for f in fields:
imago_dict[f] = []
return imago_dict | e80993965b423a2e5c0b68a4af0b2d270fb82439 | 440,740 |
def strip_neighbor_features(features, neighbor_config):
"""Strips graph neighbor features from a feature dictionary.
Args:
features: Dictionary of tensors mapping feature names to tensors. This
dictionary includes sample features but may or may not include
corresponding neighbor features for each s... | 01d53a4081dbce644d41120eac817143ec7e69de | 148,154 |
def tupilate(source, val):
"""Broadcasts val to be a tuple of same size as source"""
if isinstance(val, tuple):
assert(len(val) == len(source))
return val
else:
return (val,)*len(source) | 6047a14148aa22c32a2caa43f8ea2015ba69bd8c | 636,948 |
from typing import List
def split_and_strip(s: str, sep=",") -> List[str]:
"""Split a string representing a comma separated list of strings into a list of strings
where each element has been stripped. If the string has no elements an empty list is returned."""
string_list: List[str] = []
if s is not N... | eb1152e1f9021bcd92ce5acd9daa802acba27aed | 402,668 |
def promptUser(message, options=None, boolean=False):
"""Construct dynamic prompts for user input and return the user-entered value"""
inp = None
if (options):
options = list(map(str, options))
while inp not in options:
inp = input("{msg} [{options}]: ".format(msg=message, opti... | 66ddcde092ce98cb1888a89b89c4f9082d793761 | 264,819 |
def get_index_str(n, i):
"""
To convert an int 'i' to a string.
Parameters
----------
n : int
Order to put 0 if necessary.
i : int
The number to convert.
Returns
-------
res : str
The number as a string.
Examples
--------
```python
getI... | e7b3561a49b447d1edec22da8cc86d2a702ec039 | 9,401 |
def try_fix_num(n):
"""
Return ``n`` as an integer if it is numeric, otherwise return the input
"""
if not n.isdigit():
return n
if n.startswith("0"):
n = n.lstrip("0")
if not n:
n = "0"
return int(n) | 6c61da7fc483528e53ad7a48fa248b881b056113 | 236,042 |
import pickle
def save_pickle(obj, outfile, protocol=2):
"""Save the object as a pickle file
Args:
outfile (str): Filename
protocol (int): Pickle protocol to use. Default is 2 to remain compatible with Python 2
Returns:
str: Path to pickle file
"""
with open(outfile, 'wb... | fe35723fa9733514a7af09b56231cfafe007137e | 242,183 |
import re
def formatKey(input):
"""
formatKey converts the parameter key stored in ssm into
the traditional env. variable key format
examples:
/my-app/foo.bar -> FOO_BAR
/my-app/dev/hello-world -> HELLO_WORLD
/my-app/sbx/alpha/job_one -> JOB_ONE
"""
paths = input.split('/')
ke... | ab14f861235b06bd616b3cdd0826751e640b36c2 | 174,668 |
import importlib
def load_member(module, member):
"""
Load a member (function, class, ...) from a module and return it
:param str module: the module or package name where the class should be loaded from
:param str member: the name of the member to be loaded
"""
try:
module = importlib... | 29efa47baeb9bf409be5114d2ef54785b8ec888a | 286,446 |
def twos_complement_to_int(val, length=4):
"""
Two's complement representation to integer.
We assume that the number is always negative.
1. Invert all the bits through the number
2. Add one
"""
invertor = int('1' * length, 2)
return -((int(val, 2) ^ invertor) + 1) | 91e4d93bf334b3cc33e94cec407d09f8d74afb6b | 673,290 |
def parse_id(arg):
"""
Parses an ID from a discord @
:param arg: @ or ID passed
:return: ID
"""
if "<" in arg:
for i, c in enumerate(arg):
if c.isdigit():
return int(arg[i:-1])
# Using ID
else:
return int(arg) | 3171c4a9ae0a06d674109b50d7fc806905ef03ee | 668,283 |
import six
def to_list(var):
"""Convert var to list type if not"""
if isinstance(var, six.string_types):
return [var]
else:
return var | 3a5be47f0053d82970d2733acd4fbbb1693bf82b | 192,587 |
from datetime import datetime
def calculate_duration(start_time: datetime, end_time: datetime) -> float:
"""Calculate the duration of a process instance given start and end timestamp.
:param start_time: start
:param end_time: end
:return: duration in seconds
"""
return (end_time - start_time)... | 7a19973f5ab5668934e622759aa403514b5df89e | 355,472 |
import string
import random
def randomStr(length, num=True):
"""
Returns a random a mixed lowercase, uppercase, alfanumerical (if num True)
string long length
"""
chars = string.ascii_lowercase + string.ascii_uppercase
if num:
chars += string.digits
return ''.join(random.choice(cha... | 9b51ff5c32368c2d2552798c3fd9c8e50d80bbc0 | 301,597 |
def get_diff(instrs):
"""Returns a list of triplets of the form (ea, orig, new)."""
diff = []
for ins in instrs:
for i, (orig, new) in enumerate(zip(ins.bytes, ins.cbytes)):
if orig != chr(new):
diff.append((ins.addr + i, orig, chr(new)))
return diff | 32968d25e521e73ed29f4700b91940d4ac1b6744 | 586,441 |
def get_username() -> str:
"""
Prompts the user to enter a username and then returns it
:return: The username entered by the user
"""
while True:
print("Please enter your username (without spaces)")
username = input().strip()
if ' ' not in username:
return usernam... | 1a18a229908b86c32a0822c068b5b9081cc9fdc3 | 709,581 |
def factory_fixed_sequence(values):
""" Return a generator that runs through a list of values in order, looping after end """
def seq_generator():
my_list = list(values)
i = 0
while(True):
yield my_list[i]
if i == len(my_list):
i = 0
return se... | 004f5965bfd4a5f4cfb68b35e2d8108679ff1106 | 602,169 |
def get_inputs( filename ):
"""
The input file contains the starting decks of each player.
This function returns a list of lists of their decks.
"""
with open( filename, 'r' ) as input_file:
raw_data = input_file.read().split('\n\n')
decks = []
for num, raw_deck in enumerate(raw_dat... | 26450413e585523881fd66a92410940772761926 | 65,862 |
def reduce_helper(value, f, *a, **k):
"""
Help in `reduce`.
Helper function when applying `reduce` to a list of functions.
Parameters
----------
value : anything
f : callable
The function to call. This function receives `value` as first
positional argument.
*a, **k
... | abc5aa9c29ff122f989117a21e90821077d6be4a | 380,908 |
def _absolute_output_offsets_to_relative(off):
"""
Mixin outputs are specified in relative numbers. First index is absolute
and the rest is an offset of a previous one.
Helps with varint encoding size.
Example: absolute {7,11,15,20} is converted to {7,4,4,5}
"""
if len(off) == 0:
re... | 005f6da4f230725f45e30f4cc4a2a729028567fb | 455,952 |
def _format_lazy(format_string, *args, **kwargs):
"""
Apply str.format() on 'format_string' where format_string, args,
and/or kwargs might be lazy.
"""
return format_string.format(*args, **kwargs) | 2ae51537ee38af02bcbd1c952d92a702192d5866 | 22,995 |
def cal_confidence(antecedents_support, combination_support):
"""
calculate confidence of antecedents and consequents
Parameters
----------
antecedents_support : float
support of antecedents.
combination_support : float
support of combination.
Returns
-------
confid... | f86e06d5969e2cd2f2076c7ca95534906cf66203 | 52,934 |
import re
def baselineNumber (Title):
"""Extract the processing baseline number from the given product title."""
return re.sub(r".+_N(\d{4})_.+", r"\1", Title) | c69d099c6173cb771d14d35f520f12f32079229f | 17,178 |
def pwd(raw_value, unit=None):
"""Pulse Width Modulator (PWM) output.
The register is a 16-bit word as usual, but the module does not use the 5 LSBs.
So, 10-bit resolution on the PWM value (MSB is for sign and is fixed).
0-100% duty cycle maps to 0 to 32736 decimal value in the register.
``PWD = 1... | 2d0ae1895f98fccd8749f84fa5c1d31bbd6c5fcb | 303,407 |
def subsample_image(input_image, zoom_box_coords):
"""
Crops the input image to the coordinates described in the
'zoom_box_coords' argument.
Args:
input_image (numpy.array): The input image.
zoom_box_coords (tuple, list): Coordinates corresponding to the first
(low-resolution)... | 22b7d4e0b4e964c0e97ed5be9b3770f64bc9894b | 684,743 |
def add_int(a: int, b: int) -> int:
"""Add two integers
Parameters
----------
a
first number
b
second numbere
Returns
-------
s
sum
Examples
--------
>>> add_int(1, 2)
3
"""
return a + b | 7b55fae6d6c89a92df67b1fd70faecf1457184e8 | 431,900 |
import glob
def deglob(files):
"""
Given a list of files and globs, returns all the files and any files in the globs.
"""
new_files = []
for fn_or_glob in files:
found = False
for fn in glob.glob(fn_or_glob):
new_files.append(fn)
found = True
if not found:
raise Exception('Patt... | ccee96984355b562d1103bef5b04fbb84e03d04a | 382,346 |
import re
def get_uuid_from_task_link(task_link: str) -> str:
"""
Return the uuid from a task link.
:param str task_link: a task link
:rtype: str
:return: the uuid
:raises ValueError: if the link contains not task uuid
"""
try:
return re.findall("[a-fA-F0-9]{32}", task_link)[0... | 44bc614d6e7c9edb72517dab547d03ce6e9dc51c | 344,030 |
def int_to_bits(value, length):
"""
>>> int_to_bits(1, 3)
(1, 0, 0)
>>> int_to_bits(7, 2)
(1, 1)
"""
return tuple((value >> i) % 2 for i in range(length)) | 6a4e1a7af8a4f9e9ce18e71d6f852c954852885f | 463,845 |
def attach_tz_if_none(dt, tz):
"""
Makes a naive timezone aware or returns it if it is already aware.
Attaches the timezone tz to the datetime dt if dt has no tzinfo. If
dt already has tzinfo set, return dt.
:type dt: datetime
:param dt: A naive or aware datetime object.
:type tz: pytz ti... | cab689ed38574b028bb837c520c017b251b405e9 | 70,556 |
def get_json_response(request):
"""Retrieve the response object with content_type of json."""
response = request.response
response.headers.extend({'Content-Type': 'application/json'})
return response | 6202cc22e6e556c11c61bd55ddc5b03004165d3a | 609,279 |
def to_cartesian(algebraic):
"""Convert algebraic to cartesian
Parameters
----------
algebraic: str
Algebraic coordinate
Returns
-------
tuple
Cartesian coordinate
"""
mapper = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
... | 2fbdb40f23cc2734a346f97740e85624e22c90cc | 483,214 |
def rbits_to_int(rbits):
"""Convert a list of bits (MSB first) to an int.
l[0] == MSB
l[-1] == LSB
0b10000
| |
| \\--- LSB
|
\\------ MSB
>>> rbits_to_int([1])
1
>>> rbits_to_int([0])
0
>>> bin(rbits_to_int([1, 0, 0]))
'0b100'
>>> bin(rbits_to... | 57ef269f6690511c525081d542aed0d326a71c3b | 680,720 |
def action(function=None, *, permissions=None, description=None):
"""
Conveniently add attributes to an action function::
@admin.action(
permissions=['publish'],
description='Mark selected stories as published',
)
def make_published(self, request, queryset):
... | d0a96eebcad9a51065170fb44b8e91227067207c | 495,923 |
def log_file_name(dosya):
"""
Return file name without extention
"""
return '_'.join(dosya.split('.')[:-1]) | 98fdfbb74278a32b29eabea96b8e7b4229b121bb | 369,129 |
def colorGradient(color1, color2, steps):
"""
Returns a list of RGB colors creating a "smooth" gradient between 'color1'
and 'color2'. The amount of smoothness is determined by 'steps', which specifies
how many intermediate colors to create. The result includes 'color1' but not
'color2' to allow for co... | 8aa8e52f2fbd79e0bceafd3e5487441657215412 | 247,414 |
import torch
def compute_diffusion_params(beta):
"""
Compute the diffusion parameters defined in BDDMs
Parameters:
beta (tensor): the beta schedule
Returns:
diff_params (dict): a dictionary of diffusion hyperparameters including:
T (int), beta/alpha/sigma (torch.tenso... | a887ec17ddc35f37fb0b183b74f5dc7435a3d280 | 521,730 |
def to_base_str(n, base):
"""Converts a number n into base `base`."""
convert_string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < base:
return convert_string[n]
else:
return to_base_str(n // base, base) + convert_string[n % base] | bc137d41c9543ef1a201f4bb14234fa277067a77 | 2,007 |
def temporal_filter(start_date, end_date=None):
"""TemporalFilter data model.
Parameters
----------
start_date : str
ISO 8601 formatted date.
end_date : str, optional
ISO 8601 formatted date.
Returns
-------
temporal_filter : dict
TemporalFilter data model a... | 1fcbccc6332df17eaa00937c96108497c38aee5d | 316,696 |
import torch
def silu(x):
"""
SiLU (Sigmoid-weighted Linear Unit) activation function.
Also known as swish.
Elfwing et al 2017: https://arxiv.org/abs/1702.03118v3
"""
return torch.mul(x, torch.sigmoid(x)) | 3f18c6b28e21d72e47a564557190a286e98629e1 | 136,288 |
import random
def generate_random_room_event() -> str:
"""
Generate a random room event.
This is a helper function for add_room_to_the_board function.
:postcondition: returns a random event name for a room from the list of events.
:return: the event's name as a string
"""
list_of_events ... | 7022514de75941206e3742e3d95cdc6cd5a9657a | 524,163 |
import glob
def glob_as_args(glob_str, **kwargs):
"""Outputs a file glob as a verbose space-separated argument string for maximum crossplatforminess.
Arguments:
glob_str (str): A valid glob string used as the first argument to glob.glob
kwargs (dict): Keyword arguments to pass to glob.glob
... | 0bc58ba0a684af9610966a51733d67dcad710399 | 372,168 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.