content stringlengths 42 6.51k |
|---|
def prefix(x: int, name: str):
"""Prefix node name with an instance"""
return f"{x}_{name}" |
def _default_bounds(signal):
"""Create a default list of bounds for a given signal description
If no bounds were specified, they default to [0, 0]:
['name', 0, 0, 0, 0]
If no bits of the port were picked, the whole port is picked:
['name', x, y, x, y]
A signal may use a slice of a port
... |
def order_issues(validated_data):
"""
validated_data should contain issues key.
We use it in Backlog and Sprint serializers to order it
by dragging between sprint and Backlog and inside of SCRUM board.
"""
if 'issues' not in validated_data:
return validated_data
ordered_issues = validated_data['issues']
for... |
def foldx_variants(genotypes, sub, chain='A', offset=0, region=None):
"""Convert a list of genotypes into a list of FoldX individual_variants.txt entries.
Returns an empty list if no variants are suitable (e.g. out of region or mutate to same)"""
if region is None:
region = [0, float('inf')]
... |
def extend_indices(indices, required_total_size):
""" Extend the indices to obtain the required total size
by duplicating the indices """
# add extra samples to make it evenly divisible, if needed
if len(indices) < required_total_size:
while len(indices) < required_total_size:
i... |
def find_primary_lithology(tokens, lithologies_dict):
"""Find a primary lithology in a tokenised sentence.
Args:
v_tokens (iterable of iterable of str): the list of tokenised sentences.
lithologies_dict (dict): dictionary, where keys are exact markers as match for lithologies. Keys are the lith... |
def generate_weighted_list(st, ed, ratio=(20, 2, 1)):
"""
Generate an integer list consists of [st, ed].
Ratio of each integer in the list is determined using ratio parameter.
For example, st = 1, ed = 6, ratio = (20, 2, 1),
output = [ 20 1s, 20 2s, 2 3s, 2 4s, 1 5s, 1 6s ]
"""
nums = [i ... |
def split_into_chunks(xs, chunk_size):
"""Split the list, xs, into n evenly sized chunks (order not conserved)"""
return [xs[index::chunk_size] for index in range(chunk_size)] |
def moon_phase2 (yr, mn, dy, hr=0, mi=0, se=0, tz=0) :
""" get moon phase at given time
https://www.daniweb.com/programming/software-development/code/453788/moon-phase-at-a-given-date-python
args:
yr: year
mn: month
dy: day
hr: hour
mi: minute
se: second
... |
def get_item_thumbnail_url(item):
"""Returns the thumbnail for an enclosure or feedparser entry or raises a
:exc:`KeyError` if none is found."""
if 'media_thumbnail' in item:
return item['media_thumbnail'][0]['url']
blip_thumbnail_src = item.get('blip_thumbnail_src', None)
if blip_thumbnail_... |
def parse_interpro(row):
""" This function parses all of the Interpro families out of the "interpro"
field of a record. It assumes the "interpro" field, if it is present,
contains a list of dictionaries, and each dictionary contains a key
called "desc" which gives the description of that fam... |
def extract_total_coverage(raw: str) -> int:
"""Extract total coverage."""
tail_line = raw.splitlines()[-1]
return int(float(tail_line.split("\t")[-1][:-1])) |
def icingByteFcnSEV(c):
"""Return severity value of icing pixel.
Args:
c (unicode): Unicode icing pixel.
Returns:
int: Value of severity portion of icing pixel.
"""
return (ord(c) >> 3) & 0x07 |
def process_messages(email_list):
""" takes a list of messages and convert them to a format we can shove into CSV """
message_fields = ['From', 'To', 'Subject', 'Date']
messages = []
for msg in email_list:
message = { key: msg[key] for key in message_fields }
body = ''
if msg.is_... |
def add(x, y):
"""Return the addition of values x & y"""
return (x + y) |
def sample_cloudwatch_cloudtrail_rule(rec):
"""IAM Key Decrypt operation"""
return rec['detail']['eventName'] == 'Decrypt' |
def InLabels(labels, substr):
"""Returns true iff one of the labels contains substr."""
return any([substr in x for x in labels]) |
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
"""
return filename.lower().endswi... |
def _get_function(line, cur_func):
"""
>>> _get_function('foo', None)
>>> _get_function('def hello():', None)
'hello'
"""
if 'def ' in line:
start = line.find('def ') + len('def ')
end = line.find('(')
return line[start:end]
return cur_func |
def __strip_angle_brackets(prefixed_str):
"""Strips prefixed_str from sorrounding angle brackets."""
return prefixed_str[1:-1] if len(prefixed_str) > 1 and prefixed_str.startswith("<") else prefixed_str |
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequences of
outcomes of given length.
"""
answer_set = set([()])
for dummy_idx in range(length):
temp_set = set()
for partial_sequence in answer_set:
for ite... |
def get_registry(url: str) -> str:
"""
Get registry name from url
"""
return url[8:] if url.startswith('https://') else url |
def to_numpy(t):
"""
If t is a Tensor, convert it to a NumPy array; otherwise do nothing
"""
try:
return t.numpy()
except:
return t |
def square_root(value):
""" (float) -> float
Compute an approximation of the square root of <value>
"""
# Init
root = 1.0 # Provisional square root
difference = (root * root) - value # How far off is our provisional root
##--- Loop until the provisional root is close enough to the actual... |
def _gamut(component):
"""keeps color components in the proper range"""
return min(max(int(component), 0), 254) |
def sigma(ab_sig, bb_sig):
""" Perform combining rule to get A+A sigma parameter.
Output units are whatever those are of the input parameters.
:param ab_sig: A+B sigma parameter
:type ab_sig: float
:param ab_sig: B+B sigma parameter
:type ab_sig: float
:rtype: float
... |
def _before_after(n_samples):
"""Get the number of samples before and after."""
if not isinstance(n_samples, (tuple, list)):
before = n_samples // 2
after = n_samples - before
else:
assert len(n_samples) == 2
before, after = n_samples
n_samples = before + after
as... |
def bytes2human(n, format="%(value).1f%(symbol)s"):
"""Used by various scripts. See:
http://goo.gl/zeJZl
>>> bytes2human(10000)
'9.8K'
>>> bytes2human(100001221)
'95.4M'
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols[1:]):
... |
def lock_params(access_mode):
"""Returns parameters for Action Lock"""
return {'_action': 'LOCK', 'accessMode': access_mode} |
def nations_from_str(nations, home, identifier):
"""Determine the nations of identified by ``qualifier``.
Args:
nations (set): Set of all possible nations.
home (str): String denoting the home nations.
identifier (str): String qualifying a country or a
group of countr... |
def factors(n):
""" Return a sequence of (a, b) tuples where a < b giving factors of n.
Based on https://stackoverflow.com/a/6909532/916373
"""
return [(i, n//i) for i in range(1, int(n**0.5) + 1) if n % i == 0] |
def find_sequence_with_x(consensus, single_sequences):
"""
Determine the correct consensus sequence with X replacing consolidated nucleotides, based on the original
sequences to be consolidated
"""
output_sequence = ''
for position, nt in enumerate(consensus):
if nt == 'X':
... |
def forgetting_to_bwt(f):
"""
Convert forgetting to backward transfer.
BWT = -1 * forgetting
"""
if f is None:
return f
if isinstance(f, dict):
bwt = {k: -1 * v for k, v in f.items()}
elif isinstance(f, float):
bwt = -1 * f
else:
raise ValueError("Forgetti... |
def draw_turn(row, column, input_list, user):
"""
Draw the game board after user typing a choice.
Arguments:
row -- the row index.
column -- the column index.
input_list -- a two dimensional list for game board.
user -- the user who type the choice
Returns:
input_list -- a two ... |
def lelu(x):
"""LeLu activation function
Basically ReLu but the lower range leaks slightly and has a range from -inf to inf
Args:
x (float): input value
Returns:
float: output value
"""
return 0.01 * x if x < 0 else x |
def split_interface(interface):
"""Split an interface name based on first digit, slash, or space match.
Args:
interface (str): The interface you are attempting to split.
Returns:
tuple: The split between the name of the interface the value.
Example:
>>> from netutils.interface... |
def pursuant_parenting_arrangement(responses, derived):
"""
Return a list of parenting arrangement bullet points, prefaced by the
correct 'pursuant to' phrase.
"""
act = derived['child_support_acts']
act = 'Pursuant to %s,' % act if act != '' else act
try:
arrangements = responses.g... |
def _merge(*objects):
"""Merge one or more objects into a new object"""
result = {}
[result.update(obj) for obj in objects]
return result |
def etaval(lambda_reg, iteration):
""" Decrease learning rate proportionally to number of iterations """
return 1.0 / (lambda_reg * iteration) |
def from_anscii(buf):
"""
Converts a string to its alpha-numeric equivalent using a modified scheme for numeric
characters and stores the results in a list.
"""
alpha_num_list = []
for char in buf:
if ord(char) >= 128:
num = ord(char)-128 # Subtract 128 to obtain original numeric charccters (based
... |
def move(position, roll):
"""position plus double the roll amount."""
return position + (roll * 2) |
def k_invers( k,q):
""" Compute the K invers mod q-1."""
q = q-1
k = k % q
try:
for i in range(1,q):
if ((k * i) % q == 1):
return i
return 1
except Exception as e:
print("Something went wrong: ",e.__str__())
return |
def order_ids(ids):
"""
This returned the ids sorted
:param ids: array, tuple, iterator. The list of ids
:return: A sorted tuple of the ids
"""
return tuple(set(ids)) |
def number_of_yang_modules_that_passed_compilation(in_dict, compilation_condition):
"""
return the number of drafts that passed the pyang compilation
:in_dict : the "PASSED" or "FAILED" is in the 3rd position of the list,
in the dictionary key:yang-model, list of values
: compilation_cond... |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'noexit' |
def addprint(x: str, y: float):
"""Implementation for (str, float)."""
expr = "%s + %.1f" % (x, y)
return "str_float addprint(x=%r, y=%r): %r" % (x, y, expr) |
def _limits_helper(x1, x2, a, b, snap=False):
"""
Given x1, x2, a, b, where:
x1 - x0 x3 - x2
a = ------- , b = -------
x3 - x0 x3 - x0
determine the points x0 and x3:
x0 x1 x2 x3
|----------|-----------------|--------|
"""
... |
def increments(data):
"""
sums up all incrementing steps in list
so:
if x2 > x1 : increments += (x2-x1)
else : do nothin
"""
return float(sum([data[index + 1] - data[index] for index in range(len(data)-1) if data[index + 1] > data[index]])) |
def get_game_mode(queue_id):
"""
Get game mode by the queue_id
"""
if queue_id == 400:
queue_id = "Normal Draft"
elif queue_id == 420:
queue_id = "Ranked Solo"
elif queue_id == 430:
queue_id = "Normal Blind"
else:
queue_id = "Special"
return queue_id |
def first_n(m: dict, n: int):
"""Return first n items of dict"""
return {k: m[k] for k in list(m.keys())[:n]} |
def get_provenance(
software_name="x", software_version="y", schema_version="1", environment=None,
parameters=None):
"""
Utility function to return a provenance document for testing.
"""
document = {
"schema_version": schema_version,
"software": {
"name": soft... |
def bounding_box(points):
"""
Computes a bounding box from a list of coordinates
Parameters
----------
points : list
List of coordinates in the form of [[x,y], ...]
Returns
-------
list
A 4-tuple consisting of [xmin, ymin, xmax, ymax]
"""
x_coordinates, y_coordi... |
def partition(thelist, n):
"""
Break a list into ``n`` pieces. The last list may be larger than the rest if
the list doesn't break cleanly. That is::
>>> l = range(10)
>>> partition(l, 2)
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> partition(l, 3)
[[0, 1, 2], [3, 4, 5],... |
def progress(train_loss: float, val_loss: float) -> str:
"""
Create progress bar description.
Args:
train_loss: Training loss
val_loss: Validation or test loss
Returns:
String with training and test loss
"""
return 'Train/Loss: {:.8f} ' \
'Val/Loss: {:.8f}' \... |
def convertToTitle(n):
"""
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
"""
based = ord('A')
ret = ""
while n:
ret = chr((n - 1) % 26 + based) + ret
n = (n - 1) // 26
return ret |
def get_status(summary):
"""
:param summary: The job summary dict. Normally ctx.summary
:returns: A status string like 'pass', 'fail', or 'dead'
"""
status = summary.get('status')
if status is not None:
return status
success = summary.get('success')
if success is True:
... |
def utf8len(strn):
"""Length of a string in bytes.
:param strn: string
:type strn: str
:return: length of string in bytes
:rtype: int
"""
return len(strn.encode("utf-8")) |
def __normalize_str(name):
"""Removes all non-alphanumeric characters from a string and converts
it to lowercase.
"""
return ''.join(ch for ch in name if ch.isalnum()).lower() |
def get_score(word):
"""Score a given word."""
if len(word) == 4:
return 1
else:
score = len(word)
if len(set(word)) == 7:
score += 7
return score |
def count_items_bigger_than(numbers, threshold):
"""
What comes in:
-- An sequence of numbers.
-- A number that is a 'threshold'.
What goes out:
Returns the number of items in the given sequence of numbers
that are strictly bigger than the given 'threshold' number.
Side effects: ... |
def Z(m):
"""
@summary: fill m zero in string
@param m: {int} size of string
@return: \x00 * m
"""
return "\x00" * m |
def get_hosts_from_node(node):
"""
Return the host set for an MPI node in the graph and its children
"""
node_hosts = set()
node_host = node["msg"].get("exec_host", "")
node_hosts.add(node_host)
children = node.get("chained", list())
for c in children:
child_hosts = get_hosts_fr... |
def index_to_world(index, resolution, origin, width):
""" Convert index to world coordinates """
x = int(index % width); y = int(index // width)
x = resolution * x + origin[0] + resolution / 2
y = resolution * y + origin[1] + resolution / 2
return x, y |
def split_by_len(string, length):
"""
Split a string into an array of strings of max length ``len``.
Last line will be whatever is remaining if there aren't exactly enough
characters for all full lines.
:param str string: String to split.
:len int length: Max length of the lines.
:return l... |
def normal(x, mu, sigma):
""" Evaluate logarithm of normal distribution (not normalized!!)
Evaluates the logarithm of a normal distribution at x.
Inputs
------
x : float
Values to evaluate the normal distribution at.
mu : float
Distribution mean.
sigma : float
Dist... |
def bt2IndexFiles(baseName):
"""Return a tuple of bowtie2 index files.
Input:
baseName: the base name of bowtie2 index files.
Output:
list of strings, bowtie2 index files.
"""
exts = ['1.bt2', '2.bt2', '3.bt2', '4.bt2',
'rev.1.bt2', 'rev.2.bt2']
retu... |
def find_first_occurrence(key, numbers):
"""
vstup: 'key' hodnota hledaneho cisla, 'numbers' serazene pole cisel
vystup: index prvniho vyskytu hodnoty 'key' v poli 'numbers',
-1, pokud se tam tato hodnota nevyskytuje
casova slozitost: O(log n), kde 'n' je pocet prvku pole 'numbers'
"""
... |
def trans_dict_to_dict(pose, indice_transform):
"""
param pose : dict()
param indice_transform : [int, int, int, ...]
return : dict()
"""
ret = {}
for idx_ret, idx in enumerate(indice_transform):
if idx in pose.keys():
ret[idx_ret] = pose[idx]
return ret |
def needs_binary_relocation(m_type, m_subtype):
"""Returns True if the file with MIME type/subtype passed as arguments
needs binary relocation, False otherwise.
Args:
m_type (str): MIME type of the file
m_subtype (str): MIME subtype of the file
"""
if m_type == 'application':
... |
def euclidean_gcd(first, second):
"""
Calculates GCD of two numbers using the division-based Euclidean Algorithm
:param first: First number
:param second: Second number
"""
while(second):
first, second = second, first % second
return first |
def prettyPercent( numerator, denominator, format = "%5.2f" ):
"""output a percent value or "na" if not defined"""
try:
x = format % (100.0 * numerator / denominator )
except (ValueError, ZeroDivisionError):
x = "na"
return x |
def for_update(row_file, row_db):
"""
Checks if row in uploaded file is equal to record in database with same feature_uuid value.
Takes two arguments:
- "row_file" (dictionary that contains data from row in uploaded file)
- "row_db" (dictionary that contains data from record in data... |
def convertTimeFormatToSecs(timeString):
"""Converts the time in format h:mm:ss to seconds from midnight.
The input is a string and must have the format h:mm:ss or hh:mm:ss.
Example:
#print(convertTimeFormatToSecs('14:03:04'));
"""
# gets the value of hour, minute, and second
hhSt... |
def rgba_to_int(r: int, g: int, b: int, a: int) -> int:
"""Use int.from_bytes to convert a color tuple.
>>> print(rgba_to_int(0, 0, 0, 0))
0
>>> print(rgba_to_int(0, 1, 135, 4))
100100
"""
return int.from_bytes([r, g, b, a], byteorder="big", signed=True) |
def percentage(value, arg):
"""
Divides the value; argument is the divisor.
Returns empty string on any error.
"""
try:
percent_value = float( arg )
if percent_value:
return round(value / 100 * percent_value, 2)
except Exception:
pass
return '' |
def rms(varray=[]):
""" Root mean squared velocity. Returns
square root of sum of squares of velocities """
squares = map(lambda x: x*x, varray)
return pow(sum(squares), 0.5) |
def _escapeArg(arg):
"""Escape the given command line argument for the shell."""
#XXX There is a *lot* more that we should escape here.
return arg.replace('"', r'\"') |
def find_count(substring, string):
"""finds the number of occurences of substring in string"""
counter = 0
index = string.find(substring)
while index >= 0:
counter += 1
index = string.find(substring, index + 1)
return counter |
def hotel_name(hotel):
"""Returns a human-readable name for a hotel."""
if hotel == "sheraton_fisherman_s_wharf_hotel":
return "Sheraton Fisherman's Wharf Hotel"
if hotel == "the_westin_st_francis":
return "The Westin St. Francis San Francisco on Union Square"
if hotel == "best_western_t... |
def int_to_bytes(n, byte_order='big'):
"""
:param n: int
:param byte_order: str
:return: str
"""
return n.to_bytes(8, byte_order) |
def percent_of(part, whole):
"""What percent of ``whole`` is ``part``?
>>> percent_of(5, 100)
5.0
>>> percent_of(13, 26)
50.0
"""
# Use float to force true division.
return float(part * 100) / whole |
def _dedent(text):
"""Like `textwrap.dedent()` but only supports space indents."""
indents = []
for line in text.splitlines():
stripped = line.lstrip(" ")
if stripped:
indents.append(len(line) - len(stripped))
if not indents:
return text
indent = min(indents)
... |
def binSearch(myList, start, end, objetive, iter_bin=0):
"""
Searches the objetive number in the list, if cannot find the number, it will make the list smaller to search again.
"""
print(f'Searching {objetive} between {myList[start]} and {myList[end-1]}:')
iter_bin+=1
if start > end:
ret... |
def unpack_mm_params(p):
"""
Description:
Unpacking parameter that can contains min and max values or single value.
Checking type of input parameter for correctly process.
Parameters:
p (int or float or list or tuple) - single value or min and max values for some range
Returns:
(p1, p2)... |
def normalise_text_score(query: str, score: float) -> float:
"""Approximate a mongo text score to the range [0, 1].
Args:
query: Query which was used
score: Text score
Returns:
An approximation of the normalised text score which is guaranteed
to be in the closed interval [0... |
def format_float(f, precision=3):
""" returns float as a string with given precision """
fmt = "{:.%df}" % precision
return fmt.format(f) |
def get_audios(connection):
"""Get audios list for selected album.
:param connection: :class:`vk_api.vk_api.VkApi` connection
:type connection: :class:`vk_api.vk_api.VkApi`
:return: list of photo albums or ``None``
:rtype: list
"""
try:
return connection.method('audio.get')
exc... |
def move_right(board, row):
"""Move the given row to one position right"""
board[row] = board[row][-1:] + board[row][:-1]
return board |
def update_tuple_item_with_fn(tuple_data, index, fn, *args):
"""
Update the ``index``th item of ``tuple_data`` to the result of calling ``fn`` on the existing
value.
"""
list_data = list(tuple_data)
try:
old_value = list_data[index]
list_data[index] = fn(old_value, *args)
ex... |
def get_DF(fname):
"""Specify the DF value for equation.
DF= -8.d0 for all most recent models (Ergs/sec/cm**2/cm). For older model
series like the NextGen and AMES-Cond grids DF= -26.9007901434d0,
because previous Phoenix outputs were giving out the luminosity,
L (= R**2 * H) in erg/s/cm**2/c... |
def is_suspicious(transaction: dict) -> bool:
"""Determine whether a transaction is suspicious."""
return transaction['amount'] >= 900 |
def blackjack(a, b, c):
"""
Given three integers between 1 and 11, if their sum is less than or equal to 21,
return their sum.
If their sum exceeds 21 and there's an eleven, reduce the total sum by 10.
Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'
:param a: int
:param... |
def preprocess_reference_text(text):
"""Preprocess a PDF text.
Parameters
----------
text : str
The text (possibly from a converted PDF) to preprocess.
Returns
-------
tuple
A tuple consisting of the following elements:
- has_reference_section : A boolean which is t... |
def isValidPasswordPartTwo(firstIndex: int, secondIndex: int, targetLetter: str, password: str) -> int:
"""
Takes a password and returns 1 if valid, 0 otherwise. Second part of the puzzle
"""
bool1: bool = password[firstIndex - 1] == targetLetter
bool2: bool = password[secondIndex - 1] == targetLetter
... |
def is_palindrome(sequence):
"""
Checks if sequence is a palindrome, returns true or false
"""
sequence = str(sequence).lower()
for index, letter in enumerate(sequence):
if letter != sequence[(index + 1) * -1]:
return False
return True |
def allow_incoming_bindings_for_initial_objects(annotation,name_into_obj,zep):
"""
this function inject a -1 as a requirer for the intial objects
this allows the binder to add bindings also to the intial object
:param the intial json annotation
:param the zephyrus json specification
:return: the zephyrus js... |
def minutes_readable(minutes):
"""
convert the duration in minutes to a more readable form
Args:
minutes (float | int): duration in minutes
Returns:
str: duration as a string
"""
if minutes <= 60:
return '{:0.0f}min'.format(minutes)
elif 60 < minutes < 60 * 24:
... |
def default_if_false(value, default):
"""Return given default if value is False"""
if not value:
return default
return value |
def maxSubarray(x):
"""Returns (a, b, c) such that sum(x[a:b]) = c and c is maximized.
See https://en.wikipedia.org/wiki/Maximum_subarray_problem"""
cur, best = 0, 0
curi = starti = besti = 0
for ind, i in enumerate(x):
if cur + i > 0:
cur += i
else: # reset start position
cur, curi = 0, ind + 1
if cu... |
def is_media_url(url):
"""
Returns whether the given url uses the discord's media content delivery network.
Parameters
----------
url : `str`
The url to check.
Returns
-------
is_media_url : `bool`
"""
return url.startswith('https://media.discordapp.net/') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.