content stringlengths 42 6.51k |
|---|
def _all_are_equal(list_of_objects):
"""Helper function to check if all the items in a list are the same."""
if not list_of_objects:
return True
if isinstance(list_of_objects[0], list):
list_of_objects = [tuple(obj) for obj in list_of_objects]
return len(set(list_of_objects)) == 1 |
def int2color(x):
"""
converts lattice integer to RGB tuple
:param x: int
:return: RGB
"""
# r = int(1000 * x % 255)
# g = int(10000 * x % 255)
# b = int(100000 * x % 255)
x = 0 if x == 0 else int(1/x)
b = x & 0xff
g = (x >> 8) & 0xff
r = (x >> 16) & 0xff
return [r, g... |
def lerp(t, a, b):
"""Linear Interpolation function
Args:
t (float): Alpha Value
a (np.ndarray): Vector 1
b (np.ndarray): Vector 2
Returns:
(np.ndarray) Vector from linear interpolation
"""
return (1 - t) * a + t * b |
def imod(a, b):
"""Same as a %= b."""
a %= b
return a |
def mapped_to_chromosome(chrom):
"""
Returns true if mapped to, eg, chr1 or X;
false if mapped to other contig, eg GL*, MT*, hs*, M*
"""
if chrom[0:2] in ["GL", "MT", "hs", "NC"] or chrom[0:1] == "M":
return False
return True |
def vertices_generation(number_of_vertices):
"""
Generate the vertices list
:param number_of_vertices:
:return: vertices list in format [0, 1, 2, 3...]
"""
# here, the list is much more efficient than set
return [s for s in range(1, number_of_vertices + 1)] |
def findTheDifferenceB(s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
result = 0
for char in t:
result += ord(char)
for char in s:
result -= ord(char)
return chr(result) |
def squeeze(array):
"""Return array contents if array contains only one element.
Otherwise, return the full array.
"""
if len(array) == 1:
array = array[0]
return array |
def moira_user_emails(member_list):
"""
Transform a list of moira list members to emails.
Assumes kerberos id => <kerberos_id>@mit.edu
Args:
member_list (list of str): List of members returned by Moira
Returns:
list of str: Member emails in list
"""
return list(
map... |
def check_variable_exists(variable: str) -> bool:
""" Function check variable is exist or not """
if variable in globals():
return True
elif variable in locals():
return True
return False |
def mac_matches_by_one(formatted_mac_1: str, formatted_mac_2: str) -> bool:
"""Check if a mac address is only one digit off.
Some of the devices have two mac addresses which are
one off from each other. We need to treat them as the same
since its the same device.
"""
mac_int_1 = int(formatted_m... |
def shorten_number(number: int, width: int) -> str:
""" """
result = "%*d" % (width, number)
if len(result) <= width:
return result
number //= 1000;
result = "%*dk" % (width - 1, number)
if len(result) <= width:
return result
number //= 1000;
result = "%*dM" % (width - 1,... |
def parse_metadata_state_descriptions(state_string):
"""From string in format 'col1:good1,good2;col2:good1' return dict."""
result = {}
state_string = state_string.strip()
if state_string:
cols = [s.strip() for s in state_string.split(';')]
for c in cols:
# split on the firs... |
def parse_amount(value):
""" Convert string to amount (float)
:param value: string value
:return: float value if the parameter can be converted to float, otherwise None
"""
try:
return float(value)
except ValueError:
return None |
def iob2(tags):
""" Check that tags have a valid IOB format.
Tags in IOB1 format are converted to IOB2. """
for i, tag in enumerate(tags):
if tag == 'O':
continue
split = tag.split('-')
if len(split) != 2 or split[0] not in ['I', 'B']:
return False
if ... |
def get_speciesindices(specieslist):
"""
Create a dictionary to assign an arbitrary index to each of the species in
the kinetic scheme.
Parameters
----------
specieslist : list
a list of all the species in the model
Returns
-------
speciesindices : dict
... |
def kalkulasi_percepatan(
kecepatan_awal: float, kecepatan_akhir: float, waktu: float
) -> float:
"""
Menghitung percepatan dari suatu pergerakan
dengan kecepatan awal dan kecepatan akhir yang berbeda
>>> kalkulasi_percepatan(10, 22, 5)
2.4
>>> kalkulasi_percepatan(10, 17.2, 1)
7.1999999... |
def calculate_precision(pred_vector, label_vector):
"""
Calculate the precision of the predicted values.
"""
n = len(pred_vector)
TP = sum([(label_vector[i] == 1) and (pred_vector[i] == 1) for i in range(n)])
FP = sum([(label_vector[i] == 0) and (pred_vector[i] == 1) for i in range(n)])
... |
def is_prembeable(index_of_number,array,length):
"""
CHeck hogy jo e a szam
"""
i=index_of_number-length
while i<index_of_number:
j=i+1
while j<index_of_number:
if(array[index_of_number]==array[i]+array[j]):
return True
j=j+1
i=i+1
return False |
def bubble_sort(list):
"""Sort list using Bubble Sort algorithm
Arguments:
list {integer} -- Unsorted list
Returns:
list {integer} -- Sorted list
"""
swap=True
test ="It is a bad code";
while swap:
swap = False
for n in range(len(list) - 1 ):
... |
def quick_remove_equivalent_partitions(partitions):
"""Just remove double ups. (For now.)
This is also a good place to remove partitions that you know will be
filtered out.
"""
return list(set(partitions)) |
def _prec(p,l):
"""
retrieve the predecessor of p in list l
"""
pos = l.index(p)
if pos-1 < 0:
return l[-1]
else:
return l[pos-1] |
def get_frame(filename):
"""
Example of filename: '/tmp2/ashesh/gaze360_data/imgs/rec_022/head/000000/000131.jpg'
"""
tokens = filename.split('/')
return int(tokens[-1].split('.')[0]) |
def url_mape(seed:int):
"""Turn seed into map url of the form '/map/xxxxxxxxxx'"""
return f"/map/{seed}" |
def normalize(dist):
"""Scale values in a dictionary or list such that they represent
a probability distribution. Each value lies in 0 <= value <= 1
and the sum of all values is 1.
:param dist: The distribution. May be numeric, or a dictionary of numeric
values. Note that dictiona... |
def find_blocksize(x_dim, y_dim, desired_size):
"""
Finds the appropriate block size for an input image of a given dimensions.
Method returns the first factor of the input dimension that is greater than
the desired size.
"""
block_size_x = desired_size
block_size_y = desired_size
... |
def check_integer(initial_number_of_balls):
"""
This function checks if the user's initial input is an integer or not.
If not: return False
If it is: return True
:param initial_number_of_balls: this is the variable saving the user's input
:return: True if the user puts in an integer
F... |
def sortCirclesBySize(circles):
"""
Sort a list of circles by size;
The imput is a list of [x,y,r] items where r is the size
The return is the list sorted
"""
sortedCircles = sorted(circles,key=lambda circles: circles[2])
return sortedCircles |
def unique(inlist):
"""
Returns all unique items in the passed list. If the a list-of-lists
is passed, unique LISTS are found (i.e., items in the first dimension are
compared).
Usage: unique (inlist)
Returns: the unique elements (or rows) in inlist
"""
uniques = []
for item in inlist:
if item no... |
def tile_position(tile_ref, tile_size):
"""Returns the x and y coordinates of the top-left corner of a tile, given the tile's row and column.
tile_ref is a 2-item sequence representing the column and row of the tile
tile_size is the size of each tile as an int."""
return tile_ref[0]*tile_s... |
def _unique_id_from_status(status):
"""Find the best unique id value from the status."""
serial = status.get("Serial")
if not serial:
return None
return serial |
def shift(g, dx, dy=0):
"""Punkte im Pfad/Glyph g um dx und dy verschieben"""
return [(x + dx, y + dy) for (x, y) in g] |
def isunicode(c):
"""
return True if `c` is a non-ASCII unicode code point
"""
return c != '' and ord(c) >= 128 |
def _set_default_rated_temperature(rated_temperature_max: float, type_id: int) -> float:
"""Set the default max rated temperature for mechanical relays.
:param rated_temperature_max: the current maximum rated temperature.
:param type_id: the type ID of the relay with missing defaults.
:return: _rated_t... |
def handleWPTS(wpts):
"""Handler for Waypoints in gpx xml-dom."""
w = []
for wpt in wpts:
if wpt.hasAttribute('lat'):
lat = float(wpt.getAttribute('lat'))
else:
continue
if wpt.hasAttribute('lon'):
lon = float(wpt.getAttribute('lon'))
else... |
def yes_no(value):
"""Convert boolen value to text representation
:param value: Truth value to be converted
:type value: bool
:return: Yes or No text
:rtype: str
"""
return 'Yes' if value else 'No' |
def change_characters(mapping, change):
"""
Changes the mapping according to the partial mapping given in "change".
Returns an error in the case where a key has two characters mapped on it.
"""
new_mapping = mapping.copy()
for c, v in change.items():
new_mapping[c] = v
rev_multidic... |
def nonConstructibleChangePrimary(coins):
"""
Takes an arrary of coin values and find the minimum change that can't be made by the coins
available in the array.
solution complexity : O(nlogn) time complexity and O(1) space complexity
args:
-----------
coins (array): an array contains available coin values.... |
def remove_none(options):
"""
Simple function that traverse the options and removed any None items
CloudCA really dislikes null values.
:param options:
:return:
"""
new_dict = {}
for k, v in options.items():
if v:
new_dict[k] = v
# this is super hacky and gross,... |
def is_remote_path(path):
"""
Returns True iff the path is one of the remote formats that this
module supports
"""
return path.startswith('gs://') or path.startswith('hdfs://') |
def merge_dicts(d1: dict, d2: dict) -> dict:
"""Merge nested dictionaries in depth.
:param d1: First dictionary to merge
:param d2: Second dictionary to merge, takes precedence over the first
:return: A dictionary merged from d1 and d2
"""
d3 = {}
d1keys = set(d1)
d2keys = set(d2)
... |
def alphabet(num):
"""
Returns a capital letter from a number.
:param num: int
:return:
"""
return chr(65 + (num % 26)) |
def append(the_audio, sound):
""" the_audio += asound, None==empty """
if sound is None:
return the_audio
if the_audio is None:
return sound
return the_audio + sound |
def _scss_to_dict(string):
"""Parse variables and return a dict."""
data = {}
lines = string.split('\n')
for line in lines:
line = line.strip()
if line and line.startswith('$'):
key, value = line.split(':')
key = key[1:].strip()
key = key.replace('-'... |
def factorial(
of: int,
down_to: int = 0
) -> int:
"""
Returns the multiplication of all positive integers from ``of`` down
to (but not including) ``down_to``.
:param of:
The greatest positive integer to include in the product.
:param down_to:
The gre... |
def back_transform(string):
"""Tranform the string, which can contains not allowed printable chars to the
string with escape sequences
Arguments:
string(string): string to tranformation
Return:
string: the string with escape sequences
"""
i = 0
while i < len(string):
... |
def subtract_overlap (uncovered_regions, covered_regions, spacer = 0):
"""
Given two sets of regions in the form
[[start, end], [start, end]], return a set
of regions that is the second set subtracted from
the first.
"""
uncovered_set = set()
for r in uncovered_regions:
try:
... |
def fibonacci(n):
""" Return nth Fibonacci sequence number computed recursively
"""
if n < 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) |
def _color_burn(a, b):
"""
:type a: ImageMath._Operand
:type b: ImageMath._Operand
:rtype: ImageMath._Operand
"""
non_zero_area = (b != 0)
fa = a / 255.0
fb = b / 255.0
return (1.0 - ((1.0 - fa) / fb)) * 255.0 * non_zero_area |
def replicate_compartment(
n_replications,
current_compartments,
compartment_stem,
infectious_compartments,
initial_populations,
infectious=False,
infectious_seed=0.,
):
"""
Implements n repeated sequential compartments of a certain type
Also returns t... |
def duplicates(tests):
"""Return question duplicates.
"""
dup = set()
seen = set()
for q in tests:
if q in seen:
dup.add(q)
else:
seen.add(q)
return dup |
def multiply(x, y):
"""
Function to multiply two numbers
Parameters
----------
x : int/float
First number to be multiplied
y : int/float
Second number to be multiplied
Returns
-------
product : int/float
Sum of the two numbers
... |
def swagger_type_to_pydantic_type(t, models=[]):
"""Given a swagger type or format or ref definition, return its corresponding python type"""
# Take a swagger type and return the corresponding python type
if t in models:
return t
mapping = {
# swagger type: pydantic type (https://pydant... |
def take(n, seq):
"""Returns first n values from the given sequence."""
# seq = iter(seq)
# seq = seq
result = []
try:
for i in range(n):
result.append(seq.next())
except StopIteration:
pass
return result |
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1):
"""
Utility function for computing output of convolutions
takes a tuple of (h,w) and returns a tuple of (h,w)
"""
if type(h_w) is not tuple:
h_w = (h_w, h_w)
if type(kernel_size) is not tuple:
kernel_size =... |
def _older_than(number, unit):
"""
Returns a query item matching messages older than a time period.
Args:
number (int): The number of units of time of the period.
unit (str): The unit of time: "day", "month", or "year".
Returns:
The query string.
"""
return f"older_th... |
def triples2relations(triples):
"""
:param triples:
:return:
>>> triples2relations([[1,2,3], [0, 3,4]])
[1,0]
>>> triples2relations([[1,2,3], [1,2,3]])
[1]
"""
relations = []
for triple in triples:
relations.append(triple[0])
return list(set(relations)) |
def l_sa_check(template, literal, is_standalone):
"""Do a preliminary check to see if a tag could be a standalone"""
# If there is a newline, or the previous tag was a standalone
if literal.find('\n') != -1 or is_standalone:
padding = literal.split('\n')[-1]
# If all the characters since t... |
def get_chess_square(size, x, y):
"""
Returns the coordinates of the square block given mouse position `x` and `y`
"""
return (x // (size // 8), y // (size // 8)) |
def first_occ_index(array, n_at_least):
"""
Getting index of first occurence in boolean array
with at least n consecutive False entries
"""
curr_found_false = 0
curr_index = 0
for index, elem in enumerate(array):
if not elem:
if curr_found_false == 0:
curr... |
def get(tree, s):
"""Get the tree node or full pathname for a specified
tuple of indices such as (1, 3, 2). Returns None if not found."""
if len(s) == 0:
return 'top', tree
name, e = tree[s[0]]
if len(s) == 1:
return name, e
return get(e, s[1:]) |
def query_list_to_list(query_list):
"""
OrderedDict_list==>list
OrderedDict_dict==>dict
"""
if not query_list:
return []
if isinstance(query_list, dict):
try:
return dict(query_list)
except:
return query_list
elif isinstance(query_list, li... |
def get_pred(succ):
"""Given a successor edge map, produce an inverted predecessor edge
map.
"""
out = {key: [] for key in succ}
for p, ss in succ.items():
for s in ss:
out[s].append(p)
return out |
def format_file_size(size_in_bytes: float) -> str:
"""Return a string representation of the specified size as its largest 2^10 representation
Examples:
>>> format_file_size(2048)
'2.00 KiB'
>>> format_file_size(16252928.0)
'15.50 MiB'
Args:
size_in_bytes: a size in ... |
def reg_dims(reg):
"""
Accepts a dict containing the fields 'start' and 'nbits'.
Returns a string containing the dims in verilog syntax.
If nbits is 0, returns empty string.
"""
if (int(reg['nbits']) == 0):
return ''
else:
return "["+str(int(reg['nbits'])+int(reg['start'])-1)+":"+reg['start']+"]" |
def header(img, author, report_date, report_time, report_tz, title) -> str:
"""Creates reports header
Parameters
----------
img : str
Image for customizable report
author : str
Name of author responsible by report
report_date : str
Date when report is run
report_time... |
def split(list_a: list, length_of_first: int):
"""Problem 17: Split a list in two parts; the length of the first list is given.
Parameters
----------
list_a : list
The input list
length_of_first : int
The desired length of the first output list
Returns
-------
(list, li... |
def calc_intensity(locations):
""" Calculate intensity per location"""
max_duration = float(max(locations.values()))
result = {}
for key, value in locations.items():
result[key] = value/max_duration
return result |
def _merge_questions(text_questions, choice_questions):
"""Merge the choice and text based questions into schedule type
{'Talk': {'text': [..], 'choice': [...]},}
"""
types = set(text_questions.keys())
types.union(list(choice_questions.keys()))
questions = {}
for item in types:
quest... |
def recipe_prior_step(recipe, step):
"""Compares a recipe and a step, and returns the prior step
"""
steps = recipe['recipe']
if steps.index(step) == 0:
return step
return steps[steps.index(step)-1] |
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 0)
1
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
"""
falling_result = 1
if k == 0:
return falling_result
while k >= 1:
... |
def carry(b, a, compute_p=True):
""" Carry propogation:
(p,g) = (p_2, g_2)o(p_1, g_1) -> (p_1 & p_2, g_2 | (p_2 & g_1))
"""
if compute_p:
t1 = a[0] * b[0]
else:
t1 = None
t2 = a[1] + a[0] * b[1]
return (t1, t2) |
def extract_id(link: str) -> str:
"""Extract ID from URL"""
link = link.replace("?usp=sharing", "")
file_id = link[link.find("1") :]
end = file_id.find("/")
if end != -1:
file_id = file_id[:end]
return file_id |
def test(condition, true, false):
"""
Implements the C expression:
condition ? true : false
Required to correctly interpret plural forms.
"""
if condition:
return true
else:
return false |
def reverse_hex(input_hex):
"""Reverse a HEX string, treating 2 chars as a byte.
Expected results look like this:
reverse_hex('abcdef') = 'efcdab'
Args:
input_hex (str): Input string in hex which needs to be converted.
Returns:
Hex string reversed.
"""
return "".join([inpu... |
def postal(value, strip=False):
"""A very generic postal code validator that is meant to allow all international postal codes through"""
if strip:
value = value.strip()
length = len(value)
if length < 2:
raise ValueError(
"Provided value {} is shorter than any official posta... |
def determineTotalBytes(list):
"""
:param list:
:return total:
"""
# Returns the length of the list divided by 8 as an integer (no remainder)
return int(len(list) / 8) |
def rank2int(rank):
"""Convert a rank/placing string into an integer."""
ret = None
try:
ret = int(rank.replace('.',''))
except:
pass
return ret |
def clamp(value, inMin, inMax):
"""returns the value clamped between inMin and inMax"""
return min(inMax, max(inMin, value)) |
def _explode_permissions(entry):
"""
This function flattens permission objects in order to distribute permission attributes
out to the individual permission entries. For example, this code will take the following
entry:
```
{
"user_name": "owner@company.com",
"all_permissions":... |
def filter_packages(packages: list, key: str) -> list:
"""Filter out packages based on the given category."""
return [p for p in packages if p["category"] == key] |
def pf_mobility(phi, gamma):
""" Phase field mobility function. """
#func = 1.-phi**2
#return 0.75 * gamma * max_value(0., func)
return gamma |
def _parse_arg(s):
"""Parse a number or string."""
try:
return int(s)
except ValueError:
pass
try:
return float(s)
except ValueError:
pass
return s |
def is_defined(value):
"""Return True IFF `value` is not 'UNDEFINED' or None.
>>> is_defined("UNDEFINED")
False
>>> is_defined(None)
False
>>> is_defined("FOO")
True
"""
return value not in ["UNDEFINED", None] |
def toy2(choice):
""" return three fake line lists to play with"""
lines1 = {"lee":115.27, "doug":115.0, "marc":112.0}
lines2 = {"leslie":111.00, "mark":110.0, "peter":113.0}
lines3 = {"lisa":114.0, "robert":112.1, "kevin":112.2}
if choice == 1:
return lines1
elif choice == 2:
... |
def parse_dict(the_dict):
"""parse dictionary from string without worrying about proper json syntax"""
if isinstance(the_dict, str):
the_dict = the_dict.replace('{', '').replace('}', '')
tkns = the_dict.split(',')
if len(tkns) > 1:
return {tkn.split(':')[0].strip(): tkn.split... |
def split_snake_case_name_to_words(name):
""" 'snake_case_name' -> ['snake', 'case', 'name'] """
return [n for n in name.split('_') if n] |
def fib_recursive(n):
"""Calcualte n-th element of Fibonacci sequence.
Returns: Fibonacci n-the element.
"""
if n == 0: # base cases
return 0
elif n == 1:
return 1
else: # general case
return (fib_recursive(n-1) + fib_recursive(n-2)) # use recursion |
def binlist(n, width=0):
"""
Return list of bits that represent a non-negative integer.
n -- non-negative integer
width -- number of bits in returned zero-filled list (default 0)
"""
return list(map(int, list(bin(n)[2:].zfill(width)))) |
def remove_duplicates(input_dataset, input_scores):
"""Remove duplicate elements in a dataset
Parameters
-------
input_dataset : list
list of dictionaries, each one corresponds to a piece
input_scores : list
list of scores of each piece
Returns
-------
output_dataset :... |
def ten_digit_to_comma_format(badge):
"""Returns the comma-format RFID number (without the comma) from the
10-digit RFID number.
Explanation:
*On an EM4100/4001 spec RFID card, there will generally be two sets of
numbers like this: 0015362878 234,27454
*The part of the number before the comma r... |
def pct_to_value(data, d_pct):
"""
Function takes dictionary with base value, and dictionary with percentage and converts percentage to value.
"""
if not data or not d_pct:
return data
out_map = {}
for _k in data:
if _k not in d_pct:
continue
out_map[_k] = ... |
def show_sexp(e):
"""Convert an S-expr to a string."""
if isinstance(e, tuple):
return '(%s)' % ' '.join(show_sexp(s) for s in e)
elif isinstance(e, str):
return e
else:
raise TypeError('Expected tuple or str, got %r' % (e,)) |
def _proposed_scaling_both(current, desired):
"""
identify a x and y scaling to make the current size into the desired size
Arguments
---------
current : tuple
float tuple of current size of svg object
desired : tuple
float tuple of desired size of svg object
Returns
--... |
def parseBwvs(bws, bwvs=""):
"""
Parse input bigwig values limts.
"""
if bwvs == "":
bwvs = []
for i in range(len(bws)):
bwvs.append([None, None])
else:
bwvs = bwvs.split(";")
nbwvs = []
for t in bwvs:
if t == "":
nbwvs.... |
def ComputerIcon(icon_one, icon_two, player_icon):
"""Return the opposite icon to the accepted player icon"""
if player_icon == icon_one:
return icon_two
else:
return icon_one |
def get_dict_val(refobject):
""" dict type format
"""
values = [str(k) + ': ' + repr(val) for k, val in refobject.items()]
return '\n'.join(values) |
def Loss_Calc(Eta_Act, Eta_Ohmic, Eta_Conc):
"""
Calculate loss.
:param Eta_Act: Eta activation [V]
:type Eta_Act : float
:param Eta_Ohmic: Eta ohmic [V]
:type Eta_Ohmic : float
:param Eta_Conc: Eta concentration [V]
:type Eta_Conc : float
:return: loss [V] as float
"""
try:... |
def is_solution(cnf, assignment):
"""Test whether the given assignment is a solution to the CNF.
assignment is a dictionary from variable names to truth values.
It is not required that all variables in the CNF are assigned.
"""
for clause in cnf:
satisfied = False
for lit in clause... |
def getDirFromPts(p0,p1,p2):
"""
Determines the directin of the path formed by following
points p0 -> p1 -> p2.
"""
x0,y0 = p0
x1,y1 = p1
x2,y2 = p2
ccwTest = (x1-x0)*(y2-y0) > (y1-y0)*(x2-x0)
if ccwTest:
return 'ccw'
else:
return 'cw' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.