content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def arrstrip(arr):
""" Strip beginning and end blanklines of an array """
if not arr[0]: arr.pop(0)
if not arr[-1]: arr.pop()
return arr
|
cd79ce4fe12c864e0b57f1513962e3123e291b8d
| 36,460 |
def evaluate_part_two(expression: str) -> int:
"""Solve the expression giving preference to additions over multiplications"""
while "+" in expression:
expression_list = expression.split()
i = expression_list.index("+")
new_expression = str()
for j, char in enumerate(expression_list):
if j in [i, i - 1]:
pass
elif j == i + 1:
new_expression += str(eval(f"{expression_list[i - 1]} + {expression_list[i + 1]}")) + " "
else:
new_expression += char + " "
expression = new_expression.strip()
return eval(expression)
|
5e9a28a0ca079abcfc364ce3085dbfd3ef3a695e
| 36,463 |
def markdown_image(url):
"""Markdown image markup for `url`."""
return ''.format(url)
|
df17ec7e51b8b5ad10e1e489dd499aa840dbc45b
| 36,467 |
def task_exists(twarrior, task_name: str) -> bool:
"""
Check if task exists before inserting it
in Task Warrior.
"""
tasks = twarrior.load_tasks()
for key in tasks.keys():
for task in tasks[key]:
if task['description'] == task_name:
return True
return False
|
1a5dbd790b11492c7417b7611c7f62af544a7862
| 36,471 |
def select_coefs(model_coefs, idx):
"""
Auxiliary function for compute_couplings().
Used to select the desired subvector/submatrix from the vector/matrix
of model coefficients.
"""
if len(model_coefs.shape) == 1: # Binomial case
sel_coefs = model_coefs[range(idx, idx + 20)]
else: # Multinomial case
sel_coefs = model_coefs[:, range(idx, idx + 20)]
return sel_coefs, idx + 20
|
b8a90fa20c5dc4ff9630291466eeaaea2f44046b
| 36,479 |
def _normalize_site_motif(motif):
"""Normalize the PSP site motif to all caps with no underscores and return
the preprocessed motif sequence and the position of the target residue
in the motif (zero-indexed)."""
no_underscores = motif.replace('_', '')
offset = motif.find(no_underscores)
respos = 7 - offset
return (no_underscores.upper(), respos)
|
6758ff876b123eba86ec623753c49007baa07431
| 36,482 |
from typing import Dict
from typing import Any
import json
def _serialize_content_with_header(content: Dict[str, Any]) -> bytes:
"""Writes serialized LSP message that includes a header and content."""
serialized_content = json.dumps(content).encode("utf-8")
# Each header parameter is terminated by \r\n, and the header itself is also
# terminated by \r\n.
header = (f"Content-Length: {len(serialized_content)}\r\n"
"Content-Type: application/vscode-jsonrpc;charset=utf-8\r\n"
"\r\n")
return header.encode("utf-8") + serialized_content
|
5058de8a604cf626616011220b6c20dd17a61c9c
| 36,484 |
import random
def normalDistrib(a, b, gauss=random.gauss):
"""
NOTE: assumes a < b
Returns random number between a and b, using gaussian distribution, with
mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve
between a and b.
For ease of use, outlying results are re-computed until result is in [a, b]
This should fit the remaining .3% of the curve that lies outside [a, b]
uniformly onto the curve inside [a, b]
------------------------------------------------------------------------
http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
The 68-95-99.7% Rule
====================
All normal density curves satisfy the following property which is often
referred to as the Empirical Rule:
68% of the observations fall within 1 standard deviation of the mean.
95% of the observations fall within 2 standard deviations of the mean.
99.7% of the observations fall within 3 standard deviations of the mean.
Thus, for a normal distribution, almost all values lie within 3 standard
deviations of the mean.
------------------------------------------------------------------------
In calculating our standard deviation, we divide (b-a) by 6, since the
99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
"""
while True:
r = gauss((a+b)*.5, (b-a)/6.)
if (r >= a) and (r <= b):
return r
|
cbb6d6e10998a46c7686956820987fb5e125a598
| 36,489 |
def read_object(self, obj):
"""
Read an object file, enabling injection in libs/programs. Will trigger a rebuild if the file changes.
:param obj: object file path, as string or Node
"""
if not isinstance(obj, self.path.__class__):
obj = self.path.find_resource(obj)
return self(features='fake_obj', source=obj, name=obj.name)
|
973e4bce06d28243a3ebf07a9f945509730af7c1
| 36,490 |
def convert_to_bool(b_str:str):
"""Converts a string to a boolean.
b_str (str): A string that spells out True or False, regardless of
capitilisation.
Return bool
"""
if not isinstance(b_str, str):
raise TypeError("Input must be a string.")
if b_str.upper() == "TRUE":
return True
elif b_str.upper() == "FALSE":
return False
else:
raise ValueError("Please check your spelling for True or False.")
|
52dddf84d1bdd0e72774104c2b736989d941a196
| 36,492 |
def _as256String(rgb):
"""
Encode the given color as a 256-colors string
Parameters:
rgb (tuple): a tuple containing Red, Green and Blue information
Returns:
The encoded string
"""
redRatio = (0 if rgb[0] < 75 else (rgb[0] - 35) / 40) * 6 * 6
greenRatio = (0 if rgb[1] < 75 else (rgb[1] - 35) / 40) * 6
blueRatio = (0 if rgb[2] < 75 else (rgb[2] - 35) / 40) + 16
return "5;{}".format(int(redRatio + greenRatio + blueRatio))
|
cbefff1dcb11be3e74f5b12bb02fbc897f1e5d07
| 36,495 |
def new(name, num_servings):
""" Create and return a new recipe.
"""
return {'name' : name,
'num_servings' : num_servings,
'instructions' : [],
'ingredients' : []}
|
d8d864308a962307514a4966eb226a95d7c0fb05
| 36,496 |
def label_rs_or_ps(player_data_list, label):
"""Adds label of either RS or PS.
Args:
player_data_list: player data list
label: RS or PS
Returns:
Labels data RS or PS
"""
return [[*year, label] for year in player_data_list]
|
1fd4d87df1b656bb3a90c6fe8d2ce4ba2f62b508
| 36,497 |
import itertools
def get_grid(args):
""" Make a dict that contains every combination of hyperparameters to explore"""
# Make a list of every value in the dict if its not
for k, v in args.items():
if type(v) is not list:
args[k] = [v]
# Get every pairwise combination
hyperparam, values = zip(*args.items())
grid = [dict(zip(hyperparam, v)) for v in itertools.product(*values)]
return grid
|
ef29106e3bc27359f5e27ae2acd4984e85e8489d
| 36,500 |
def get_5_cards(deck):
"""Return a list of 5 cards dealt from a given deck."""
l =[]
for i in range(5):
l.append(deck.deal_card())
return l
|
c7b6cf751a144e7d4b0dccb40a92dbb3cc3022c9
| 36,504 |
def GetBuildersWithNoneMessages(statuses, failing):
"""Returns a list of failed builders with NoneType failure message.
Args:
statuses: A dict mapping build config names to their BuilderStatus.
failing: Names of the builders that failed.
Returns:
A list of builder names.
"""
return [x for x in failing if statuses[x].message is None]
|
207a71f5a3965609b41da424492a316d03df0d7d
| 36,505 |
def str_name_value(name, value, tab=4, ljust=25):
"""
This will return a str of name and value with uniform spacing
:param name: str of the name
:param value: str of the value
:param tab: int of the number of spaces before the name
:param ljust: int of the name ljust to apply to name
:return: str of the formatted string
"""
rep_name = (name.startswith('_') and name[1:]) or name
try:
return ' ' * tab + str(rep_name).ljust(ljust) + \
str(value).replace('\n', '\n' + ' ' * (ljust + tab))
except:
rep_name = "Exception in serializing %s value" % name
return ' ' * tab + str(rep_name).ljust(ljust) + \
str(value).replace('\n', '\n' + ' ' * (ljust + tab))
|
fdcbba230e6045c3f84bc050cf3774fe0e4c6036
| 36,509 |
def verbose_name(instance, field_name=None):
"""
Returns verbose_name for a model instance or a field.
"""
if field_name:
return instance._meta.get_field(field_name).verbose_name
return instance._meta.verbose_name
|
50e3c9c341e5cd8e259b00807daf068edc2a1772
| 36,511 |
def findClosestValueInBST(bst , target):
"""
You are given a BST data structure consisting of BST nodes.
Each BST node has an integer value stored in a property
called "value" and two children nodes stored in properties called
"left" and "right," respectively. A node is said to be a
BST node if and only if it satisfies the BST property:
its value is strictly greater than the values of every
node to its left; its value is less than or equal to the
values of every node to its right; and both of its children
nodes are either BST nodes themselves or None (null) values.
You are also given a target integer value; write a function
that finds the closest value to that target value contained in the BST.
Assume that there will only be one closest value.
"""
currentNode = bst
closs_val = 0
while(currentNode is not None):
if((target - closs_val) >abs(target - currentNode.value)):
closs_val = currentNode.value
if target > currentNode.value:
# print(currentNode.right.value)
currentNode = currentNode.right
elif target<currentNode.value:
currentNode = currentNode.left
else:
break
return closs_val
|
8b91b6cea5350babfafb43698eac4d9aef79662d
| 36,513 |
import re
from typing import OrderedDict
def _make_str_data_list(filename):
"""
read pickle_list file to make group of list of pickle files.
group id is denoted in front of the line (optional).
if group id is not denoted, group id of -1 is assigned.
example:
0:file1.pickle
0:file2.pickle
14:file3.pickle
"""
h = re.compile("([0-9]+):(.*)")
data_list = OrderedDict()
with open(filename, 'r') as fil:
for line in fil:
m = h.match(line.strip())
if m:
group_id, file_name = m.group(1), m.group(2)
else:
group_id, file_name = -1, line.strip()
if group_id not in data_list:
data_list[group_id] = []
data_list[group_id].append(file_name)
return data_list.values()
|
cf69c678c8cf0b544d6d811034c1efe94370e08e
| 36,515 |
def get_description_data(description):
"""If description is set will try to open the file (at given path), and read the contents.
To use as the description for the MR.
Args:
description (str): Path to description for MR.
Returns
str: The description to use for the MR.
Raises:
OSError: If couldn't open file for some reason.
"""
description_data = ""
if description:
try:
with open(description) as mr_description:
description_data = mr_description.read()
except FileNotFoundError:
print(f"Unable to find description file at {description}. No description will be set.")
except OSError:
print(f"Unable to open description file at {description}. No description will be set.")
return description_data
|
e1594ef02f9f33443e24fac76f186846912a45fa
| 36,517 |
def order(request):
"""
A possible bond order.
"""
return request.param
|
7d5d9bc55d1b839c5df19caa560889901e6dd009
| 36,519 |
import grp
def gid_to_name(gid):
"""
Find the group name associated with a group ID.
:param gid: The group ID (an integer).
:returns: The group name (a string) or :data:`None` if :func:`grp.getgrgid()`
fails to locate a group for the given ID.
"""
try:
return grp.getgrgid(gid).gr_name
except Exception:
return None
|
abde4a17fccd88add0392a4185f2db40753ccae0
| 36,522 |
def have_binaries(packages):
"""Check if there are any binaries (executables) in the packages.
Return: (bool) True if packages have any binaries, False otherwise
"""
for pkg in packages:
for filepath in pkg.files:
if filepath.startswith(('/usr/bin', '/usr/sbin')):
return True
return False
|
f270defa5f9ab141692bf17fc91d1580989437de
| 36,523 |
def get_param_names(df):
"""Get the parameter names from df.
Since the parameters are dynamically retrieved from the df,
this function ensures that we have a consistent and correct mapping
between their names and values across the callbacks.
"""
return sorted(col for col in df.columns if col.startswith("param_"))
|
8def5a18c717dffb3d07da006cc0a04efbf1cf8d
| 36,527 |
def div_roundup(a, b):
""" Return a/b rounded up to nearest integer,
equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
without possible floating point accuracy errors.
"""
return (int(a) + int(b) - 1) // int(b)
|
cb44ec46b1867e56906edeb99f64f7aedd088482
| 36,529 |
def _point_cloud_error_balltree(src_pts, tgt_tree):
"""Find the distance from each source point to its closest target point
Uses sklearn.neighbors.BallTree for greater efficiency
Parameters
----------
src_pts : array, shape = (n, 3)
Source points.
tgt_tree : sklearn.neighbors.BallTree
BallTree of the target points.
Returns
-------
dist : array, shape = (n, )
For each point in ``src_pts``, the distance to the closest point in
``tgt_pts``.
"""
dist, _ = tgt_tree.query(src_pts)
return dist.ravel()
|
6a5c37b639bbb4f0bc971c482834a47d560fd8e4
| 36,530 |
def __get_default_resource_group() -> str:
"""Get the resource group name for player account"""
return 'CloudGemPlayerAccount'
|
c77a4f29292f3c761b2bd687456bb1e60114173c
| 36,534 |
def matrixAsList( matrix, value = True ):
"""
Turns a matrix into a list of coordinates matching the specified value
"""
rows, cols = len( matrix ), len( matrix[0] )
cells = []
for row in range( rows ):
for col in range( cols ):
if matrix[row][col] == value:
cells.append( ( row, col ) )
return cells
|
837944d212635cff0b01549b4397624a4e4bbfd9
| 36,537 |
def is_next_month(first_date, second_date):
""" Return True if second_date is in following month to first_date """
return (second_date.month - first_date.month) + \
(second_date.year - first_date.year) * first_date.month == 1
|
bd22ffd4ffd7dba142090130015de50f9a079945
| 36,538 |
def convert_title(x) -> str:
"""Trim trailing characters on the title"""
return x.strip()
|
a63ccc9886fc16f936ce38fba37e3b6c6b7d0fba
| 36,539 |
def GetFileExt(path, add_dot=False):
""" Returns the filetype extension from the given file path.
:param str path: file path
:param boolean add_dot: whether to append a period/dot to the returned extension
:returns str: filetype extension (e.g: png)
"""
ext = path.split(".")
ext.reverse()
if add_dot == True:
return ".{}".format(ext[0])
else:
return ext[0]
|
149b5df42b0f37b2414e6c1ef46b9a35a8308fdf
| 36,541 |
def unit_conversion(array, unit_prefix, current_prefix=""):
"""
Converts an array or value to of a certain
unit scale to another unit scale.
Accepted units are:
E - exa - 1e18
P - peta - 1e15
T - tera - 1e12
G - giga - 1e9
M - mega - 1e6
k - kilo - 1e3
m - milli - 1e-3
u - micro - 1e-6
n - nano - 1e-9
p - pico - 1e-12
f - femto - 1e-15
a - atto - 1e-18
Parameters
----------
array : ndarray
Array to be converted
unit_prefix : string
desired unit (metric) prefix (e.g. nm would be n, ms would be m)
current_prefix : optional, string
current prefix of units of data (assumed to be in SI units
by default (e.g. m or s)
Returns
-------
converted_array : ndarray
Array multiplied such as to be in the units specified
"""
UnitDict = {
'E': 1e18,
'P': 1e15,
'T': 1e12,
'G': 1e9,
'M': 1e6,
'k': 1e3,
'': 1,
'm': 1e-3,
'u': 1e-6,
'n': 1e-9,
'p': 1e-12,
'f': 1e-15,
'a': 1e-18,
}
try:
Desired_units = UnitDict[unit_prefix]
except KeyError:
raise ValueError(
"You entered {} for the unit_prefix, this is not a valid prefix".
format(unit_prefix))
try:
Current_units = UnitDict[current_prefix]
except KeyError:
raise ValueError(
"You entered {} for the current_prefix, this is not a valid prefix"
.format(current_prefix))
conversion_multiplication = Current_units / Desired_units
converted_array = array * conversion_multiplication
return converted_array
|
202725b01912532a6e899e6dbaff1e5edfbef7e0
| 36,542 |
def second(x, y):
"""Second argument"""
return y
|
2a66d4dc0ea831537af565cd8ad03f16ad54b554
| 36,549 |
def epiweek_to_month(ew):
"""
Convert an epiweek to a month.
"""
return (((ew - 40) + 52) % 52) // 4 + 1
|
95403f0ef57d4dece759cc7922e3bf295d08c459
| 36,550 |
import torch
def masked_function(function, *inputs, mask=None, restore_shape=True):
"""
Apply a function to the masked part of an input tensor.
:param function: The function to apply.
:param inputs: Input tensor, shape (N* x hidden)
:param mask: Mask, shape (N*) or broadcastable, optional
:return: The output of applying the function to only the masked part of the tensor,
but in the original shape
"""
if mask is None:
return function(*inputs)
valid_indices = torch.nonzero(mask.view(-1)).squeeze(1)
# remember the original shape
original_shape = inputs[0].size()
num_items = torch.prod(original_shape[:-1])
clean_inputs = []
for inp in inputs:
flat_input = inp.view(-1, original_shape[-1])
clean_inputs.append(flat_input.index_select(0, valid_indices))
# forward pass on the clean input only
clean_output = function(*clean_inputs)
if not restore_shape:
return clean_output
# after that, scatter the output (the position where we don't scatter are masked zeros anyways)
flat_output = inputs[0].new_zeros(num_items, clean_output.size(-1))
flat_output.index_copy_(0, valid_indices, clean_output)
output = flat_output.view(*original_shape[:-1], clean_output.size(-1))
return output
|
35fbacad265a94b409131ec74d84b87c824f0c8a
| 36,552 |
def _determine_dimensions(ideal_dimensions, current_dimensions):
"""
ideal_dimensions: dimensions we want an image to fit into (width, height)
current_dimensions: the dimensions the image currently has (width, height)
returns the dimensions the image should be resized to
"""
current_width = current_dimensions[0]
current_height = current_dimensions[1]
ideal_width = ideal_dimensions[0]
ideal_height = ideal_dimensions[1]
width_diff = current_width - ideal_width
height_diff = current_height - ideal_height
if (width_diff <= 0) and (height_diff <= 0):
return current_dimensions
if width_diff > height_diff:
return ideal_width, int((ideal_width / current_width) * current_height)
else:
return int((ideal_height / current_height) * current_width), ideal_height
|
5954ca209b6d8aa12480944d53346035379cd4c7
| 36,558 |
import requests
def genderize(first_name):
""" Use genderize.io to return a dictionary with the result of the
probability of a first name being of a man or a woman.
Example: {'count': 5856,
'gender': 'male',
'name': 'Alex',
'probability': '0.87'}
Parameters
----------
first_name: str
Returns
-------
query_result: dict
"""
return requests.get("https://api.genderize.io/", params={"name": first_name}).json()
|
dd6d107ce28bec3a5149f815ae15865cf34205be
| 36,569 |
def import_sensors_from_device(client, device):
"""
Imports sensor data of specified devices from the Rayleigh Connect API
:param client: An instance of the RayleighClient class
:param device: A list of Node objects describing the Rayleigh devices
:return: A JSON object containing the sensors for each device, retrieved from the Rayleigh Connect API
"""
return client.retrieve_sensors(device)
|
275f818cb56aa244e79aa5b9b3ad077472026e0e
| 36,578 |
def get_years(start_time, stop_time):
"""Get years contained in a time period.
Returns the list of years contained in between the provided
start time and the stop time.
:param start_time: Start time to determine list of years
:type start_time: str
:param stop_time: Stop time to determine list of years
:type stop_time: str
:return: Creation date
:rtype: list of str
"""
years = []
start_year = start_time.split("-")[0]
finish_year = stop_time.split("-")[0]
year = int(start_year)
while year <= int(finish_year):
years.append(str(year))
year += 1
return years
|
9d8073933f7dfe4c2917b1eb95e38700e30b3243
| 36,579 |
def and_join(items: list[str], sep: str = ", ") -> str:
"""Joins a list by a separator with an 'and' at the very end for readability."""
return f"{sep.join(str(x) for x in items[:-1])}{sep}and {items[-1]}"
|
4ba8be63f7add4a124dce05c139a1521d83ab12e
| 36,581 |
def test_same_type(iterable_obj):
"""
Utility function to test whether all elements of an iterable_obj are of the
same type. If not it raises a TypeError.
"""
# by set definition, the set of types of the elements in iterable_obj
# includes all and only the different types of the elements in iterable_obj.
# If its length is 1, then all the elements of iterable_obj are of the
# same data-type
if len(set([type(x) for x in iterable_obj])) == 1:
# all element are of the same type: test successful!
return True
else:
raise TypeError("Iterable '{}' in input has elements of heterogeneous types: {}"
.format(iterable_obj, [type(x) for x in iterable_obj]))
|
25b48d11eef503f8a0fd78b648f5b6b273f0a8a9
| 36,582 |
def schur_representative_from_index(i0, i1):
"""
Simultaneously reorder a pair of tuples to obtain the equivalent
element of the distinguished basis of the Schur algebra.
.. SEEALSO::
:func:`schur_representative_indices`
INPUT:
- A pair of tuples of length `r` with elements in `\{1,\dots,n\}`
OUTPUT:
- The corresponding pair of tuples ordered correctly.
EXAMPLES::
sage: from sage.algebras.schur_algebra import schur_representative_from_index
sage: schur_representative_from_index([2,1,2,2], [1,3,0,0])
((1, 2, 2, 2), (3, 0, 0, 1))
"""
w = []
for i, val in enumerate(i0):
w.append((val, i1[i]))
w.sort()
i0 = []
i1 = []
for pair in w:
i0.append(pair[0])
i1.append(pair[1])
return (tuple(i0), tuple(i1))
|
b747f247c77b108e86564eb30b6f06376551c7bc
| 36,583 |
import requests
def import_web_intraday(ticker):
"""
Queries the website of the stock market data provider AlphaVantage (AV). AV provides stock,
forex, and cryptocurrency data. AV limits access for free users as such:
1. maximum of : 5 unique queries per minute, and 500 unique queries per 24h period
2. Intraday history is capped at the past five days (current + 4)
3. After-hour data is not available
The provided data is JSON formatted. The data is a series of 'ticks' for each minute during
trading hours: open (09:30am) to closing (04:00pm).
Each tick lists the following stock data: open, close, low, high, average, volume
--------
:param <ticker>: String ; ticker of a company traded on the financial markets
"""
website = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol='+ticker+'&interval=1min&apikey=’+YOUR_API_KEY+’&outputsize=full&datatype=json'
raw_json_intraday_data = requests.get(website)
return raw_json_intraday_data.json()
|
8d38a950923f32c805d15e8f29d83b113e4e3b5b
| 36,584 |
def command_handler(option_value):
"""Dynamically load a Python object from a module and return an instance"""
module, klass = option_value.rsplit('.',1)
mod = __import__(module, fromlist=[klass])
return getattr(mod, klass)()
|
d199b8f031c08f4e559aa66edb5a3979a295079c
| 36,586 |
def to_list(collection):
""":yaql:toList
Returns collection converted to list.
:signature: collection.toList()
:receiverArg collection: collection to be converted
:argType collection: iterable
:returnType: list
.. code::
yaql> range(0, 3).toList()
[0, 1, 2]
"""
return list(collection)
|
730c2d1b939b24f501461362e585212a353cf1b8
| 36,587 |
def safe_dict_set_value(tree_node, key, value):
"""Safely set a value to a node in a tree read from JSON or YAML.
The JSON and YAML parsers returns nodes that can be container or non-container
types. This method internally checks the node to make sure it's a dictionary
before setting for the specified key. If value is None, try to remove key
from tree_node.
Args:
tree_node: Node to set.
key: Key of the entry to be added to the node.
value: Value of the entry to be added to the node. If None, try to remove
the entry from tree_node.
Returns:
Return tree_node
"""
if not issubclass(tree_node.__class__, dict):
return tree_node
if value is None:
if key in tree_node:
del tree_node[key]
else:
tree_node[key] = value
return tree_node
|
5a6e527a2e0bde659086c75f9cca06824069cd9a
| 36,588 |
def get_next_cursor(res):
"""Extract the next_cursor field from a message object. This is
used by all Web API calls which get paginated results.
"""
metadata = res.get('response_metadata')
if not metadata:
return None
return metadata.get('next_cursor', None)
|
e5ef1daaf228a4c556387e913297998810c82511
| 36,594 |
def resource_to_type_name(resource):
"""Creates a type/name format from a resource dbo."""
return resource.type_name
|
444ce157cdef0cb54c842c2636801ec075e1db15
| 36,599 |
def get_kmers(start,end,input_alignment):
"""
Accepts as start and end position within a MSA and returns a dict of all of the kmers
:param start: int
:param end: int
:param input_alignment: dict of sequences
:return: dict of sequence kmers corresponding to the positions
"""
kmers = {}
seq_iter = input_alignment.keys()
for seq_id in seq_iter :
kmers[seq_id] = input_alignment[seq_id][start:end]
return kmers
|
d4fa3a98cb4a9bdbba4aff423df94f7898430d3c
| 36,600 |
from typing import List
from typing import Any
def stable_sort(deck: List[Any]) -> List[Any]:
"""Sort of list of object, assuming that <, ==, and > are implement for the
objects in the list.
This function implements a merge sort, which has an average performance of
O(nlog(n)) and a worst case performance of O(nlog(n)). Although merge sort
can have memory usage of O(n), because Python requires passing by value and
not by reference, this implementation uses O(nlog(n)) memory. This sort is
stable so the order between identical objects in the input array is
preserved.
Arguments:
deck: List[Any]
List of objects to be sorted
Returns:
List[Any]: sorted list of objects
"""
if len(deck) > 1:
first = stable_sort(deck[:len(deck) // 2])
last = stable_sort(deck[(len(deck) // 2):])
i = 0
j = 0
while i < len(first) or j < len(last):
if i >= len(first):
deck[i + j] = last[j]
j += 1
elif j >= len(last):
deck[i + j] = first[i]
i += 1
elif first[i] < last[j]:
deck[i + j] = first[i]
i += 1
else:
deck[i + j] = last[j]
j += 1
return deck
|
d35ab897160c0f483b924ed4527edf718e3e21d2
| 36,601 |
def get_device_model(device):
"""
Get the model of a given device
Args:
device: The device instance.
Returns:
The device model.
"""
logFile = device.adb("shell", "getprop", "ro.product.model")
return logFile.strip()
|
acea6f64f2aa6aefe6963f660d08a8bb7421cf94
| 36,610 |
import shutil
from pathlib import Path
def get_program_path(program):
"""Get full path to a program on system PATH."""
path = shutil.which(program)
if not program:
raise OSError(f"{program} not found on system $PATH")
return Path(path).resolve()
|
5422a0577527149110a77bf07a67a4ea83ed5add
| 36,613 |
def split_jaspar_id(id):
"""
Utility function to split a JASPAR matrix ID into its component base ID
and version number, e.g. 'MA0047.2' is returned as ('MA0047', 2).
"""
id_split = id.split('.')
base_id = None
version = None
if len(id_split) == 2:
base_id = id_split[0]
version = id_split[1]
else:
base_id = id
return (base_id, version)
|
d1a0646abf2650b87421b656d5abc7fb4bfa4c31
| 36,615 |
def iota(n):
"""
Return a list of integers.
"""
return list(range(n))
|
6fda33ce7e367cdf46330a6aa089571397b38535
| 36,617 |
def get_limelines_by_name(resolve_project, timeline_names):
"""
For a given list of timeline names, will output a list of timeline objects
"""
all_timelines = []
output = []
for index in range(int(resolve_project.GetTimelineCount())):
all_timelines.append(resolve_project.GetTimelineByIndex(index + 1))
for timeline_name in timeline_names:
for timeline_object in all_timelines:
if timeline_object.GetName() == timeline_name:
output.append(timeline_object)
break
return output
|
4038dfa5efd995c938ef12fd636ffd289b8977dc
| 36,624 |
def capital_recovery_factor(interest_rate, years):
"""Compute the capital recovery factor
Computes the ratio of a constant loan payment to the present value
of paying that loan for a given length of time. In other words,
this works out the fraction of the overnight capital cost you need
to pay back each year if you were to use debt to
pay for the expenditure.
Arguments
---------
interest_rate: float
The interest rate as a decimal value <= 1
years: int
The technology's economic lifetime
"""
if float(interest_rate) == 0.:
return 1. / years
else:
top = interest_rate * ((1 + interest_rate) ** years)
bottom = ((1 + interest_rate) ** years) - 1
total = top / bottom
return total
|
4a92ca527557087537973e2adfedd48279a7c59e
| 36,625 |
def ellipsis_eqiv(key):
"""
Returns whether *key* is a *tuple* of *Ellipsis* or equivalent *slice*s.
"""
return isinstance(key, tuple) and all(
k is Ellipsis or
isinstance(k, slice) and (
k.start in (None, 0) and
k.stop in (None, -1) and
k.step in (None, 1)
)
for k in key
)
|
5c0de46415afd936b9828685229f848fbf099e18
| 36,629 |
def prepare_tenant_name(ts, tenant_name, product_name):
"""
Prepares a tenant name by prefixing it with the organization shortname and returns the
product and organization record associated with it. The value of 'tenant_name' may
already contain the prefix.
Returns a dict of 'tenant_name', 'product' and 'organization'.
"""
products = ts.get_table('products')
product = products.get({'product_name': product_name})
if not product:
raise RuntimeError("Product '{}' not found.".format(product_name))
organization = products.get_foreign_row(product, 'organizations')
if '-' in tenant_name:
org_short_name = tenant_name.split('-', 1)[0]
if org_short_name != organization['short_name']:
raise RuntimeError("Tenant name '{}' must be prefixed with '{}'.".format(
tenant_name, org_short_name)
)
else:
tenant_name = '{}-{}'.format(organization['short_name'], tenant_name)
return {
'tenant_name': tenant_name,
'product': product,
'organization': organization,
}
|
e5afa36eb866e182c0ca674cb0a578a66fad242a
| 36,638 |
def linear_search(L, e):
"""
Function of linear searching a list to look for specific element
Complexity: O(n)
:param L: List-object
:param e: Element to look for
:return: Boolean value if element has been found
"""
found = False
for i in range(len(L)):
if e == L[i]:
found = True
return found
|
56d690d13ced909868943baa7ef5bc75d2f4de6a
| 36,640 |
def parse_hal_spikes(hal_spikes):
"""Parses the tag information from the output of HAL
Parameters
----------
hal_spikes: output of HAL.get_spikes() (list of tuples)
Returns a nested dictionary:
[pool][neuron] = list of (times, 1) tuples
The 1 is for consistency with the return of parse_hal_tags
"""
parsed_spikes = {}
for time, pool, neuron in hal_spikes:
if pool not in parsed_spikes:
parsed_spikes[pool] = {}
if neuron not in parsed_spikes[pool]:
parsed_spikes[pool][neuron] = []
parsed_spikes[pool][neuron].append((time, 1))
return parsed_spikes
|
fb1faba1c10845331bc2e526bbd5553289be2be7
| 36,641 |
from typing import List
from typing import Optional
def brute_force(arr: List[int], value: int) -> Optional[int]:
"""
A brute force method that runs in O(n) and thus does not satisfy the question's requirements.
We use it for comparison.
:param arr: the rotated array
:param value: the value to find in the array
:return: the index of value, or None if it does not exist
>>> brute_force([2, 3, 0, 1], 2)
0
>>> brute_force([-1, 0], 0)
1
>>> brute_force([0, 1, 2], 1)
1
>>> brute_force([13, 18, 25, 2, 8, 10], 8)
4
>>> brute_force([13, 18, 25, 2, 8, 10], 3) is None
True
"""
if arr is None or not arr or value is None:
return None
try:
return arr.index(value)
except ValueError:
return None
|
b374a81843dc827984382830b9f89d14b24a1c74
| 36,643 |
import random
def hsk_grabber(
target_hsk: float, search_str: str = "", deviation: float = 0.2, limit: int = 10
):
"""
Finds HSK sentences at `target_hsk` level, with a ± deviation of `deviation`.
Search for sentences that contain words (space-separated) with `search_str` and set a sentence output limit with `limit`.
"""
sentences = []
with open("data/sentences.tsv", "r", encoding="utf-8") as file:
for line in file.read().splitlines()[1:]:
line = line.split("\t")
in_line = True
for char in search_str.split(" "):
if char not in line[0]:
in_line = False
if in_line == True:
if (
float(line[3]) < target_hsk + deviation
and float(line[3]) > target_hsk - deviation
):
sentences.append((line[0], line[1], line[2], line[3]))
random.shuffle(sentences)
return sentences[:limit]
|
c5f5b4c6f015c309588dcbf791fded250428ab6e
| 36,646 |
from typing import List
def bip32_path_from_string(path: str) -> List[bytes]:
"""Convert BIP32 path string to list of bytes."""
splitted_path: List[str] = path.split("/")
if "m" in splitted_path and splitted_path[0] == "m":
splitted_path = splitted_path[1:]
return [int(p).to_bytes(4, byteorder="big") if "'" not in p
else (0x80000000 | int(p[:-1])).to_bytes(4, byteorder="big")
for p in splitted_path]
|
8a79d738669724ebacf6afd241f08b7773fcacba
| 36,648 |
def _get_centering_constraint_from_dmatrix(design_matrix):
""" Computes the centering constraint from the given design matrix.
We want to ensure that if ``b`` is the array of parameters, our
model is centered, ie ``np.mean(np.dot(design_matrix, b))`` is zero.
We can rewrite this as ``np.dot(c, b)`` being zero with ``c`` a 1-row
constraint matrix containing the mean of each column of ``design_matrix``.
:param design_matrix: The 2-d array design matrix.
:return: A 2-d array (1 x ncols(design_matrix)) defining the
centering constraint.
"""
return design_matrix.mean(axis=0).reshape((1, design_matrix.shape[1]))
|
47aff43f5e6658309e7c11ed2328b279a44e2243
| 36,649 |
def float_callback(input_):
"""Accepts only a float or '' as entry.
Args:
input_ (str): input to check
Returns:
bool: True if input is a float or an empty string, False otherwise
"""
if input_ != "":
try:
float(input_)
except (ValueError, TypeError):
return False
return True
|
979443f9f6efcec65a09fbc7e7b8b5281763ce7b
| 36,650 |
def __checkCanLink(context, source, source_type, message_libname, real_libs=[]):
"""
Check that source can be successfully compiled and linked against real_libs.
Keyword arguments:
source -- source to try to compile
source_type -- type of source file, (probably should be ".c")
message_libname -- library name to show in the message output from scons
real_libs -- list of actual libraries to link against (defaults to a list
with one element, the value of messager_libname)
"""
if not real_libs:
real_libs = [message_libname]
context.Message("Checking for %s..." % message_libname)
libsave = context.env.get('LIBS')
context.env.AppendUnique(LIBS=real_libs)
ret = context.TryLink(source, source_type)
context.Result( ret )
if libsave is None:
del(context.env['LIBS'])
else:
context.env['LIBS'] = libsave
return ret
|
66cc4819d684501462465308eb9f8fdeca9f3e6e
| 36,656 |
def figsize(rows=1, cols=1):
"""Default figsize for a plot with given subplot rows and columns."""
return (7 * rows, 5 * cols)
|
1269f7e6400f903249b3de5857f355aad9a53d46
| 36,664 |
def compare_lists(lst, other_lst):
""" compare two lists
:param lst: list for compare
:param other_lst: list for compare
:return: result compare
"""
return frozenset(lst) == frozenset(other_lst)
|
764ecc0974e863395407f81c435cd1eb4631d649
| 36,669 |
def bool2option(b):
"""
Get config-file-usable string representation of boolean value.
:param bool b: value to convert.
:rtype: string
:returns: ``yes`` if input is ``True``, ``no`` otherwise.
"""
return 'yes' if b else 'no'
|
0a0eec4b27cd3c062c7dbe6b1fd7625648c2f0ba
| 36,671 |
def gotoHostGnx(c, target):
"""Change host node selection to target gnx.
This will not change the node displayed by the
invoking window.
ARGUMENTS
c -- the Leo commander of the outline hosting our window.
target -- the gnx to be selected in the host, as a string.
RETURNS
True if target was found, else False
"""
if c.p.gnx == target:
return True
for p in c.all_unique_positions():
if p.v.gnx == target:
c.selectPosition(p)
return True
return False
|
22eeb26137b2f082abb32ab9fd1daedf44c08033
| 36,675 |
import click
def check(fn, error_message=None):
"""
Creates callback function which raises click.BadParameter when `fn` returns `False` on given input.
>>> @click.command()
>>> @click.option('--probability', callback=check(lambda x: 0 <= x <= 1, "--probability must be between 0 and 1 (inclusive)"))
>>> def f(probability):
>>> print('P:', probability)
"""
def f(ctx, param, value):
if fn(value):
return value
else:
if error_message is None:
msg = str(value)
else:
msg = '{}. Value: {}'.format(error_message, value)
raise click.BadParameter(msg)
return f
|
8519e6c29a1cb2843260570a8888b551d8c4987c
| 36,676 |
def surround_double_quotes(string: str) -> str:
"""Surrounds the input string with double quotes and returns the modified string.
Args:
string: String to be modified.
Returns:
str: String with double quotes.
"""
return '"' + str(string) + '"'
|
63526107bc13772e23a4d1eb198bc703cb6824b0
| 36,683 |
import itertools
def sort_and_group(iterable, key):
"""Sort an iterable and group the items by the given key func"""
groups = [
(k, list(g)) for k, g in
itertools.groupby(sorted(iterable, key=key), key=key)
]
return groups
|
e0bddcad90cc4c4e6652a6a9a8faa043dcb69ebd
| 36,685 |
def whitespace_tokenize(text):
"""Splits an input into tokens by whitespace."""
return text.strip().split()
|
266f6bb537f82e599c85c96f70675a571bf5dafd
| 36,688 |
def interpret(instruction: str) -> tuple:
"""
Split and interpret a piloting instruction and return a tuple of action and
units.
Paramaters:
instruction (str): Instruction to interpret
Returns
tuple: Tuple of action and units
"""
action, units = instruction.split(" ", 1)
units = int(units)
return (action, units)
|
5d52bbefea69aaab66a3f34cfa0f8185c9abadff
| 36,692 |
def main(args=None):
""" Main entry point of hello-world """
print('Hello World')
return 0
|
7c2032c045d7ce96e5a32a20483176c362689ab3
| 36,693 |
import hashlib
import json
def check_hash(hash: str, content: dict) -> bool:
"""Check that the stored hash from the metadata file matches the pyproject.toml file."""
# OG source: https://github.com/python-poetry/poetry/blob/fe59f689f255ea7f3290daf635aefb0060add056/poetry/packages/locker.py#L44 # noqa: E501
# This code is as verbatim as possible, with a few changes to be non-object-oriented.
_relevant_keys = ["dependencies", "dev-dependencies", "source", "extras"]
def get_hash(content: dict) -> str:
"""Returns the sha256 hash of the sorted content of the pyproject file."""
content = content["tool"]["poetry"]
relevant_content = {}
for key in _relevant_keys:
relevant_content[key] = content.get(key)
content_hash = hashlib.sha256(json.dumps(relevant_content, sort_keys=True).encode()).hexdigest()
return content_hash
return hash == get_hash(content)
|
5b4d9407c95eb2239c42dd13c5052ce011f4fa5a
| 36,694 |
def _percent_str(percentages):
"""Convert percentages values into string representations"""
pstr = []
for percent in percentages:
if percent >= 0.1:
pstr.append('%.1f' %round(percent, 1)+' %')
elif percent >= 0.01:
pstr.append('%.2f' %round(percent, 2)+' %')
else:
pstr.append('%.3f' %round(percent, 3)+' %')
return pstr
|
0e6acc22eb14e0e5dfb1f44a52dc64e076e15b33
| 36,695 |
import typing
def isunion(T) -> bool:
"""Returns whether the given type is a generic union"""
return typing.get_origin(T) == typing.Union
|
23e8095ad8e131abf079e384c850038c25b57aab
| 36,696 |
def get_non_job_argslist(details_form):
"""
Gets a list of all fields returned with the Job options forms that
shouldn't be included in the job args list put in the database.
Args:
details_form (WTForm): the JobDetails form (a form that is
used as a base for most other job
options forms)
Returns:
list: list of arguments to remove from the job_args list
"""
details_list = ['csrf_token', 'start_job']
for fieldname, value in details_form.data.items():
details_list.append(fieldname)
return details_list
|
f236bfdfd3edab88406845dda893cc4b35f9378d
| 36,703 |
def temp_dir_simulated_files(tmp_path_factory):
"""Temporal common directory for processing simulated data."""
return tmp_path_factory.mktemp("simulated_files")
|
0f1cf4b8501463b9e2dd484d68e9c74978f9b5b8
| 36,706 |
def _indent(msg, tab=' '):
"""Add indentation to a message line per line"""
res = ''
for line in msg.split('\n'):
res += tab+line+'\n'
return res
|
af871f6b9478ed4a21a0d8c8437b23942002c781
| 36,709 |
def create_payment_msg(identifier, status):
"""Create a payment payload for the paymentToken."""
payment_msg = {'paymentToken': {'id': identifier, 'statusCode': status}}
return payment_msg
|
265401c5b8c9bbc0f71cfb718157101e3b48e8de
| 36,713 |
def addElements(record,recordInfo,featureList):
"""
Input: record - node from XML File,
recordInfo - dict of info about record,
featureList - list of features to parse
Output: Updated recordInfo with text of features in featureList
"""
for entry in featureList:
try:
#Locate feature in the record
feature = record.find(entry)
#Add feature text under feature tag to record info
recordInfo[feature.tag] = feature.text.strip()
except AttributeError:
print(entry,'of type',type(entry),'in record',record,'is missing text method')
return recordInfo
|
351d06e23c6d21ee3c4da980e077dcd09b163a61
| 36,714 |
def path_to_str(pathP: list) -> str:
"""Use to get a string representing a path from a list"""
if len(pathP) < 1:
return ""
if len(pathP) < 2:
return pathP[0]
res = f"{pathP[0]} -> "
for i in range(1, len(pathP) - 1):
res += f"{pathP[i]} -> "
return res + f"{pathP[-1]}"
|
db4a2c054455e2de6a6b4c7844b3104b4706c7f4
| 36,716 |
def truncate_int(tval, time_int):
"""Truncate tval to nearest time interval."""
return((int(tval)/time_int) * time_int)
|
3c366f417ab9e84b5337814f78d7888fca4d0265
| 36,717 |
def get_cid_from_cert_lot_result(result):
"""
Get CID from a certificate-by-location query result.
The query looks like:
'[hardware_api]/201404-14986/'
This function is a parser to get 201404-14986.
:param result: elements of results queried from C3 certificate API
:return: string, CID
"""
return result['machine'].split('/')[-2]
|
724d9371411e378e1e143d9d09d6d3686e7133c7
| 36,719 |
def _create_expr(symbols, prefix='B', suffix='NK'):
"""Create einsum expr with prefix and suffix."""
return prefix + ''.join(symbols) + suffix
|
d5e0aff866f375d611b4a4fa82665a0a5447bf02
| 36,720 |
def raw_to_regular(exitcode):
"""
This function decodes the raw exitcode into a plain format:
For a regular exitcode, it returns a value between 0 and 127;
For signals, it returns the negative signal number (-1 through -127)
For failures (when exitcode < 0), it returns the special value -128
"""
if not isinstance(exitcode, int):
return exitcode
if exitcode < 0:
return -128
if (exitcode & 127) > 0:
# Signal
return -(exitcode & 127)
return exitcode >> 8
|
1146bc0303886489f10864c9511280dff8047710
| 36,727 |
def get_trigger_severity(code):
"""Get trigger severity from code."""
trigger_severity = {0: "Not classified", 1: "Information", 2: "Warning", 3: "Average", 4: "High", 5: "Disaster"}
if code in trigger_severity:
return trigger_severity[code]
return "Unknown ({})".format(str(code))
|
234c58a04f374a2f227f11b519a82b6272b7aa18
| 36,728 |
def get_attributevalue_from_directchildnode (parentnode, childname, attribute):
""" Takes a parent node element as input
Searches for the first child with the provided name under the parent node
If child is present returns the value for the requested child attribute (the returns None if
the child does not have that attributte)
Returns False if child is not found under the parent
"""
childnode = parentnode.find(childname)
if childnode is not None:
value = childnode.get(attribute)
return value
else: return False
|
cee739b8c0f79f4361f2bee4faf47465ecf06212
| 36,751 |
def get_H_O_index_list(atoms):
"""Returns two lists with the indices of hydrogen and oxygen atoms.
"""
H_list = O_list = []
for index, atom in enumerate(atoms):
if atom[0] == 'H':
H_list.append(index)
if atom[0] == 'O':
O_list.append(index)
return H_list, O_list
|
337d6809e3953172601b7a698b7fb28b96bc3720
| 36,754 |
def _one_or_both(a, b):
"""Returns f"{a}\n{b}" if a is truthy, else returns str(b).
"""
if not a:
return str(b)
return f"{a}\n{b}"
|
c206b64654817b91962a3583d08204cc02b8c003
| 36,756 |
def update_figure_data_dropdowns(_df1, _df2):
"""
:param _df1: regular season DataFrame values
:param _df2: play-off DataFrame values
:return: return lists with dictionaries for drop down menus
"""
if len(_df1) > 0:
drop_values = [{'label': 'Regular season', 'value': 'Regular season'}]
else:
drop_values = []
if len(_df2) > 0:
drop_values += [{'label': 'Play-off', 'value': 'Play-off'}]
return drop_values
|
f50fdd29946cd639b42d8883fc4c08b65d87293a
| 36,757 |
def to_bdc(number: int) -> bytes:
"""
4 bit bcd (Binary Coded Decimal)
Example: Decimal 30 would be encoded with b"\x30" or 0b0011 0000
"""
chars = str(number)
if (len(chars) % 2) != 0:
# pad string to make it a hexadecimal one.
chars = "0" + chars
bcd = bytes.fromhex(str(chars))
return bcd
|
948da3d4e50e6348a3174826c8bd9ec5c78b559c
| 36,760 |
def get_counters(cursor):
""" Fetches counters for the different database categories and returns
them in a dictionary """
counter = {}
cursor.execute('SELECT "count" FROM "counters" WHERE "category" = "genes"')
counter["genes"] = int(cursor.fetchone()[0])
cursor.execute('SELECT "count" FROM "counters" WHERE "category" = "transcripts"')
counter["transcripts"] = int(cursor.fetchone()[0])
cursor.execute('SELECT "count" FROM "counters" WHERE "category" = "vertex"')
counter["vertices"] = int(cursor.fetchone()[0])
cursor.execute('SELECT "count" FROM "counters" WHERE "category" = "edge"')
counter["edges"] = int(cursor.fetchone()[0])
cursor.execute('SELECT "count" FROM "counters" WHERE "category" = "dataset"')
counter["datasets"] = int(cursor.fetchone()[0])
cursor.execute('SELECT "count" FROM "counters" WHERE "category" = "observed"')
counter["observed"] = int(cursor.fetchone()[0])
return counter
|
761337a42b13f1e65bc21f0bf9f815a72fd9bef5
| 36,762 |
def is_arn_filter_match(arn: str, filter_arn: str) -> bool:
"""
Returns True if the given arn matches the filter pattern. In order
for an arn to be a match, it must match each field separated by a
colon(:). If the filter pattern contains an empty field, then it is
treated as wildcard for that field.
Examples:
arn=abc:def:ghi filter_arn=abc:def:ghi #exact match returns True
arn=abc:def:ghi filter_arn=abc::ghi #wildcarded match returns True
"""
arn_split = arn.split(":")
filter_arn_split = filter_arn.split(":")
# arns of different field lenth are treated as mismatch
if len(arn_split) != len(filter_arn_split):
return False
for i in range(0, len(arn_split), 1):
# filter pattern with value defined can be considered for mismatch
if filter_arn_split[i] and filter_arn_split[i] != arn_split[i]:
return False
return True
|
e94cf5852f4993386b1cbe8d6ada25c6100fb348
| 36,765 |
def calc_delay2(freq, freqref, dm, scale=None):
""" Calculates the delay in seconds due to dispersion delay.
freq is array of frequencies. delay is relative to freqref.
default scale is 4.1488e-3 as linear prefactor (reproducing for rtpipe<=1.54 requires 4.2e-3).
"""
scale = 4.1488e-3 if not scale else scale
return scale*dm*(1./freq**2 - 1./freqref**2)
|
7475f140f593692ece4976795a0fd34eba93cffd
| 36,766 |
def c_terminal_proline(amino_acids):
"""
Is the right-most (C-terminal) amino acid a proline?
"""
return amino_acids[-1] == "P"
|
f54563ff59973d398e787186a1c390da03ff8999
| 36,768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.