content stringlengths 42 6.51k |
|---|
def _result_str_valid(result):
"""Check the format of a result string per the SGF file format.
See http://www.red-bean.com/sgf/ for details.
"""
if result in ['0', 'Draw', 'Void', '?']:
return True
if result.startswith('B') or result.startswith('W'):
score = result[2:]
if s... |
def connected_four(bit_board):
"""Evaluates if player bit board has made a connect 4.
Parameters:
bit_board (int): bit board representation of player pieces the game
Returns:
bool : True if the board has achieved a connect 4"""
# Horizontal check
m = bit_board & (bit_board >> 7)
if m ... |
def get_object_id(obj: dict) -> str:
"""Returns unique id of the object."""
return obj["name"].rpartition("/")[-1] |
def parse_sbd_devices(options):
"""Returns an array of all sbd devices.
Key arguments:
options -- options dictionary
Return Value:
devices -- array of device paths
"""
devices = [str.strip(dev) \
for dev in str.split(options["--devices"], ",")]
return devices |
def avg_price(prices):
"""Returns the average price of a list of 1 or more prices."""
storage = 0
for x in range(len(prices)):
storage = storage + prices[x]
return storage/len(prices) |
def num2str(num):
""" convert a number into a short string"""
if abs(num) < 0.01 and abs(num) > 1e-50 or abs(num) > 1E4:
numFormat = ".2e"
elif abs(round(num) - num) < 0.001 or abs(num) > 1E2:
numFormat = ".0f"
elif abs(num) > 1E1:
numFormat = ".1f"
else:
numFormat = ".2f"
return ("{:" + numFormat + "}")... |
def extract_aligned_sequences(aligned_array):
"""
Transforms aligned sequences into FASTA format
:param aligned_array: array of aligned sequences
:return: string, aligned sequences in FASTA format
"""
aligned_seqs = ''
for element in aligned_array:
if len(aligned_seqs) > 0:
... |
def url_params_from_lookup_dict(lookups):
"""
Convert the type of lookups specified in a ForeignKey limit_choices_to
attribute to a dictionary of query parameters
"""
params = {}
if lookups and hasattr(lookups, 'items'):
items = []
for k, v in lookups.items():
if call... |
def erratum_check(agr_data, value):
"""
future: check a database reference has comment_and_corrections connection to another reference
:param agr_data:
:param value:
:return:
"""
# when comments and corrections loaded, check that an xref is made to value e.g. PMID:2 to PMID:8
return 'S... |
def ship_size(bf, position):
"""
:param bf: 2D list representation of a battlefield: list(list)
:param position: Coordinates of a position on a battlefield: tuple
:return: length of ship, part of which is on that position: int
"""
x, y = position[0], position[1]
up, down, left, right = 0, 0,... |
def process_alpha(alpha: float) -> float:
"""
Asserts input `alpha` is appropriate to be used in the model.
Args
----
alpha: float
Ranges from 0 up to 1 indicating level of significance to assert when
testing for presence of signal in post-intervention data.
Returns
-... |
def strip_whitespaces(tpl):
""" Strip white spaces before and after each item """
return [item.strip() for item in tpl] |
def _check_domain_structure(domains, n_dim):
"""Checks whether the domain structure is valid."""
vals = [val for domain in list(domains.values()) for val in domain] # flatten values
# each dimension must appear in exactly one domain
for i in range(n_dim):
if vals.count(i) != 1:
... |
def get_cli_kwargs(**kwargs):
"""
Transform Python keyword arguments to CLI keyword arguments
:param kwargs: Keyword arguments
:return: CLI keyword arguments
"""
return ' '.join(
[
f'--{k.replace("_", "-")} {str(v).replace(",", " ")}'
for k, v in kwargs.items()
... |
def find_in_dict(a_dict, find_func, reverse=False):
"""Find a matched item in dict
- a_dict: dict like object
- find_func: the filter function to find a matched item
- reverse: find in reversed? True/False
Return (key, value) of the dict
Example:
data = {'a': 1, 'b': 2: 'c': 3}
find_i... |
def reverse(points, i, j):
"""
Reverses a sub part of circuit.
Retourne une partie du circuit.
@param points circuit
@param i first index
@param j second index (<= len(points))
@return new circuit
"""
points = points.copy()
... |
def num_sevens(n):
"""Returns the number of times 7 appears as a digit of n.
>>> num_sevens(3)
0
>>> num_sevens(7)
1
>>> num_sevens(7777777)
7
>>> num_sevens(2637)
1
>>> num_sevens(76370)
2
>>> num_sevens(12345)
0
>>> from construct_check import check
>>> # b... |
def compute_jth_inversion_sequence(n, j):
"""The are ``n!`` permutations of ``n`` elements. Each permutation can be
uniquely identified by and constructed from its "inversion sequence". This
function will compute the ``j``th inversion sequence for a set of ``n``
elements.
Information on inversion s... |
def XRI(xri):
"""An XRI object allowing comparison of XRI.
Ideally, this would do full normalization and provide comparsion
operators as per XRI Syntax. Right now, it just does a bit of
canonicalization by ensuring the xri scheme is present.
@param xri: an xri string
@type xri: six.text_type
... |
def source_dx_dy(source_pos_x, source_pos_y, cog_x, cog_y):
"""
Compute the coordinates of the vector (dx, dy) from the center of gravity to the source position
Parameters
----------
source_pos_x: X coordinate of the source in the camera
source_pos_y: Y coordinate of the source in the camera
... |
def untar_cmd(src, dest):
""" Create the tar commandline call
Args:
src (str): relative or full path to source tar file
dest (str): full path to output directory
Returns:
str: the tar command ready for execution
Examples:
>>> untar_cmd('my.tar.gz', '/path/to/place')
... |
def _get_messages(data):
"""
Get messages (ErrorCode) from Response.
:param data: dict of datas
:return list: Empty list or list of errors
"""
error_messages = []
for ret in data.get("responses", [data]):
if "errorCode" in ret:
error_messages.append(
"{0}... |
def asif(nominal_control):
"""
Active Set Invariance Filter implementation of cbf.
Recall CBF formulation:
Given function h, which is denoting safety (h(x) >= 0 is safe)
Set invariance (or safety) can be achived by:
Nagumo's theorem: (works on boundary of safe set)
h_dot(x) >= ... |
def sh_escape(command):
"""
Escape special characters from a command so that it can be passed
as a double quoted (" ") string in a (ba)sh command.
Args:
command: the command string to escape.
Returns:
The escaped command string. The required englobing double
quo... |
def _significance_pruning_step(pre_pruning_assembly):
"""
Between two assemblies with the same unit set arranged into different
configurations the most significant one is chosen.
Parameters
----------
pre_pruning_assembly : list
contains the whole set of significant assemblies (unfilter... |
def find_it(seq):
"""Function returns number that occurs odd num of times."""
counts = {}
for item in seq:
if item in counts:
counts[item] += 1
else:
counts[item] = 1
for prop in counts:
if counts[prop] % 2 != 0:
return(prop) |
def _is_header(row: list) -> bool:
"""
Determine if a row is a header row.
Keyword arguments:
row -- the row to check
Returns: True if the row is a header row, False otherwise
"""
return row[0].strip().lower() == "company name" |
def transpose(table):
"""
Returns a copy of table with rows and columns swapped
Example:
1 2 1 3 5
3 4 => 2 4 6
5 6
Parameter table: the table to transpose
Precondition: table is a rectangular 2d List of numbers
"""
# LIST COMPREHENSIO... |
def give_me_proper_embl(cross_refs):
"""
Filter for references where the first element == 'EMBL',
then search for the first occurence where the genome accession is not '-'.
This is to get both a valid protein accession and genome accession.
:param cross_refs: The full list of SwissProt.record.cross... |
def get_message_type(message):
"""Get the type of the message that was send to jstipBot"""
if 'text' not in message:
return 'NO_TEXT'
elif 'entities' not in message:
return 'NO_COMMAND'
else:
for entity in message['entities']:
if entity['type'] == 'bot_command':
... |
def invert_atom_map(atom_map):
"""
Invert atom map `{map_idx:atom_idx} --> {atom_idx:map_idx}`
Parameters
----------
atom_map: dict
`{map_idx:atom_idx}`
Returns
-------
dict
`{atom_idx:map_idx}`
"""
return dict(zip(atom_map.values(), atom_map.keys())) |
def to_unweighted_population(distribution_or_values):
"""
:param distribution_or_values:
:return:
"""
if hasattr(distribution_or_values, 'measurements'):
return [x.value for x in distribution_or_values.measurements]
return distribution_or_values |
def is_valid_modulo(barcode):
"""
:param barcode: takes the user's input and does several operations to the odd and even positions with the module check character method.
:return: checkdigit (the variable that should match the last digit of the barcode
"""
oddnumbers = [] ... |
def check_blank_line(message):
"""Check if there is a blank line between subject and a paragraph."""
splitted = message.splitlines()
if len(splitted) > 1:
# check should only be needed for multyline commit messages
check = not splitted[1]
else:
check = True
return check |
def make_indices(dimensions):
""" Generates complete set of indices for given dimensions """
level = len(dimensions)
if level == 1:
return range(dimensions[0])
indices = [[]]
while level:
_indices = []
for j in range(dimensions[level - 1]):
_indices += [[j]... |
def replace_keys(d, old, new):
"""replace keys in a dict."""
return {k.replace(old, new): v for k, v in d.items()} |
def extended_gcd(a, b):
"""Euclids extended gcd algorithm."""
x = 0
y = 1
last_x = 1
last_y = 0
while b != 0:
quot = a // b
a, b = b, a % b
x, last_x = last_x - quot * x, x
y, last_y = last_y - quot * y, y
return last_x, last_y |
def saveInstancesMatsToFile(filename, matrices):
"""
save a list of instance matrices to a file
status = saveInstancesMatsToFile(filename, matrices)
status will be 1 if it worked
"""
f = open(filename, 'w')
if not f:
return 0
for mat in matrices:
for v in mat.flatten()... |
def _format_progress_event(status, progress, total, step):
"""Helper to format progress events for mocking it with fake responses."""
return {'status': status, 'progress': progress, 'total': total, 'last_step': step} |
def subbooster_pvinfo(sector):
"""
Returns basic PV information about a subbooster in a given sector
Parameters
----------
sector : int
sector in [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
Returns
-------
dict with:
name : str
description : str
ph... |
def recipe_type(lst):
"""
>>> recipe_type([])
'No preference'
>>> recipe_type(['vegetarian', 'meatarian','vegetarian', 'meatarian', 'meatarian'])
'meatarian'
>>> recipe_type(['vegetarian', 'meatarian','vegetarian'])
'vegetarian'
"""
meat = 0 # number of meatarians in list
... |
def mergeAlternately(word1, word2):
"""
:type word1: str
:type word2: str
:rtype: str
"""
res = ""
count = 0
if len(word1) > len(word2):
count += len(word1)
for i in range(count):
if i < len(word2):
res += word1[i]
res += word2[... |
def has_duplicates(t):
# Old Code
# tmp = []
# for i in t:
# tmp.append(i)
# Worked solution this way because I didn't think to just use days 1-365 and instead
# chose to work with strings like 'mm-dd'. I think the nested conditional is
# particularly gross, especially given the knowledg... |
def contains_common_item_5(arr1, arr2):
"""
Use any function to check item in list
"""
return any(True for item in arr1 if item in arr2) |
def floatN(x):
"""
Convert the input to a floating point number if possible, but return NaN if it's not
:param x: Value to convert
:return: floating-point value of input, or NaN if conversion fails
"""
try:
return float(x)
except ValueError:
return float('NaN') |
def i2osp(x: int, x_len: int) -> bytes:
"""
Integer to OctetString Primitive:
https://tools.ietf.org/html/rfc8017#section-4.1
"""
return int(x).to_bytes(x_len, "big") |
def nb_consecutives(x, y, dx, dy, position, color):
"""Maximum number of consecutive stones of color `color` in the board position
`position`,starting from (x,y) and using slope (dx, dy).
Parameters
----------
x: int
x-coordinate of the start position
y: int
x-coordinate of the start position
dx:... |
def calc_bmi(weight, length):
"""Provided/DONE:
Calc BMI give a weight in kg and length in cm, return the BMI
rounded on 2 decimals"""
bmi = float(weight) / ((float(length) / 100) ** 2)
return round(bmi, 2) |
def simple_environ(prefix='', env_value='value'):
"""Returns dict with example environment with given prefix and value."""
return {
'{0}key'.format(prefix): env_value,
'a': 'b',
} |
def mangle(name):
"""Mangle a name according to the ABI"""
namespaces = name.split("::")
mangled_name = ""
for namespace in namespaces:
mangled_name += str(len(namespace)) + namespace
if len(namespaces) > 1:
mangled_name = "N" + mangled_name + "E"
return mangled_name |
def overlaps(region_1, region_2):
"""
Find if two regions overlaps
a region is defined as dictionary with
chromosome/contig, start- and end position given
Args:
region_1/region_2(dict): dictionary holding region information
Returns:
overlapping(bool)... |
def is_component(obj):
"""
Check if an object is a component or not
Args:
obj (unicode): Object name to check if its a component
Returns:
(bool): True if it is a component
"""
if "." in obj:
return True
return False |
def _urls(package, version, mirrors):
"""Computes the urls from which an archive of the provided PyPI package and
version should be downloaded.
Args:
package: PyPI package name.
version: version for which the archive should be downloaded.
mirrors: dictionary of mirrors, see mirrors... |
def func_ab_kwargs(a=2, b=3, **kwargs):
"""func.
Parameters
----------
a, b: int, optional
kwargs: dict
Returns
-------
a, b: int
kwargs: dict
"""
return None, None, a, b, None, None, None, kwargs |
def _port_to_key(port: int) -> str:
"""Create string from an port number"""
string = str(port) + '_AXIS'
if port < 10:
string = '0' + string
return string |
def factorial(num):
"""Returns an integer
Factorial of the number passed as argument
"""
fact = 1
for i in range(1, num+1):
fact *= i
return fact |
def find_records(dataset, search_string):
"""Retrieve records filtered on search string.
Parameters:
dataset (list): dataset to be searched
search_string (str): query string
Returns:
list: filtered list of records
"""
records = [] # empty list (accumulator pattern)
for ... |
def strip_additional_byte_order_marks(unicode_contents):
"""
Creditor Reporting System data seems to be in utf-16, but with multiple "Byte Order Marks" (BOMs) per file.
(probably due to cat'ing together several utf-16 files)
There is generally only supposed to be a leading BOM for a Unicode file.
Th... |
def assign_year(month, cycle):
"""Returns the proper year of a date given the month and cycle."""
if int(month) >= 6:
return str(int(cycle) - 1)
else:
return str(int(cycle)) |
def _can_parse_to_int(s: str):
"""Checks if the string can be parsed to an int."""
try:
int(s)
return True
except (ValueError, TypeError):
return False |
def _merge_metadata(base_metadata, more_metadata):
"""Merge metadata from two different sources.
:param list base_metadata: A (possibly undefined) set of metadata.
:param list more_metadata: Metadata to add (also possibly undefined).
"""
result = []
if base_metadata:
result.extend(base_m... |
def ipaddr_to_geo(ipaddr, geoip2_reader):
"""
Returns (lat, long, iso_code) or (None, None, None)
"""
try:
geodata = geoip2_reader.city(ipaddr)
return (geodata.location.latitude,
geodata.location.longitude,
geodata.country.iso_code)
except:
re... |
def get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(in... |
def calc_prob(curr_layer, total_layers, p_l):
"""Calculates drop prob depending on the current layer."""
return 1 - (float(curr_layer) / total_layers) * p_l |
def recall_from_metadata(prediction_titles, all_metadata):
"""Calculates recall for movie suggestions in redial.
Args:
prediction_titles: a list of lists containing the titles mentioned in
each prediciton.
all_metadata: the metadata of each redial conversation
Returns:
the rec... |
def get_quantized_ints_block(dct_width, quantized_block):
"""
Store quantized block as integers.
The 4 float values of each row are stored as 1 byte each in an int.
First row value is stored in least significant byte.
Results in a list of 4 ints.
"""
ints_block = []
for y_index in range(... |
def pretty_unicode(obj):
"""Filter to pretty print iterables."""
if not isinstance(obj, (str, bytes)):
try:
return ' '.join(str(item) for item in obj)
except TypeError:
pass
return str(obj) |
def get_alignment_indices(n_imgs, ref_img_idx=None):
"""Get indices to align in stack.
Indices go from bottom to center, then top to center. In each case,
the alignments go from closest to the center, to next closet, etc...
The reference image is exclued from this list.
For example, if `ref_img_idx... |
def salt(length=2):
"""Returns a string of random letters"""
import string
import random
letters = string.ascii_letters+string.digits
return ''.join([random.SystemRandom().choice(letters) for _ in range(length)]) |
def eval_search(ripe_object, name, value):
"""
Evaluate RIPE answer when searching objects
"""
# print(ripe_object)
try:
error = ripe_object["errormessages"]["errormessage"][0]["text"]
if error.find("101"):
return 1
else:
return 2
except:
r... |
def select2_processor(idps):
"""
A simple processor for Select2, to adjust the data ready to use for Select2.
See https://select2.org/data-sources/formats
"""
def change_idp(idp):
idp['id'] = idp.pop('entity_id')
idp['text'] = idp.pop('name')
return idp
return [change_id... |
def ordinal_indicator(num):
"""Appends the ordinal indicator (th/st etc.) to the end of a number."""
return "%d%s" % (num,"tsnrhtdd"[(num // 10 % 10 != 1) * (num % 10 < 4) * num % 10::4]) |
def add_quotes(input_str, is_quotes_added):
"""add quotes to incoming str
Returns:
Quotes added based on bool value
"""
return '"%s"' % input_str if is_quotes_added else input_str |
def is_number(x):
"""Extracts all values that are numerical
Example: rel = [{('a',1), 'b', 3}, {('a',2), 'f', 'g'}]
>>rel[is_number]
[{3}]
"""
try:
float(x)
return True
except:
return False |
def sum_economic_loss(effect_list):
"""Sums the economic loss values in an effects list"""
return sum(el.economic_loss for el in effect_list) |
def _build_gcs_destination(config):
"""Builds a GcsDestination from values in a config dict.
Args:
config: All the user-specified export parameters. Will be modified in-place
by removing parameters used in the GcsDestination.
Returns:
A GcsDestination containing information extracted from
conf... |
def list_arg(raw_value):
"""argparse type for a list of strings"""
return str(raw_value).split(',') |
def extract_service_catalog(auth_response):
"""
Extract the service catalog from an authentication response.
:param dict auth_response: A dictionary containing the decoded response
from the authentication API.
:rtype: str
"""
return auth_response['access']['serviceCatalog'] |
def reverse(word):
"""
Return the reverse text of the provided word
"""
return word[::-1] |
def dot(a,b):
"""Dot product of two TT-matrices or two TT-tensors"""
if hasattr(a,'__dot__'):
return a.__dot__(b)
if a is None:
return b
else:
raise ValueError('Dot is waiting for two TT-tensors or two TT-matrices') |
def remove_duplicate(duplicate):
"""
remove duplicates in list
"""
final_list = []
for num in duplicate:
if num not in final_list:
final_list.append(num)
return final_list |
def merge_metadata(original, changes):
"""
Merge together two metadata dictionaries. By default, overwrite any existing values.
If the object is a list, concatenate the original and new list instead.
If the object is a dict with the $extend property set to true, merge the two
dictionaries instead of... |
def merge_two_dicts(x, y):
"""Given two dicts, merge them."""
z = x.copy()
z.update(y)
return z |
def first(s):
"""Return the first element from an ordered collection
or an arbitrary element from an unordered collection.
Raise StopIteration if the collection is empty.
"""
return next(iter(s.items())) |
def value_for_keypath(dict, keypath):
"""
Returns the value of a keypath in a dictionary
if the keypath exists or None if the keypath
does not exist.
"""
if len(keypath) == 0:
return dict
keys = keypath.split('.')
value = dict
for key in keys:
if key in value:
... |
def interval_toggle(swp_on, mode_val, dt):
"""change the interval to high frequency for sweep"""
if dt <= 0:
# Precaution against the user
dt = 0.5
if mode_val == "single":
return 1000000
else:
if swp_on:
return dt * 1000
else:
return 10000... |
def _lin_f(p, x):
"""Basic linear regression 'model' for use with ODR.
This is a function of 2 variables, slope and intercept.
"""
return (p[0] * x) + p[1] |
def linear_search(arr, x):
"""
Performs a linear search
:param arr: Iterable of elements
:param x: Element to search for
:return: Index if element found else None
"""
l = len(arr)
for i in range(l):
if arr[i] == x:
return i
return None |
def _parse_eloss(line, lines):
"""Parse Energy [eV] eloss_xx eloss_zz"""
split_line = line.split()
energy = float(split_line[0])
eloss_xx = float(split_line[1])
eloss_zz = float(split_line[2])
return {"energy": energy, "eloss_xx": eloss_xx, "eloss_zz": eloss_zz} |
def fix_delex(curr_dialog_acts, act_idx, text):
"""Given system dialogue acts fix automatic delexicalization."""
if not act_idx in curr_dialog_acts:
return text
turn = curr_dialog_acts[act_idx]
if isinstance(turn, dict): # it's annotated:
for key in turn:
if 'Attraction' i... |
def solution_(N):
"""
https://app.codility.com/demo/results/trainingWH96Z8-RSB/
The Idea is, until number is event increase the count
until number is odd keep state of longest number and reset the current longest
:param n =
:return:
Test - 9: below is the steps
1001 - 9
0001
0... |
def _surface_tilt(latitude):
"""
Returns the best surface tilt.
Equation by Oxford model.
Reference:
"""
lat = latitude
# In north hemisphere
if lat > 0:
best_tilt = 1.3793 + lat * \
(1.2011 + lat*(-0.014404 + lat*(0.000080509)))
# In south hemisphere
elif... |
def u_format(s):
""""{u}'abc'" --> "'abc'" (Python 3)
Accepts a string or a function, so it can be used as a decorator."""
return s.format(u='') |
def get_realtime_dublin_bus_delay(realtime_updates, trip_id, stop_sequence):
"""
Get the current delay for a particular trip from the response from the
realtime NTA API.
Args
---
realtime_updates: list
A list of dicts with updates for each trip from the realtime API
trip_... |
def find_string_indices(input_string, string_to_search):
"""Copied from
https://github.com/jeniyat/StackOverflowNER/blob/master/code/DataReader/read_so_post_info.py"""
string_indices=[]
location=-1
while True:
location = input_string.find(string_to_search, location + 1)
if locati... |
def remove_duplicate_words(s):
""" removes duplicate words from a string
s: a string of words separated by spaces
"""
s = s.split()
unique = []
for word in s:
if word not in unique:
unique.append(word)
s = ' '.join(unique)
return s |
def chunk(input_data, size):
"""
Chunk given bytes into parts
:param input_data: bytes to split
:param size: size of a single chunk
:return: list of chunks
"""
assert len(input_data) % size == 0, \
"can't split data into chunks of equal size, try using chunk_with_remainder or pad dat... |
def sort_points(labels, az_order = True):
"""
Sorts a list of letter-indexed (or letter-number-mixed) points, eg. "Neighbours"
Uses bubble sort, since list is already supposed to be sorted almost perfectly
NOTE: a-z order changes the order of num postfixes, too (C12, C8, B5, B3, ...)
Input: array o... |
def get_variables_from_monomial(monomial):
"""
It is fed by a non-constant monomial like x*y*z and
returns a list consisting of given monomial's
variables. which in this case are: ['x', 'y', 'z']
"""
assert(not monomial.isdigit())
temp = monomial.split('*')
temp.sort()
return temp |
def _interpolate_scalar(x, x0, x1, y0, y1):
"""
Interpolate between two points.
"""
return y0 + (y1 - y0) * (x - x0) / (x1 - x0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.