content
stringlengths 42
6.51k
|
---|
def get_activities_from_log(trace_log, attribute_key="concept:name"):
"""
Get the attributes of the log along with their count
Parameters
----------
trace_log
Trace log
attribute_key
Attribute key (must be specified if different from concept:name)
Returns
----------
attributes
Dictionary of attributes associated with their count
"""
activities = {}
for trace in trace_log:
for event in trace:
if attribute_key in event:
attribute = event[attribute_key]
if not attribute in activities:
activities[attribute] = 0
activities[attribute] = activities[attribute] + 1
return activities
|
def unique(seq):
"""Keep unique while preserving order."""
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))]
|
def bytes_to_hex(bstr):
"""Convert a bytestring to a text string of hexadecimal digits.
This exists solely to support Python 3.4 for Cygwin users.
bytes(...).hex() was added in Python 3.5.
Note that most callers of this function need to encode the text string
back into a bytestring of ASCII characters. This function does not do that
to remain equivalent to bytes(...).hex().
Args:
bstr: The bytestring.
Returns:
The text string of hexadecimal digits.
"""
return ''.join(format(b, '02x') for b in bstr)
|
def T(a, p):
"""
the number of dots in tri-angle down
"""
ret = 0
ed = (p + 1) >> 1
for i in range(ed):
ret += a * i // p
return ret
|
def create_message(payload, event_status, environment):
"""
Parameters
----------
payload: dict
Status -- str in {New Data Loaded, Daily Data Updated}
New Records -- int, number of new records added since previous run
Updated Records -- int, number of updated records from this new run
event_status: str in {Success, Failure} based on source lambda invocation
environment: str in {production, testing}
Returns
------
message: str, message that is published to SNS topic
subject: str, Subject line for SNS topic email subscribers
"""
if event_status == 'Success':
message = f"Environment: {environment}\n{payload['Status']}\nNumber of New Records: {payload['New Records']}\nNumber of Updated Records: {payload['Updated Records']}"
subject = "COVID-19 ETL Process Successful, Data Updated"
else:
message = "An error occured in the COVID-19 ETL Process"
subject = "COVID-19 ETL Process Unsuccessful"
return message, subject
|
def gemi(red, nir):
"""Global Environment Monitoring Index boosted with Numba
See:
https://www.indexdatabase.de/db/i-single.php?id=25
"""
red2 = red ** 2
nir2 = nir ** 2
eta = (2 * (nir2 - red2) + (1.5 * nir) + (0.5 * red)) / (nir + red + 0.5)
return eta * (1 - 0.25*eta) - ((red - 0.125) / (1 - red))
|
def standardise_efficiency(efficiency):
"""Standardise efficiency types; one of the five categories:
poor, very poor, average, good, very good
Parameters
----------
efficiency : str
Raw efficiency type.
Return
----------
standardised efficiency : str
Standardised efficiency type."""
# Handle NaN
if isinstance(efficiency, float):
return "unknown"
efficiency = efficiency.lower().strip()
efficiency = efficiency.strip('"')
efficiency = efficiency.strip()
efficiency = efficiency.strip("|")
efficiency = efficiency.strip()
efficiency_mapping = {
"poor |": "Poor",
"very poor |": "Very Poor",
"average |": "Average",
"good |": "Good",
"very good |": "Very Good",
"poor": "Poor",
"very poor": "Very Poor",
"average": "Average",
"good": "Good",
"very good": "Very Good",
"n/a": "unknown",
"n/a |": "unknown",
"n/a": "unknown",
"n/a | n/a": "unknown",
"n/a | n/a | n/a": "unknown",
"n/a | n/a | n/a | n/a": "unknown",
"no data!": "unknown",
"unknown": "unknown",
}
return efficiency_mapping[efficiency]
|
def convert_public_keys_to_names(nodes_by_public_key, public_keys):
"""Convert a set/list of node public keys to a set of names"""
return {
nodes_by_public_key[public_key]['name'] if 'name' in nodes_by_public_key[public_key] \
else public_key \
for public_key in public_keys
}
|
def get_datasets_and_restrictions(train_datasets='',
eval_datasets='',
use_dumped_episodes=False,
restrict_classes=None,
restrict_num_per_class=None):
"""Gets the list of dataset names and possible restrictions on their classes.
Args:
train_datasets: A string of comma-separated dataset names for training.
eval_datasets: A string of comma-separated dataset names for evaluation.
use_dumped_episodes: bool, if True `eval_datasets` are prefixed with
`dumped` to trigger evaluation on dumped episodes instead of on the fly
sampling.
restrict_classes: If provided, a dict that maps dataset names to a dict that
specifies for each of `TRAIN_SPLIT`, `VALID_SPLIT` and `TEST_SPLIT` the
number of classes to restrict to. This can lead to some classes of a
particular split of a particular dataset never participating in episode
creation.
restrict_num_per_class: If provided, a dict that maps dataset names to a
dict that specifies for each of `meta_dataset.trainer.TRAIN_SPLIT`,
`meta_dataset.trainer.VALID_SPLIT` and `meta_dataset.trainer.TEST_SPLIT`
the number of examples per class to restrict to. For datasets / splits
that are not specified, no restriction is applied.
Returns:
Two lists of dataset names and two possibly empty dictionaries.
"""
if restrict_classes is None:
restrict_classes = {}
if restrict_num_per_class is None:
restrict_num_per_class = {}
train_datasets = [d.strip() for d in train_datasets.split(',')]
eval_datasets = [d.strip() for d in eval_datasets.split(',')]
if use_dumped_episodes:
eval_datasets = ['dumped_%s' % ds for ds in eval_datasets]
return train_datasets, eval_datasets, restrict_classes, restrict_num_per_class
|
def pwlcm(x, p):
"""
"""
if 0 < x <= p:
return x/p
elif p < x < 1:
return (1-x)/(1-p)
else:
print(x)
raise ValueError
|
def startswith(string, prefixes):
"""Checks if str starts with any of the strings in the prefixes tuple.
Returns the first string in prefixes that matches. If there is no match,
the function returns None.
"""
if isinstance(prefixes, tuple):
for prefix in prefixes:
if string.startswith(prefix):
return prefix
return None
elif isinstance(prefixes, str):
prefix = prefixes
if string.startswith(prefix):
return prefix
return None
else:
raise Exception('Second argument must be string or a tuple of strings.')
|
def has_valid_parens(text):
"""
Checks if an input string contains valid parenthesis patterns.
:param text: input string
:return: boolean (True if the parentheses are valid, False otherwise)
"""
for i in range(len(text)):
text = text.replace('()', '').replace('{}', '').replace('[]', '')
if not text:
return True
return False
|
def reverse_value_map(key_map, value_map):
"""Utility function for creating a
"reverse" value map from a given key map and value map.
"""
r_value_map = {}
for k, v in value_map.items():
sub_values = r_value_map[key_map[k]] = {}
for k2, v2 in v.items():
sub_values[v2] = k2
return r_value_map
|
def _get_default_value_name(name):
"""Returns the class default value of an attribute.
For each specified attribute, we create a default value that is class-specific
and not thread-specific. This class-wide default value is stored in an
internal attribute that is named `_attr_default` where `attr` is the name of
the specified attribute.
Args:
name: str, name of the exposed attribute.
Returns:
str, name of the internal attribute storing thread local value.
"""
return '_' + name + '_default'
|
def filterOnRange(intime,tstart,tstop):
"""filter on data within time ranges"""
outlist = []
for i in range(len(intime)):
for j in range(len(tstart)):
if intime[i] > tstart[j] and intime[i] < tstop[j]:
if len(outlist) == 0:
outlist.append(i)
elif i > outlist[-1]:
outlist.append(i)
return outlist
|
def check_ssid(ssid: str) -> str:
""" Check if SSID is valid """
if len(ssid) > 32:
raise ValueError("%s length is greater than 32" % ssid)
return ssid
|
def is_pair(arg):
"""Return True if ARG is a non-empty list or vector."""
if isinstance(arg, list) and len(arg) > 0:
return True
else:
return False
|
def pythagore_triangle(c, b):
"""
This function calculate the side of a right triangle using the Pythagore Theorem
:param c:
:param b:
:return:
"""
return ((c ** 2 - b ** 2) ** (0.5))
|
def newB(m, point):
"""find the y-intersection that the function/point pair passes through"""
b = (point[1] - (m * point[0]))
return b
|
def walk(G, s, S=set()):
"""
Returns a traversal path from s on G
source: Python Algorithms Mastering Basic Algorithms in the Python Language, 2010, p.104
"""
P, Q, SG = dict(), set(), dict()
P[s] = None
SG[s] = G[s]
Q.add(s)
while Q:
u = Q.pop()
for v in set(G[u].keys()).difference(P, S):
Q.add(v)
P[v] = u
SG[v] = G[v]
return SG
|
def get_latex_image_string(filename):
""" This function removes the final dot (".") and extension from the
filename, surrounds the remaining bits with braces ("{"), and sticks
the dot and extension back on.
"""
last_dot_index = filename.rfind(".")
f = filename[:last_dot_index]
extension = filename[last_dot_index+1:]
latex_image_string = "{" + f + "}." + extension
return latex_image_string
|
def dictation(m) -> str:
"""Arbitrary dictation."""
# Custom words are strings, phrases are lists
return " ".join([str(part).strip() for part in m])
|
def unquote(str):
"""Remove quotes from a string."""
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
return str[1:-1]
return str
|
def _is_const(expr, value):
"""
Helper Method, given an expression, returns True
if the expression is a constant and is equal to
the value passed in with VALUE
"""
if expr["type"] == "const":
return value == expr["value"]
return False
|
def create_composite_func(func0, func1):
"""Return a composite of two functions."""
if func0 is None:
return func1
if func1 is None:
return func0
return lambda x: func0(func1(x))
|
def validate_string(data: str) -> bool:
"""
Validate input for a field that must have a ``str`` value.
Args:
data (str): The data to be validated.
Returns:
bool: Validation passed.
Raises:
ValueError: Validation failed.
"""
if not isinstance(data, str):
raise ValueError(f"Not a string ({data})")
return True
|
def short_to_decimal(code):
"""
Convert an ICD9 code from short format to decimal format.
"""
if len(code) <= 3:
return code.lstrip("0")
else:
return code[:3].lstrip("0") + "." + code[3:]
|
def percent_clear_days(clear_days, total_days):
"""Returns the percentage of clear days, given
the number total days and clear days.
Parameters
----------
clear_days : int
Number of clear days.
total_days : int
Number of total days
Returns
-------
percent_clear : float
Percentage of clear days.
Example
-------
>>> # Calculate percent clear
>>> percent_clear = percent_clear_days(15, 31)
>>> # Show percent clear
>>> percent_clear
48.39
"""
# Calculate percent clear
percent_clear = round(100 * clear_days / total_days, 2)
# Return result
return percent_clear
|
def eye(n, K):
"""
Returns an identity matrix of size n.
Examples
========
>>> from sympy.matrices.densetools import eye
>>> from sympy import ZZ
>>> eye(3, ZZ)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
result = []
for i in range(n):
result.append([])
for j in range(n):
if i == j:
result[i].append(K(1))
else:
result[i].append(K.zero)
return result
|
def format_underscore_template(name, content):
"""
Format the template as an Underscore.js template.
:param name: name of the template
:param content: content of the template
:return: string containing formatted template
"""
return '\n<script type="text/template" id="{0}">\n{1}\n</script>\n'.format(name, content)
|
def dict_merge(dct, merge_dct, add_keys=True):
"""
https://gist.github.com/angstwad/bf22d1822c38a92ec0a9?permalink_comment_id=2622319#gistcomment-2622319
Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
updating only top-level keys, dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
``dct``.
This version will return a copy of the dictionary and leave the original
arguments untouched.
The optional argument ``add_keys``, determines whether keys which are
present in ``merge_dict`` but not ``dct`` should be included in the
new dict.
Args:
dct (dict) onto which the merge is executed
merge_dct (dict): dct merged into dct
add_keys (bool): whether to add new keys
Returns:
dict: updated dict
"""
try:
if isinstance(dct, dict):
dct = dct.copy()
if not add_keys:
merge_dct = {
k: merge_dct[k]
for k in set(dct).intersection(set(merge_dct))
}
for k, v in merge_dct.items():
if (k in dct and isinstance(dct[k], dict) and isinstance(merge_dct[k], dict)):
dct[k] = dict_merge(dct[k], merge_dct[k], add_keys=add_keys)
else:
dct[k] = merge_dct[k]
elif isinstance(dct, list):
return dct + list(set(merge_dct) - set(dct))
except Exception as e:
pass
return dct
|
def safe_eval(source):
"""
Protected string evaluation.
Evaluate a string containing a Python literal expression without
allowing the execution of arbitrary non-literal code.
Parameters
----------
source : str
The string to evaluate.
Returns
-------
obj : object
The result of evaluating `source`.
Raises
------
SyntaxError
If the code has invalid Python syntax, or if it contains
non-literal code.
Examples
--------
>>> np.safe_eval('1')
1
>>> np.safe_eval('[1, 2, 3]')
[1, 2, 3]
>>> np.safe_eval('{"foo": ("bar", 10.0)}')
{'foo': ('bar', 10.0)}
>>> np.safe_eval('import os')
Traceback (most recent call last):
...
SyntaxError: invalid syntax
>>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')
Traceback (most recent call last):
...
SyntaxError: Unsupported source construct: compiler.ast.CallFunc
"""
# Local import to speed up numpy's import time.
import ast
return ast.literal_eval(source)
|
def is_number(obj):
"""
Checks if the given object is a number.
Parameters
----------
obj : Any
The input argument.
Returns
-------
test result : bool
The test result of whether obj can be converted to a number or not.
>>> is_number(3)
True
>>> is_number(1.34)
True
>>> is_number('3')
True
>>> is_number(np.array(3))
True
>>> is_number('a')
False
>>> is_number([1, 2, 3])
False
>>> is_number(None)
False
"""
try:
float(obj)
return True
except (ValueError, TypeError):
return False
|
def legacy_position_transform(positions):
"""
Transforms positions in the tree sequence into VCF coordinates under
the pre 0.2.0 legacy rule.
"""
last_pos = 0
transformed = []
for pos in positions:
pos = int(round(pos))
if pos <= last_pos:
pos = last_pos + 1
transformed.append(pos)
last_pos = pos
return transformed
|
def map_reads(snps, reads):
"""
Find READS mapped to each SNP position.
:return list of snps have read mapped to
"""
return [snp.detect_mapped_reads(reads) for snp in snps]
|
def parse_response(response):
"""
Utility function to parse a response into a list.
"""
elements = []
for element in response['responses'][0]['labelAnnotations']:
elements.append(element['description'].capitalize())
return elements
|
def sim_percentage_change(obj_1, obj_2):
"""Calculate the percentage change of two objects
Args:
obj_1 ([type]): object 1
obj_2 ([type]): object 2
Returns:
float: numerical similarity
"""
try:
a = float(obj_1)
b = float(obj_2)
max_ab = max(abs(a), abs(b))
if max_ab == 0:
if a == b:
return 1
if a != b:
return 0
return 1 - abs(a - b) / max_ab
except ValueError:
return 0
|
def find_missing_number_using_sum(arr, arr2):
"""
This approach may be problematic in case if arrays are two long
or elements are very small
"""
complete_sum = 0
for val in arr:
complete_sum += val
missing_sum = 0
for val in arr2:
missing_sum += val
return complete_sum - missing_sum
|
def _verbosity_from_log_level(level):
"""Get log level from verbosity."""
if level == 40:
return 0
elif level == 20:
return 1
elif level == 10:
return 2
|
def _make_radial_gradient(X, Y):
"""Generates index map for radial gradients."""
import numpy as np
Z = np.sqrt(np.power(X, 2) + np.power(Y, 2))
return Z
|
def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges
|
def testMacFormat(macF):
"""Savoir si le format est dans la liste."""
if macF and macF.upper() in ('CISCO', 'UNIXE', 'BARE', 'NORMAL', 'UNIX', 'PGSQL'):
return macF
else:
return 'unixe'
|
def w_binary_to_hex(word):
"""Converts binary word to hex (word is a list)
>>> w_binary_to_hex("111")
'0x7'
>>> w_binary_to_hex([1,1,1,1])
'0xf'
>>> w_binary_to_hex([0,0,0,0,1,1,1,1])
'0xf'
>>> w_binary_to_hex([0,1,1,1,1,1,0,0])
'0x7c'
"""
if isinstance(word, str):
return hex(int(word, 2))
elif isinstance(word, list):
bin_str = "".join(str(e) for e in word)
return hex(int(bin_str, 2))
|
def sql(request_type, *args):
"""
Composes queries based on type of request.
"""
query = ''
if request_type == 'GET_ALL_USERS':
query = """ SELECT name FROM users"""
elif request_type == 'GET_USER_BY_ID':
query = """SELECT * FROM users where id = %s"""
elif request_type == 'GET_USER_BY_NAME':
query = """SELECT * FROM users where name = %s"""
elif request_type == 'GET_COMMUNITY_BY_NAME':
query = """SELECT * FROM community where name like %s"""
elif request_type == 'GET_COMMUNITY_BY_AREA':
query = """SELECT * FROM community where area = %s"""
elif request_type == 'GET_ALL_COMMUNITIES':
query = """SELECT * FROM community"""
elif request_type == 'POST_REGISTER_USER':
query = """INSERT INTO `users` (name, hash) VALUES(%s, %s)"""
elif request_type == 'POST_UPDATE_TOKEN':
query = """UPDATE `users` SET token = (%s) WHERE id = (%s)"""
elif request_type == 'POST_UPDATE_USER':
query ="""
UPDATE `users`
SET hash = (%s), address = (%s), phone_number = (%s), fk_community_ids = (%s)
WHERE id = (%s)
"""
return query
|
def keywords_parser(keywords):
"""
EM : Converts the string input from the GUI to a list object of strings.
"""
# Remove spaces
kwrds = keywords.replace(' ','')
# Split at ',' to separate time windows, then keep non-empty words
kwrds = [x for x in kwrds.split(',') if x]
if kwrds:
return kwrds
else:
return None
|
def check_diagonals(board, player):
""" 2 diagonals check """
diagonal_1 = [board[0],board[4],board[8]] # 0 | 4 | 8
diagonal_2 = [board[2],board[4],board[6]] # 2 | 4 | 6
d_1_win = (diagonal_1.count(player) == 3)
d_2_win = (diagonal_2.count(player) == 3)
win = (d_1_win or d_2_win)
return win
|
def camelize(string, uppercase_first_letter=True):
"""
Convert a string with underscores to a camelCase string.
Inspired by :func:`inflection.camelize` but even seems to run a little faster.
Args:
string (str): The string to be converted.
uppercase_first_letter (bool): Determines whether the first letter
of the string should be capitalized.
Returns:
str: The camelized string.
"""
if uppercase_first_letter:
return ''.join([word.capitalize() for word in string.split('_')])
elif not uppercase_first_letter:
words = [word.capitalize() for word in string.split('_')]
words[0] = words[0].lower()
return ''.join(words)
|
def try_id(item):
"""
Try and get the ID from an item, otherwise returning None.
"""
try:
return item.id
except AttributeError:
return None
|
def generate_color_series(color, variation, diff=10, reverse=False):
"""Generate light and dark color series.
Args:
color (tuple) : Color [0,255]
variation (int) : How many colors to create.
diff (int) : How much to change
reverse (bool) : If ``True``, sort in descending order.
Returns:
colors (list) : colors.
Examples:
>>> from pycharmers.utils import generateLightDarks
>>> generateLightDarks(color=(245,20,25), variation=3, diff=10)
[(235, 10, 15), (245, 20, 25), (255, 30, 35)]
>>> generateLightDarks(color=(245, 20, 25), variation=3, diff=-10)
[(225, 0, 5), (235, 10, 15), (245, 20, 25)]
"""
val = max(color[:3]) if diff > 0 else min(color[:3])
u = 0
for _ in range(variation - 1):
val += diff
if not 255 >= val >= 0:
break
u += 1
return sorted(
[
tuple(
[
max(min(e + diff * (u - v), 255), 0) if i < 3 else e
for i, e in enumerate(color)
]
)
for v in range(variation)
],
reverse=reverse,
)
|
def sum_valid_rooms(valid_rooms):
"""
Get the sum of all the sector IDs in valid rooms.
Args:
valid_rooms (list): List containting tuples of valid rooms.
Returns:
int
"""
# Valid Room:
# (room_name, sector_id, checksum)
return sum([i[1] for i in valid_rooms])
|
def min_ge(seq, val):
"""
Same as min_gt() except items equal to val are accepted as well.
:param seq:
:param val:
:return:
Examples:
min_ge([1, 3, 6, 7], 6)
>>>6
min_ge([2, 3, 4, 8], 8)
>>>8
"""
for v in seq:
if v >= val:
return v
return None
|
def get_alpha(score, weighted_ave, C=8):
"""
Get the main interest score of the lean
return: score is from 0 to 1
"""
alpha = 1 + C * abs(score - weighted_ave) / weighted_ave
return alpha
|
def _verify_src_version(version):
"""Checks to make sure an arbitrary character string is a valid version id
Version numbers are expected to be of the form X.Y.Z
Args:
version (str): string to validate
Returns:
bool: True if the string is a version number, else false
"""
if not isinstance(version, str):
return False
if "." not in version:
return False
parts = version.split(".")
if len(parts) != 3:
return False
for cur_part in parts:
if not cur_part.isdigit():
return False
return True
|
def execute(st, **kwargs):
"""
Work around for Python3 exec function which doesn't allow changes to the local namespace because of scope.
This breaks a lot of the old functionality in the code which was originally in Python2. So this function
runs just like exec except that it returns the output of the input statement to the local namespace. It may
break if you start feeding it multiline monoliths of statements (haven't tested) but you shouldn't do that
anyway (bad programming).
Parameters
-----------
st : the statement you want executed and for which you want the return
kwargs : anything that may need to be in this namespace to execute st
Returns
-------
The return value of executing the input statement
"""
namespace = kwargs
exec("b = {}".format(st), namespace)
return namespace['b']
|
def hex2dec(s):
""" Convert hex string to decimal number. Answer None if conversion raises
an error.
>>> hex2dec('0064')
100
>>> hex2dec('FFFF')
65535
>>> hex2dec(dec2hex(32))
32
>>> hex2dec('FFZ') is None
True
"""
try:
return int(s, 16)
except ValueError:
pass
return None
|
def get_param_map(iline, word, required_keys=None):
"""
get the optional arguments on a line
Examples
--------
>>> iline = 0
>>> word = 'elset,instance=dummy2,generate'
>>> params = get_param_map(iline, word, required_keys=['instance'])
params = {
'elset' : None,
'instance' : 'dummy2,
'generate' : None,
}
"""
if required_keys is None:
required_keys = []
words = word.split(',')
param_map = {}
for wordi in words:
if '=' not in wordi:
key = wordi.strip()
value = None
else:
sword = wordi.split('=', 1)
assert len(sword) == 2, sword
key = sword[0].strip()
value = sword[1].strip()
param_map[key] = value
msg = ''
for key in required_keys:
if key not in param_map:
msg += 'line %i: %r not found in %r\n' % (iline, key, word)
if msg:
raise RuntimeError(msg)
return param_map
|
def qsort_partition(arr: list, low: int, high: int):
"""
Quicksort partition logic.
The first element is chosen as the pivot
"""
i = low
j = high
pivot = arr[low]
while i < j:
i += 1
while i < high and pivot > arr[i]:
i += 1
j -= 1
while j > low and pivot < arr[j]:
j -= 1
if (i < j and arr[i] > arr[j]):
arr[i], arr[j] = arr[j], arr[i]
arr[j], arr[low] = pivot, arr[j]
return j
|
def list2dict(values_list):
"""A super simple function that takes a list of two element iterables
and returns a dictionary of lists keyed by the first element.
This: [("A","1"), ("A","2"), ("B","1"), ("C","1")]
Becomes: {"A": ["1", "2"], "B": ["1"], "C": ["1"] }
Arguments:
- `values_list`: list of two element lists or tuples.
"""
dictionary = dict()
for x in values_list:
elements = dictionary.get(x[0])
if elements:
elements.append(x[1])
dictionary[x[0]] = elements
else:
dictionary[x[0]] = [
x[1],
]
return dictionary
|
def isInt(string):
"""
Determine whether a string is an int
@param string: the string to check
@return True if the string is an int, False otherwise
"""
try: int(string)
except: return False
return True
|
def sequential_search_ordered(a_list, item):
"""Sequential search by ordering first."""
a_list = sorted(a_list)
pos = 0
is_found = False
is_stop = False
while pos < len(a_list) and not is_found and not is_stop:
if a_list[pos] == item:
is_found = True
else:
if a_list[pos] > item:
is_stop = True
else:
pos += 1
return is_found
|
def generate_search_space(max_x, max_y):
"""
@params: max_x : x axis consists of integer multiples of 8. (each value in the range(8, max_x+1. 8) represents one ihls)
@params: max_y : y axis just consists of powers of 2. (each value in the range 1,2,4,8,16,32 ... max_y (exclusive) represents one df)
Each entry is the (division factor, initial hidden layer size)
@returns search space (list)
"""
search_space = []
if max_x % 8 != 0 or max_y % 2 != 0: return search_space
i = 1
while i < max_y:
current_row = []
for j in range(8, max_x+1, 8):
current_row.append((i, j))
search_space.append(current_row)
i *= 2
return search_space
|
def cmds_to_bash(cmds):
"""Turn a list of cmds into a bash script.
"""
return """\
#!/bin/bash
set -vexubE -o pipefail
%s
""" % '\n'.join(cmds)
|
def create_8021Q_vea_cmd(lpar_id, slotnum, port_vlan_id, addl_vlan_ids):
"""
Generate IVM command to create 8021Q virtual ethernet adapter.
:param lpar_id: LPAR id
:param slotnum: virtual adapter slot number
:param port_vlan_id: untagged port vlan id
:param addl_vlan_ids: tagged VLAN id list
:returns: A HMC command that can create 8021Q veth based on the
specification from input.
"""
vids = [] if not addl_vlan_ids else addl_vlan_ids
cmd = ('chhwres -r virtualio --rsubtype eth -o a -s %(slot)s '
'--id %(lparid)s -a ieee_virtual_eth=1,'
'port_vlan_id=%(pvid)s,is_trunk=1,'
'trunk_priority=1,\\\"addl_vlan_ids=%(addlvids)s\\\"' %
{'slot': slotnum,
'lparid': lpar_id,
'pvid': port_vlan_id,
'addlvids': ",".join(str(x) for x in vids)})
return cmd
|
def pluralized(word):
"""
Get the plural of the given word. Contains a dictionary for non-standard
plural forms. If the word ends in one of 5 known endings, appends an 'es'
to the end. By default, just appends an 's' to the given word.
@param word: the word to pluralize
@return: the plural form of the noun
"""
defined_plurals = {"person": "people"}
if word in defined_plurals:
return defined_plurals[word]
es_endings = ["s", "sh", "ch", "x", "z"]
if any([word.endswith(ending) for ending in es_endings]):
return f"{word}es"
else:
return f"{word}s"
|
def is_class_or_instance(obj, cls):
"""returns True is obj is an instance of cls or is cls itself"""
return isinstance(obj, cls) or obj is cls
|
def camel_to_snake(name: str) -> str:
"""Convert CamelCase to snake_case, handling acronyms properly."""
out = name[0].lower()
for c0, c1, c2 in zip(name[:-2], name[1:-1], name[2:]):
# Catch lower->upper transitions.
if not c0.isupper() and c1.isupper():
out += "_"
# Catch acronym endings.
if c0.isupper() and c1.isupper() and c2.islower():
out += "_"
out += c1.lower()
out += name[-1].lower()
return out
|
def needs_update(version, upstream):
"""
Do a dumb comparison to determine if the version needs to be updated.
"""
if "+git" in version:
# strip +git and see if this is a post-release snapshot
version = version.replace("+git", "")
return version != upstream
|
def unpack_numpy(var, count, dtype, buff):
"""
create numpy deserialization code
"""
return var + " = numpy.frombuffer(%s, dtype=%s, count=%s)"%(buff, dtype, count)
|
def print_formatted_2(output):
"""
textual output of mecules in 3 |-separated field per line (and per molecule).
molecule id | list of atom indexes | list of chemical shifts in the same order as in the list of atom indexes
"""
output_formatted = ""
for (molid, curmol) in output:
atomids = ' '.join([str(curatom[0]+1) for curatom in curmol])
chemshifts = ' '.join(["%.2f" % (curatom[1],) for curatom in curmol])
# print(" | ".join([str(molid+1), atomids, chemshifts]))
output_formatted += (" | ".join([str(molid+1), atomids, chemshifts]) + '\n')
return output_formatted
|
def remove_blank_chars(text):
"""
(str) -> str
Removes superfluous blank characters from text, leaving at most
a single space behind where there was more than one (space or newline)
>>> remove_blank_chars('Happy \n \n Birthday')
"Happy Birthday"
:param text: text from which to remove superfluous blanks
:returns: text with superfluous blanks removed
"""
text = text.replace('\n', ' ')
while ' ' in text:
text = text.replace(' ', ' ')
return text
|
def format_line(line):
"""format list into a csv line"""
return ",".join(line)
|
def _test(language, test_language=None):
"""Test language."""
return test_language is None or test_language == '*' or language == test_language
|
def select(subject, result_if_one, result_if_zero):
# type: (int, int, int) -> int
"""Perform a constant time(-ish) branch operation"""
return (~(subject - 1) & result_if_one) | ((subject - 1) & result_if_zero)
|
def truncate(n: float, decimals: int = 0) -> float:
"""
Support function to truncate any float value to a specified decimal points
"""
multiplier = 10 ** decimals
return int(n * multiplier) / multiplier
|
def preprocess_for_cse(expr, optimizations):
""" Preprocess an expression to optimize for common subexpression
elimination.
Parameters
==========
expr : sympy expression
The target expression to optimize.
optimizations : list of (callable, callable) pairs
The (preprocessor, postprocessor) pairs.
Returns
=======
expr : sympy expression
The transformed expression.
"""
for pre, post in optimizations:
if pre is not None:
expr = pre(expr)
return expr
|
def unquote_to_bytes(string):
"""unquote_to_bytes('abc%20def') -> b'abc def'."""
# Note: strings are encoded as UTF-8. This is only an issue if it contains
# unescaped non-ASCII characters, which URIs should not.
if isinstance(string, str):
string = string.encode('utf-8')
res = string.split(b'%')
res[0] = res[0]
for i in range(1, len(res)):
item = res[i]
try:
res[i] = bytes([int(item[:2], 16)]) + item[2:]
except ValueError:
res[i] = b'%' + item
return b''.join(res)
|
def check_x_path(current, end, state):
"""Tells the robot to change spaces on the x axis."""
change = False
if current[1] > end[1] and state[current[0]][current[1] - 1].get() == 0:
current[1] -= 1
change = True
elif current[1] < end[1] and state[current[0]][current[1] + 1].get() == 0:
current[1] += 1
change = True
return current, change
|
def format_price(price):
"""Format price with two decimal places."""
return f"${price:.2f}"
|
def strtobool(val: str) -> bool:
"""Convert a string representation of truth to True or False.
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
if not isinstance(val, str):
raise TypeError(f"{val} is not a str")
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return True
elif val in ("n", "no", "f", "false", "off", "0"):
return False
else:
raise ValueError("invalid truth value %r" % (val,))
|
def ternary_search(func, lo, hi, abs_prec=1e-7):
""" Find maximum of unimodal function func() within [lo, hi] """
while abs(hi - lo) > abs_prec:
lo_third = lo + (hi - lo) / 3
hi_third = hi - (hi - lo) / 3
if func(lo_third) < func(hi_third):
lo = lo_third
else:
hi = hi_third
return (lo + hi) / 2
|
def escape_underscores(s):
"""
escape underscores with back slashes
separate function to keep f strings
from getting too long
:param s: a string
:return: s with underscores prefixed with back slashes
"""
return s.replace("_", "\_")
|
def select_pred_files(model_fn,curr_ana_l):
"""
Get all files related to a particular analysis
Parameters
----------
model_fn : list
all files in a particular analysis folder
curr_ana_l : list
name of model we are going to analyze
Returns
-------
list
files that are required for a particular analysis
"""
files_ana = []
for f in model_fn:
f_split = f.replace(".csv","").split("_")
analyze = True
for temp_c in curr_ana_l:
if temp_c not in f_split: analyze = False
if analyze:
if "preds" in f_split and len(f_split) - len(curr_ana_l) == 1:
files_ana.append(f)
if "train" in f_split and len(f_split) - len(curr_ana_l) == 2:
files_ana.append(f)
return(files_ana)
|
def get_techniques_of_tactic(tactic, techniques):
"""Given a tactic and a full list of techniques, return techniques that
appear inside of tactic
"""
techniques_list = []
for technique in techniques:
for phase in technique['kill_chain_phases']:
if phase['phase_name'] == tactic['x_mitre_shortname']:
techniques_list.append(technique)
techniques_list = sorted(techniques_list, key=lambda k: k['name'].lower())
return techniques_list
|
def copy_peps_tensors(peps):
"""
Create a copy of the PEPS tensors
"""
cp = []
for x in range(len(peps)):
tmp = []
for y in range(len(peps[0])):
tmp += [peps[x][y].copy()]
cp += [tmp]
return cp
|
def is_list(obj: object):
"""Returns true if object is a list. Principle use is to determine if a
field has undergone validation: unvalidated field.errors is a tuple,
validated field.errors is a list."""
return isinstance(obj, list)
|
def _to_value_seq(values):
"""
:param values: Either a single numeric value or a sequence of numeric values
:return: A sequence, possibly of length one, of all the values in ``values``
"""
try:
val = float(values)
return [val,]
except (ValueError, TypeError):
return values
|
def SplitLines( contents ):
"""Return a list of each of the lines in the unicode string |contents|."""
# We often want to get a list representation of a buffer such that we can
# index all of the 'lines' within it. Python provides str.splitlines for this
# purpose. However, this method not only splits on newline characters (\n,
# \r\n, and \r) but also on line boundaries like \v and \f. Since old
# Macintosh newlines (\r) are obsolete and Windows newlines (\r\n) end with a
# \n character, we can ignore carriage return characters (\r) and only split
# on \n.
return contents.split( '\n' )
|
def compute_Cp(T,Cv,V,B0,beta):
"""
This function computes the isobaric heat capacity from the equation:
:math:`Cp - Cv = T V beta^2 B0`
where *Cp,Cv* are the isobaric and isocoric heat capacities respectively,
*T* is the temperature, *V* the unit cell volume, *beta* the volumetric
thermal expansion and *B0* the isothermal bulk modulus.
"""
Cp = Cv + T * V * beta * beta * B0
return Cp
|
def convert_to_pronoun(day):
"""Take input "day" as a datatype integer, and convert to datatype string"""
if day == 0:
return "Monday"
if day == 1:
return "Tuesday"
if day == 2:
return "Wednesday"
if day == 3:
return "Thursday"
if day == 4:
return "Friday"
if day == 5:
return "Saturday"
if day == 6:
return "Sunday"
|
def isint(a):
"""
Test for integer.
"""
return(type(a) == int)
|
def parser_preferred_name_list_Descriptor(data,i,length,end):
"""\
parser_preferred_name_list_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "preferred_name_list", "contents" : unparsed_descriptor_contents }
(Defined in ETSI EN 300 468 specification)
"""
return { "type" : "preferred_name_list", "contents" : data[i+2:end] }
|
def divisors(n, with_1_and_n=False):
"""
https://stackoverflow.com/questions/171765/what-is-the-best-way-to-get-all-the-divisors-of-a-number#171784
"""
# Get factors and their counts
factors = {}
nn = n
i = 2
while i*i <= nn:
while nn % i == 0:
if i not in factors:
factors[i] = 0
factors[i] += 1
nn //= i
i += 1
if nn > 1:
factors[nn] = 1
primes = list(factors.keys())
# Generates factors from primes[k:] subset
def generate(k):
if k == len(primes):
yield 1
else:
rest = generate(k+1)
prime = primes[k]
for _factor in rest:
prime_to_i = 1
# Prime_to_i iterates prime**o values, o being all possible exponents
for _ in range(factors[prime] + 1):
yield _factor * prime_to_i
prime_to_i *= prime
if with_1_and_n:
return list(generate(0))
else:
return list(generate(0))[1:-1]
|
def build_type_define(build_type=None):
"""
returns definitions specific to the build type (Debug, Release, etc.)
like DEBUG, _DEBUG, NDEBUG
"""
return 'NDEBUG' if build_type in ['Release', 'RelWithDebInfo', 'MinSizeRel'] else ""
|
def parse_file_path(file_path):
"""Extract file metadata from its path."""
file_name = file_path.split('/')[-1]
name_components = file_name.split('.')
sample_name = name_components[0]
result_type = name_components[1]
file_type = name_components[2]
return sample_name, result_type, file_type
|
def get_joints_time(controller_joints, time):
""" Converte a single time to an array of time """
if isinstance(time, (int, float)):
times = {}
for key in controller_joints:
times[key] = time
else:
times = time
return times
|
def order_validation(order):
"""
Validate the order. If it's under 2 then raise a ValueError
"""
if order < 2:
raise ValueError("An order lower than two is not allowed.")
else:
return order
|
def get_sid_set(sources):
"""
Compile all the SID's which appear inside the Chemical Vendors or Legacy
Depositors entries in a pubchem JSON file. From my current understanding
SID is a unique entry that identifies a product+manufacturer. There should
be no duplicates. Therefore we assert that this is the case.
"""
sid_list = []
for source_dict in sources:
sid = source_dict['SID']
sid_list.append(sid)
sid_set = set(sid_list)
assert len(sid_set) == len(sid_set), "Duplicate SID detected"
return sid_set
|
def get_num_den_accs(acc_time_str):
"""
Get num and den for accumulation period.
Parameters
----------
acc_time_str : str
accumulation time (e.g. "1/3").
Returns
-------
num : int
numerator of the fraction.
den : int
denominator of the fraction.
Notes
-----
|
| **TO DO:**
|
| Consider removing along with get_acc_float(), initially devised to support fractions as integration times.
"""
num=1
den=1
acc_split=acc_time_str.split("/")
if len(acc_split)>1:
den=int(acc_split[1])
else:
num=int(acc_split[0])
return([num,den])
|
def build_evaluation_from_config_item(configuration_item, compliance_type, annotation=None):
"""Form an evaluation as a dictionary. Usually suited to report on configuration change rules.
Keyword arguments:
configuration_item -- the configurationItem dictionary in the invokingEvent
compliance_type -- either COMPLIANT, NON_COMPLIANT or NOT_APPLICABLE
annotation -- an annotation to be added to the evaluation (default None)
"""
eval_ci = {}
if annotation:
eval_ci['Annotation'] = annotation
eval_ci['ComplianceResourceType'] = configuration_item['resourceType']
eval_ci['ComplianceResourceId'] = configuration_item['resourceId']
eval_ci['ComplianceType'] = compliance_type
eval_ci['OrderingTimestamp'] = configuration_item['configurationItemCaptureTime']
return eval_ci
|
def listdir_matches(match):
"""Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash.
"""
import os
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
match_prefix = match
result_prefix = ''
else:
match_prefix = match[last_slash + 1:]
if last_slash == 0:
dirname = '/'
result_prefix = '/'
else:
dirname = match[0:last_slash]
result_prefix = dirname + '/'
def add_suffix_if_dir(filename):
try:
if (os.stat(filename)[0] & 0x4000) != 0:
return filename + '/'
except FileNotFoundError:
# This can happen when a symlink points to a non-existant file.
pass
return filename
matches = [add_suffix_if_dir(result_prefix + filename)
for filename in os.listdir(dirname) if filename.startswith(match_prefix)]
return matches
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.