content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def refine_search(
ra: list, dec: list, oid: list,
id_out: list, names: list, types: list) -> list:
""" Create a final table by merging coordinates of objects found on the
bibliographical database, with those objects which were not found.
Parameters
----------
ra: list of float
List of RA
dec: list of float
List of Dec of the same size as ra.
oid: list of str
List of object ID (custom)
id_out: list of str
List of object ID returned by the xmatch with CDS
names: list of str
For matches, names of the celestial objects found
types: list of str
For matches, astronomical types of the celestial objects found
Returns
----------
out: List of Tuple
Each tuple contains (objectId, ra, dec, name, type).
If the object is not found in Simbad, name & type
are marked as Unknown. In the case several objects match
the centroid of the alert, only the closest is returned.
"""
out = []
for ra_in, dec_in, id_in in zip(ra, dec, oid):
# cast for picky Spark
ra_in, dec_in = float(ra_in), float(dec_in)
id_in = str(id_in)
# Discriminate with the objectID
if id_in in id_out:
# Return the closest object in case of many
# (smallest angular distance)
index = id_out.index(id_in)
out.append((
id_in, ra_in, dec_in,
str(names[index]), str(types[index])))
else:
# Mark as unknown if no match
out.append((id_in, ra_in, dec_in, "Unknown", "Unknown"))
return out | afaae8e9e1404e6e13cfe77c25d5bffb2dd1c91b | 119,296 |
def get_leaves(tree):
"""Return the set of leaf nodes of a random projection tree.
Parameters
----------
tree: RandomProjectionTreeNode
The root node of the tree to get leaves of.
Returns
-------
leaves: list
A list of arrays of indices of points in each leaf node.
"""
if tree.is_leaf:
return [tree.indices]
else:
return get_leaves(tree.left_child) + get_leaves(tree.right_child) | c8d446b3fe45acc85303f7dc72782a12771f92f6 | 119,298 |
import math
def squares_between(a, b):
"""Finds the number of square integers between a and b."""
count = math.floor(math.sqrt(b)) - math.floor(math.sqrt(a - 1))
return count | 484ef82b316afa6611263de23479edf184969a4a | 119,299 |
def _lib_name(lib, version = "", static = False):
"""Constructs the name of a library on Linux.
Args:
lib: The name of the library, such as "hip"
version: The version of the library.
static: True the library is static or False if it is a shared object.
Returns:
The platform-specific name of the library.
"""
if static:
return "lib%s.a" % lib
else:
if version:
version = ".%s" % version
return "lib%s.so%s" % (lib, version) | 452b582b2c59fa77db881967f33936c0e0a0b25c | 119,301 |
def is_broadcast(mac):
"""Whether or not a mac is broadcast MAC address.
Args:
mac (str): MAC address in string format (``xx:xx:xx:xx:xx:xx``). Case
insensitive.
Returns:
bool.
"""
return mac.lower() == 'ff:ff:ff:ff:ff:ff' | a1fdaf3b01eb9684e4b1038563122d589a9d86c6 | 119,305 |
def space_space_fix(text):
"""Replace "space-space" with "space".
Args:
text (str): The string to work with
Returns:
The text with the appropriate fix.
"""
space_space = ' '
space = ' '
while space_space in text:
text = text.replace(space_space, space)
return text | 4d86b682cb37e106557bd2e33d8129c3ed1465dd | 119,306 |
def reduce_rows(df, downsample):
"""Reduce number of rows in a pandas df by skipping alternate rows
Note: drops rows containing NaNs in the 'cases_mtl_0-4' column
Parameters
----------
df : pandas.core.frame.DataFrame
A pandas dataframe.
downsample : int
Factor by which to downsample dataframe. Step == input nrows // downsample
Returns
-------
pandas.core.frame.DataFrame
A pandas dataframe with a reduced number of rows
"""
df = df[df['cases_mtl_0-4'].notna()] # drop rows with no age data
last_row = df.iloc[-1, :] # always keep data for latest day
rows_to_reduce = df.iloc[0:-1, :]
nrows = rows_to_reduce.shape[0]
step = nrows // downsample
reduced_rows = rows_to_reduce.iloc[::step, :]
new_rows = reduced_rows.append(last_row)
return new_rows | 8e40aba556f7d6f2b41aea8f50c4105d7838064d | 119,309 |
import re
def parse_size_specification(spec, allow_units=True):
"""Parses a size specification used as arguments for some options
in ``qplot``. Size specifications contain two numbers separated
by an ``x``, a comma or a semicolon. Numbers are assumed to denote
inches unless they are followed by ``cm`` (to denote centimeters)
or ``mm`` (to denote millimeters).
The result is always provided in inches.
Example::
>>> parse_size_specification("")
>>> parse_size_specification("8 x 6")
(8.0, 6.0)
>>> parse_size_specification("2.54 cm; 50.8 mm")
(1.0, 2.0)
"""
spec = spec.strip()
if not spec:
return None
parts = re.split("[x;,]", spec, maxsplit=1)
if not parts:
return None
if len(parts) > 2:
raise ValueError("Size specification must contain two numbers only")
if len(parts) == 1:
parts = parts * 2
def parse_part(part):
part = part.strip().lower()
factor = 1.0
if allow_units:
if part.endswith("cm"):
factor = 2.54
part = part[:-2].strip()
elif part.endswith("mm"):
factor = 25.4
part = part[:-2].strip()
return float(part) / factor
return tuple(parse_part(part) for part in parts) | 731608257e213caaedd92046b1cb89f3ba70ff19 | 119,311 |
from typing import Counter
def digest_line(line):
"""
Parses a line into a dictionary containing letter counts.
"""
seen = Counter(line.strip())
return seen | aeb035a1bd56436fd4bf248db0ab40411714ea3f | 119,312 |
def ceil(number):
"""
Return the closest integer >= number.
"""
floored = number // 1
if number == floored:
return number
else:
return floored + 1 | 0dcd75a04fc44c5b6b7c2d0edd7cc59831b6b4cf | 119,316 |
def md_escape_underscores(text):
"""Prepend underscores with backslashes."""
return text.replace("_", r"\_") | 57791ec5b8806e8aa438510f71cca8288d3c83c9 | 119,326 |
def dict_assign(obj, key, value):
"""Chainable dictionary assignment. Returns a copy.
Parameters
----------
obj : dict
A dictionary
key : string
Which attribute to set. May be a new attribute, or overwriting an existing one
value
A value of any type
Returns
-------
dict
A new dictionary, with the given attribute set to the given value
"""
new_dict = dict(obj)
new_dict[key] = value
return new_dict | 0b019e9b7e2c8ee5ae7d58436eedc914d08d6fd9 | 119,328 |
def __combinePackage(node):
"""Combines a package variable (e.g. foo.bar.baz) into one string."""
result = [node.value]
parent = node.parent
while parent.type == "dot":
result.append(parent[1].value)
parent = parent.parent
return ".".join(result) | 9d2418ee963106f9d2b80cb73855ae5ab712b47a | 119,333 |
from typing import List
def mp_data() -> List[List[str]]:
"""Return dummy MP data for tests."""
return [
["20", "McPerson", "Pat"] + 4 * [""] + 2 * ["<Henkilo><Ammatti/></Henkilo>"],
["21", "Another", "A"] + 4 * [""] + 2 * ["<Henkilo></Henkilo>"],
] | b1c816b58823f342c204d5aa147dbf978f609f11 | 119,336 |
def maglimits(inst, wfs, site, iq, cc, sb, verbose=False):
"""
Magnitude correction for conditions
Parameters
inst: Instrument ['GMOS', 'F2']
wfs: Wavefront sensor ['OIWFS', 'PWFS1', 'PWFS2']
site: Gemini site ['N', 'S', 'mko', 'cpo']
iq: Image quality constraint ['20', '70', '85', 'Any']
cc: Cloud cover constraint [0.0, -0.3, -1.0, -3.0]
sb: Sky brightness constraint ['20', '50', '80', 'Any']
verbose Verbose output?
Return
magbright
mangmax
"""
magbright = 9999.
magfaint = 9999.
# limiting magnitudes are r-band except GNIRS OI (K-band)
# oifaint = {'GMOS-N': 16.95, 'GMOS-S': 15.65, 'F2': 16.15, 'GNIRS': 0.0}
# oibright = {'GMOS-N': 6.0, 'GMOS-S': 6.0, 'F2': 6.0, 'GNIRS': 14.0}
oifaint = {'GMOS-N': 16.95, 'GMOS-S': 15.65, 'F2': 16.15}
oibright = {'GMOS-N': 6.0, 'GMOS-S': 6.0, 'F2': 6.0}
p1faint = {'N': 15.65, 'S': 14.15}
p1bright = {'N': 7.0, 'S': 7.0}
p2faint = {'N': 15.65, 'S': 15.65}
p2bright = {'N': 7.0, 'S': 7.0}
# Magnitude corrections for conditions
dmag = 0.0
dmcc = [0.0, -0.3, -1.0, -3.0]
try:
ii = ['50', '70', '80', 'Any'].index(cc)
except Exception:
if verbose:
print("cc must be one of '50','70','80','Any'")
return magbright, magfaint
dmag += dmcc[ii]
dmiq = [0.25, 0.0, -0.25, -1.25]
try:
ii = ['20', '70', '85', 'Any'].index(iq)
except Exception:
if verbose:
print("iq must be one of '20','70','85','Any'")
return magbright, magfaint
dmag += dmiq[ii]
dmsb = [0.1, 0.0, -0.1, -0.2]
try:
ii = ['20', '50', '80', 'Any'].index(sb)
except Exception:
if verbose:
print("sb must be one of '20','50','80','Any'")
return magbright, magfaint
dmag += dmsb[ii]
if verbose:
print('Dmag = ', dmag)
if wfs == 'OIWFS':
try:
magbright = oibright[inst] + dmag
magfaint = oifaint[inst] + dmag
except Exception:
if verbose:
print('Only GMOS-N, GMOS-S, and F2 have supported OIs.')
elif wfs == 'PWFS1':
magbright = p1bright[site] + dmag
magfaint = p1faint[site] + dmag
elif wfs == 'PWFS2':
magbright = p2bright[site] + dmag
magfaint = p2faint[site] + dmag
return magbright, magfaint | 89bf25136f6ab346c9bbc0ea0e2f23b14ae3bfee | 119,344 |
def get_root_table_from_path(path):
"""extract root table name from path"""
spath = path.split('.')
if len(spath) == 0:
return path
else:
return spath[0] | f9e979c50c6e941e3ddfc7cb446b98d66bfcc571 | 119,345 |
def h2i(a):
"""Decode hex string to int"""
return int(a, 16) | 7fb0d1fafaad0ee9fe953369e785086481fc7824 | 119,350 |
def isolate_probabilistic_rows(param_df, analysis_type):
"""Filter dfs by whether the index is a number in the range 1:num_trials
(signifying a probabilistic trial)
Inputs:
param_df - a df of paramters where the indexes are strings for
deterministic scenarios and numbers for probabilistic trials
Returns:
a filtered df where all the data is for probabilistic trials
"""
num_trials = analysis_type['num_trials']
param_prob_df = param_df.loc[param_df.index.isin(range(1,num_trials+1))].copy()
return param_prob_df | 86061fbf2db9595461226eda4d609118b527c5d9 | 119,357 |
def fetch_file_type(node, default_value):
"""Return file type from *node*.
:param node: :class:`nuke.Node` instance.
:param default_value: Default value to return if no file type
is set.
:return: File type value.
"""
value = node["file_type"].value()
return value.strip() or default_value | 3be18cc35b4e1e47833981e3ffb82c1c2e90c68c | 119,358 |
def shift_tuple(vec, N):
""" Shifts a vector by N elements. Fills up with zeros. """
if N > 0:
return (0,) * N + tuple(vec[0:-N])
else:
N = -N
return tuple(vec[N:]) + (0,) * N | b0001f0c9c91ab1157c59292966cc221243bb504 | 119,359 |
def construct_lvol_bdev(client, lvol_name, size, thin_provision=False, uuid=None, lvs_name=None, clear_method=None):
"""Create a logical volume on a logical volume store.
Args:
lvol_name: name of logical volume to create
size: desired size of logical volume in bytes (will be rounded up to a multiple of cluster size)
thin_provision: True to enable thin provisioning
uuid: UUID of logical volume store to create logical volume on (optional)
lvs_name: name of logical volume store to create logical volume on (optional)
Either uuid or lvs_name must be specified, but not both.
Returns:
Name of created logical volume block device.
"""
if (uuid and lvs_name) or (not uuid and not lvs_name):
raise ValueError("Either uuid or lvs_name must be specified, but not both")
params = {'lvol_name': lvol_name, 'size': size}
if thin_provision:
params['thin_provision'] = thin_provision
if uuid:
params['uuid'] = uuid
if lvs_name:
params['lvs_name'] = lvs_name
if clear_method:
params['clear_method'] = clear_method
return client.call('construct_lvol_bdev', params) | eed8fd8f5cfde9b3cbade885c421c178a42f49d6 | 119,360 |
def isDM(channel_id):
"""Helper to check if a channel ID is for a DM"""
return channel_id.startswith("D") | bf336834102dfa9ab21f36974c477e14c4249031 | 119,365 |
def check_true(expr, ex=AssertionError, msg="expr was not True"):
"""
Raises an Exception when expr evaluates to False.
:param expr: The expression
:param ex: (optional, default AssertionError) exception to raise.
:param msg: (optional) The message for the exception
:return: True otherwise
"""
if not bool(expr):
raise ex(msg)
else:
return True | ddce313bfbfceb4c64644c8e0bb0fa7bf1ddee2a | 119,366 |
def build_mailing_list(names, domain, format="{first}.{last}@{domain}"):
"""
Infers mails from a list of names.
@param names list of strings
@param domain something like ``ensae.fr``.
@param format mail format
@return list of mails
Examples :
::
DUPRE Xavier
Everything upper case is the last name,
everything lower case is the first name.
"""
mails = []
for name in names:
words = name.split()
first = []
last = []
for w in words:
if w.upper() == w:
last.append(w)
else:
first.append(w)
first = ".".join(s.lower() for s in first)
last = ".".join(s.lower() for s in last)
mail = format.format(first=first, last=last, domain=domain)
mails.append(mail)
return mails | b7102e88710d06e7f655b40fd587fe86869c7181 | 119,370 |
def get_info(vswitch):
"""
Retrieves vswitch information from an vswitch
ID and returns it as a dictionary
"""
return {
'available_ip_address_count': vswitch.available_ip_address_count,
'cidr_block': vswitch.cidr_block,
'description': vswitch.description,
'is_default': vswitch.is_default,
'region': vswitch.region,
'status': vswitch.status,
'tags': vswitch.tags,
'vpc_id': vswitch.vpc_id,
'vswitch_id': vswitch.vswitch_id,
'vswitch_name': vswitch.vswitch_name,
'zone_id': vswitch.zone_id
} | 02e1bf17a7044973f88ed1adeb641f66d2028c22 | 119,372 |
def minimum(aabb):
"""Returns the minimum point of the AABB.
"""
return aabb[0].copy() | 36f25db55d01e41e5f8f4a1c257fb5058efc55a1 | 119,373 |
from typing import List
def target_tables() -> List[str]:
"""Build list of tables to be deserialized."""
return [
"h_customer",
"h_customer_role_playing",
"h_order",
"l_order_customer",
"l_order_customer_role_playing",
"hs_customer",
"ls_order_customer_eff",
"ls_order_customer_role_playing_eff",
] | 34583296d1c5f873a514f44a4035b9a1062d35dc | 119,374 |
import torch
def normal_sample_shape(batch_size, mean_shape, std_vector):
"""
Gaussian sampling of shape parameter deviations from the mean.
"""
device = mean_shape.device
delta_betas = torch.randn(batch_size, 10, device=device)*std_vector
shape = delta_betas + mean_shape
return shape | aaab40694339abadf7df2e6ba5d53142400bb8f5 | 119,375 |
import inspect
def get_arg_spec(function, follow_wrapped=False) -> inspect.FullArgSpec:
"""
Get the arg spec for a function.
:param function: A function.
:param follow_wrapped: Follow `__wrapped__`, defaults to False.
:return: A :class:`inspect.FullArgSpec`
"""
if follow_wrapped:
function = inspect.unwrap(function)
return inspect.getfullargspec(function) | e3e397ddbcfc341c0e02c06d693fa04ea65e6cb5 | 119,378 |
import json
def http500(msg):
"""
Create the result payload for a 500 error.
"""
if not msg:
msg = "Internal server error"
ret = json.dumps({"success": False, "message": msg}, indent=2)
return (ret, 500, {'Content-length': len(ret), 'Content-Type': 'application/json'}) | bbc3922d0f25186cff59684845729dddd49d0ef7 | 119,384 |
def extract_text(element):
"""
Returns the text from an element in a nice, readable form with whitespace
trimmed and non-breaking spaces turned into regular spaces.
"""
return element.get_attribute('textContent').replace(u'\xa0', ' ').strip() | 8d70d951076c8a1740069d3554c7025112cfb829 | 119,387 |
def get_lightness(rgb):
"""Returns the lightness (hsl format) of a given rgb color
:param rgb: rgb tuple or list
:return: lightness
"""
return (max(rgb) + min(rgb)) / 2 / 255 | 08889501174694809decd52f9764f0bbb367b514 | 119,388 |
def mod_rec_exponentiate(number, exponent, mod):
"""
Modular exponentiation - recursive method
Complexity: O(logEXPONENT)
Sometimes, when the number can be extremely big, we find
the answer modulo some other number. We can do it in both
the recursive and the serial way. For simplicity we just
implement it in the recursive method.
"""
if exponent == 0:
return 1
elif exponent % 2 == 0:
return mod_rec_exponentiate((number**2) % mod, exponent//2, mod)
else:
return number * mod_rec_exponentiate((number**2) % mod, exponent//2, mod) % mod | d7f0af22a54abdc367d8bed12c0cffecad44d0db | 119,390 |
import torch
def imgrad(dim, vs=None, which='central', dtype=None, device=None):
"""Kernel that computes the first order gradients of a tensor.
The returned kernel is intended for volumes ordered as (B, C, W, H, D).
For more information about ordering conventions in nitorch, see
`nitorch.spatial?`.
The returned kernel is ordered as (C, 1, W, H, D), and the output
components (i.e., channels) are ordered as (W, H, D).
Args:
dim (int): Dimension.
vs (tuple[float], optional): Voxel size. Defaults to 1.
which (str, optional): Gradient types (one or more):
. 'forward': forward gradients (next - centre)
. 'backward': backward gradients (centre - previous)
. 'central': central gradients ((next - previous)/2)
Defaults to 'central'.
dtype (torch.dtype, optional): Data type. Defaults to None.
device (torch.device, optional): Device. Defaults to None.
Returns:
ker (torch.tensor): Kernel that can be used to extract image gradients
(dim*len(which), 1, W, H, D)
"""
if vs is None:
vs = (1,) * dim
elif len(vs) != dim:
raise ValueError('There must be as many voxel sizes as dimensions')
coord = (0, 2) if which == 'central' else \
(1, 2) if which == 'forward' else \
(0, 1)
ker = torch.zeros((dim, 1) + (3,) * dim, dtype=dtype, device=device)
for d in range(dim):
sub = tuple(coord[0] if dd == d else 1 for dd in range(0, dim, -1))
ker[(d, 0) + sub] = -1./(vs[d]*(coord[1]-coord[0]))
sub = tuple(coord[1] if dd == d else 1 for dd in range(0, dim, -1))
ker[(d, 0) + sub] = 1./(vs[d]*(coord[1]-coord[0]))
ker = ker.reshape((dim, 1) + (3,)*dim)
return ker | 33554e0f4b66638269f7e50a8dbcb54dd3bc953f | 119,391 |
def empty_results(num_classes, num_images):
"""Return empty results lists for boxes, masks, and keypoints.
Box detections are collected into:
all_boxes[cls][image] = N x 5 array with columns (x1, y1, x2, y2, score)
Instance mask predictions are collected into:
all_segms[cls][image] = [...] list of COCO RLE encoded masks that are in
1:1 correspondence with the boxes in all_boxes[cls][image]
Keypoint predictions are collected into:
all_keyps[cls][image] = [...] list of keypoints results, each encoded as
a 3D array (#rois, 4, #keypoints) with the 4 rows corresponding to
[x, y, logit, prob] (See: utils.keypoints.heatmaps_to_keypoints).
Keypoints are recorded for person (cls = 1); they are in 1:1
correspondence with the boxes in all_boxes[cls][image].
"""
# Note: do not be tempted to use [[] * N], which gives N references to the
# *same* empty list.
all_boxes = [[[] for _ in range(num_images)] for _ in range(num_classes)]
all_segms = [[[] for _ in range(num_images)] for _ in range(num_classes)]
all_keyps = [[[] for _ in range(num_images)] for _ in range(num_classes)]
return all_boxes, all_segms, all_keyps | fe20287e3eed76c11abf2e35efa260535e735d71 | 119,400 |
def create_element(type, props=None, *children):
""" Convenience function to create a dictionary to represent
a virtual DOM node. Intended for use inside ``Widget._render_dom()``.
The content of the widget may be given as a series/list of child nodes
(virtual or real), and strings. Strings are converted to text nodes. To
insert raw HTML, use the ``innerHTML`` prop, but be careful not to
include user-defined text, as this may introduce openings for XSS attacks.
The returned dictionary has three fields: type, props, children.
"""
if len(children) == 0:
children = None # i.e. don't touch children
elif len(children) == 1 and isinstance(children[0], list):
children = children[0]
return dict(type=type,
props=props or {},
children=children,
) | 4160c04e9c3031879fab3501914f75a61139f55e | 119,407 |
def get_text(block, blocks_map):
"""Retrieves text associated with a block.
Args:
block (dict): Information related to one Block Object
blocks_map (dict): All Block objects analyzed by textract.
Returns:
str: Text associated with a Block.
"""
text = ''
if 'Relationships' in block:
for relationship in block['Relationships']:
if relationship['Type'] == 'CHILD':
for child_id in relationship['Ids']:
word = blocks_map[child_id]
if word['BlockType'] == 'WORD':
text += word['Text'] + ' '
return text | 7ab56f352316d23f5bc16d638cd81f790b617690 | 119,408 |
import string
def full_clean_cxr(sentence):
"""Removes whitespace from beginning and end of a sentence. Lowercases.
Replaces punctuation (except periods) with a space. Removes multiple spaces."""
sentence = sentence.strip()
sentence = sentence.lower()
#replace punctuation with a space
for punc in string.punctuation.replace('.',''): #for all punctuation except a period
sentence = sentence.replace(punc,' ')
#replace multiple whitespace with single
sentence = ' '.join(sentence.split())
#remove period from the end of sentence (don't remove all periods to
#preserve decimal measurements of lesions)
sentence = sentence.strip('. ')
return sentence | e40b383147530c89698c9948d49a1bbbeb752fd3 | 119,411 |
def get_isotopic_abundance_product(components):
"""
Estimates the abundance of a molecule based on the abundance of the isotopic
components.
Returns
-------
:class:`float`
Notes
------
This is essentially a simplistic activity model.
Isotopic abundances from periodictable are in %, and are hence divded by 100 here.
"""
abund = 1.0
for iso in components:
abund *= iso.abundance / 100.0
return abund | 554db46ae3ba43fab780e7c6458efa79d1927697 | 119,425 |
from typing import Set
import inspect
def get_constructor_args(cls) -> Set[str]:
"""
E.g.
class Bar():
def __init__(self, arg1, arg2):
get_constructor_args(Bar)
# returns ['arg1', 'arg2']
Args:
cls (object):
Returns: set containing names of constructor arguments
"""
return set(inspect.getfullargspec(cls.__init__).args[1:]) | 298c9aff193aecb338bd4ca2086d5e026f5b3bbb | 119,430 |
def shortest_mesh_path_length(source, destination):
"""Get the length of a shortest path from source to destination without
using wrap-around links.
Parameters
----------
source : (x, y, z)
destination : (x, y, z)
Returns
-------
int
"""
x, y, z = (d - s for s, d in zip(source, destination))
# When vectors are minimised, (1,1,1) is added or subtracted from them.
# This process does not change the range of numbers in the vector. When a
# vector is minimal, it is easy to see that the range of numbers gives the
# magnitude since there are at most two non-zero numbers (with opposite
# signs) and the sum of their magnitudes will also be their range.
return max(x, y, z) - min(x, y, z) | 05626631edf7cbd72b6e1e53e891f9f7c891071a | 119,434 |
def overlap(v1, v2):
"""determine whether affected positions of two variants overlap
"""
#if v1.pos==4589049:
# import pdb; pdb.set_trace()
pos1 = set([v1.pos+i for i in range(max([len(v1.ref), len(v1.alt)]))])
pos2 = set([v2.pos+i for i in range(max([len(v2.ref), len(v2.alt)]))])
return len(pos1.intersection(pos2))>0 | df2c4f217a498758a7be7a3e3f8001d836a4b16b | 119,440 |
def get_mosaicity_from_x(x, SIM):
"""
:param x: refinement parameters
:param SIM: simulator used during refinement
:return: float or 3-tuple, depending on whether mosaic spread was modeled isotropically
"""
eta_params = [SIM.P["eta_abc%d"%i] for i in range(3)]
eta_abc = [p.get_val(x[p.xpos]) for p in eta_params]
if not SIM.D.has_anisotropic_mosaic_spread:
eta_abc = [eta_abc[0]]*3
return eta_abc | fddf606c0cd3d667b1b2a50a065d4a7fc6c3e27b | 119,442 |
import math
def mean_anomaly_radians(time):
"""Returns mean anomaly (in radians) at time."""
return math.radians((357.528 + 0.9856003 * time) % 360) | 5725a60b0f8def4c3234374d2bab6ec436a15133 | 119,443 |
def get_header_string(search_category, search_string):
"""Returns personalized heading text depending on the passed search category."""
header_string = ""
csv_title_index = 0; csv_year_index = 1; csv_author_index = 2
if search_category == csv_title_index:
header_string = "\n\nResults books with titles containing: "
elif search_category == csv_year_index:
header_string = "\n\nResults for books published in the years: "
elif search_category == csv_author_index:
header_string = "\n\nResults for books written by: "
return header_string + search_string | 191291345dd893731e8a683b6907fbe058f6e67f | 119,448 |
def _validate_timezone(hours_offset: int):
"""Creates an int from -48 to 36 that represents the timezone
offset in 15-minute increments as per the FlashAir docs"""
param_value = int(hours_offset * 4)
assert -48 <= param_value <= 36
return param_value | e2d7dd25c0252cc8dca24ad7dbbbbf8287667a05 | 119,457 |
import re
def convert_ticker_to_variable(ticker):
"""
Convert a ticker to a valid variable name (which passes for a file name).
Based on answer from Triptych
https://stackoverflow.com/questions/3303312/how-do-i-convert-a-string-to-a-valid-variable-name-in-python
I never figured out regular expressions...
:param ticker: str
:return: str
"""
if len(ticker) == 0:
raise ValueError('Cannot deal with empty tickers')
try:
ticker = re.sub('[^0-9a-zA-Z_]', '_', ticker)
except:
raise ValueError('Cannot parse ticker: {0}'.format(ticker))
# Not sure how to this with re
if ticker[0].isdigit():
ticker = '_' + ticker
return ticker | e8ae0388fe3ec32d0898c21abf1402fb56155f85 | 119,460 |
def procdict(fname):
"""Returns a dictionary of key-values from the given file.
These are in `/proc` format::
key:[\t]*value
"""
d = dict(l.strip().split(':', 1) for l in open(fname))
for k in d:
d[k] = d[k].strip()
return d | 5f2fa87cd8a4be5a9c34fe0c89766b4db4867b49 | 119,462 |
def sourcelen(unit):
"""Returns the length of the source string"""
return len(unit.source) | daf870f14cbbd0cfff4c61016a3892c4582e4343 | 119,463 |
def search(x, k):
"""
搜索B+Tree
:param x: 根结点
:param k: 关键字
:return: (目标结点, 目标关键字索引)
"""
# 定位k的位置索引
i = x.n - 1
while i >= 0 and k < x.keys[i]:
i -= 1
if i < 0:
# 如果k小于树的最小值,关键字不存在
return None, -1
if x.is_leaf:
# 如果是叶子结点,直接定位关键字
if k == x.keys[i]:
return x, i
else:
return None, -1
# 递归搜索
return search(x.c[i], k) | 872cb553cb5bb51e19a15544812f0ccaa22d6fed | 119,465 |
def f_add_ext(fpath, ext):
"""
Append an extension if not already there
Args:
ext: will add a preceding `.` if doesn't exist
"""
if not ext.startswith('.'):
ext = '.' + ext
if fpath.endswith(ext):
return fpath
else:
return fpath + ext | 964d6bb361c0ac06936c305ab0a8d7164e27035c | 119,466 |
def factoriel( n : int ) -> int :
"""
forme non récursive de factoriel
:param n: entier positif
:return: factoriel n
"""
fact = 1
for i in range(1,n+1) :
fact *= i
return fact | 2b109aab3c70103a36c0683983271d46ba692cc0 | 119,467 |
def make_extension_validator(base_cls, fn_names=(),
attributes=('description',)):
"""Create an extension validation function checking that key methods were
overridden and attributes values provided.
Parameters
----------
base_cls : type
Base class from which the contribution should inherit.
fn_names : iterable[unicode], optional
Names of the function the extensions must override.
attributes : iterable[unicode], optional
Names of the attributes the extension should provide values for.
Returns
-------
validator : callable
Function that can be used to validate an extension contribution.
"""
def validator(contrib):
"""Validate the children of an extension.
"""
for name in fn_names:
member = getattr(contrib, name)
# Compatibilty trick for Enaml declarative function (not necessary
# for enaml compatible with Python 3)
func = getattr(member, 'im_func',
getattr(member, '__func__', None))
o_func = getattr(base_cls, name)
if not func or func is o_func:
msg = "%s '%s' does not declare a %s function"
return False, msg % (base_cls, contrib.id, name)
for attr in attributes:
if not getattr(contrib, attr):
msg = '%s %s does not provide a %s'
return False, msg % (base_cls, contrib.id, attr)
return True, ''
doc = 'Ensure that %s subclasses does override %s' % (base_cls, fn_names)
validator.__doc__ = doc
return validator | f5a6b6208c6f38bca8be2df291af808d86149340 | 119,470 |
def _to_list(x):
"""
Normalizes a list/tensor to a list.
:param x: target object to be Normalized.
:return: a list
"""
if isinstance(x, list):
return x
return [x] | fef3ce93505c7245cdc2bdfdb7a19cfdd9ac83e3 | 119,472 |
def cvt_geometry(geostr):
""" Convert geometry string to integer 4-tuple.
Parameter:
geostr - Geometry string '(widthxheight+xoffset+yoffset)
Return Value:
4-tuple (width, height, xoffset, yoffset)
"""
w = h = xoff = yoff = 0
if not geostr:
return (w, h, xoff, yoff)
off = geostr.split('+')
dim = off[0].split('x')
if len(dim) == 2: # ['width', 'height']
w = int(dim[0])
h = int(dim[1])
if len(off) == 3: # ['', 'xoffset', 'yoffset']
xoff = int(off[1])
yoff = int(off[2])
return (w, h, xoff, yoff) | 7b3c5095e58567d3d29bbd3e42ada4fde2d801b2 | 119,474 |
def make_list(value):
"""
Returns the value turned into a list.
For an integer, it's a list of digits.
For a string, it's a list of characters.
"""
return list(value) | 30492e2c59c18f5319b108a7b9cefc7bb4360f88 | 119,486 |
def invalid_usb_device_class(request):
"""
Fixture that yields a invalid USB device class.
"""
return request.param | 38a99bd6b2ea0d3c813133481c510c7731783721 | 119,487 |
def estimated_sharpe_ratio(returns):
"""
Calculate the estimated sharpe ratio (risk_free=0).
Parameters
----------
returns: np.array, pd.Series, pd.DataFrame
Returns
-------
float, pd.Series
"""
return returns.mean() / returns.std(ddof=1) | 11eff262940062db12e5802b22abc367a461739c | 119,488 |
import torch
def denormalizeimage(images, mean=(0., 0., 0.), std=(1., 1., 1.)):
"""Denormalize tensor images with mean and standard deviation.
Args:
images (tensor): N*C*H*W
mean (tuple): means for each channel.
std (tuple): standard deviations for each channel.
"""
images = images.cpu().numpy()
# N*C*H*W to N*H*W*C
images = images.transpose((0,2,3,1))
images *= std
images += mean
images *=255.0
# N*H*W*C to N*C*H*W
images = images.transpose((0,3,1,2))
return torch.tensor(images) | 0c12f207c644d34f69da9244dadadc132c934ee1 | 119,492 |
def _str(val):
"""Ensure that the val is the default str() type for python2 or 3."""
if str == bytes:
if isinstance(val, str):
return val
else:
return str(val)
else:
if isinstance(val, str):
return val
else:
return str(val, 'ascii') | 331709de9f27ef969fab88326681db2bbffd5367 | 119,495 |
from typing import Union
from typing import List
def create_list_from_parameter_value(value: Union[object, List[object], None]) -> list:
"""Many methods can either take a single value, a list or None as input. Usually we want to iterate all given
values. Therefore, this method ensures that a list is always returned.
Args:
value (Union[object, List[object], None])): The value that will be mapped onto a list representation.
Returns:
List[object]: Either an empty list or a list with all given objects.
Examples:
value = None => []
value = [] => []
value = 5 => [5]
value = [5,6] => [5,6]
"""
if not value:
# => create empty list
return []
if not isinstance(value, list):
# => create list with single value
return [value]
# => value is already a list
return value | ac6bd3acd7af04d84467dd5552bb75687e2e1086 | 119,501 |
def build_url(address, port, slug=False):
"""
Build url from address, port and optional slug.
"""
if slug:
return "http://{}:{}/{}".format(address, port, slug)
else:
return "http://{}:{}/".format(address, port) | 0e61ddac1fa2c094bd23d1f8e9ca68ff6c97145f | 119,505 |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
O(n) does not necessarily mean single-traversal. For e.g. if you traverse the array twice, that would still be an
O(n) solution but it will not count as single traversal.
Args:
input_list(list): List to be sorted
"""
# reference indexes marks the last 0 in the list and the first 2
last_zero_idx = -1
first_two_idx = len(input_list) # after the end of the list
idx = 0
output_list = input_list.copy()
# traverse
while idx < first_two_idx:
if output_list[idx] == 0: # send zero to the beginning
if idx == last_zero_idx + 1: # if it is next to the last_zero_idx, only increment the index
last_zero_idx += 1
else: # otherwise, swap elements
# in this situation, we can assume input_list[last_zero_idx + 1] is always a 1, otherwise we would have
# swapped or changed the reference indexes already
output_list[idx], output_list[last_zero_idx + 1] = output_list[last_zero_idx + 1], output_list[idx]
last_zero_idx += 1 # increment reference index of last zero in the list
elif output_list[idx] == 2:
if idx == first_two_idx - 1: # if the 2 is just before the first_two_idx, just decrement the index and it's all set
first_two_idx -= 1
else: # otherwise, send 2 to the beginning of the 2's sector
output_list[idx], output_list[first_two_idx - 1] = output_list[first_two_idx - 1], output_list[idx]
first_two_idx -= 1
# since we don't know which element is going to be swapped with the idx, idx cannot be incremented yet
continue
idx += 1
return output_list | a9c51ff650ae4360c26922984dea949e8048a27b | 119,507 |
def basename(key_or_uri):
"""
Returns the file name from an S3 URI or key. Mirrors the behavior of the os.path.basename function.
.. code-block:: python
>>> import larry as lry
>>> lry.s3.basename('s3://my-bucket/my-dir/sub-dir/my-file.txt')
my-file.txt
:param key_or_uri: An S3 URI or object key
"""
if '/' in key_or_uri:
return key_or_uri.split('/')[-1]
else:
return key_or_uri | eef870d855cf2878078bec13a9ba85d2cfa2bf31 | 119,508 |
import math
def latlng2tile_terrain(lat_deg, lng_deg, z):
"""
convert latitude, longitude and zoom into tile in x and y axis, cesium terrain rule
:param lat_deg: latitude in degree
:param lng_deg: longitude in degree
:param z: map scale (0-18)
:return: Return two parameters as tile numbers in x axis and y axis
"""
n = math.pow(2, int(z + 1))
reg = 360.0 / n
x = (lng_deg + 180.0) // reg
y = (lat_deg + 90.0) // reg
return x, y | ced47aa0ef68c329e3318d7390ba29316dd9ccb1 | 119,510 |
def get_filenames(window, bids):
"""
Return dict of buffer_id: file_name for all views in window.
Assign a substitute name to untitled buffers: <untitled buffer_id>
"""
return {
v.buffer_id(): v.file_name() or "<untitled {}>".format(v.buffer_id())
for v in window.views()
if v.buffer_id() in bids
} | 0ed8bf28264e59fa6a222b7056330da1606ec657 | 119,516 |
def lem_num(orth: str):
"""Return a nice lemma for a thing supposed to be a number"""
return "NUM" | 44560b84ac70e5aad9c81808dea7302b02cbf624 | 119,518 |
import torch
def get_device(gpu_id=-1):
"""Get a device to use.
Args:
use_gpu (int): GPU ID to use. When using the CPU, specify -1.
Returns:
torch.device: Device to use.
"""
if gpu_id >= 0 and torch.cuda.is_available():
return torch.device("cuda", gpu_id)
else:
return torch.device("cpu") | 18fa86309fba39d9e08c95b7158ff62e3ea0eb45 | 119,521 |
import click
def maybe_read_stdin(_ctx, _param, value):
"""Read the stdin if no value is provided"""
if not value and not click.get_text_stream("stdin").isatty():
return click.get_text_stream("stdin").read().strip().split(" ")
else:
return value | f8fe3344d54c248f3dc08de6a5f1ebda3bfe50d8 | 119,522 |
def validate_preprocess_kwargs(preprocessing_kwargs):
"""
Tests the arguments of preprocess function and raises errors for invalid arguments.
Parameters
----------
preprocessing_kwargs : dict-like or None or False
A dictionary object to store keyword arguments for the preprocess function.
It can also be None/False/{}/"".
Returns
-------
valid_kwargs : dict-like or None
The valid keyword arguments for the preprocess function.
Returns None if the input preprocessing_kwargs is None/False/{}/"".
Raises
------
ValueError
If preprocessing_kwargs is not dict-like or None.
If gets invalid key(s) for preprocessing_kwargs.
If gets invalid value(s) for preprocessing_kwargs['window'], preprocessing_kwargs['impute_method']
preprocessing_kwargs['impute_direction'] and preprocessing_kwargs['add_noise'].
"""
if preprocessing_kwargs:
valid_preprocessing_kwargs_keys = {'window', 'impute_method', 'impute_direction', 'add_noise'}
if not isinstance(preprocessing_kwargs,dict):
raise ValueError("The parameter 'preprocessing_kwargs' is not dict like!")
elif set(preprocessing_kwargs.keys()).issubset(valid_preprocessing_kwargs_keys):
window = 4
impute_method = 'mean'
impute_direction = 'forward'
add_noise = True
methods = ['mean', 'median', 'min', 'max']
directions = ['forward', 'fwd', 'f', 'backward', 'bwd', 'b']
if 'window' in preprocessing_kwargs.keys():
if not isinstance(preprocessing_kwargs['window'],int):
raise ValueError("The value for preprocessing_kwargs['window'] is not an integer!")
window = preprocessing_kwargs['window']
if 'impute_method' in preprocessing_kwargs.keys():
if preprocessing_kwargs['impute_method'] not in methods:
raise ValueError('invalid imputation method! valid include options: ' + ', '.join(methods))
impute_method = preprocessing_kwargs['impute_method']
if 'impute_direction' in preprocessing_kwargs.keys():
if preprocessing_kwargs['impute_direction'] not in directions:
raise ValueError('invalid imputation direction! valid include options: ' + ', '.join(directions))
impute_direction = preprocessing_kwargs['impute_direction']
if 'add_noise' in preprocessing_kwargs.keys():
if not isinstance(preprocessing_kwargs['add_noise'],bool):
raise ValueError("The value for preprocessing_kwargs['add_noise'] is not a boolean value!")
add_noise = preprocessing_kwargs['add_noise']
valid_kwargs = { 'window': window,
'impute_method': impute_method,
'impute_direction': impute_direction,
'add_noise': add_noise }
else:
raise ValueError('invalid key(s) for preprocessing_kwargs! '
'valid key(s) should include '+ str(valid_preprocessing_kwargs_keys))
else:
valid_kwargs = None
return valid_kwargs | a4f7c48f6d727cce6d2875a4e1cdcb80c98d02e9 | 119,525 |
def denormalize(T, coords):
"""
Convert coordinates in the range [-1, 1] to
coordinates in the range [0, T] where T is
the size of the image.
"""
return (0.5 * ((coords + 1.0) * T)).long() | 3512a3c072943507b9f48977ce182151e19ccbc3 | 119,541 |
def label_latexify(label):
"""
Convert a label to latex format by appending surrounding $ and escaping spaces
Parameters
----------
label : str
The label string to be converted to latex expression
Returns
-------
str
A string with $ surrounding
"""
return '$' + label.replace(' ', r'\ ') + '$' | 001b344c1cb4a0e8b2519cad5edf1719841238e2 | 119,544 |
def date_format(date):
"""Converts datetime to '%d.%m.%Y-%H:%M:%S' formatted string"""
return date.strftime("%d.%m.%Y-%H:%M:%S") | cf67b5ae9b98692f3dbd2dbbf793db3b673b54b2 | 119,548 |
def linearly_increasing_force(t_start, t_end, f_max):
"""
Returns a linearly increasing force:
f_max at t_end
-------------
/
/ |
/ |
/ |
---- |__ t_end
|__ t_start
Parameters
----------
t_start: float
time where linear force starts to raise
t_end: float
time where force reaches maximum
f_max: float
maximum value of force
Returns
-------
f: callable
function f(t)
"""
def f(t):
if t <= t_start:
return 0.0
elif t_start < t <= t_end:
return f_max * (t-t_start) / (t_end-t_start)
else:
return f_max
return f | ee4c541662cee2f72280b1d039993a172c0fa7f8 | 119,554 |
from typing import Callable
def simple_numerical_differentiation(f: Callable[[float], float], x: float) -> float:
"""Calculate the differential value for given point(x) on given function(f)
By definition, the differential value of a function is defined as follow:
diff = [lim h go to 0] (f(x + h) - f(x - h)) / 2h
# f(x) = 2x
>>> abs(simple_numerical_differentiation(lambda x: 2*x, 3) - 2) < 1e-06
True
# f(x) = 3x^3 - 2x^2 + x - 3
>>> abs(simple_numerical_differentiation(lambda x: 3*x**3 - 2*x**2 + x - 3, 1) - 6) < 1e-06
True
"""
h = 1e-4
diff = (f(x + h) - f(x - h)) / (2 * h)
return diff | 3703671a9cb7b66c26a4b70968d795d77b0ac1f9 | 119,555 |
def deal_cards(deck, how_many):
"""
Function used to deal certain number of cards.
:param deck: list with deck of cards from which cards will be dealt
:param how_many: number of cards to deal
:return: list with dealt cards, list with deck, number of dealt cards
"""
cards = []
if len(deck) >= how_many:
for _ in range(how_many):
cards.append(deck.pop())
cards_dealt = how_many
else:
cards_dealt = len(deck)
for _ in range(len(deck)):
cards.append(deck.pop())
return cards, deck, cards_dealt | 01014d6e7a427bda4138f04fbaabf98408d72e98 | 119,557 |
def distance(word1, word2):
"""
Returns the number of different letters between word1 and word2
"""
ndiffs = 0
for a, b in zip(word1, word2):
if a != b:
ndiffs += 1
return ndiffs | 06f616f87e451599b3dde3f9c41ae957fbb94f26 | 119,560 |
def trace_overall_index(batch_idx, test_time_indices):
"""
Given
batch_idx: the particular program this all corresponds to
test_time_indices: list of which (tests, timestep) to select
Returns (trace_idxs, time_idxs)
trace_idxs: the indices int the traces to be returned
time_idxs: the indices into which timesteps should be returned
"""
# this assumes 5 tests exactly
assert all(test < 5 for test, _ in test_time_indices)
return [batch_idx * 5 + test for test, _ in test_time_indices], [time for _, time in test_time_indices] | b063be90d53726d49937d6b6978d75f79617b2c1 | 119,561 |
def caffeBlob_to_imgGrayLinear(blob):
"""Take a caffe blob and turn it into an OpenCV image."""
b, c = blob.shape[:2]
if b != 1 or c != 1:
msg = ("Expecting to get 1 image in mini-batch having 1 channel, " +
"but got batch size of {} and {} channels".format(b, c))
raise ValueError(msg)
return blob[0, 0, :, :] | 3e79744ad93a6efc6ed3a58ce2b766626f960333 | 119,564 |
def get_from_subtree(subtree, key):
"""
Find the value associated to the key in the given subtree
:param subtree: the subtree to search in
:param key: the key to search for
:return: the value associated to the key in the given subtree or None if this key is not in the subtree
"""
temp_subtree = subtree
while temp_subtree is not None:
if key == temp_subtree.key:
return temp_subtree.value
elif key < temp_subtree.key:
temp_subtree = temp_subtree.left
elif key > temp_subtree.key:
temp_subtree = temp_subtree.right
return None | 8a2b27ea64f98d5020d6141ca1a2964170fb3dea | 119,565 |
def confirm(question, *, default=False):
"""Prompt the user to confirm an action."""
hint = {True: 'Y/n', False: 'y/N', None: 'y/n'}[default]
while True:
answer = input(f'{question} [{hint}] ').strip().lower()
if answer in ('y', 'yes'):
return True
elif answer in ('n', 'no'):
return False
elif not answer and default is not None:
return default
print("Please answer '(y)es' or '(n)o'.") | c7c548fbc88dfc2384184653926b92f8fa3c6ef5 | 119,566 |
import six
def upgrader(version=None):
"""
A decorator for marking a method as an upgrader from an older
version of a given object. Can be used in two different ways:
``@upgrader``
In this usage, the decorated method updates from the previous
schema version to this schema version.
``@upgrader(number)``
In this usage, the decorated method updates from the
designated schema version to this schema version.
Note that upgrader methods are implicitly class methods, as the
``Schema`` object has not been constructed at the time the
upgrader method is called. Also note that upgraders take a single
argument--a dictionary of attributes--and must return a
dictionary. Upgraders may modify the argument in place, if
desired.
:param version: The version number the upgrader converts from.
:returns: If called with no arguments or with an integer version,
returns a decorator. If called with a callable, returns
the callable.
"""
def decorator(func):
# Save the version to update from
func.__vers_upgrader__ = version
return func
# What is version? It can be None, an int, or a callable,
# depending on how @upgrader() was called
if version is None:
# Called as @upgrader(); return the decorator
return decorator
elif isinstance(version, six.integer_types):
# Called as @upgrader(1); sanity-check version and return the
# decorator
if version < 1:
raise TypeError("Invalid upgrader version number %r" % version)
return decorator
elif callable(version):
# Called as @upgrader; use version = None and call the
# decorator
func = version
version = None
return decorator(func)
else:
# Called with an invalid version
raise TypeError("Invalid upgrader version number %r" % version) | a012900845970706192f1ccf71bcb08c86562242 | 119,567 |
def IsRegionalUrlMapRef(url_map_ref):
"""Returns True if the URL Map reference is regional."""
return url_map_ref.Collection() == 'compute.regionUrlMaps' | c2597eaebbaa7812a47093405a1a59914fe01acc | 119,570 |
def last_index_of(array, value):
"""Return the last index of `value` in the given list, or -1 if it does not exist."""
result = -1
for i in reversed(range(len(array))):
entry = array[i]
if entry == value or (callable(value) and value(entry)):
return i
return result | 33b7cc3b51f4931498cae684984fec213eac6584 | 119,585 |
import re
def filter_compiler_errors(compiler_output):
"""Identify common errors that occur in compilation.
Return message to emit when error found."""
error_msg = ''
err_strings = ['could not checkout FLEXlm license']
for s in err_strings:
if re.search(s, compiler_output, re.IGNORECASE) != None:
error_msg = '(private issue #398) '
break
return error_msg | 678a1fe5f48ee7cbca38dcb8745d9184128d2148 | 119,587 |
import asyncio
import functools
def run_sync(func, *args, **kwargs):
"""
Run a synchronous function with given args via asyncio.run_in_executor and return the result
:param callable func: Any callable
:param list args: Position args to pass to `func`
:param dict kwargs: Keyword args to pass to `func`
:return asyncio.Future:
"""
return asyncio.get_event_loop().run_in_executor(None, functools.partial(func, *args, **kwargs)) | 46982df970fce9b95c8b035fc8ecfa1f3a41b694 | 119,589 |
def isSorted(lyst):
"""
Return whether the argument lyst is in non-decreasing order.
"""
for i in range(1, len(lyst)):
if lyst[i] < lyst[i-1]:
return False
return True | ce106bfc73aa0d3b1d30012c863bf95de72e3860 | 119,590 |
import numbers
import torch
def extract_item(x):
"""Extract value from single value tensor."""
if isinstance(x, numbers.Number):
return x
elif isinstance(x, torch.Tensor):
return x.item()
else:
raise ValueError('Unknown type: {}'.format(type(x))) | df3b8faecd7f190d1fcaacf66c0ade8059c78413 | 119,593 |
def getPositions(data):
"""
Get the positions that were determined by the neural network model
:param data: JSON Object
:return: Array of dance positions
"""
positions = data['pos']
return positions | c645bcdba5ee30656a172e7c7a063a9174edbc04 | 119,594 |
import torch
def get_gradient_kernel_3x3() -> torch.Tensor:
"""
Utility function that returns a gradient kernel of 3x3
in x direction (transpose for y direction)
kernel_gradient_v = [[0, -1, 0],
[0, 0, 0],
[0, 1, 0]]
kernel_gradient_h = [[0, 0, 0],
[-1, 0, 1],
[0, 0, 0]]
"""
return torch.tensor([
[0, 0, 0],
[-1, 0, 1],
[0, 0, 0],
]) | 488708bf1885e43efe3724219159a4b1c1f43d80 | 119,596 |
import re
import itertools
def get_paragraphs_below_header(soup, header_text):
"""Collect the paragraphs directly underneath a header."""
# regex to match headers 1-6
header = re.compile('^h[1-2]$')
# We need to use a lambda here because we are checking the contents of the header which is within a span
# nested inside the header
header_tag = soup.find(lambda tag: header.match(tag.name) and re.match(header_text, tag.get_text()))
# This page does not have a Transcript section
# https://www.explainxkcd.com/wiki/index.php/1116:_Traffic_Lights
body_contents = ''
if header_tag is not None:
# This is a little complicated list comprehension that iterates across the siblings of the header (i.e. the
# paragraphs tags below it) until it encounters a header which tells itertools to stop. The text in these tags
# are extracted and joined.
body_contents = ''.join([
tag.get_text()
for tag in itertools.takewhile(lambda sibling: not header.match(sibling.name),
header_tag.find_next_siblings())
])
return body_contents | 097a0e3c076182be33deb917f839aaf96757aead | 119,598 |
def soak_test(request):
"""Fixture for --soak-test."""
return request.config.getoption("--soak-test") | 1adaeeb9bbcd5af43ec62d4c2f454f12a2392da1 | 119,600 |
import string
def char2inversed_id(char):
""" Converts char to id (int) with one-hot encoding handling of unexpected characters"""
if char in string.ascii_lowercase:
return 97 + (122 - ord(char))
elif char in string.ascii_lowercase:
return 65 + (90 - ord(char))
else: # pass other characters normally
return ord(char) | fa2722b82bdc9265b726224819e7ac71e2c7fa0b | 119,606 |
def Str2Bool(string):
"""
Converts a string to Python boolean. If not 'true' in lowercase, returns
False.
:param string: a string of True or False, not cap sensitive
:return: Boolean
"""
if string == 'True' or string == 'true':
return True
else:
return False | d1058b051e22b7d8926a08e28431d32916128d0b | 119,607 |
def html_mark_warning(text):
""" Simple mark warning using html and css. """
return u"<div style='color:orange;'>%s</div>" % text | 159a2e5ed613ba718c945fcee3d8126810089527 | 119,610 |
def columnletter2num(text):
"""
Takes excel column header string and returns the equivalent column count
:param str text: excel column (ex: 'AAA' will return 703)
:return: int of column count
"""
letter_pos = len(text) - 1
val = 0
try:
val = (ord(text[0].upper())-64) * 26 ** letter_pos
next_val = columnletter2num(text[1:])
val = val + next_val
except IndexError:
return val
return val | 0a247f7da6e71f3f65179c125634b9dd453990d5 | 119,615 |
import difflib
def udiff(str_a, str_b, *, number_of_context_lines=0):
"""Compute unified diff of two strings."""
# "True" preserves line endings
lines_a = str_a.splitlines(True)
lines_b = str_b.splitlines(True)
diff_generator = difflib.unified_diff(lines_a,
lines_b,
n=number_of_context_lines)
# Conditionally skip two unneeded lines
diff_lines = list(diff_generator)[2:]
diff_str = "".join(diff_lines)
return diff_str | 4d0ae7f75e96e848daab8699e24b3f6e43875672 | 119,620 |
import jinja2
def render_template(template_string, **kwargs):
"""Render a jinja2 template."""
template = jinja2.Template(template_string)
return template.render(**kwargs) | 245fbee8ea304cd4332aa0ee3b3d12dc4806714b | 119,622 |
def parse_feature(feature, feature_id):
"""
helper for building a generic feature object
:param feature: BioPython feature
:param feature_id: some unique identifier for this feature
:return: generic feature object
"""
return {
'id': feature_id,
'protein_id': '.'.join(feature.qualifiers['protein_id']),
'label': '.'.join(feature.qualifiers['gene']),
'start': int(feature.location.start),
'end': int(feature.location.end),
'strand': feature.location.strand,
'metadata': feature.qualifiers['note']
} | 292a2dbfdfb120b57a5f98a11138f3894cbd4400 | 119,627 |
def group_dictionaries_by_key(list_of_dicts, key, remove_key=True):
"""
Takes a list of dictionaries and returns a
dictionary of lists of dictionaries with the same value for the given key.
The grouping key is removed by default.
If the key is not in any dictionary an empty dict is returned.
"""
dict_of_lists = dict()
for dicty in list_of_dicts:
if key not in dicty:
continue
dicty_value = dicty[key]
if remove_key:
dicty.pop(key)
if dicty_value in dict_of_lists:
dict_of_lists[dicty_value].append(dicty)
else:
dict_of_lists[dicty_value] = [dicty]
return dict_of_lists | 0feb9337d44912ef7cc8f4449d86cce6b96d97a6 | 119,632 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.