content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def get_subnode(node, key):
"""Returns the requested value from a dictionary, while ignoring null values"""
if node != None and key in node:
return node[key]
return None | 2377bcfc374882e53b169b5e5978e1248000a779 | 363,528 |
def sensor_error(raw_sensor_value):
"""Actual sensor error derived from field tests."""
return (raw_sensor_value + 2.5) / 1.32 | bc9cf40071198d38d638326c647c482a49f75a0d | 652,885 |
def remove_coord(cube, coord):
"""Remove a coordinate from a cube (when the Iris built-in fails).
Args:
cube (iris.cube.Cube) : Cube of data
coord (str) : Name of the coordinate
Returns:
iris.cube.Cube : Updated cube, sans coordinate
"""
if coord in [c.standard_name for c in cube.coords()]:
cube.remove_coord(coord)
return cube | 2556d4f87a423a6313b03e1a43d120e6b960b2a5 | 152,398 |
import glob
def get_photos() -> list:
""" Returns a list of paths to photos. """
path = "static/img/conklin/"
return list(map(lambda x: "/".join(x.split("/")[1:]), glob.glob("{}*.jpg".format(path)) + glob.glob("{}*.JPG".format(path)))) | f43186f0a2439364607c1c24e71d31efc0dcec5c | 264,372 |
def unit_propagate(clauses, cascade=True):
"""Divide a collection of clauses into a set of satisfied literals and a
new collection of clauses with satisfied literals removed.
Args:
clauses (:obj:`iter` of :obj:`iter` of :obj:`int`): A collection of clauses.
cascade (:obj:`bool`, optional): Whether to recursively apply ``unit_propagate``.
Defaults to `True`.
Returns:
:obj:`tuple` - The first element is a :obj:`set` of :obj:`int` containing
satisfied literals. The second element is a collection of clauses with
all satisfied literals removed.
"""
cnf_1, cnf_n = set(), set()
cnf_other = list()
for clause in clauses:
if len(clause) == 1:
cnf_1.add(list(clause)[0])
else:
cnf_other.append(clause)
if not cnf_1:
return cnf_1, cnf_other
for clause in cnf_other:
clause = set(clause)
for literal in list(clause):
# Remove clauses containing True literals
if literal in cnf_1:
break
# Remove false literals from clauses
if -literal in cnf_1:
clause.remove(literal)
else:
cnf_n.add(frozenset(clause))
if cascade:
cnf_1_next, cnf_n = unit_propagate(cnf_n)
cnf_1.update(cnf_1_next)
return cnf_1, cnf_n | 5314e2b87cc9765791b6d02ee40105d747c9d7ce | 260,386 |
def trigger_dict(ts_epoch):
"""A dictionary representing a date trigger."""
return {"run_date": ts_epoch, "timezone": "utc"} | c14ab8144cb38391c91581487e594c7492b2615d | 401,219 |
def backward_propagation_l2_regularization(m,W,lambd):
"""
computes the l2 regularization term for backpropagation of a single layer
Arguments:
m -- number of examples
W -- weights of the layer
lamdb -- regularization term for scaling of "ssmoothing"
Returns:
L2_regularization_backpropagation - value of the regularized loss function term for backpropagation
"""
L2_regularization_backpropagation = ((lambd/m)*W)
return L2_regularization_backpropagation | cc10405d6bc45ee629da14cbce1fca5f3381c8b6 | 457,334 |
import torch
def quaternion_to_matrix(quaternions: torch.Tensor) -> torch.Tensor:
"""
Convert rotations given as quaternions to rotation matrices.
Args:
quaternions: quaternions with real part first,
as tensor of shape (..., 4).
Returns:
Rotation matrices as tensor of shape (..., 3, 3).
"""
r, i, j, k = torch.unbind(quaternions, -1)
two_s = 2.0 / (quaternions * quaternions).sum(-1)
o = torch.stack(
(
1 - two_s * (j * j + k * k),
two_s * (i * j - k * r),
two_s * (i * k + j * r),
two_s * (i * j + k * r),
1 - two_s * (i * i + k * k),
two_s * (j * k - i * r),
two_s * (i * k - j * r),
two_s * (j * k + i * r),
1 - two_s * (i * i + j * j),
),
-1,
)
return o.reshape(quaternions.shape[:-1] + (3, 3)) | 025a3559e96997a986c89151a9ec08d8e33cf991 | 270,472 |
def startswith(prefix):
"""
Create a function that checks if the argument
that is passed in starts with string
:param str prefix: string to check the start for
:return func startswith_function: a function that checks if the
argument starts with the specified string
"""
def string_starts_with(string):
return str.startswith(string, prefix)
return string_starts_with | 47e0967ce9864743f412070ba1e016f83fe708ed | 639,990 |
def format_time( t ):
""" format seconds as mm:ss """
m,s = divmod(t,60)
if m > 59:
h,m = divmod(m,60)
return "%d:%02d:%02d"%(h,m,s)
else:
return "%d:%02d"%(m,s) | d8e79bd86183d2b5466d09add2d893392829c5f3 | 264,367 |
def modular_geometric_sum(x, n, mod):
""" Compute a_n = (1 + a^1 + ... + a^{n-1}) % mod
using that
a_{2n} = ((x_n + 1) * a_n) % mod
a_{2n+1} = (x^{2n} + a_{2n}) % mod
"""
if n == 1:
return 1 % mod
elif n % 2 == 0:
return ((pow(x, n // 2, mod) + 1) * modular_geometric_sum(x, n // 2, mod)) % mod
else:
return (pow(x, n - 1, mod) + modular_geometric_sum(x, n - 1, mod)) % mod | 5ec1af73ec6229679c1075a49c21bdb0eccc53f8 | 657,175 |
def validate_numeric_range_parameter(parameter, default_val, min_val=None, max_val=None):
"""Validates the range-type parameter, e.g. angle in Random Rotation.
Parameters
----------
parameter : tuple or None
The value of the parameter
default_val : object
Default value of the parameter if it is None.
min_val: None or float or int
Check whether the parameter is greater or equal than this. Optional.
max_val: None or float or int
Check whether the parameter is less or equal than this. Optional.
Returns
-------
out : tuple
Parameter value, passed all the checks.
"""
if not isinstance(default_val, tuple):
raise TypeError
if parameter is None:
parameter = default_val
if isinstance(parameter, list):
parameter = tuple(parameter)
if not isinstance(parameter, tuple):
raise TypeError
if len(parameter) != 2:
raise ValueError
if parameter[0] > parameter[1]:
raise ValueError
if not (isinstance(parameter[0], (int, float)) and isinstance(parameter[1], (int, float))):
raise TypeError("Incorrect type of the parameter!")
if min_val is not None:
if parameter[0] < min_val or parameter[1] < min_val:
raise ValueError
if max_val is not None:
if parameter[0] > max_val or parameter[1] > max_val:
raise ValueError
return parameter | 0db74e17b68b4c3cc8965b7a6d7d644dbc87fd81 | 447,397 |
import json
def parse_logs(file_name):
"""Read the timing logs out of the log file."""
data = []
with open(file_name) as f:
for line in f:
entry = json.loads(line)
if 'phase' in entry and entry['phase'] == 'Test':
continue
if 'time' in entry:
data.append(entry)
return data | 2ce6ee1022f7ce733537bfc6555356afeb7c721b | 258,849 |
def toList(buffer):
"""
Takes a list, bytes object or string and converts it to a list
of integers.
Args:
buffer: A list, bytes object or string.
Returns:
A list of integers.
"""
if isinstance(buffer, str):
return [ord(ch) for ch in buffer]
else:
return [int(val) for val in buffer] | 68e682351672d5d002e94b2e668284bd5f999751 | 258,512 |
def monthdelta(date, delta):
"""because we wish datetime.timedelta had a month kwarg.
Courtesy of: http://stackoverflow.com/a/3425124/3916180
Parameters
----------
date : datetime.date
Date object
delta : int
Month delta
Returns
-------
datetime.date
New Date object with delta offset.
"""
month, year = (date.month + delta) % 12, date.year + ((date.month) + delta - 1) // 12
if not month:
month = 12
day = min(date.day, [31, 29 if year % 4 == 0 and not year % 400 == 0 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]) # pylint: disable=line-too-long
return date.replace(day=day, month=month, year=year) | d79afe2bf8d86a86caa01f88bed16814c27fcdda | 128,468 |
def generate_sas_url(
account_name: str,
account_domain: str,
container_name: str,
blob_name: str,
sas_token: str
) -> str:
"""
Generates and returns a sas url for accessing blob storage
"""
return f"https://{account_name}.{account_domain}/{container_name}/{blob_name}?{sas_token}" | 6fedfb9cacc08fddc8e6912bb6cd5c0c2d929e9b | 49,784 |
def get_color(pict, x, y):
""" (Cimpl.Image, int, int) -> Cimpl.Color
Return a Color containing the RGB components of the pixel at
location (x, y) in Image pict.
"""
return pict.get_color(x, y) | dde7f8106d6cfd04f195f5075197f01aa7b55201 | 163,421 |
from typing import List
def most_frequent(list_: List):
"""
Return most frequent element of a list if not empty elase return empty string
:param l: list with element
:return: item in list with most occurrence
"""
if not list_:
return ""
else:
return max(set(list_), key=list_.count) | f1790b42fa66f509c4cda361dc9ac8986c9d8ed5 | 373,208 |
def compute_error_vector(y, tx, w):
"""
Computes the error vector that is defined as y - tx . w
Args:
y: labels
tx: features
w: weight vector
Returns:
error_vector: the error vector defined as y - tx.dot(w)
"""
return y - tx.dot(w) | 104998f9ae1b88463ac7eef09cf0337ffb91a691 | 139,073 |
def build_factorized(factorized: dict) -> int:
"""
Build integer from its factorized form, (reverse function of factorization)
:param factorized: factorized integer dict
:return: integer
"""
num = 1
for factor in factorized:
num *= factor ** factorized[factor]
return int(num) | 73db0c09db2c7644f4f95c76dbe21b64f54d7641 | 22,798 |
def find_author(name, authors):
""" Find the author with the provided name, in the list of authors"""
for author in authors:
if author.name == name: return author
raise ValueError('Author', name, 'not found.') | dd47f0ecf8574d68a0ce9b5e94dff19b58f5887a | 8,584 |
def _get_ad_description(soup_body):
"""
Helper function that fetches Diva's advert description from page
Returns:
dict: dict containing `description` key and description text
"""
desc_container = soup_body.find('div', attrs={'id': 'anons_content'}).find(
'div', attrs={'id': 'tresc_pl'}
)
return ' '.join(desc_container.stripped_strings) | e137793a9b34b246782e224a029291a73dea5c11 | 202,952 |
def get_pars(ts, coors, mode=None, region=None, ig=None):
"""
We can define the coefficient `load.val` as a function of space.
For scalar parameters, the shape has to be set to `(coors.shape[0], 1, 1)`.
"""
if mode == 'qp':
x = coors[:,0]
val = 55.0 * (x - 0.05)
val.shape = (coors.shape[0], 1, 1)
return {'val' : val} | 00ea9705a9f59388d1d3ab1c97796da687da6686 | 622,238 |
def sumsequences(N,K):
"""
All sequences of length N with numbers adding up to K;
The number of such is sequences is given by the multiset number:
N+K-1 over K.
"""
seqs = [ [] ]
for i in range(N-1):
new_seqs = []
for s in seqs:
for j in range(K - sum(s) + 1):
new_seqs += [ [j] + s ]
seqs = new_seqs
return [ [ K - sum(s) ] + s for s in seqs ] | 4d957edaa5ef35b6d4ae5b5041efcd8f501bfad2 | 593,719 |
def remove_des(name):
"""
remove 'Class A Common Stock' and 'Common Stock' from listing names
"""
if name.endswith("Class A Common Stock"):
name = name[:-21]
if name.endswith("Common Stock"):
name = name[:-13]
return name | 3f4fb80d42c029e85b5354f226206df511911cc1 | 616,507 |
def mk_falls_description(data_id, data): # measurement group 8
"""
transforms a h-falls-description.json form into the triples used by insertMeasurementGroup to
store each measurement that is in the form
:param data_id: unique id from the json form
:param data: data array from the json form
:return: The list of (typeid,valType,value) triples that are used by insertMeasurementGroup to add the measurements
"""
return [(220, 2, data_id),
(48, 7, data['fallint']),
(49, 2, data['falldesc']),
(50, 2, data['fallinjury'])] | 1e0c304538159b9bb01d677bdacdfa9a0b3b4e4d | 23,428 |
def read_labels(file_name):
"""
Read list of labels from file like this:
label1
label2
label3
...
"""
labels_tmp = []
try:
with open(file_name, 'r') as f:
labels_tmp = f.readlines()
labels_tmp = [(i.rstrip(), 0) for i in labels_tmp]
except:
pass
labels = []
for label in labels_tmp:
label = list(label)
labels.append(label)
return labels | 247807c6a7a5e452b7bdb8a3874aabc889ef1ec9 | 667,768 |
import base64
def encodebase64(inputStr, encodeFlag=True):
""" Encode str to base64 """
if encodeFlag and inputStr:
return base64.b64encode(inputStr)
return inputStr | 17b190d9cae37df336820398e5a46b75e0199740 | 178,177 |
def _function_wrapper(args_tuple):
"""Function wrapper to call from multiprocessing."""
function, args = args_tuple
return function(*args) | 05eee157304eec7570be3d10ab9d77830a307749 | 338,667 |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"state": string, # space/~ converted to null
"remote": string,
"refid": string,
"st": integer,
"t": string,
"when": integer, # - converted to null
"poll": integer,
"reach": integer,
"delay": float,
"offset": float,
"jitter": float
},
]
"""
for entry in proc_data:
if entry['s'] == '~':
entry['s'] = None
entry['state'] = entry.pop('s')
int_list = ['st', 'when', 'poll', 'reach']
for key in int_list:
if key in entry:
try:
entry[key] = int(entry[key])
except (ValueError):
entry[key] = None
float_list = ['delay', 'offset', 'jitter']
for key in float_list:
if key in entry:
try:
entry[key] = float(entry[key])
except (ValueError):
entry[key] = None
return proc_data | 059495d483be437692a888e75a1406f506a8c689 | 497,258 |
def v12_add(*matrices):
"""Add corresponding numbers in given 2-D matrices."""
matrix_shapes = {
tuple(len(r) for r in matrix)
for matrix in matrices
}
if len(set(matrix_shapes)) > 1:
raise ValueError("Given matrices are not the same size.")
return [
[sum(values) for values in zip(*rows)]
for rows in zip(*matrices)
] | 934dbd82be527f113eeb2eaad01f8c867100a869 | 650,152 |
def xeval(sexpr):
"""
>>> xeval('')
0
>>> xeval('1234567')
1234567
>>> xeval('+1234567')
1234567
>>> xeval('-1234567')
-1234567
>>> xeval('2+3')
5
>>> xeval('2-3')
-1
>>> xeval('2-23+4')
-17
>>> xeval('2-01+3-1')
3
>>> xeval('1-2-3-4-5')
-13
"""
if not sexpr:
return 0
size = len(sexpr)
start = 0
curr = 1 if sexpr[0] == '+' or sexpr[0] == '-' else 0
while curr < size and sexpr[curr] != '+' and sexpr[curr] != '-':
curr += 1
this = int(sexpr[start:curr])
if curr >= size - 1:
return this
return this + xeval(sexpr[curr:]) | 9e7f8120b9f546fdc94c08ab0ee9978d528309f2 | 647,646 |
def contingency_table(ys, yhats, positive=True):
"""Computes a contingency table for given predictions.
:param ys: true labels
:type ys: iterable
:param yhats: predicted labels
:type yhats: iterable
:param positive: the positive label
:return: TP, FP, TN, FN
>>> ys = [True, True, True, True, True, False]
>>> yhats = [True, True, False, False, False, True]
>>> tab = contingency_table(ys, yhats, 1)
>>> print(tab)
(2, 1, 0, 3)
"""
TP = 0
TN = 0
FP = 0
FN = 0
for y, yhat in zip(ys, yhats):
if y == positive:
if y == yhat:
TP += 1
else:
FN += 1
else:
if y == yhat:
TN += 1
else:
FP += 1
return TP, FP, TN, FN | 83efd6b17654dc6424d933723c84fb162dc04263 | 603,348 |
def number_of_component_generated_from_default_template(location):
"""
Return number of component generated from the default template.
"""
lines = []
with open(location) as f:
lines = f.readlines()
count = 0
for line in lines:
if '<h3 class="component-name">' in line:
if line.replace('<h3 class="component-name">', '').strip():
count += 1
return count | 6d9342ebcb5f24129440421b0369fa2222df7e71 | 234,864 |
def conjugate(x: complex) -> complex:
"""
Returns the conjugate of a complex number
"""
return x.real - x.imag * 1j | 6cacee436e7ca74d586364a4f578b745c08768d2 | 46,146 |
def truncation_replacement(random, population, parents, offspring, args):
"""Replaces population with the best of the population and offspring.
This function performs truncation replacement, which means that
the entire existing population is replaced by the best from among
the current population and offspring, keeping the existing population
size fixed. This is similar to so-called "plus" replacement in the
evolution strategies literature, except that "plus" replacement
considers only parents and offspring for survival. However, if the
entire population are parents (which is often the case in evolution
strategies), then truncation replacement and plus-replacement are
equivalent approaches.
.. Arguments:
random -- the random number generator object
population -- the population of individuals
parents -- the list of parent individuals
offspring -- the list of offspring individuals
args -- a dictionary of keyword arguments
"""
psize = len(population)
population.extend(list(offspring))
population.sort(reverse=True)
return population[:psize] | eede329cdecee7fd980666a0253fba77120fe0ed | 459,880 |
from typing import OrderedDict
import torch
def filter_state_dict(
state_dict: "OrderedDict[str, torch.Tensor]", name: str
) -> "OrderedDict[str, torch.Tensor]":
"""
Filters state dict for keys that start with provided name.
Strips provided name from beginning of key in the resulting state dict.
Args:
state_dict (OrderedDict[str, torch.Tensor]): input state dict to filter.
name (str): name to filter from state dict keys.
Returns:
OrderedDict[str, torch.Tensor]: filtered state dict.
"""
filtered_state_dict = OrderedDict()
for key, value in state_dict.items():
if key.startswith(name):
# + 1 to length is to remove the '.' after the key
filtered_state_dict[key[len(name) + 1 :]] = value
return filtered_state_dict | c032f9d838cfc9f04cde0094aade9f8e9ae80e8a | 228,702 |
import click
def command_line_timelines_options(f):
"""
Decorator for common timelines command line options
"""
f = click.option(
"--exclude-replies",
is_flag=True,
default=False,
help="Exclude replies from timeline",
)(f)
f = click.option(
"--exclude-retweets",
is_flag=True,
default=False,
help="Exclude retweets from timeline",
)(f)
f = click.option(
"--use-search",
is_flag=True,
default=False,
help="Use the search/all API endpoint which is not limited to the last 3200 tweets, but requires Academic Product Track access.",
)(f)
return f | a42a95b6bc34a35419929eba546121e8c6c5ccb5 | 595,809 |
def joblib_log_level(level: str) -> int:
"""
Convert python log level to joblib int verbosity.
"""
if level == 'INFO':
return 0
else:
return 60 | 82798af0bf8bbbe5b653f22aaf66216579ca85bd | 477,061 |
def listdict2dictlist(list_dict, flatten=False):
"""Function that takes a list of dict and converts it into a dict of lists
Args:
list_dict ([list]): The original list of dicts
Returns:
[dict]: A dict of lists
"""
keys = {key for tmp_dict in list_dict for key in tmp_dict}
res = {}
for k in keys:
tmp = []
for d in list_dict:
if k in d:
val = d.get(k)
if flatten and isinstance(val, list):
tmp += val
else:
tmp.append(val)
res[k] = tmp
return res | 2d615bd5c0869c487bcc19677db26f85ccd6487b | 246,348 |
from typing import Iterable
def remove_nones(sequence: Iterable) -> list:
"""Removes elements where bool(x) evaluates to False.
Examples
--------
Normal usage::
remove_nones(['m', '', 'l', 0, 42, False, True])
# ['m', 'l', 42, True]
"""
# Note this is redundant with it.chain
return [x for x in sequence if x] | 975c0104b3cc05bb82fa211c1b85b49c7d3cb174 | 1,619 |
import socket
def client_connect(host, port):
"""
Wrapper function to connect to client
"""
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
return client
except socket.error as err:
print("Unable to connect to the client: [%s]"%(repr(err)))
raise err | 65832b574e45f545c90481a25e037075552d1e93 | 234,952 |
def find(predicate, iterable, default=None):
"""Return the first item matching `predicate` in `iterable`, or `default` if no match.
If you need all matching items, just use the builtin `filter` or a comprehension;
this is a convenience utility to get the first match only.
"""
return next(filter(predicate, iterable), default) | 70d0d4265d7ef70e3ff041794712990b2dfc10c6 | 660,928 |
def breakLine(line):
"""Breaks a file line into it's command/instruction components.
Most lines in tuflow files are in the form::
Read Command == ..\some\path.ext ! comment
This separates the command from the rest.
Args:
line(str): the line as read from the file.
Returns:
Tuple - (command, instruction).
"""
line = line.strip()
command, instruction = line.split('==', 1)
command = command.strip()
instruction = instruction.strip()
return command, instruction | 40078fb197880b073c0cb8f0e4d4a989cdc4fe48 | 340,745 |
def scale_image(img):
"""Scale image to 1920 by 1080"""
height, width = 1080, 1920 # Desired resolution
# height, width = 720, 1280 # Desired resolution
scale_y = min(img.height, height) / max(img.height, height)
scale_x = min(width, img.width) / max(width, img.width)
if img.height < height and img.width < width:
img.scale = max(scale_x, scale_y)
img.width = img.width / img.scale
img.height = img.height / img.scale
else:
img.scale = min(scale_x, scale_y)
img.width = img.width * img.scale
img.height = img.height * img.scale
return img | 1ba636d874c5853b239b51b9f238591773ccc98f | 283,657 |
def read_file(file):
""" Open given file and returns the content as a string. """
with open(file) as f:
wall = f.read()
return wall | bcfb29a31ac2cfcdf5b733a0bfd3019889a30fba | 691,992 |
def kpoint_path(ikpt):
""" construct path to kpoint
e.g. electrons/kpoint_0/spin_0/state_0
Args:
ikpt (int): kpoint index
Returns:
str: path in hdf5 file
"""
path = 'electrons/kpoint_%d' % (ikpt)
return path | bcda4c4d6f6bd1e9d09c592277d69a34d158a16f | 322,502 |
def find_point_in_path(path, sub):
"""Find a point in a path.
Parameters
----------
path : tuple of array_like
Tuple of arrays of int that represent indices into a matrix.
sub : tuple in int
Indices to search *path* for.
Returns
-------
int or None
Index into *path* if the indices are found. Otherwise, ``None``.
Examples
--------
>>> path = ((0, 1, 4, 6, 5), (3, 1, 7, 8, 10))
>>> find_point_in_path(path, (4, 7))
2
>>> find_point_in_path(path, (99, 2)) is None
True
"""
try:
return list(zip(*path)).index(sub)
except ValueError:
return None | 09cd23b8e55239033fa82f697aaf8445768d9c51 | 239,928 |
def address_column_split(a):
"""
Extracts city and state in an address and provides separate columns for each
"""
asplit = a.split(",")
city = asplit[0].split()[-1]
state = asplit[1].split()[0]
return city, state | 539123969beb28f2623466db193077f4351d04cb | 30,502 |
from typing import List
from typing import Union
def shortest_name(names: List[str]) -> Union[str, None]:
"""Find the shortest name in a list of names that shares at least one
character with every other name in the list. For example in the list:
['add', 'dog', 'tree', 'house', 'gave'], 'gave' is the word that satisfies
the above requirement.
Arguments:
names: List[str]
List of names to search.
Returns:
Union[str, None]: the shortest name that shares a letter in common with
every other name or None if no such name exists.
"""
return_list = []
for current_name in names:
candidate = True
for compare_name in names:
shares_letter = False
for letter in current_name.replace(' ', ''):
if letter in compare_name.replace(' ', ''):
shares_letter = True
break
if shares_letter == False:
candidate = False
break
if candidate != False:
return_list.append(current_name)
if len(return_list) == 0:
return None
smallest_name = return_list[0]
for name in return_list:
if len(name) < len(smallest_name):
smallest_name = name
return smallest_name | ee13af0bc7ca1c7a98bb3e4d7a50074ba0d85131 | 384,190 |
def sum_divisors(n):
"""
Returns a sum of numbers proper divisors.
For exsample sum_divisors(28) = 1 + 2 + 4 + 7 + 14 = 28
"""
s = 1
limit = int(n ** 0.5)
if limit ** 2 == n:
s += limit
limit -= 1
for i in range(2, limit + 1):
if n % i == 0:
s += (i + n // i)
return s | 75acad72444c514bc946ce1bac34c5190032654e | 350,294 |
def _round_up(a: int, b: int) -> int:
"""Round up to a multiple of b"""
return ((a + b - 1) // b) * b | 005ecb28637f88d6c76c5ec5133706e8a787d5d8 | 543,872 |
def rpartition(text, sep):
"""
Splits ``text`` at the last occurrence of ``sep``, returning the result as 3-tuple.
If the separator is not found, this function a 3-tuple containing two empty strings,
followed by the string itself.
:return: a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.
:rtype: ``tuple`` of ``str``
"""
assert isinstance(text,str), '%s is not a string' % text
return text.rpartition(sep) | b0e2c30d5a2f91dd2d75c6688278a2c82b1071a7 | 440,328 |
def unique_routes(routes):
"""
Returns an list with unique routes for all nodes.
This function achieves this by removing simetrical
routes (A, B, C) == (C, B, A).
Args:
routes - a list of routes, as sequences of nodes
Returns: An list with unique routes.
"""
# Iterate over all routes in reversed order
for route in list(reversed(routes)):
# If the reversed route (C, B, A) exists in the list
if list(reversed(route)) in routes:
# Remove it from the list
routes.remove(route)
return routes | 2e67aefcb1ec10f30fbfba7f148bd207b68e8082 | 428,633 |
def date_remove_dashes(std_date):
"""STD_DATE is a date in string form with dashes. Removes dashes for storage in JSON."""
return std_date[0:4] + std_date[5:7] + std_date[8:] | 67e6337a90d6d966325cdd96f4b1844da540fa2e | 692,016 |
def get_concat_peptide(front_coord_pair, back_coord_pair, front_peptide, back_peptide, strand, k=None):
"""
Get the concatenated peptide from possible match peptide.
Parameters
----------
front_coord_pair: str. coordinate string for the front exon pair.
back_coord_pair: str. coordinate string for the back exon pair.
front_peptide: str. peptide translated from the front exon pair.
back_peptide: str. peptide translated from the back exon pair.
strand: str. '+' or '-'
k: k for k-mer.
Returns
-------
new_peptide: str. concatenated peptide. If none is found, return empty string
Examples
--------
front_pep: 'MKTT', back_pep: 'TTAC', concatenated_pep: 'MKTTAC'
"""
def get_longest_match_position(front_str,back_str,L=None):
if L is None:
L = min(len(front_str),len(back_str))
for i in reversed(list(range(1,L+1))):
if front_str[-i:] == back_str[:i]:
return i
return None
if strand == '+':
front_coord = front_coord_pair.stop_v2
back_coord = back_coord_pair.start_v1
else:
front_coord = front_coord_pair.start_v2
back_coord = back_coord_pair.stop_v1
if abs(front_coord-back_coord) % 3 == 0:
if front_coord == back_coord: # no intersection and we concatenate them directly
new_peptide = front_peptide + back_peptide
else:
pep_common_num = get_longest_match_position(front_peptide,back_peptide,L=k)
if pep_common_num is None:
new_peptide = ''
else:
new_peptide = front_peptide + back_peptide[pep_common_num:]
return new_peptide
else:
return '' | 704f0d364493233a1a95538844ef92e16838337e | 569,659 |
def is_palindrome(n):
""" Check whether the passed number is a palindrome.
Args:
n: An int to be checked.
Returns:
A bool.
Used by:
004, 055
"""
word_n = str(n)
return word_n == word_n[::-1] | 53b9798958ec97eb47a3ef90264f898e1dd4d546 | 335,724 |
import collections
def sort_dict(dictionary):
"""
Return a dictionary as an OrderedDict sorted by keys.
"""
items = sorted(dictionary.items())
return collections.OrderedDict(items) | 2e7e7be0e94ead309cb6ae7194f2172e94371e40 | 594,501 |
import re
def is_timestamp(string):
"""Tests if the input string is formatted as -yyyy-mm-dd hh:mm:ss"""
reg_exp = re.compile(r'-\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}')
if reg_exp.match(string) is not None:
return True
return False | 6a8927fffef991e2eb45b376e0491b3fb7bd941f | 218,993 |
import math
def round_gb_size_up(gb_size, dp=2):
"""Rounds a GB disk size (as a decimal float) up to suit the platform.
Use this method to ensure that new vdisks, LUs, etc. are big enough, as the
platform generally rounds inputs to the nearest [whatever]. For example, a
disk of size 4.321GB may wind up at 4.32GB after rounding, possibly leaving
insufficient space for the image.
:param gb_size: A decimal float representing the GB size to be rounded.
:param dp: The number of decimal places to round (up) to. May be zero
(round to next highest integer) or negative, (e.g. -1 will round to the
next highest ten).
:return: A new decimal float which is greater than or equal to the input.
"""
shift = 10.0 ** dp
return float(math.ceil(gb_size * shift)) / shift | 3e65412f461e8ab2f7bb11ef19102879b9e5782b | 32,542 |
def symmetric_mass_ratio_to_mass_ratio(symmetric_mass_ratio):
"""
Convert the symmetric mass ratio to the normal mass ratio.
Parameters
----------
symmetric_mass_ratio: float
Symmetric mass ratio of the binary
Return
------
mass_ratio: float
Mass ratio of the binary
"""
temp = (1 / symmetric_mass_ratio / 2 - 1)
return temp - (temp ** 2 - 1) ** 0.5 | 9fea10403726f4f86e0a90004e23958afee43488 | 515,550 |
def fix_macro_int(lines, key, value):
"""
Fix lines to have new value for a given key
lines: array of strings
where key to be found
key: string
key
value: int
set to be for a given key
returns: bool
True on success, False otherwise
"""
l = -1
k = 0
for line in lines:
if key in line:
l = k
break
k += 1
if l >= 0:
s = lines[l].split(' ')
lines[l] = s[0] + " " + str(value) + "\n"
return True
return False | 3490b533bc0941c249753ac8dd4c916048fe97f1 | 249,187 |
from typing import Type
from typing import List
from typing import Tuple
def get_required_class_field(class_type: Type) -> List[Tuple[str, Type]]:
"""Gets all the (valid) class fields which are mandatory.
Args:
class_type (Type): [description]
Returns:
List[Tuple[str, Type]]: [description]
"""
return [
(field_name, field)
for field_name, field in class_type.__fields__.items()
if field.required and not field_name.startswith("__")
] | 6ff5878238877b011b7366dbfa4e530547c01d2c | 671,871 |
def encode(data):
"""
Encode string to byte in utf-8
:param data: Byte or str
:return: Encoded byte data
:raises: TypeError
"""
if isinstance(data, bytes):
return data
elif isinstance(data, str):
return str.encode(data)
else:
return bytes(data) | 77b2a070f6b436671e6d6074f37fe0e10ebff98d | 659,824 |
import hashlib
def validate_file(file_obj, hash_value, hash_type="sha256"):
"""Validate a given file object with its hash.
Args:
file_obj: File object to read from.
hash_value (str): Hash for url.
hash_type (str, optional): Hash type, among "sha256" and "md5" (Default: ``"sha256"``).
Returns:
bool: return True if its a valid file, else False.
"""
if hash_type == "sha256":
hash_func = hashlib.sha256()
elif hash_type == "md5":
hash_func = hashlib.md5()
else:
raise ValueError
while True:
# Read by chunk to avoid filling memory
chunk = file_obj.read(1024 ** 2)
if not chunk:
break
hash_func.update(chunk)
return hash_func.hexdigest() == hash_value | 9e1468cc44b204cbdb0d7c73b0bb943eeb7eaedf | 375,120 |
import csv
def ConvertCSVStringToList(csv_string):
"""Helper to convert a csv string to a list."""
reader = csv.reader([csv_string])
return list(reader)[0] | fa244d2a1c8c50b2b097883f964f1b5bb7ccf393 | 709,119 |
def eqir(registers, opcodes):
"""eqir (equal immediate/register) sets register C to 1 if value A is
equal to register B. Otherwise, register C is set to 0."""
test_result = int(opcodes[1] == registers[opcodes[2]])
return test_result | 0c2d23c1f1377cebb8d658edf8b764891c748094 | 590,237 |
def get_vcond(lambdam, taum):
"""Return conductance velocity in m/s
lambda -- electronic length in m
taum -- membrane time constant
"""
return 2*lambdam/taum | f13a3599a54f1eb85b3e8526f5f3ee764c9a43f3 | 522,224 |
def create_sequence(padding_mask, idx, pad_id=None):
"""
Create a sequence filled with an index
Args:
padding_mask: padding mask of target sequence
idx: filled value
pad_id: index of pad
Returns:
- a long tensor that is of the same shape as padding_mask and filled with idx
"""
seq = padding_mask.long()
seq = seq.masked_fill(~padding_mask, idx)
if pad_id is not None:
seq = seq.masked_fill(padding_mask, pad_id)
return seq | 939894b8a8ed1a08d35c2d92744fec5eca42d369 | 168,782 |
def split_opts(seq):
"""Splits a name from its list of options."""
parts = seq.split('::')
name, opts = parts[0], dict()
for x in map(lambda x: x.split(':'), parts[1:]):
for y in x:
try:
opt, val = y.split('=')
except ValueError:
opt, val = y, True
if opt:
opts[opt] = val
return name, opts | aa7e103aaae21e6cdb5e97fdb902cec9af4da4f4 | 376,721 |
def index_power(array, n):
"""
Find Nth power of the element with index N.
"""
if n > len(array) - 1:
return -1
return array[n] ** n | b7b1b78f8f3e5ad079670dcf63290cad83196395 | 499,860 |
def mean(data):
"""
Compute the mean value of a sequence of numbers.
"""
if not hasattr(data, '__iter__'):
data = [data]
avg = float(sum(data)) / len(data)
# Done
return avg | 1718655e7bb0012f164c2579107e282f0593bb75 | 412,502 |
import csv
def read_csv(filepath, encoding='utf-8'):
"""
This function reads in a csv and returns its contents as a list
Parameters:
filepath (str): A str representing the filepath for the file to be read
encoding (str): A str representing the character encoding of the file
Returns:
(list): A list with the content of the file
"""
with open(filepath, 'r', encoding=encoding) as file:
reader = csv.reader(file)
data = []
for line in reader:
data.append(line)
return data | aee38a14ca7194c7040b6e8652ad9d43b10e0144 | 688,544 |
def _get_mix_filepath(coverage_datum):
""" Extracts mix file path from a coverage datum.
"""
return coverage_datum.mix_file.short_path | 82a4e0dc8aab0fe6b520a4d7c11e94575157944d | 492,928 |
def mndwi(b3, b11):
"""
Modified Normalized Difference Water Index (Xu, 2006).
.. math:: MNDWI = (b3 - b11) / (b3 + b11)
:param b3: Green.
:type b3: numpy.ndarray or float
:param b11: SWIR 1.
:type b11: numpy.ndarray or float
:returns MNDWI: Index value
.. Tip::
Xu, H. (2006). Modification of normalised difference water index \
(NDWI) to enhance open water features in remotely sensed imagery. \
International Journal of Remote Sensing 27(14), 3025-3033. \
doi:10.1080/01431160600589179.
"""
MNDWI = (b3 - b11) / (b3 + b11)
return MNDWI | 957ad51dee7942000f826ed144c3aabb94613f9c | 185,672 |
import socket
def _lookup_host(loop, host, family):
"""Look up IPv4 or IPv6 addresses of a host name"""
try:
addrinfo = yield from loop.getaddrinfo(host, 0, family=family,
type=socket.SOCK_STREAM)
except socket.gaierror:
return []
return [ai[4][0] for ai in addrinfo] | b7827e342166c31b50fd536e8eb930c3b9598a14 | 145,110 |
def get_surfaces_per_volume(my_core, entityset_ranges):
"""
Get the number of surfaces that each volume in a given file contains
inputs
------
my_core : a MOAB core instance
entity_ranges : a dictionary of the entityset ranges of each tag in a file
outputs
-------
s_p_v : a dictionary containing the volume entityhandle
and the number of surfaces each volume in the file contains
i.e. {volume entityhandle:surfaces it contains}
"""
s_p_v = {}
for volumeset in entityset_ranges['Volumes']:
s_p_v[volumeset] = my_core.get_child_meshsets(volumeset).size()
return s_p_v | 309c86226484bf5485ed46d2f399c8a4c25bc9c7 | 499,537 |
def get_github_path(owner: str, repo: str) -> str:
"""Get github path from owner and repo name"""
return "%s/%s" % (owner, repo) | 189cae1d577ccb32ed5fa0c6f0a0a98fb74768c4 | 634,708 |
def bin_to_str(bin_str_arr):
"""
Convert binary number in string to string
:param bin_str_arr: str, whose length must be a multiple of 8
:return: str
"""
res = ''
for i in range(0, len(bin_str_arr), 8):
res += chr(int(bin_str_arr[i:i+8], 2))
return res | 4da23c7f6261f4f5da7a8bd830ad474855bce811 | 171,049 |
def line_count(node, file):
"""Return the line count of file on node"""
out = [line for line in node.account.ssh_capture("wc -l %s" % file)]
if len(out) != 1:
raise Exception("Expected single line of output from wc -l")
return int(out[0].strip().split(" ")[0]) | 60afe65d0e4a6c731ed5c0ea87370818aa0733ab | 562,557 |
def map_to_docs(solr_response):
"""
Response mapper that only returns the list of result documents.
"""
return solr_response['response']['docs'] | 2661b9075c05a91c241342151d713702973b9c12 | 6,246 |
import base64
def generate_http_basic_token(username, password):
"""
Generates a HTTP basic token from username and password
Returns a token string (not a byte)
"""
token = base64.b64encode("{}:{}".format(username, password).encode("utf-8")).decode(
"utf-8"
)
return token | ce0fafa49b55e7692be5b55b0bb4543a6038e158 | 459,551 |
def read_file(filename):
"""Function reads contents of file
Args:
filename (str): Filename to read
Returns:
list: List with lines of text in file
"""
with open(filename, "r", encoding="utf-8") as fp:
return fp.readlines() | 23924d0c86712b14be7d3cf0c1faec186f8cc726 | 114,169 |
def split_file_name(file_absolute_name):
"""
Splits a file name into: [directory, name, extension]
:param full_name_template:
:return:
"""
split_template = file_absolute_name.split('/')
[name, extension] = split_template[-1].split('.')
directory = "/".join(split_template[0: len(split_template) - 1])
return [directory, name, extension] | f3144b0f75cbde26c8a8244cb8d8eda712e8edfa | 635,306 |
import time
def get_close_string(time_to_close):
"""
Given a time in seconds, this will format it as a string like 03h:12m
"""
time_to_close = time.gmtime(time_to_close)
close_string = time.strftime('%Hh:%Mm', time_to_close)
return close_string | f7c678bf2b5ef0b0db4e3e50e10adb977a869ff7 | 248,680 |
def VERSION(parent, r):
"""Return the current version of PyBot library"""
return parent.robot._get_pybot_version() | beac216fb3f5b861cea328c7f481887c312acf7b | 282,455 |
def extract_id(url):
"""
:param url like http://data.finlex.fi/ecli/kko/1998/138:
:return: 1998_138
"""
splitted = url.split('/')
return splitted[-2] + '_' + splitted[-1] | 3b788be247bb7039b419a79fa0216459b078e552 | 608,561 |
import re
def contains_chinese(text):
"""Returns whether the given text contains any chinese characters."""
return re.search(u'[\u4e00-\u9fff]', text) | a2ea77109b3af46cae1f99f8c7fb20fc6f1ab4b1 | 642,535 |
def german_X(german_data):
"""Process German to remove categorical columns."""
outcome_name = german_data.columns[0]
return german_data.drop([outcome_name, 'Gender', 'PurposeOfLoan', 'OtherLoansAtStore'], axis=1) | fb178f96bbef53628d7dcd26d0f86c864cb370f8 | 453,975 |
def fix_ext_py(filename):
"""Given a .pyc filename converts it to the appropriate .py"""
if filename.endswith('.pyc'):
filename = filename[:-1]
return filename | c978f86af22b6833e681de8a040a8718aeaa4bfc | 543,971 |
def player_value_to_string(text):
"""
Parses the player's value from a string.
Args:
text: The standard string of a player's value from Transfermarkt.
Returns:
A float representing the player's value. If the value cannot be parsed,
returns None.
"""
# Free transfer
if "Free" in text:
value = 0
elif "M" in text:
value = float(text.split("M")[0].replace(",", "."))
elif "T" in text:
value = float(text.split("T")[0].replace(",", ".")) / 1000
else:
return None
return value | 642de7e7d67409c3cb288286806530068f2ac602 | 229,854 |
def load_user_id_whitelist(fw):
"""
Load user IDs from a FW-group-defined whitelist.
"""
# Group name is intentionally not configurable.
group_name = 'hpc-whitelist'
group_perms = fw.get_group(group_name)['permissions']
return list(map(lambda x: x.id, group_perms)) | 645388df94d00944feaef07b14ff11f40b1dc40d | 435,624 |
import re
def parse_freq_err_resp(resp):
""" Parse the frequency error response
@param resp: response from ATECPS
@return: frequency error in Hz
"""
pattern = '\[(.+)\]'
freqerr = re.search(pattern, resp)
if freqerr:
return int(freqerr.group(1))
else:
return 0 | 7eff65d3b91299d3c1954d104baee3a29ca9ff84 | 431,121 |
import re
def validate_hostname(hostname):
"""
Validate a hostname string. This allows standard hostnames and IPv4
addresses.
:param hostname: The hostname to validate.
:return: Boolean: True if valid, False if invalid
"""
# Hostname length is limited.
if len(hostname) > 255:
return False
# Hostname labels may consist of numbers, letters and hyphens, but may not
# end or begin with a hyphen.
allowed = re.compile("(?!-)[a-z\d-]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(x) for x in hostname.split(".")) | 70a2f2c8367af5480f0c9daca0ce4f02af50c786 | 536,289 |
def get_is_active(language, order):
"""
Checks if order is active or no and creates response in appropriate language
:param language: language of conversation
:param order: client order
:return: string with info about if order is active or no
"""
output_string = ""
if language == 'pl':
if order.is_active:
output_string = "TAK"
else:
output_string = "Nie"
elif language == 'en':
if order.is_active:
output_string = "YES"
else:
output_string = "NO"
return output_string | 15e065cc545cf6aa9c471b36c73400317d43b4bc | 607,042 |
def fix_text_note(text):
"""Wrap CHS document text."""
if not text:
return ""
else:
return """* CHS "Chicago Streets" Document:\n> «{}»""".format(text) | 56cbcbad7e8b3eee6bb527a240ad96701c4eea2f | 6,412 |
def intervals_overlap(i1, i2):
"""Returns True if Interval i1 overlaps Interval i2. The intervals are considered to be closed, so the intervals
still overlap if i1.end == i2.begin or i2.end == i1.begin.
"""
return not (i1.end < i2.begin or i2.end < i1.begin) | 4ab6cea8e869739eed369f6be348db233f64f6e8 | 119,945 |
import pickle
def get_plankton(path, *plankton_sets):
"""Returns plankton training sets converted from serialised pickle objects
into Pandas dataframes.
Args:
path ([path]): Path to pickled training sets
plankton_sets (*[pkl]): Four * pkl objects
Returns:
[pd.DataFrames]: Two training sets (measurements/random - 1987-2008)
Two of same config. but 2079-2100 (for future PDP's)
"""
p_sets = []
for p_set in plankton_sets:
with open(f"{path}/{p_set}.pkl", "rb") as handle:
plankton_set = pickle.load(handle)
p_sets.append(plankton_set)
return [p_sets[i] for i in range(len(p_sets))] | 97dfdb58d8737ded321943c5185ec12c98561000 | 252,894 |
def allowed_file(filename, allowed_set):
"""Checks if filename extension is one of the allowed filename extensions for upload.
Args:
filename: filename of the uploaded file to be checked.
allowed_set: set containing the valid image file extensions.
Returns:
check: boolean value representing if the file extension is in the allowed extension list.
True = file is allowed
False = file not allowed.
"""
check = '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_set
return check | 199e43b124ba92da6d9b644b3c9564ee86f7d69d | 291,518 |
async def _get_post_id(db, author, permlink):
"""Get post_id from hive db."""
sql = "SELECT id FROM hive_posts WHERE author = :a AND permlink = :p"
return await db.query_one(sql, a=author, p=permlink) | be64e63c81ebf9e70c5e8f97b1d57256ed756cd5 | 643,543 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.