content stringlengths 42 6.51k |
|---|
def shiftRight(n, x):
""" shift n for x places """
return (n >> x & 0xFF) |
def palindrome_permutation(string: str) -> bool:
"""
Determine if a string has a permutation that makes it a palindrome.
Args:
string (str): The string we are checking.
Returns:
bool: True if the string has a viable permutation.
"""
characters = set()
for c in string:
... |
def cchunkify(lines, lang='', limit=2000):
"""
Creates code block chunks from the given lines.
Parameters
----------
lines : `list` of `str`
Lines of text to be chunkified.
lang : `str`, Optional
Language prefix of the code-block.
limit : `int`, Optional
The maxi... |
def get_game_ids(experiment_id):
"""
Get the games (train, eval) belonging to the given experiment ID. Training games will be randomized, where the
evaluation games will not.
"""
if experiment_id in [1]:
return [10000, ] * 10, \
[10000 + i for i in range(1, 21)]
elif exper... |
def min_abs_mod(a, b):
"""
This function returns absolute minimum modulo of a over b.
"""
if a >= 0:
return a - b * ((a + a + b) // (b + b))
a = -a
return -(a - b * ((a + a + b) // (b + b))) |
def generate_ena_api_endpoint(result: str, data_portal: str, fields: str, optional: str = ''):
"""
Generate the url for ENA API endpoint
:param result: either be read_run (for experiment, file, dataset import) or analysis (for analysis import)
:param data_portal: either ena (legacy data) or faang (faang... |
def not_found_response(resource='servers'):
"""
Return a 404 response body for Nova, depending on the resource. Expects
resource to be one of "servers", "images", or "flavors".
If the resource is unrecognized, defaults to
"The resource culd not be found."
"""
message = {
'servers':... |
def warn(string: str) -> str:
"""Add warn colour codes to string
Args:
string (str): Input string
Returns:
str: Warn string
"""
return "\033[93m" + string + "\033[0m" |
def isLowSurrogate(ch):
"""Tests whether a Unicode character is from the low surrogates range"""
code = ord(ch)
return (0xDC00 <= code and code < 0xDFFF) |
def shortened_hash(s, n):
""" Return a shortened string with the first and last bits of a hash
:param s: the full string to shorten
:param n: the desired length of the string returned
:return: An n-character string with the first and last bits of s
"""
side_len = int((n - 3) / 2)
if len(s) <... |
def generate_file_name(year_lst):
"""Generate a csv title including the years being scraped
Args:
year_lst (list): list containing the years being scrapped.
Returns:
str: csv file name specific to the years being scrapped.
"""
return f"{year_lst[0]}-{year_lst[-1]}_Team_Stats.cs... |
def get_from_power_tuple(power_tuple, index):
"""
Extracts an exponent from an exponent tuple that may have been canonicalized
to be shorter than the expected length, by removing extra zeroes.
"""
if index >= len(power_tuple):
return 0
else:
return power_tuple[index] |
def cycle_checker(head):
"""Check if the Singly Linked List is cyclic.
Returns boolean value based on the result
"""
marker_1 = head
marker_2 = head
flag = False
while marker_2 != None and marker_2.next_node != None:
marker_1 = marker_1.next_node
marker_2 = marker_2.next_no... |
def line_number_match(array1, array2):
"""
Function that compares two lists of line numbers and determines which line numbers are missing from either array.
:param array1: A list to be compared
:param array2: A list to be compared
:return: Where in the program there is a parenthesis missing as an in... |
def merge_dicts(*dicts, **kwargs):
"""Merge all dicts in `*dicts` into a single dict, and return the result. If any of the entries
in `*dicts` is None, and `default` is specified as keyword argument, then return `default`."""
result = {}
for d in dicts:
if d is None and "default" in kwargs:
... |
def disappear_angle_brackets(text: str) -> str:
"""
Remove all angle brackets, keeping the surrounding text; no spaces are inserted
:param text: text with angle bracket
:return: text without angle brackets
"""
text = text.replace("<", "")
text = text.replace(">", "")
return text |
def convertListToString(theList):
"""
Really simply converts a list to a string
"""
string = ""
for x in range(0, len(theList)):
string = string + theList[x]
return string |
def selection_sort(m):
"""From left to right, replace each element with element with larger index
and smallest value."""
for i in range(len(m)):
min_pos = i # assume i has the smallest value.
for j in range(i + 1, len(m)): # compare with the rest of elements.
if m[min_pos] > m[... |
def say_hi(name: str, age: int) -> str:
"""
Hi!
"""
# your code here
return "Hi. My name is {} and I'm {} years old".format(name, age) |
def binary_search_iterative(array, left, right, key):
"""Iterativni verze predesle funkce.
Iterativni podobu napiste podle intuice.
"""
while left < right:
mid = (left + right) // 2
if key < array[mid]:
right = mid - 1
elif key > array[mid]:
left = mid + 1... |
def get_first_image_in_list(body_response, name_filter=None):
"""
Gets the first image in the list
:param body_response: Parsed response (Python dic)
:param name_filter: If this arg is set, this method will filtered by name content
:return: First image in list (that contains name_filter in its name)... |
def split_array(array, cells):
"""
Helper function for parsing fdtget output
"""
if array is None:
return None
assert (len(array) % cells) == 0
return frozenset(tuple(array[i*cells:(i*cells)+cells]) for i in range(len(array) // cells)) |
def parse_params(all_params):
"""Parses all_params dictionary into separate dictionaries"""
directories = all_params.pop('directories')
params = all_params.pop('parameters')
classes = all_params.pop('classes')
class_numbers = {c: n for (c, n) in list(zip(classes, [i for i in range(len(classes))]))}
... |
def pick_penalty(table, wtype, bpart, rank):
"""
Picks the relevant penalty from the
specified penalty table based on:
- The weapon type
- The body part
- The seriousness of the damage
"""
try:
return table[wtype][bpart][rank]
except KeyError as error:
re... |
def del_key_if_present(dict_, key):
"""Returns dict with deleted key if it was there, otherwise unchanged dict"""
if key in dict_.keys():
del dict_[key]
return dict_ |
def assign_item(obj, index, val, oper=None):
"""
does an augmented assignment to the indexed (keyed)
item of obj. returns obj for chaining.
does a simple replacement if no operator is specified
usually used in combination with the operator module,
though any appropriate binary function may be ... |
def generate_memory_region(region_descriptor):
""" Generates definition of memory region.
Args:
region_descriptor (dict): memory region description
Returns:
string: repl definition of the memory region
"""
return """
{}: Memory.MappedMemory @ sysbus {}
size: {}
""".format(regi... |
def remove_excess_whitespace(line):
"""
Remove excess whitespace from a line.
Args:
line (str): line to remove excess whitespace from.
Returns:
str: The line with excess whitespace removed.
"""
return " ".join(line.strip().split()) |
def make_table(oldtable=None, values=None):
"""Return a table with thermodynamic parameters (as dictionary).
Arguments:
- oldtable: An existing dictionary with thermodynamic parameters.
- values: A dictionary with new or updated values.
E.g., to replace the initiation parameters in the Sugimoto ... |
def user_match(user, username):
"""
Return True if this is the user we are looking for.
Compares a user structure from a Gerrit record to a username (or email
address). All users match if the username is None.
"""
if username is None:
return True
def field_match(field):
if ... |
def audit_fields():
"""return audit fields"""
return(("effective_user",),
("update_time",), ("update_user",),
("creation_time",), ("creation_user",)) |
def to_bytes(string: str) -> bytes:
"""Encodes the string to UTF-8."""
return string.encode("utf-8") |
def process_files(args_array, cfg, log):
"""Function: process_files
Description: This is a function stub for pulled_search.process_files.
Arguments:
(input) args_array -> Dictionary of command line options and values.
(input) cfg -> Configuration setup.
(input) log -> Log class ... |
def remove_duplicate_awarded_flairs(all_awarded_flairs):
"""Edit find all award flairs that have the same type (duplicates) and remove one, putting information of there being more into a field"""
ls = []
flair_id_ls = []
for awarded_flair in all_awarded_flairs:
if awarded_flair.flair_id in fla... |
def get_full_policy_path(arn: str) -> str:
"""
Resource string will output strings like the following examples.
Case 1:
Input: arn:aws:iam::aws:policy/aws-service-role/AmazonGuardDutyServiceRolePolicy
Output:
aws-service-role/AmazonGuardDutyServiceRolePolicy
Case 2:
Input: arn:aws... |
def quasi_newton( f , xi , step , epsilon=1e-5 , max=100 ):
"""
quasi_newton( f , xi , step , epsilon , max ).
This is a root-finding method that finds the minimum of a function (f) using quasi-newton method.
Parameters:
f (function): the function to minimize
xi (float): the starting po... |
def read_count(f, n):
"""Read n bytes from a file stream; return empty string on EOF"""
buf = ''
while len(buf) < n:
nextchunk = f.read(n - len(buf))
if not nextchunk:
return ''
buf += nextchunk
return buf |
def safe_division(a, b):
"""
:param a: quantity A
:param b: quantity B
:return: the quatient
:rtype: float
"""
try:
return a / b
except ZeroDivisionError:
return 0.0 |
def localname(uri):
"""Determine the local name (after namespace) of the given URI."""
return uri.split('/')[-1].split('#')[-1] |
def format_binary(byte_array: bytearray):
"""
Formats the given byte array into a readable binary string.
"""
return ''.join('{:08b}_'.format(i) for i in byte_array) |
def highlight(text):
"""Returns a text fragment (tuple) that will be highlighted to stand out."""
return ('highlight', text) |
def merge_sort(input_list):
"""Merge sort function to split lists and recurrisvely call on left/right side, then add to results list."""
if isinstance(input_list, list):
center = len(input_list) // 2
left = input_list[:center]
right = input_list[center:]
if len(left) > 1:
... |
def dist2(p1, p2):
"""
calculate 3d euclidean distance between points.
"""
return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2 |
def sum_var_named_args(a, b, **kwargs):
"""perform math operation, variable number of named args"""
sum = a + b
for key, value in sorted(kwargs.items()):
sum += value
return sum |
def generate_ctrlpts_weights(ctrlpts):
""" Generates unweighted control points from weighted ones in 1-D.
This function
#. Takes in 1-D control points list whose coordinates are organized in (x*w, y*w, z*w, w) format
#. Converts the input control points list into (x, y, z, w) format
#. Returns the... |
def data_by_type(data_iterable):
"""
Takes a iterable of data and creates a dictionary of data types and sets
up an array.
"""
data_by_typ = {}
for datum in data_iterable:
if datum.typ not in data_by_typ:
data_by_typ[datum.typ] = []
data_by_typ[datum.typ].append(datu... |
def invert_map(dict_):
"""Invert the keys and values in a dict."""
inverted = {v: k for k, v in dict_.items()}
return inverted |
def is_point_in_rect(pt, rect=(0, 0, 0, 0)):
"""
To detect point is in rect or not
:param pt:
:param rect:
:return:
return True/False value to mean point is including in rect or not
"""
(x_min, x_max, y_min, y_max) = rect
x = pt[0]
y = pt[1]
if x >= x_min and x < x_max an... |
def is_dataset(X, require_attrs=None):
""" Check whether an object is a Dataset.
Parameters
----------
X : anything
The object to be checked.
require_attrs : list of str, optional
The attributes the object has to have in order to pass as a Dataset.
Returns
-------
bool
... |
def get_filter_arg_csr(f, arg):
"""Convert integer to csr string."""
arg_types = {
1: 'CSR_ALLOW_UNTRUSTED_KEXTS',
2: 'CSR_ALLOW_UNRESTRICTED_FS',
4: 'CSR_ALLOW_TASK_FOR_PID',
8: 'CSR_ALLOW_KERNEL_DEBUGGER',
16: 'CSR_ALLOW_APPLE_INTERNAL',
... |
def isDominated(wvalues1, wvalues2):
"""Returns whether or not *wvalues1* dominates *wvalues2*.
:param wvalues1: The weighted fitness values that would be dominated.
:param wvalues2: The weighted fitness values of the dominant.
:returns: :obj:`True` if wvalues2 dominates wvalues1, :obj:`False`
... |
def validate_output(output_str):
"""This function returns true if the string given is a suitable value
from interacting with gravi_utils"""
errors = ['Could not resolve hostname', 'not found',
'Error writting to device', 'Timeout error']
if any(error in output_str for error in errors):
... |
def _fixSlist(slist):
""" Guarantees that a signed list has exactly four elements. """
slist.extend([0] * (4-len(slist)))
return slist[:4] |
def _el_orb(string):
"""Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (str): The element and orbitals as a string, in the form
``"C.s.p,O"``.
Returns:
dict: T... |
def _to_original(sequence, result):
""" Cast result into the same type
>>> _to_original([], ())
[]
>>> _to_original((), [])
()
"""
if isinstance(sequence, tuple):
return tuple(result)
if isinstance(sequence, list):
return list(result)
return result |
def remover_sp_str_load(list_parameters):
""" Remove the sp and the brackets of the elements of the list """
i = 0
length = len(list_parameters)
while i < length:
list_parameters[i] = list_parameters[i].replace("[", "").replace("]", "").replace("sp", "")
i += 1
list_parameters.remove... |
def app_engine_service_account(project_id):
"""Get the default App Engine service account."""
return project_id + '@appspot.gserviceaccount.com' |
def parseDockerAppliance(appliance):
"""
Takes string describing a docker image and returns the parsed
registry, image reference, and tag for that image.
Example: "quay.io/ucsc_cgl/toil:latest"
Should return: "quay.io", "ucsc_cgl/toil", "latest"
If a registry is not defined, the default is: "d... |
def flatten(x, out=None, prefix='', sep='.'):
"""
Flatten nested dict
"""
out = out if out is not None else {}
if isinstance(x, dict):
for k in x:
flatten(x[k], out=out, prefix=f"{prefix}{sep if prefix else ''}{k}", sep=sep)
elif isinstance(x, (list, tuple)):
for k, v in enumerate(x):
f... |
def int_or_none(v, default=None, get_attr=None):
"""Check if input is int.
Args:
v (int): Input to check.
default (type, optional): Expected type of get_attr. Defaults to None.
get_attr (getter, optional): Getter to use. Defaults to None.
Returns:
int or None: Return int if... |
def common_substring(s1, s2):
"""
:type s1: str
:type s2: str
:rtype: str
"""
s1 = set(s1)
s2 = set(s2)
for c in s1:
if c in s2:
return True
return False |
def _parseUNIX(factory, address, mode='666', backlog=50, lockfile=True):
"""
Internal parser function for L{_parseServer} to convert the string
arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the
structured arguments.
@param factory: the protocol factory being parsed, or L{None}. (... |
def get_y_from_key(key):
"""
:param key:
:return:
"""
return (key >> 16) & 0xFF |
def percent(num):
"""Format number as per cent with 2 decimal places."""
return "{:.2f}%".format(num * 100) |
def is_sequence(value):
"""
Return ``True`` if ``value`` is a sequence type.
Sequences are types which can be iterated over but are not strings
or bytes.
"""
return not isinstance(value, str) and not isinstance(value, bytes) and hasattr(type(value), '__iter__') |
def assign_to_red_or_black_group(x, y, x_cutoff, y_cutoff):
"""xcoord is coefficient (MAST already took log2). ycoord is -log10(pval). label is gene name."""
if abs(x) > x_cutoff and y > y_cutoff:
color = "red"
# x coordinate (coef) is set to 0 if one of the two groups has zero counts (in that case,... |
def is_valid_state(state):
"""this function returns true if the given state is of formed by only . and 0, false otherwise
GIVEN: a state
WHEN: I apply it to generate an initial state
THEN: the result is true if it contains only . and 0
"""
return set(state) == {".","0"} |
def show_collapsing_menu(outline):
"""
This template tag takes a list of dicts, outline, with the following
structure:
[
{
'title': title,
'url': url,
'children':
[
{
... |
def str_version(version):
"""converts a tuple of intergers to a version number"""
return '.'.join(str(versioni) for versioni in version) |
def conj_phrase(list_, cond='or'):
"""
Joins a list of words using English conjunction rules
Args:
list_ (list): of strings
cond (str): a conjunction (or, and, but)
Returns:
str: the joined cconjunction phrase
References:
http://en.wikipedia.org/wiki/Conjunction_(... |
def file_url(category, event_id=None, train_or_test="train"):
"""Returns the path of a csv corresponding to a given event and data
category.
Arguments:
category -- one of "cells", "hits", "particles", "truth", "detectors",
"sample_submission" or "hit_orders".
event_id -- the integer id ... |
def calculate_markedness(PPV, NPV):
"""
Calculates the markedness meassure of the supplied data, using the equation as per: http://www.flinders.edu.au/science_engineering/fms/School-CSEM/publications/tech_reps-research_artfcts/TRRA_2007.pdf (page 5)
Markedness = PPV+NPV-1
Input:
... |
def _scaleRep(reportData):
"""
Scales reports of different sets of terms.
Using the percent change with the 1 month overlap should take care of the
variation in time of a single report. However, if, at the same moment in
time, a secondary report contains a term which is larger than the constant
term and so causes... |
def _validate_boolean(value):
"""Validate value is a float."""
if isinstance(value, str):
value = value.lower()
if value not in {True, False, "true", "false"}:
raise ValueError("Only boolean values are valid.")
return value is True or value == "true" |
def safename(name):
"""Make name filesystem-safe."""
name = name.replace(u'/', u'-')
name = name.replace(u':', u'-')
return name |
def isAncestorOf(ancestor, child):
"""Return True if `ancestor` is an ancestor of `child`, QObject-tree-wise."""
while child is not None:
if child is ancestor:
return True
child = child.parent()
return False |
def args_from_id(id, arg_ranges):
"""Convert a single id number to the corresponding set of arguments"""
args = list()
for arg_range in arg_ranges:
i = id % len(arg_range)
id = id // len(arg_range)
args.append(arg_range[i])
return tuple(args) |
def get_summary_length(num_summarizers):
"""
Inputs:
- summary: the summary
Outputs: the summary length
Purpose: to calculate the fifth truth value T5. This helps avoid long summaries that are not easily comprehensible by the human user
"""
return 2 * (0.5 ** num_sum... |
def get_dict_path(base, path):
"""
Get the value at the dict path ``path`` on the dict ``base``.
A dict path is a way to represent an item deep inside a dict structure.
For example, the dict path ``["a", "b"]`` represents the number 42 in the
dict ``{"a": {"b": 42}}``
"""
path = list(path)
... |
def SQRT(number):
"""
Calculates the square root of a positive number and returns the result as a double.
See https://docs.mongodb.com/manual/reference/operator/aggregation/sqrt/
for more details
:param number: The number or field of number
:return: Aggregation operator
"""
return {'$sqr... |
def _StripPC(addr, cpu_arch):
"""Strips the Thumb bit a program counter address when appropriate.
Args:
addr: the program counter address
cpu_arch: Target CPU architecture.
Returns:
The stripped program counter address.
"""
if cpu_arch == "arm":
return addr & ~1
return addr |
def parse_bool(value):
"""Represents value as boolean.
:param value:
:rtype: bool
"""
if isinstance(value, bool):
return value
value = str(value).lower()
return value in ('1', 'true', 'yes') |
def objc_strip_extension_registry(lines):
"""Removes extensionRegistry methods from the classes."""
skip = False
result = []
for line in lines:
if '+ (GPBExtensionRegistry*)extensionRegistry {' in line:
skip = True
if not skip:
result.append(line)
elif line == '}\n':
skip = False
... |
def canonicalize_job_spec(job_spec):
"""Returns a copy of job_spec with default values filled in.
Also performs a tiny bit of validation.
"""
def canonicalize_import(item):
item = dict(item)
if item.setdefault('ref', None) == '':
raise ValueError('Empty ref should be None, n... |
def pairWiseSwap(head):
"""
We dont need to change the references just swap the values of the next
and the current node
"""
ptr = head
while ptr and ptr.next:
ptr.data, ptr.next.data = ptr.next.data, ptr.data
ptr = ptr.next.next
return head |
def de_jong_step_a_function(transposed_decimal_pop_input):
"""De Jong Step - A Test Function"""
y = []
for individual in transposed_decimal_pop_input:
de_jong_step = 0
for xi in individual:
de_jong_step = de_jong_step + abs(round(xi)) # (abs) was used to adjust the f... |
def mili_to_standard(militaryTime):
"""Function to convert military time to Standard time.
:param militaryTime: Military time in format HH:MM
:type militaryTime: str
:return: Standard time that was converted from the supplied military time
:rtype: str
"""
# Handles formatting errors in th... |
def is_keyed_tuple(obj):
"""Return True if ``obj`` has keyed tuple behavior, such as
namedtuples or SQLAlchemy's KeyedTuples.
"""
return isinstance(obj, tuple) and hasattr(obj, '_fields') |
def _parse_duration(duration: str) -> float:
"""
Convert string value of time (duration: "25:36:59") to a float value of seconds (92219.0)
"""
try:
# {(1, "s"), (60, "m"), (3600, "h")}
mapped_increments = zip([1, 60, 3600], reversed(duration.split(":")))
seconds = sum(multiplier ... |
def frames_to_seconds(num_frames, frame_length, frame_step):
"""
compute the time given the frame number
"""
if num_frames == 0:
return 0
return (num_frames - 1) * frame_step + frame_length |
def generate_op_run_log(op_data):
"""Returns operator execution log."""
return 'device id={} op={}, ready={}, start={}, end={}\n'.format(
op_data['p'], op_data['name'], op_data['ready_ts'],
op_data['start_ts'], op_data['end_ts']) |
def prime_factorization(n):
"""Return the prime factorization of `n`.
Parameters
----------
n : int
The number for which the prime factorization should be computed.
Returns
-------
dict[int, int]
List of tuples containing the prime factors and multiplicities of `n`.
""... |
def adding_two_numbers(number_1,number_2):
"""
This function returns the sum of two numbers.
PARAMETERS;
number_1: float, takes in the first numbber to sum;
number_2: float, takes in the second number to sum;
RETURN TYPE;
The return type should be in float.
EXAMPLE:
add(7,7)
"""
total_sum = number_1 + number_2
... |
def to_bytearray(value):
"""
Convert hex to byte array
"""
if value and isinstance(value, str):
value = bytearray.fromhex(value)
return value |
def isint(val):
"""
check if the entry can become an integer (integer or string of integer)
Parameters
----------
val
an entry of any type
Returns
-------
bool
True if the input can become an integer, False otherwise
"""
try:
int(val)
return Tru... |
def generate_status_bar(percent: float, img_size: int):
"""
take a percent and create a progress bar
:param percent: percent complete
:param img_size: size of the image MB
:return: progress bar
"""
bar_length = 50
number_bars = round((int(str(percent).split(".")[0])) / (100 / bar_length)... |
def porcentage(number, porc):
"""This function will return the porcentage plus the value.
Args:
number (int/float): value
porcentage (int/float): porcentage quantity
"""
return number + (number * (porc / 100)) |
def hparams_power(hparams):
"""Some value we want to go up in powers of 2
So any hyper param that ends in power will be used this way.
"""
hparams_old = hparams.copy()
for k in hparams_old.keys():
if k.endswith("_power"):
k_new = k.replace("_power", "")
hparams[k_new... |
def tweakObject(obj):
"""
Takes as input an object and returns a list of synonyms
- Input:
* obj (string)
- Output:
* tweakedObj (list of strings)
"""
tweakedObj = [obj]
if obj == 'bell_pepper':
tweakedObj = ['bell pepper']
elif obj == 'cup':
tweakedObj = ... |
def life_counter(field):
"""
returns quanity of living squares
"""
hype = 0
for y in range(len(field)):
for x in range(len(field[y])):
if field[y][x] == 0:
hype += 1
return hype |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.