content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
import unicodedata
def normalize_text(text: str) -> str:
"""Normalize the text to remove accents
and ensure all the characters are valid
ascii symbols.
Args:
text : Input text
Returns:
Output text
"""
nfkd_form = unicodedata.normalize("NFKD", text)
only_ascii = nfkd_form.encode("ASCII", "ignore")
return only_ascii.decode() | fa1c5362caa9946e79152f9e14ccf2131754f258 | 6,584 |
def rotate_y(x, z, cosangle, sinangle):
"""3D rotaion around *y* (roll). *x* and *z* are values or arrays.
Positive rotation is for positive *sinangle*. Returns *xNew, zNew*."""
return cosangle*x + sinangle*z, -sinangle*x + cosangle*z | 0a1b28548f771b9ca8cec29ba4060be7b0919182 | 6,585 |
def parse_address(address):
"""Convert host:port or port to address to pass to connect."""
if ':' not in address:
return ('', int(address))
host, port = address.rsplit(':', 1)
return (host, int(port)) | 06eb172974c4e75d33ae205f952e8533c88acfeb | 6,597 |
def expand_basic(state):
"""
Simple function which returns child states by appending an available move to
current state.
"""
assert(len(state) < 9)
# Calculte set difference to get remaining moves.
n = tuple(set(range(9)) - set(state))
# Create tuple of available new states and return to caller.
c = tuple(state + (q,) for q in n)
return c | 0889a21b043f6f675d133fed6e3c825eb69f4a82 | 6,608 |
def get_reachable_observed_variables_for_inferred_variables(model, observed=set()):
"""
After performing inference on a BayesianModel, get the labels of observed variables
("reachable observed variables") that influenced the beliefs of variables inferred
to be in a definite state.
Args
model: instance of BayesianModel class or subclass
observed: set,
set of labels (strings) corresponding to variables pinned to a definite
state during inference.
Returns
dict,
key, value pairs {source_label_id: reachable_observed_vars}, where
source_label_id is an int or string, and reachable_observed_vars is a list
of label_ids
"""
if not observed:
return {}
source_vars = model.get_unobserved_variables_in_definite_state(observed)
return {var: model.reachable_observed_variables(var, observed) for var in source_vars} | a693d6c57969b38b357a4a57fe2e868650b514b6 | 6,610 |
from textwrap import dedent
def get_device_number(connection_str):
"""Return the integer device number from the connection string or raise ValueError
if the connection string is not in the format "device <n>" with positive n."""
try:
prefix, num = connection_str.split(' ')
num = int(num)
if prefix != 'device' or num <= 0:
raise ValueError
except (TypeError, ValueError):
msg = f"""Connection string '{connection_str}' not in required format 'device
<n>' with n > 0"""
raise ValueError(dedent(msg)) from None
return num | 396a13d4449166e0d63e830b17b07b3b22a208e7 | 6,612 |
import importlib
def getattr_in_module(module_name: str, func_name: str):
""" 在某个模块中获取属性
Args:
module_name: 模块名
func_name: 属性名
Returns:
属性
"""
m = importlib.import_module(module_name)
return getattr(m, func_name) | e0ceec50c063cea8350c04a4f048ca53d75ab5f6 | 6,617 |
import torch
def _get_product_features(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Get outer product of 2 tensors along the last dimension.
All dimensions except last are preserved. The last dimension is replaced
with flattened outer products of last-dimension-vectors from input tensors
This is a vectorized implementation of (for 2D case):
for i in range(x.shape[0]):
out[i, :] = torch.outer(x[i, :], y[i, :]).flatten()
For 2D inputs:
Input shapes:
x: (batch, feature_dim_x)
y: (batch, feature_dim_y)
Output shape:
(batch, feature_dim_x*feature_dim_y)
"""
return torch.einsum("...i,...j->...ij", (x, y)).flatten(start_dim=-2) | cf438a799b749563ea9509184cf117f4075730ab | 6,620 |
def slice_or_index(index):
"""Return index or slice the array [:]."""
return slice(None) if index is None else index | 7bdf34a0667cfcc387c41bfcfc000d0881c3f6cd | 6,622 |
def get_bits(byte_size, number):
"""Returns last byte_size*8 bits from number."""
res = []
for i in range(byte_size * 8):
res.append(str(number % 2))
number //= 2
res.reverse()
return res | ad41d3c9f1192b2f7026caa0f42a084ea39c82fa | 6,623 |
import json
from networkx.readwrite import json_graph
def write_nxgraph_to_json(g, output):
"""
Write a networkx graph as JSON to the specified output
Args:
g (networkx.Graph): graph to write as JSON
output (filelike): output to write to
"""
jsond = json_graph.node_link_data(g)
return json.dump(jsond, output) | a909fd3f4e8c87bb3fe059b310819570758c553e | 6,625 |
from typing import Optional
from typing import List
def clean_eisenhower(raw_eisen: Optional[List[str]]) -> List[str]:
"""Clean the raw Eisenhower values from Notion."""
if raw_eisen is None:
return []
return [e for e in raw_eisen if e != ''] | a8dd48a307455f20b8dd7afbf5b5aec1835c7a2d | 6,626 |
def get_instance_type(entity_name, instance_dict=None):
"""
:param entity_name: name of an entity;
:param instance_dict: dictionary that contains the instance type of each entity;
:return: the instance type of the provided entity;
Get the instance type of a given entity, as specified by the instance_dict;
If the entity is not present, return "owl#Thing";
"""
if (instance_dict is None) or (entity_name not in instance_dict):
return "owl#Thing"
else:
return instance_dict[entity_name] | 0fead313271ee8b2b0d7be0d8048d506657b4944 | 6,628 |
def secondes(heure):
"""Prend une heure au format `H:M:S` et renvoie le nombre de secondes
correspondantes (entier).
On suppose que l'heure est bien formattée. On aura toujours un nombre
d'heures valide, un nombre de minutes valide et un nombre de secondes valide.
"""
H, M, S = heure.split(":")
return (3600 * int(H)) + (60 * int(M)) + int(S) | 33d380005479d66041e747130a4451c555baf497 | 6,638 |
import csv
def csv_to_list(filename: str) -> list:
"""Receive an csv filename and returns rows of file with an list"""
with open(filename) as csv_file:
reader = csv.DictReader(csv_file)
csv_data = [line for line in reader]
return csv_data | d7344496271de6edcb3fc1df30bb78dd00980c30 | 6,643 |
import copy
def update_dict(original, new):
"""
Update nested dictionary (dictionary possibly containing dictionaries)
If a field is present in new and original, take the value from new.
If a field is present in new but not original, insert this field
:param original: source dictionary
:type original: dict
:param new: dictionary to take new values from
:type new: dict
:return: updated dictionary
:rtype: dict
"""
updated = copy.deepcopy(original)
for key, value in original.items():
if key in new.keys():
if isinstance(value, dict):
updated[key] = update_dict(value, new[key])
else:
updated[key] = new[key]
return updated | 1608d28321d294943f4c955e42939b054966751f | 6,648 |
def _compute_third(first, second):
""" Compute a third coordinate given the other two """
return -first - second | 57ea03c71f13f3847d4008516ec8f0f5c02424af | 6,651 |
def create_list_from_dict(mydict):
"""
Converts entities dictionary to flat list.
Args:
mydict (dict): Input entities dictionary
Returns:
list
"""
outputs = []
for k, v in mydict.items():
if len(v) > 0:
for i in v:
outputs.append(i)
return outputs | 50fba98b7590bd7d243464cf45be24c4405f2cef | 6,656 |
def json_format(subtitle, data):
"""
Format json to string
:param subtitle: description to text
:type subtitle: string
:param data: content to format
:type data: dictionary
"""
msg = subtitle+':\n'
for name in data: msg += name+': '+data[name]+'\n'
return msg.strip() | bb3392d7ad57a482b4175838858d316ecc5f56e1 | 6,665 |
def remove_dihedral(mol, a, b, c, d):
"""
utils.remove_dihedral
Remove a specific dihedral in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index removing a specific dihedral (int)
Returns:
boolean
"""
if not hasattr(mol, 'dihedrals'):
return False
for i, dihedral in enumerate(mol.dihedrals):
if ((dihedral.a == a and dihedral.b == b and dihedral.c == c and dihedral.d == d) or
(dihedral.d == a and dihedral.c == b and dihedral.b == c and dihedral.a == d)):
del mol.dihedrals[i]
break
return True | 7e26e995fec97c5c6d2304e11d06fec03b990942 | 6,666 |
import torch
def thresh_ious(gt_dists, pred_dists, thresh):
"""
Computes the contact intersection over union for a given threshold
"""
gt_contacts = gt_dists <= thresh
pred_contacts = pred_dists <= thresh
inter = (gt_contacts * pred_contacts).sum(1).float()
union = union = (gt_contacts | pred_contacts).sum(1).float()
iou = torch.zeros_like(union)
iou[union != 0] = inter[union != 0] / union[union != 0]
return iou | 9bd6244325acae0d3ebb5ffca46e0453a71000d1 | 6,667 |
def prettyprint(s, toUpper=False):
"""Given a string, replaces underscores with spaces and uppercases the
first letter of each word ONLY if the string is composed of lowercased
letters. If the param, toUpper is given then s.upper is returned.
Examples: "data_quality" -> "Data Quality"
"copy_number_123" -> "Copy Number 123"
"My_own_title" -> "My own title"
"Hla" -> "Hla"
"""
if toUpper:
s = s.upper()
s= s.replace("_", " ")
else:
s = s.title()
s= s.replace("_", " ")
return s | 18a57e74a2e3df66db4ede337663f9d8993a986b | 6,672 |
import math
def _rsqrt(step_number, tail_start, body_value):
"""Computes a tail using a scaled reciprocal square root of step number.
Args:
step_number: Absolute step number from the start of training.
tail_start: Step number at which the tail of the curve starts.
body_value: Value relative to which the tail should be computed.
Returns:
A learning rate value that falls as the reciprocal square root of the step
number, scaled so that it joins smoothly with the body of a BodyAndTail
instance.
"""
return body_value * (math.sqrt(tail_start) / math.sqrt(step_number)) | 99138c88ae8d0fc0d49a5ac55e389cd5a40d5f90 | 6,674 |
def has_other_useful_output(content_text):
"""Returns whether |content_text| has other useful output.
Namely, console errors/warnings & alerts/confirms/prompts.
"""
prefixes = ('CONSOLE ERROR:', 'CONSOLE WARNING:', 'ALERT:', 'CONFIRM:',
'PROMPT:')
def is_useful(line):
return any(line.startswith(prefix) for prefix in prefixes)
lines = content_text.strip().splitlines()
return any(is_useful(line) for line in lines) | c1abfdaf681816314134ae33b5fd0fc48757dcc5 | 6,679 |
def to_nbsphinx(s):
"""Use the sphinx naming style for anchors of headings"""
s = s.replace(" ", "-").lower()
return "".join(filter(lambda c : c not in "()", s)) | 87b266c84f9b32c1d7357c5ed23ba4058ba33673 | 6,681 |
def check_type_match(actual_val, expected_val) -> bool:
"""Check actual_val matches type of expected_val
The exception here is that expected_val can be
float, and in that case actual_val can be either
int or float
Args:
actual_val (Any): Actual type
expected_val (Any): Expected type
Returns:
bool: Whether the type matches
"""
if type(actual_val) == type(expected_val):
return True
# Make an exception here since int can be represented as float
# But not vice versa (for example, index)
if type(expected_val) == float and type(actual_val) == int:
return True
return False | 90f74b1978deb0c55b65a4faa2569f54fe6bceee | 6,686 |
def fieldtype(field):
"""Get the type of a django form field (thus helps you know what class to apply to it)"""
return field.field.widget.__class__.__name__ | e2d68cbdd72219de1a23095100c054a46c6c191b | 6,687 |
def get_team_repo(remote_url):
"""
Takes remote URL (e.g., `[email protected]:mozilla/fireplace.git`) and
returns team/repo pair (e.g., `mozilla/fireplace`).
"""
if ':' not in remote_url:
return remote_url
return remote_url.split(':')[1].replace('.git', '') | 5e0120881557e9d95b697ab194fd7a8e8a84c68d | 6,689 |
import re
def check_if_partial(comments):
"""
Checks if comments contain info about Dat being a part of a series of dats (i.e. two part entropy scans where first
part is wide and second part is narrow with more repeats)
Args:
comments (string): Sweeplogs comments (where info on part#of# should be found)
Returns:
bool: True or False
"""
assert type(comments) == str
comments = comments.split(',')
comments = [com.strip() for com in comments]
part_comment = [com for com in comments if re.match('part*', com)]
if part_comment:
return True
else:
return False | 6f565bae6fe1cf5da4a11e0d511a25daa07aadd1 | 6,690 |
def read_file_info(filename):
"""
Read an info file.
Parameters
----------
filename : string
The name of file with cross-sectional area and length information.
Returns
-------
info : dict
The values of cross-sectional area and length of the specimens,
"""
fd = open(filename, 'r')
info = {}
for line in fd:
if line and (not line.isspace()) and (line[0] != '#'):
key, val = line.split()
info[key] = float(val)
fd.close()
return info | c3f8c106126b45845c1202b34b19cad2ce2ae036 | 6,691 |
def nice_layer_name(weight_key):
"""Takes a tuple like ('weights', 2) and returns a nice string like "2nd layer weights"
for use in plots and legends."""
return "Layer {num} {name}".format(num=weight_key[1] + 1, name=weight_key[0]) | c88dd554c2a3cf35e6d6e96131833738c19766ac | 6,693 |
def stringify(num):
"""
Takes a number and returns a string putting a zero in front if it's
single digit.
"""
num_string = str(num)
if len(num_string) == 1:
num_string = '0' + num_string
return num_string | 7cf37776bc774d02bce0b2016d41b26b8ab94cf7 | 6,701 |
def euc_distance(vertex, circle_obstacle):
"""
Finds the distance between the point and center of the circle.
vertex: Vertex in question.
circle_obstacle: Circle obstacle in question.
return: Distance between the vertex and the center of the circle.
"""
x = vertex[0] - circle_obstacle.position[0]
y = vertex[1] - circle_obstacle.position[1]
dist = ((x ** 2) + (y ** 2)) ** 0.5
return dist | 60ed338eb7a81fc282196c38d41cecda8f28efb7 | 6,702 |
def get_mvarg(size_pos, position="full"):
"""Take xrandrs size&pos and prepare it for wmctrl (MVARG) format
MVARG: <G>,<X>,<Y>,<W>,<H>
* <G> - gravity, 0 is default
"""
allowed = ["left", "right", "top", "bottom", "full"]
if position not in allowed:
raise ValueError(f"Position has to be one of {allowed}")
size, x, y = size_pos.split("+")
w, h = size.split("x")
if position == "left":
w = int(w) // 2
if position == "right":
w = int(w) // 2
x = int(x) + w
return f"0,{x},{y},{w},{h}" | 0b8a9c3f5ca7e24212502a3f2c76b18167deef6e | 6,704 |
def is_class_name(class_name):
"""
Check if the given string is a python class.
The criteria to use is the convention that Python classes start with uppercase
:param class_name: The name of class candidate
:type class_name: str
:return: True whether the class_name is a python class otherwise False
"""
return class_name.capitalize()[0] == class_name[0] | 2b4b6a09f2a112f7e8163f3caf97fdfca0c93e12 | 6,709 |
def _lookup_alias(aliases, value):
"""
Translate to a common name if our value is an alias.
:type aliases: dict of (str, [str])
:type value: str
:rtype: str
>>> _lookup_alias({'name1': ['alias1']}, 'name1')
'name1'
>>> _lookup_alias({'name1': ['alias1', 'alias2']}, 'alias1')
'name1'
>>> _lookup_alias({'name1': ['alias1', 'alias2']}, 'alias2')
'name1'
>>> _lookup_alias({'name1': ['alias1']}, 'name2')
'name2'
"""
better_name = [name for (name, aliases) in aliases.items()
if value in aliases]
return better_name[0] if better_name else value | df0641b1f8aca964f76afd2a83fb91a587d52e1d | 6,711 |
def missing_columns(df, missing_threshold=0.6):
"""Find missing features
Parameters
----------
df : pd.DataFrame, shape (n_samples, n_features)
Training data, where n_samples is the number of samples and n_features is the number of features.
missing_threshold : float, default=0.6
Count all features with a missing rate greater than `missing_threshold`.
Returns
-------
t : All features with a missing rate greater than `missing_threshold`
"""
assert 1>=missing_threshold>=0, "`missing_threshold` should be one of [0, 1]."
t = (1-df.count()/len(df)).reset_index()
t.columns = ['feature_name', 'missing_rate']
t = t[t.missing_rate>=missing_threshold].reset_index(drop=True)
return t | 4d31673670d894556b6571a0233ec36c8452570a | 6,712 |
def is_ordered(treap):
""" Utility to check that every node in the given Treap satisfies the following:
Rules:
- if v is a child of u, then v.priority <= u.priority
- if v is a left child of u, then v.key < u.key
- if v is a right child of u, then v.key > u.key
"""
# iterate through all nodes in the heap
for node in treap:
# check parent (if not root)
if node != treap.root and (node.priority > node.parent.priority):
print("Node {} and parent ({}) have mismatched priorities.".format(node, node.parent))
return False
# check left and right. All are optional, technically
if node.left and (node.key < node.left.key):
print("Node {} and left child ({}) have mismatched keys.".format(node, node.left))
return False
if node.right and (node.key > node.right.key):
print("Node {} and right child ({}) have mismatched keys.".format(node, node.right))
return False
return True | 38b7fd7690931e017e9ece52b6cba09dbb708400 | 6,713 |
from typing import Sequence
import fnmatch
def _should_ignore(fd_name: str, patterns: Sequence[str]) -> bool:
"""Return whether `fd_name` should be ignored according to `patterns`.
Examples
--------
>>> fd_name = "google/protobuf/empty.proto"
>>> pattern = "google/protobuf/*"
>>> _should_ignore(fd_name, [pattern])
True
>>> fd_name = "foo/bar"
>>> _should_ignore(fd_name, [pattern])
False
"""
return any(fnmatch.fnmatchcase(fd_name, pattern) for pattern in patterns) | 8bf698afddbda869e26ebcaa98e1f4e950117c08 | 6,714 |
import gzip
def read_consanguineous_samples(path, cutoff=0.05):
"""
Read inbreeding coefficients from a TSV file at the specified path.
Second column is sample id, 6th column is F coefficient. From PLINK:
FID, IID, O(HOM), E(HOM), N(NM), F
Additional columns may be present but will be ignored.
"""
consanguineous_samples = {}
myopen = gzip.open if path.endswith('.gz') else open
with myopen(path) as inf:
_ = inf.readline()
for line in inf:
cols = line.strip().split()
if float(cols[5]) > cutoff:
consanguineous_samples[cols[1]] = True
return consanguineous_samples | be3515e6704966ae927bfaff2594be9191063889 | 6,722 |
def get_xy_coords(xda):
"""Return the dimension name for x and y coordinates
e.g. XC or XG
Parameters
----------
xda : xarray DataArray
with all grid information
Returns
-------
x,y : str
with e.g. 'XC' or 'YC'
"""
x = 'XC' if 'XC' in xda.coords else 'XG'
y = 'YC' if 'YC' in xda.coords else 'YG'
return x,y | 6aca5de1eda17df617027c742a06f97cf77af1d5 | 6,723 |
def obv(df, price, volume, obv):
"""
The On Balance Volume (OBV) is a cumulative total of the up and down volume.
When the close is higher than the previous close, the volume is added to
the running total, and when the close is lower than the previous close,
the volume is subtracted from the running total.
Parameters:
df (pd.DataFrame): DataFrame which contain the asset price.
price (string): the column name of the price of the asset.
volume (string): the column name of the volume of the asset.
obv (string): the column name for the on balance volume values.
Returns:
df (pd.DataFrame): Dataframe with obv of the asset calculated.
"""
df["diff"] = df[price].diff()
df = df.fillna(1)
df.loc[df["diff"] > 0, obv + "_sign"] = 1
df.loc[df["diff"] < 0, obv + "_sign"] = -1
df.loc[df["diff"] == 0, obv + "_sign"] = 0
volume_sign = df[volume] * df[obv + "_sign"]
df[obv] = volume_sign.cumsum()
df.drop(["diff", obv + "_sign"], axis=1, inplace=True)
return df | 19f4c456ed501523d2b349e2766d482bd1fef13b | 6,727 |
def is_data(line):
"""
Function utilized by itertool's groupby method in determining
the delimiter between our blocks of data.
"""
return True if line.strip() else False | da3db970c5c5a3169446513cb4148ffedf598095 | 6,728 |
def anneal(c_max, step, iteration_threshold):
"""Anneal function for anneal_vae (https://arxiv.org/abs/1804.03599).
Args:
c_max: Maximum capacity.
step: Current step.
iteration_threshold: How many iterations to reach c_max.
Returns:
Capacity annealed linearly until c_max.
"""
return min(c_max * 1.,
c_max * 1. * (step) / iteration_threshold) | ca6cbb5fe109e5d6b36870b398604ee79042827f | 6,731 |
from typing import Union
def _value_to_int(value: Union[int, str]) -> int:
"""String value to int."""
try:
return int(value)
except ValueError as error:
raise Exception("The value is not integer") | 635afb6d75edec8df64b12dad8db7dd408502250 | 6,740 |
def get_active_lines(lines, comment_char="#"):
"""
Returns lines, or parts of lines, from content that are not commented out
or completely empty. The resulting lines are all individually stripped.
This is useful for parsing many config files such as ifcfg.
Parameters:
lines (list): List of strings to parse.
comment_char (str): String indicating that all chars following
are part of a comment and will be removed from the output.
Returns:
list: List of valid lines remaining in the input.
Examples:
>>> lines = [
... 'First line',
... ' ',
... '# Comment line',
... 'Inline comment # comment',
... ' Whitespace ',
... 'Last line']
>>> get_active_lines(lines)
['First line', 'Inline comment', 'Whitespace', 'Last line']
"""
return list(filter(None, (line.split(comment_char, 1)[0].strip() for line in lines))) | b49c8cd034c8fa8e7dcf0b5153c8d5bcce52a1f3 | 6,742 |
def snake_to_camel_case(snake_text):
"""
Converts snake case text into camel case
test_path --> testPath
:param snake_text:str
:return: str
"""
components = snake_text.split('_')
# We capitalize the first letter of each component except the first one with
# the 'title' method and join them together.
return components[0] + ''.join(x.title() for x in components[1:]) | b42e1393cf99b88e2ebbcf4b38643c770e218ceb | 6,747 |
def is_occ_conflict_exception(e):
"""
Is the exception an OccConflictException?
:type e: :py:class:`botocore.exceptions.ClientError`
:param e: The ClientError caught.
:rtype: bool
:return: True if the exception is an OccConflictException. False otherwise.
"""
is_occ = e.response['Error']['Code'] == 'OccConflictException'
return is_occ | 3df46480341b617570e1e980ade194c9bd3fb26e | 6,753 |
def average(v):
"""
:param v: a list of numerical values
:return: average for a list of values expressed as a float
"""
return sum(v) * 1.0 / len(v) | cbc9e450ee854289c62b613c257655fcd0c3e62c | 6,755 |
def get_days_word_ending(days: int) -> str:
"""Определяет окончание слова "дня", "дней" и т.д. в зависимости от входящего числа"""
last_numeral = days % 10
prelast_numeral = days % 100
prelast_numeral = prelast_numeral // 10
if prelast_numeral == 1:
return 'дней'
if last_numeral == 0 or last_numeral >= 5:
return 'дней'
elif last_numeral == 1:
return 'день'
else:
return 'дня' | 4f2887b438ab8909b29a0fa572c5735477da2262 | 6,761 |
def compute_throughputs(batch_size, gpu_times):
"""
Given a batch size and an array of time running on GPU,
returns an array of throughputs
"""
return [batch_size / gpu_times[i] * 1000 for i in range(len(gpu_times))] | 14b20806ad8e21126c460613a99f9b68bce31ef0 | 6,762 |
def bond_quatinty(price, investment, minimum_fraction=0.1):
"""
Computes the quantity of bonds purchased given the investment,
bond price per unit, and the minimum fraction of a bond that
can be purchased
:param investment: Amount of money that will be invested
:param minimum_fraction: Minimum fraction that can be purchased
:param price: Price of bond per unit
:return: [quantity of bonds purchased, Total Value Invested, Eror%]
"""
Qf = int(investment / (minimum_fraction * price))
Q = Qf * minimum_fraction
value = Q * price
error = (investment - value) / value * 100
return [Q, value, error] | 7b42ae44d2e2db2229251088cf3645e965887e0d | 6,771 |
def reset_color_picker(modal_open, font_color):
"""
Reset the color-picker to white font color after closing the modal
component.
Parameters
----------
modal_open : bool
A boolean that describes if the modal component is open or not
font_color : dict of { 'hex': str,
'rgb': dict of { 'rgb' : 'r': int,
'g': int,
'b': int,
'a': int
}
}
The hex and rgb value of the selected font color
Returns
-------
dict of { 'rgb': dict of { 'rgb' : 'r': int,
'g': int,
'b': int
}
}
The rgb value of the selected font color
"""
# The modal window is closed so reset the font color.
if not modal_open:
return dict(rgb=dict(r=255, g=255, b=255))
# The modal window is open so return the current font color.
return font_color | 03aaf2207f351eee70fbc8dda406ec0d8bc04530 | 6,776 |
def convert_params_to_string(params: dict) -> str:
""" Create a string representation of parameters in PBC format
"""
return '\n'.join(['%s %s' % (key, value) for (key, value) in params.items()]) | d121ea62f14333ad7f02727a7a6777b8880fef45 | 6,787 |
def contains_end_of_message(message, end_sequence):
"""Función que dado un string message, verifica si es que end_sequence es un
substring de message.
Parameters:
message (str): Mensaje en el cual buscar la secuencia end_sequence.
end_sequence (str): Secuencia que buscar en el string message.
Returns:
bool: True si end_sequence es substring de message y False de lo contrario.
"""
return False if message.find(end_sequence) == -1 else True | 3966e3e2ddf62843c2eb12cf6ae144e53408c360 | 6,792 |
def utility_num2columnletters(num):
"""
Takes a column number and converts it to the equivalent excel column letters
:param int num: column number
:return str: excel column letters
"""
def pre_num2alpha(num):
if num % 26 != 0:
num = [num // 26, num % 26]
else:
num = [(num - 1) // 26, 26]
if num[0] > 26:
num = pre_num2alpha(num[0]) + [num[1]]
else:
num = list(filter(lambda x: False if x == 0 else True, num))
return num
return "".join(list(map(lambda x: chr(x + 64), pre_num2alpha(num)))) | 295b8c5391d5250f91781c2f6df1626a0acb8022 | 6,794 |
from typing import Optional
from typing import Dict
def no_response_from_crawl(stats: Optional[Dict]) -> bool:
"""
Check that the stats dict has received an HTTP 200 response
:param stats: Crawl stats dictionary
:return: True if the dict exists and has no 200 response
"""
if not stats or not isinstance(stats, Dict):
return False
status_codes = stats.get("status_codes", {})
if not status_codes or not isinstance(status_codes, Dict):
return False
return 200 not in status_codes | 461d3deb9ec6a162dfd7f3f3c0ac73262090c35b | 6,797 |
def paralog_cn_str(paralog_cn, paralog_qual, min_qual_value=5):
"""
Returns
- paralog CN: string,
- paralog qual: tuple of integers,
- any_known: bool (any of the values over the threshold).
If paralog quality is less than min_qual_value, corresponding CN is replaced with '?' and quality
is replaced with 0. Additionally, quality is rounded down to integers.
"""
paralog_cn_str = []
new_paralog_qual = []
any_known = False
for cn, qual in zip(paralog_cn, paralog_qual):
if qual < min_qual_value:
paralog_cn_str.append('?')
new_paralog_qual.append(0)
else:
paralog_cn_str.append(str(cn))
new_paralog_qual.append(int(qual))
any_known = True
return ','.join(paralog_cn_str), tuple(new_paralog_qual), any_known | 07012dd9b065622365798ba65024c316cdb8c0c7 | 6,800 |
def offbyK(s1,s2,k):
"""Input: two strings s1,s2, integer k
Process: if both strings are of same length, the function checks if the
number of dissimilar characters is less than or equal to k
Output: returns True when conditions are met otherwise False is returned"""
if len(s1)==len(s2):
flag=0
for i in range(len(s1)):
if s1[i]!=s2[i]:
flag=flag+1
if flag==k:
return True
else:
return False
else:
return False | a64c02b85acca64427852fc988ed2f769f750aa7 | 6,801 |
def SmiNetDate(python_date):
"""
Date as a string in the format `YYYY-MM-DD`
Original xsd documentation: SmiNetLabExporters datumformat (ÅÅÅÅ-MM-DD).
"""
return python_date.strftime("%Y-%m-%d") | 8d43d99516fed915b344f42da8171689f8f9ef0b | 6,802 |
def then(value):
"""
Creates an action that ignores the passed state and returns the value.
>>> then(1)("whatever")
1
>>> then(1)("anything")
1
"""
return lambda _state: value | 5cf3f7b64b222a8329e961fa6c8c70f6c2c4cab0 | 6,808 |
def get_coverage_value(coverage_report):
"""
extract coverage from last line:
TOTAL 116 22 81%
"""
coverage_value = coverage_report.split()[-1].rstrip('%')
coverage_value = int(coverage_value)
return coverage_value | ffd47b6c4ecec4851aab65dcb208ef776d12e36f | 6,811 |
from typing import Iterable
from typing import Mapping
def _iter_but_not_str_or_map(maybe_iter):
"""Helper function to differ between iterables and iterables that are
strings or mappings. This is used for pynads.concrete.List to determine
if an iterable should be consumed or placed into a single value tuple.
"""
return (isinstance(maybe_iter, Iterable) and
not isinstance(maybe_iter, (str, Mapping))) | 3dab46cfd2d2d19bd0fa744370b9059d6a0683bc | 6,815 |
import re
def to_snake_case(s):
"""Convert a string to snake-case format
Parameters
----------
s: String
String to convert to snake-case
Returns
-------
String
Snake-case formatted string
Notes
-----
Adapted from https://gist.github.com/jaytaylor/3660565
Examples
--------
>>> to_snake_case("snakesOnAPlane") == "snakes_on_a_plane"
True
>>> to_snake_case("SnakesOnAPlane") == "snakes_on_a_plane"
True
>>> to_snake_case("snakes_on_a_plane") == "snakes_on_a_plane"
True
>>> to_snake_case("IPhoneHysteria") == "i_phone_hysteria"
True
>>> to_snake_case("iPhoneHysteria") == "i_phone_hysteria"
True
"""
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", s)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() | cf3ca065c471ed526ab15de5d6c07e9be74ddb59 | 6,824 |
def is_help_command(command):
"""
Checks that the user inputted command is a help command, which will not go over the wire.
This is a command with -h or --help.
The help functionality is triggered no matter where the -h appears in the command (arg ordering)
:param command: a list of strings representing the command, for example, ['node', 'list', '-h']
:return: True if it is a help command. False otherwise.
"""
for segment in command:
if segment in ('-h', '--help'):
return True
return False | e68142c38d734e492f9f65dfdf04ac87f79bd666 | 6,827 |
import math
def num_k_of_n(n: int, k: int) -> int:
"""Return number of combinations of k elements out of n."""
if k > n:
return 0
if k == n:
return 1
return math.factorial(n) // (math.factorial(k) * math.factorial((n - k))) | de99dd88fc6e747421e36c698a525b7e58b1e4de | 6,832 |
def from_Point(ros_pt):
"""From ROS Point to Klamp't point"""
return [ros_pt.x,ros_pt.y,ros_pt.z] | 34d83ea0266883679c7e2f51c4eb555e189940d4 | 6,836 |
def realm_from_principal(principal):
"""
Attempt to retrieve a realm name from a principal, if the principal is fully qualified.
:param principal: A principal name: [email protected]
:type: principal: str
:return: realm if present, else None
:rtype: str
"""
if '@' not in principal:
return
else:
parts = principal.split('@')
if len(parts) < 2:
return
return parts[-1] | 1880fef7b4383edc6f2ccd94958200686d500e0c | 6,841 |
def filtertime(timestamp, interval):
"""Check if timestamp is between timestamp_range - (time1,time2)
Args:
timestamp --> UNIX timestamp value.
interval --> `Tuple` of 2 UNIX timestamp values.
Returns:
`bool` --> True/False
"""
T0, T1 = interval
if (timestamp <= T1) and (timestamp >= T0):
return True
else:
return False | 72fe1aa9ed01e59ad7bbe5299b4c21272fab7354 | 6,842 |
import random
def summon_blocks(board):
"""Place 1-8 circles in random places on the speed board"""
for _ in range(random.randint(1, 8)):
x = random.randint(0, 4)
y = random.randint(0, 4)
while board[x][y] != 'g':
x = random.randint(0, 4)
y = random.randint(0, 4)
board[x][y] = 'b'
return board | 0cfa703b6451e44ea8688561bc857ac70f560c90 | 6,845 |
def scope_to_list(scope):
"""Convert a space separated string to a list of scopes."""
if isinstance(scope, list) or scope is None:
return scope
else:
return scope.split(" ") | c806f91192f86dbc42719787d9ddfe0d79690f0c | 6,846 |
import math
def frequencyToMidi(frequency):
"""
Convert a given frequency in Hertz to its corresponding MIDI pitch number (60 = Middle C)
"""
return int(round(69 + 12 * math.log(frequency / 440.0, 2))) | 29d4b92b9deacb81f768b554200c4b63b632bf23 | 6,849 |
def has_enabled_clear_method(store):
"""Returns True iff obj has a clear method that is enabled (i.e. not disabled)"""
return hasattr(store, 'clear') and ( # has a clear method...
not hasattr(store.clear, 'disabled') # that doesn't have a disabled attribute
or not store.clear.disabled
) | 28ee30f92d44d14300e30fec0de37a2a241c8e92 | 6,856 |
import torch
def coin_flip(prob):
"""
Return the outcome of a biased coin flip.
Args:
prob: the probability of True.
Returns: bool
"""
return prob > 0 and torch.rand(1).item() < prob | 672929fb49a0e65101a4bdfdd13e981ae5eae31c | 6,858 |
def to_pass(line):
"""
Replace a line of code with a pass statement, with
the correct number of leading spaces
Arguments
----------
line : str, line of code
Returns
----------
passed : str, line of code with same leading spaces
but code replaced with pass statement
"""
# the number of leading spaces on the line
spaces = len(line) - len(line.lstrip(' '))
# replace statement with pass and correct leading spaces
passed = (' ' * spaces) + 'pass'
return passed | f8444ecc38523aaef13d535258974881956e30b9 | 6,860 |
def broadcastable_to_str(b):
"""Return string representation of broadcastable."""
named_broadcastable = {
(): "scalar",
(False,): "vector",
(False, True): "col",
(True, False): "row",
(False, False): "matrix",
}
if b in named_broadcastable:
bcast = named_broadcastable[b]
else:
bcast = ""
return bcast | 35dbe968a8341d076a264333c68fb597212439bc | 6,863 |
def New_Dataframe(old_df,indicator_name):
""" create a new dataframe that is composed of only one indicator
Args:
old_df (dataframe): general dataframe from which we extract the new one
indicator_name (string): Name onf the indicator that will composed the new dataframe
Returns:
(dataframe): dataframe composed of only the chosen indicator
"""
return old_df.loc[old_df.Indicator == indicator_name] | 5ccd394a01a70b39b64d2a12ed0aac6f39296a0a | 6,866 |
from pathlib import Path
def check_path_in_dir(file_path, directory_path):
"""
Check if a file path is in a directory
:param file_path: Full path to a file
:param directory_path: Full path to a directory the file may be in
:return: True if the file is in the directory
"""
directory = Path(directory_path)
parent = Path(file_path).parent
return parent == directory | 5e96abd89c72ea39a944e75b4548fc20b67892cd | 6,871 |
def flat_out(f, *a, **kw):
"""Flatten the output of target function."""
return f(*a, **kw).flatten() | ffe09ffbaae93657fde818de8a03cc17fee962f1 | 6,873 |
def id_for_base(val):
"""Return an id for a param set."""
if val is None:
return "No base params"
if "editor-command" in val:
return "Long base params"
if "ecmd" in val:
return "Short base params"
return "Unknown base params" | ecf54fa40195ba4de7db13874e44388a04527bed | 6,877 |
def serialize_serializable(obj, spec, ctx):
""" Serialize any class that defines a ``serialize`` method. """
return obj.serafin_serialize(spec, ctx) | 936c3b51257c60c156cd9686e38b09ec55a929f2 | 6,878 |
def parse_labels_mapping(s):
"""
Parse the mapping between a label type and it's feature map.
For instance:
'0;1;2;3' -> [0, 1, 2, 3]
'0+2;3' -> [0, None, 0, 1]
'3;0+2;1' -> [1, 2, 1, 0]
"""
if len(s) > 0:
split = [[int(y) for y in x.split('+')] for x in s.split(';')]
elements = sum(split, [])
assert all(x in range(4) for x in elements)
assert len(elements) == len(set(elements))
labels_mapping = []
for i in range(4):
found = False
for j, l in enumerate(split):
if i in l:
assert not found
found = True
labels_mapping.append(j)
if not found:
labels_mapping.append(None)
assert len(labels_mapping) == 4
else:
labels_mapping = None
return labels_mapping | d2f77876f1759e6d4093afc720e7631f1b4d9ff4 | 6,879 |
from typing import Any
import dataclasses
def _is_nested(x: Any) -> bool:
"""Returns whether a value is nested."""
return isinstance(x, dict) or dataclasses.is_dataclass(x) | 798000adfd8eb900b61be988ab6a31e1b062540d | 6,880 |
def contains_pept(name):
"""Checks if the saccharide name contains the peptide fragment,
such as EES, GS, SA etc"""
contains_pept = False
for pept_stub_name in ('_E', '_G', '_S', '_A'):
if (pept_stub_name in name) and ('_NRE' not in name):
contains_pept = True
return contains_pept | 937679a96b21766e96eb455baca51c1695412287 | 6,881 |
import torch
def check_stacked_complex(data: torch.Tensor) -> torch.Tensor:
"""
Check if tensor is stacked complex (real & imag parts stacked along last dim) and convert it to a combined complex
tensor.
Args:
data: A complex valued tensor, where the size of the final dimension might be 2.
Returns:
A complex valued tensor.
"""
return torch.view_as_complex(data) if data.shape[-1] == 2 else data | afce7ac1840ff64199c9ebc9f4222e1d3f09dafd | 6,882 |
def get_leaf_nodes(struct):
""" Get the list of leaf nodes.
"""
leaf_list = []
for idx, node in enumerate(struct):
if node['is_leaf']:
leaf_list.append(idx)
return leaf_list | 90c66e49bac0c49ef5d2c75b4c1cbe6f4fdd4b83 | 6,888 |
import time
def parse_data(driver):
"""Return a float of the current price given the driver open to the TMX page of the specific symbol."""
# The driver needs time to load the page before it can be parsed.
time.sleep(5)
content_obj = driver.find_element(by="id", value="root")
content_text = content_obj.text
price_string = content_text.split("PRICE")[1].split("CHANGE")[0].strip()
try:
price_float = float(price_string.replace("$", "").replace(",", ""))
return price_float
except ValueError as e:
raise e | 289a71909753278336c414a0b3c3854aeb60b05f | 6,893 |
def add_shift_steps_unbalanced(
im_label_list_all, shift_step=0):
"""
Appends a fixed shift step to each large image (ROI)
Args:
im_label_list_all - list of tuples of [(impath, lblpath),]
Returns:
im_label_list_all but with an added element to each tuple (shift step)
"""
return [(j[0], j[1], shift_step) for j in im_label_list_all] | 63fc45bc14e54ec5af473ec955bd45602f3c7041 | 6,894 |
def are_aabb_colliding(a, b):
"""
Return True if given AABB are colliding.
:param AABBCollider a: AABB a
:param AABBCollider b: AABB b
:return: True if AABB are colliding
:rtype bool:
"""
a_min = [a.center[i] - a.size3[i] / 2 for i in range(3)]
a_max = [a.center[i] + a.size3[i] / 2 for i in range(3)]
b_min = [b.center[i] - b.size3[i] / 2 for i in range(3)]
b_max = [b.center[i] + b.size3[i] / 2 for i in range(3)]
return (a_min[0] <= b_max[0] and a_max[0] >= b_min[0]) and \
(a_min[1] <= b_max[1] and a_max[1] >= b_min[1]) and \
(a_min[2] <= b_max[2] and a_max[2] >= b_min[2]) | e4d3174cbde1bcffb8e43a710ad2434fb9e4e783 | 6,895 |
def aic(X, k, likelihood_func):
"""Akaike information criterion.
Args:
X (np.ndarray): Data to fit on.
k (int): Free parameters.
likelihood_func (function): Log likelihood function that takes X as input.
"""
return 2 * k - 2 * likelihood_func(X) | 18ec376d15bdb8190818730b4676febdc01bd476 | 6,897 |
def construct_policy(
bucket_name: str,
home_directory: str,
):
"""
Create the user-specific IAM policy.
Docs: https://docs.aws.amazon.com/transfer/latest/userguide/
custom-identity-provider-users.html#authentication-api-method
"""
return {
'Version': '2012-10-17',
'Statement': [{
'Condition': {
'StringLike': {
's3:prefix': [
f'{home_directory}/*',
f'{home_directory}/',
f'{home_directory}',
],
},
},
'Resource': f'arn:aws:s3:::{bucket_name}',
'Action': 's3:ListBucket',
'Effect': 'Allow',
'Sid': 'ListHomeDir',
}, {
"Sid": "AWSTransferRequirements",
"Effect": "Allow",
"Action": [
"s3:ListAllMyBuckets",
"s3:GetBucketLocation",
],
"Resource": "*",
}, {
'Resource': 'arn:aws:s3:::*',
'Action': [
's3:PutObject',
's3:GetObject',
's3:DeleteObjectVersion',
's3:DeleteObject',
's3:GetObjectVersion',
's3:GetObjectACL',
's3:PutObjectACL',
],
'Effect': 'Allow',
'Sid': 'HomeDirObjectAccess',
}],
} | 650459810d01b28cc82d320a3b42592d3bb51170 | 6,898 |
def find_n_max_vals(list_, num):
"""Function searches the num-biggest values of a given list of numbers.
Returns the num maximas list and the index list wrapped up in a list.
"""
li_ = list_.copy()
max_vals = [] #the values
max_ind = []# the index of the value, can be used to get the param
while num > 0:
max_val = max(li_)
max_id = li_.index(max_val)
max_vals.append(max_val)
max_ind.append(max_id)
li_[max_id] = 0 #better than deleting
num -= 1 # count down
return [max_vals, max_ind] | 48e274a2e2feac04b285b883ce5948c8f39caff3 | 6,903 |
def is_same_float(a, b, tolerance=1e-09):
"""Return true if the two floats numbers (a,b) are almost equal."""
abs_diff = abs(a - b)
return abs_diff < tolerance | a8c10ae330db1c091253bba162f124b10789ba13 | 6,908 |
import curses
def new_border_and_win(ws):
"""
Returns two curses windows, one serving as the border, the other as the
inside from these *_FRAME tuples above.
"""
return (
curses.newwin(ws[1][1], ws[1][0], ws[0][1], ws[0][0]),
curses.newwin(ws[1][1] - 2, ws[1][0] - 2, ws[0][1] + 1, ws[0][0] + 1),
) | cec302bda38ba5fa9d0c88dbfac1c501984a96a0 | 6,915 |
def cmd(command_id):
"""
A helper function for identifying command functions
"""
def decorator(func):
func.__COMMAND_ID__ = command_id
return func
return decorator | cff8664ad18c78629bb3c1b4946be592142711e0 | 6,918 |
def xover_selection(snakes, survivors, opts, num_survivors):
""" Picks parents from the current generation of snakes for crossover
params:
snakes: list, current generation of snakes of class Snake
survivors: list, snakes of class Snake that survived
opts: dict, contains hyperparamters
num_survivors: int, how many survivors there should be
returns:
list of parents of class Snake
"""
parents = []
max_num_parents = opts["PopulationSize"] - num_survivors
while len(parents) < max_num_parents:
for survivor in survivors:
if (len(parents) < max_num_parents):
parents.append(survivor)
for snake in snakes:
if snake not in survivors:
if snake.selected:
if (len(parents) < max_num_parents):
parents.append(snake)
return parents | 990e65aac637abe8c4c6c8a661f4a039b0900ca4 | 6,919 |
import json
def credentials_from_file(file):
"""Load credentials corresponding to an evaluation from file"""
with open(file) as file:
return json.load(file) | 8f73c595b4e61757ae454b1674a7177ab4d05059 | 6,924 |
def format_date(value, format='%Y-%m-%d'):
"""Returns a formatted time string
:param value: The datetime object that should be formatted
:param format: How the result should look like. A full list of available
directives is here: http://goo.gl/gNxMHE
"""
return value.strftime(format) | 3f094918610617e644db69415d987fa770a06014 | 6,926 |
def read_file(filename):
"""Read filename; return contents as one string."""
with open(filename) as my_file:
return my_file.read() | fa4b47085f5d3ace5c011fcda27e6ffa94c7085a | 6,936 |
def external(field):
"""
Mark a field as external.
"""
field._external = True
return field | 83de43305f9655aa2be9c6b7264552bd3e2783f7 | 6,942 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.