content stringlengths 42 6.51k |
|---|
def calculateFlightDistance(planePartStatus):
"""
Calculates the "score" the user gets based on which parts of the plane are coloured in.
If they are missing any part of the plane, 10 points deducted.
"""
score = 0
for i in planePartStatus:
if planePartStatus[i] == True:
scor... |
def get(iterable, **fields):
"""Returns a list of items in the :attrs: iterable that have the :attrs: attr equal to :attrs: value. For
example:
game = get(client.get_all_games(), id=2)
would find the all :class: Game whose id is 2 and return them as a list. If no entry is found then
the empty ... |
def service_urls(service_data):
"""
Args:
service_data (Dict): the loaded service data
Returns:
List[str]: list of urls of a service
"""
return service_data.get('urls') |
def ret_normalized_vec(vec, length):
"""Normalize vector.
Parameters
----------
vec : list of (int, number)
Input vector in BoW format.
length : float
Length of vector
Returns
-------
list of (int, number)
Normalized vector in BoW format.
"""
if length ... |
def _get(data, key, default_value=None):
"""Wrapper for raising a prettier exception if data is missing.
Args:
data (dict): Object whose `get` method is called with `key`.
key (object): Value passed to `data.get`.
default_value (object or None): Optional value to return if the key is
missing.
... |
def extgcd(a, b):
"""solve ax + by = gcd(a, b)
return x, y, gcd(a, b)
unproved
"""
g = a
if b == 0:
x, y = 1, 0
else:
x, y, g = extgcd(b, a % b)
x, y = y, x - a // b * y
return x, y, g |
def RepresentsInt(s):
"""Determines if a stri could be an int.
:arg s: The string to be tested.
"""
try:
int(s)
return True
except ValueError:
return False |
def read_confounds(confounds):
""" Process input list of confounds.
Parameters
----------
confounds : list of str
List of confounds with categorical variables indicated by c(var) ('c' must be lower case).
Returns
-------
list
List of all confounds without wrapper on categor... |
def words_to_indices(sentence, worddict):
"""
Transform the words in a sentence to integer indices.
Args:
sentence: A list of words that must be transformed to indices.
worddict: A dictionary associating words to indices.
Returns:
A list of indices.
"""
# Include the be... |
def rfind(s, sub, i = 0, last=None):
"""rfind(s, sub [,start [,end]]) -> int
Return the highest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
Slen = len(s) # cache this... |
def makeQTXML(d):
"""Makes an xml file as plain text"""
"""make the header"""
s = """<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="../../help.xsl"?>
<documentation>"""
s += '</documentation>'
return s |
def show_tnseq_upload_btn(network_type):
"""Show TnSeq upload button when combined networks are selected."""
return {'display': 'block'} if network_type == 'combined' else {'display': 'none'} |
def middle_truncate(value, size):
"""
Truncates a string to the given size placing the ellipsis in the middle.
"""
size = int(size)
if len(value) > size:
if size > 3:
start = (size - 3) / 2
end = (size - 3) - start
return value[:start] + u'\u2026' + value[... |
def _print(*args):
"""Print an object in the stdout."""
return print(*args) |
def ordered(obj):
"""
Creates and ordered list from a given object. Can handle nested dictionaries and lists
Args:
obj (object): The object to order
Returns:
object: An ordered list or the original object if it is not a dict or list
"""
if isinstance(obj, dict):
return ... |
def prepare_search_keyword(s):
"""Prepare the search keywords into the form that is appropriate for searching
according to our tokenization algorithm."""
return s.lower().strip() |
def get_word_count(text, keywords):
"""
Args:
text (str):
keywords (list):
Returns:
"""
count_dict = {}
for keyword in keywords:
count_dict[keyword] = text.count(keyword)
return count_dict |
def collatzConjecture(n):
"""Returns the Fibonacci sequences to the nth entry as a list of
integers."""
if not isinstance(n, int):
raise TypeError('n should be an integer larger than 1.')
return None
if not n > 1:
raise ValueError('n should be an integer larger than 1.')
... |
def corners(flipped_points):
"""
Takes a set of lat-lon points that have been
flipped to image array coordinates and finds
the top left and and bottom right corner coordinates.
"""
x_vals = [x for (x, y) in flipped_points]
y_vals = [y for (x, y) in flipped_points]
top_left = (min(x_vals)... |
def check_reward_volume_set(data, **_):
""" Check that there is only two reward volumes within a session, one of which is 0.
Metric: M = set(rewardVolume)
Criterion: (0 < len(M) <= 2) and 0 in M
:param data: dict of trial data with keys ('rewardVolume')
"""
metric = data["rewardVolume"]
pa... |
def strip(text):
"""Strips whitespace from end of line"""
return text.rstrip("\n\t ") |
def splitlines(string_with_lines):
"""Return a ``list`` from a string with lines."""
return string_with_lines.splitlines() |
def add2(a, b):
"""exec a + b = ?"""
print('exec add2')
ret = a + b
print('add2: %s + %s = %s' % (a, b, ret))
return ret |
def _unquote(s):
"""Helper func that strips single and double quotes from inside strings"""
return s.replace('"', '').replace("'", "") |
def find_the_nth_term_for_a_geometric_sequence(first_term: int, common_ratio: int, requested_term: int) -> int:
"""
Find the nth term in a geometric sequence
:param first_term:
:param common_ratio:
:param requested_term:
:return: the nth term
"""
return first_term * common_ratio ... |
def load_dist_config(distid):
"""Creates a configuration with differently distributed
decision values for positives and negatives, which will
result in differently shaped performance curves.
distid = 1: high initial precision (near-horizontal ROC curve)
distid = 2: low initial precision (near-verti... |
def get_ordered_unique_list(seq, rev=False):
""" get_ordered_unique_list() """
return sorted(set(seq), reverse=rev) |
def calculate_score(cards):
"""Returns the score of the hand"""
if sum(cards) == 21 and len(cards) == 2:
return 0
if 11 in cards and sum(cards) > 21:
cards.remove(11)
cards.append(1)
return sum(cards) |
def getGUIDForLFN(file_dictionary, scope_lfn):
""" Get the guid that coresponds to the lfn """
found = False
guid = ""
# Locate the guid that corresponds to this lfn
for _guid, _scope_lfn in file_dictionary.items():
if scope_lfn == _scope_lfn:
guid = _guid
break
... |
def compare(O, E):
"""Returns a similarity score for corresponding elements in O and E"""
return (O - E) / E |
def describe_flip_angle(metadata: dict) -> str:
"""Generate description of flip angle."""
return "flip angle, FA={}<deg>".format(metadata.get("FlipAngle", "UNKNOWN")) |
def isActive(dict, gameID, playerID):
"""Returns true if player is currently active, false otherwise"""
return dict[gameID][playerID]["isActive"] |
def catmull_rom_one_point(x, v0, v1, v2, v3):
"""Computes interpolated y-coord for given x-coord using Catmull-Rom.
Computes an interpolated y-coordinate for the given x-coordinate between
the support points v1 and v2. The neighboring support points v0 and v3 are
used by Catmull-Rom to ensure a smooth ... |
def get_face_names_from_indices(mesh, indices):
"""
Given a list of face indices and a mesh, this will return a list of face names.
The names are built in a way that cmds.select can select them.
"""
found = []
for index in indices:
name = '%s.f[%s]' % (mesh, index... |
def mapRange(value, inMin, inMax, outMin, outMax):
"""
Function to interpret the steam-jack float values
"""
return outMin + (((value - inMin) / (inMax - inMin)) * (outMax - outMin)) |
def dotted_ip_to_bytes(ip: str) -> bytes:
"""
Convert a dotted IPv4 address string into four bytes, with
some sanity checks
"""
ip_ints = [int(i) for i in ip.split(".")]
if len(ip_ints) != 4 or any(i < 0 or i > 255 for i in ip_ints):
raise ValueError
return bytes(ip_ints) |
def get_sign(value: int) -> int:
"""
Determines the sign of a number.
Parameters
----------
value : `int`
The value whose sign is to be determined.
Returns
-------
sign : `int`
The sign of the number (-1 or 0 or 1).
The return value is based on math signum funct... |
def windMagValue(value):
"""Method to return a vector component magnitude as a string some processing"""
try:
return str(int(round(value)))
except:
return "999" |
def match(words, times):
"""A data abstraction containing all words typed and their times.
Arguments:
words: A list of strings, each string representing a word typed.
times: A list of lists for how long it took for each player to type
each word.
times[i][j] = time it too... |
def solve_one(l):
"""solved using map/dictionary. And used library function"""
mp = dict()
for i in l:
if i not in mp.keys():
mp[i] = 1
else:
mp[i]+=1
return sorted(list(mp.values()),reverse=True)[0] |
def uptime_str_from4bytes(uptime: bytes) -> str: # b'\x00\n\xab\xa2'
""" Convert bytestring to string representation of time
Args:
uptime: source bytestring
Returns:
Days, hours, minutes and seconds of device uptime
"""
t = int(uptime.hex(), 16)
d = int(t / 86400)
h = int(... |
def sort_by_multiple_indexes(lst: list, *index_nums: int, reverse=False):
"""With a two dimensional array, returns the rows sorted by one or more column index numbers.
Example:
>>> mylst = []
# create the table (name, age, job)
>>> mylst.append(["Nick", 30, "Doctor"])
>>> my... |
def formatr(x):
"""Abbreviated formatting"""
if hasattr(x,'__name__'): return x.__name__
if isinstance(x,bool) : return '1' if x else '0'
if isinstance(x,float) : return '{0:.5g}'.format(x)
if x is None: return ''
return str(x) |
def GetSPPosition(topo):#{{{
"""
Get position of Signal Peptide given a topology
2015-02-10
"""
posSP=[]
b = topo.find('S')
if b != -1:
e=topo.rfind('S')+1
posSP.append((b,e))
return posSP |
def digits(x):
"""returns digits of x"""
if type(x) != int:
print("ERROR <- x in factorial(x) is not type int")
return
return [int(i) for i in list(str(x))] |
def flops_to_string(flops, units="GFLOPs", precision=2):
"""Convert FLOPs number into a string.
Note that Here we take a multiply-add counts as one FLOP.
Args:
flops (float): FLOPs number to be converted.
units (str | None): Converted FLOPs units. Options are None, 'GFLOPs',
'MFL... |
def calc_margin_call_drop(current_lvr, base_lvr, buffer=0.0):
"""Calculates the % drop required to trigger a margin call
Args:
current_lvr (float): LVR on the loan
base_lvr (float): Max LVR allowed
buffer (float, optional): Defaults to 0.0. LVR buffer that triggers a drawdown
Retur... |
def javaData(x):
"""Create apparent Java data file format, to match pip dat files."""
if isinstance(x, str):
x = x.encode()
if isinstance(x, bytes):
return javaData(len(x))[2:] + x
if isinstance(x, int):
s = b"" # 4 bytes, most significant first
for i in range(4)... |
def get_string_from_bytes(byte_data, encoding="ascii"):
"""Decodes a string from DAT file byte data.
Note that in byte form these strings are 0 terminated and this 0 is removed
Args:
byte_data (bytes) : the binary data to convert to a string
encoding (string) : optional, the encoding type to... |
def ordenar(usuario):
"""Funcion creada para darle criterio a la funcion sorted"""
return usuario[0].lower() |
def str_aligned(results, header=None):
"""
Given a tuple, generate a nicely aligned string form.
>>> results = [["a","b","cz"],["d","ez","f"],[1,2,3]]
>>> print str_aligned(results)
a b cz
d ez f
1 2 3
Args:
result: 2d sequence of arbitrary types.
header:... |
def SubOne(bv):
"""Subtract one bit from a bit vector."""
new = bv
r = range(1, len(bv) + 1)
for i in r:
index = len(bv) - i
if 1 == bv[index]:
new[index] = 0
break
new[index] = 1
return new |
def build_stats(train_result, eval_result, time_callback):
"""Normalizes and returns dictionary of stats.
Args:
train_result: The final loss at training time.
eval_result: Output of the eval step. Assumes first value is eval_loss and
second value is accuracy_top_1.
time_callback: Time tracking ca... |
def to_string(pairs):
"""Converts a series of (int, int) tuples to a time series string."""
return " ".join("%i:%i" % pair for pair in pairs) |
def trim(string, length=70): # type: (str, int) -> str
"""Trim a string to the given length."""
return (string[:length - 1] + '...') if len(string) > length else string |
def rgba(red, green, blue,
alpha=1):
"""
Return the string HTML representation of the color
in 'rgba(red, blue, green, alpha)' format.
:param red: 0 <= int <= 255
:param green: 0 <= int <= 255
:param blue: 0 <= int <= 255
:param alpha: 0 <= float or int <= 1
:return: str
... |
def get_clusters(cluster_config):
"""Get list of clusters"""
return list(cluster_config['clusters']) |
def get_wgs84_utm_epsg_code(*utm_zone):
"""
Convert utm zone information to an EPSG code to make projection definition easier. Can take parameters output
from `get_utm_zone` as arguments for `utm_zone`.
:param utm_zone: iterable with at least two parameters (zone number[int], hemisphere[str:'north'|'so... |
def pipeline_select_genre(artist_genres):
"""
Assign single, broad genre to track
Parameters:
|| artist_genres (list) ||
collection of Spotify-generated artists for the
artist the function is being called for
Returns:
|| _ (string) ||
broad genre to ... |
def callback(_):
"""Stub callback."""
return {"Water": True} |
def clicked_quality_reward(responses):
"""Calculates the total clicked watchtime from a list of responses.
Args:
responses: A list of IEvResponse objects
Returns:
reward: A float representing the total watch time from the responses
"""
qual = 0.0
watch = 0.0
for response in res... |
def branch_options(branch):
""" Enables or not the options for branch technique according to switch"""
if not branch:
return True, True
else:
return False, False |
def get_line_equation(p1, p2):
"""
Solve the system of equations:
y1 = m*x1 + b
y2 = m*x2 + b
This translates to:
m = (y2 - y1) / (x2 - x1)
b = y1 - m*x1
Input:
p1: first point [x1, y1]
p2: second point [x2, y2]
returns: slope, intercept
"""
m = (p2[1] ... |
def getminmax_tournament(arr, low, high):
""" Tournament Method
Divide the array into two parts and compare the maximums and minimums of the two
parts to get the maximum and the minimum of the whole array.
"""
if low == high:
return arr[low], arr[low]
if abs(low - high) == 1:
... |
def ymxc_line_points(m, c, min_x, max_x, step=1):
"""
Function to return the points for y = mx + c
"""
x_values = []
y_values = []
x = min_x
while x <= max_x:
y_value = m * x + c
x_values.append(x)
y_values.append(y_value)
x += step
return (x_values, ... |
def find_line(xs, ys):
"""Calculates the slope and intercept, using normal equations"""
# number of points
n = len(xs)
# calculate means
x_bar = sum(xs)/n
y_bar = sum(ys)/n
# calculate slope
num = 0
denom = 0
for i in range(n):
num += (xs[i]-x_bar)*(ys[i]-y_... |
def X1X2_to_Xs(X1, X2):
"""Convert dimensionless spins X1, X2 to symmetric spin Xs"""
return (X1+X2)/2. |
def build_test_git_item(modes, distinct_snapshot_length, min_freq):
"""Create a dictionary object with all required key-pair values, to be used
for testing the GIT method.
"""
return {"allowedModeList": modes,
"distinctSnapshotLength": distinct_snapshot_length,
"minSourceFrequenc... |
def test_model(model, data):
"""Return if the dictionary `data` complies with the `model`."""
same_keys = set(model.keys()) == set(data.keys())
if not same_keys:
print(
"model_keys: {}\ndata_keys: {}".format(
sorted(model.keys()), sorted(data.keys())
)
... |
def remove_duplicate_filenodes(filenodes):
"""
Remove duplicate file nodes from a given list of file nodes
:param filenodes: A list of file nodes (list of File)
:return: A list of filtered file nodes (list of File)
"""
filtered_filenodes = []
for filenode in filenodes:
if filenode no... |
def is_subdict(subset, superset):
"""Return whether one dict is a subset of another."""
if isinstance(subset, dict):
return all(
key in superset and is_subdict(val, superset[key]) for key, val in subset.items()
)
if isinstance(subset, list) and isinstance(superset, list) and len... |
def compute_total_unique_words_fraction(sentence_list):
"""
Compute fraction os unique words
:param sentence_list: a list of sentences, each being a list of words
:return: the fraction of unique words in the sentences
"""
all_words = [word for word_list in sentence_list for word in word_list]
... |
def combine_lists(list_of_lists):
"""
"""
ret = []
for l in list_of_lists:
ret.extend(l)
return ret |
def _get_channel_mappings(fluoro_dict: dict) -> list:
"""
Generates a list of dictionary objects that describe the fluorochrome mappings in this FCS file
Parameters
-----------
fluoro_dict: dict
dictionary object from the channels param of the fcs file
Returns
--------
List
... |
def hex_to_string(val):
"""Converts hex string to utf-8 string.
Accepts padded or unpadded values.
"""
if val is None:
return ""
s = val.strip('0x').rstrip('0')
if len(s) % 2 == 1:
s += "0"
return bytes.fromhex(s).decode('utf-8') |
def select_covar_types(nd, ns):
"""
Heuristics to choose the types of covariance matrix to explore based on the data dimension and the (effective)
number of samples per mixture component.
:param nd: data dimension.
:param ns: number of samples.
:return: list of covariance types.
"""
if ... |
def fetch_sources(vis):
"""
fetch calibrator and target sources from the measurement set and return dictionary
"""
pmcalf = '0'
pmcals = '1'
bpcalf = '0'
bpcals = '3'
fdcalf = '0'
fdcals = '1'
targets = '2'
targetf = '1'
return {'pmcalf':pmcalf, 'pmcals':pmcals,
... |
def downsample(red, green, blue):
"""Downsamples RGB from 24-bit to 8-bit
:param red: 24-bit red value
:type red: int
:param green: 24-bit green value
:type green: int
:param blue: 24-bit blue value
:type blue: int
:return: 8-bit downscaled RGB tuple
:rty... |
def remove_whitespace(string: str) -> str:
"""
This function replace whitespaces for void string -> ''
Input: string with (or without) whitespace
Output: string without whitespace
"""
try:
if len(string) == 0 or (len(string) == 1 and string != ' '):
retu... |
def backward_sorted_array(len_arr):
"""
Function generates a backward array of size 2 ** n of integers.
"""
array = []
for i in range(len_arr):
array.append(len_arr-i)
return array |
def calculate_residuals(fit_function,a,xdata,ydata):
"""Given the fit function, a parameter vector, xdata, and ydata returns the residuals as [x_data,y_data]"""
output_x=xdata
output_y=[fit_function(a,x)-ydata[index] for index,x in enumerate(xdata)]
return [output_x,output_y] |
def _compose_error_message(key: str, supported_parameters: list):
"""Creates the error message depending on the number of supported parameters available."""
error_message = f'Parameter "{key}" is not supported. Expected '
if len(supported_parameters) > 1:
supported_parameters.sort()
error_m... |
def escape_for_display(s) :
"""Substitute certain chars to assist debug traces."""
if len(s) == 0 :
return "[EMPTY]"
return s.replace("\n","[NL]").replace("\t","[TAB]") |
def negate_entries(lst, idx):
"""Negate subset of list members indicated by indices list """
return [-int(x) if i in idx else x for i, x in enumerate(lst)] |
def is_only_preceded_by(string: str, to_find: str, preceded: str) -> bool:
"""
check if an element in a string is only preceded
by the indicated character, even multiple times.
Raise an ValueError if to_find is not found
:param string: the string to search in
:param to_find: the string to searc... |
def normalize_rgb(rgb: list) -> list:
"""
:param rgb: [255,255,255]
:return: [255,255,255] -> [1.0, 1.0, 1.0]
"""
return [c / 256 for c in rgb] |
def keep_firstn(lst, n):
"""Keep only the first n elems in a list."""
if len(lst) <= n:
return lst
else:
return lst[:n] |
def clean_str(s):
""" replace unwanted characters"""
return s.replace(" ", "_").replace(".", "").strip() |
def multi_count(n: int, x: int) -> int:
"""
The count of number of factors (from 2 to n) is the count.
exception: n > x, add 2 to the count (for 1 and x)
Time Complexity: O(n)
"""
if n < 1:
return 0
if x == 1:
return 1
total: int = 2 if x <= n else 0
for i in rang... |
def crc_xmodem_update(crc, data):
""" Calculate CRC for 1 byte.
Polynomial: x^16 + x^12 + x^5 + 1 (0x1021)
Initial value: 0x0
Example:: python
crc_xmodem_update( crc, 0x34 )
:param crc: 16 bit CRC value
:param data: 8 bit data value
"""
# crc must not be higher than 16 bits
... |
def group_envars(evs, prefix):
"""Group envars on given prefix and return dictionary with elements without prefix and lowercased keys"""
res = {}
p = prefix.upper() + '_'
plen = len(p)
for vk in evs:
if vk[:plen] == p:
nk = vk[plen:].lower()
res[nk] = evs[vk]
retu... |
def is_cached_property(_cached_property):
"""
Check if a class's property is wrapped by `cached_property`.
:param _cached_property: The property in question.
:rtype: bool
:see: cached_property
"""
# Get the `fget` method from the property.
fget = getattr(_cached_property, 'fget', None)
... |
def score_type(type):
"""calculate a score based on a given type
Arguments:
type: the type to base the score on
"""
if type == 'quoted':
return 0.6
if type == 'replied_to':
return 0.7
if type == 'retweeted':
return 0.1
# original tweet
return 1 |
def total_words_extractor(word_tokens):
"""total_words
Counts the number of words in the text.
A "word" in this context is any token.text in the spacy doc instance which does
not match the regular expression '[^\w]+$'.
Known differences with Writeprints Static feature "total words": None.
No... |
def set_top_level_meta(raw_meta):
"""Set top level assembly metadata."""
top_level = {
"assembly_id": raw_meta["assembly_id"],
"taxon_id": raw_meta["taxon_id"],
}
return top_level |
def annotatorjs(quote: str,
text: str,
start: str,
end: str,
startOffset: int,
endOffset: int) -> dict:
"""Returns annotatorjs type object"""
return {
"id": 0,
"quote": quote,
"ranges": [
{
... |
def _baths_to_str(num_baths_int):
"""
Retrieves a bath string from a number of bathrooms
"""
if num_baths_int == 0 or num_baths_int == 1:
return "0 to 1"
elif num_baths_int == 2:
return "2"
elif num_baths_int >=3:
return "3 or more"
else:
raise Exception("num_... |
def get_users_str(username_list):
"""Return a string of comma-separated user names for success messages."""
users_str = username_list[0]
for i in range(1, len(username_list)):
users_str += f", {username_list[i]}"
return users_str |
def join_rows(rows, sep='\n'):
"""Given a list of rows (a list of lists) this function returns a
flattened list where each the individual columns of all rows are joined
together using the line separator.
"""
output = []
for row in rows:
# grow output array, if necessary
if len(o... |
def parse(cleaned):
"""
Return list of words beginning with wss
"""
ret = [url for url in cleaned.split() if url.startswith("wss")]
# print (ret)
return ret |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.