content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def mk_opt_args(keys, kwargs):
"""
Make optional kwargs valid and optimized for each backend.
:param keys: optional argument names
:param kwargs: keyword arguements to process
>>> mk_opt_args(("aaa", ), dict(aaa=1, bbb=2))
{'aaa': 1}
>>> mk_opt_args(("aaa", ), dict(bbb=2))
{}
"""
def filter_kwargs(kwargs):
for k in keys:
if k in kwargs:
yield (k, kwargs[k])
return dict((k, v) for k, v in filter_kwargs(kwargs))
|
f926f87f9d166f63ba4907d1ceb4157fbbba45ad
| 165,839 |
def get_kpoints(content):
"""Read a list of kpoints and their weights from kgrid.x output file."""
lines = content.splitlines()[2:]
kpoints = list()
weights = list()
for line in lines:
k = [ float(ki) for ki in line.split()[:3] ]
w = float(line.split()[-1])
kpoints.append(k)
weights.append(w)
return kpoints, weights
|
ca049c42808c39a0ef1d28ab39f6bb661e695c6a
| 564,155 |
def sift3_distance(s_1, s_2, max_offset=5):
"""Calculate string distance
See http://siderite.blogspot.com/2007/04/super-fast-and-accurate-string-\
distance.html for background. This is a port of sift3Distance from mailcheck.js
rather than the Python code from https://gist.github.com/fjorgemota/3067867
because the latter produces different results.
:param s_1: first string
:param s_2: second string
:param max_offset: maximum offset, default: 5
:type s_1: str
:type s_2: str
:type max_offset: int
:returns: string distance
:rtype: int
"""
len_s_1 = len(s_1)
len_s_2 = len(s_2)
if len_s_1 == 0:
if len_s_2 == 0:
return 0
else:
return len_s_2
if len_s_2 == 0:
return len_s_1
c = 0
offset_1 = 0
offset_2 = 0
lcs = 0
while (c + offset_1 < len_s_1) and (c + offset_2 < len_s_2):
if s_1[c + offset_1] == s_2[c + offset_2]:
lcs += 1
else:
offset_1 = 0
offset_2 = 0
for i in range(0, max_offset):
if (c + i < len_s_1) and (s_1[c + i] == s_2[c]):
offset_1 = i
break
if (c + i < len_s_2) and (s_1[c] == s_2[c + i]):
offset_2 = i
break
c += 1
return (len_s_1 + len_s_2) / 2.0 - lcs
|
f85f983c6cbd9912a75cedf9f6a7555a5de13fc9
| 582,028 |
from typing import Iterable
def bag_of_words_to_docs(text_docs_bow: Iterable[Iterable[str]]) -> Iterable[str]:
"""Converts list of documents in "bag of words" format.
This converts back into form of document being stored in one string.
Args:
text_docs_bow: A list of lists of words from a document
Returns:
A generator expression for all of the processed documents
"""
return (" ".join(doc) for doc in text_docs_bow)
|
f728a46b26d97c8f49f88f3ec450e0732e649701
| 367,697 |
def is_indel(variant):
"""Checks if variant is an indel."""
if (len(variant.alleles[0]) != 1) or (len(variant.alleles[1])) != 1:
return True
|
574732ee20c295712a356a48636f3db66c3b7331
| 254,886 |
def cell_value_converter(cell, *args, **kwds):
"""Returns the value of a given cell."""
return cell.value
|
aced8ca5644b74463eb9248da7c0f5bd47479857
| 179,712 |
def calc_sals_ratio_ts(sals_ts):
"""
This function calculates the ratio between the saliency values of consecutive fixations.
Useful for calculating rho of the full model (see paper for details).
:param sals_ts: list of lists of time serieses of saliency values
:return: list of lists of arrays num_images x num_subjects x (T(image, subject) - 1)
of ratios between the saliencies.
"""
sals_ratio_ts = []
for sal_ts in sals_ts:
sals_ratio_ts.append([])
for subject_ts in sal_ts:
sals_ratio_ts[-1].append(subject_ts[1:] / subject_ts[:-1])
return sals_ratio_ts
|
2e025d64d0508d13f680c27e8348876cbef2cc01
| 112,348 |
import requests
import json
def get_driving_distance(start_point, end_point):
"""Gets the driving distance (km) from the start point to the end point (input in [lat, long])."""
# call the OSMR API - needs [long, lat]
r = requests.get(
f"http://router.project-osrm.org/route/v1/car/{end_point[1]},{end_point[0]};{start_point[1]},{start_point[0]}?overview=false""")
# then you load the response using the json libray
# by default you get only one alternative so you access 0-th element of the `routes`
routes = json.loads(r.content)
route_1 = routes.get("routes")[0]
driving_distance = route_1["distance"] / 1000
return driving_distance
|
49551b08a127e33c36117d847155f4c5144be01c
| 63,070 |
def edits1(word):
"""
Return all strings that are one edit away
from the input word.
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def splits(word):
"""
Return a list of all possible (first, rest) pairs
that the input word is made of.
"""
return [(word[:i], word[i:])
for i in range(len(word)+1)]
pairs = splits(word)
deletes = [a+b[1:] for (a, b) in pairs if b]
transposes = [a+b[1]+b[0]+b[2:] for (a, b) in pairs if len(b) > 1]
replaces = [a+c+b[1:] for (a, b) in pairs for c in alphabet if b]
inserts = [a+c+b for (a, b) in pairs for c in alphabet]
return set(deletes + transposes + replaces + inserts)
|
f37960f233bf9c4e6a6ca1d6e217104e3b4ba481
| 649,786 |
def _is_chinese_char(char_code: int):
"""Checks whether char_code is the code of a Chinese character."""
# https://en.wikipedia.org/wiki/List_of_CJK_Unified_Ideographs,_part_1_of_4
if (
(char_code >= 0x4E00 and char_code <= 0x9FFF) # CJK Unified Ideographs
or (char_code >= 0x3400 and char_code <= 0x4DBF) # CJK Unified Ideographs Extension A
or (char_code >= 0x20000 and char_code <= 0x2A6DF) # CJK Unified Ideographs Extension B
or (char_code >= 0x2A700 and char_code <= 0x2B73F) # CJK Unified Ideographs Extension C
or (char_code >= 0x2B740 and char_code <= 0x2B81F) # CJK Unified Ideographs Extension D
or (char_code >= 0x2B820 and char_code <= 0x2CEAF) # CJK Unified Ideographs Extension E
or (char_code >= 0xF900 and char_code <= 0xFAFF) # CJK Compatibility Ideographs
or (char_code >= 0x2F800 and char_code <= 0x2FA1F) # CJK Compatibility Ideographs Supplement
):
return True
return False
|
b36aff17e96fe900300635274d36c594f2f3e24b
| 119,824 |
def exp_max_s_option(max_exp_s):
""" Returns an options dictionary that sets the maximum expiration seconds for a JWT. """
return {
'exp_max_s': max_exp_s,
}
|
1c26da49f4cf249890441857b01ae1621d9b1cad
| 506,924 |
def reverse_taskname(name: str) -> str:
"""
Reverses components in the name of task. Reversed convention is used for filenames since
it groups log/scratch files of related tasks together
0.somejob.somerun -> somerun.somejob.0
0.somejob -> somejob.0
somename -> somename
Args:
name: name of task
"""
components = name.split('.')
assert len(components) <= 3
return '.'.join(components[::-1])
|
a49c97f3e694120b7aecba9ea325dbe78420150e
| 69,595 |
import struct
def read_tfrecord(input):
""" Read a binary TFRecord from the given input stream, and return the raw
bytes. """
# Each TFRecord has the following format, we will only read the first 8
# bytes in order to fetch the `length`, and then assume the rest of the
# record looks correct.
#
# ```
# uint64 length
# uint32 masked_crc32_of_length
# byte data[length]
# uint32 masked_crc32_of_data
# ```
#
length_bytes = b''
while len(length_bytes) < 8:
buf = input.read(8 - len(length_bytes))
if not buf:
return None
length_bytes += buf
length = struct.unpack('<Q', length_bytes)[0] + 8
remaining = b''
while len(remaining) < length:
remaining += input.read(length - len(remaining))
return length_bytes + remaining
|
a0567f95bbdecc11678c2add07be31afdfcac383
| 122,704 |
import re
def force_clean_name(name):
"""Return a name free of SWAT text tags and leading/trailing whitespace."""
while True:
match = re.search(r'(\[[\\/]?[cub]\]|\[c=[^\[\]]*?\])', name, flags=re.I)
if not match:
break
name = name.replace(match.group(1), '')
return name.strip()
|
35714933a9c5a1c0573234610d1b43b096323719
| 180,097 |
def iter_to_dict_frequency(iterable):
"""
creates a dictionary form a list and the values
are the counts of each unique item
"""
dict_frequency = {}
for item in iterable:
dict_frequency.setdefault(item, 0)
dict_frequency[item]+=1
return dict_frequency
|
266d6d1520151c1c2bda297578200021c28da70d
| 33,061 |
import torch
def sgd_momentum_old(w, dw, config=None):
"""
Performs stochastic gradient descent with momentum.
config format:
- learning_rate: Scalar learning rate.
- momentum: Scalar between 0 and 1 giving the momentum value.
Setting momentum = 0 reduces to sgd.
- velocity: A numpy array of the same shape as w and dw used to store a moving
average of the gradients.
"""
if config is None:
config = {}
config.setdefault('learning_rate', 1e-2)
config.setdefault('momentum', 0.9)
v = config.get('velocity', torch.zeros_like(w))
v = config['momentum'] * v + dw
next_w = w - config['learning_rate'] * v
config['velocity'] = v
return next_w, config
|
e4aac5fc171f98f546317b1d2c4b8bdf0dd08e3e
| 599,240 |
from typing import Dict
def filter_reuses(reuses_dict: Dict):
"""
Filter reuses and returns only those that contain some machine learning-y term in the description
:param reuses_dict:
:return:
"""
list_ml_terms = ["deep learning", "apprentissage automatique", "machine learning", "classification",
"data science", "prédire"]
ml_reuses = []
for reuse in reuses_dict["data"]:
if not reuse["featured"]:
# reuse not featured, continue
continue
reuse_ml_terms = [term in reuse["description"].lower()
for term in list_ml_terms]
if not any(reuse_ml_terms):
# no ml terms, continue
continue
ml_reuses.append(reuse)
return ml_reuses
|
0ceb4a3a31abbc8cd0c846d261e65a8efc4cda09
| 443,426 |
def set_invenio(ctx, production):
"""Add Invenio details: api urls, communities, to context object
Parameters
----------
ctx: click context obj
Api details
production: bool
If True using production api, if False using sandbox
Returns
-------
ctx: click context obj
Api details with url and community added
"""
if production:
base_url = 'https://oneclimate.dmponline.cloud.edu.au/api'
else:
base_url = 'https://test.dmponline.cloud.edu.au/api'
ctx.obj['url'] = f'{base_url}/records'
ctx.obj['deposit'] = f'{base_url}/records'
ctx.obj['communities'] = f'{base_url}/communities'
return ctx
|
f34d0c2806f9a8594d4cc07037daa6288686f786
| 33,538 |
def normalize(values, gammas):
"""Adjust a list of brightness values according to a list of gamma values.
Given a list of light brightness values from 0.0 to 1.0, adjust the value
according to the corresponding maximum brightness in the gamma list. For
example::
>>> gammas = [0.3, 1.0]
>>> values = [1.0, 1.0]
>>> normalize(values, gammas)
[0.3, 1.0]
>>> values = [0.5, 0.5]
>>> normalize(values, gammas)
[0.15, 0.5]
>>> values = [0.1, 0.0]
>>> normalize(values, gammas)
[0.03, 0.0]
"""
return [value * gamma for value, gamma in zip(values, gammas)]
|
9ba98b6dc6774c99a821141192a7af802441587e
| 302,799 |
def _el_orb(string):
"""Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (str): The element and orbitals as a string, in the form
``"C.s.p,O"``.
Returns:
dict: The elements and orbitals as a :obj:`dict`. For example::
{'Bi': ['s', 'px', 'py', 'd']}.
If an element symbol is included with an empty list, then all orbitals
for that species are considered.
"""
el_orbs = {}
for split in string.split(','):
orbs = split.split('.')
orbs = [orbs[0], 's', 'p', 'd', 'f'] if len(orbs) == 1 else orbs
el_orbs[orbs.pop(0)] = orbs
return el_orbs
|
654d085347913bca2fd2834816b988ea81ab7164
| 707,686 |
def dot(X, Y):
"""Dot product two vectors."""
return X[0]*Y[0] + X[1]*Y[1]
|
cf950b5dde688348e78b11b0b1229bc52b31b596
| 450,933 |
import uuid
def is_valid_uuid(text):
"""Return truth if given string is valid uuid.
Args:
text: a uuid string
Return:
a uuid string in standard format (dash-separated, lowercase) when text
is valid uuid or False.
"""
try:
return str(uuid.UUID(text))
except ValueError:
return False
|
d397ee9e2d877da0270f0eb166da00a347ff5c6b
| 132,304 |
def _CheckNoInterfacesInBase(input_api, output_api):
"""Checks to make sure no files in libbase.a have |@interface|."""
pattern = input_api.re.compile(r'@interface')
files = []
for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
if (f.LocalPath().find('base/') != -1 and
f.LocalPath().find('base/test/') == -1):
contents = input_api.ReadFile(f)
if pattern.search(contents):
files.append(f)
if len(files):
return [ output_api.PresubmitError(
'Objective-C interfaces or categories are forbidden in libbase. ' +
'See http://groups.google.com/a/chromium.org/group/chromium-dev/' +
'browse_thread/thread/efb28c10435987fd',
files) ]
return []
|
12ea2309bdef26e6cb361b855ab1e97c0ac5c688
| 664,234 |
def format_exception(exception):
"""
Handle the all the HTTPExceptions to return a tuple with the following
values: statusCode, status, and error_message
Parameters
----------
exception : HTTPException
The exception that catch the @app.errorhandler decorator
Returns
-------
formatted_exception : tuple
(statusCode: int, status: str, error_message: str)
"""
# HTTPException Example:
# 405 Method Not Allowed: The method is not allowed for the requested URL.
# Create a list of strings from HTTPException splitted by :
# ['405 Method Not Allowed',
# 'The method is not allowed for the requested URL.']
exception_list = str(exception).split(': ')
# Get the statusCode from the slice of the first item of the exception_list
statusCode = int(exception_list[0][:3])
# Get the status from the slice of the first item of the exception_list
status = exception_list[0][3:].strip()
# Get the error_message from the second item of the exception_list
error_message = exception_list[1]
return statusCode, status, error_message
|
d6164623df4c9044977d8d481ce1a4e130cc5dc8
| 222,762 |
def timeseries_train_test_split(X, y, test_size):
"""
Perform train-test split with respect to time series structure
"""
# get the index after which test set starts
test_index = int(len(X)*(1-test_size))
X_train = X.iloc[:test_index]
y_train = y.iloc[:test_index]
X_test = X.iloc[test_index:]
y_test = y.iloc[test_index:]
return X_train, X_test, y_train, y_test
|
f066cde3fc58de00b6d592d406b94e98beb0cbeb
| 666,063 |
def primitiveIsValue(interp, s_frame, w_recv):
"""
Tests if `w_recv` is a value.
:param interp: The interpreter proxy.
:param s_frame: The stack frame.
:param w_recv: The receiver object.
:returns: `w_true` if `w_recv` is a value.
"""
if w_recv.is_value():
return interp.space.w_true
return interp.space.w_false
|
ccce7897afcb4ef9a8bab3a45f22608ecd345fec
| 439,804 |
def get_data_frequency(data, features):
"""
Returns number of rows in `data` where the rows have value specified by `features`.
Counts all rows where for which the column values corresponds those given in `features`.
Parameters
----------
data : numpy array
N x D table of recorded occurrences
features : dict of {int : int}
Dictionary of (data_index : value) pairs
Key is the feature index, and value is a truth value: 0 or 1.
Returns
-------
int in [0,N]
Number of samples with corresponding feature values.
"""
return len([item for item in data if all(item[feature] == val for feature, val in features.items())])
|
e5d377f11ff4b49e167ba68c31008b29ee112d6a
| 495,417 |
def convert_to_regex(rules_dict: dict, rule_num: int, depth: int=0) -> str:
"""Convert rule to its regex equivalent and return it.
Args:
rules_dict: Dictionary of rule_num: rule.
rule_num: Key for rules_dict corresponding to rule to be converted.
depth: Number of recursive calls to the function. Defaults to 0 and
used to set a limit on processing of loops.
Returns:
The regex string equivalent of the rule at key rule_num in rules_dict
(to a capped depth).
"""
if depth > 15:
return ''
if rules_dict[rule_num] in ('a', 'b'):
return rules_dict[rule_num]
rules = []
for branches in rules_dict[rule_num].split('|'):
branch_answer = ''
for branch_num in branches.split():
branch_re = convert_to_regex(rules_dict, branch_num, depth + 1)
branch_answer += branch_re
rules.append(branch_answer)
return '(' + '|'.join(rules) + ')'
|
13acce0b54a69b9c45c3c0ce35f9779bfe6934bc
| 475,046 |
import gzip
import bz2
import lzma
def fopen(filename, mode=None):
"""GZ/BZ2/XZ-aware file opening function."""
# NOTE: Mode is not used but kept for not breaking iterators.
if filename.endswith('.gz'):
return gzip.open(filename, 'rt')
elif filename.endswith('.bz2'):
return bz2.open(filename, 'rt')
elif filename.endswith(('.xz', '.lzma')):
return lzma.open(filename, 'rt')
else:
# Plain text
return open(filename, 'r')
|
b384cae1b40b409b3d16b4431565d493da8d363f
| 681,506 |
def normalize_common_name(common_names):
"""
This will produce a set normalized common names (that is they will be
lowercased).
"""
return {n.lower() for n in common_names if n}
|
9c6a7c37062655fe047e193e7feddf43161bc18b
| 321,707 |
from pathlib import Path
def dir_path(path):
"""Wrapper around Path that ensures this directory is created."""
if not isinstance(path, Path):
path = Path(path)
path.mkdir(exist_ok=True, parents=True)
return path
|
9227f9ac99d6c4278ea16c094c08205deeed7337
| 583,544 |
import pathlib
def invalid_file(tmpdir, request):
"""Return a path to an invalid config file.
Remove the file when a test is finished with it.
"""
data_dir = pathlib.Path(str(tmpdir))
invalid_file = data_dir.joinpath('invalid')
with invalid_file.open('w') as f:
f.write('this is invalid')
def tearDown():
if invalid_file.exists():
invalid_file.unlink()
request.addfinalizer(tearDown)
return invalid_file
|
fe84f645a433dec37f2dd8a55f2927d7debef3e0
| 180,025 |
def desaturate(img):
"""Desaturate an RGB or BGR image
Receive an RGB or BGR image as a 3D uint8 numpy array. Custom
desaturate by keeping only the value of the darkest pixel in any of
the channels. White background and black ink are therefore not
affected but even very bright ink of commonly used colors (namely
blue and red but also valid for green, cyan, magenta and even yellow)
in the same image is desaturated to near black to facilitate
thresholding. Return a single-channel image as a 2D uint8 numpy array.
Note: Specifically for text detection against a white-balanced
background this should be the preferred desaturating method followed
by custom thresholding even (especially) if the intent is to use the
thresholded result by OpenCV contour detection or similar algorithms.
"""
return img.min(axis=2)
|
cc21b1cc942e14bffcc05699c20a08e384dc6e3e
| 421,243 |
def unsetbit(x, nth_bit):
"""unset n-th bit (i.e. set to 0) in an integer or array of integers
Args:
x: integer or :class:`numpy.ndarray` of integers
nth_bit: position of bit to be set (0, 1, 2, ..)
Returns:
integer or array of integers where n-th bit is unset while all other bits are kept as in input x
Examples:
>>> unsetbit(7, 2)
3
>>> unsetbit(8, 2)
8
"""
if nth_bit < 0:
raise ValueError('position of bit cannot be negative')
mask = 1 << nth_bit
return x & ~mask
|
48db00ca0d8e9f7e89df092a0d96c5b8cc79c00a
| 486,949 |
def write_meta(meta_data, data_set):
"""
Writes meta data into the data set.
:param meta_data: Array N x 4, where N is the number of data elements.
:param data_set: Dicom Data Set
:return: Modified Data Set
"""
for elem in meta_data:
data_set.add_new((hex(elem[0]), hex(elem[1])), elem[2], elem[3])
return data_set
|
83d9bac7e896a50e249425ddcf5f6c1acad68789
| 306,545 |
from typing import Iterable
def closest_smaller(list_of_numbers: Iterable[int], number: int) -> int:
"""Returns the closest number that is smaller that the given number.
Examples
--------
>>> l = [1, 4, 9, 16, 25]
>>> n = 19
>>> closest_smaller(l, n)
16
Parameters
----------
list_of_numbers: Iterable[int]
The numbers to get the closest from
number: int
The number to get the closest of
Returns
-------
int
The closest smaller number
"""
return min(list_of_numbers, key=lambda x: abs(x - number))
|
5255782d0a3bc5309436f7348b2a5d0e7ab91dce
| 223,811 |
def GuessTargetArch(bisect_bot):
"""Returns target architecture for the bisect job."""
if 'x64' in bisect_bot or 'win64' in bisect_bot:
return 'x64'
elif bisect_bot in ['android_nexus9_perf_bisect']:
return 'arm64'
else:
return 'ia32'
|
9c40ce5e32f6b6faca6ef6c6fecb43a22fe7319c
| 347,931 |
def parseDependencyFile(path, targetSuffix):
"""Parse a .d file and return the list of dependencies.
@param path: The path to the dependency file.
@type path: string
@param targetSuffix: Suffix used by targets.
@type targetSuffix: string
@return: A list of dependencies.
@rtype: list of string
"""
dependencies = []
uniqueDeps = set()
def addPath(path):
if path and path not in uniqueDeps:
uniqueDeps.add(path)
path = path.replace('\\ ', ' ') # fix escaped spaces
dependencies.append(path)
f = open(path, 'rt')
try:
text = f.read()
text = text.replace('\\\n', ' ') # join escaped lines
text = text.replace('\n', ' ') # join other lines
text = text.lstrip() # strip leading whitespace
# Find the 'target:' rule
i = text.find(targetSuffix + ':')
if i != -1:
text = text[i+len(targetSuffix)+1:] # strip target + ':'
while True:
text = text.lstrip() # strip leading whitespace
i = text.find(' ')
while i != -1 and text[i-1] == '\\': # Skip escaped spaces
i = text.find(' ', i+1)
if i == -1:
addPath(text)
break
else:
addPath(text[:i])
text = text[i:]
finally:
f.close()
return dependencies
|
14b624c1870083e154d896d77ed41133a4e5ef36
| 57,757 |
def linear(xs, slope, y0):
"""A simple linear function, applied element-wise.
Args:
xs (np.ndarray or float): Input(s) to the function.
slope (float): Slope of the line.
y0 (float): y-intercept of the line.
"""
ys = slope * xs + y0
return ys
|
2a588addaa6e99f5c027e322e0c25b64739e11fc
| 537,187 |
import uuid
def is_valid_uuid(uuid_to_test, version=None):
"""
Check if uuid_to_test is a valid UUID.
:param uuid_to_test: str
:param version: int {1, 2, 3, 4} or None
:return: True if uuid_to_test is from a valid UUID
"""
try:
if version:
uuid_obj = uuid.UUID(uuid_to_test, version=version)
else:
uuid_obj = uuid.UUID(uuid_to_test)
except (ValueError, AttributeError, TypeError):
return False
return uuid_obj.hex == uuid_to_test
|
6233c5b96d41e7002a27e0d8d181da44d34094c2
| 581,921 |
import uuid
def case_key(case):
"""
Create a unique key for this case.
"""
if hasattr(case, 'key'):
return case.key
key = str(uuid.uuid1())
return key
|
6239d2bf196b421ec9ca19d3628a87a3632bbbcb
| 376,302 |
def _endpoints_by_hosts(endpoints):
"""Return a dict consisting of the host-endpoint pairs as key-values."""
rv = {}
for ep in endpoints:
host, _ = ep['hostport'].split(':')
rv[host] = ep
return rv
|
4a30f03bda29572e03ea3bef4c97ad86dd8d4886
| 524,521 |
def compute_perc_word_usage(word, tokenized_string):
"""
Given a tokenized string (list of tokens), return the fraction of use of a given word as fraction of all tokens.
"""
return tokenized_string.count(word) / len(tokenized_string)
|
289baa8bd6f598a86a53b67753d99d26f2b712f0
| 392,229 |
def is_base_complement(c1, c2):
"""Returns true if c1 is a watson-crick complement of c2
args:
c1 -- char
c2 -- char
returns:
bool -- True if is complement, false otherwise
"""
if c1 == "A":
return c2 == "U"
elif c1 == "U":
return c2 == "G" or c2 == "A"
elif c1 == "G":
return c2 == "C" or c2 == "U"
elif c1 == "C":
return c2 == "G"
return False
|
992a2b7f5aaf9761acc9f3f5763e62cdf9c115a0
| 483,973 |
def new_id_map(df, next_id):
""" Creates a new id for each record in df, starting with next_id """
segids = df.index.tolist()
id_map = {segid: n for (segid, n) in
zip(segids, range(next_id, next_id+len(segids)))}
return id_map, next_id+len(segids)
|
35a0ef56ae3b9beac7fda70495724badbecbe9a8
| 422,601 |
def _replace_null_column_names(column_list):
"""Replace null names in columns from file cleaning with an appropriately
blank column name.
Parameters
----------
column_list: list[dict]
the list of columns from file cleaning.
Returns
--------
column_list: list[dict]
"""
new_cols = []
for i, col in enumerate(column_list):
# Avoid mutating input arguments
new_col = dict(col)
if new_col.get('name') is None:
new_col['name'] = 'column_{}'.format(i)
new_cols.append(new_col)
return new_cols
|
d3345c5b18ae22f774c7ed63c0c29c108d74d2ef
| 438,843 |
def convert_asterisk_to_none(state: str) -> str | None:
"""Convert HERE API representation of None."""
if state == "*":
return None
return state
|
6b2d63d7a2dcfbbb947b71e7e4d414a4a514c469
| 475,893 |
def serial_number_hash(data: str) -> str:
"""Hashes any string to 6 bytes serial number
Example: 'PyHAP' -> '3331779EC7A8'
Hash function is BLAKE2b with 6 bytes digest size
"""
h = blake2b(digest_size=6) # type: ignore
h.update(data.encode())
return h.hexdigest().upper()
|
22b514486b7a79db9f0ce59654dc3853f05e3677
| 206,651 |
def add(*items):
"""Adds one or more vectors."""
if len(items) == 0: return 0
n = len(items[0])
for v in items:
if n!=len(v):
raise RuntimeError('Vector dimensions not equal')
return [sum([v[i] for v in items]) for i in range(n)]
|
837321ac712cd5a7f3c52c96e0512d0153749001
| 68,144 |
import toml
def check_fpm_toml(contents):
"""Checks contents of fpm.toml, returns cut-down version for json index"""
p = toml.loads(contents)
fpm_info = {}
# Must be present, copied to json
required_keys = ["name", "version", "license", "author",
"maintainer", "copyright"]
# Optionally present, copied to json
optional_keys = ["description", "executable", "dependencies",
"dev-dependencies"]
# Optionally present, not copied to json
other_keys = ["test", "library", "build", "extra"]
# Check for required keys
for key in required_keys:
if key not in p:
raise Exception(f"Missing required key '{key}' in fpm.toml.")
for key in p.keys():
if key not in required_keys + optional_keys + other_keys:
print(f" (!) Warning: unexpected key '{key}; in fpm.toml")
# Copy keys to dict for json index
for key in required_keys:
fpm_info[key] = p[key]
for key in optional_keys:
if key in p:
fpm_info[key] = p[key]
else:
fpm_info[key] = None
return fpm_info
|
3a6cdb8bbfe8f490f0986fa923c8205fad7c3a8a
| 233,668 |
def get_matrix_or_template_parameters(cli_args):
"""
cifti_conn_matrix and cifti_conn_template both have the same required
parameters, with only a few exceptions. This function returns a list of
all parameters required by both scripts.
:param cli_args: Full argparse namespace containing all CLI args, including
all necessary parameters for cifti_conn_matrix and cifti_conn_template.
:return: A list of all parameters required by matrix and template scripts.
"""
return([
cli_args.mre_dir,
cli_args.wb_command,
cli_args.series_file,
cli_args.time_series,
cli_args.motion,
cli_args.fd,
cli_args.tr,
cli_args.minutes,
cli_args.smoothing_kernel,
cli_args.left,
cli_args.right,
cli_args.beta8,
cli_args.remove_outliers,
cli_args.mask,
cli_args.make_conn_conc,
cli_args.output,
cli_args.dtseries
])
|
fbda701f988ebf490bfd33fa8d78d8bcc1dd109f
| 695,412 |
def calc_eccentricity(dist_list):
"""Calculate & return eccentricity from list of radii."""
apoapsis = max(dist_list)
periapsis = min(dist_list)
eccentricity = (apoapsis - periapsis) / (apoapsis + periapsis)
return eccentricity
|
3f4558251ad114efea206464b1b9a93983303979
| 509,610 |
def how_many_can_list(num_market_listings: int, number_to_sell: int, num_in_inventory: int) -> int:
"""
How many items I can actually list on market to have number_to_sell on sale
:param num_market_listings: Number of own listing on market.
:param number_to_sell: Max number on sale
:param num_in_inventory: Number in inventory
:return: number that can be listed
"""
if number_to_sell > num_market_listings:
toList = number_to_sell - num_market_listings
return min(toList, num_in_inventory)
elif number_to_sell == num_market_listings or number_to_sell < num_market_listings:
return 0
return 0
|
29a9844448ebd68710920b83378025ad9ffd74a3
| 22,338 |
import re
def AtConc_to_ZWeightPer(row):
"""Function to convert spent fuel inventory from nuclidewise atom concentration
to elementwise weight percentage.
The function expects a pandas row from the MVA dataset.
1, calculates the mass per cm3 for each isotope
2, changes the ZAID into elements and sums the mass of each element
3, returns the normalized mass (ie w%) for each element
Parameters
----------
row : pandas dataframe
Row in dataframe describing the fuel inventory
Returns
-------
masspervolume : dict
Dictionary which stores the mass percentage for each element (which are the keys).
"""
#precondition row into dictionary
inventory = row.to_dict()
inventory.pop('Unnamed: 0') #note this is highly specific
inventory.pop('BU')
inventory.pop('CT')
inventory.pop('IE')
inventory.pop('fuelType')
inventory.pop('TOT_SF')
inventory.pop('TOT_GSRC')
inventory.pop('TOT_A')
inventory.pop('TOT_H')
NA = 6.022140857E23
masspervolume = {}
for iso in inventory:
isoText = re.findall('\D+', iso)
isoNum = re.findall('\d+', iso)
Z=isoText[0]
A=float(isoNum[0])
massconci = A*((inventory[iso]*1e24)/NA) #this gives the mass of that isotope in g/cm3
if Z in masspervolume:
masspervolume[Z]=masspervolume[Z]+massconci
else:
masspervolume[Z]=massconci
#getting weight%
summass=sum(masspervolume.values())
for element in masspervolume:
masspervolume[element]=masspervolume[element]/summass
return masspervolume
|
49ed26f33d2f0c2a5e599143530cc082214e0b01
| 492,798 |
def get_first_duplicate_freq(changes: list):
"""Find the first duplicate frequency.
Args:
changes: frequency changes
Returns:
first duplicate frequency
"""
cur_freq = 0
visited_freqs = set()
while True:
for change in changes:
if cur_freq in visited_freqs:
return cur_freq
visited_freqs.add(cur_freq)
cur_freq += change
|
1111734849e383cad625744df0af3ade311e1b39
| 485,313 |
def arch_url(hostname, port, ext):
"""
Return the base url for a particular archiver service.
Parameters
----------
{hostname}
port : int
port on host that has the ext directory
ext : string
directory that hosts the desired service
"""
return "http://" + hostname + ":" + str(port) + ext
|
2c4930527461ab6da9ea0e1b0f52a763e13a8bf9
| 402,729 |
def get_img_size(n_fids):
"""Get guide image readout size from ``n_fids``.
This is the core definition for the default rule that OR's (with fids) get
6x6 and ER's (no fids) get 8x8. This might change in the future.
Parameters
----------
n_fids : int
Number of fids in the catalog
Returns
-------
int
Guide star image readout size to be used in a catalog (6 or 8)
"""
return 6 if n_fids > 0 else 8
|
83c5cefc456b6807c6c90b5deafd44c2a5f07886
| 142,917 |
def pip_cn(p, poly):
"""2D point inclusion: returns True if point is inside polygon (uses crossing number algorithm).
arguments:
p (numpy array, tuple or list of at least 2 floats): xy point to test for inclusion in polygon
poly (2D numpy array, tuple or list of tuples or lists of at least 2 floats): the xy points
defining a polygon
returns:
boolean: True if point is within the polygon
note:
if the polygon is represented by a closed resqpy Polyline, pass Polyline.coordinates as poly
"""
# p should be a tuple-like object with first two elements x, y
# poly should be a numpy array with first axis being the different vertices
# and the second starting x, y
crossings = 0
for edge in range(len(poly)):
v1 = poly[edge - 1]
v2 = poly[edge]
if ((v1[0] > p[0] or v2[0] > p[0]) and ((v1[1] <= p[1] and v2[1] > p[1]) or (v1[1] > p[1] and v2[1] <= p[1]))):
if v1[0] > p[0] and v2[0] > p[0]:
crossings += 1
elif p[0] < v1[0] + (v2[0] - v1[0]) * (p[1] - v1[1]) / (v2[1] - v1[1]):
crossings += 1
return bool(crossings & 1)
|
226c7f654e407c4148ec5eb99607a80119347f4e
| 483,104 |
from typing import List
import torch
def _flatten_zero_dim_tensor_optim_state(
state_name: str,
zero_dim_tensors: List[torch.Tensor],
unflat_param_names: List[str],
) -> torch.Tensor:
"""
Flattens the zero-dimension tensor optimizer state given by the values
``zero_dim_tensors`` for the state ``state_name`` for a single flattened
parameter corresponding to the unflattened parameter names
``unflat_param_names`` by enforcing that all tensors are the same and using
that common value.
NOTE: The requirement that the tensors are the same across all unflattened
parameters comprising the flattened parameter is needed to maintain the
invariant that FSDP performs the same computation as its non-sharded
equivalent. This means that none of the unflattened parameters can be
missing this state since imposing a value may differ from having no value.
For example, for Adam's "step", no value means maximum bias correction,
while having some positive value means less bias correction.
Args:
state_name (str): Optimizer state name.
zero_dim_tensors (List[torch.Tensor]): Zero-dimension optimizer state
for the unflattened parameters corresponding to the single
flattened parameter.
unflat_param_names (List[str]): A :class:`list` of unflattened
parameter names corresponding to the single flattened parameter.
Returns:
torch.Tensor: A zero-dimensional tensor giving the value of the state
``state_name`` for all unflattened parameters corresponding to the
names ``unflat_param_names``.
"""
non_none_tensors = [t for t in zero_dim_tensors if t is not None]
# Enforce that all have the same value and dtype
values_set = set(t.item() if t is not None else None for t in zero_dim_tensors)
dtypes = set(t.dtype if t is not None else None for t in zero_dim_tensors)
if len(non_none_tensors) != len(zero_dim_tensors) or \
len(values_set) != 1 or len(dtypes) != 1:
raise ValueError(
"All unflattened parameters comprising a single flattened "
"parameter must have scalar state with the same value and dtype "
f"but got values {values_set} and dtypes {dtypes} for state "
f"{state_name} and unflattened parameter names "
f"{unflat_param_names}"
)
value = next(iter(values_set))
dtype = next(iter(dtypes))
return torch.tensor(value, dtype=dtype, device=torch.device("cpu"))
|
6d7e4e6898d3e58b9120f3c0f0cb6fbe0525d1fe
| 330,688 |
def escape(literal):
"""
Escape the backtick in table/column name
@param literal: name string to escape
@type literal: string
@return: escaped string
@rtype : string
"""
return literal.replace('`', '``')
|
46adc116f533fa6ccfcfe12e86fe75f1f228cb22
| 133,834 |
def hauteur(arbre):
"""Fonction qui renvoie la hauteur d'un arbre binaire"""
# si l'arbre est vide
if arbre is None:
return 0
hg = hauteur(arbre.get_ag())
hd = hauteur(arbre.get_ad())
return max(hg, hd) + 1
|
64561b3c708f9e3afa30a4b405b0ce2e2de5c346
| 306,185 |
def _get_sort_and_permutation(lst: list):
"""
Sorts a list, returned the sorted list along with a permutation-index list which can be used for
cursored access to data which was indexed by the unsorted list. Nominally for chunking of CSR
matrices into TileDB which needs sorted string dimension-values for efficient fragmentation.
"""
# Example input: x=['E','A','C','D','B']
# e.g. [('E', 0), ('A', 1), ('C', 2), ('D', 3), ('B', 4)]
lst_and_indices = [(e, i) for i, e in enumerate(lst)]
# e.g. [('A', 1), ('B', 4), ('C', 2), ('D', 3), ('E', 0)]
lst_and_indices.sort(key=lambda pair: pair[0])
# e.g. ['A' 'B' 'C' 'D' 'E']
# and [1, 4, 2, 3, 0]
lst_sorted = [e for e, i in lst_and_indices]
permutation = [i for e, i in lst_and_indices]
return (lst_sorted, permutation)
|
16f3097697517911cdbd78cd70bcf383e1be4eca
| 110,694 |
def get_time_signature_code(number: int) -> str:
"""Return a string for a time signature number."""
if number > 10:
div, mod = divmod(number, 10)
return chr(57472 + div) + chr(57472 + mod)
return chr(57472 + number)
|
97e835f56a701f9250df9ab08a9859feb312d1a2
| 445,046 |
import re
def _dos2unix(file_content: bytes) -> bytes:
"""
Replace occurrences of Windows line terminator CR/LF with only LF.
:param file_content: the content of the file.
:return: the same content but with the line terminator
"""
return re.sub(b"\r\n", b"\n", file_content, flags=re.M)
|
7d7190c357ba25c28cdc8dd0df245d81273dae5e
| 272,175 |
def open_input(input_path: str) -> list[str]:
"""Opens and sanitizes the `input.txt` file for the day reading in each line as an element of a list.
- Remove any extra lines at the end of the input files (if present, due to auto-formatting)
- Remove newline characters for individual element strings
- Strip any whitespace
"""
with open(input_path, 'r') as f:
lines = f.readlines()
line_data = lines[:-1] if lines[-1] == '' else lines
data = [line_item.replace('\n', '').strip() for line_item in line_data]
return data
|
5b78f7d64d076bd1ed8b6ed1839aaaa45c48e001
| 628,547 |
def cyclic_linear_lr(
iteration: int,
num_iterations_cycle: int,
initial_lr: float,
final_lr: float,
) -> float:
"""
Linearly cycle learning rate
Args:
iteration: current iteration
num_iterations_cycle: number of iterations per cycle
initial_lr: learning rate to start cycle
final_lr: learning rate to end cycle
Returns:
float: learning rate
"""
cycle_iteration = int(iteration) % num_iterations_cycle
lr_multiplier = 1 - (cycle_iteration / float(num_iterations_cycle))
return initial_lr + (final_lr - initial_lr) * lr_multiplier
|
b55ef12d3050a20f0509ac54b914c0fabbb05e7d
| 188,586 |
import re
def camel_case_to_lower(name):
# type: (str) -> str
"""
Convert a string written in CamelCase to lower case, with underscores inserted before capitals.
:param name: CamelCase string
:return: camel_case string returned as lower case
"""
return re.sub("([^A-Z])([A-Z][A-Za-z]*)", r"\1_\2", name).lower()
|
ed260dd2f135a12f095c1bf3d38af392e4d3b2fd
| 396,908 |
def get_image_data(image):
"""
Return a mapping of Image-related data given an `image`.
"""
exclude = ["base_location", "extracted_to_location", "layers"]
image_data = {
key: value for key, value in image.to_dict().items() if key not in exclude
}
return image_data
|
684cd2a358599b161e2311f88c3e84c016ad2fef
| 21,558 |
def element_to_set_distance(v, s):
"""Returns shortest distance of some value to any element of a set."""
return min([abs(v-x) for x in s])
|
af77a125773312fd815cbad639b81601c427cf6b
| 37,338 |
def count_jailed(model):
"""Count number of jailed agents."""
count = 0
for agent in model.schedule.agents:
if agent.breed == "citizen" and agent.jail_sentence:
count += 1
return count
|
d6f7aca961917eebf40db11ab859511cf7c2606a
| 97,445 |
def time_of_flight(v0):
"""
Compute time in the air, given the initial vertical
velocity v0. Assume negligible air resistance.
"""
g = 9.81
return 2*v0/g
|
9c37c3960767255f4e165b0f57527de461b73bed
| 467,039 |
def tree_map(f, tr) :
"""
apply f recursively to all the tree nodes
"""
return (f(tr[0]), tuple([tree_map(f, x) for x in tr[1]]))
|
ec8c12b09cb4fedf61085802cd4d8b659e5903c5
| 61,260 |
def is_cidr_notation(netmask) -> bool:
"""
This function will check if the netmask is in CIDR format.
:param netmask: Can be a 255.255.255.255 or CIDR /24 format
:return bool: True if mask is in CIDR format
"""
return "." not in str(netmask)
|
088ba56ec6bc52f4e14affafa79ea7e426ccc77e
| 475,747 |
def _select_shorter_captions(captions, top_n):
"""
:param captions: a list of lists of string, such as [['a','b'],['c','d','e']]
:param top_n: an integer
:return: a list with top_n shortest length of the lists of string,
"""
assert top_n <= 10
lengths = [[x, len(y)] for x, y in enumerate(captions)]
# note: python3 works well, python2 unknown
lengths.sort(key=lambda elem: elem[1])
hit_elem = lengths[:top_n]
top_n_sentences = [captions[id_len[0]] for id_len in hit_elem]
return top_n_sentences
|
3ef0e0dc37d4efb963eb04d23d2171af8664c0fc
| 524,253 |
def _get_upstream_source(runtime, image_meta):
"""
Analyzes an image metadata to find the upstream URL and branch associated with its content.
:param runtime: The runtime object
:param image_meta: The metadata to inspect
:return: A tuple containing (url, branch) for the upstream source OR (None, None) if there
is no upstream source.
"""
if "git" in image_meta.config.content.source:
source_repo_url = image_meta.config.content.source.git.url
source_repo_branch = image_meta.config.content.source.git.branch.target
elif "alias" in image_meta.config.content.source:
alias = image_meta.config.content.source.alias
if alias not in runtime.group_config.sources:
raise IOError(f'Unable to find source alias {alias} for {image_meta.distgit_key}')
source_repo_url = runtime.group_config.sources[alias].url
source_repo_branch = runtime.group_config.sources[alias].branch.target
else:
# No upstream source, no PR to open
return None, None
return source_repo_url, source_repo_branch
|
1398d8515c4d4eb95241fa179b285553063dcf3b
| 524,557 |
def calc_max_quant_value(bits):
"""Calculate the maximum symmetric quantized value according to number of bits"""
return 2**(bits) - 1
|
0cd845c06aef8742cf62132b6569ed725fae4147
| 57,206 |
def soft_thresholding(v, threshold):
"""
soft thresholding function
:param v: scalar
:param threshold: positive scalar
:return: st(v)
"""
if v >= threshold:
return (v - threshold)
elif v <= - threshold:
return (v + threshold)
else:
return 0
|
64df33154368fd7701816231f88a8f92dfd201a4
| 480,853 |
import re
def get_browser_repo_url_from_git_url(git_url):
"""
Converts a git https or ssh url to a corresponding browser url
:param git_url: is the https or ssh git-clone format url
:return: https browser-friendly url to the repo site
"""
git_url = re.sub(r"\.git$", "", git_url)
if git_url.startswith("git@"):
return re.sub(r"^git@([^:]+):(.*)$", r"https://\1/\2", git_url)
elif git_url.startswith("https://"):
return re.sub(r"^https://([^@]+@)?(.*)$", r"https://\2", git_url)
return ""
|
12187906bb6acb7fef239f6a4bc52a955ce1fa41
| 143,303 |
import csv
def get_size_metrics(report_file, reader=None):
"""Get the size metrics from file."""
metrics = {}
with open(report_file, "r", newline="\n", encoding="utf-8") as csv_file:
csv_reader = reader or csv.DictReader(csv_file, delimiter=",")
for row in csv_reader:
language_metric = {
"files": row["files"],
"blank": row["blank"],
"comment": row["comment"],
"code": row["code"],
}
metrics[row["language"]] = language_metric
return metrics
|
65e31bee95d60da65c5091c16ef532dd76b72147
| 341,257 |
def memoize(fun):
"""Memoizes a function of one argument."""
the_dict = {}
def wrapper_decorator(*args, **kwargs):
assert len(args) == 1, "Only works with one argument"
if args[0] not in the_dict:
the_dict[args[0]] = fun(args[0])
return the_dict[args[0]]
return wrapper_decorator
|
722d6ed6048ad7275f7debfb88cb44da7b978e67
| 611,170 |
def get_tuned_params_dict(model, tuned_params_keys):
"""Given a list of tuned parameter keys and the model, create a dictionary with the tuned parameters and its values
associated with it.
Used for printing out scores
:param model: Model, such that we can extract the parameters from
:param tuned_params_keys: Parameters that we tuned in RandomizedSearchCV
:return: Dictionary with tuned parameters and its values
"""
values = [model.get_params()[x] for x in tuned_params_keys]
return dict(zip(tuned_params_keys, values))
|
11993cd01106b654aaf30f56be1ee2269b97759e
| 531,516 |
def explode_hyperedge(hyperedge, hyperedge_id):
"""
Takes a hyperedge set, and generates all the dyadic connections for a similar regular edge.
:param hyperedge: (list) List of participating terms.
:param hyperedge_id: (int) Identifier for the hyperedge, used for postgres.
:return: (list) List of connection tuples
"""
# We'll sort, so we have a clear idea of how many of the same edge we have, since it will always be
# of the form (smaller_id, larger_id).
hyperedge = sorted(hyperedge)
edge_set = []
postgres_set = []
# essentially build connections to all "vertices after". This guarantees we don't do edges twice.
for i, _ in enumerate(hyperedge):
for j in range(i+1, len(hyperedge)):
edge_set.append((hyperedge[i], hyperedge[j]))
# postgres performs better with duplicate edges, so we manually correct this here
postgres_set.append((hyperedge_id, hyperedge[i], hyperedge[j]))
postgres_set.append((hyperedge_id, hyperedge[j], hyperedge[i]))
return edge_set, postgres_set
|
f584c1d3b86582787651825f58211b0237949cf0
| 569,335 |
def add_dummy_data(bitmap, width, height):
"""
Adds dummy data to a bitmap to ensure the width is divisible by 4.
This is required because the SSD1322 OLED driver maintains a single column
address for four pixels.
bitmap (list): A list of integers (pixel values)
width (int): The width of the bitmap
height (int): The height of the bitmap
Returns (tuple): A tuple which contains modified image data.
|
|--> bitmap_data (tuple)
| |--> bitmap pixel array (list)
| |--> bitmap width (int)
| \--> bitmap height (int)
|
\--> dummy_to_add (int): Columns of dummy data added
"""
output = []
bitmap_data = tuple()
# Maximum dummy data should be 3
dummy_to_add = (4 - (width % 4)) % 4
new_width = width + dummy_to_add
if dummy_to_add > 0:
index = 0
for i in range(height):
for j in range(new_width):
# Add dummy data beyond original width
if j > (width - 1):
output.append(0)
else:
output.append(bitmap[index])
index += 1
bitmap_data = (output, new_width, height)
else:
bitmap_data = (bitmap, width, height)
return (bitmap_data, dummy_to_add)
|
5739330189d504b69af6740a5d85692beb6dbe3a
| 491,668 |
def polygon_jaccard(final_polygons, train_polygons):
"""
Calcualte the jaccard index of two polygons, based on data type of
shapely.geometry.MultiPolygon
:param final_polygons:
:param train_polygons:
:return:
"""
return final_polygons.intersection(train_polygons).area /\
final_polygons.union(train_polygons).area
|
55a3a65c274dd203a2f021bd90b5520fbe82b596
| 463,057 |
def consecutive_seconds(rel_seconds, window_size_sec, stride_sec=1):
"""
Return a list of all the possible [window_start, window_end] pairs
containing consecutive seconds of length window_size_sec inside.
Args:
rel_seconds: a list of qualified seconds
window_size_sec: int
stride_sec: int
Returns:
win_start_end: a list of all the possible [window_start, window_end] pairs.
Test:
>>> rel_seconds = [2,3,4,5,6,7,9,10,11,12,16,17,18]; window_size_sec = 3; stride_sec = 1
>>> print(consecutive_seconds(rel_seconds, window_size_sec))
>>> [[2, 4], [3, 5], [4, 6], [5, 7], [9, 11], [10, 12], [16, 18]]
"""
win_start_end = []
for i in range(0, len(rel_seconds) - window_size_sec + 1, stride_sec):
if rel_seconds[i + window_size_sec - 1] - rel_seconds[i] == window_size_sec - 1:
win_start_end.append([rel_seconds[i], rel_seconds[i + window_size_sec - 1]])
return win_start_end
|
e9c4d0fe5d8823530c372b35ef16b6a2e762e606
| 220,491 |
from functools import reduce
def getAllTextWords(texts):
""" Returns a set of all the words in the given texts """
return reduce(lambda x,y: x | set(y), texts.values(), set())
|
52e475b180031b0abf67bad3fe148b9509baaed1
| 34,375 |
def convert_to_demisto_severity(dg_severity: str) -> int:
"""
Convert dg_severity to demisto severity
:param dg_severity:
:return: int demisto severity
"""
severity_map = {
'Critical': 4,
'High': 3,
'Medium': 2,
}
return severity_map.get(dg_severity, 1)
|
fbaa86e2697d804a3547a58e4041e5b41c573a36
| 603,946 |
def v3_multimax(iterable):
"""Return a list of all maximum values.
Bonus 1: make sure our function returned an empty list when
given an empty iterable.
"""
max_item = None
for item in iterable:
if max_item is None or item > max_item:
max_item = item
return [
item
for item in iterable
if item == max_item
]
|
9ba3d17c510406ea85ab6f1d1806446165db0610
| 109,692 |
def mastinEVEM(HT, DRE = 2500):
"""Calculating erupted volume based on plume height.
Inputs: Plume height (HT) in km
DRE = dense-rock equivalent (kg/m^3)
Outputs: Eruptive Volume (km^3 DRE) and Eruptive Mass (kg)
No time component to this??
Equation from Mastin et al. 2009: H = 25.9 + 6.64log(V) --> log base 10"""
p = (HT - 25.9)/6.64
EV = 10**p
EM = EV * DRE * (1000**3)
return EV, EM
|
a869927ef8ad6ad3540842c1990214add2adce0c
| 435,506 |
import math
def _get_qv(snpcount, length):
""" Get accuracy based on snps comparison to reference
Args:
snpcount: Number of snps
length: Number of nucleotides in fasta reference
Returns:
quality_value: A Phred Quality Score
"""
if snpcount != 0:
quality_value = round(
-10 * math.log10(int(snpcount) / float(length)), 3)
# if there are 0 snps, it means the query perfectly matches the reference
else:
quality_value = round(-10 * math.log10(1 / float(length)), 3)
return quality_value
|
61fa6d19512527443c1347b600f78845b759e9f4
| 358,771 |
def query_prefix_transform(query_term):
"""str -> (str, bool)
return (query-term, is-prefix) tuple
"""
is_prefix = query_term.endswith('*')
query_term = query_term[:-1] if is_prefix else query_term
return (query_term, is_prefix)
|
d33dd4222f53cba471be349b61e969838f6188d5
| 29,486 |
import asyncio
async def readexactly_or_exc(reader, n, timeout = None):
"""
Helper function to read exactly N amount of data from the wire.
:param reader: The reader object
:type reader: asyncio.StreamReader
:param n: The maximum amount of bytes to read.
:type n: int
:param timeout: Time in seconds to wait for the reader to return data
:type timeout: int
:return: bytearray
"""
temp = await asyncio.gather(*[asyncio.wait_for(reader.readexactly(n), timeout = timeout)], return_exceptions=True)
if isinstance(temp[0], bytes):
return temp[0]
else:
raise temp[0]
|
25cac7a98e9cf2aefcc33c43de599a342779e32c
| 400,676 |
def nested_getattr(baseobject, attribute):
""" Returns the value of an attribute of an object that is nested
several layers deep.
Parameters
----------
baseobject : this seriously can be anything
The top-level object
attribute : string
Any string of what you want.
Returns
-------
output : object
No telling what type it is. It depends on what you ask for.
Examples
--------
>>> class Level_1:
... a = 1
>>> class Level_2:
... b = Level_1()
>>> x = Level_2()
>>> nested_getattr(x, 'b.a')
1
"""
for attr in attribute.split("."):
baseobject = getattr(baseobject, attr)
return baseobject
|
33711d06982dc7de0d6ba3ef5581f1cd59ced8a3
| 481,473 |
def count_of(thing_list, thing_name, plural_name=None, colon=False):
"""Return a string representing a count of things, given in thing_list.
Example:
>>> count_of([1, 2, 3], 'number')
'3 numbers'
>>> count_of([1], 'number')
'1 number'
>>> count_of(['salmon', 'carp'], 'fish', 'fishies')
'2 fishies'
"""
if plural_name is None:
plural_name = thing_name + 's'
format = '%d ' + (thing_name if len(thing_list) == 1 else plural_name)
if colon:
format += ':'
return format % len(thing_list)
|
7d63bf3c324cd58e9e1812debce31043b1389f30
| 237,433 |
def _tester(func, *args):
"""
Tests function ``func`` on arguments and returns first positive.
>>> _tester(lambda x: x%3 == 0, 1, 2, 3, 4, 5, 6)
3
>>> _tester(lambda x: x%3 == 0, 1, 2)
None
:param func: function(arg)->boolean
:param args: other arguments
:return: something or none
"""
for arg in args:
if arg is not None and func(arg):
return arg
return None
|
035c8bf68b4ff7e4fbdb7ed1b2601f04110287d8
| 708,787 |
def mock_upsert_profile(mocker):
"""Mock of upsert_profile function"""
return mocker.patch("channels.api.search_task_helpers.upsert_profile")
|
a5f93200e923f455409fc0e9e444ba4508c16c85
| 297,571 |
import struct
import socket
def inet_atoni(ip):
"""Like inet_aton() but returns an integer."""
return struct.unpack('>I', socket.inet_aton(ip))[0]
|
3bd18b7aecf9a5a45033c7873163ee1387cb8a13
| 704,692 |
import re
def camel_case_to_pep_8(attribute_name: str) -> str:
"""
Converts a camel case name to PEP 8 standard
Parameters
----------
attribute_name : str
The camel case attribute name
Returns
-------
str
The PEP 8 formatted attribute name
"""
matches = re.finditer(
".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", attribute_name
)
return "_".join([m.group(0)[0].lower() + m.group(0)[1:] for m in matches])
|
e2ddb49b1f1f74cbf0cf99206281c93c1d38815e
| 468,723 |
def locMcmcName(xspecFile):
"""A function to find the name of the mcmc fits file you have defined in you XSPEC .xcm file,
if it's there.
Parameters
----------
xspecFile : str
The XSPEC .xcm file that has the "writefits" command used in it.
Returns
-------
The mcmc fits path+file name from the .xcm file.
Example
-------
# to get mcmc fits path+file name from the .xcm file
fitsFile = loc8fitsAndTxtName("apec1fit_fpm1_cstat.xcm")
"""
with open(xspecFile, "r") as lf:
for line in lf.readlines():
if line.startswith("chain run"):
# get the path and mcmc file name for the "chain run" line
return line.split()[-1]
return ""
|
07b65d3b292ff03484f43c44d8f84f644e0e04f1
| 274,245 |
import re
def parse_component(comp):
"""Parse "10 ORE" -> (10, 'ORE')."""
m = re.match(r'(\d+) ([A-Z]+)$', comp)
assert m, comp
amt, what = m.groups()
return int(amt), what
|
df17c10c37ce0ed9e096d8954b1cef9b19730443
| 623,744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.