content stringlengths 42 6.51k |
|---|
def make_window(x, y, xmin, ymin, windowsize):
"""
Create a window for writing a child tile to a parent output tif
"""
if x < xmin or y < ymin:
raise ValueError("Indices can't be smaller than origin")
row = (y - ymin) * windowsize
col = (x - xmin) * windowsize
return (
(... |
def resolve(name, env):
"""
Resolve the value assigned to NAME by ENV, possibly via chained bindings
"""
t = name
while t in env:
t = env[t]
return t |
def missing_3mers(three_mers, vec_dict):
"""Checks that the 3mers are in the model"""
missing = [x for x in three_mers if x not in list(vec_dict.keys())]
return missing |
def __convex__hull(points):
"""Computes the convex hull of a set of 2D points.
Input: an iterable sequence of (x, y) pairs representing the points.
Output: a list of vertices of the convex hull in counter-clockwise order,
starting from the vertex with the lexicographically smallest coordinates.
... |
def deepmerge(source, destination):
"""Found at https://stackoverflow.com/a/20666342/435004"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
deepmerge(value, node)
else:
... |
def split_list_by_n(l, n):
"""Split a list into lists of size n.
Args:
l: List of stuff.
n: Size of new lists.
Returns:
list: List of lists each of size n derived from l.
"""
n = max(1, n)
return list(l[i:i+n] for i in range(0, len(l), n)) |
def filter_listing(listing, property_name, allowed_values, dict_representation=True):
"""
Removes items from the result of a listing fn if a property
does not comply with a given value.
Parameters
----------
setupid_setup : dict of dicts or objects, representing
openml objects as obtai... |
def manhattan_distance(xy_a, xy_b):
"""
Number of steps between two squares allowing only
up, down, left and right steps.
"""
x_a, y_a = xy_a
x_b, y_b = xy_b
return abs(x_a-x_b) + abs(y_a-y_b) |
def hex_rgb(argument):
"""Convert the argument string to a tuple of integers.
"""
h = argument.lstrip("#")
num_digits = len(h)
if num_digits == 3:
return (
int(h[0], 16),
int(h[1], 16),
int(h[2], 16),
)
elif num_digits == 4:
return (
... |
def isglobalelement(domains):
""" Check whether all domains are negations."""
for domain in domains.split(","):
if domain and not domain.startswith("~"):
return False
return True |
def _split_line(line):
"""Split line into leading whitespace, list of words, and trailing whitespace."""
return line[:-len(line.lstrip())], line.split(), line[len(line.rstrip()):] |
def add_metadata_defaults(md):
"""Central location for defaults for algorithm inputs.
"""
defaults = {"batch": None,
"phenotype": ""}
for k, v in defaults.items():
if k not in md:
md[k] = v
return md |
def fun(arg1: int) -> str: # comment
"""AI is creating summary for fun
:param arg1: [description]
:type arg1: int
:raises FileExistsError: [description]
:return: [description]
:rtype: str
"""
if arg1 > 1:
raise FileExistsError() # comment
return "abc" |
def normalize_metric_name(name):
"""
Makes the name conform to common naming conventions and limitations:
* The result will start with a letter.
* The result will only contain alphanumerics, underscores, and periods.
* The result will be lowercase.
* The result will not exceed 2... |
def _merge_mappings(*args):
"""Merges a sequence of dictionaries and/or tuples into a single dictionary.
If a given argument is a tuple, it must have two elements, the first of which is a sequence of keys and the second
of which is a single value, which will be mapped to from each of the keys in the sequen... |
def get_property_identities_dict(property_identities_tag, inclusion_test=None):
"""
Reads in a propertyIdentities tag and converts it to a dictionary of property identities
:param lxml._Element property_identities_tag: a tag containing propertyIdentities, or None
:param lambda inclusion_test: a test fo... |
def to_camel_case(string: str):
"""Returns a CamelCase version of the string and removes some characters (see source code)"""
string = string.title()
remove = ["_", " ", ".", "-", ":", "@", "#", "!", "?", "(", ")", "[", "]", "{", "}", "/", "\\", ",", "=", ">", "<",
"|"]
string = string.tra... |
def cyclic_partition(partition, sep="", captions=None):
"""Display a partition in cyclic form.
If the matrix has n nodes, then the partition should be given as
a list of n integers between 0 and k-1, where k is the number of
merged nodes (number of equivalence classes). Such a partition
representat... |
def largest(max) -> int:
"""
Returns the highest number fizzbuzz wihtin the max limit, if there is none, return -1
"""
while max >0:
if max % 3 == 0 and max % 5 == 0:
return max
max-= 1
return -1 |
def diff_object_types_histograms(new_histo, old_histo):
""" Returns a new histogram that is the difference of it inputs """
all_keys = set(new_histo.keys()).union(old_histo.keys())
dd = {k: new_histo[k] - old_histo[k] for k in all_keys if new_histo[k] - old_histo[k] != 0}
return dd |
def multiply(expression):
"""multiplication calculation
:param expression: string e.g. "1024*1024*50"
:return: integer
"""
value = 1
for n in expression.split('*'):
value *= int(n)
return value |
def diff(a, b):
"""Returns a new list of the differences between a and b"""
return set(b).difference(set(a)) |
def str_to_felt(text):
"""Convert from string to felt."""
b_text = bytes(text, "ascii")
return int.from_bytes(b_text, "big") |
def filter_list(list_data, min_index):
"""Filter list by index."""
return list(filter(lambda r: r[0] >= min_index, list_data)) |
def is_http_url(filepath):
"""Determine if the given path is a http(s) URL."""
return filepath.startswith("http://") or filepath.startswith("https://") |
def asbool(v, default=False):
"""
Convert v to a boolean value
"""
if isinstance(v, bool):
return v
try:
return bool(int(v))
except ValueError:
v = str(v).lower()
if v in ("true", "true", "yes", "ok"):
return True
if v in ("false", "no"):
... |
def _default_es_levels(print_keyword_dct):
""" ?
"""
es_model = {'geo': print_keyword_dct['geolvl']}
es_model['harm'] = print_keyword_dct['geolvl']
es_model['ene'] = print_keyword_dct['geolvl']
es_model['sym'] = print_keyword_dct['geolvl']
es_model['tors'] = (
print_keyword_dct['geol... |
def format_attributes(callable, *args):
"""
Format the results of *callable* in the format expected
by Graphviz.
"""
value = callable(*args)
if not value:
return ""
else:
parts = []
for k in sorted(value):
parts.append(f"{k}={value[k]}")
return f"... |
def formatInterval(secs, fmt):
"""Format an interval of length secs seconds according to format string
fmt.
fmt may contain labeled references {h}, {m} and {s} for hours, minutes
and seconds. e.g. fmt = '{h:d}:{m:02d}:{s:02d}'"""
try:
secs = int(secs)
except (TypeError, ValueError):
... |
def _get_object_description(target):
"""Return a string describing the *target*"""
if isinstance(target, list):
data = "<list, length {}>".format(len(target))
elif isinstance(target, dict):
data = "<dict, length {}>".format(len(target))
else:
data = target
return data |
def get_int(string, min=0, max=99999):
"""
Converts a string into an integer with an optional min and max range.
...
Parameters
---
string: string
a numeric string
min: integer
a number less than or equal to the requested number
max: ar... |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the in... |
def chunks(l, n):
"""splits list l into chunks of size n
Parameters
----------
l : list
list of well names
n : int
number of wells available per cell line
Returns
-------
wells_per_line : list of lists
lenght of the list equals number of cell lines
"""
n =... |
def catchments_with_station(stations):
"""
Returns a set of all catchments monitored by 'stations'.
"""
catchment_list = []
for station in stations:
catchment_list.append(station.catchment)
return set(catchment_list) |
def _scipy_distribution_positional_args_from_dict(distribution, params):
"""Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see a... |
def snake_to_pascal(snake_case: str) -> str:
"""Return a PascalCase version of a snake_case name.
Arguments:
snake_case: the string to turn into PascalCase.
"""
snake_case = snake_case.lower()
return snake_case.replace("_", " ").title().replace(" ", "") |
def altCase(text: str):
"""
Returns an Alternate Casing of the `text`.
"""
return "".join(
[
words.upper() if index % 2 else words.lower()
for index, words in enumerate(text)
]
) |
def bord(c):
"""In Python2, one calls ord(buf[i]) to get the i-th byte of
a bytestring. In Python3, buf[i] already returns an int.
Call bord(buf[i]) to achieve portability."""
if isinstance(c, int):
return c
return ord(c) |
def newArr(arr):
"""
MapReduce: O(n^2)
1. Map: construct the Map with Key is each element and Value is the array
2. Reduce: product all element of Value except the key
"""
result = []
hashmap = {}
for i in arr:
hashmap[i] = arr
for key, value in hashmap.items():
... |
def slave_entry(slave, programs, filesystems):
"""
Template tag {% slave_entry slave programms %} is used to display a single
slave.
Arguments
---------
slave: Slave object
programs: Array of programs
Returns
-------
A context which maps the slave object to slave an... |
def join_path(keys):
"""
This function joins a list of keys into a dot seperated path.
The advantage of this function over a simple '.'.join(keys) is that it
handles backslash escaping so that keys can contain dot characters.
"""
chars = []
for i, key in enumerate(keys):
if i != 0:
chars.append('.')
for c... |
def beale(x, y):
"""
Beale's function (see https://en.wikipedia.org/wiki/Test_functions_for_optimization).
Has a global _minimum_ of 0 at x=3, y=0.5.
"""
a = (1.5 - x + x * y)**2
b = (2.25 - x + x * y * y)**2
c = (2.625 - x + x * y * y * y)**2
return a + b + c |
def dispatch(split, *funcs):
"""takes a tuple of items and delivers each item to a different function
/--> item1 --> double(item1) -----> \
/ \
split ----> item2 --> triple(item2) -----> _OUTPUT
\\ /
... |
def is_blank_line(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() |
def prettySeconds(seconds):
"""Convert seconds in hours, minutes and seconds.
Returns
-------
hours, minutes, seconds : (float, float, float)
"""
is_negative = seconds < 0
seconds = abs(seconds)
hours = seconds // 3600
minutes = (seconds // 60) % 60
secs = seconds - minutes *... |
def linear(stiffness):
"""
Defines the stiffness for a linear elastic material.
Args:
stiffness(float) : Bulk modulus of the material in Pascal for SAENO Simulation (see [Steinwachs,2015])
"""
return {'K_0': stiffness, 'D_0': 1e30, 'L_S': 1e30, 'D_S': 1e30} |
def spiral_copy(inputMatrix):
"""
Returns the elements of a 2D array in clockwise order.
Parameters:
inputMatrix: List[List[int]]
Returns: List[int]
^ row index (moving through a col)
|
|
|
... |
def init_changes_since_stats(stats, commit, changes):
"""Initialize stats related to changes since previous bugfix
Parameters
----------
stats :
Statistics for each commit / bug report, to be saved as CSV
and/or to generate summary of overall statistics of bug
reports and the re... |
def partition_with_intervals(remaining_length, proper_partitions_only=False):
"""
Generates all possible partitions of a thing of length `remaining`.
:param proper_partitions_only: If True, the trivial partition of an interval with itself will be excluded.
:param remaining_length:
"""
# We use this to denote a p... |
def assemble_url(league_id: int) -> str:
"""Assemble the ranking HTML's URL for the league with that ID."""
template = (
'http://www.basketball-bund.net/public/tabelle.jsp'
'?print=1'
'&viewDescKey=sport.dbb.views.TabellePublicView/index.jsp_'
'&liga_id={:d}'
)
return te... |
def errToX(x, y=None, dx=None, dy=None):
"""
calculate error of x**2
:param x: float value
:param dx: float value
"""
if dx is None:
dx = 0
return dx |
def euler_problem_9(n=1000):
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
import math
... |
def _repair_year(s1, s2, y1, y2, year):
"""takes two strings differing only by year, and replaces their years (which must be 4-digit) with a new one"""
ys1 = "%04d" % y1
ys2 = "%04d" % y2
ys = "%d" % year
t = ""
i = 0
while True:
f = s1.find(ys1, i)
if f == -1:
br... |
def maestro_api_error(error):
"""Wraps an error value in zkAPI format."""
if type(error) == tuple:
error = list(error)
if type(error) != list:
error = [error]
if len(error) == 0:
error = ['INTERNAL_ERROR', 'Empty list given to maestro_api_error']
return { "Status": "Failure"... |
def extract_lower_k_bits(integer, k):
"""
Converts integer into a binary representation.
Then extracts the lower k bits and convert it back to integer.
"""
binary = '{:032b}'.format(integer & 0xffffffff)
start = len(binary) - k
end = len(binary)
lower_bits = binary[start:end]
lower_bits_integer = int(... |
def parse_value(input_string, parse_function, default_value=0):
"""Parse input values."""
result = default_value
try:
result = parse_function(input_string)
except ValueError as e:
print(
"Exception parsing '{}': "
"".format(input_string),
e
)
... |
def recover_link(entity_name):
"""Recover the entity link given the entity name"""
pos = entity_name.rfind("_(")
if pos > 0:
return entity_name[:pos]
return entity_name |
def message_to_oscsysexpayload(message):
"""Convert a sysex message into an OSC payload string.
"""
return message.hex().replace(' ', '') |
def csFriendCircles_FLAGS(friendships):
"""
Args:
friendships: list[list]
result
count: int
"""
# set a counter count
count = 0
# the length of friends
N = len(friendships)
# start them off as False == not seen
seen = [False] * N
def visit(c... |
def validate_sortkind(kind):
"""Define valid sorting algorithm names."""
valid_kind_names = ["quicksort", "mergesort", "heapsort", "stable"]
# Chek if string
if not isinstance(kind, str):
raise TypeError(
"Kind: Sorting name must be a string. "
"Got instead type {}".form... |
def _add_parens(required, text):
"""
Add parens around a license expression if `required` is True, otherwise
return `text` unmodified.
"""
return "({})".format(text) if required else text |
def erb(f):
"""Equivalent rectangular bandwidth formula"""
return 24.7+0.108*f |
def _udev_rule(vid, pid=None, *args):
""" Helper function that return udev rules
"""
rule = ""
if pid:
rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s", ATTRS{idProduct}=="%s", TAG+="uaccess", RUN{builtin}+="uaccess"' % (vid, pid)
else:
rule = 'SUBSYSTEMS=="usb", ATTRS{idVendor}=="%s... |
def get_dhcp_server(network=None, asset=[]):
"""Return IP address of DHCP server based on network or asset.
Args:
network: string, white, green or blue
asset: string, asset name
Return:
dhcp_server: string, IP address
"""
if network == 'blue' or asset[:1] == 'b':
dhcp_server = '172.16.2.10'... |
def get_texts(pain, search_results):
"""Return list of all texts associated with pain in search_results dict.
search_results is of the form:
{'yellowjacket': [google search url, [[link text, url, page text] for each search result], ...}
"""
texts = [ result[2] for result in search_results[pa... |
def buildParameters(obj, validList):
"""
>>> class TestClass(object):
... pass
>>> testClass = TestClass()
>>> testClass.a = 1
>>> testClass.b = "2"
>>> testClass.c = 3
>>> testClass.d = True
>>> buildParameters(testClass, ["a", "b"])
['--a', u'1', '--b', u'2']
>>> testCla... |
def is_cell_free(line, col, grid):
""" Checks whether a cell is free.
Does not throw if the indices are out of bounds. These cases return as free.
"""
# Negative indices are "legal", but we treat them as out of bounds.
if line < 0 or col < 0:
return True
try:
return grid[line][... |
def get_object_classes(predictions, confidence):
"""
Get a list of the unique object classes predicted.
"""
classes = [pred['label']
for pred in predictions if float(pred['confidence']) >= confidence]
return set(classes) |
def names_parameters_computation(parameters):
"""Names of each combination computation. Extraction of names
information from parameters information."""
perturbations_info, format_info, models_info = parameters[:3]
samplings_info, scorer_info = parameters[3:]
pert_names, format_names, model_names = [... |
def standardized_api_list(component):
"""
Convert result dict to list just to have standardized API
"""
keyword = 'componentResults'
if (not isinstance(component, dict) or
keyword not in component or
not component[keyword]):
return component
# Remove reference, ... |
def tldSorting(subdomainList):
"""
This function will sort all the items within the list in dictionary order.
Parameters
-------
subdomainList: list
List of subdomains found from content.
Returns
--------
list
a list of subdomains.
"""
localsortedlist = list()... |
def list2dict(basedict, field):
"""
generates a dict from list by splitting up the key value pairs seperated by =
:param basedict: dict to work on
:param field: field in dict to work on
:return: fixed dict
"""
list_from_dict = basedict[field]
basedict[field] = {}
for info_list in ... |
def nullstring_dict(returnedTags):
"""Convert list to nullstring dict"""
return {_: "" for _ in returnedTags} |
def unflatten(master):
"""
:param dict master: a multilevel dictionary
:return: a unflattened dictionary
:rtype: dict
Unflattens a single-level dictionary a multilevel into one so that::
{'foo.bar.a': 1,
'foo.bar.b': True,
'foo.bar.a': 1,
}
would become::
... |
def det(c,num):
""" c:character and num :r or real number, takes a character
and a number ,then returns character that belongs to c's list(given character ' lsit) using num
for example we give it "a" and 2 then returns c """
flag=0
l2=['a','b','c']
gl2=['A','B','C']
l3=['d','e','f']... |
def image_person_object_factory(image_id, person_id):
"""Cook up a fake imageperson json object from given ids."""
personimage = {
'image_id': image_id,
'person_id': person_id
}
return personimage |
def bool_2_int(value):
"""Convert boolean to 0 or 1
Required for eg. /json.htm?type=command¶m=makefavorite&idx=IDX&isfavorite=FAVORITE
Args:
value (bool)
Returns:
1 if True, else 0
"""
if isinstance(value, bool):
return int(value)
else:
return 0 |
def pipe(x, *f):
""" Pipe Operator
>>> pipe(range(5, 0, -1), reversed, list)
[1, 2, 3, 4, 5]
>>> pipe([3, 2, 2, 4, 5, 1], sorted, set)
{1, 2, 3, 4, 5}
"""
if not f: return x
return pipe(f[0](x), *f[1:]) |
def create_diatomic_molecule_geometry(species1, species2, bond_length):
"""Create a molecular geometry for a diatomic molecule.
Args:
species1 (str): Chemical symbol of the first atom, e.g. 'H'.
species2 (str): Chemical symbol of the second atom.
bond_length (float): bond distance.
... |
def how_many_days(month_number):
"""Returns the number of days in a month.
WARNING: This function doesn't account for leap years!
"""
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
month_index = month_number - 1
return days_in_month[month_index] |
def find_map(
fn,
itr,
not_found=None,
nothing=(None, False),
):
"""\
Like `find()`, but returns first value returned by `predicate` that is not
`False` or `None`.
>>> find_map(
... lambda dct: dct.get('z'),
... ({'x': 1}, {'y': 2}, {'z': 3}),
... )
3
"""
... |
def accumulate(lst, start=0):
"""compute sum of `lst`."""
return sum(lst, start) |
def rgb(r, g, b, divide_by=255.0):
"""Convenience function: return colour in [0, 1]."""
return (r/divide_by, g/divide_by, b/divide_by) |
def strip_space(string):
"""Remove spaces from string
:argument string: target string
:type string: str
:returns str
"""
return string.replace(' ', '') |
def _extract_field(query):
"""Extract field name, e.g. 'updateShipment' from a query like
mutation { updateShipment(id: 1) { state } }
Only works for queries that have arguments (and hence a '(' right after the
operation name).
"""
return query.split("{")[1].split("(")[0].strip() |
def call_sig(args, kwargs):
"""Generates a function-like signature of function called with certain parameters.
Args:
args: *args
kwargs: **kwargs
Returns:
A string that contains parameters in parentheses like the call to it.
"""
arglist = [repr(x) for x in args]
arglist... |
def bioconductor_experiment_data_url(package, pkg_version, bioc_version):
"""
Constructs a url for an experiment data package tarball
Parameters
----------
package : str
Case-sensitive Bioconductor package name
pkg_version : str
Bioconductor package version
bioc_version : ... |
def force_unlist(anything):
"""
Returns the first element of a list, only if it is a list.
Useful for turning [x] into x.
Args:
[Anything]
Returns:
Anything
"""
if isinstance(anything, list):
return anything[0]
return anything |
def get_edge_names_from_indices(mesh, indices):
"""
Given a list of edge indices and a mesh, this will return a list of edge names.
The names are built in a way that cmds.select can select them.
"""
found = []
for index in indices:
name = '%s.e[%s]' % (mesh, index... |
def deltas(xs):
"""Computes the differences between the elements of a sequence of integers.
>>> deltas([-1, 0, 1])
[1, 1]
>>> deltas([1, 1, 2, 3, 5, 8, 13])
[0, 1, 1, 2, 3, 5]
@param xs: A sequence of integers.
@type xs: C{list}
@return: A list of differences between consecutive eleme... |
def calc_bfdp(bf, prior):
"""
Calculate BFDP for a single gene per Wakefield, AJHG, 2007
"""
# Wakefield phrases prior as probability of no effect, so we need to invert
prior = 1 - prior
po = prior / (1 - prior)
bftpo = bf * po
bfdp = bftpo / (1 + bftpo)
return bfdp |
def get_query_cls_name(
with_pagination: bool,
with_filtering: bool,
with_sorting: bool,
) -> str:
"""Get query class name.
:param with_pagination: have pagination
:param with_filtering: have filtering
:param with_sorting: have sorting
:return: class name
"""
cls_name = 'QueryO'... |
def match_record(partial_record, records):
"""
Parameters
----------
partial_record : dict
Partial record to match against records.
records : list of dict
Records to search for a match.
Returns
-------
record : dict
The first record matching the partial record, ... |
def dot_reverse(dot):
"""Reverse bracket notation.
Args:
dot: Bracket notation.
Return:
reversed (string): Reversed bracket notation.
"""
return dot[::-1].replace('(', '/').replace(')', '(').replace('/', ')') |
def instantiate_classes(module_classes, class_instances={}):
"""instantiate specific class."""
# print("module_classes", module_classes)
# create a Object Instance from Class
for class_name, class_obj in module_classes.items():
if class_name not in class_instances:
class_instances[cl... |
def create_pattern_neighbors(width, n_states=2):
"""
This is a private function that returns the weights for calculating an unique
number for each different neighborhood pattern in a random Boolean network.
Parameters
----------
width : int
Neighborhood size.
n_states : int
Number of discrete... |
def reply_is_success(reply: dict):
"""
Predicate to check if `reply` is a dict and contains the key-value pair
"status" = "success"
@param reply A python dict
@return True if the dict contains "status" = "success"
"""
return (
reply
and type(reply) is dict
and reply.g... |
def _property_name_to_values(entities):
"""Returns a a mapping of entity property names to a list of their values.
For example:
_property_name_to_values([{'cat': 5, 'dog': 10},
{'dog': 15, 'mouse': 'happy'}])
=> {'cat': [5], 'dog': [10, 15], 'mouse': ['happy']}
Args:
en... |
def defaultargs(options):
"""Produce a dictionary of default arguments from a list of options
tuples
Parameter
tuple[] - (flag, default, docstring) tuples describing each flag
Return
dict - {flag: default} for each option in input
"""
config = {}
for longname, default, d... |
def get_link_name(key, number):
"""Return formatted link name over enumerated links."""
return '{}#{}'.format(key, str(number+1)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.