content
stringlengths 42
6.51k
|
|---|
def _split_to_slist(s):
"""Splits coverage language string to a list of strings. Here we
make sure that parentheses () will be separate items in list.
???Consider: it would be better to separate only those parentheses
which are not escaped with backslash; this would allow using
(escaped) parentheses in the regular expressions."""
return s.replace("("," ( ").replace(")"," ) ").split()
|
def IsStrictlyIncreasing(lst):
"""Returns true if the list is strictly increasing."""
return all([x < y for x, y in zip(lst, lst[1:])])
|
def _get_first_of(obj, *args):
"""
Helper function, returns first existing property of the object that is not None.
:param obj:
:param args: variadic, names of the properties
:return:
"""
for arg in args:
if hasattr(obj, arg):
prop = getattr(obj, arg)
if prop is not None:
return prop
return None
|
def perimeter_and_area(s1, s2):
"""prints the perimeter and returns the area"""
print(2*(s1+s2))
return (s1*s2)
|
def dense_array(array, divide):
"""
delete inconsistent elements of 2D array and reduce its size by creating smaller array
:param
array: array to dense
:param
divide: number to divide the array size
:return:
2D divided array with consistent shape
"""
result = []
# get the right size from first element
size = len(array[0])
print(size)
for e in array:
# if the element has different size delete it
if len(e) != size:
i = array.index(e)
del array[i]
# divide the array into smaller array
for i in range(len(array)):
if i % divide == 0:
result.append(array[i])
return result
|
def sort(lst, key=lambda x:x, p=""):
"""
sort(lst, key, p="")
key(ele): key function
p="r" -> reversed
"""
rev_flag = True if "r" in p else False
lst.sort(key=key, reverse = rev_flag)
return lst
|
def sort_by_article_count(tags):
"""Return a number articles with the given tag."""
return sorted(tags, key=lambda tags: len(tags[1]), reverse=True)
|
def num_water_bottles(num_bottles: int, num_exchange: int) -> int:
"""Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Return the maximum number of water bottles you can drink."""
if num_bottles < num_exchange:
return num_bottles
# the maximum number of water bottles without any exchanges are obviously the given number of water bottles
max_exchanges = num_bottles
# if we can still exchange, then loop
while num_bottles >= num_exchange:
# number of bottle to exchange are the floor of the total number of water bottles
# divided by the exchange cost(num_exchange)
to_exchange = num_bottles // num_exchange
# add the number of bottle to exchange to the max number of water to drink
max_exchanges += to_exchange
# the number of bottle that are left out of the last exchange are
# the number of water bottles modulo exchange cost(num_exchange)
not_exchanged = num_bottles % num_exchange
# the number of bottle that are still left to exchange are the number of bottles to exchange
# plus the number of water bottles that are not used in the previous exchange
num_bottles = to_exchange + not_exchanged
return max_exchanges
|
def __eliminarDias(diasExcluidos):
"""
Funcion para devolver una lista con los dias de la semana excluyendo los que se pasan como parametro
"""
dias = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]
for ex in diasExcluidos:
if ex in dias:
dias.remove(ex)
return dias
|
def get_telemetry_data(data):
""" Returns tuple of telemetry data"""
pos_x = float(data["telemetry"]["pos_x"])
pos_y = float(data["telemetry"]["pos_y"])
time = float(data["telemetry"]["time"])
velocity = float(data["telemetry"]["velocity"])
return pos_x, pos_y, time, velocity
|
def get_switch_port_name (port):
"""
Get the name for the specified switch port.
Parameters:
port -- The port number to use when generating the same.
Return:
The internal name for the switch port.
"""
return "gi" + str (port)
|
def subdict_by_prefix(flat, prefix, key=None):
"""
Put key-value pairs in `flat` dict prefixed by `prefix` in a sub-dict.
>>> flat = dict(
... prefix_alpha=1,
... prefix_beta=2,
... gamma=3,
... )
>>> assert subdict_by_prefix(flat, 'prefix_') == dict(
... prefix=dict(alpha=1, beta=2),
... gamma=3,
... )
Key of the sub-dictionary can be explicitly specified:
>>> assert subdict_by_prefix(flat, 'prefix_', 'delta') == dict(
... delta=dict(alpha=1, beta=2),
... gamma=3,
... )
If the sub-dictionary already exists, it is copied and then
extended:
>>> flat['prefix'] = dict(theta=4)
>>> assert subdict_by_prefix(flat, 'prefix_') == dict(
... prefix=dict(alpha=1, beta=2, theta=4),
... gamma=3,
... )
>>> assert flat['prefix'] == dict(theta=4) # i.e., not modified
"""
if key is None:
key = prefix.rstrip('_')
nested = {}
nested[key] = subdict = flat.get(key, {}).copy()
assert isinstance(subdict, dict)
for k, v in flat.items():
if k == key:
pass
elif k.startswith(prefix):
subdict[k[len(prefix):]] = v
else:
nested[k] = v
return nested
|
def compare(op_a: bytearray, op_b: bytearray) -> bool:
"""
Compare two byte arrays.
This function, in contrast to the simple comparison operation '==', is
performed in constant time to prevent timing attacks.
Args:
op_a: First array to compare.
op_b: Second array to compare.
Returns:
Comparison result (boolean).
"""
op_a = bytearray(op_a)
op_b = bytearray(op_b)
res_check = 0
if len(op_a) != len(op_b):
return False
for i in enumerate(op_a):
check = op_a[i[0]] ^ op_b[i[0]]
res_check = res_check + check
return not res_check
|
def fromHexToInt(input):
"""
Transforms hexadecimal to decimal.
:param input: An hexadecimal number.
:return: An integer in base 10.
"""
return int(input, base=16)
|
def elapsed_time(start, end):
"""
A function that calculate time difference between two times
:param start: the starting time
:param end: the ending time
:return: the time difference in readable format.
"""
hours, rem = divmod(end - start, 3600)
minutes, seconds = divmod(rem, 60)
return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds)
|
def string_to_bytes(text):
"""converts a string to bytes
Args:
text: the text that should be converted
Returns:
the converted text
"""
return str.encode(str(text))
|
def getFileNameOnly(fileName):
"""
return the file name minus the trailing suffix
"""
return '.'.join(fileName.split('/')[-1].split('.')[:-1])
|
def level_to_rgb(level, background):
"""
Converts internal consept of level to a gray color for text in RGB
:param level: range from 1 to 15
:return: tuple referring to (R, G, B)
"""
#Level goes from 1 to 15, starting from level1:(30,30,30), and getting darker with 1 point
if level not in range(1, 16):
return None
gray_code = background[0]+15-level+1
print(f"{level}::{gray_code}")
return (gray_code, gray_code, gray_code)
|
def evaluate(f, x ,y):
"""Uses a function f that evaluates x and y"""
return f(x, y)
|
def isDoor(case):
"""Teste si la case est une porte"""
if "special_type" in case.keys():
return case['special_type'] == "door"
else:
return False
|
def linear_disj(s, op='||'):
"""Return linear disjunction in prefix syntax."""
b = ' {op} '.format(op=op)
return b.join('({x})'.format(x=x) for x in s if x != '')
|
def convert_size(number):
"""
Convert and integer to a human-readable B/KB/MB/GB/TB string.
:param number:
integer to be converted to readable string
:type number: ``int``
:returns: `str`
"""
for x in ['B', 'KB', 'MB', 'GB']:
if number < 1024.0:
string = "%3.1d%s" % (number, x)
return string.strip()
number /= 1024.0
string = "%3.1f%s" % (number, 'TB')
return string.strip()
|
def get_timedelta_in_seconds(time_interval):
"""Convert time delta as string into numeric value in seconds
:param time_interval: time interval as string in format HH:MM:SS.FFFFFF
:return: time interval in seconds
"""
if ":" not in time_interval:
return 0
(hours, minutes, sf) = time_interval.split(":")
(seconds, fraction) = sf.split(".") if "." in sf else (0, 0)
secs = int(hours) * 60 * 60 + \
int(minutes) * 60 + \
int(seconds) + \
int(fraction) / 1000000
return secs
|
def myfunction( x , iterations):
""" using tylor series
x must be in range (-1,1]
"""
if x<=-1.0 or x >1.0 :
raise ValueError("x not in range (-1,1] ")
ans=0.0
multiply = -x
for i in range(1,iterations+1):
#print("i= ",i, " x= ",x," ans ",ans," multiply ",multiply)
ans+=x/i
x*=multiply
return ans
|
def CByte(num):
"""Return the closest byte of a value"""
n = round(float(num))
if 0 <= n <= 255:
return int(n)
else:
raise ValueError("Out of range in CByte (%s)" % n)
|
def create_bins(lower_bound, width, upper_bound):
"""
Creates bin if given the lower and upper bound
with the wirdth information.
"""
bins = []
for low in range(lower_bound, upper_bound, width):
bins.append([low, low + width])
return bins
|
def _union(groupA, groupB):
"""Returns the union of groupA and groupB"""
elems = set(groupA)
elems.update(groupB)
return list(elems)
|
def is_exception_class(obj):
"""Return whether obj is an exception class, or a tuple of the same.
>>> is_exception_class(ValueError)
True
>>> is_exception_class(float)
False
>>> is_exception_class(ValueError()) # An instance, not a class.
False
>>> is_exception_class((ValueError, KeyError))
True
"""
try:
if isinstance(obj, tuple):
return obj and all(issubclass(X, BaseException) for X in obj)
return issubclass(obj, BaseException)
except TypeError:
return False
|
def str_fraction(f):
"""Utility fonction to print fractions."""
return float(f) if f else 0.0
|
def resource_created(payload=None):
"""Return custom JSON if a resource is created but doesn't have output
:param payload: Customize the JSON to return if needed
:type payload: dict, optional
:return: A JSON dict with a message
:rtype: dict
"""
if payload is not None:
return payload
else:
return {"status": "created"}
|
def findAll(needle, haystack):
"""Find all occurrances of 'needle' in 'haystack', even overlapping ones.
Returns a list of zero-based offsets.
"""
results = []
offset = 0
while True:
search = haystack[offset:]
if not search:
break
x = search.find(needle)
if x < 0:
break
results.append(offset + x)
offset += x + 1
return results
|
def sort_io_dict(performance_utilization: dict):
"""
Sorts io dict by max_io in descending order.
"""
sorted_io_dict = {
'io_all': dict(sorted(performance_utilization['io'].items(), key=lambda x: x[1], reverse=True))
}
performance_utilization.update({**sorted_io_dict})
del performance_utilization['io']
return performance_utilization
|
def was_last_response_B(last_keypress):
"""this function returns last_response_chose_delayed as True or False,
taking into account the location of the immediate and delayed rewards.
last_keypress is either 'left' or 'right'
"""
if last_keypress == "left":
last_response_chose_B = False
elif last_keypress == "right":
last_response_chose_B = True
else:
raise Exception("unexpected last_keypress")
return last_response_chose_B
|
def get_effective_power(unit):
"""Get effective power of unit."""
return unit['count'] * unit['damage']
|
def reverse_words(str):
"""Reverse the order of letters in each word in a string."""
return " ".join(["".join(s[::-1]) for s in str.split(" ")])
|
def _validate_timeout(timeout, where):
"""Helper for get_params()"""
if timeout is None:
return None
try:
return int(timeout)
except ValueError:
raise ValueError('Invalid timeout %s from %s' % (timeout, where))
|
def statsGet(request, countType):
"""getSubsCount function return subscriber count
Args:
stats (dict): statistics dictionary
Returns:
int: [Subscriber Count]
"""
count = request['items'][0]['statistics'][countType]
print(f"{countType}: {count}")
return count
|
def _hanoi(n: int, ls: list, src='A', aux='B', dst='C') -> list:
"""Recursively solve the Towers of Hanoi game for n disks.
The smallest disk, which is the topmost one at the beginning, is called 1,
and the largest one is called n.
src is the start rod where all disks are set in a neat stack in ascending
order.
aux is the third rod.
dst is similarly the destination rod."""
if n > 0:
_hanoi(n - 1, ls, src, dst, aux)
ls.append((n, src, dst))
_hanoi(n - 1, ls, aux, src, dst)
return ls
|
def largest_remaining_processing_time(evs, iface):
""" Sort EVs in decreasing order by the time taken to finish charging them at the EVSE's maximum rate.
Args:
evs (List[EV]): List of EVs to be sorted.
iface (Interface): Interface object.
Returns:
List[EV]: List of EVs sorted by remaining processing time in decreasing order.
"""
def remaining_processing_time(ev):
""" Calculate minimum time needed to fully charge the EV based its remaining energy request and the EVSE's max
charging rate.
Args:
ev (EV): An EV object.
Returns:
float: The minimum remaining processing time of the EV.
"""
rpt = (iface.remaining_amp_periods(ev) / iface.max_pilot_signal(ev.station_id))
return rpt
return sorted(evs, key=lambda x: remaining_processing_time(x), reverse=True)
|
def get_by_name(container, name, name_field="name"):
"""Return item from container by .name field if it exists, None otherwise"""
names = [getattr(x, name_field) for x in container]
try:
ind = names.index(name)
return container[ind]
except ValueError:
return None
|
def pop_comments_gte(reply_stack, level_lte=0):
"""
Helper filter used to list comments in the <comments/list.html> template.
"""
comments_lte = []
try:
for index in range(len(reply_stack) - 1, -1, -1):
if reply_stack[index].level < level_lte:
break
comments_lte.append(reply_stack.pop(index))
finally:
return comments_lte
|
def absolute_date(resolution, start, end):
"""Select an absolute date range for a location selector.
:keyword resolution: Time resolution specifier, e.g. ``hours`` or ``days``.
:keyword start: UTC start time in ISO 8601 format.
:keyword end: UTC end time in ISO 8601 format.
>>> from pprint import pprint
>>> d = absolute_date(resolution='months', start='2013-01', end='2013-06')
>>> pprint(d)
{'months': {'end': '2013-06', 'start': '2013-01'}}
>>> d = absolute_date(resolution='minutes', start='2012-01-01 12:00',
... end='2012-01-01 12:45')
>>> pprint(d, width=76)
{'minutes': {'end': '2012-01-01 12:45', 'start': '2012-01-01 12:00'}}
"""
if resolution not in ('minutes' 'hours' 'days' 'weeks' 'months' 'years'):
raise ValueError('Invalid date resolution: %s' % resolution)
payload = {resolution: {'start': start, 'end': end}}
return payload
|
def _inputs_swap_needed(mode, shape1, shape2):
"""
If in 'valid' mode, returns whether or not the input arrays need to be
swapped depending on whether `shape1` is at least as large as `shape2` in
every dimension.
This is important for some of the correlation and convolution
implementations in this module, where the larger array input needs to come
before the smaller array input when operating in this mode.
Note that if the mode provided is not 'valid', False is immediately
returned.
"""
if mode == "valid":
ok1, ok2 = True, True
for d1, d2 in zip(shape1, shape2):
if not d1 >= d2:
ok1 = False
if not d2 >= d1:
ok2 = False
if not (ok1 or ok2):
raise ValueError(
"For 'valid' mode, one must be at least "
"as large as the other in every dimension"
)
return not ok1
return False
|
def isBool( obj ):
"""
Returns a boolean whether or not 'obj' is of type 'bool'.
"""
return isinstance( obj, bool )
|
def find_index(text, pattern):
"""Return the starting index of the first occurrence of pattern in text,
or None if not found."""
text_index = 0 # start at beginning of text
if pattern == "": # check if pattern contains anything
return text_index
# as long as there are still letters to look thru...
while text_index != len(text):
for i in range(len(pattern)):
if text_index + i < len(text):
# check letter from text again letter from pattern
if text[text_index + i] != pattern[i]:
break # stop if no match
if i == len(pattern) - 1:
return text_index # return index where pattern starts
text_index += 1
|
def docs_with_doi(doi, docs):
"""look in document list for doi fields
and return project ids with the given doi
"""
return [p[1]['@id'] for p in docs if 'doi' in p[1] and doi in p[1]['doi']]
|
def final_reclassifier(original_classifier, seq):
"""Reclassify the strategy"""
original_classifier["makes_use_of"].update(["length"])
original_classifier["memory_depth"] = max(
len(seq), original_classifier["memory_depth"]
)
return original_classifier
|
def progressbar_colour(value: float):
"""Converts a percentage to a bootstrap label"""
if value > 99.5:
return "progress-bar-green"
elif value < 50.0:
return "progress-bar-red"
else:
return "progress-bar-yellow"
|
def make_option_name(name):
"""
'poll_interval' -> '--poll-interval'
"""
return '--' + name.replace('_', '-')
|
def concatenate(lists):
"""
This concatenates all the lists contained in a list.
:param lists: a list of lists.
:return:
new_list: concatenated list.
"""
new_list = []
for i in lists:
new_list.extend(i)
return new_list
|
def map_types(params):
""" Takes a dict of params in the form i:{'value':'val','type':type} and maps them to i:value according to type """
type_map = {
'int':int,
'real':float,
'string':str,
'bool':bool
}
newparams = dict()
for p in params:
if params[p]['Value'] == "":
newparams[p] = None
continue
newparams[p] = type_map[params[p]['Type']](params[p]['Value']) # assume that this works because the validator should've checked it
return newparams
|
def folder_path_cleaning(folder):
"""
Modifies string file names from Windows format to Unix format if necessary
and makes sure there is a ``/`` at the end.
Parameters
----------
folder : string
The folder path
Returns
-------
folder_path : str
The folder path
"""
folder_path = folder.replace('\\', '/')
if folder_path[-1] != '/':
folder_path += '/'
return folder_path
|
def to_camel(s):
"""Convert an underscored title into camel case. 'PARENT_ORGANISATION_ID' => 'parentOrganisationId'"""
bits = [(x.lower() if i == 0 else x.title())
for (i, x) in enumerate(s.split("_"))]
return "".join(bits)
|
def are_lists_identical(l1,l2):
"""
Quick function that asks if two lists are identical or not.
Parameters
-----------
l1 : list
First list
l2 : list
Second list
Returns
----------
bool
Returns True if they are identical, or False if not
"""
if len(l1) != len(l2):
return False
for i in range(len(l1)):
if l1[i] != l2[i]:
return False
return True
|
def ensure_tuple_of_ints(L):
"""This could possibly be done more efficiently with `tolist` if L is
np or pd array, but will stick with this simple solution for now.
"""
T = tuple([int(mm) for mm in L])
return T
|
def get_confusion(pred, actual , data_map):
"""
Modify the actual classes according to the datamap, so we can look at the confusion matrix.
"""
result = []
for ac in actual:
for cl in data_map:
if ac in data_map[cl]:
result.append(cl)
for i in range(0, len(actual)):
if pred[i] != result[i]:
print(actual[i])
return result
|
def _get_reaction_key(functional_groups):
"""
Return a key for :data:`._reactions`
Parameters
----------
functional_groups : :class:`iterable`
An :class:`iterable` of :class:`.GenericFunctionalGroup`.
The correct reaction must be selected for these functional
groups.
Returns
-------
:class:`.frozenset`
A key for :data:`_reactions`, which maps to the correct
reaction.
"""
return frozenset(
functional_group.get_num_bonders()
for functional_group in functional_groups
)
|
def tower_build(n_floors=1):
"""
n_floors: number of floors for the tower
return: tower consisting of "*" from top to bottom layed out as a pyramid
"""
tower_list = ([" "*(n_floors-i) + "*"*(2*i-1) + " "*(n_floors-i) for i in range(1, n_floors+1)])
return tower_list
|
def reindent(s, numspaces):
""" reinidents a string (s) by the given number of spaces (numspaces) """
leading_space = numspaces * ' '
lines = [leading_space + line.strip()for line in s.splitlines()]
return '\n'.join(lines)
|
def contains_string(string,lines):
"""returns true if at least one of the lines contains the given string"""
for line in lines:
if string in line:
return True
return False
|
def throttle_delay_set(session, delay):
"""Assign a new throttle delay to a session. The throttle delay
value, in seconds, is added to each request to avoid hitting
RESTCONF throttling limit.
:param session: Dictionary of session returned by :func:`login`.
:param delay: New delay to be assigned to the session, in seconds.
:rtype: None.
"""
session['throttle_delay'] = delay
return "Success"
|
def find_list_depth(a):
"""
Finds the depth of a list using recursion
Parameters
----------
a : list
list of arbitrary depth
Returns
-------
depth : integer
depth of list
"""
if isinstance(a, (list, tuple)):
depth = 1 + max(find_list_depth(item) for item in a)
else:
depth = 0
return depth
|
def render_chart(word_list):
"""
Renders a bar chart to the console. Each row of the chart contains the frequency
of each letter in the word list.
Returns:
A dictionary whose keys are the letters and values are the freqency (N) of the
letter. The value is a string containing the key repeated N times.
For example in the string 'apple' the result would be like this:
{"A": "a"},
{"E": "e"},
{"L": "l"},
{"P": "pp"}
Although not shown above all keys are returned even if the frequency is zero.
"""
chart = {chr(n): "" for n in range(ord('A'), ord('Z') + 1)}
for word in word_list:
for letter in word:
try:
chart[letter.upper()] += letter.upper()
except KeyError:
continue
return chart
|
def _get_node_colors(nodes, path, colors):
"""For each node, assign color based on membership in path."""
node_colors = []
for x in nodes:
if x in path:
node_colors.append(colors['active'])
else:
node_colors.append(colors['inactive_node'])
return node_colors
|
def fizzbuzz(n, fizz, buzz):
"""Compute fizzbuzz nth item given modulo values for fizz and buzz.
>>> fizzbuzz(5, fizz=3, buzz=5)
'buzz'
>>> fizzbuzz(3, fizz=3, buzz=5)
'fizz'
>>> fizzbuzz(15, fizz=3, buzz=5)
'fizzbuzz'
>>> fizzbuzz(4, fizz=3, buzz=5)
4
>>> fizzbuzz(4, fizz=4, buzz=6)
'fizz'
"""
if n % fizz == 0 and n % buzz == 0:
return "fizzbuzz"
if n % fizz == 0:
return "fizz"
if n % buzz == 0:
return "buzz"
return n
|
def tsk(basename, task, obj=None):
"""Merge in some defaults for task creation"""
if not obj: obj, task = task, None # argument order
return {
'basename': basename,
'name': task,
'title': lambda t: f'{t.name} -> {t.targets[0]}',
'clean': True,
**obj, # merge in, overriding previous
}
|
def fact_iter(n):
"""Assumes n is an int >= 0
* computes factorial
* number of steps:
* ignore additive constants
* ignore multplicative constants
"""
answer = 1
while n > 1:
answer *= n
n -= 1
return answer
|
def question4c(T, r, n1, n2):
""" Find the least common ancestor between two nodes on a binary search tree """
# if three has less than three nodes, return None
if len(T)<=2:
return
# order search nodes
if n1<n2:
ln, rn = n1, n2
else:
ln, rn = n2, n1
while True:
# if either node matches with root, return root
if r==ln or r==ln:
return r
# if one node is in each side, return root
if ln < r and rn > r:
return r
# if both on the right side, set root the right node and continue
if ln > r and rn > r:
# search the array from right to left to get the right node
for i in range(len(T[r])-1, -1, -1):
if T[r][i] == 1:
r = i
break
# if both on the left side, set root the left node and continue
if ln < r and rn < r:
# search the array from left to right to get the left node
for i in range(len(T[r])):
if T[r][i] == 1:
r = i
break
|
def max_clamp(val: int, limit: int) -> int:
"""Clamp int to limit."""
return min(val, limit)
|
def convert_from_cammel_case_to_spaces(text):
"""
>>> convert_from_cammel_case_to_spaces('HelloWorld')
'Hello world'
>>> convert_from_cammel_case_to_spaces('helloMotto')
'hello motto'
"""
spaced_text = text[0]
for char in text[1:]:
if char == char.capitalize():
spaced_text += ' ' + char.lower()
else:
spaced_text += char
return spaced_text
|
def compress_runs(runs, incrementable):
"""
return a 2-tuple list (idx, run) filter out not incrementables
"""
return [(i, r) for i, r in enumerate(runs)
if r.analysis_type in incrementable]
|
def split_reaction_identifier(rid):
""" SMIRKS-style reaction ID from reactant and product species IDs
"""
rct_str, prd_str = str.split(rid, '>>')
rct_sids = tuple(str.split(rct_str, '.'))
prd_sids = tuple(str.split(prd_str, '.'))
return (rct_sids, prd_sids)
|
def gari( redchan, nirchan, bluechan, greenchan ):
"""
GARI: green atmospherically resistant vegetation index
gari( redchan, nirchan, bluechan, greenchan )
"""
redchan = 1.0*redchan
nirchan = 1.0*nirchan
bluechan = 1.0*bluechan
greenchan = 1.0*greenchan
result = ( nirchan - (greenchan-(bluechan - redchan))) / ( nirchan- (greenchan-(bluechan - redchan)))
return result
|
def compute_fsl_sigma(cutoff, TR, const=2):
"""Convert filter cutoff from seconds to sigma required by fslmaths"""
return cutoff / (TR*const)
|
def get_cell_neighborhood(seq, pos):
"""
Return the neighborhood (a triple) of the cell in the specified
position of a sequence.
"""
cell = seq[pos]
left = seq[-1] if pos == 0 else seq[pos-1]
right = seq[0] if pos == (len(seq) - 1) else seq[pos+1]
return (left, cell, right)
|
def closest_cruising_altitude(altitude):
"""
Calculate the closest cruising altitude to the given altitude.
Parameters
----------
altitude: float
An altitude [feet]
Returns
-------
The closest cruising altitude to the given altitude.
"""
return 1000 * ((altitude + 500) // 1000)
|
def result_string_to_dictionary(result_string: str) -> dict:
"""
Convert result string saved in a .csv file to a dictionary
:param result_string: string from .csv file
:return: dictionary with info from .csv file
"""
key_value_strings = result_string.split('\\')[0][2:-2].replace('\'', '').split(',')
dict_result = {}
for key_value_string in key_value_strings:
key = key_value_string.split(':')[0].strip()
value = key_value_string.split(':')[1].strip()
try:
value = float(value)
value = int(value) if value == int(value) else value
except:
value = value
dict_result[key] = value
return dict_result
|
def arg_range(arg, lo, hi):
"""
Given a string of the format `[int][-][int]`, return a list of
integers in the inclusive range specified. Open intervals are
allowed, which will be capped at the `lo` and `hi` values given.
If `arg` is empty or only contains `-`, then all integers in the
range `[lo, hi]` will be returned.
"""
arg = arg.strip()
if len(arg) == 0 or arg == '-':
return range(lo, hi+1)
if '-' not in arg:
return [int(arg)]
start, end = map(str.strip, arg.split('-'))
if len(start) == 0:
return range(lo, int(end)+1)
elif len(end) == 0:
return range(int(start), hi+1)
else:
return range(int(start), int(end)+1)
|
def SignToBool(inp):
"""Converts signed bits into boolean bits
-1 -> 0
1 -> 1"""
return (inp + 1) / 2
|
def b64encode(data):
"""Encodes data in base64 format.
Custom base64 function that is similar to Keycloaks base64url.js stringify function.
Used to conform with Keycloaks expected format, as Pythons base64 module seems
to produce unexpected output.
See https://github.com/keycloak/keycloak/blob/master/themes/src/main/resources/theme/base/login/resources/js/base64url.js
"""
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
enc_bits = 6
mask = (1 << enc_bits) - 1
out = ''
bits = 0 # Number of bits currently in the buffer
buffer = 0 # Bits waiting to be written out, MSB first
for i in range(len(data)):
# Slurp data into the buffer:
buffer = (buffer << 8) | (0xff & data[i]);
bits += 8;
# Write out as much as we can:
while bits > enc_bits:
bits -= enc_bits
out += chars[mask & (buffer >> bits)]
# Partial character:
if bits:
out += chars[mask & (buffer << (enc_bits - bits))];
return out
|
def _make_body(mapping, source_key='source'):
"""
Given a dict mapping Keboola tables to aliases, construct the body of
the HTTP request to load said tables.
Args:
mapping(:obj:`dict`): Keys contain the full names of the tables to
be loaded (ie. 'in.c-bucker.table_name') and values contain the
aliases to which they will be loaded (ie. 'table_name').
"""
body = {}
template = 'input[{0}][{1}]'
for i, (k, v) in enumerate(mapping.items()):
body[template.format(i, source_key)] = k
body[template.format(i, 'destination')] = v
return body
|
def is_spotify(track):
""" Check if the input song is a Spotify link. """
status = len(track) == 22 and track.replace(" ", "%20") == track
status = status or track.find("spotify") > -1
return status
|
def center_x(display_width: int, line: str) -> int:
"""
Find the horizontal center position of the given text line
Parameters:
display_width (int) : The character width of the screen/space/display
line (int) : Line of text
Returns:
(int): Horizontal character number
"""
return display_width // 2 - len(line) // 2
|
def parse_capability_lists(cls_str):
"""Parse list of capability lists in --capabilitylistindex option
Input string of the form: uri,uri
"""
return(cls_str.split(','))
|
def url(search_string, date_string):
"""
date_string of the form ddMONyyyy e.g. 25OCT2018, 31JAN2019
When requesting options, must be in the future.
Must be a valid option expiration date for that stock.
return url
"""
base_url = 'https://www.nseindia.com'
query_prefix = '/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?'
date_query = ''
if date_string is not None:
date_query = f'&date={date_string}'
url_string = base_url + query_prefix + search_string + date_query
return url_string
|
def is_in_list(num, lst):
"""
>>> is_in_list(4, [1, 2, 3, 4, 5])
True
>>> is_in_list(6, [1, 2, 3, 4, 5])
False
>>> is_in_list(5, [5, 4, 3, 2, 1])
True
"""
if not lst:
return False
else:
return lst[0] == num or is_in_list(num, lst[1:])
|
def parts_to_url(codechecker_cfg):
"""
Creates a product URL string from the test configuration dict.
"""
return codechecker_cfg['viewer_host'] + ':' + \
str(codechecker_cfg['viewer_port']) + '/' + \
codechecker_cfg['viewer_product']
|
def fib_3_iterative(n):
"""
Solution: Iterative solution.
Complexity:
Time: O(n)
Space: O(1)
"""
if n < 0:
raise ValueError('input must be a positive whole number')
x, y = 0, 1
for i in range(n):
x, y = y, x + y
return x
|
def _get_creator(hardict):
"""
Get creator of HAR file.
"""
creator = hardict["log"]["creator"]
return "%s %s%s" % (creator["name"], creator["version"],
" (Comment: %s)" % creator["comment"] if creator.get("comment") else "")
|
def _dummy_parameters(layer_group, n_in):
"""Return dummy parameters"""
return {'weights':[], 'bias':[], 'architecture':'dense'}, n_in
|
def access_by_path(dic, path):
"""
Allows to access a nested dictionary using path to an entry, as if the nested
dictionary was a file system.
Parameters
----------
- dic: nested dictionary
- path: string with a path to a value within the dictionary (/key1/key2/key3)
Returns
-------
The object located in the input path
"""
keys = path.strip('/').split('/')
for key in keys:
dic = dic[key]
return dic
|
def format_result(result, verbose):
"""
Common code to format the results.
"""
if verbose:
return f"line: {result['line_number']} - ({result['rule']}) {result['meta']['description']} - {result['line']}"
return f"line: {result['line_number']} - ({result['rule']}) {result['meta']['description']}"
|
def options_to_str(options_list):
"""
Helper method to create a sting out of a list of choice options.
"""
tmp_list = ["{} - {}".format(i + 1, o) for i, o in enumerate(options_list)]
return "\n".join(tmp_list)
|
def count_send(link_counters):
"""Find the send count in the counters returned by a CommunicationLink."""
for processor in link_counters.values():
if 'send' in processor:
return processor['send']
|
def list_ascendant(input_list):
"""Function that orders a list on ascendant order using insertion sort
Args:
input_list (list): List with the values that we want to order
Returns:
list: The ordered list
"""
for i in range(1, len(input_list)):
j = i-1
next_element = input_list[i]
# Compare the current element with next one
while (input_list[j] > next_element) and (j >= 0):
input_list[j+1] = input_list[j]
j = j-1
input_list[j+1] = next_element
return input_list
|
def gen_hpack_huffman(data):
"""Generates the hpack_huffman array and returns a tuple with the length of the array and the content of the array both as strings"""
content = ""
for d in data:
content += " { " + str(d['bit_len']) + ", 0x" + d['LSB_hex'] + "u },\n"
# We remove the last comma and new line
return (str(len(data)), content[:-2])
|
def getFlattenDictionary(dd, separator='_', prefix=''):
"""
Args:
dd:
separator:
prefix:
Returns:
"""
return {prefix + separator + k if prefix else k: v
for kk, vv in dd.items()
for k, v in getFlattenDictionary(vv, separator, kk).items()
} if isinstance(dd, dict) else {prefix: dd}
|
def _fix_links(md):
"""Change links in markdown to make them work in HTML."""
md = md.replace('(doc/', '(')
md = md.replace('.md)', '.html)')
return md
|
def array_swap_transform_next_index_to_current_index(position, move):
"""Transforms the position depending on the move.
Works with the array_swap move type.
This function transforms the position so that it can be used as the indice
in the unaltered array, yet return the value it would have had if the move
was actually performed and the position was used as indice.
Parameters
----------
position : int
The index that one wants to use in the array if the move was performed.
move : tuple of int
A tuple with that represents a single, unique move.
Returns
-------
int
The index in the unaltered array that has the same value as the
location in an array where the move was performed.
Examples
--------
Some simple examples, the move remains the same, but the position changes:
.. doctest::
>>> from lclpy.evaluation.deltaeval.delta_qap \\
... import array_swap_transform_next_index_to_current_index \\
... as transform_next_index_to_current_index
... # tests
>>> transform_next_index_to_current_index(0, (1, 3))
0
>>> transform_next_index_to_current_index(1, (1, 3))
3
>>> transform_next_index_to_current_index(2, (1, 3))
2
>>> transform_next_index_to_current_index(3, (1, 3))
1
>>> transform_next_index_to_current_index(4, (1, 3))
4
"""
# transform frm so it returns the value that from would have if the
# move was performed.
if position == move[0]:
position = move[1]
elif position == move[1]:
position = move[0]
return position
|
def font_name(family, style):
"""
Same as ``full_name()``, but ``family`` and ``style`` names are separated by a hyphen instead of space.
"""
if style == 'Regular':
font_name = family
else:
font_name = family + '-' + style
return font_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.