content stringlengths 42 6.51k |
|---|
def unique_by_index(sequence):
""" unique elements in `sequence` in the order in which they occur
Parameters
----------
sequence : iterable
Returns
-------
uniques : list
unique elements of sequence, ordered by the order in which the element
occurs in `sequence`
"""
... |
def is_comment_end(line):
"""Determine whether a *line* ends a new multi-line comment.
:param line: A properties line
:type line: unicode
:return: True if line ends a new multi-line comment
:rtype: bool
"""
stripped = line.strip()
return not stripped.startswith('/*') and stripped.endswi... |
def _parse_layout_macro(layout_macro):
"""Split the LAYOUT macro into its constituent parts
"""
layout_macro = layout_macro.replace('\\', '').replace(' ', '').replace('\t', '').replace('#define', '')
macro_name, layout = layout_macro.split('(', 1)
layout, matrix = layout.split(')', 1)
return ma... |
def nzbget_group_is_active(group):
""" Returns True if the group is considered 'active' i.e. downloading, post-processing, running a script, etc, but NOT 'PAUSED'. """
return group['Status'] != 'PAUSED' |
def compute_critical_voxel_radius(offset, radius, thickness):
"""
Compute the offset-sepcific critical radius of a pinhole aperture.
Parameters
----------
offset : scalar
The offset from the front of the pinhole to the layer position.
radius : scalar
pinhole radius.
thicknes... |
def match_with_gaps(my_word, other_word):
""" my_word: string with _ characters, current guess of secret word
other_word: string, regular English word
Returns: boolean, True if all the actual letters of my_word match the
corresponding letters of other_word, or the letter is the special symbol
... |
def add(*matrices):
"""Adds corresponding numbers in lists-of-lists."""
return [
[sum(values) for values in zip(*rows)]
for rows in zip(*matrices)
] |
def trajectory_importance_avg_delta(states_importance):
""" computes the importance of the trajectory, according to the average delta approach """
sum_delta = 0
for i in range(len(states_importance)):
sum_delta += states_importance[i] - states_importance[i - 1]
avg_delta = sum_delta / len(states... |
def dist_interval(v, mi, ma):
"""
Distance from v to interval [min,max]
"""
if v < mi:
return mi - v
if v > ma:
return v - ma
return 0 |
def unlist(l):
"""returns a list of values from a list of lists of values"""
return [x[0] for x in l] |
def biquad(X, c, x1, y1, x2, y2, xy):
"""
Biquadratic surface, for curve fitting
"""
x,y = X
return x2*x**2 + y2*y**2 + xy*x*y + x1*x + y1*y + c |
def wind_direction(degrees):
""" Convert wind degrees to direction """
try:
degrees = int(degrees)
except ValueError:
return ''
if degrees < 23 or degrees >= 338:
return 'N'
elif degrees < 68:
return 'NE'
elif degrees < 113:
return 'E'
elif degrees < ... |
def calculate_cycling_factor(
quality_id: int,
n_cycles: float,
) -> float:
"""Calculate the cycling factor (piCYC) for the relay.
:param quality_id: the quality level identifier.
:param n_cycles: the number of relay cycles per hour in application.
:return: _pi_cyc; the calculated cycling facto... |
def default(d, k, i, default=None):
"""Returns d[k][i], defaults to default if KeyError or IndexError is raised."""
try:
return d[k][i]
except (KeyError, IndexError):
return default |
def gcd(m: int, n: int) -> int:
"""Finds the greatest common divisor of two numbers.
Args:
m: A positive integer value.
n: A second positive integer value.
Returns:
The greatest positive integer that evenly divides both ``m`` and ``n``.
"""
while n != 0:
m, n = n, m... |
def multiply_numbers(bound, numbers):
"""Funkce vypocita soucin cisel v poli numbers, jejichz hodnota
je z intervalu 1 az bound (vcetne). Pokud se v poli zadna takova
cisla nenachazeji, vrati 1.
Parametry:
bound horni hranice intervalu pro hodnotu cisel,
ktera se zapocitavaji ... |
def swap_kv(kv):
"""Swap a key-value tuple."""
return (kv[1], kv[0]) |
def timesteps(paths):
"""Return the total number of timesteps in a list of trajectories"""
return sum(len(path.rewards) for path in paths) |
def collapse_epitopes(epitopes):
"""
Inverts the epitope map and merges epitopes with enst and pos added.
"""
output_epitopes = {}
for k, v in epitopes.items():
enst, ensg, name, pos, chrom, genome_pos, fasta_name = k
#alt_epitope, wt_epitope = v
if v in output_epitopes:
... |
def canonical_order(match):
"""
Before defining a new interaction, we must check to see if an
interaction between these same 4 atoms has already been created
(perhaps listed in a different, but equivalent order).
If we don't check for this this, we will create many unnecessary redundant
interac... |
def ip2uint_str(ipv4_str):
"""Convert IPv4 string to 32-bit integer value"""
parts = ipv4_str.split('.')
if len(parts) != 4:
raise ValueError('Expected IPv4 address in form A.B.C.D, got {}'.
format(ipv4_str))
ip = [0]*4
for i, part in enumerate(parts):
try:
... |
def minfeat(part_features, accumulator_features, feat, nonevalue = None):
"""a helper method that calculates the min of a target feature over two feature dictionaries
Returns:
the min of the target feature over the given list of objects
"""
part_feat = eval('part_features' + feat)
acc_feat ... |
def checkIfParametersAreComplete(requiredParameters, paymentDetails):
""" This returns true/false depending on if the paymentDetails match the required parameters """
for i in requiredParameters:
if i not in paymentDetails:
raise IncompletePaymentDetailsError(i, requiredParameters)
retur... |
def get_current_card(pawn, on_board_cards):
"""
Return the ID of the card where the current pawn is positionned.
"""
i, j = pawn
for card in on_board_cards:
if i >= card["top_left"][0] and i < card["top_left"][0] + 4 and j >= card["top_left"][1] and j < card["top_left"][1] + 4:
r... |
def _convert_params(sql, params):
"""convert sql and params args to DBAPI2.0 compliant format"""
args = [sql]
if params is not None:
if hasattr(params, 'keys'): # test if params is a mapping
args += [params]
else:
args += [list(params)]
return args |
def bytes_needed(data):
"""Find an appropriate type to represent all values in data.
"""
if any(d < 0 for d in data):
prefix, nbits = "", max(max(data).bit_length(), (-1 - min(data)).bit_length()) + 1
else:
prefix, nbits = "u", max(data).bit_length()
return prefix, next(v for v in (... |
def ratio_str(to_str, a, b):
"""
Example: to_str = duration_str, a = 60, b = 120 => "1m / 2m (50%)"
"""
return '%s / %s (%.1f%%)' % (to_str(a), to_str(b), 100.0 * a / b) |
def is_trunk_revision(rev):
"""Return True iff REV is a trunk revision.
REV is a CVS revision number (e.g., '1.6' or '1.6.4.5'). Return
True iff the revision is on trunk."""
return rev.count('.') == 1 |
def _verify_picture_index(index):
"""Raise error if picture index is not a 2D index/slice."""
if not (isinstance(index, tuple) and len(index) == 2):
raise IndexError("Expected 2D index but got {0!r}".format(index))
if all(isinstance(i, int) for i in index):
return index
# In case we ne... |
def recursive_update(obj, new):
"""Merge a dictionary or a list, recursively."""
if isinstance(obj, dict):
for k, v in new.items():
obj[k] = recursive_update(obj.get(k, None), v)
elif isinstance(obj, list):
new = [new] if not (isinstance(new, list)) else new
obj.extend(ne... |
def split_asset_name(asset_name):
"""Splits an asset name into the parent and ID parts.
Args:
asset_name: The asset ID to split, in the form 'projects/*/assets/**'.
Returns:
The parent ('projects/*') and ID ('**') parts of the name.
"""
projects, parent, _, remainder = asset_name.split('/', 3)
ret... |
def arn_endpoint_wildcard(arn: str) -> str:
"""
Take an arn containing a full path of endpoints and
return the arn with a wildcard for all endpoints
Example
-------
input: arn:aws:execute-api:us-east-1:0000000000:XXXYYY/stage/POST/some/endpoint
output: arn:aws:execute-api:us-east-1:00000000... |
def largest_nonadjacent_sum(arr):
"""
Find the largest sum of non-adjacent numbers
"""
before_last = 0
last = 0
for elt in arr:
cur = before_last + elt
before_last = max(before_last, last)
last = max(cur, last)
return last |
def diff(total, partial):
"""
Return a diff list: total - partial
params:
------------
total : list
partial: list
"""
return list(set(total) - set (partial)) |
def difference_quotient(f, x, h):
"""the limit of the difference quotients"""
return (f(x + h) - f(x)) / h |
def get_case_solution(data):
"""Get case solution"""
return data['NEMSPDCaseFile']['NemSpdOutputs']['CaseSolution'] |
def asset_name_from_uri(uri):
"""
Given a valid and complete URI, return just the asset name. Does no validation as to whether this is a
valid asset name.
:param uri:
The valid and complete URI.
:return:
An asset name.
"""
return uri.split("#")[1] |
def _image_name(image):
"""Convert long image name to short one.
e.g 'dockerregistry-v2.my.domain.com.foobar/isilon-data-insights:latest@sha256:HASH' -> dockerreg.../isilon-data-insights:latest
"""
try:
# remove @sha256:....
image = image.split("@")[0]
except IndexError:
pas... |
def get_erpk_score(protein_length, average_read_length, length_cutoff):
"""Calculates ERPK score of a single hit (effective RPK)
Note: For very short proteins (<<90 aa) and very short reads, effective gene
length may be negative. In such cases, this function assumes effective
gene length is 1 bp.
... |
def round_float(number, decimals):
"""
Rounds decimal number to exact number of decimals.
:param number: (float) Float number.
:param decimals: (int) Number of numbers after decimal point
:return:
"""
number = float(number)
out = round(number, decimals)
return out |
def increment_deck(deck_size, cards, increment):
"""Increment operation."""
return [(card * increment) % deck_size for card in cards] |
def jaccard_distance(w1, w2):
"""
Parameters:
-----------
w1: str
w2: str
Returns:
--------
float:
Jaccard distance between w1 and w2
"""
ws1 = set(w1)
ws2 = set(w2)
if (len(ws1) > 1) or (len(ws2) > 1):
dist = 1 - len(ws1.intersection(ws2))/len(... |
def f1(x):
"""
A simple quadratic function.
"""
y = x**2 - 3.*x + 5.
return y |
def func(x, a1, a2, a3, a4, a5):
"""x = 10**-10 * sin(theta/2)/lambda"""
A = 1 + a1*x**2 + a2 * x**3 + a3 * x**4
B = 1 + a4*x**2 + a5 * x**4
return A/B**2 |
def extract_ad(assignee_email):
"""This takes in email-id and spits out the username of the email."""
return assignee_email.split('@')[0] |
def tile(x, count, dim=0):
"""
Tiles x on dimension dim count times.
"""
if x is None:
return None
perm = list(range(len(x.size())))
if dim != 0:
perm[0], perm[dim] = perm[dim], perm[0]
x = x.permute(perm).contiguous()
out_size = list(x.size())
out_size[0] *= coun... |
def _left_0_pad_32(input_bytes):
"""
Pads bytes with 0 on the left to length of 32
:param input_bytes: bytes
:return: padded bytes
"""
return b"\x00" * (32 - len(input_bytes)) + input_bytes |
def get_compare_state(service_bibcode, classic_bibcode, classic_score):
"""
compare service and classic resolved bibcodes and return descriptive state
:param service_bibcode:
:param classic_bibcode:
:param classic_score:
:return:
"""
not_found = '.' * 19
if classic_score == u'5':
... |
def de_dup_and_sort(input):
"""
Given an input list of strings, return a list in which the duplicates are removed and the items are sorted.
"""
input = set(input)
input = list(input)
input.sort()
return input |
def get_uri_name(uri):
"""Return name from Pyro4 URI."""
return uri[uri.find("PYRO:") + 5:uri.find("@")] |
def hagen_poiseuille_equation(reynold):
"""Returns darcy friction coefficient for laminar flow.
:param reynold: reynold number [-]
"""
return round(64 / reynold, 3) |
def CMYtoCMYK(C, M, Y):
""" convert CMY to CMYK color
:param C: C value (0;1)
:param M: M value (0;1)
:param Y: Y value (0;1)
:return: CMYK tuple (0;1) """
tmp_K = 1.0
for i in (C, M, Y):
if i < tmp_K:
tmp_K = i
if tmp_K == 1.0: # Black
CMYK = [0.0, 0.0, 0.... |
def expand_basic(state):
"""
Simple function which returns child states by appending an available move to
current state.
"""
assert(len(state) < 9)
# Calculte set difference to get remaining moves.
n = tuple(set(range(9)) - set(state))
# Create tuple of available new states and return... |
def poly_derivative(poly):
"""Derivative from list"""
if not isinstance(poly, list) or len(poly) < 1:
return None
lenPoly = len(poly)
ans = []
if lenPoly == 1:
return [0]
for i in range(1, lenPoly):
ans.append(poly[i] * i)
return ans |
def first_non_blank(lines):
"""Find first non blank line."""
for each_line in lines:
if not each_line.strip():
continue
else:
return each_line |
def knapsack(V, W, capacity):
"""
Dynamic programming implementation of the knapsack problem
:param V: List of the values
:param W: List of weights
:param capacity: max capacity of knapsack
:return: List of tuples of objects stolen in form (w, v)
"""
choices = [[[] for i in range(capaci... |
def convert_to_hours(duration_seconds: float) -> float:
"""Convert seconds to hours"""
return max(round(duration_seconds / 3600, 2), 0.25) |
def trailing_negative(value, default=0):
"""Attempts to handle the trailing negative issue in a more performant way
Args:
value (str, int, or float): The value to clean
default (float or int, optional): A default value to return if `value`
cannot be cleaned
Returns:
flo... |
def unbind(instance_id, binding_id):
"""
Unbind an existing instance associated
with the binding_id provided
DELETE /v2/service_instances/<instance_id>/service_bindings/<binding_id>:
<instance_id> is the Cloud Controller provided
value used to provision the instance
<binding_i... |
def solution(year):
"""Example:
>>> solution(1905)
20
>>> solution(1700)
17
"""
return (year + 99) // 100 |
def FXR_calc(item):
"""
Calculate False negative rate, False positive rate, False discovery rate (FDR), and False omission rate (FOR).
:param item: item In expression
:type item:float
:return: result as float
"""
try:
result = 1 - item
return result
except TypeError:
... |
def tr_tet_tr_oct_cubo_coord_test(x, y, z): # dist2 = 4
"""Test for coordinate in truncated tetrahedron/truncated octahedron/
cuboctahedron grid"""
x = abs(x) % 6
y = abs(y) % 6
z = abs(z) % 6
if x > 3:
x = 6-x
if y > 3:
y = 6-y
if z > 3:
z = 6-z
dist2 = x**2... |
def heaviside(value):
"""!
@brief Calculates Heaviside function that represents step function.
@details If input value is greater than 0 then returns 1, otherwise returns 0.
@param[in] value (double): Argument of Heaviside function.
@return (double) Value of Heaviside function.
... |
def intFromRoman(roman):
"""
Code taken from Paul Winkler's "Roman Numerals" recipe in the Python
Cookbook.
"""
roman = roman.upper()
coding = (("M", 1000, 3), ("CM", 900, 1), ("D", 500, 1),
("CD", 400, 1), ("C", 100, 3), ("XC", 90, 1),
("L", 50, 1), ("XL", 40, 1)... |
def _xmlcharref_encode(unicode_data, encoding):
"""Emulate Python 2.3's 'xmlcharrefreplace' encoding error handler."""
chars = []
# Phase through the unicode_data string one character at a time in
# order to catch unencodable characters:
for char in unicode_data:
try:
chars.appen... |
def get_write_to_map_from_permutation(original, permuted):
"""With a permutation given by C{original} and C{permuted},
generate a list C{wtm} of indices such that
C{permuted[wtm[i]] == original[i]}.
Requires that the permutation can be inferred from
C{original} and C{permuted}.
.. doctest::
... |
def vs2vp(vs):
"""
Empirical relation from Brocher 2005 valid for non-mafic 0<vs<4.5
"""
vp = 0.9409 + 2.0947*vs - 0.8206*vs**2 + 0.2683*vs**3 - 0.0251*vs**4
return vp |
def getCloneCandidate(outputs):
"""
:returns single connected & enabled display output which will be cloned
"""
index = None
for i,output in enumerate(outputs):
if output and index is None:
index = i
if output['isPrimary']:
return output
if index is None:... |
def add_x_to_plotting_options(plotting_options: dict, option_cat: str, x: str, defaultvalue):
"""
don't override given plotting_options, meaning it only add the default value
if value not already defined in plotting_options
"""
if plotting_options is None:
plotting_options = {}
if option... |
def _escape(s, separator):
"""Escapes the specified string if it contains
the specified separator character."""
if separator in s:
return "\"" + s + "\""
else:
return s |
def cmp_serial(a, b):
# pylint: disable=invalid-name
"""Compare serial numbers. -1 if a is before b, 0 if a=b, else 1.
Do comparison using RFC1982.
"""
if a == b:
return 0
if (a < b and (b - a) < (2**31 - 1)) or (a > b and (a - b) > (2**31 - 1)):
return -1
return 1 |
def __get_tags_gff(tagline):
"""Extract tags from given tagline in a gff or gff3 file"""
tags = dict()
for t in tagline.strip(';').split(';'):
tt = t.split('=')
tags[tt[0]] = tt[1]
return tags |
def _safe_delay(delay):
"""Checks that `delay` is a positive float number else raises a
ValueError."""
try:
delay = float(delay)
except ValueError:
raise ValueError("{} is not a valid delay (not a number)".format(delay))
if delay < 0:
raise ValueError("{} is not a valid delay... |
def mean(data):
"""Returns the mean of data.
data -- a sequence of numerical arguments
>>> mean((1,2,3))
2.0
>>> mean([-3,-4,-8])
-5.0
>>> mean(range(1001))
500.0
>>> mean()
Traceback (most recent call last):
TypeError: mean() missing 1 required positional argument: 'data'
... |
def generate_cf_list(n_cf):
"""Generate a list with the names of CFs
Names are 'cf_id' i.e: cf_0, cf_1...
Args:
n_cf (int): Number of CF in the swarm
Returns:
list: List of CFs names
"""
return [('cf_' + str(i)) for i in range(n_cf)] |
def evaluateInteriorInverseBarrierPenalty(
function, position,
inequalityConstraints=[],
equalityConstraints=[],
rp=1.0):
"""returns a float at the location selected with constraint penalties"""
objectiveValue = function(position)
ineq_constraint_penalty = 0
for constraint in inequalityConstraints:
constrai... |
def overlaps(low1: int, high1: int, low2: int, high2: int) -> bool:
"""
Returns true if the two regions
[low1, high1] and [low2, high2]
overlap.
"""
return high1 >= low2 and high2 >= low1 |
def ensure_list(v):
"""
Makes sure that the given value is a list.
"""
return list(v) if getattr(v, '__iter__', False) else [v] |
def aspect_ratio(nprocx,nprocy):
"""compute aspect ratio of decomposition"""
nprocx = abs(float(nprocx))
nprocy = abs(float(nprocy))
if (nprocx > nprocy):
return nprocx/nprocy
else:
return nprocy/nprocx |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*',\
'*?????*', '*2*1***'])
False
>>> check... |
def cut_list(l, length=100):
"""Truncates string representation of a list for a given length.
:param l: list to truncate
:param length: amount of characters to truncate to
:return: string containing given length of characters from the list
"""
if not isinstance(l, list):
raise ValueErro... |
def divide(numbers):
"""Divides the 1..Nth numbers from the 0th one"""
result = numbers[0]
for number in numbers[1:]:
result /= number
return result |
def binomial_coef_v3(n, k):
"""Computes the k-th coefficient of n-th degree binomial.
Args:
n (int): The degree of binomial.
k (int): The order of binomial coefficient.
Returns:
(int): The k-th coefficient of n-th degree binomial.
"""
k = min(k, n - k)
table = [1] + [0... |
def is_in_optional_scope(context):
"""Return True if the current context is within a scope marked @optional."""
return 'optional' in context |
def make_igv_tracks(name, file_list):
""" Return a dict according to IGV track format. """
track_list = []
counter = 0
for r in file_list:
track_list.append(
{"name": name, "url": file_list[counter], "min": 0.0, "max": 30.0}
)
counter += 1
return track_list |
def get_embedded(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the embedded object for link_relation. The returned object can be
treated as a result object in its own right.
'result_object' a JSON object returned by a previous API call.
The ... |
def _assign_default_model_name_for_none(model_name, protocol):
"""
Assign default model file name according to protocol.
:param model_name:
:param protocol:
:return:
"""
default_model_name = 'mpc_model'
if model_name is None:
# the name of model file is "mpc_model.aby3"
m... |
def solution(desired_position, array):
"""
Finds max(i), given i: the index of first occurrence for the values in 1..desired_position
"""
if desired_position > len(array):
return -1
path = [-1] * (desired_position)
for i in range(len(array)):
if array[i] <= desired_position and (path[array[i] -... |
def trimContainer(a_string):
"""Removes quotes,braces,parens, or brackets from both sides of a string"""
if (["(","'",'"',"{","["].count(a_string[:1])):
return a_string[1:-1]
return a_string |
def find_starts(DNA: str, pat: str) -> list:
"""Find all start indexes of a substring
:param DNA: the longer string to search in
:type DNA: str
:param pattern: the substring to search for
:type pattern: str
:returns: all indexes where pattern starts in DNA
:rtype: list
"""
... |
def extractrelation(s, level=0):
""" Extract discourse relation on different level
"""
return s.lower().split('-')[0] |
def multimax(k, key=None):
"""Returns an in-place list of the max values in the k.
Args:
k(lazy iteration, generator or list): contains the list of items
key: a key by which to sort the items
Returns:
A list of the max values in the input.
"""
p = list(k)[:]
if not p: r... |
def _convert_soap_method_args(*args):
"""Convert arguments to be consumed by a SoapClient method
Soap client required a list of named arguments:
>>> _convert_soap_method_args('a', 1)
[('arg0', 'a'), ('arg1', 1)]
"""
soap_args = []
for arg_n, arg in enumerate(args):
soap_args.append... |
def strings(n, k):
"""Number of distinct unordered samples (with replacement) of k items from a set of n items."""
return pow(n, k) |
def getMaxValue(data, index):
"""get max value of an index in data list
Args:
data (list): the data to be searched
index (int): the index to search in data
"""
maxValue = [-99999, 0]
for i in data:
if i[index] > maxValue[0]:
maxValue[0] = i[index]
max... |
def _str_to_bytes(s):
"""Convert str to bytes."""
if isinstance(s, str):
return s.encode('utf-8', 'surrogatepass')
return s |
def stars_gathered(stars):
"""Return whether or not the stars are gathered together."""
for point in stars:
alone = True
x, y = point
close_to = [
(x-1, y), (x+1, y), (x, y-1), (x, y+1),
(x-1, y-1), (x+1, y+1), (x-1, y+1), (x+1, y-1)
]
for close in... |
def get_formatted_month_year(month, year):
"""
Returns month/year formatted like MM/YYYY.
e.g.: 09/2015
:param year: Year
:param month: Month
:return: Formatted month/year (e.g. 09/2015), ``str``
"""
return "{0:=02}/{1}".format(month,
year) |
def is_multivalued(value):
"""
Determine whether the given value should be treated as a sequence
of multiple values when used as a request parameter.
In general anything that is iterable is multivalued. For example,
`list` and `tuple` instances are multivalued. Generators are
multivalued, as ... |
def join(tokens):
""" construct a string sentence from joining tokens with spaces
args:
tokens: list of strings
returns:
joined_tokens: a string containing all tokens
"""
joined_tokens = ' '.join(tokens)
return joined_tokens |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.