content stringlengths 42 6.51k |
|---|
def make_signal_header(label, dimension='uV', sample_rate=256,
physical_min=-200, physical_max=200, digital_min=-32768,
digital_max=32767, transducer='', prefiler=''):
"""
A convenience function that creates a signal header for a given signal.
This can be used to create a list of signal headers that is used by
pyedflib to create an edf. With this, different sampling frequencies
can be indicated.
Parameters
----------
label : str
the name of the channel.
dimension : str, optional
dimension, eg mV. The default is 'uV'.
sample_rate : int, optional
sampling frequency. The default is 256.
physical_min : float, optional
minimum value in dimension. The default is -200.
physical_max : float, optional
maximum value in dimension. The default is 200.
digital_min : int, optional
digital minimum of the ADC. The default is -32768.
digital_max : int, optional
digital maximum of the ADC. The default is 32767.
transducer : str, optional
electrode type that was used. The default is ''.
prefiler : str, optional
filtering and sampling method. The default is ''.
Returns
-------
signal_header : dict
a signal header that can be used to save a channel to an EDF.
"""
signal_header = {'label': label,
'dimension': dimension,
'sample_rate': sample_rate,
'physical_min': physical_min,
'physical_max': physical_max,
'digital_min': digital_min,
'digital_max': digital_max,
'transducer': transducer,
'prefilter': prefiler}
return signal_header |
def copyList(A):
"""
This function just copies a list. It was written before the original author
realized that the copy module had a deepcopy function.
Parameters
---------------------------------------------------------------------------
A: list
A list of values
Returns
---------------------------------------------------------------------------
deepcopy(A): list
A deepcopy of the original list, A.
"""
import copy
return copy.deepcopy(A) |
def train_params(max_episodes=1000,
max_steps_per_episode=1000,
stop_value=100,
avg_window=100,
render=False,
verbose=True,
save_agent=True,
save_file='checkpoint_dqn.pth'):
"""
Parameters
----------
max_episodes : number, optional
Maximum number of training episodes. The default is 1000.
max_steps_per_episode : number, optional
Maximum environment steps in a training episode. The default is 1000.
stop_value : number, optional
Average score over avg_window episodes. Training is terminated on reaching this value. The default is 100.
avg_window : number, optional
Window length for score averaging. The default is 100.
render : boolean, optional
Flag to set environment visualization. The default is False.
verbose : boolean, optional
Flag for verbose training mode. The default is True.
save_agent : boolean, optional
Flag to save agent after training. The default is True.
save_file : char, optional
File name for saving agent. The default is 'checkpoint_dqn.pth'.
Returns
-------
"""
params = {
'max_episodes': max_episodes,
'max_steps_per_episode': max_steps_per_episode,
'stop_value': stop_value,
'avg_window': avg_window,
'render': render,
'verbose': verbose,
'save_agent': save_agent,
'save_file': save_file
}
return params |
def replace(param, index=None):
"""
Optionally used by the preload generator to wrap items in the preload
that need to be replaced by end users
:param param: parameter name
:param index: optional index (int or str) of the parameter
"""
if (param.endswith("_names") or param.endswith("_ips")) and index is not None:
param = "{}[{}]".format(param, index)
return "VALUE FOR: {}".format(param) if param else "" |
def nextpow2(i):
"""
Find 2^n that is equal to or greater than.
"""
n = 0
while (2**n) < i:
n += 1
return n |
def check_pem_files(keys_path):
"""Check *_public.pem and *_private.pem is exist."""
from pathlib import Path
pub_file = Path(keys_path + "_public.pem")
pri_file = Path(keys_path + "_private.pem")
return bool(pub_file.is_file() and pri_file.is_file()) |
def parse_cron_options(argstring):
"""
Parse periodic task options.
Obtains configuration value, returns dictionary.
Example::
my_periodic_task = 60; now=true
"""
parts = argstring.split(';')
options = {'interval': float(parts[0].strip())}
for part in parts[1:]:
name, value = part.split('=')
options[name.strip()] = value.strip()
return options |
def TSKVsPartGetStartSector(tsk_vs_part):
"""Retrieves the start sector of a TSK volume system part object.
Args:
tsk_vs_part (pytsk3.TSK_VS_PART_INFO): TSK volume system part information.
Returns:
int: start sector or None.
"""
# Note that because pytsk3.TSK_VS_PART_INFO does not explicitly defines
# start we need to check if the attribute exists.
return getattr(tsk_vs_part, 'start', None) |
def _latency_label_customers(avg_latency, std_latency, recency):
"""Add a label to describe a customer's latency metric.
Args:
avg_latency (float): Average latency in days
std_latency (float): Standard deviation of latency in days
recency (float): Recency in days
Returns:
Label describing the latency metric in relation to the customer.
"""
days_to_next_order_upper = avg_latency - (recency - std_latency)
days_to_next_order_lower = avg_latency - (recency + std_latency)
if recency < days_to_next_order_lower:
return 'Order not due'
elif (recency <= days_to_next_order_lower) or (recency <= days_to_next_order_upper):
return 'Order due soon'
elif recency > days_to_next_order_upper:
return 'Order overdue'
else:
return 'Not sure' |
def headers(auth_token=None):
"""
Generate an appropriate set of headers given an auth_token.
:param str auth_token: The auth_token or None.
:return: A dict of common headers.
"""
h = {'content-type': ['application/json'],
'accept': ['application/json']}
if auth_token is not None:
h['x-auth-token'] = [auth_token]
return h |
def ver_tuple_to_str(req_ver):
"""Converts a requirement version tuple into a version string."""
return ".".join(str(x) for x in req_ver) |
def fib_recursive(n):
""" return the n th fibonacci number recursive """
if n <= 2:
return 1
else:
return fib_recursive(n - 1) + fib_recursive(n - 2) |
def isnum(n):
""" Return True if n is a number, else False """
try:
y = n+1
return True
except:
return False |
def ext_valid_update_path(cursor, ext, current_version, version):
"""
Check to see if the installed extension version has a valid update
path to the given version. A version of 'latest' is always a valid path.
Return True if a valid path exists. Otherwise return False.
Args:
cursor (cursor) -- cursor object of psycopg2 library
ext (str) -- extension name
current_version (str) -- installed version of the extension.
version (str) -- target extension version to update to.
A value of 'latest' is always a valid path and will result
in the extension update command always being run.
"""
valid_path = False
params = {}
if version != 'latest':
query = ("SELECT path FROM pg_extension_update_paths(%(ext)s) "
"WHERE source = %(cv)s "
"AND target = %(ver)s")
params['ext'] = ext
params['cv'] = current_version
params['ver'] = version
cursor.execute(query, params)
res = cursor.fetchone()
if res is not None:
valid_path = True
else:
valid_path = True
return (valid_path) |
def mean(lst):
"""Return the average of a float list."""
length = len(lst)
return sum(lst)/float(length) if length != 0 else None |
def key_at_depth(dic, dpt):
""" From koffein
http://stackoverflow.com/questions/20425886/python-how-do-i-get-a-list-of-all-keys-in-a-dictionary-of-dictionaries-at-a-gi
"""
if dpt > 0:
return [key for subdic in dic.values() if isinstance(subdic,dict)
for key in key_at_depth(subdic, dpt-1) ]
else:
if isinstance(dic,dict):
return dic.keys()
else:
return [] |
def bfs(graph, start):
"""Visits all the nodes of a graph using BFS
Args:
graph (dict): Search space represented by a graph
start (str): Starting state
Returns:
explored (list): List of the explored nodes
"""
# list to keep track of all visited nodes
explored = []
# the FIFO queue
queue = []
# add the start node to the queue
queue.append(start)
# keep looping until there are no nodes still to be checked
while len(queue) > 0:
# pop first item from queue (FIFO)
node = queue.pop(0)
# check if the node has already been explored
if node not in explored:
# add node to list of checked nodes
explored.append(node)
# get neighbours if node is present, otherwise default to empty list
neighbours = graph.get(node, [])
# add neighbours of node to queue
for neighbour in neighbours:
queue.append(neighbour)
# return the explored nodes
return explored |
def GetChangePageUrl(host, change_number):
"""Given a gerrit host name and change number, return change page url."""
return 'https://%s/#/c/%d/' % (host, change_number) |
def _list_diff(a, b):
"""
Get the difference between two lists.
:param a: The first list.
:param b: The second list.
:return: A list of items that are in the first list but not in the second \
list.
"""
# Return the difference between two lists
return [x for x in a if x not in b] |
def rfib2(n):
"""With functools.lru_cache"""
return rfib2(n - 1) + rfib2(n - 2) if n > 2 else 1 |
def bytechr(i):
"""Return bytestring of one character with ordinal i; 0 <= i < 256."""
if not 0 <= i < 256:
if not isinstance(i, int):
raise TypeError('an integer is required')
else:
raise ValueError('bytechr() arg not in range(256)')
return chr(i).encode('latin1') |
def _find_pk(pk, queryset):
"""Find a PK in a queryset in memory"""
found = None
try:
pk = int(pk)
found = next(obj for obj in queryset if obj.pk == pk)
except (ValueError, StopIteration):
pass
return found |
def IterWrapper(value):
""" Return an iterable for the value """
if type(value) is tuple:
return value
else:
return (value,) |
def get_int(string):
"""return the int value of a binary string"""
return int(string, 2) |
def split(value: str) -> list:
"""
Splits string and returns as list
:param value: required, string. bash command.
:returns: list. List of separated arguments.
"""
return value.split() |
def _set_gps_from_zone(kwargs, location, zone):
"""Set the see parameters from the zone parameters.
Async friendly.
"""
if zone is not None:
kwargs['gps'] = (
zone.attributes['latitude'],
zone.attributes['longitude'])
kwargs['gps_accuracy'] = zone.attributes['radius']
kwargs['location_name'] = location
return kwargs |
def nick(raw_nick):
"""
Split nick into constituent parts.
Nicks with an ident are in the following format:
nick!ident@hostname
When they don't have an ident, they have a leading tilde instead:
~nick@hostname
"""
if '!' in raw_nick:
nick, _rest = raw_nick.split('!')
ident, host = _rest.split('@')
elif '@' in raw_nick:
nick, host = raw_nick.split('@')
nick = nick.lstrip('~')
ident = None
else:
nick = raw_nick
ident = host = None
return {
'nick': nick,
'ident': ident,
'host': host,
} |
def get_process_output(cmd_stdout, cmd_stderr):
"""Get task process log output."""
text = ''
if cmd_stdout:
text += cmd_stdout.decode(errors='ignore').replace('\r', '')
if cmd_stderr:
text += cmd_stderr.decode(errors='ignore').replace('\r', '')
return text.rstrip('\n\r') |
def queue_suffix_for_platform(platform):
"""Get the queue suffix for a platform."""
return '-' + platform.lower().replace('_', '-') |
def color565(r, g, b):
"""Convert red, green, blue components to a 16-bit 565 RGB value. Components
should be values 0 to 255.
"""
return ((r & 0xF0) << 8) | ((g & 0xFC) << 3) | (b >> 3) |
def validate_input(self,user_input):
"""check some edge cases"""
#check if len of input is equal to or less than amount of frames
#return if this is the case, no simulation needed here
#user must enter jobs before submitting
if(len(user_input) <= 0):
return -1
#user must delimit with comma
if(',' not in user_input):
return -1
#split input on comma
user_input=user_input.split(',')
return user_input |
def check_days_to_check(days_to_check: int):
"""
days_to_check has to be 0 or bigger.
"""
if days_to_check < 0:
return (False)
return (True) |
def get_last_version(documents):
"""
Helper function to get the last version of the list of documents provided.
:param documents: List of documents to check.
:type documents: [cla.models.model_interfaces.Document]
:return: 2-item tuple containing (major, minor) version number.
:rtype: tuple
"""
last_major = 0 # 0 will be returned if no document was found.
last_minor = -1 # -1 will be returned if no document was found.
for document in documents:
current_major = document.get_document_major_version()
current_minor = document.get_document_minor_version()
if current_major > last_major:
last_major = current_major
last_minor = current_minor
continue
if current_major == last_major and current_minor > last_minor:
last_minor = current_minor
return last_major, last_minor |
def long_to_bytes(val, expect_byte_count=None, endianness='big'):
"""
Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
convert ``val``, a :func:`long`, to a byte :func:`str`.
:param expect_byte_count:
:param long val: The value to pack
:param str endianness: The endianness of the result. ``'big'`` for
big-endian, ``'little'`` for little-endian.
If you want byte- and word-ordering to differ, you're on your own.
Using :ref:`string formatting` lets us use Python's C innards.
"""
from binascii import unhexlify
# one (1) hex digit per four (4) bits
width = val.bit_length()
# unhexlify wants an even multiple of eight (8) bits, but we don't
# want more digits than we need (hence the ternary-ish 'or')
width += 8 - ((width % 8) or 8)
if expect_byte_count is not None and expect_byte_count > width // 8:
width = expect_byte_count * 8
# format width specifier: four (4) bits per hex digit
fmt = '%%0%dx' % (width // 4)
# prepend zero (0) to the width, to zero-pad the output
s = unhexlify(fmt % val)
if endianness == 'little':
# see http://stackoverflow.com/a/931095/309233
s = s[::-1]
return s |
def return_union_item(item):
"""union of statements, next statement"""
return " __result.update({0})".format(item) |
def count_line_length(file_contents):
"""
The function count line length
Parameters
----------
file_contents : str
file contents
Returns
-------
: list[int]
list of line length
"""
return [len(line) for line in file_contents.splitlines()] |
def extract_property_class(prop):
"""
This function extracts the property class from the property string.
Property strings have the format of -([<function>.]<property_class_id>.<counter>)
"""
prop_class = prop["property"].rsplit(".", 3)
# Do nothing if prop_class is diff than cbmc's convention
class_id = prop_class[-2] if len(prop_class) > 1 else None
return class_id |
def with_previous_s1(iterable):
"""Provide each sequence item with item before it
Comments:
This is an improvement over the previous solution:
1. We are now keeping track of the previous item
2. We are avoiding indexes.
Solution passes 1 bonus
"""
prev = None
items = []
for item in iterable:
items.append((item, prev))
prev = item
return items |
def get_attachment_path(problem_number):
"""
Given a problem number, return the path of the attachment file.
"""
import os
# hard-coded configs
attachment_dir = "attachments"
attachment_filenames = {
22: "p022_names.txt",
42: "p042_words.txt",
54: "p054_poker.txt",
59: "p059_cipher.txt",
67: "p067_triangle.txt",
79: "p079_keylog.txt",
81: "p081_matrix.txt",
82: "p082_matrix.txt",
83: "p083_matrix.txt",
99: "p099_base_exp.txt",
}
attachment_path = os.path.join(attachment_dir, attachment_filenames[problem_number])
return attachment_path |
def find_unordered_cfg_lines(intended_cfg, actual_cfg):
"""Check if config lines are miss-ordered, i.e in ACL-s.
Args:
intended_cfg (str): Feature intended configuration.
actual_cfg: (str): Feature actual configuration.
Returns:
list: List of tuples with unordered_compliant cfg lines.
Example:
>>> intended_cfg = '''
... ntp server 10.10.10.10
... ntp server 10.10.10.11
... ntp server 10.10.10.12'''
>>>
>>> actual_cfg = '''
... ntp server 10.10.10.12
... ntp server 10.10.10.11
... ntp server 10.10.10.10'''
>>>
>>> find_unordered_cfg_lines(intended_cfg, actual_cfg)
(True, [('ntp server 10.10.10.10', 'ntp server 10.10.10.12'), ('ntp server 10.10.10.12', 'ntp server 10.10.10.10')])
"""
intended_lines = intended_cfg.splitlines()
actual_lines = actual_cfg.splitlines()
unordered_lines = []
if len(intended_lines) == len(actual_lines):
# Process to find actual lines that are misordered
unordered_lines = [(e1, e2) for e1, e2 in zip(intended_lines, actual_lines) if e1 != e2]
# Process to find determine if there are any different lines, regardless of order
if not set(intended_lines).difference(actual_lines):
return (True, unordered_lines)
return (False, unordered_lines) |
def calculate_kinetic_energy(mass, velocity):
"""Returns kinetic energy of mass [kg] with velocity [ms]."""
return 0.5 * mass * velocity ** 2 |
def partition(array: list, low: int, high: int, pivot: int) -> int:
"""
>>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
>>> partition(array, 0, len(array), 12)
8
"""
i = low
j = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
array[i], array[j] = array[j], array[i]
i += 1 |
def reformat_for_export(parsed_note_data):
"""
Format a parsed note into an understandable
plain text version for later download
"""
export_string = "================================================================\n"
export_string += "Title: " + parsed_note_data["title"] + "\n"
export_string += "================================================================\n"
export_string += "Date Created: " + parsed_note_data["ui_date"] + "\n"
export_string += "Tags: " + ", ".join(parsed_note_data["tags"]) + "\n"
export_string += "================================================================\n"
export_string += "Note:\n" + parsed_note_data["content"] + "\n"
return export_string |
def format_3(value):
"""Round a number to 3 digits after the dot."""
return "{:.3f}".format(value) |
def format_image_bboxes(bboxes_on_image, class_dict, crop_size=512):
"""Convert ImageAug BoundingBoxOnImage object to YOLO fmt labels
Parameters
----------
bboxes_on_image: imgaug.imgaug.BoundingBoxexOnImage
ImgAug object containing all bboxes
class_dict: dict
Dictionary containing class labels as keys and class numbers as objects
Returns
-------
formatted_bboxes: list
List of strings formatted in YOLO format for writing to text file.
"""
formatted_bboxes = []
# Ensure that some bounding boxes exist
if bboxes_on_image:
for bbox in bboxes_on_image.bounding_boxes:
coords = [(bbox.x1 + bbox.width / 2.) / crop_size,
(bbox.y1 + bbox.height /2.) / crop_size,
bbox.width / crop_size,
bbox.height / crop_size]
for coord_i, coord in enumerate(coords):
if coord <= 0:
coords[coord_i] = 1e-8
if coord >= 1:
coords[coord_i] = 1 - 1e-8
line = '{cls} {x:.8f} {y:.8f} {w:.8f} {h:.8f}\n'.format(
cls=bbox.label, x=coords[0], y=coords[1], w=coords[2],
h=coords[3])
formatted_bboxes.append(line)
return formatted_bboxes |
def id_is_int(patient_id):
""" Check if patient id is integer
Check if the patient's id is a integer
Args:
patient_id (int): id number of the patient
Returns:
True or str: indicate if the input patient id is an integer
"""
try:
int(patient_id)
return True
except ValueError:
return "Please use an integer or a numeric string containing " \
"an ID number but without any letter" |
def norm_aplha(alpha):
""" normalise alpha in range (0, 1)
:param float alpha:
:return float:
>>> norm_aplha(0.5)
0.5
>>> norm_aplha(255)
1.0
>>> norm_aplha(-1)
0
"""
alpha = alpha / 255. if alpha > 1. else alpha
alpha = 0 if alpha < 0. else alpha
alpha = 1. if alpha > 1. else alpha
return alpha |
def try_divide(x, y, val=0.0):
"""
try to divide two numbers
"""
if y != 0.0:
val = float(x) / y
return val |
def rational_lcm(*args):
"""Least common multiple of rationals"""
# Handle the case that a list is provided
if len(args) == 1 and type(args[0]) is list:
return sum(*args[0])
return sum(args) |
def search_by_id(target_book_id = ""):
"""
this function takes in a book id and returns a list of possible matches
"""
# do nothing if no name given
if target_book_id == "":
# [] represents not found
return []
# open file and load file contents to an array
f = open("database.txt","r")
database_arr = f.readlines()
f.close()
# search_results is [] by default which means target not found
search_results = []
for record in database_arr:
# [:-1] removes the last \n character in record_arr
record_arr = record.split(',')[:-1]
# in record_arr, 0: book id, 1: book name, 2: author name, 3: purchase date, 4: Member id (0 if not borrowed)
if target_book_id == record_arr[0]:
# if book name found, add this line into search result array
search_results.append(record_arr)
return search_results |
def euclid_alg (a, b):
""" Euclidean algorithm for gcd.
Finds the greatest common divisor of
two integers.
"""
a, b = abs(a), abs(b)
while b != 0:
r = a % b
a, b = b, r
return a |
def getItemNames(fullname):
"""Split a fullname in the 3 parts that compose it
Args:
fullname(str): Fullname
Returns:
tuple with the names of each item in the hierarchy or None
for the items that are not present
"""
n = fullname.split(':')
if len(n) == 1:
return n[0], None, None
if len(n) == 2:
return n[0], n[1], None
if len(n) == 3:
return n[0], n[1], n[2]
return None, None, None |
def single_line(line, report_errors=True, joiner='+'):
"""Force a string to be a single line with no carriage returns, and report
a warning if there was more than one line."""
lines = line.strip().splitlines()
if report_errors and len(lines) > 1:
print('multiline result:', lines)
return joiner.join(lines) |
def longest_in_list( l:list ) ->str:
"""
Returns the longest item's string inside a list
"""
longest :str = ''
for i in range( len(l) ):
if len( str(l[i]) ) > len(longest):
longest = l[i]
return longest |
def item_empty_filter(d):
"""return a dict with only nonempty values"""
pairs = [(k, v) for (k, v) in d.items() if v]
return dict(pairs) |
def replace_at(string,old,new,indices):
"""Replace the substring "old" by "new" in a string at specific locations
only.
indices: starting indices of the occurences of "old" where to perform the
replacement
return value: string with replacements done"""
if len(indices) == 0: return string
indices = sorted(indices)
s = string[0:indices[0]]
for i in range(0,len(indices)-1):
s += string[indices[i]:indices[i+1]].replace(old,new,1)
s += string[indices[-1]:].replace(old,new,1)
return s |
def twos_complement(dec):
"""
Convert decimal integer number to U2
:param dec: Number to change
:type dec: int
:return: Number in U2
:rtype: string
"""
if dec >= 0:
binint = "{0:b}".format(dec)
if binint[0] == "1": binint = "0" + binint
else:
dec2 = abs(dec + 1)
binint_r = "{0:b}".format(dec2)
binint = "1"
for bit in binint_r:
if bit == "1":
binint += "0"
else:
binint += "1"
return binint |
def _label(label: str) -> str:
"""
Returns a query term matching a label.
Args:
label: The label the message must have applied.
Returns:
The query string.
"""
return f'label:{label}' |
def get_input_data(input_section):
"""
Gets playbook single input item - support simple and complex input.
:param input_section: playbook input item.
:return: The input default value(accessor) and the input source(root).
"""
default_value = input_section.get('value')
if isinstance(default_value, str):
return default_value, ''
if default_value:
complex = default_value.get('complex')
if complex:
return complex.get('accessor'), complex.get('root')
return default_value.get('simple'), ''
return '', '' |
def reverse(x):
"""
:type x: int
:rtype: int
"""
lower = -(2 ** 31)
upper = (2 ** 31) - 1
if x < 0:
neg = True
else:
neg = False
x = abs(x)
answer = 0
while (x // 10) >= 0:
answer = (answer * 10) + x % 10
x //= 10
if x == 0:
break
if neg:
answer = -answer
else:
answer = answer
if answer < lower or answer > upper:
return 0
return answer |
def split_component_view(arg):
"""
Split the input to data or subset.__getitem__ into its pieces.
Parameters
----------
arg
The input passed to ``data`` or ``subset.__getitem__``. Assumed to be
either a scalar or tuple
Returns
-------
selection
The Component selection (a ComponentID or string)
view
Tuple of slices, slice scalar, or view
"""
if isinstance(arg, tuple):
if len(arg) == 1:
raise TypeError("Expected a scalar or >length-1 tuple, "
"got length-1 tuple")
if len(arg) == 2:
return arg[0], arg[1]
return arg[0], arg[1:]
else:
return arg, None |
def stable_unique(items):
"""
Return a copy of ``items`` without duplicates. The order of other items is
unchanged.
>>> stable_unique([1,4,6,4,6,5,7])
[1, 4, 6, 5, 7]
"""
result = []
seen = set()
for item in items:
if item in seen:
continue
seen.add(item)
result.append(item)
return result |
def _trim_pandas_styles(styles):
"""Trim pandas styles dict.
Parameters
----------
styles : dict
pandas.Styler translated styles.
"""
# Filter out empty styles, as every cell will have a class
# but the list of props may just be [['', '']].
return [x for x in styles if any(any(y) for y in x["props"])] |
def is_valid_aspect_target(target):
"""Returns whether the target has had the aspect run on it."""
return hasattr(target, "intellij_info") |
def force_iterator(mixed):
"""Sudo make me an iterator.
Deprecated?
:param mixed:
:return: Iterator, baby.
"""
if isinstance(mixed, str):
return [mixed]
try:
return iter(mixed)
except TypeError:
return [mixed] if mixed else [] |
def extract_types_from_response(response_data):
"""
This function extracts the list of types found by code_inspector from the response.
:param response_data json response from code_inspector
"""
types = []
software_info = {}
if "software_invocation" in response_data:
software_info = response_data['software_invocation']
for soft_entry in software_info:
type_s = soft_entry["type"] # "type" is not a list anymore
if type_s not in types:
if "script" in type_s: # we have annotated script with main and without main as script
types.append("script")
else:
types.append(type_s)
return types, software_info |
def macaddr_pack(data, bytes = bytes):
"""
Pack a MAC address
Format found in PGSQL src/backend/utils/adt/mac.c, and PGSQL Manual types
"""
# Accept all possible PGSQL Macaddr formats as in manual
# Oh for sscanf() as we could just copy PGSQL C in src/util/adt/mac.c
colon_parts = data.split(':')
dash_parts = data.split('-')
dot_parts = data.split('.')
if len(colon_parts) == 6:
mac_parts = colon_parts
elif len(dash_parts) == 6:
mac_parts = dash_parts
elif len(colon_parts) == 2:
mac_parts = [colon_parts[0][:2], colon_parts[0][2:4], colon_parts[0][4:],
colon_parts[1][:2], colon_parts[1][2:4], colon_parts[1][4:]]
elif len(dash_parts) == 2:
mac_parts = [dash_parts[0][:2], dash_parts[0][2:4], dash_parts[0][4:],
dash_parts[1][:2], dash_parts[1][2:4], dash_parts[1][4:]]
elif len(dot_parts) == 3:
mac_parts = [dot_parts[0][:2], dot_parts[0][2:], dot_parts[1][:2],
dot_parts[1][2:], dot_parts[2][:2], dot_parts[2][2:]]
elif len(colon_parts) == 1:
mac_parts = [data[:2], data[2:4], data[4:6], data[6:8], data[8:10], data[10:]]
else:
raise ValueError('data string cannot be parsed to bytes')
if len(mac_parts) != 6 and len(mac_parts[-1]) != 2:
raise ValueError('data string cannot be parsed to bytes')
return bytes([int(p, 16) for p in mac_parts]) |
def print_float(value): # sInt #string_float_value
"""int represented as a short float"""
value = "%f" % value
return value.rstrip('0') |
def coalesce(*args):
"""return first non-None arg or None if none"""
for arg in args:
if arg is not None:
return arg
return None |
def read_labels(labels_file):
"""
Returns a list of strings
Arguments:
labels_file -- path to a .txt file
"""
if not labels_file:
print('WARNING: No labels file provided. Results will be difficult to interpret.')
return None
labels = []
with open(labels_file) as infile:
for line in infile:
label = line.strip()
if label:
labels.append(label)
assert len(labels), 'No labels found'
return labels |
def get_available_resources(threshold, usage, total):
""" Get a map of the available resource capacity.
:param threshold: A threshold on the maximum allowed resource usage.
:type threshold: float,>=0
:param usage: A map of hosts to the resource usage.
:type usage: dict(str: number)
:param total: A map of hosts to the total resource capacity.
:type total: dict(str: number)
:return: A map of hosts to the available resource capacity.
:rtype: dict(str: int)
"""
return dict((host, int(threshold * total[host] - resource))
for host, resource in usage.items()) |
def length_vector_sqrd(vector):
"""Compute the squared length of a vector.
Parameters
----------
vector : list
XYZ components of the vector.
Returns
-------
float
The squared length.
Examples
--------
>>> length_vector_sqrd([1.0, 1.0, 0.0])
2.0
"""
return vector[0] ** 2 + vector[1] ** 2 + vector[2] ** 2 |
def superpack_name(pyver, numver):
"""Return the filename of the superpack installer."""
return 'numpy-%s-win32-superpack-python%s.exe' % (numver, pyver) |
def _coord(x):
"""String representation for coordinate"""
return ("%.4f" % x).rstrip("0").rstrip(".") |
def verifica_participante(s):
"""
"""
return "Participants" in s |
def sign_to_int(signs):
"""
Convert a list to an integer.
[-1, 1, 1, -1], -> 0b0110 -> 6
"""
return int("".join('0' if x == -1 else '1' for x in signs),2) |
def det2(a, b, c, d):
"""Determinant of 2x2 matrix"""
return a * d - b * c |
def name_spin_sym(nElec: int) -> str:
"""Finds the suitable name (or more general: string representation) for the given amount of unpaired
electrons. For instance 2 unpaired electrons represent a "Triplet"."""
names = ["Singlet", "Doublet", "Triplet", "Quartet",
"Quintet", "Sextet", "Septet", "Octet", "Nonet", "Decet"]
if nElec < len(names):
return names[nElec]
if nElec % 2:
return "S=%d" % (nElec // 2)
else:
return "S=%d/2" % nElec |
def client_registration_supported_to_gui(config_file_dict,
config_gui_structure):
"""
Converts a required information from config file to a config GUI structure
:param config_gui_structure: Data structure used to hold and show
configuration information in the Gui
:param config_file_dict: The configuration file from which the
configuration required information data should be gathered
:return The updated configuration GUI data structure
"""
supports_dynamic_client_registration = False
if "client_registration" not in config_file_dict:
return config_gui_structure
if "client_id" in config_file_dict["client_registration"]:
supports_dynamic_client_registration = True
config_gui_structure["dynamicClientRegistrationDropDown"][
"value"] = "no"
for text_field in config_gui_structure["supportsStaticClientRegistrationTextFields"]:
if text_field["id"] == "client_id":
text_field["textFieldContent"] = \
config_file_dict["client_registration"]["client_id"]
if "client_secret" in config_file_dict["client_registration"]:
supports_dynamic_client_registration = True
config_gui_structure["dynamicClientRegistrationDropDown"][
"value"] = "no"
for text_field in config_gui_structure["supportsStaticClientRegistrationTextFields"]:
if text_field["id"] == "client_secret":
text_field["textFieldContent"] = \
config_file_dict["client_registration"]["client_secret"]
if not supports_dynamic_client_registration:
config_gui_structure["dynamicClientRegistrationDropDown"][
"value"] = "yes"
return config_gui_structure |
def get_color(val, trendType):
"""Determine if evolution is positive or negative.
From trend type - determined in config.toml for each KPIs,
picking right color to return
"""
if(val > 0):
if(trendType == 'normal'):
color = 'red'
else:
color = 'green'
elif(val < 0):
if(trendType == 'normal'):
color = 'green'
else:
color = 'red'
else:
color = 'blue'
return color |
def _pf1c(val1, val2):
"""
Returns
-------
Description for the return statement
"""
return int(val1 + int(val2[0])) |
def LineRamp(t, duration, Initial, Final):
"""Creates a linear ramp from A to B"""
f = t / duration
return (1 - f) * Initial + f * Final |
def parse_dimension(string):
"""Parses a dimension string to a tuple (key, value, expiration_secs)."""
key, value = string.split(':', 1)
expiration_secs = 0
try:
expiration_secs = int(key)
except ValueError:
pass
else:
key, value = value.split(':', 1)
return key, value, expiration_secs |
def sanitize_field(value):
"""Clean field used in the payment request form
:param string value:
:return: A sanitized value
Adyen suggest to remove all new-line, so we do.
"""
if value is None:
return value
return str(value).replace('\n', ' ').replace('\r', ' ').strip() |
def lettergrade(value):
"""
Maps grade point average to letter grade.
"""
if value > 3.85:
return 'A'
elif value > 3.5:
return 'A-'
elif value > 3.15:
return 'B+'
elif value > 2.85:
return 'B'
elif value > 2.5:
return 'B-'
elif value > 2.15:
return 'C+'
elif value > 1.85:
return 'C'
elif value > 1.5:
return 'C-'
elif value > 1.15:
return 'D+'
elif value > 0.85:
return 'D'
elif value > 0.5:
return 'D-'
else:
return 'F' |
def trapped_rainwater(arr_tank):
"""
The elements of the array are heights of walls.
If it rains, how much rain water will be trapped?
I will answer this question for any array you give me.
"""
prev_ht = arr_tank[0]
drops = []
goingdown=True
area = 0
for ht in arr_tank[1:]:
for i in range(len(drops)):
drops[i]+=1
if ht < prev_ht:
#if not goingdown:
# drops = []
goingdown=True
for _ in range(prev_ht-ht):
drops.append(0)
elif ht > prev_ht:
goingdown=False
for _ in range(ht-prev_ht):
if len(drops)>0:
area += drops.pop()
prev_ht = ht
print(str(drops))
return area |
def score_discrete(tabcode_a, tabcode_b):
"""
Return the tableau matching score between the two tableaux entries
tabcode_a amd tabcode_b, as per Kamat et al (2008) (s5.1).
This score is 2 if the tableau entries are equal, 1 if they are equal
in only one position, else -2.
"""
if tabcode_a[0] == tabcode_b[0]:
if tabcode_a[1] == tabcode_b[1]:
return 2
else:
return 1
elif tabcode_a[1] == tabcode_b[1]:
return 1
else:
return -2 |
def mean(x: list) -> float:
"""given x can be an array or list output is the mean value"""
mean_x = sum(x)/len(x)
return mean_x |
def reverseStrA(s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
if len(s) <=k:
return s[::-1]
elif k<=len(s)<2*k:
return s[:k][::-1]+s[k:]
else:
result=""
start=0
value=len(s) % (2 * k)
if value != 0:
s+=" "*(2*k-value)
for i in range(2*k-1,len(s),2*k):
string=s[start:i+1]
substring=string[:k]
result+=substring[::-1]+string[k:]
start=i+1
return result.replace(" ","") |
def _get_keys(response):
"""
return lists of strings that are the keys from a client.list_objects() response
"""
keys = []
if 'Contents' in response:
objects_list = response['Contents']
keys = [obj['Key'] for obj in objects_list]
return keys |
def extract(predicate, iterable):
"""Separates the wheat from the shaft (`predicate` defines what's the wheat), and returns both.
"""
wheat = []
shaft = []
for item in iterable:
if predicate(item):
wheat.append(item)
else:
shaft.append(item)
return wheat, shaft |
def get_horizontal_radius(res):
"""Returns half the width of the input rectangle."""
return round(res[0] / 2) |
def get_aa_using_name_gct(gct=None, aa=None):
"""
This function returns a dictionary object containing
:param gct: dictionary object containing gc table data.
:param aa: amino acid notation/ name (String) e.g. Full name e.g. Alanine or
3-letter notation e.g. Ala or single letter notation e.g. A
:return:
"""
try:
if gct is None or aa is None:
# Invalid set of inputs provided
return None
# if notation is given
if len(aa) == 3:
if aa.lower() in gct.keys():
return gct.get(aa.lower())
# lookup for fullname or notation
for key in gct.keys():
aa_data = gct.get(key)
if aa_data["name"].lower() == aa.lower() or \
aa_data["symbol"].lower() == aa.lower():
return aa_data
# If nothing is found, return None
return None
except Exception:
return None |
def sinal(u):
""" Retorna a classe baseada no valor de u. """
return 1 if u >= 0 else -1 |
def sol(a, b):
"""
Take an XOR, so 1 will be set whereever there is bit diff.
Keep doing AND with the number to check if the last bit is set
"""
c = a^b
count=0
while c:
if c&1:
count+=1
c=c>>1
return count |
def RPL_UNIQOPIS(sender, receipient, message):
""" Reply Code 325 """
return "<" + sender + ">: " + message |
def poisson_lambda_mle(d):
"""
Computes the Maximum Likelihood Estimate for a given 1D training
dataset from a Poisson distribution.
"""
return sum(d) / len(d) |
def vis444(n):
"""
O OO OOO OOOO
O O O
O O
O
"""
result = ''
for i in range(n):
result = 'O' + 'O' * (n - 1)
result += '\nO' * (n - 1)
return result |
def limit_lines(lines, N=32):
""" When number of lines > 2*N, reduce to N.
"""
if len(lines) > 2 * N:
lines = [b"... showing only last few lines ..."] + lines[-N:]
return lines |
def place_equiv(y, y_hat):
"""
Checks if two cvs have equivalent place.
"""
if ((y%19 in [0, 2, 10, 1, 11, 6, 3, 17]) and
(y_hat%19 in [0, 2, 10, 1, 11, 6, 3, 17])):
if (y%19 in [0, 2, 10]) and (y_hat%19 in [0, 2, 10]):
# b, f, r
return True
elif (y%19 in [1, 11, 6]) and (y_hat%19 in [1, 11, 6]):
# d, s, l
return True
elif (y%19 in [3, 17]) and (y_hat%19 in [3, 17]):
# g, y
return True
else:
return False
else:
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.