content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def dont_linkify_urls(attrs, new=False):
"""Prevent file extensions to convert to links.
This is a callback function used by bleach.linkify().
Prevent strings ending with substrings in `file_exts` to be
converted to links unless it starts with http or https.
"""
file_exts = ('.py', '.md', '.sh')
txt = attrs['_text']
if txt.startswith(('http://', 'https://')):
return attrs
if txt.endswith(file_exts):
return None
return attrs | e0ab3b0a004a2f6a3adca9ca24f0c33c6fc34d3a | 658,610 |
def find_pareto_front(population):
"""Finds a subset of nondominated individuals in a given list
:param population: a list of individuals
:return: a set of indices corresponding to nondominated individuals
"""
pareto_front = set(range(len(population)))
for i in range(len(population)):
if i not in pareto_front:
continue
ind1 = population[i]
for j in range(i + 1, len(population)):
ind2 = population[j]
# if individuals are equal on all objectives, mark one of them (the first encountered one) as dominated
# to prevent excessive growth of the Pareto front
if ind2.fitness.dominates(ind1.fitness) or ind1.fitness == ind2.fitness:
pareto_front.discard(i)
if ind1.fitness.dominates(ind2.fitness):
pareto_front.discard(j)
return pareto_front | 2e53edda5e3d3afd541cedff3bb3d247f913969c | 697,316 |
from pathlib import Path
import string
import random
def make_random_dir_path() -> Path:
""" Creates a fully-qualified Path to a fake directory. The directory path is
guarantee to begin with / and starts with no special characters other than /.
The branch_depth of the path (ie /one/two/three has a depth of 3) is random and
lies between 2 and 10 inclusive. Each node in the branch has between 1 and 10
characters, which comprise upper- and lower-case characters and numbers. """
characters = string.ascii_letters + string.digits
branch_depth = random.randint(2, 10)
dirs = []
for _ in range(branch_depth):
string_length = random.randint(1, 10)
random_string = ''.join(random.choice(characters) for _ in range(string_length))
dirs.append(random_string)
dir_str = '/' + '/'.join(dirs)
return Path(dir_str) | adea6a44228e4c6781f10334f0a62c32c5f29d6f | 185,172 |
import torch
def load_model(filename, model):
"""Load the model parameters in {filename}."""
model_params = torch.load(str(filename))
model.load_state_dict(model_params)
return model | 14cb058d61dedc1ad4b41b0aab09a4ce56db37a1 | 673,612 |
def aliquot_sum(input_num: int) -> int:
"""
Finds the aliquot sum of an input integer, where the
aliquot sum of a number n is defined as the sum of all
natural numbers less than n that divide n evenly. For
example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is
a simple O(n) implementation.
@param input_num: a positive integer whose aliquot sum is to be found
@return: the aliquot sum of input_num, if input_num is positive.
Otherwise, raise a ValueError
Wikipedia Explanation: https://en.wikipedia.org/wiki/Aliquot_sum
>>> aliquot_sum(15)
9
>>> aliquot_sum(6)
6
>>> aliquot_sum(-1)
Traceback (most recent call last):
...
ValueError: Input must be positive
>>> aliquot_sum(0)
Traceback (most recent call last):
...
ValueError: Input must be positive
>>> aliquot_sum(1.6)
Traceback (most recent call last):
...
ValueError: Input must be an integer
>>> aliquot_sum(12)
16
>>> aliquot_sum(1)
0
>>> aliquot_sum(19)
1
"""
if not isinstance(input_num, int):
raise ValueError("Input must be an integer")
if input_num <= 0:
raise ValueError("Input must be positive")
return sum(
divisor for divisor in range(1, input_num // 2 + 1) if input_num % divisor == 0
) | d7839f10d54c44f61525835d2947b09780666b4f | 323,265 |
async def convert_media_format(media_format):
"""Translates media format names into norwegian"""
media_formats = {
'TV': 'TV-Serie',
'TV_SHORT': 'Kort TV-Serie',
'MOVIE': 'Film',
'SPECIAL': 'Ekstramateriale',
'MUSIC': 'Musikk',
'MANGA': 'Manga',
'NOVEL': 'Novelle',
'ONE_SHOT': 'Kort Manga'
}
try:
return media_formats[media_format]
except KeyError:
return media_format | bd338c984baf9fa46f2f427c8965ff2331198a76 | 576,926 |
def wrap(x, m):
"""
Mathematical modulo; wraps x so that 0 <= wrap(x,m) < m. x can be negative.
"""
return (x % m + m) % m | 7cd3b2e5f2edcd09f093cf29f9dc09e3eb97e2ed | 485,919 |
import json
def fluent_list_output(value):
"""
Return stored json representation as a multilingual dict, if
value is already a dict just pass it through.
"""
if isinstance(value, dict):
return value
try:
result = json.loads(value)
return {k: v if isinstance(v, list) else [v] for k, v in list(result.items())}
except ValueError:
# plain string in the db, return as is so it can be migrated
return value | 1155137a37237e41066c95910e30f2d5a18c467c | 553,413 |
import requests
def is_license_valid(key):
"""Checking License Key from External API
Args:
key (str): Serial Key for Raven Restocks
Returns:
bool: If the key is valid
"""
r = requests.post(
'https://xserver.boxmarshall.com/api/v2/authorize/validate/no-device', json={"serialkey": key})
return r.json()['success'] | d42e9be643380a095d361d5e668c923218996e0a | 281,420 |
def write_alarm_msg(radar_name, param_name_unit, date_last, target, tol_abs,
np_trend, value_trend, tol_trend, nevents, np_last,
value_last, fname):
"""
writes an alarm file
Parameters
----------
radar_name : str
Name of the radar being controlled
param_name_unit : str
Parameter and units
date_last : datetime object
date of the current event
target, tol_abs : float
Target value and tolerance
np_trend : int
Total number of points in trend
value_trend, tol_trend : float
Trend value and tolerance
nevents: int
Number of events in trend
np_last : int
Number of points in the current event
value_last : float
Value of the current event
fname : str
Name of file where to store the alarm information
Returns
-------
fname : str
the name of the file where data has written
"""
with open(fname, 'w', newline='') as txtfile:
txtfile.write(
'Weather radar polarimetric parameters monitoring alarm\n')
if radar_name is not None:
txtfile.write('Radar name: '+radar_name+'\n')
txtfile.write('Parameter [Unit]: '+param_name_unit+'\n')
txtfile.write('Date : '+date_last.strftime('%Y%m%d')+'\n')
txtfile.write('Target value: '+str(target)+' +/- '+str(tol_abs)+'\n')
if np_trend > 0:
txtfile.write(
'Number of points in trend: '+str(np_trend)+' in ' +
str(nevents)+' events\n')
txtfile.write(
'Trend value: '+str(value_trend)+' (tolerance: +/- ' +
str(tol_trend)+')\n')
else:
txtfile.write('Number of points in trend: NA\n')
txtfile.write('Trend value: NA\n')
txtfile.write('Number of points: '+str(np_last)+'\n')
txtfile.write('Value: '+str(value_last)+'\n')
txtfile.close()
return fname | f734983e1aa59cb9c17a2e3988d870625f9aee3d | 101,983 |
def get_contents(collection_id, collections_referenced):
"""Return the ``contents`` value of the collection with ``collection_id`` as its ``id`` value.
:param int collection_id: the ``id`` value of a collection model.
:param dict collections_referenced: the collections (recursively) referenced by a collection.
:returns: the contents of a collection, or a warning message.
"""
return getattr(collections_referenced[collection_id],
u'contents',
u'Collection %d has no contents.' % collection_id) | 9d5db9a2b4338a1bd6ba311361018a73bae386bb | 353,917 |
def _ifOnlyWalk(row):
"""Helper funtion to return True if row only contains Walk mode."""
modes = set(row.split(","))
walkExist = "Mode::Walk" in modes
length = len(modes) == 1
return walkExist & length | 61fa0c853936dd53dd8981aa25f63a3a2488565b | 565,233 |
def add_header(response):
"""
Append after request the nessesary headers.
"""
response.headers['Access-Control-Allow-Headers'] = "accept, content-type"
return response | 0d8367134570e39838c5af060186f74a841eda9f | 209,649 |
def sz_to_ind(sz, charge, nsingle):
"""
Converts :math:`S_{z}` to a list index.
Parameters
----------
sz : int
Value :math:`S_{z}` of a spin projection in the z direction.
charge : int
Value of the charge.
nsingle : int
Number of single particle states.
Returns
-------
int
Value of the list index corresponding to sz.
"""
szmax = min(charge, nsingle-charge)
return int((szmax+sz)/2) | c6016a5f21f4a4e9904046260b94b1f4d6d397ba | 49,391 |
def load_file(infile):
"""Read and return text file as a string of lowercase characters."""
with open(infile) as f:
loaded_string = f.read().lower()
return loaded_string | 0a78a660ddabc897f1c8344c4588e59700687f09 | 613,671 |
def get_inputs(depthdata_str_list):
"""
Given a list of strings composed of 3 floating pt nbrs x, y, z separated by commas,
convert them to floats and return them as 3 individual lists.
:param depthdata_str_list: list of floating point string pairs, separated by a comma (think .csv file)
:return: lists of x values, y values, and corresponding z values
"""
assert isinstance(depthdata_str_list, list)
assert all([isinstance(s, str) for s in depthdata_str_list])
assert all([3 == len(v.split(",")) for v in depthdata_str_list])
x_list = []
y_list = []
z_list = []
for i, line_str in enumerate(depthdata_str_list):
str_list = line_str.split(",")
x_str, y_str, z_str = str_list
x = float(x_str)
y = float(y_str)
z = float(z_str)
x_list.append(x)
y_list.append(y)
z_list.append(z)
return x_list, y_list, z_list | 397937ca85dbd2836582ef37ae193f9929b79ab0 | 678,755 |
def _user_can_edit(user, group_profile):
"""Can the given user edit the given group profile?"""
return user.has_perm("groups.change_groupprofile") or user in group_profile.leaders.all() | 9ebcea9592b821fe3ec3a25186204342c119815c | 105,157 |
def _set_default_capacitance(
subcategory_id: int,
style_id: int,
) -> float:
"""Set the default value of the capacitance.
:param subcategory_id:
:param style_id:
:return: _capacitance
:rtype: float
:raises: KeyError if passed a subcategory ID outside the bounds.
:raises: IndexError if passed a style ID outside the bounds when subcategory ID
is equal to three.
"""
_capacitance = {
1: 0.15e-6,
2: 0.061e-6,
3: [0.027e-6, 0.033e-6],
4: 0.14e-6,
5: 0.33e-6,
6: 0.14e-6,
7: 300e-12,
8: 160e-12,
9: 30e-12,
10: 3300e-12,
11: 81e-12,
12: 1e-6,
13: 20e-6,
14: 1700e-6,
15: 1600e-6,
16: 0.0,
17: 0.0,
18: 0.0,
19: 0.0,
}[subcategory_id]
if subcategory_id == 3:
_capacitance = _capacitance[style_id - 1]
return _capacitance | 2b016bf2a8f4006fcff6c6b081037a0ff589f0de | 205,251 |
def test_file(test_dir):
"""
Returns path to the file with `filename` and `content` at `test_dir`.
"""
def wrapper(filename: str, content: str):
file = test_dir / filename
file.write_text(content, encoding="utf-8")
return file
return wrapper | e4e9d500ba7c5227add47833bdc8d3be3a8d4252 | 45,447 |
def obj_name(obj, oid):
"""Return name of folder/collection object based on id
Args: obj - dict
oid - string
"""
return obj[oid]['name'] | 8ae962c271e89fb034221432cae461b8f6500b72 | 360,320 |
def CompressList(lines, max_length, middle_replacement):
"""Ensures that |lines| is no longer than |max_length|. If |lines| need to
be compressed then the middle items are replaced by |middle_replacement|.
"""
if len(lines) <= max_length:
return lines
remove_from_start = max_length / 2
return (lines[:remove_from_start] +
[middle_replacement] +
lines[len(lines) - (max_length - remove_from_start):]) | 4ef04859c70a71055272a28e6634cdb3e4d269e4 | 302,624 |
def avgCl(lst):
"""return the average RGB of a RGB list"""
c1=c2=c3=0
n = len(lst)
for c in lst:
c1+=c[0]
c2+=c[1]
c3+=c[2]
c1,c2,c3=c1/n,c2/n,c3/n
return [c1,c2,c3] | 289728e3870adf7affe0d76001b46333428edd2f | 117,387 |
def gist_namer(art_title, num):
"""
Create formatted gist name to help with grouping gists
Parameters
----------
art_title : str
defaults to the notebook name
num: int
gist count for this article e.g. first gist of article is 0
"""
# lower case and snake_case the whole thing
title = art_title.lower().replace(" ", "_")
title += str(num)
return title | 5b7cff7b91b291870e9e8d913875af14e44f3c08 | 169,297 |
def retag_from_strings(string_tag) :
"""
Returns only the final node tag
"""
valure = string_tag.rfind('+')
if valure!= -1 :
tag_recal =string_tag [valure+1:]
else :
tag_recal = string_tag
return tag_recal | 5bef884498efb19eb354bb6119450c9c25a19e1c | 700,817 |
def removesuffix(s, suffix):
"""
Removes suffix a string
:param s: string to remove suffix from
:param suffix: suffix to remove
:type s: str
:type suffix: str
:return: a copy of the string with the suffix removed
:rtype: str
"""
return s if not s.endswith(suffix) else s[:-len(suffix)] | 7503e7ca390434936cdda8f706f5ca1eb7b80b98 | 24,437 |
def st_rowfreq(row,srate,length):
"""
for a row in a stockwell transform, give what frequency (Hz)
it corresponds to, given the sampling rate srate and the length of the original
array
"""
return row*srate/length | 283405aa5c3ae96d96a98b84e0533d5f78f4eef3 | 310,507 |
def convert_labels(df, columns=['label'], reverse=False):
""" Convert labels in provided columns to numeric values (or back to text). Edits the dataframe in place. """
if reverse:
labels_vals = {
0: 'Refuted',
1: 'Supported',
2: 'NotEnoughInfo'
}
else:
labels_vals = {
'Refuted': 0,
'Supported': 1,
'NotEnoughInfo': 2
}
for col in columns:
df[col] = df[col].apply(lambda x: labels_vals[x])
return df | 155e7171811dd4d9c1b819affb4ee7a23b56b5c9 | 85,115 |
def select_bboxes_via_score(bboxes_list, scores_list, score_thr):
"""Select bboxes with scores >= score_thr.
Args:
bboxes_list (list[ndarray]): List of bboxes. Each element is ndarray of
shape (n,8)
scores_list (list(list[float])): List of lists of scores.
score_thr (float): The score threshold to filter out bboxes.
Returns:
selected_bboxes (list[ndarray]): List of bboxes. Each element is
ndarray of shape (m,8) with m<=n.
"""
assert isinstance(bboxes_list, list)
assert isinstance(scores_list, list)
assert isinstance(score_thr, float)
assert len(bboxes_list) == len(scores_list)
assert 0 <= score_thr <= 1
selected_bboxes = []
for bboxes, scores in zip(bboxes_list, scores_list):
if len(scores) > 0:
assert len(scores) == bboxes.shape[0]
inds = [
iter for iter in range(len(scores))
if scores[iter] >= score_thr
]
selected_bboxes.append(bboxes[inds, :])
else:
selected_bboxes.append(bboxes)
return selected_bboxes | e3bd82706cb79b0385d1a7c5cc45e0a6637ec841 | 331,144 |
def fetch_all_views(eng):
"""
Finds all views.
"""
tables = eng.execute("SELECT table_name from information_schema.views;")
return [table[0] for table in tables if "exp_view_table" in table[0]] | 583abe6efe1c42c27daaf6fbc5b44c4b276e1ded | 124,352 |
def add_argument(parser, flag, type=None, **kwargs):
"""Wrapper to add arguments to an argument parser. Fixes argparse's
behavior with type=bool. For a bool flag 'test', this adds options '--test'
which by default sets test to on, and additionally supports '--test true',
'--test false' and so on. Finally, 'test' can also be turned off by simply
specifying '--notest'.
"""
def str2bool(v):
return v.lower() in ('true', 't', '1')
if flag.startswith('-'):
raise ValueError('Flags should not have the preceeding - symbols, -- will be added automatically.')
if type == bool:
parser.add_argument('--' + flag, type=str2bool, nargs='?', const=True, **kwargs)
parser.add_argument('--no' + flag, action='store_false', dest=flag)
else:
parser.add_argument('--' + flag, type=type, **kwargs) | d802615f737c806be97962f18fdd7e8057512f96 | 15,239 |
def elevation(location):
"""Return the elevation field of a location."""
return location[2] | 6509a4f7d59d56a94f7c9e8b199a3911c33c72bc | 302,052 |
import math
def distance(M, node_1, node_2):
"""Computes the Euclidean L2 Distance."""
x1, y1 = M.intersections[node_1]
x2, y2 = M.intersections[node_2]
return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) | c4b8cc9d5c352d6a4399926c4495c3cb072ad876 | 508,210 |
def audit_renamed_col_dict(dct: dict) -> dict:
"""
Description
-----------
Handle edge cases where a col could be renamed back to itself.
example: no primary_geo, but country is present. Because it is a protected
col name, it would be renamed country_non_primary. Later, it would be set
as primary_geo country, and the pair added to renamed_col_dict again:
{'country_non_primary' : ['country'], "country": ['country_non_primary'] }
Parameters
----------
dct: dict
renamed_col_dict of key: new column name, value: list of old columns
Output
------
dict:
The modified parameter dict.
"""
remove_these = set()
for k, v in dct.items():
vstr = "".join(v)
if vstr in dct.keys() and [k] in dct.values():
remove_these.add(vstr)
remove_these.add(k)
for k in remove_these:
dct.pop(k, None)
return dct | 5f70bbce182e3cccbe22d13975f02b941c01c090 | 233,738 |
def _mangle(cls, name):
"""
Given a class and a name, apply python name mangling to it
:param cls: Class to mangle with
:param name: Name to mangle
:return: Mangled name
"""
return f"_{cls.__name__}__{name}" | 8b789a03b2f25c71bc661cc1eb394650087128b9 | 40,397 |
import torch
def sample_pdf(
bins: torch.Tensor,
weights: torch.Tensor,
N_samples: int,
det: bool = False,
eps: float = 1e-5,
):
"""
Samples a probability density functions defined by bin edges `bins` and
the non-negative per-bin probabilities `weights`.
Note: This is a direct conversion of the TensorFlow function from the original
release [1] to PyTorch.
Args:
bins: Tensor of shape `(..., n_bins+1)` denoting the edges of the sampling bins.
weights: Tensor of shape `(..., n_bins)` containing non-negative numbers
representing the probability of sampling the corresponding bin.
N_samples: The number of samples to draw from each set of bins.
det: If `False`, the sampling is random. `True` yields deterministic
uniformly-spaced sampling from the inverse cumulative density function.
eps: A constant preventing division by zero in case empty bins are present.
Returns:
samples: Tensor of shape `(..., N_samples)` containing `N_samples` samples
drawn from each set probability distribution.
Refs:
[1] https://github.com/bmild/nerf/blob/55d8b00244d7b5178f4d003526ab6667683c9da9/run_nerf_helpers.py#L183 # noqa E501
"""
# Get pdf
weights = weights + eps # prevent nans
pdf = weights / weights.sum(dim=-1, keepdim=True)
cdf = torch.cumsum(pdf, -1)
cdf = torch.cat([torch.zeros_like(cdf[..., :1]), cdf], -1)
# Take uniform samples
if det:
u = torch.linspace(0.0, 1.0, N_samples, device=cdf.device, dtype=cdf.dtype)
u = u.expand(list(cdf.shape[:-1]) + [N_samples]).contiguous()
else:
u = torch.rand(
list(cdf.shape[:-1]) + [N_samples], device=cdf.device, dtype=cdf.dtype
)
# Invert CDF
inds = torch.searchsorted(cdf, u, right=True)
below = (inds - 1).clamp(0)
above = inds.clamp(max=cdf.shape[-1] - 1)
inds_g = torch.stack([below, above], -1).view(
*below.shape[:-1], below.shape[-1] * 2
)
cdf_g = torch.gather(cdf, -1, inds_g).view(*below.shape, 2)
bins_g = torch.gather(bins, -1, inds_g).view(*below.shape, 2)
denom = cdf_g[..., 1] - cdf_g[..., 0]
denom = torch.where(denom < eps, torch.ones_like(denom), denom)
t = (u - cdf_g[..., 0]) / denom
samples = bins_g[..., 0] + t * (bins_g[..., 1] - bins_g[..., 0])
return samples | 8d706ef5952a3c4ff5081a04d22f2e5fd4b2045b | 680,607 |
def insert_user(cursor,username,hash_pw):
"""
Insert a new user in the database
Parameters:
-----------
cursor: Psycopg2 cursor
Cursor of type RealDict in the postgres database
username : Str
name of the user
hash_pw : Str
encrypted password of the user (to be tested against the encrypted password)
Returns:
--------
id : Int
identifier of the inserted user
"""
SQL = "INSERT INTO users(username, password_hash) VALUES(%s,%s) RETURNING id"
cursor.execute(SQL,[username,hash_pw])
res = cursor.fetchone()['id']
return res | 0fe9f192bf50e95392ffa0fb5d6e2bf42d5bd627 | 329,243 |
def rectanglesOverlap(r1, r2):
"""Check whether r1 and r2 overlap."""
if ((r1[0] >= r2[0] + r2[2]) or (r1[0] + r1[2] <= r2[0])
or (r1[1] + r1[3] <= r2[1]) or (r1[1] >= r2[1] + r2[3])):
return False
else:
return True | bf1022196956dd01694084c65ba54a7b597b0fd0 | 100,527 |
def select_shape(input_shape, slice_point, axis=1):
""" calculate the output shape of this layer using input shape
Args:
@input_shape (list of num): a list of number which represents the input shape
@slice_point (list): parameter from caffe's Slice layer
@axis (int): parameter from caffe's Slice layer
Returns:
@output_shape (list of num): a list of numbers represent the output shape
"""
input_shape = list(input_shape)
start = slice_point[0]
if len(slice_point) == 2:
end = slice_point[1]
else:
end = input_shape[axis]
assert end > start, "invalid slice_point with [start:%d, end:%d]"\
% (start, end)
output_shape = input_shape
output_shape[axis] = end - start
return output_shape | ba468d2a7d7f52055082d9ae34ea2dac41d9802e | 204,278 |
def _dtype_descr(dtype):
"""
Get a string that describes a numpy datatype.
:param dtype: The numpy datatype.
:return: A string describing the type.
"""
if dtype.kind == 'V':
return dtype.descr
else:
return dtype.char | 690c98fdd787313317182c647e64ccb8784ca9ad | 136,754 |
from typing import Dict
def parse_guid(guid: str) -> Dict[str, int]:
"""
Parse a guid back to its four constituents
Args:
guid: a valid guid str
Returns:
A dict with keys 'location', 'work_station', 'sample', and 'time'
as integer values
"""
guid = guid.replace('-', '')
components = {}
components['sample'] = int(guid[:8], base=16)
components['location'] = int(guid[8:10], base=16)
components['work_station'] = int(guid[10:16], base=16)
components['time'] = int(guid[16:], base=16)
return components | b76994b2da80b750fb09e33bda6ac4a05dd9d1b1 | 615,627 |
def GetInputs(var, env):
"""Expands an env substitution variable and returns it as a list of
strings."""
return [str(v) for v in env.subst_list(var)[0]] | ee0deb1c4f25d732fcb93c2dd96f3bb162fefcbf | 456,751 |
def parse_gage(s):
"""Parse a streamgage key-value pair.
Parse a streamgage key-value pair, separated by '='; that's the reverse of ShellArgs.
On the command line (argparse) a declaration will typically look like::
foo=hello or foo="hello world"
:param s: str
:rtype: tuple(key, value)
"""
# Adapted from: https://gist.github.com/fralau/061a4f6c13251367ef1d9a9a99fb3e8d
items = s.split('=')
key = items[0].strip() # we remove blanks around keys, as is logical
value = ''
if len(items) > 1:
# rejoin the rest:
value = '='.join(items[1:])
return key, value | 299b47f3a4757c924620bdc05e74f195a4cb7967 | 709,261 |
def last_support(entry):
"""Find the last friendly action between the players"""
seasons = entry['seasons']
last_support = None
for season in seasons[:-1]:
if 'support' in season['interaction'].values():
last_support = season['season']
return last_support | ee997b73a428b99d47819db1c80db077d9a78ddd | 426,539 |
def draw_sure(deck, n, exclusions):
"""Draw n cards from a deck but skip any cards listed in
exclusions. Please note this func always returns a list, unlike
native deuces draw function.
"""
drawn = []
while len(drawn) < n:
c = deck.draw()
if c in exclusions + drawn:
continue
drawn.append(c)
return drawn | 4e43998962e15916b397843cb1ea254b10a1c1b9 | 618,350 |
def getPointRange(iFace, dims):
"""Return the correct point range for face iFace on a block with
dimensions given in dims"""
il = dims[0]
jl = dims[1]
kl = dims[2]
if iFace == 0:
return [[1, il], [1, jl], [1, 1]]
elif iFace == 1:
return [[1, il], [1, jl], [kl, kl]]
elif iFace == 2:
return [[1, 1], [1, jl], [1, kl]]
elif iFace == 3:
return [[il, il], [1, jl], [1, kl]]
elif iFace == 4:
return [[1, il], [1, 1], [1, kl]]
elif iFace == 5:
return [[1, il], [jl, jl], [1, kl]] | 63945a7ae725fdda799deb7e20090a60101c326a | 441,597 |
def pypi_link(pkg_filename):
"""
Given the filename, including md5 fragment, construct the
dependency link for PyPI.
"""
root = 'https://files.pythonhosted.org/packages/source'
name, sep, rest = pkg_filename.partition('-')
parts = root, name[0], name, pkg_filename
return '/'.join(parts) | 1f71b2c6c34b52a60c2ead14b40e98ef0c89a8cf | 16,844 |
def _manifest(package_name):
"""
Helper function to create an appropriate manifest with a provided package name.
:pram package_name The package name used in the manifest file.
"""
return """
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="{}" >
<uses-sdk
android:minSdkVersion="21"
android:targetSdkVersion="29"/>
</manifest>
""".format(package_name) | f7da2c1285558327f143e4ca231ba7586c1acb58 | 150,846 |
import re
def avg_word_length(text):
"""
Averages the word length in `text`
:param text: The text to analyze (str)
:return: average_word_len (float)
"""
words = re.sub(r'[\.\?!]', '', text).split()
return sum(len(word) for word in words) / len(words) | ef710c291d0a29a2969818ade60a93b111f471da | 249,976 |
def generate_outpath(filepath):
"""
Generates the output name for an input nii.gz file by appending 'noise'
to file name.
"""
parts = filepath.split('.')
prefix = '.'.join(parts[:-2]+['noise'])
return prefix | 4a041b847aee153bd693ca6113a9ac5c71cd01d3 | 339,206 |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
The idea is to put 0 and 2 in their correct positions, which will make sure
all the 1s are automatically placed in their right positions
Args:
input_list(list): List to be sorted
"""
# If list is empty
if not input_list:
return input_list
# initialize pointers for next positions of 0 and 2
next_pos_0 = 0
next_pos_2 = len(input_list) - 1
front_index = 0
while front_index <= next_pos_2:
if input_list[front_index] == 0: # If the element is 0, place element at next position
input_list[front_index] = input_list[next_pos_0]
input_list[next_pos_0] = 0
next_pos_0 += 1
front_index += 1
elif input_list[front_index] == 2: # If the element is 2, place element at next position of 2
input_list[front_index] = input_list[next_pos_2]
input_list[next_pos_2] = 2
next_pos_2 -= 1
else:
front_index += 1
return input_list | a88ebdb718c42140bdec5aafbf352ff8f403e3f7 | 253,296 |
def ft2m(ft):
"""feet -> meters"""
return 0.3048*ft | 8ab872d97eb8adcc2cbf72bae270ea5e9045a5ff | 673,760 |
def split_by_unescaped_sep(text, sep=':'):
"""Split string at sep but only if not escaped."""
def remerge(s):
# s is a list of strings.
for i in range(len(s) - 1):
n_esc = len(s[i]) - len(s[i].rstrip('\\'))
if n_esc % 2 == 0:
continue
else:
new_s = s[:i] + [s[i] + sep + s[i + 1]] + s[i + 2:]
return remerge(new_s)
return s
# split by every sep (even unescaped ones)
# then re-merge strings that end in an uneven number of escape chars:
return remerge(text.split(sep)) | 6eb360787a3ba5e08f499d2a3352d1170d2fcf89 | 39,166 |
def discretize(pde, geo, time_nsteps=None, space_nsteps=None):
"""
Discretize PDE and Geometry
Parameters:
pde (PDE): The partial differential equations.
geo (Geometry): The geometry to be discretized.
Returns
--------
pde_disc: PDE
Reserved parameter
geo_disc: DiscreteGeometry
Discrte Geometry
"""
# Geometry
geo_disc = geo.discretize(time_nsteps, space_nsteps)
return pde, geo_disc | 1f2e8df5a143b056892a53a71ec2baa0d2d1c92f | 421,527 |
import hmac
import hashlib
import base64
def sign(message, secret):
"""Compute a Base64-encoded HMAC-SHA256.
Arguments:
message (unicode): The value to be signed.
secret (unicode): The secret key to use when signing the message.
Returns:
unicode: The message signature.
"""
message = message.encode('utf-8')
secret = secret.encode('utf-8')
# Calculate a message hash (i.e., digest) using the provided secret key
digest = hmac.new(secret, msg=message, digestmod=hashlib.sha256).digest()
# Base64-encode the message hash
signature = base64.b64encode(digest).decode()
return signature | 96aba415aa95e9bfb59d01e6b88b2d4034d213b3 | 496,540 |
import re
def get_flex_counters(module):
"""
@summary: Parse output of "counterpoll show" command and convert it to the dictionary.
Composed dictionary example:
{'PG_WATERMARK_STAT': {'Interval': '10000', 'Status': 'enable'},
'PORT_STAT': {'Interval': '10000', 'Status': 'enable'},
'QUEUE_STAT': {'Interval': '10000', 'Status': 'enable'},
'QUEUE_WATERMARK_STAT': {'Interval': '10000', 'Status': 'enable'}}
CLI output example:
Type Interval (in ms) Status
-------------------- ------------------ --------
QUEUE_STAT default (10000) enable
PORT_STAT default (1000) enable
QUEUE_WATERMARK_STAT default (10000) enable
PG_WATERMARK_STAT default (10000) enable
@param module: The AnsibleModule object
@return: Return dictionary of parsed counters
"""
result = {}
cli_cmd = "counterpoll show"
skip_lines = 2
rc, stdout, stderr = module.run_command(cli_cmd)
if rc != 0:
module.fail_json(msg="Failed to run {}, rc={}, stdout={}, stderr={}".format(cli_cmd, rc, stdout, stderr))
try:
for line in stdout.splitlines()[skip_lines:]:
if line:
key = line.split()[0]
matched = re.search("{}.*(enable|disable)".format(key), line)
if matched:
counter_line = matched.group(0).split()
result[key] = {}
# Output line will contain 4 columns if default was not changed
# And 3 columns if default was changed
index = 2 if len(counter_line) % 3 else 1
result[key]["Interval"] = counter_line[index].strip("(|)")
result[key]["Status"] = counter_line[-1]
except Exception as e:
module.fail_json(msg="Failed to parse output of '{}', err={}".format(cli_cmd, str(e)))
return result | 8c8205c52dd8b08f4434297ebf39846197b6f74f | 543,936 |
def convert_period_into_pandas_freq(period_str):
"""converts the period into a frequency format used by pandas library.
Args:
period_str (string): period in string format using m, h and d to represent
minutes, hours and days.
Returns:
string: new value for period according to pandas frequency format.
ex: 1m -> 1min, 1h -> 1H and 1d -> 1D
"""
number = ''.join(filter(str.isdigit, period_str))
letter = ''.join(filter(str.isalpha, period_str))
if letter == 'm':
return ''.join([number, 'min'])
# return uppercase of period_str for other values of letter
return period_str.upper() | e471ee8a2b6bdb384d4db089ac3a62d9658ef69b | 92,388 |
def newline_join(string, line_length):
"""
Inserts newline into the string. Newline is inserted at first the word
boundary after the line_length characters.
Parameters
----------
string : str
String to insert newlines into.
line_length : int
Line length threshold after which the new line will be inserted.
Returns
-------
str with inserted newlines
"""
array = string.split()
count = 0
line = ""
for word in array:
count = count + len(word) + 1
if count > line_length:
line = line + "\n" + word
count = len(word)
else:
line = line + " " + word
return(line.strip()) | 771f6f41876f8ed004eb26f73970801e0a8ad247 | 552,059 |
def Odds(p):
"""Computes odds for a given probability.
Example: p=0.75 means 75 for and 25 against, or 3:1 odds in favor.
Note: when p=1, the formula for odds divides by zero, which is
normally undefined. But I think it is reasonable to define Odds(1)
to be infinity, so that's what this function does.
p: float 0-1
Returns: float odds
"""
if p == 1:
return float('inf')
return p / (1 - p) | f4e40f290b4207a9262d4f4ed6014bead0eec92a | 179,028 |
def seq_to_kmers(seq, k=3):
""" Divide a string into a list of kmers strings.
Parameters:
seq (string)
k (int), default 3
Returns:
List containing a list of kmers.
"""
N = len(seq)
return [seq[i:i+k] for i in range(N - k + 1)] | 77901b378a329529955a1852419662ae2d7acbec | 248,247 |
def make_shape_channels_first(shape):
"""Makes a (N, ..., C) shape into (N, C, ...)."""
return shape[:1] + shape[-1:] + shape[1:-1] | db3315f9191957a6f0395f17273d32cb8f954ef3 | 446,038 |
import itertools
def flatten(ls):
"""
flatten a nested list
"""
flat_ls = list(itertools.chain.from_iterable(ls))
return flat_ls | 46c9ce5b089cae4ee67876b4f5e798dbf334036d | 54,845 |
import json
def get_placeholder_value_given_type(value):
"""Given an a parameter type, return a placeholder value"""
# string, array, object, boolean, integer, float, or datetime.
if value.lower() == "string":
return json.dumps("")
elif value.lower() == "array":
return []
elif value.lower() == "object":
return {}
elif value.lower() == "boolean":
return "false"
elif value.lower() == "integer":
return 0
elif value.lower() == "float":
return 0
elif value.lower() == "datetime":
return "2021-04-01T00:00:00.fffffffZ" | e8e8b6f6730b6ed301e57aac0938714588ce8467 | 461,916 |
def is_dos_style_abspath(path):
"""
Check whether the given path is a DOS/Windows style absolute path.
path: A path string
"""
if len(path) < 3:
return False
drv = path[0] # drive letter
# A:65, B:66, ... Z:90, a:97, b:98, ... z:122
if ord(drv) < 65 or (ord(drv) > 90 and ord(drv) < 97) or ord(drv) > 122:
return False
return path[1:3] == ":\\" | 167f2a00a15897f6fcfc6aeb1785b0b97ae3fb22 | 489,291 |
def subsample(data_array, subsample_interval):
""" Subsample every points_per_sample points """
return data_array[..., 0::subsample_interval] | 514f667052e6a5135eac7df91052839b49120a0a | 139,845 |
def find_next_empty(puzzle):
"""
Takes a puzzle as parameter
Finds the next row, col on the puzzle
that's not filled yet (with a value of -1)
Returns (row, col) tuple
or (None, None) if there is none
"""
for row in range(9):
for col in range(9):
if puzzle[row][col] == -1:
return row, col
return None, None | fd56f9c46659cb9c4e21bc00c984ef55a5238f1e | 516,707 |
def is_defined(value):
"""Return True IFF `value` is not 'UNDEFINED' or None.
>>> is_defined("UNDEFINED")
False
>>> is_defined(None)
False
>>> is_defined("FOO")
True
"""
return value not in ["UNDEFINED", None] | 2776c6df504b0d2aca148bd8c69e341fcab2f9c7 | 531,470 |
def _mpas_to_netcdf_calendar(calendar):
"""
Convert from MPAS calendar to NetCDF4 calendar names.
"""
if calendar == 'gregorian_noleap':
calendar = 'noleap'
elif calendar != 'gregorian':
raise ValueError('Unsupported calendar {}'.format(calendar))
return calendar | bdeaf343deeb4beb8c04654ab5104425396e98be | 27,535 |
def cut_rod2(p, n, r={}):
"""Cut rod.
Same functionality as the original but implemented
as a top-down with memoization.
"""
q = r.get(n, None)
if q:
return q
else:
if n == 0:
return 0
else:
q = 0
for i in range(n):
q = max(q, p[i] + cut_rod2(p, n - (i + 1), r))
r[n] = q
return q | 2fa1433dffb9099709e466025645c4981f289692 | 10,270 |
import requests
def follow_url(URL):
"""
Just a wrapper function that automatically raises
an error if there's issues requesting.
"""
r = requests.get(URL)
r.raise_for_status()
return r.text | 1fae5b04f25b1509fdaf71855b3ad0de2cc228e1 | 342,978 |
def risk_level(value):
"""
Returns a string based risk level from a number.
1: Low
2: Medium
3: Medium
4: High
"""
if value == 1:
return 'low'
if value == 2 or value == 3:
return 'medium'
if value == 4:
return 'high' | 1afa4f2a74956a5e2eebf030ed2183dae7bd9227 | 267,375 |
def _cv_delta(x, eps=1.):
"""Returns the result of a regularised dirac function of the
input value(s).
"""
return eps / (eps**2 + x**2) | 8dcfc19acd0f311ea7ffa12c2a1d7b806d69c59b | 595,866 |
def bezier_sample(t, params):
"""Sample points from cubic Bezier curves defined by params at t values."""
A = params.new_tensor([[1, 0, 0, 0],
[-3, 3, 0, 0],
[3, -6, 3, 0],
[-1, 3, -3, 1]])
t = t.pow(t.new_tensor([0, 1, 2, 3])) # [n_samples, 4]
points = t @ A @ params # [..., n_samples, 3]
return points | 3e57054df8ee955b40ae3dbb375589c44eb72b2e | 440,345 |
import _warnings
def snap_to_lines(fixation_sequence, text_block, method="warp", **kwargs):
"""
Deprecated in 0.4. Use `eyekit.fixation.FixationSequence.snap_to_lines()`.
"""
_warnings.warn(
"eyekit.tools.snap_to_lines() is deprecated, use FixationSequence.snap_to_lines() instead",
FutureWarning,
)
return fixation_sequence.snap_to_lines(text_block, method, **kwargs) | f7357c2ea56dc928b6e209ad5361dfd8157808e9 | 323,530 |
def is_valid_interval(interval):
"""Checks if the given interval is valid. A valid interval
is always a positive, non-zero integer value.
"""
if not isinstance(interval, int):
return False
if interval < 0:
return False
return True | 18c41942e6b72251d618653516232eb74c8b5097 | 59,661 |
def get_node_info(node, ws):
"""
Args:
node (Node):
ws (list(int)): knowledge weights. [cdscore, rdscore, asscore, stscore]
Returns:
return node information for a searched tree analysis
node information: self node, parent node, depth, score, RDScore, CDScore, STScore, ASScore
"""
return (f"{id(node)}\t"
f"{id(node.parent_node)}\t"
f"{node.depth}\t"
f"{node.total_scores / node.visits}\t"
f"{node.state.rdscore}\t"
f"{node.state.cdscore * ws[0]}\t"
f"{node.state.stscore * ws[3]}\t"
f"{node.state.asscore * ws[2]}") | d17ce544acbedc6171b1af11a27b1a3356ea3a0e | 67,258 |
import ipaddress
def is_ipv4(ip: str):
"""Return True if given address is a valid IPv4 address, otherwise return False"""
try:
ipaddress.IPv4Address(ip)
except ipaddress.AddressValueError:
return False
return True | 3efccd8d5b969d53a26f4b0bc52db909fe160213 | 293,145 |
def mutate_string(string, pos, change_to):
"""
Fastest way I've found to mutate a string
@ 736 ns
>>> mutate_string('anthony', 0, 'A')
'Anthony'
:param string:
:param pos:
:param change_to:
:return:
"""
string_array = list(string)
string_array[pos] = change_to
return ''.join(string_array) | c6119076411b57f9ded2e899d40b6b82bb5f7836 | 12,855 |
def create_minio_dispatcher_node(name):
"""
Args:
name(str): Name of the minio node
Returns:
dict: A dictionnary with the minio node configuration
"""
return {
"endpoint_url": "http://{:s}:9000/".format(name),
"aws_access_key_id": "playcloud",
"aws_secret_access_key": "playcloud",
"type": "s3",
} | df313dfa7152944332551dd70aab4b0a0e36ff56 | 643,358 |
def activeTT_init(M):
"""
Initialize list of tour types that can be used in this problem instance
:param M: Model
:return: list of tour type indexes
"""
return [t for t in M.TTYPES if M.tt_ub[t] > 0] | b90006e640569b92fb6d1eb196564bdec5898b11 | 448,089 |
def get_other_person_from_match(user_id, match):
"""given a Match, return the Person corresponding to the user who is NOT
the passed user ID (i.e. the other Person)
"""
if match.person_1.user_id == user_id:
return match.person_2
elif match.person_2.user_id == user_id:
return match.person_1
else:
raise Exception(f"Person with user ID \"{user_id}\" is not part of "
f"the passed match ({match}).") | 5ee3af4a095d084eb8685cb044c2df2ea365d65d | 359,314 |
def partition_from_ragged_tensor_by_name(ragged_tensor, partition_type: str):
"""Extract row partition tensor from ragged tensor defined by string identifier of the partition scheme.
Args:
ragged_tensor (tf.RaggedTensor): Ragged tensor to extract row partition from.
partition_type (str): String identifier of the partition scheme. Either `row_splits`, `row_limits` etc.
Returns:
tf.Tensor: Row partition defined by partition_type.
"""
# Not for nested ragged definition
flat_tens = ragged_tensor.values
if partition_type in ["row_length", "row_lengths"]:
out_part = ragged_tensor.row_lengths()
elif partition_type in ["row_split", "row_splits"]:
out_part = ragged_tensor.row_splits
elif partition_type == "value_rowids":
out_part = ragged_tensor.value_rowids()
elif partition_type in ["row_limit", "row_limits"]:
out_part = ragged_tensor.row_limits()
elif partition_type in ["row_start", "row_starts"]:
out_part = ragged_tensor.row_starts()
else:
raise TypeError("Unknown partition scheme, use: 'row_lengths', 'row_splits', ...")
return [flat_tens, out_part] | dfc449f5dd044d61ae54a676ff2a00a91ba570bf | 239,295 |
def lerp(value1=0.0, value2=1.0, parameter=0.5):
"""
Linearly interpolates between value1 and value2 according to a parameter.
Args:
value1: First interpolation value
value2: Second interpolation value
parameter: Parameter of interpolation
Returns:
The linear intepolation between value 1 and value 2
"""
return value1 + parameter * (value2 - value1) | dc37e08e0e586e19a565dd9c48995e1de811c512 | 323,112 |
def trim_variant_fields(location, ref, alt):
"""
Trims common prefixes from the ref and alt sequences
Parameters
----------
location : int
Position (starting from 1) on some chromosome
ref : str
Reference nucleotides
alt : str
Alternate (mutant) nucleotide
Returns adjusted triplet (location, ref, alt)
"""
if len(alt) > 0 and ref.startswith(alt):
# if alt is a prefix of the ref sequence then we actually have a
# deletion like:
# g.10 GTT > GT
# which can be trimmed to
# g.12 'T'>''
ref = ref[len(alt):]
location += len(alt)
alt = ""
if len(ref) > 0 and alt.startswith(ref):
# if ref sequence is a prefix of the alt sequence then we actually have
# an insertion like:
# g.10 GT>GTT
# which can be trimmed to
# g.11 ''>'T'
# Note that we are selecting the position *before* the insertion
# (as an arbitrary convention)
alt = alt[len(ref):]
location += len(ref) - 1
ref = ""
return location, ref, alt | c211b2a62d38dfcecf0351d0fa62e9cc70baf974 | 375,714 |
def ensure_quotes(s: str) -> str:
"""Quote a string that isn't solely alphanumeric."""
return '"{}"'.format(s) if not s.isalnum() else s | 650a58a0b33350b661a698c206ac02b729b25fc7 | 144,952 |
import math
def keep_top_genes(counts, num_genes_discard, criteria="Variance"):
"""
This function takes a matrix of counts (Genes as columns and spots as rows)
and returns a new matrix of counts where a number of genesa re kept
using the variance or the total count as filtering criterias.
:param counts: a matrix of counts
:param num_genes_discard: the % (1-100) of genes to keep
:param criteria: the criteria used to select ("Variance or "TopRanked")
:return: a new matrix of counts with only the top ranked genes.
"""
if num_genes_discard <= 0:
return counts
# Spots as columns and genes as rows
counts = counts.transpose()
# Keep only the genes with higher over-all variance
num_genes = len(counts.index)
print("Removing {}% of genes based on the {}".format(num_genes_discard * 100, criteria))
if criteria == "Variance":
var = counts.var(axis=1)
min_genes_spot_var = var.quantile(num_genes_discard)
if math.isnan(min_genes_spot_var):
print("Computed variance is NaN! Check your input data.")
else:
print("Min normalized variance a gene must have over all spots "
"to be kept ({0}% of total) {1}".format(num_genes_discard, min_genes_spot_var))
counts = counts[var >= min_genes_spot_var]
elif criteria == "TopRanked":
sum = counts.sum(axis=1)
min_genes_spot_sum = sum.quantile(num_genes_discard)
if math.isnan(min_genes_spot_sum):
print("Computed sum is NaN! Check your input data.")
else:
print("Min normalized total count a gene must have over all spots "
"to be kept ({0}% of total) {1}".format(num_genes_discard, min_genes_spot_sum))
counts = counts[sum >= min_genes_spot_sum]
else:
raise RuntimeError("Error, incorrect criteria method\n")
print("Dropped {} genes".format(num_genes - len(counts.index)))
return counts.transpose() | ed364e66d35b9ae035cc3d2af16e0fbeb355e1ed | 383,804 |
import re
def fixSlashes(url):
"""
Removes double slashes in URLs, and ensures the protocol is doubleslahed
"""
# insert missing protocol slashes
p = re.compile( '(:/)([^/])' )
url = p.subn( r'\1/\2', url)[0]
# strip any double slashes excluding ://
p = re.compile( '([^:])//' )
return p.subn( r'\1/', url)[0] | 8213ff86e85d49a829f4eff8627a97c33e984a9e | 687,871 |
import math
def days_to_hmsm(days):
"""
Convert fractional days to hours, minutes, seconds, and microseconds.
Precision beyond microseconds is rounded to the nearest microsecond.
Parameters
----------
days : float
A fractional number of days. Must be less than 1.
Returns
-------
hour : int
Hour number.
min : int
Minute number.
sec : int
Second number.
micro : int
Microsecond number.
Raises
------
ValueError
If `days` is >= 1.
Examples
--------
>>> days_to_hmsm(0.1)
(2, 24, 0, 0)
"""
hours = days * 24.
hours, hour = math.modf(hours)
mins = hours * 60.
mins, min = math.modf(mins)
secs = mins * 60.
secs, sec = math.modf(secs)
micro = round(secs * 1.e6)
return int(hour), int(min), int(sec), int(micro) | 94d454bbcae30e043b8017f2903bc1e19489226d | 304,999 |
def filter_resources(resource, filter_name, filter_value):
"""Filter AWS resources
Args:
resource (object): EC2 resource
filter_name (string): Filter name
filter_value (string/list): Filter value(s)
Returns:
List: Filtered AWS resources
"""
values = [filter_value]
if type(filter_value) is list:
values = filter_value
filters = [{
"Name": filter_name,
"Values": values
}]
return list(resource.filter(Filters=filters)) | d72f091af78ec73a81a50dc02cbeefde94de58d9 | 19,419 |
def read_prophage_table(infile):
"""
Reads tab-delimited table with columns for:
1 - path to GenBank file,
2 - replicon id,
3 - prophage start coordinate,
4 - prophage end coordinate,
5 (optional) - prophage name (if not provided pp1, pp2, etc.
will be assigned for each file)
:param infile: path to the file
:return prophages: dictionary of GenBank file(s) paths, replicons and prophages coordinates
"""
prophages = {}
with open(infile) as inf:
for line in inf:
if line.startswith('#'): continue
line = line.strip().split('\t')
file_path, replicon_id, start, end = line[:4]
# adjust coords to Python's indexing
coords = (int(start) - 1, int(end) - 1)
if start > end:
start, end = end, start
if file_path in prophages:
pp_cnt = len(prophages[file_path]) + 1
else:
pp_cnt = 1
pp = line[4] if len(line) == 5 else f"pp{pp_cnt}"
try:
prophages[file_path][replicon_id][coords] = pp
except KeyError:
try:
prophages[file_path][replicon_id] = {coords: pp}
except KeyError:
prophages[file_path] = {replicon_id: {coords: pp}}
return prophages | 22ce00548ff0fb1fa9ee45c51269bfa40babc512 | 126,251 |
import struct
def read_uint(buf, endianness=""):
"""
Reads an unsigned integer from `buf`.
"""
return struct.unpack(endianness + "H", buf.read(2))[0] | 19e9a962e9d8e66fe04832cf6bfcac72c19943b0 | 71,527 |
def _is_A_list_company_symbol(code: str) -> bool:
"""测试code是否是符合A股代码要求的字符串
Precondition
=======================================================================================
:param code: A股代码
Post condition
=======================================================================================
:return: True or False
Examples:
=======================================================================================
>>> _is_A_list_company_symbol('300072')
True
>>> _is_A_list_company_symbol(300072)
Traceback (most recent call last):
...
AssertionError
>>> _is_A_list_company_symbol('300072.SZ')
False
>>> _is_A_list_company_symbol('700072.SZ')
False
"""
assert isinstance(code, str)
return code.isdigit() \
and len(code) == 6 \
and code[:3] in ('000', '002', '300', '600', '601', '603', '608', '688') | 3b139cc1726682d8c2a363d765fc112a7822de5c | 377,671 |
import requests
def url_exists(url):
"""Check if a given url exists."""
codes = [200, 302] # 200 OK, 302 Found
return True if requests.head(url).status_code in codes else False | 19d0221f0169a0338c9d114999e26c0a86c473cf | 479,782 |
def get_text(soup):
"""
Extracts text from the page source
PARAMS:
soup:BeautifulSoup object - page source converted to BeautifulSoup object
RETURNS:
text:str - text contents of the page
"""
text = ""
lead = soup.find("div", {"class": "delfi-article-lead"}).text
text += lead
p_tags = soup.find_all("p")
for p in p_tags:
if not p.text.endswith("..."):
text += p.text + "\n "
return text | 2cce80d5abad085a9b5962af6cf2d4f8bbc3eaa1 | 185,697 |
def fraction_str(numerator, denominator) -> str:
"""
Formats a fraction to the format %.5f [numerator/deniminator]
:param numerator:
:param denominator:
:return: Formatted string
"""
if denominator > 0:
return "%.5f [%.5f/%d]" % (float(numerator)/denominator, numerator, denominator)
else:
return "No Data" | 280f734854551a6e1315dee34e2c4af5da1591e3 | 535,318 |
import typing
def first_non_null(iterable: list) -> typing.Optional[str]:
"""Takes in an iterable, returns the first item that is not equal to '', if not found then None.
:parameter iterable: A list that a for loop can iterate over
:type iterable: list
:return: The first item that is not equal to '' in the list or None if none is found
:rtype: str or None
"""
for i in iterable:
if i != '':
return str(i)
return None | 18517a9e73f2cea1953234fc02842aedb55c445f | 270,314 |
def ndvire3(b7, b8):
"""
Normalized Difference Vegetation Index Red-edge 3 \
(Gitelson and Merzlyak, 1994).
.. math:: NDVIRE3 = (b8 - b7) / (b8 + b7)
:param b7: Red-edge 3.
:type b7: numpy.ndarray or float
:param b8: NIR.
:type b8: numpy.ndarray or float
:returns NDVIRE3: Index value
.. Tip::
Gitelson, A., Merzlyak, M. N. 1994. Spectral reflectance changes \
associated with autumn senescence of Aesculus hippocastanum L. and \
Acer platanoides L. leaves. Spectral features and relation to \
chlorophyll estimation. Journal of Plant Physiology 143(3), 286-292. \
doi:10.1016/S0176-1617(11)81633-0.
"""
NDVIRE3 = (b8 - b7) / (b8 + b7)
return NDVIRE3 | 965a27aec24d0a53c6d5afe23f4b2c951cf7fb17 | 535,704 |
def FormatDiffHunks(hunks):
"""Re-serialize a list of DiffHunks."""
r = []
last_header = None
for hunk in hunks:
this_header = hunk.header[0:2]
if last_header != this_header:
r.extend(hunk.header)
last_header = this_header
else:
r.extend(hunk.header[2])
r.extend(hunk.lines)
r.append("\n")
return "".join(r) | b3baa2ccc1784301a7ebf45746864f1a9bbabaa4 | 622,114 |
def _parse_r_line(line, *_):
"""
Parse router info line.
:param line: the line
:return: dict with router info
"""
split_line = line.split(' ')
return {
'nickname': split_line[0],
'ip': split_line[5],
'dir_port': int(split_line[7]),
'tor_port': int(split_line[6]),
'_fingerprint': split_line[1],
} | 5e4befcebf6a8d254d52bf5b49f4834346dc62a2 | 433,594 |
def _conditional_field_block(if_keyword, expression, colon, comment, newline,
indent, fields, dedent):
"""Applies an existence_condition to each element of fields."""
del if_keyword, newline, colon, comment, indent, dedent # Unused.
for field in fields.list:
condition = field.field.existence_condition
condition.CopyFrom(expression)
condition.source_location.is_disjoint_from_parent = True
return fields | 969d2c95e5f6724a0d65c2b72c6149d27bc4676f | 240,605 |
def convert_bool_args(args: dict) -> dict:
"""Convert boolean CLI arguments from string to bool.
Args:
args: a mapping from CLI argument names to values
Returns:
copy of args with boolean string values convert to bool
"""
new_args = {}
for k, v in args.items():
if v.lower() == 'true':
v = True
elif v.lower() == 'false':
v = False
new_args[k] = v
return new_args | 0f0c44faf01e26ad814b3779e62f071a56d626bf | 540,872 |
Subsets and Splits