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 = alignment.get_tag('CR')
umi = alignment.get_tag('UR')
# The quality scores for the sequence is returned as an array.array of
# unsigned chars.
sequence = alignment.query_sequence
return ([barcode], [umi], sequence)
|
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:
raise Exception('Unknown Species: %s ' % str(Species))
return Species
|
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, and false otherwise.
"""
for (interval1, interval2) in zip(intervals, intervals[1:]):
if interval1[1] >= interval2[0]:
return False
return True
|
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
"""
element = tx.hex[tx.offset:tx.offset + size * 2]
tx.offset += size * 2
return element
|
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
sample_types = gsm_info[3]
has_ctrl = has_pert = False
for sample_type in sample_types:
if has_ctrl and has_pert:
break
if sample_type == "ctrl":
has_ctrl = True
elif sample_type == "pert":
has_pert = True
return has_ctrl and has_pert
|
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 manifest.*", line):
return "No matching tags, including 'latest', to inspect for tags list"
return "See output"
|
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:
code (str): A string of code to be formatted.
Returns
str: Formatted code.
"""
# Remove trailing whitespace from any line.
code = re.sub(r'[ ]+\n', '\n', code)
# Ensure at most two blank lines before top level definitions.
code = re.sub(r'\s+\n\s*\n\s*\n(class|def|@|#|_)', r'\n\n\n\1', code)
# Ensure at most one line before nested definitions.
code = re.sub(r'\s+\n\s*\n(( )+)(\w|_|@|#)', r'\n\n\1\3', code)
# All files shall end in one and exactly one line break.
return f'{code.rstrip()}\n'
|
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":3, "B", 4}, {"Q": 5}]
listi(l, "B", default=0) == [2, 4, 0]
"""
ret = []
for i in list_:
if isinstance(i, dict):
if elem in i:
ret += [i[elem]]
elif default is not None:
ret += [default]
else:
raise KeyError("Missing elem in list of dicts")
else:
if 0 <= elem < len(i):
ret += [i[elem]]
elif default is not None:
ret += [default]
else:
raise KeyError("Missing elem in list of lists")
return ret
|
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 income over $138,586.
"""
amt = income
tax_amt = 0
first_amt = min(44701, amt)
tax_amt = first_amt * 0.15
amt = amt - first_amt
second_amt = min(44700, amt)
tax_amt = tax_amt + (second_amt * 0.22)
amt = amt - second_amt
third_amt = min(49185, amt)
tax_amt = tax_amt + (third_amt * 0.26)
amt = amt - third_amt
tax_amt = tax_amt + (amt * 0.29)
return tax_amt
|
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:
headers = []
seqs = []
# In each genome, modify the headers and then save the headers and sequences
# in diferent lists.
for file in list_genomes:
n = 0
# Open the file to read.
file_in = open(file, 'r')
for line in file_in:
line = line.strip()
if line[0] == '>':
n += 1
# New format of header.
header = '>' + file[:-6] + '_' + str(n)
headers.append(header)
else:
seqs.append(line)
return headers, seqs
|
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 arguments that coincide with func's parameters.
:return: Dict indexed on funcs parameter names with the values of args and kwargs.
kwargs will override any conflicts with args.
"""
mergedArgs = dict(zip(func.__code__.co_varnames[:func.__code__.co_argcount], args))
mergedArgs.update(kwargs)
return mergedArgs
|
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 observed frame using the redsh keyword argument.
Warning: this function currently only works for spectra in wavelength
units. For spectra in frequency units the conversion to rest-frame will
be incorrect.
:param input_spec: Input spectrum
:type input_spec: sculptor.speconed.SpecOneD
:param dispersion: Central dispersion
:type dispersion: float
:param width: Width of the dispersion window
:type width: float
:param redshift: Redshift argument to redshift the dispersion window into
the observed frame.
:type redshift: float
:return: Average flux density
:rtype: astropy.units.Quantity
"""
disp_range = [(dispersion - width / 2.)*(1.+redshift),
(dispersion + width / 2.)*(1.+redshift)]
unit = input_spec.fluxden_unit
return input_spec.average_fluxden(dispersion_range=disp_range) * unit
|
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, len(arr)):
# Update min if new minimum found
if arr[j] < arr[min]:
min = j
# Swap current value with min value
arr[i], arr[min] = arr[min], arr[i]
return arr
|
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.convert_type(node_type_choices)(node_type)
except click.BadParameter:
raise click.exceptions.UsageError(
f"'{node_type}' is not one of {', '.join(map(repr, node_type_choices.choices))}."
) from None
return node_type
|
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 to noise ratio for the radar.
:return: The loop gain for the radar.
"""
return reference_range ** 4 * reference_snr / reference_rcs
|
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 format for formatiig the event timestamp.
The format must be compatible with :func:`datetime.strftime`
:returns: the formatted event as string.
"""
data = {
"id": event.id,
"tags": ",".join(event.tags),
"source": event.source,
"content": event.content
}
if datefmt:
try:
event_time = datetime.fromtimestamp(event.timestamp)
data['timestamp'] = event_time.strftime(datefmt)
except ValueError:
data['timestamp'] = event.timestamp
else:
data["timestamp"] = event.timestamp
return fmt.format(**data)
|
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_evidence_map
|
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, Any]:
"""Execute the OpenAPI `POST /v2/datasets/{owner}/{dataset}/commits/{commit_id}/sheets\
/{sheet}/search?offset={offset}&limit={limit}`.
Arguments:
access_key: User's access key.
url: The URL of the graviti website.
owner: The owner of the dataset.
dataset: Name of the dataset, unique for a user.
commit_id: The commit id.
sheet: The sheet name.
criteria: The criteria of the search.
offset: The offset of the page. The default value of this param in OpenAPIv2 is 0.
limit: The limit of the page. The default value of this param in OpenAPIv2 is 128.
Returns:
The response of OpenAPI.
Examples:
>>> create_search(
... "ACCESSKEY-********",
... "https://api.graviti.com",
... "czhual",
... "BDD100K",
... commit_id = "fde63f357daf46088639e9f57fd81cad",
... sheet = "train",
... criteria = {
... "opt": "or",
... "value": [
... {
... "opt": "eq",
... "key": "filename",
... "value": "0000f77c-6257be58.jpg"
... },
... {
... "opt": "and",
... "value": [
... {
... "opt": "eq",
... "key": "attribute.weather",
... "value": "clear"
... },
... {
... "opt": "eq",
... "key": "attribute.timeofday",
... "value": "daytime"
... }
... ]
... }
... ]
... }
... )
{
"data": [
{
"__record_key": "123750493121329585",
"filename": "0000f77c-6257be58.jpg",
"image": {
"url": "https://content-store-prod-vers",
"checksum": "dcc197970e607f7576d978972f6fb312911ce005"
},
"attribute": {
"weather": "clear",
"scene": "city street",
"timeofday": "daytime"
}
},
...(total 128 items)
],
"offset": 0,
"record_size": 128,
"total_count": 200
}
"""
url = f"{url}/v2/datasets/{owner}/{dataset}/commits/{commit_id}/sheets/{sheet}/search"
post_data = {"criteria": criteria}
params = {}
if offset is not None:
params["offset"] = offset
if limit is not None:
params["limit"] = limit
return open_api_do( # type: ignore[no-any-return]
"POST", access_key, url, json=post_data, params=params
).json()
|
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 node
"""
if point_idx >= 0:
return node_idx - 8 * point_idx
raise ValueError('Point index must be positive.')
|
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, (False, None))
|
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, adds a selfie entry to db["AdminSelfieQ"]
"""
entry = {
"img_id": img_id,
"mural_id": mural_id
}
db["AdminSelfieQ"].insert(entry)
return None
|
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", attrs={"data-ng-bind": "item.gameWeek"}
).text
gameweek_dict["opponent"] = row.find(
"td", attrs={"data-ng-bind": "item.opponent"}
).text
gameweek_dict["points"] = row.find(
"td", attrs={"data-ng-bind": "item.points"}
).text
gameweek_dict["goals"] = row.find(
"td", attrs={"data-ng-bind": "item.goals"}
).text
gameweek_dict["assists"] = row.find(
"td", attrs={"data-ng-bind": "item.assists"}
).text
gameweek_dict["minutes"] = row.find(
"td", attrs={"data-ng-bind": "item.minutes"}
).text
gameweek_dict["bonus"] = row.find("td", attrs={"data-ng-bind": "item.bps"}).text
gameweek_dict["conceded"] = row.find(
"td", attrs={"data-ng-bind": "item.goalsConceded"}
).text
gameweek_dict["own_goals"] = row.find(
"td", attrs={"data-ng-bind": "item.ownGoals"}
).text
player_detail.append(gameweek_dict)
return player_detail
|
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 range(length):
if prediction[i] == y_test.iloc[i]:
count += 1
return count / length
|
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).
* depth: int
* height: int
* width: int
"""
return input_batch.view(input_batch.shape[0], depth, height, width)
|
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 : sklearn predictor
A scikit-learn prediction class, such as ExtraTreesClassifier or
ExtraTreesRegressor
Returns
-------
scores : pandas.Series
A (n_features,) size series of how important each feature was to the
classification (bigger is better)
"""
return cls.feature_importances_
|
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 items:
if isinstance(item, (frozenset, list, set, tuple)):
retval += flatten(item)
else:
retval.append(item)
return retval
|
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 `s` stuck together with length at most `l`.
"""
# Initialisations
s_list = [ ]
output_list = [ ]
for i in range(len(s)):
s_list.append(s[i])
while len(output_list) < l - len(s_list):
output_list += s_list
if l - len(output_list) == len(s_list):
output_list += s_list
output = "".join(output_list)
return output
|
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',
'read_only_root_access_hosts', 'read_write_hosts',
'root_access_hosts')
for host_obj_param in host_obj_params:
if nfs_details.get(host_obj_param):
return True
return False
|
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 sample feature.
neighbor_config: An instance of `nsl.configs.GraphNeighborConfig`.
Returns:
A dictionary mapping only sample feature names to tensors. Neighbor
features in the input are not included.
"""
return {
key: value
for key, value in features.items()
if not key.startswith(neighbor_config.prefix)
}
|
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 None and isinstance(s, str):
string_list = [s.strip() for s in s.split(sep)]
return string_list
|
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, options=', '.join(options)))
elif (boolean):
inp = input("{msg} [Y/N]: ".format(msg=message)) in ["Y", "y"]
else:
inp = input("{msg}: ".format(msg=message))
return inp
|
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
getIndexStr(100,15)
```
Out:
```
'015'
```
"""
if i < 0 or i > n:
raise ValueError("N >= i or i > 0 is required")
lm = len(str(n))
res = str(i)
while lm > len(res):
res = "0" + res
return res
|
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') as f:
pickle.dump(obj, f, protocol=protocol)
return outfile
|
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('/')
keyName = paths[-1] # last item is key name
formattedKey = re.sub(r'[\.\-\_]', '_', keyName).upper()
return formattedKey
|
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.import_module(module)
except ImportError:
return None
try:
result = getattr(module, member)
except AttributeError:
return None
return result
|
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).total_seconds()
|
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(chars) for x in range(length))
|
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 username
|
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 seq_generator
|
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_data):
deck = [int(card) for card in raw_deck.splitlines()[1:] ]
decks.append( deck )
return decks
|
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
Args and kwargs passed to `f`.
"""
return f(value, *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:
return off
off.sort()
for i in range(len(off) - 1, 0, -1):
off[i] -= off[i - 1]
return off
|
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
-------
confidence of antecedents and combination.
"""
try:
return combination_support / antecedents_support
except ZeroDivisionError:
return 0
|
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 = 100 * raw_value / (2**15 - 1)``
"""
return (100 * float(raw_value) / (2 ** 15 - 1), unit)
|
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) image. Coordinates are described and ordered as
follows: (x, y, width in pixels, height in pixels), where 'x' and 'y'
describe the top-left of the box.
Default is None, which draws no box and shows no zoomed images in the
row below.
Returns:
(numpy.array) The cropped image.
Notes:
Code adapted from:
https://stackoverflow.com/questions/39382412/crop-center-portion-of-a-numpy-image
"""
start_x, start_y = zoom_box_coords[0:2]
return input_image[start_y:start_y+zoom_box_coords[3], start_x:start_x+zoom_box_coords[2]]
|
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('Pattern {} did not match any files.'.format(fn_or_glob))
return new_files
|
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]
except IndexError:
raise ValueError("Link does not contain a valid task uuid")
|
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 timezone
:param tz: The timezone to add to the datetime
:rtype: datetime
:returns: An aware datetime dt with tzinfo set to tz. If dt already had
tzinfo set, dt is returned unchanged.
"""
return tz.localize(dt) if dt.tzinfo is None else dt
|
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,
'F': 6,
'G': 7,
'H': 8}
hor = mapper[algebraic[0]]
ver = int(algebraic[1])
return (hor, ver)
|
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_int([1, 0, 1, 0]))
'0b1010'
>>> bin(rbits_to_int([1, 0, 1, 0, 0, 0, 0, 0]))
'0b10100000'
"""
v = 0
for i in range(0, len(rbits)):
v |= rbits[i] << len(rbits)-i-1
return v
|
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):
queryset.update(status='p')
This is equivalent to setting some attributes (with the original, longer
names) on the function directly::
def make_published(self, request, queryset):
queryset.update(status='p')
make_published.allowed_permissions = ['publish']
make_published.short_description = 'Mark selected stories as published'
"""
def decorator(func):
if permissions is not None:
func.allowed_permissions = permissions
if description is not None:
func.short_description = description
return func
if function is None:
return decorator
else:
return decorator(function)
|
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 connecting one gradient to another (without duplication
of colors).
"""
gradientList = [] # holds RGB lists of individual gradient colors
# find difference between color extremes
differenceR = color2[0] - color1[0] # R component
differenceG = color2[1] - color1[1] # G component
differenceB = color2[2] - color1[2] # B component
# interpolate RGB values between extremes
for i in range(steps):
gradientR = color1[0] + i * differenceR / steps
gradientG = color1[1] + i * differenceG / steps
gradientB = color1[2] + i * differenceB / steps
gradientList.append( [gradientR, gradientG, gradientB] )
# now, gradient list contains all the intermediate colors, including color1
# but not color2
return gradientList # so, return it
|
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.tensor on cpu, shape=(T, ))
These cpu tensors are changed to cuda tensors on each individual gpu
"""
alpha = 1 - beta
sigma = beta + 0
for t in range(1, len(beta)):
alpha[t] *= alpha[t-1]
sigma[t] *= (1-alpha[t-1]) / (1-alpha[t])
alpha = torch.sqrt(alpha)
sigma = torch.sqrt(sigma)
diff_params = {"T": len(beta), "beta": beta, "alpha": alpha, "sigma": sigma}
return diff_params
|
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 as a dictionnary.
"""
if not end_date:
end_date = start_date
return {
'startDate': start_date,
'endDate': end_date
}
|
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 = [
"Empty Room",
"Ancient Altar Room",
"Crate",
"Eldritch Altar",
"Stack of Books",
"Discarded Pack",
"Necronian Chest",
"Necronian Alchemy Table",
"Decorative Urn",
"Iron Maiden",
"Locked Sarcophagus",
"Suit of Armor",
"Makeshift Dining Table",
"Pile of Bones",
"Eerie Spiderweb",
"Mummified Remains",
"Transcendent Terror",
"Iron Crown",
"Ceiling Drops",
"Shifting Mist"
]
return random.choices(list_of_events, weights=[5, 1, 3, 1, 2, 3, 2, 1, 3, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1], k=1)[0]
|
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
"""
return " ".join(glob.glob(glob_str, **kwargs))
|
0bc58ba0a684af9610966a51733d67dcad710399
| 372,168 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.