content stringlengths 42 6.51k |
|---|
def cond_probs(obs):
"""
Computes a discrete conditional probability distribution from two lists of observations.
:param obs:
An ordered list of observations.
:return:
Dict: A discrete conditional probability distribution, represented as a dictionary.
"""
if type(obs) is str:
obs = list(obs)
obs = [str(ob) for ob in obs]
syms = set(obs)
counts = {}
probs_dict = {}
totals = {}
for sym in syms:
totals[sym] = obs.count(sym)
counts[sym] = {}
probs_dict[sym] = {}
for other_sym in syms:
counts[sym][other_sym] = 0
probs_dict[sym][other_sym] = 0
for i in range(len(obs) - 1):
if obs[i + 1] in counts[obs[i]]:
counts[obs[i]][obs[i + 1]] += 1
continue
counts[obs[i]][obs[i + 1]] = 1
for sym in syms:
div = 1 if totals[sym] is 0 else totals[sym]
for other_sym in syms:
probs_dict[sym][other_sym] = counts[sym][other_sym] / float(div)
return probs_dict |
def count_circle_lattice_points(cx: int, cy: int, r: int, k: int) -> int:
"""
count up integer point (x, y) in the circle
centered at (cx, cy) with radius r.
and both x and y are multiple of k.
"""
assert r >= 0 and k >= 0
cx %= k
cy %= k
def is_ok(dx: int, dy: int) -> bool:
return dx * dx + dy * dy <= r * r
def count_right(cx: int, cy: int, x0: int) -> int:
assert x0 == 0 or x0 == k
y0, y1 = 0, 1
count = 0
for x in range((cx + r) // k * k, x0 - 1, -k):
while is_ok(x - cx, y0 * k - cy):
y0 -= 1
while is_ok(x - cx, y1 * k - cy):
y1 += 1
count += y1 - y0 - 1
return count
return count_right(cx, cy, k) + count_right(-cx, cy, 0) |
def substitute_ascii_equivalents(text_unicode):
# Method taken from: http://code.activestate.com/recipes/251871/
"""
This takes a UNICODE string and replaces Latin-1 characters with something
equivalent in 7-bit ASCII. It returns a plain ASCII string. This function
makes a best effort to convert Latin-1 characters into ASCII equivalents.
It does not just strip out the Latin-1 characters. All characters in the
standard 7-bit ASCII range are preserved. In the 8th bit range all the
Latin-1 accented letters are converted to unaccented equivalents. Most
symbol characters are converted to something meaningful. Anything not
converted is deleted.
"""
char_mapping = {
0xc0: 'A', 0xc1: 'A', 0xc2: 'A', 0xc3: 'A', 0xc4: 'A', 0xc5: 'A',
0xc6: 'Ae', 0xc7: 'C',
0xc8: 'E', 0xc9: 'E', 0xca: 'E', 0xcb: 'E',
0xcc: 'I', 0xcd: 'I', 0xce: 'I', 0xcf: 'I',
0xd0: 'Th', 0xd1: 'N',
0xd2: 'O', 0xd3: 'O', 0xd4: 'O', 0xd5: 'O', 0xd6: 'O', 0xd8: 'O',
0xd9: 'U', 0xda: 'U', 0xdb: 'U', 0xdc: 'U',
0xdd: 'Y', 0xde: 'th', 0xdf: 'ss',
0xe0: 'a', 0xe1: 'a', 0xe2: 'a', 0xe3: 'a', 0xe4: 'a', 0xe5: 'a',
0xe6: 'ae', 0xe7: 'c',
0xe8: 'e', 0xe9: 'e', 0xea: 'e', 0xeb: 'e',
0xec: 'i', 0xed: 'i', 0xee: 'i', 0xef: 'i',
0xf0: 'th', 0xf1: 'n',
0xf2: 'o', 0xf3: 'o', 0xf4: 'o', 0xf5: 'o', 0xf6: 'o', 0xf8: 'o',
0xf9: 'u', 0xfa: 'u', 0xfb: 'u', 0xfc: 'u',
0xfd: 'y', 0xfe: 'th', 0xff: 'y',
#0xa1: '!', 0xa2: '{cent}', 0xa3: '{pound}', 0xa4: '{currency}',
#0xa5: '{yen}', 0xa6: '|', 0xa7: '{section}', 0xa8: '{umlaut}',
#0xa9: '{C}', 0xaa: '{^a}', 0xab: '<<', 0xac: '{not}',
#0xad: '-', 0xae: '{R}', 0xaf: '_', 0xb0: '{degrees}',
#0xb1: '{+/-}', 0xb2: '{^2}', 0xb3: '{^3}', 0xb4:"'",
#0xb5: '{micro}', 0xb6: '{paragraph}', 0xb7: '*', 0xb8: '{cedilla}',
#0xb9: '{^1}', 0xba: '{^o}', 0xbb: '>>',
#0xbc: '{1/4}', 0xbd: '{1/2}', 0xbe: '{3/4}', 0xbf: '?',
#0xd7: '*', 0xf7: '/'
}
r = ''
for char in text_unicode:
if ord(char) in char_mapping:
r += char_mapping[ord(char)]
elif ord(char) >= 0x80:
pass
else:
r += str(char)
return r |
def c2f(t):
"""
Converts Celsius Temperature to Fahrenheit Temperature.
"""
return t * float(1.8000) + float(32.00) |
def remove_empty(data):
"""Removes empty items from list"""
out = []
for item in data:
if item == '':
continue
out.append(item)
return out |
def get_name_by_index(index, labels):
"""get name with acv for index
Args:
index ([int]): [index/labelcode]
labels ([dict]): [labels]
Returns:
[String]: [name (acv)]
"""
name = ""
acv = ""
for x in labels:
if (x.get('labelcode')==index):
name = x.get('name')
acv = x.get('acv')
if (name==""):
print(f"no matching name for {index}")
return "X"
else:
return (name + " (" + acv + ")") |
def asint(value):
"""Coerce to integer."""
if value is None:
return value
return int(value) |
def fib(n):
""" Calculate the nth digit of Fibonacci
0 1 1 2 3 5 8 13 21 34 ... """
a, b = 0, 1
for i in range(n - 1):
a, b = b, a + b
return a |
def count_classifier(words, pos, neg):
"""
Count the positive or negative words in the sentence
return the label
"""
score = 0
for word in words:
if word + ' ' in pos:
score += 1
elif word + ' ' in neg:
score -= 1
return score |
def format(msg, leftmargin=0, rightmargin=78):
"""Format a message by inserting line breaks at appropriate places.
msg is the text of the message.
leftmargin is the position of the left margin.
rightmargin is the position of the right margin.
Return the formatted message.
"""
curs = leftmargin
fmsg = " " * leftmargin
for w in msg.split():
l = len(w)
if curs != leftmargin and curs + l > rightmargin:
fmsg = fmsg + "\n" + (" " * leftmargin)
curs = leftmargin
if curs > leftmargin:
fmsg = fmsg + " "
curs = curs + 1
fmsg = fmsg + w
curs = curs + l
return fmsg |
def denseFeature(feat):
"""
create dictionary for dense feature
:param feat: dense feature name
:return:
"""
return {'feat_name': feat} |
def is_nan(value):
"""
Checks if value is 'nan' or NaT
Parameters
---------
value: object
The object to be checked that it is not nan
Returns
---------
isnan: Boolean
True: nan
False: not nan
"""
isnan = str(value).lower() == 'nan'
isnat = str(value).lower() == 'nat'
return isnan or isnat |
def sentence_to_token_ids(sentence, word2id):
""" Gets token id's of each word in the sentence and returns a list of
those words. Is called by data_to_token_ids and the Lexer.
Args:
sentence: A list of word tokens.
word2id: A dictionary that maps words to its given id. This can
be for the input or target vocabulary.
"""
tokenized_sentence = []
for word in sentence:
tokenized_sentence.append(str(word2id[word]))
return tokenized_sentence |
def song_decoder(song):
"""Return decoded song string"""
return ' '.join((song.replace("WUB"," ").strip()).split()) |
def cxSet(ind1, ind2):
"""Apply a crossover operation on input sets. The first child is the
intersection of the two sets, the second child is the difference of the
two sets.
"""
temp = set(ind1) # Used in order to keep type
ind1 &= ind2 # Intersection (inplace)
ind2 ^= temp # Symmetric Difference (inplace)
return ind1, ind2 |
def floor(value, size, offset=200):
"""Floor of `value` given `size` and `offset`.
The floor function is best understood with a diagram of the number line::
-200 -100 0 100 200
<--|--x--|-----|--y--|--z--|-->
The number line shown has offset 200 denoted by the left-hand tick mark at
-200 and size 100 denoted by the tick marks at -100, 0, 100, and 200. The
floor of a value is the left-hand tick mark of the range where it lies. So
for the points show above: ``floor(x)`` is -200, ``floor(y)`` is 0, and
``floor(z)`` is 100.
>>> floor(10, 100)
0.0
>>> floor(120, 100)
100.0
>>> floor(-10, 100)
-100.0
>>> floor(-150, 100)
-200.0
>>> floor(50, 167)
-33.0
"""
return float(((value + offset) // size) * size - offset) |
def allclose(a, b, tol=1e-7):
"""Are all elements of a vector close to one another"""
return all([abs(ai - bi) < tol for ai, bi in zip(a,b)]) |
def bounding_box(*boxes):
"""Compute a bounding box around other boxes."""
x0, y0, x1, y1 = boxes[0]
for bx0, by0, bx1, by1 in boxes[1:]:
x0 = min(x0, bx0)
y0 = min(y0, by0)
x1 = max(x1, bx1)
y1 = max(y1, by1)
return x0, y0, x1, y1 |
def get_count(results):
"""Creates a dictionary, word being the key, and word count being the value"""
counts_dict = dict()
for word in results:
counts_dict[word] = counts_dict.get(word, 0) + 1
return counts_dict |
def extractIniParam(iniparams, inStr):
""" if inStr starts with $ then we return matching param from the ini
params, otherwise return taskval
Params:
iniparams - the map of parameters derived from the ini file
inStr - input string
"""
taskval = inStr
if inStr.startswith('$'):
#find the param
# note that this has been pre-validated, so we should not ever
# actually fail to find the key
param = inStr[1:]
if param in iniparams:
taskval = iniparams[param]
if taskval == "":
taskval = None
return taskval |
def get_csv_table(column_store, separator=";"):
"""Return a csv table from a column-store."""
csv_table = ""
for idx in range(len(column_store[0])):
columns = (column[idx] for column in column_store)
csv_table += separator.join(columns) + "\n"
return csv_table |
def cmdline_for_pid(pid):
"""Get the commandline arguments list for a given pid.
Potentially returns None if the process doesn't exist anymore."""
try:
with open('/proc/%s/cmdline' % pid, 'rb') as f:
return f.read().split(b'\0')
except EnvironmentError:
# process already terminated, or can't access cmdline
return None |
def index_to_name(index):
"""Construct the full name for the node given its path."""
if index:
return '.'.join(index)
return 'everything' |
def _xyz_vec2str(x):
"""Convert a vector to string.
"""
return "\t".join([str(i) for i in x]) |
def next_up(v, seq):
"""
Return the first item in seq that is > v.
"""
for s in seq:
if s > v:
return s
return v |
def parse_number(n) :
"""Try to cast intput first to float, then int, returning unchanged if both fail"""
try :
return float(n) if '.' in n else int(n)
except :
return n |
def get_FY_sel(ef1, sf1, ef2, sf2, fy):
"""
NB have changed so it compares end of season and start of season,
not start of consecutive seasons.
This is because sexual reproduction can cause a change that wasn't due
to the tactic but was just down to ratios starting away from those expected
in a perfectly mixed population.
"""
fy = int(fy)
if not fy > 1:
return None
sr1 = ef1/sf1
sr2 = ef2/sf2
try:
return sr1/(sr1+sr2)
except Exception as e:
print(f"find_FY_sel warning/error: {e} \n srs={(sr1,sr2)}")
return None |
def bgTiret(r, ra, b0, bi):
"""
Generalized Tiret et al. 2007 anisotropy profile.
Parameters
----------
r : array_like, float
Distance from center of the system.
ra : float
Anisotropy radius.
b0 : float
Anisotropy at r = 0.
bi : float
Anisotropy at r -> Infinity.
Returns
-------
b : array_like, float
Anisotropy profile.
"""
b = b0 + (bi - b0) / (1 + (ra / r))
return b |
def gcd(a, b):
"""
a, b: two positive integers
Returns the greatest common divisor of a and b
"""
#YOUR CODE HERE
if b == 0:
return a
else:
return gcd(b, a % b) |
def unescape(s):
"""Unescape &, <, and > in a string of data.
"""
if '&' not in s:
return s
return s.replace('>', '>').replace('<', '<').replace('&', '&') |
def convert_tag(tag):
"""Convert the tag given by nltk.pos_tag to the tag used by wordnet.synsets"""
tag_dict = {'N': 'n', 'J': 'a', 'R': 'r', 'V': 'v'}
try:
return tag_dict[tag[0]]
except KeyError:
return None |
def add_blank_lines(player_data_list):
"""Add blank lines that will store differences.
Args:
player_data_list: player data list
Returns:
player data list with blank rows for differences
"""
length_appended = max([len(row) for row in player_data_list])
player_data_list = player_data_list + [[''] * length_appended]
upper_bound = len(player_data_list) - 1
row = 0
while row < upper_bound:
if ((player_data_list[row][0] != '') & (player_data_list[row + 1][0] != '') & (player_data_list[row][-1] != player_data_list[row + 1][-1])):
player_data_list = player_data_list[:row + 1] + [[''] * length_appended] + player_data_list[row + 1:]
upper_bound += 1
row += 1
return player_data_list |
def _remove_empty_line(line):
"""function _remove_empty_line
Args:
line:
Returns:
"""
return True if line.strip() == "" else False |
def coq_axiom(name, type):
"""Coq axiom
Arguments:
- `name`: name of the axiom
- `type`: type of the axiom
"""
return "Axiom {0!s} : {1!s}.\n".format(name, type) |
def remove_call_brackets(call: str):
"""Return the given string with the trailing `()` removed, if present.
NOTE Made redundant by `str.removesuffix("()")` in Python 3.9+
"""
if call.endswith("()"):
return call[:-2]
return call |
def rescale(inlist, newrange=(0, 1)):
"""
rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum)
"""
OldMax = max(inlist)
OldMin = min(inlist)
if OldMin == OldMax:
raise RuntimeError('list contains of only one unique value')
OldRange = OldMax - OldMin
NewRange = newrange[1] - newrange[0]
result = [(((float(x) - OldMin) * NewRange) / OldRange) + newrange[0] for x in inlist]
return result |
def _normalize_percent_rgb(value: str) -> str:
"""
Internal normalization function for clipping percent values into
the permitted range (0%-100%, inclusive).
"""
value = value.split("%")[0]
percent = float(value) if "." in value else int(value)
return "0%" if percent < 0 else "100%" if percent > 100 else "{}%".format(percent) |
def is_prime(n: int) -> bool:
""" Simple function to check if a given number n is prime or not
Parameters
----------
n: int
number that will be checked if it is prime or not
Returns
-------
bool: True if the given number (n) is prime, False if it is not
"""
while True:
if n <= 1: # prime numbers are greater than 1
prime, i = False, 1
else:
for i in range(2, n): # Iterate from 2 to n / 2
# If n is divisible by any number between 2 and n / 2,
# it is not prime
if n % i == 0:
prime = False
break
else:
prime, i = True, 0
if prime is not None:
break
print(
f"'{n}' is a prime number" if prime
else f"'{n}' is not a prime number, it is divisible by {i}",
)
return prime |
def getFilenameFromDetails(details):
"""Takes a dictionary of details and makes a machine readible filename
out of it. Angle comes in radians."""
filename = "{}_{:.3f}keV_{:.2f}ze_{:.2f}az".format(details['base'],
details['keV'],
details['ze'],
details['az'])
return filename |
def to_ascii_hex(value: int, digits: int) -> str:
"""Converts an int value to ASCII hex, as used by LifeSOS.
Unlike regular hex, it uses the first 6 characters that follow
numerics on the ASCII table instead of A - F."""
if digits < 1:
return ''
text = ''
for _ in range(0, digits):
text = chr(ord('0') + (value % 0x10)) + text
value //= 0x10
return text |
def is_three_doubles(word):
"""check if a word have three consecutive double letters."""
if word is None or len(word) < 6:
return False
consecutives = 0
index = 0
while index < len(word) - 1:
if word[index+1] == word[index]:
consecutives += 1
if consecutives == 3:
return True
index += 2
else:
consecutives = 0
index += 1
return False |
def get_response_tokens_from_object(_object):
"""Get response tokens from response payload"""
if not _object:
return []
options = _object.options or []
return [option.response_tokens for option in options if option.response_tokens] |
def longest_increasing_subsequence_by_one(a):
"""
Solution:
memo[i] stores the length of the longest subsequence which ends with a[i].
For every i, if a[i] - 1 is present in the array before the ith element,
then a[i] will add to the increasing subsequence which has a[i] - 1.
"""
index_of = {}
memo = [0 for _ in a]
for i, el in enumerate(a):
index_of[el] = i
try:
memo[i] = memo[index_of[el - 1]] + 1
except KeyError:
memo[i] = 1
return max(memo) |
def create_commit_map(resolved_sbom):
"""
Arrange packages by repository ( main, community )
Exclude sub-packages, since they share APKBUILD
"""
packages_commit = {}
if 'dependencies' in resolved_sbom:
i = 0
for package in resolved_sbom['dependencies']:
parent = package['pipeline']['aggregator']['alpine']['parent']
repo = package['pipeline']['aggregator']['alpine']['repo']
ID = package['ID']
entry = {}
entry['ID'] = ID
entry['index'] = i
product = package['pipeline']['product']
entry['package'] = product
if parent == product:
if repo not in packages_commit:
packages_commit[repo] = []
packages_commit[repo].append(entry)
else:
packages_commit[repo].append(entry)
i = i + 1
if 'metadata' in resolved_sbom:
for repo in resolved_sbom['metadata']['aggregator']['alpine']['aports']['repo']:
if repo in packages_commit:
resolved_sbom['metadata']['aggregator']['alpine']['aports']['repo'][repo]['source'] = packages_commit[repo]
return resolved_sbom |
def frames_to_time_code(frames: int, fps: int) -> str:
"""
Function converts frames to time code `00:00:00:00` format
:param frames: number of total frames
:type frames: int
:param fps: frames per second
:type fps: int
:return: time code format
:rtype: str
"""
sec_in_min = 60
fra_in_min = sec_in_min * fps
fra_in_hrs = sec_in_min * fra_in_min
hrs = int(frames / fra_in_hrs)
min = int(frames / fra_in_min) % sec_in_min
sec = int((frames % fra_in_min) / fps)
fra = int((frames % fra_in_min) % fps)
time_code = str("%02d:%02d:%02d:%02d" % (hrs, min, sec, fra))
return time_code |
def divide_set(rows, column, value):
"""
:param rows:
:param column:
:param value:
:return:
"""
# for numerical values
if isinstance(value, int) or isinstance(value, float):
split_function = lambda row: row[column] >= value
# for nominal values
else:
split_function = lambda row: row[column] == value
# Divide the rows into two sets and return them
set1 = [row for row in rows if split_function(row)] # if split_function(row)
set2 = [row for row in rows if not split_function(row)]
return set1, set2 |
def convert_mug_to_cup(value):
"""Helper function to convert a string from mug to cup"""
if isinstance(value, str) and value.lower() == 'mug':
return 'cup'
else:
return value |
def front(inlist):
"""
Pop from a list or tuple, otherwise return untouched.
Examples
--------
>>> front([1, 0])
1
>>> front("/path/somewhere")
'/path/somewhere'
"""
if isinstance(inlist, (list, tuple)):
return inlist[0]
return inlist |
def encode_str(str):
"""Encode the string."""
str = str.replace('\r\n', ' ')
str = str.replace('\n', ' ')
str = str.replace('\r', ' ')
str = str.replace('\\', '\\\\')
str = str.replace('"', '\\"')
str = '"' + str + '"'
return str |
def get_username_list(cmdline_username, config):
"""Get a list of possible usernames.
Usernames are select from the command line and the config file.
"""
usernames = []
if cmdline_username:
usernames = [cmdline_username]
else:
username = config.get('default-username')
if username:
usernames = username.strip().split()
return usernames |
def ms_to_kmh(value):
"""
# Convert m/s to km/h
"""
return value * 3.6 if value is not None else None |
def get_mode_two_initial_mw(t2, min_loading, current_mode_time):
"""
Get initial MW when unit is in mode two and on fixed startup trajectory
Note: InitialMW is based on trader's position within the fixed startup
trajectory for fast-start units. This may differ from the InitialMW
value reported by SCADA telemetry.
"""
return (min_loading / t2) * current_mode_time |
def get_both_list(toLoggedInUser, fromLoggedInUser):
"""
This function takes the list of messages to and from the logged in user and organises them.
The function takes two sorted lists and merges them in approximately O(n). This is done to
ensure that messages are kept in order.
"""
bothList = []
j = 0
i = 0
smallerList = []
largerList = []
if len(toLoggedInUser) > len(fromLoggedInUser): #Determine which list is smaller
smallerList = fromLoggedInUser
largerList = toLoggedInUser
else:
smallerList = toLoggedInUser
largerList = fromLoggedInUser
while i < (len(smallerList)) and j < (len(largerList)): #Merge
if float(smallerList[i][4]) < float(largerList[j][4]):
if (smallerList[i] not in bothList):
bothList.append(smallerList[i])
i += 1
else:
if (largerList[j] not in bothList):
bothList.append(largerList[j])
j += 1
if i < len(smallerList):
for k in range (i,len(smallerList)):
if (smallerList[k] not in bothList):
bothList.append(smallerList[k])
elif j < len (largerList):
for k in range (j,len(largerList)):
if (largerList[k] not in bothList):
bothList.append(largerList[k])
return bothList |
def matlabize(s):
"""Make string s suitable for use as a MATLAB function/script name"""
s = s.replace(' ', '_')
s = s.replace('.', '_')
s = s.replace('-', '_')
assert len(s) <= 63 # MATLAB function/script name length limitation
return s |
def atttyp(att: str) -> str:
"""
Helper function to return attribute type as string.
:param str: attribute type e.g. 'U002'
:return: type of attribute as string e.g. 'U'
:rtype: str
"""
return att[0:1] |
def get_eval_tags(trg, pred):
"""Compares the pred to the trg
Args:
- trg (list): the target sequence (either a list of words
or a list of tags S or C)
- pred (list): the predicted sequence (either a list of words
or a list of tags S or C)
Returns:
- tags (list): list of tags (G or B)
"""
tags = []
for i, trg_w in enumerate(trg):
if i > len(pred) - 1:
break
pred_w = pred[i]
if trg_w == pred_w:
tags.append('G')
else:
tags.append('B')
# penalize over or under generation
while len(tags) != len(trg):
tags.append('B')
return tags |
def pause_slicer(samp: int, width: int) -> slice:
"""Returns a slice object which satisfies the range of indexes for a pause
point.
The incoming numbers for samp are 1-based pixel numbers, so must
subtract 1 to get a list index.
The width values are the number of pixels to affect, including the
pause point pixel. If positive they start with the pause point pixel
and count 'up.' If negative, they start with the pause point pixel
and count 'down.'
"""
# We don't need to protect for indices less than zero or greater than the
# length of the list, because slice objects can take values that would not
# be valid for item access.
if width > 0:
s_start = samp - 1
s_stop = s_start + width
else:
s_start = samp + width
s_stop = samp
return slice(s_start, s_stop) |
def cast_int(value):
"""
Cast value to 32bit integer
Usage:
cast_int(1 << 31) == -1
(where as: 1 << 31 == 2147483648)
"""
value = value & 0xffffffff
if value & 0x80000000:
value = ~value + 1 & 0xffffffff
return -value
else:
return value |
def determine_angle_label(angle: str) -> str:
""" Determine the full angle label and return the corresponding latex.
Args:
angle: Angle to be used in the label.
Returns:
Full angle label.
"""
return_value = r"$\Delta"
# Need to lower because the label in the hist name is upper
angle = angle.lower()
if angle == "phi":
# "phi" -> "varphi"
angle = "var" + angle
return_value += r"\%s$" % (angle)
return return_value |
def nested(func, default=None):
"""
get a nested value if it exists, or return the given default if it doesn't
Arguments:
func(function):
A function with no arguments that returns the nested value
default:
the default value, in case the nested value does not exist
Returns:
the nested attribute(s) or the default value. For example:
For example:
.. code-block:: python
d = D(c=C(b=B(a=A(i=5))))
assert nested(lambda: d.c.b.a.i) == 5
d.c.foo = [1, 2, 3]
assert nested(lambda: d.c.foo[100]) is None
assert nested(lambda: d.c.foo[2]) == 3
"""
try:
return func()
except (AttributeError, TypeError, IndexError, KeyError):
return default |
def make_save_string(save_properties: list) -> str:
"""
:param save_properties: list of tuples containing (property, val)
:return: save string with underscores delimiting values and properties
"""
save_string = ""
return save_string.join([p + "_" + str(v) + "_" for p, v in save_properties]) |
def RSet(var, value):
"""Do a VB RSet
Right aligns a string within a string variable.
RSet stringvar = string
If stringvar is longer than string, RSet replaces any leftover characters
in stringvar with spaces, back to its beginning.
"""
return " " * (len(var) - len(value)) + value[:len(var)] |
def app_icon_url(*args, **kwargs):
"""Get the URL to the application icon."""
app_id = args[0]
return f"http://192.168.1.160:8060/query/icon/{app_id}" |
def set_to_bounds(i_s, i_e, j_s, j_e, low=0, high=1):
"""
Makes sure the given index values stay with the
bounds (low and high). This works only for 2 dimensional
square matrices where low and high are same in both
dimensions.
Arguments:
i_s : Starting value for row index
i_e : Ending value for row index
j_s : Starting value for column index
j_e : Ending value for column index
low : Minimum value for index possible
high : Maximum value for index possible
Returns:
Values within bounds for given index positions
"""
if i_s < low:
i_s = low
if i_e > high:
i_e = high
if j_s < low:
j_s = low
if j_e > high:
j_e = high
return i_s, i_e, j_s, j_e |
def update_bits(n, m, i, j):
"""
Update n with m at bit position from i to j
:param n: original number to be updated
:type n: int
:param m: number to update
:type m: int
:param i: beginning bit position
:type i: int
:param j: ending bit position
:type j: int
:return: updated number
:rtype: int
"""
# mask = left | right
# left = 1111...000...000
# right = 0000...000...111
if j < 31:
mask = (~0 << (j + 1)) | ((1 << i) - 1)
result = (n & mask) | (m << i)
else:
# integer of Python 3 is not 32-bit but infinity
# so to simulate as 32-bit, we need to check the 32th bit
# and compute the compliment
mask = (1 << i) - 1
result = (n & mask) | (m << i)
if (result >> 32) == 0:
result -= 1 << 32
return result |
def channel_name(channel_number: int) -> str:
"""Gets the channel name associated with a channel number, e.g. 'Channel_19'.
Parameters
----------
channel_number : int
Which channel to generate the name for.
Returns
-------
str
The name of the channel as a string.
"""
return f"Channel_{channel_number}" |
def try_except_pass(errors, func, *args, **kwargs):
"""
try to return FUNC with ARGS, pass on ERRORS
parameters
----------
errors
a single error, or a tuple of errors.
func
a function that takes args and kwargs
"""
try:
return func(*args, **kwargs)
except errors:
pass |
def _understand_err_col(colnames):
"""Get which column names are error columns
Examples
--------
>>> colnames = ['a', 'a_err', 'b', 'b_perr', 'b_nerr']
>>> serr, terr = _understand_err_col(colnames)
>>> np.allclose(serr, [1])
True
>>> np.allclose(terr, [2])
True
>>> serr, terr = _understand_err_col(['a', 'a_nerr'])
Traceback (most recent call last):
...
ValueError: Missing positive error...
>>> serr, terr = _understand_err_col(['a', 'a_perr'])
Traceback (most recent call last):
...
ValueError: Missing negative error...
"""
shift = 0
serr = []
terr = []
for i, col in enumerate(colnames):
if col.endswith("_err"):
# The previous column, but they're numbered from 1!
# Plus, take shift into account
serr.append(i - shift)
shift += 1
elif col.endswith("_perr"):
terr.append(i - shift)
if len(colnames) == i + 1 or not colnames[i + 1].endswith('_nerr'):
raise ValueError("Missing negative error")
shift += 2
elif col.endswith("_nerr") and not colnames[i - 1].endswith('_perr'):
raise ValueError("Missing positive error")
return serr, terr |
def check_refcond(n, h, k, l):
"""Check reflection condition *n* against h, k, l.
The condition number n is the same as in the PowderCell space-group file.
"""
if n == 0:
return True
elif n == 1:
return h % 2 == 0
elif n == 2:
return k % 2 == 0
elif n == 3:
return l % 2 == 0
elif n == 4:
return (k + l) % 2 == 0
elif n == 5:
return (h + l) % 2 == 0
elif n == 6:
return (h + k) % 2 == 0
elif n == 7:
return h % 2 == k % 2 == l % 2
elif n == 8:
return (k + l) % 4 == 0
elif n == 9:
return (h + l) % 4 == 0
elif n == 10:
return (h + k) % 4 == 0
elif n == 11:
return (2*h + l) % 2 == 0
elif n == 12:
return (2*h + l) % 4 == 0
elif n == 13:
return (h + k + l) % 2 == 0
elif n == 14:
return (-h + k + l) % 3 == 0
elif n == 15:
return (h - k + l) % 3 == 0
elif n == 16:
return h % 4 == 0
elif n == 17:
return k % 4 == 0
elif n == 18:
return l % 3 == 0
elif n == 19:
return l % 4 == 0
elif n == 20:
return l % 6 == 0
elif n == 21:
return abs(h) >= abs(k) >= abs(l)
elif n == 22:
return (2*h + k) % 2 == 0
elif n == 23:
return (2*h + k) % 4 == 0
elif n == 24:
return (h + 2*k) % 2 == 0
elif n == 25:
return (h + 2*k) % 4 == 0
elif n == 26:
return h % 2 == 0 and k % 2 == 0
elif n == 27:
return k % 2 == 0 and l % 2 == 0
elif n == 28:
return h % 2 == 0 and l % 2 == 0
elif n == 29:
return (k + l) % 4 == 0 and k % 2 == 0 and l % 2 == 0
elif n == 30:
return (h + l) % 4 == 0 and h % 2 == 0 and l % 2 == 0
elif n == 31:
return (h + k) % 4 == 0 and h % 2 == 0 and k % 2 == 0
else:
assert False, 'invalid condition number' |
def brie_mixing(Kliquid, Kgas, Sliquid, Sgas, brie_exp=3.0):
"""
Brie mixing of liquid and gas phases for pore filling fluids
"""
Kbrie = (Kliquid - Kgas)*(1.0-Sgas)**brie_exp + Kgas
return Kbrie |
def geopotential_to_geometric(h, r0):
"""Converts from given geopotential altitude to geometric one.
Parameters
----------
h: float
Geopotential altitude.
r0: float
Planet/Natural satellite radius.
Returns
-------
z: float
Geometric altitude.
"""
z = r0 * h / (r0 - h)
return z |
def mean(num_lst):
"""
This function calculates the average of a list of numbers
Parameters
-------------
num_lst : list
List of numbers to calculate the average of
Returns
-------------
The average/mean of num_lst
Examples
--------------
>>> mean([1, 2, 3, 4, 5])
3.0
"""
return sum(num_lst) / len(num_lst) |
def remove_margin_slice(array_shape, slice_with_margin, slice_without_margin):
"""
Remove_margin_slice
Parameters
----------
array_shape : tuple
slice_with_margin : array_like
slice_without_margin : array_like
Returns
-------
sliced_tuple : tuple
"""
slice_tuple = tuple(
slice(max(0, v.start - u.start), min(v.stop - u.start, l), 1)
for l, u, v in zip(array_shape, slice_with_margin, slice_without_margin)
)
return slice_tuple |
def get_bytes(bits):
"""Returns bytes from list of bits"""
number = int(''.join(bits), 2)
return number.to_bytes(len(bits) // 8, byteorder='big') |
def check_rows(board):
"""
Returns False if there are two identical numbers in row and True otherwise
>>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
True
>>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
True
>>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****",\
" 5 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"])
False
"""
uniqueness = True
for i,row in enumerate(board):
if i not in (0, len(board) - 1):
for j,number in enumerate(row):
if j > row.index(number) and number not in("*", " "):
uniqueness = False
break
return uniqueness |
def validate_header(fields, required):
""" Validate the header line in a source file.
Parameters
----------
fields : list of str
Each element is the name of a field from a header line
required : set of str
Each element is the name of a required field
Returns
-------
dict
Dictionary with field name as key and list index number as value
"""
# Map field names to column numbers.
names = {fields[index]: index for index in range(len(fields))}
# Confirm that required field names are in the header line.
for req in required:
if req not in names:
raise ValueError('Required field {0} is missing from header line'.format(req))
return names |
def diff( source1, source2, start=None, end=None ):
"""Perform a diff between two equal-sized binary strings and
return a list of (offset, size) tuples denoting the differences.
source1
The first byte string source.
source2
The second byte string source.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
"""
start = start if start is not None else 0
end = end if end is not None else min( len( source1 ), len( source2 ) )
end_point = min( end, len( source1 ), len( source2 ) )
pointer = start
diff_start = None
results = []
while pointer < end_point:
if source1[pointer] != source2[pointer]:
if diff_start is None:
diff_start = pointer
else:
if diff_start is not None:
results.append( (diff_start, pointer-diff_start) )
diff_start = None
pointer += 1
if diff_start is not None:
results.append( (diff_start, pointer-diff_start) )
diff_start = None
return results |
def _is_support_vcvars_ver(vc_full_version):
"""-vcvars_ver option is supported from version 14.11.25503 (VS 2017 version 15.3)."""
version = [int(i) for i in vc_full_version.split(".")]
min_version = [14, 11, 25503]
return version >= min_version |
def dict_to_dot_str(d, parent_key='digraph D', indent='', base_indent=''):
"""Dict will be converted into DOT like the followings:
1) Value string will not be double-quotted in DOT.
- make sure to escape double-quotes in a string with special characters
(e.g. whitespace, # and ;)
2) If "value" is None then "key" will be just added to DOT without "="
dict:
{ "key1": "val1", "key2": "val2", "key3": { "key3_1": "val3_1", }... }
dot:
digraph D {
key1 = val1;
key2 = val2;
key3 {
key3_1 = val3_1;
...
}
...
}
Example in a Croo output def JSON file:
(note that strings for "label" are double-quote-escaped).
dict:
{
"rankdir": "TD",
"start": "[shape=Mdiamond]",
"end": "[shape=Msquare]",
"subgraph cluster_rep1": {
"style": "filled",
"color": "mistyrose",
"label": "\"Replicate 1\""
},
"subgraph cluster_rep2": {
"style": "filled",
"color": "azure",
"label": "\"Replicate 2\""
},
"a0 -> b0": null,
"c0 -> d0": null
}
Such dict will be converted into a dot:
dot:
digraph D {
rankDir = TD;
start = [shape=Mdiamond];
end = [shape=Msquare];
subgraph cluster_rep1 {
style = filled;
color = mistyrose;
label = "Replicate 1"
};
subgraph cluster_rep2 {
style = filled;
color = azure;
label = "Replicate 2"
};
a0 -> b0;
c0 -> d0;
}
"""
result = ''
if d is None:
return '{}{};\n'.format(base_indent, parent_key)
elif isinstance(d, str):
return '{}{} = {};\n'.format(base_indent, parent_key, d)
elif isinstance(d, dict):
result += base_indent + parent_key + ' {\n'
for k, v in d.items():
result += dict_to_dot_str(
v, parent_key=k, indent=indent, base_indent=base_indent + indent
)
result += base_indent + '}\n'
else:
raise ValueError(
'Unsupported data type: {} '
'(only str and dict/JSON are allowed).'.format(type(d))
)
return result |
def check_adjacent(a):
"""
Check if three empty slots are adjacent
:param a: array
:return: True or False
"""
counter = 0
for i in a:
if i:
counter += 1
if counter == 3:
return True
else:
counter = 0
# Do two loops as the structure is circular
for i in a:
if i:
counter += 1
if counter == 3:
return True
else:
counter = 0
return False |
def select_from_view(view, targets):
"""
Identify the fragments of the view that contain
at least one of the targets
Args:
view (dict): if present, identifies the fragments that contain the
relevant units
targets (list): list of the fragments to search in the view
Returns:
list: fragments to select
"""
reselect = []
for frag in targets:
for key, val in view.items():
if frag in val and key not in reselect:
reselect.append(key)
break
return reselect |
def minimum_bounding_box(geojson):
"""Gets the minimum bounding box for a geojson polygon.
Args:
geojson (dict): A geojson dictionary.
Returns:
tuple: Returns a tuple containing the minimum bounding box in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (32, -120)).
"""
coordinates = []
try:
if 'geometry' in geojson.keys():
coordinates = geojson['geometry']['coordinates'][0]
else:
coordinates = geojson['coordinates'][0]
lower_left = min([x[1] for x in coordinates]), min(
[x[0] for x in coordinates]) # (lat, lon)
upper_right = max([x[1] for x in coordinates]), max([x[0]
for x in coordinates]) # (lat, lon)
bounds = (lower_left, upper_right)
return bounds
except Exception as e:
raise Exception(e) |
def linear_unmap(val, lo, hi):
"""Linear unmapping."""
return (val - lo) / (hi - lo) |
def get_from_module(module_params, module_name, identifier):
"""Gets a class/instance of a module member specified by the identifier.
Args:
module_params: dict, contains identifiers
module_name: str, containing the name of the module
identifier: str, specifying the module member
Returns:
a class or an instance of a module member specified
by the identifier
"""
res = module_params.get(identifier.lower())
if res is None:
raise ValueError("Invalid {} identifier!".format(module_name), identifier)
return res |
def convertcl(text: str) -> str:
"""
CL tag format conversion.
Convert cl tags that appear only before chapter one to
the form that appears after each chapter marker.
"""
lines = text.split("\n")
# count number of cl tags in text
clcount = len([_ for _ in lines if _.startswith(r"\cl ")])
# test for presence of only 1 cl marker.
if clcount == 1:
chaplines = [
_ for _ in range(len(lines)) if lines[_].startswith(r"\c ")
]
# get cl marker line if it precedes chapter 1 and add this after
# each chapter marker in the book.
if lines[chaplines[0] - 1].startswith(r"\cl "):
clmarker = lines[chaplines[0] - 1]
lines[chaplines[0] - 1] = ""
for i in reversed(chaplines):
cnumber = lines[i].split(" ")[1]
lines.insert(i + 1, " ".join([clmarker, cnumber]))
# return our lines with converted cl tags.
return "\n".join(lines) |
def setFlag(flagbyte, pos, status):
"""
Sets the bit at 'pos' to 'status', and
returns the modified flagbyte.
"""
if status:
return flagbyte | 2 ** pos
else:
return flagbyte & ~2 ** pos |
def build_windows_time(high_word, low_word):
"""
Generate Windows time value from high and low date times.
:param high_word: high word portion of the Windows datetime
:param low_word: low word portion of the Windows datetime
:return: time in 100ns since 1601/01/01 00:00:00 UTC
"""
return (high_word << 32) + low_word |
def ipv4_prefix_to_mask(prefix):
"""
ipv4 cidr prefix to net mask
:param prefix: cidr prefix , rang in (0, 32)
:type prefix: int
:return: dot separated ipv4 net mask code, eg: 255.255.255.0
:rtype: str
"""
if prefix > 32 or prefix < 0:
raise ValueError("invalid cidr prefix for ipv4")
else:
mask = ((1 << 32) - 1) ^ ((1 << (32 - prefix)) - 1)
eight_ones = 255 # 0b11111111
mask_str = ''
for i in range(0, 4):
mask_str = str(mask & eight_ones) + mask_str
mask = mask >> 8
if i != 3:
mask_str = '.' + mask_str
return mask_str |
def create_query(section):
"""
Creates a search query based on the section of the config file.
"""
query = {}
if 'ports' in section:
query['ports'] = [section['ports']]
if 'up' in section:
query['up'] = bool(section['up'])
if 'search' in section:
query['search'] = [section['search']]
if 'tags' in section:
query['tags'] = [section['tags']]
if 'groups' in section:
query['groups'] = [section['groups']]
return query |
def romaine_v2(string):
"""
(str) -> (bool or int)
Converts roman numerals to arabic numerals without using string methods.
Restrictions: String must strictly consist of any one of M, D, C, X, V, and
I. Anything else (such as trailing whitespaces) will return False.
"""
total = 0
for y in string:
if y == 'm' or y == 'M':
total += 1000
elif y == 'd' or y == 'D':
total += 500
elif y == 'c' or y == 'C':
total += 100
elif y == 'x' or y == 'X':
total += 10
elif y == 'v' or y == 'V':
total += 5
elif y == 'i' or y == 'I':
total += 1
else:
return False
return total |
def _mask(buf, key):
"""
Mask or unmask a buffer of bytes with a masking key.
@type buf: C{str}
@param buf: A buffer of bytes.
@type key: C{str}
@param key: The masking key. Must be exactly four bytes.
@rtype: C{str}
@return: A masked buffer of bytes.
"""
key = [ord(i) for i in key]
buf = list(buf)
for i, char in enumerate(buf):
buf[i] = chr(ord(char) ^ key[i % 4])
return "".join(buf) |
def _try_import(module_name, insistance):
"""Maybe import a module and maybe raise an error if the import fails.
"""
if insistance in [False, 'no', 'false', 'False']:
return None
module = None
try:
module = __import__(module_name)
except ImportError as e:
if insistance in [True, 'yes', 'true', 'True']:
raise(e)
return module |
def split_commas(ctx, param, value):
"""
Convert from a comma-separated list to a true list.
"""
# ctx, param, value is the required calling signature for a Click callback
try:
values = value.split(',')
except AttributeError:
# values is None
values = None
return values |
def isCMSSWSupported(thisCMSSW, supportedCMSSW):
"""
_isCMSSWSupported_
Function used to validate whether the CMSSW release to be used supports
a feature that is not available in all releases.
:param thisCMSSW: release to be used in this job
:param allowedCMSSW: first (lowest) release that started supporting the
feature you'd like to use.
NOTE: only the 3 digits version are evaluated, pre and patch releases
are not taken into consideration
"""
if not thisCMSSW or not supportedCMSSW:
return False
if thisCMSSW == supportedCMSSW:
return True
thisCMSSW = [int(i) for i in thisCMSSW.split('_', 4)[1:4]]
supportedCMSSW = [int(i) for i in supportedCMSSW.split('_', 4)[1:4]]
for idx in range(3):
if thisCMSSW[idx] > supportedCMSSW[idx]:
return True
elif thisCMSSW[idx] == supportedCMSSW[idx] and idx < 2:
if thisCMSSW[idx + 1] > supportedCMSSW[idx + 1]:
return True
else:
return False
return False |
def str2bool(v):
"""
Convert string to boolean
"""
return v.lower() in ('yes', 'true', 't', 'y', '1', 'on') |
def _etextno_to_uri_subdirectory(etextno):
"""Returns the subdirectory that an etextno will be found in a gutenberg
mirror. Generally, one finds the subdirectory by separating out each digit
of the etext number, and uses it for a directory. The exception here is for
etext numbers less than 10, which are prepended with a 0 for the directory
traversal.
>>> _etextno_to_uri_subdirectory(1)
'0/1'
>>> _etextno_to_uri_subdirectory(19)
'1/19'
>>> _etextno_to_uri_subdirectory(15453)
'1/5/4/5/15453'
"""
str_etextno = str(etextno).zfill(2)
all_but_last_digit = list(str_etextno[:-1])
subdir_part = "/".join(all_but_last_digit)
subdir = "{}/{}".format(subdir_part, etextno) # etextno not zfilled
return subdir |
def isAscii(name, listExcluded=None):
"""
@param name: string to check
@param listExcluded: list of char or string excluded.
@return: True of False whether name is pure ascii or not
"""
isascii = None
try:
name.encode("ASCII")
except UnicodeDecodeError:
isascii = False
else:
if listExcluded:
isascii = not(any(bad in name for bad in listExcluded))
else:
isascii = True
return isascii |
def add_trailing_slash(directory_path):
"""
Add trailing slash if one is not already present.
Argument:
directory_path -- path to which trailing slash should be confirmed.
"""
# Add trailing slash.
if directory_path[-1] != '/':
directory_path = str().join([directory_path, '/'])
# Return directory_path with trailing slash.
return directory_path |
def _check_trig_shift_by_type(trig_shift_by_type):
"""Check the trig_shift_by_type parameter.
trig_shift_by_type is used to offset event numbers depending
of the type of marker (eg. Response, Stimulus).
"""
if trig_shift_by_type is None:
trig_shift_by_type = dict()
elif not isinstance(trig_shift_by_type, dict):
raise TypeError("'trig_shift_by_type' must be None or dict")
for mrk_type in list(trig_shift_by_type.keys()):
cur_shift = trig_shift_by_type[mrk_type]
if not isinstance(cur_shift, int) and cur_shift is not None:
raise TypeError('shift for type {} must be int or None'.format(
mrk_type
))
mrk_type_lc = mrk_type.lower()
if mrk_type_lc != mrk_type:
if mrk_type_lc in trig_shift_by_type:
raise ValueError('marker type {} specified twice with'
'different case'.format(mrk_type_lc))
trig_shift_by_type[mrk_type_lc] = cur_shift
del trig_shift_by_type[mrk_type]
return trig_shift_by_type |
def is_interleaved(c1, c2, chars):
"""
Return True if the character index lists given by characters c1 qnd c2 are
interleaved, False otherwise.
"""
answer = True
# Reference the character index lists and determine which one should go
# first, i.e. which list has the smaller first element and make that list1.
list1 = chars[c1]
list2 = chars[c2]
if list1[0] > list2[0]:
list1 = chars[c2]
list2 = chars[c1]
# For the characters to be interleaved, their counts can't differ by more
# than 1.
if abs(len(list1) - len(list2)) > 1:
answer = False
# In addition, the first list can't be smaller than the second list or there
# would not be enough characters to be properly interleaved.
elif len(list1) < len(list2):
answer = False
else:
# Now actually determine if the lists are interleaved by comparing
# adjacently indexed elements in list1 and list2. We start at index 1,
# since we've already looked at index 0.
idx = 1
while idx < len(list1) and idx < len(list2):
# The element at the current index of list1 should be less than
# that of list2. In addition, the previous element in list2 should
# be less than the current element in list1. If either of these
# aren't true, the lists aren't interleaved.
if list1[idx] > list2[idx] or list1[idx] < list2[idx - 1]:
answer = False
break
idx += 1
return answer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.