content stringlengths 42 6.51k |
|---|
def reduce(args):
"""
>>> reduce([(2, 4), (4, 9)])
[(2, 4), (4, 9)]
>>> reduce([(2, 6), (4, 10)])
[(2, 10)]
"""
if len(args) < 2: return args
args.sort()
ret = [args[0]]
for next_i, (s, e) in enumerate(args, start=1):
if next_i == len(args):
ret[-1] = ret[-1][0], max(ret[-1][1], e)
break
ns, ne = args[next_i]
if e > ns or ret[-1][1] > ns:
ret[-1] = ret[-1][0], max(e, ne, ret[-1][1])
else:
ret.append((ns, ne))
return ret |
def isKanji(char):
""" return true if char is a kanji or false if not """
code = ord(char)
return 0x4E00 <= code <= 0x9FFF |
def find_artifact(event):
"""
Returns the S3 Object that holds the artifact
"""
try:
object_key = event['CodePipeline.job']['data']['inputArtifacts'][0] \
['location']['s3Location']['objectKey']
bucket = event['CodePipeline.job']['data']['inputArtifacts'][0] \
['location']['s3Location']['bucketName']
return 's3://{0}/{1}'.format(bucket, object_key)
except KeyError as err:
raise KeyError("Couldn't get S3 object!\n%s", err) |
def make_relative(path: str, root_path: str) -> str:
"""Make path relative with respect to a
root directory
Arguments:
path (str): current path.
root_path (str): root directory path.
Returns:
str: relative path.
"""
r_path = path.replace(root_path, '')
if r_path:
if r_path[0] == '/':
r_path = r_path[1:]
return r_path |
def is_valid_hcl(hcl: str) -> bool:
"""
(Hair Color) - a # followed by exactly six characters 0-9 or a-f.
:return: Status of field (true = valid).
:rtype: bool
"""
if hcl[0] != "#":
return False
if len(hcl[1:]) != 6:
return False
return True |
def argsort(t, reverse=False):
"""Given a list, sort the list and return the original indices of the sorted list."""
return sorted(range(len(t)), key=t.__getitem__, reverse=reverse) |
def get_parent_resource(project):
"""Returns the parent resource."""
return f'projects/{project}' |
def bytes_to_int15(b0, b1):
"""Convert two bytes to 15-bit signed integer."""
value = (b0 | (b1 << 8)) >> 1
if value > 16383:
value -= 32768
return value |
def _makeDefValues(keys):
"""Returns a dictionary containing None for all keys."""
return dict(((k, None) for k in keys)) |
def Floor(x, factor=10):
"""Rounds down to the nearest multiple of factor.
When factor=10, all numbers from 10 to 19 get floored to 10.
"""
return int(x/factor) * factor |
def bubble_sort(array: list) -> tuple:
""""will return the sorted array, and number of swaps"""
total_swaps = 0
for i in range(len(array)):
swaps = 0
for j in range(len(array) - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
swaps += 1
total_swaps += 1
if swaps == 0:
break
return array, total_swaps |
def get_wind_direction(degrees):
"""
Return the shorthand direction based on the given degrees.
:type degrees: str, float
:param degrees: integer for degrees of wind
:type: str
:return: wind direction in shorthand form
"""
try:
degrees = int(degrees)
except ValueError:
return ''
direction = ''
if degrees < 23 or degrees >= 338:
direction = 'N'
elif degrees < 68:
direction = 'NE'
elif degrees < 113:
direction = 'E'
elif degrees < 158:
direction = 'SE'
elif degrees < 203:
direction = 'S'
elif degrees < 248:
direction = 'SW'
elif degrees < 293:
direction = 'W'
elif degrees < 338:
direction = 'NW'
return direction |
def redshift_num2str(z: float):
"""
Converts the redshift of the snapshot from numerical to
text, in a format compatible with the file names.
E.g. float z = 2.16 ---> str z = 'z002p160'.
"""
z = round(z, 3)
integer_z, decimal_z = str(z).split('.')
integer_z = int(integer_z)
decimal_z = int(decimal_z)
return f"z{integer_z:0>3d}p{decimal_z:0<3d}" |
def diagonal_win(board, who):
"""
returns true if either diagonal contains a winner
"""
if board[0] == who and board[4] == who and board[8] == who:
return True
if board[2] == who and board[4] == who and board[6] == who:
return True
return False |
def decode_digital_bitstream(waveform):
"""Extracts a bitstream from the waveform at the specified position"""
result = []
for i, bit in enumerate(waveform):
try:
next_bit = waveform[i + 1]
# No more words, so we are finished
except IndexError:
break
# Capture bit value changes
if bit != next_bit:
result.append(next_bit)
return result |
def is_name_selector(selector):
"""
A basic method to determine if a selector is a name selector.
"""
if selector.startswith("name=") or selector.startswith("&"):
return True
return False |
def remove_none(l: list) -> list:
"""
Returns a list that does not contain any`None` values.
@param l: The list to filter
@return: a new list
"""
return list(filter(None, l)) |
def escape(x):
"""Escape brackets, '['' and ']'."""
return x.replace("[", "\\[").replace("]", "\\]") |
def odd(x):
"""``odd :: Integral a => a -> Bool``
Returns True if the integral value is odd, and False otherwise.
"""
return x % 2 == 1 |
def rgb(arg):
"""Convert a comma separate string of 3 integers to RGB values"""
colors = arg.split(',')
if len(colors) == 1:
try:
r = int(colors[0])
except ValueError:
raise ValueError('Colour should be a single integer or ' + \
'3 comma separated integers')
else:
return r, r, r
if len(colors) != 3:
raise ValueError('Colour should be specified as 3 integers')
try:
colors = tuple([int(e) for e in colors])
except ValueError:
raise ValueError('Colour should be a single integer or ' + \
'3 comma separated integers')
else:
return colors |
def reference_vector_argument(arg):
"""
Determines a reference argument, so as not to duplicate arrays of reals, vectors and row vectors,
which usually have the same implementation.
:param arg: argument
:return: reference argument
"""
if arg in ("array[] real", "row_vector"):
return "vector"
return arg |
def orderedSet(iterable):
""" Remove all duplicates from the input iterable """
res = []
for el in iterable:
if el not in res:
res.append(el)
return res |
def speed_convert_bit(ukuran: float) -> str:
"""
Hi human, you can't read bit?
"""
if not ukuran:
return ""
totals_isi = {0: '', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
totals = 2**10
no = 0
while ukuran > totals:
ukuran /= totals
no += 1
return "{:.2f} {}B".format(ukuran, totals_isi[no]) |
def is_list_of_strings(value):
"""
Check if all elements in a list are strings
:param value:
:return:
"""
return bool(value) and isinstance(value, list) and all(isinstance(elem, str) for elem in value) |
def _fast_copy_probs_table(table):
"""
Copy a dictionary representation of a probability table faster than the standard deepcopy.
:param dict table: A dictionary with the tuples of ints as keys and floats as values.
:return: The copied table.
"""
table_copy = {tuple(assign): value for assign, value in table.items()}
return table_copy |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number < 0:
return -1
if number == 0:
return 0
if number == 1:
return 1
l = 1
h = number
while l < h:
mid_index = (h+l) // 2
square = mid_index * mid_index
next_square = (mid_index + 1) * (mid_index + 1)
if (square < number and next_square > number) or square == number:
return mid_index
elif square < number:
l = mid_index
elif square > number:
h = mid_index |
def abbrv_num(num):
"""Shorten string representation of large numbers by single-letter notation and rounding to 2 decimals
Arguments:
num (int): (Large) number to be formatted
Return:
Abbreviated and rounded number with single-letter notation
"""
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
# add more suffixes if you need them
if magnitude == 0:
return '%s' % (num)
else:
return '%.2f%s' % (num, ['', 'K', 'M', 'B', 'T', 'Q'][magnitude]) |
def has_doc(f):
"""Check if function has doc string."""
return f.__doc__ is not None |
def get_prim_obj_from_sol(sol, parameters=None):
"""
Gets the primal objective from the solution of the LP problem
Parameters
-------------
sol
Solution of the ILP problem by the given algorithm
parameters
Possible parameters of the algorithm
Returns
-------------
prim_obj
Primal objective
"""
return sol["primal objective"] |
def read_np_archive(archive):
"""Load Numpy archive file into a dictionary, skipping any values
that cannot be loaded.
Args:
archive: Loaded Numpy archive.
Returns:
Dictionary with keys and values corresponding to that of the
Numpy archive, skipping any values that could not be loaded
such as those that would require pickling when not allowed.
"""
output = {}
for key in archive.keys():
try:
output[key] = archive[key]
except ValueError:
print("unable to load {} from archive, will ignore".format(key))
return output |
def get_next_breakpoint(distanceToGround, breakpoints):
"""Returns the next breakpoint based on the current distance
from the ground.
Keyword arguments:
quantity -- How many colors inside the array (default: 1)
"""
for breakpoint in breakpoints.values():
if distanceToGround < breakpoint:
return breakpoint |
def has_type(actual_value, expected_type):
"""Return whether actual_value has expected_type"""
return type(actual_value) is expected_type |
def list_to_str(lst, space=False):
""" convers list as a comma seperated string"""
if space:
base_str = ', '
else:
base_str = ','
return base_str.join((str(c) for c in lst)).rstrip() |
def normalize_org(org):
"""Internal function to normalize an org reference to a URN."""
if org.startswith('psc:org:'):
return org
return f"psc:org:{org}" |
def nth_line(src, lineno):
"""
Compute the starting index of the n-th line (where n is 1-indexed)
>>> nth_line("aaa\\nbb\\nc", 2)
4
"""
assert lineno >= 1
pos = 0
for _ in range(lineno - 1):
pos = src.find('\n', pos) + 1
return pos |
def is_target_platform(ctx, platform):
"""
Determine if the platform is a target platform or a configure/platform generator platform
:param ctx: Context
:param platform: Platform to check
:return: True if it is a target platform, False if not
"""
return platform and platform not in ('project_generator', []) |
def tie(p, ptied = None):
"""Tie one parameter to another."""
if (ptied == None): return p
for i in range(len(ptied)):
if ptied[i] == '': continue
cmd = 'p[' + str(i) + '] = ' + ptied[i]
exec(cmd)
return p |
def a2_comp(number, nb_bits):
"""Compute the A2 complement of the given number according to the given number of bits used for encoding.
>>> a2_comp(5, 8)
251
>>> a2_comp(-5, 8)
5
>>> a2_comp(-5, 9)
5
:param int number: the number to compute the A2 complement from.
:param int nb_bits: the number of bits considered.
:returns: an integer which is the A2 complement of the given number.
"""
base = 1 << nb_bits
return (base - number) % base |
def get_standard_metadata_value( md_map, file, metadata ):
"""
Gets metadata values from a file path
:param md_map: Dictionary of keys to callables to extract metadata.
Callables should accept a single parameter which is the file name.
:param file: The file path to search
:param metadata: The key of a standard metadata to retrieve
[ 'sample' ]
:returns: A list of metadata values
"""
return md_map[ metadata ]( file ) |
def bool_from_env(env_value):
"""Convert environment variable to boolean."""
if isinstance(env_value, str):
env_value = env_value.lower() in ['true', '1']
return env_value |
def palindrome(word):
"""Return True if the given word is a palindrome."""
return word == word[::-1] |
def dict_enter(dct, key, default):
"""Access dictionary entry with a default value"""
if key not in dct:
dct[key] = default
return dct[key] |
def identifier_appearance_stat_key(appearances: set) -> str:
"""Return the key given the appearances of the span."""
if {'templates', 'references'} <= appearances:
return 'in_tag_ref_and_template'
elif 'templates' in appearances:
return 'only_in_template'
elif 'references' in appearances:
return 'only_in_tag_ref'
elif 'sections' in appearances:
return 'only_in_filtered_sections'
else:
return 'only_in_raw_text' |
def explore_local(starting_nodes, large_component, other_nodes, look_for, upper_bound):
"""
Search the large component graph for additional nodes (evidence) that doesnt conflict with other nodes or the
upper bound on copy number. If a conflict is found, no nodes of that type are returned
:param starting_nodes: set of nodes in current nuclei
:param large_component: the larger graph to search
:param other_nodes: conflicting nodes already assigned to other nuclei
:param look_for: the types of edges to look for i.e. grey or yellow
:param upper_bound: an upper bound on the expected number of reads
:return: a set of additional nodes to safely add to the current nuclei
"""
additional_nodes = {k: set([]) for k in look_for}
seen = set(starting_nodes)
if len(starting_nodes) == 0:
return set([])
while True:
nd = starting_nodes.pop()
seen.add(nd)
for edge in large_component.edges(nd, data=True):
if edge[2]['c'] in additional_nodes: # If color in look_for list
for n in (0, 1): # Check both ends of the edge for uniqueness
if edge[n] not in seen:
if edge[n] in other_nodes:
del additional_nodes[edge[2]['c']] # This evidence conflicts with another source
continue
starting_nodes.add(edge[n])
additional_nodes[edge[2]['c']].add(edge[n])
# Remove this type of evidence if over upper bound
if len(additional_nodes[edge[2]['c']]) > upper_bound:
del additional_nodes[edge[2]['c']]
if len(starting_nodes) == 0:
break
return set().union(*additional_nodes.values()) |
def Any(cls): # noqa
"""
Use during testing to assert call value type.
The function will return an instantiated class that is equal to any
version of `cls`, for example using string.
>>> mock = MagicMock()
>>> mock.func("str")
>>> mock.func.assert_called_once_with(Any(str))
Comparison is done using the isinstance operation.
"""
class Any(cls):
def __eq__(self, other):
return isinstance(other, cls)
def __str__(self):
return 'Any(%s)' % str(cls)
return Any() |
def historical_site_validation(historical_sites):
""" Decide if the historical site input is valid.
Parameters:
(str): A user's input to the historical site factor.
Return:
(str): A single valid string, such as "1", "0" or "-5" and so on.
"""
while historical_sites != "5" and historical_sites != "4" and historical_sites != "3" and historical_sites != "2" and historical_sites != "1" and historical_sites != "0" and historical_sites != "-1" and historical_sites != "-2" and historical_sites != "-3" and historical_sites != "-4" and historical_sites != "-5" :
print("\nI'm sorry, but " + historical_sites + " is not a valid choice. Please try again.")
historical_sites = input("\nHow much do you like historical sites? (-5 to 5)"
+ "\n> ")
return historical_sites |
def partition_targets(targets):
"""partition all targets"""
included_targets, excluded_targets = [], []
for target in targets:
if target.startswith("-"):
excluded_targets.append(target[1:])
else:
included_targets.append(target)
return included_targets, excluded_targets |
def separate_types(data):
"""Separate out the points from the linestrings."""
if data['type'] != 'FeatureCollection':
raise TypeError('expected a FeatureCollection, not ' + data['type'])
points = []
linestrings = []
for thing in data['features']:
if thing['type'] != 'Feature':
raise TypeError('expected Feature, not ' + thing['type'])
geometry_type = thing['geometry']['type']
if geometry_type == 'Point':
points.append(thing)
elif geometry_type == 'LineString':
linestrings.append(thing)
else:
raise TypeError('expected Point or LineString, not ' + geometry_type)
return points, linestrings |
def to_host_list(value):
"""Space separated list of FQDNs."""
return value.split() |
def color_triple(color):
"""Convert a command line colour value to a RGB triple of integers."""
# FIXME: Somewhere we need support for greyscale backgrounds etc.
if color.startswith('#') and len(color) == 4:
return (int(color[1], 16),
int(color[2], 16),
int(color[3], 16))
if color.startswith('#') and len(color) == 7:
return (int(color[1:3], 16),
int(color[3:5], 16),
int(color[5:7], 16))
elif color.startswith('#') and len(color) == 13:
return (int(color[1:5], 16),
int(color[5:9], 16),
int(color[9:13], 16)) |
def _get_expression_levels(expr):
"""
:returns: dictionary with the level of depth of each part of the expression. Brackets are ignored in the result.
e.g.: ['A', 'OR', 'B', 'AND', '(', 'A', 'IF', '(', 'NOT', 'C', 'IF', 'D', ')', ')']
=> {0: [0, 1, 2, 3], 1: [5, 6], 2: [8, 9, 10, 11]}
"""
level = 0
levels = dict()
for i, x in enumerate(expr):
if x == '(':
level += 1
elif x == ')':
level -= 1
else:
levels.setdefault(level, []).append(i)
return levels |
def parse_float(word):
""" Parse into float, on failure return 0.0 """
try:
return float(word)
except ValueError:
return 0.0 |
def format_string( oldString ):
"""
This function turns a given string (one of the two arguments passed to the
script by the user) into one that can be used as part of the URL used to
fetch the page from the lyrics wiki. Specifically, it needs to be camel-
case (or 'title' case) with underscores replacing spaces.
"""
string = oldString.title()
return( string.replace( ' ', '_', -1 ) ) |
def if_entry_table(if_name):
"""
:param if_name: given interface to cast.
:return: PORT_TABLE key.
"""
return b'PORT_TABLE:' + if_name |
def build_variant_display_title(chrom, pos, ref, alt, sep='>'):
""" Builds the variant display title. """
return 'chr%s:%s%s%s%s' % (
chrom,
pos,
ref,
sep,
alt
) |
def get_rst_bold(text):
"""
Return text bold
"""
return f"**{text}** " |
def get_crc16(data, offset, length):
"""
Computes CRC16
:param data: ByteArray wich contains the data
:param offset: Data offset to begin the calculation
:param length: Number of bytes after the offset
:return: Integer (4 bytes) with CRC or 0000 on error
"""
if data is None or offset < 0 or offset > len(
data) - 1 and offset + length > len(data):
return 0
crc = 0xFFFF
for i in range(0, length):
crc ^= data[offset + i] << 8
for j in range(0, 8):
if (crc & 0x8000) > 0:
crc = (crc << 1) ^ 0x1021
else:
crc = crc << 1
return crc & 0xFFFF |
def _get_list_difference(group_1, group_2):
"""
Calculates the difference between the two event value group.
The returned lists are always a copy of the original.
Parameters
----------
group_1 : `None`, `list` of `Any`
The first group.
group_2 : `None`, `list` of `Any`
The second group.
Returns
-------
group_1 : `None`, `list` of `Any`
The first group.
group_2 : `None`, `list` of `Any`
The second group.
"""
not_null = 0
if (group_1 is not None):
group_1 = group_1.copy()
not_null += 1
if (group_2 is not None):
group_2 = group_2.copy()
not_null += 1
if not_null == 2:
for index in reversed(range(len(group_1))):
value = group_1[index]
try:
group_2.remove(value)
except ValueError:
pass
else:
del group_1[index]
if not group_2:
group_2 = None
if not group_1:
group_1 = None
return group_1, group_2 |
def objc_strip_extension_registry(lines):
"""Removes extensionRegistry methods from the classes."""
skip = False
result = []
for line in lines:
if '+ (GPBExtensionRegistry*)extensionRegistry {' in line:
skip = True
if not skip:
result.append(line)
elif line == '}\n':
skip = False
return result |
def filter_by_tags(queries, tags):
""" Returns all the queries which contain all the tags provided """
return [q for q in queries if all(elem in q['tags'] for elem in tags)] |
def indent(lines, spaces=4):
"""
Indent the given string of lines with "spaces" " " and
strip trailing newline.
"""
indented = [" "*spaces+line.strip() for line in lines.split("\n")]
return ("\n".join(indented)).rstrip() |
def parse_orig_dest_get(params, keys = ['origin', 'destination']):
""" Normalize origin and destination keys in the GET request.
"""
for key in keys:
if len(params[key]) == 5:
# Port code == 5-character uppercase string
params[key] = str(params[key]).upper()
else:
# Port slug == more than 5-character lowercase string
params[key] = str(params[key]).lower()
return params |
def height_correction(height1, height2):
"""returns height correction in m"""
return (height1 - height2) * 0.0065 |
def n_interactions(nplayers, repetitions):
"""
The number of interactions between n players
Parameters
----------
nplayers : integer
The number of players in the tournament.
repetitions : integer
The number of repetitions in the tournament.
Returns
-------
integer
The number of interactions between players excluding self-interactions.
"""
return repetitions * (nplayers - 1) |
def check_diagonal_winner(board) -> bool:
"""checks for diagonal winner"""
mid = board[1][1]
if mid is not None:
if board[0][0] == mid == board[2][2]:
return True
if board[2][0] == mid == board[0][2]:
return True
return False |
def damping_maintain_sign(x, step, damping=1.0, factor=0.5):
"""Damping function which will maintain the sign of the variable being
manipulated. If the step puts it at the other sign, the distance between `x`
and `step` will be shortened by the multiple of `factor`; i.e. if factor is
`x`, the new value of `x` will be 0 exactly.
The provided `damping` is applied as well.
Parameters
----------
x : float
Previous value in iteration, [-]
step : float
Change in `x`, [-]
damping : float, optional
The damping factor to be applied always, [-]
factor : float, optional
If the calculated step changes sign, this factor will be used instead
of the step, [-]
Returns
-------
x_new : float
The new value in the iteration, [-]
Notes
-----
Examples
--------
>>> damping_maintain_sign(100, -200, factor=.5)
50.0
"""
if isinstance(x, list):
return [damping_maintain_sign(x[i], step[i], damping, factor) for i in range(len(x))]
positive = x > 0.0
step_x = x + step
if (positive and step_x < 0) or (not positive and step_x > 0.0):
# print('damping')
step = -factor*x
return x + step*damping |
def ImagePropFromGlobalDict(glob_dict, mount_point):
"""Build an image property dictionary from the global dictionary.
Args:
glob_dict: the global dictionary from the build system.
mount_point: such as "system", "data" etc.
"""
d = {}
if "build.prop" in glob_dict:
bp = glob_dict["build.prop"]
if "ro.build.date.utc" in bp:
d["timestamp"] = bp["ro.build.date.utc"]
def copy_prop(src_p, dest_p):
if src_p in glob_dict:
d[dest_p] = str(glob_dict[src_p])
common_props = (
"extfs_sparse_flag",
"mkyaffs2_extra_flags",
"selinux_fc",
"skip_fsck",
"verity",
"verity_key",
"verity_signer_cmd"
)
for p in common_props:
copy_prop(p, p)
d["mount_point"] = mount_point
if mount_point == "system":
copy_prop("fs_type", "fs_type")
# Copy the generic sysetem fs type first, override with specific one if
# available.
copy_prop("system_fs_type", "fs_type")
copy_prop("system_size", "partition_size")
copy_prop("system_journal_size", "journal_size")
copy_prop("system_verity_block_device", "verity_block_device")
copy_prop("system_root_image", "system_root_image")
copy_prop("ramdisk_dir", "ramdisk_dir")
copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
copy_prop("system_squashfs_compressor", "squashfs_compressor")
copy_prop("system_squashfs_compressor_opt", "squashfs_compressor_opt")
elif mount_point == "data":
# Copy the generic fs type first, override with specific one if available.
copy_prop("fs_type", "fs_type")
copy_prop("userdata_fs_type", "fs_type")
copy_prop("userdata_size", "partition_size")
elif mount_point == "cache":
copy_prop("cache_fs_type", "fs_type")
copy_prop("cache_size", "partition_size")
elif mount_point == "vendor":
copy_prop("vendor_fs_type", "fs_type")
copy_prop("vendor_size", "partition_size")
copy_prop("vendor_journal_size", "journal_size")
copy_prop("vendor_verity_block_device", "verity_block_device")
copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
elif mount_point == "oem":
copy_prop("fs_type", "fs_type")
copy_prop("oem_size", "partition_size")
copy_prop("oem_journal_size", "journal_size")
copy_prop("has_ext4_reserved_blocks", "has_ext4_reserved_blocks")
return d |
def l1(vector_1, vector_2):
""" compute L2 metric """
return sum([abs((vector_1[i] - vector_2[i])) for i in range(len(vector_1))]) |
def join_ipv4_segments(segments):
"""
Helper method to join ip numeric segment pieces back into a full
ip address.
:param segments: IPv4 segments to join.
:type segments: ``list`` or ``tuple``
:return: IPv4 address.
:rtype: ``str``
"""
return ".".join([str(s) for s in segments]) |
def get_xdot(y, p_x):
"""speed in x direction, from coordinates and momenta"""
v_x = p_x + y
return v_x |
def matmul(Ma, Mb):
"""
@brief Implements matrix multiplication.
"""
assert len(Ma[0]) == len(Mb), \
"Ma and Mb sizes aren't compatible"
size = len(Mb)
Mres = [[0 for i in range(size)] for j in range(size)]
for i in range(size):
for j in range(size):
for k in range(size):
Mres[i][j] ^= Ma[i][k] and Mb[k][j]
return Mres |
def clean_string(string):
"""Removes non-letters from string leaving only ascii letters (swedish characters removed),
whitespace and hyphens. Returns the clean string.
"""
new_string = ""
string.lower()
for c in string:
if c.isalpha() or c.isspace() or c == '-':
new_string += c
return new_string |
def int_to_based_string(number: int,
states: str,
length: int = 0) -> str:
"""Generates the quivalent string representation of an integer in the
provided base states
Parameters:
-----------
number: int
integer value to be represented
states: string
ordered states to use for representation
length: int
required length of representation
Returns:
--------
sequence: string
based & justified representation of input number
Raises:
-------
* None
"""
base = len(states)
fill_state = states[0]
(div, mod) = divmod(number, base)
if div > 0:
sequence = int_to_based_string(div, states=states) + states[mod]
return sequence.rjust(length, fill_state)
return states[mod] if not length else states[mod].rjust(length, fill_state) |
def getStrips(seq):
""" find contained intervals where sequence is ordered, and return intervals
in as lists, increasing and decreasing. Single elements are considered
decreasing. "Contained" excludes the first and last interval. """
deltas = [seq[i+1] - seq[i] for i in range(len(seq)-1)]
increasing = list()
decreasing = list()
start = 0
for i, diff in enumerate(deltas):
if (abs(diff) == 1) and (diff == deltas[start]):
continue
if (start > 0):
if deltas[start] == 1:
increasing.append((start, i+1))
else:
decreasing.append((start, i+1))
start = i+1
return increasing, decreasing |
def strip_type(caller):
"""
strip the -indel or -snp from the end of a caller name
"""
vartype = ''
if caller.endswith('-snp'):
caller = caller[:-len('-snp')]
vartype = 'snp'
elif caller.endswith('-indel'):
caller = caller[:-len('-indel')]
vartype = 'indel'
# if there is still a dash, get everything after it
i = caller.rfind('-')
if i != -1:
caller = caller[i+1:]
return caller, vartype |
def verify_image_name(in_dict):
"""Verifies post request was made with correct format
The input dictionary must have the appropriate data keys
and types, or be convertible to correct types, to be added
to the image database.
Args:
in_dict (dict): input with image name
Returns:
str: if error, returns error message
bool: if input verified, returns True
"""
expected_key = "image"
expected_type = str
if expected_key not in in_dict.keys():
return "{} key not found".format(expected_key)
if type(in_dict[expected_key]) is not expected_type:
return "{} value not a string".format(expected_key)
return True |
def convert_mw(mw, to="g"):
"""(int_or_float, str) => float
Converts molecular weights (in dalton) to g, mg, ug, ng, pg.
Example:
>> diploid_human_genome_mw = 6_469.66e6 * 660 #lenght * average weight of nucleotide
>> convert_mw(diploid_human_genome_mw, to="ng")
0.0070904661368191195
"""
if to == "g":
return mw * 1.6605402e-24
if to == "mg":
return mw * 1.6605402e-21
if to == "ug":
return mw * 1.6605402e-18
if to == "ng":
return mw * 1.6605402e-15
if to == "pg":
return mw * 1.6605402e-12
raise ValueError(
f"'to' must be one of ['g','mg','ug','ng','pg'] but '{to}' was passed instead."
) |
def to_py_name(cpp_name, entry_type):
"""Returns the name the function should have in the Python api, based
on the c++-function name.
For entry_type 'function', the cpp_name is used unmodified,
otherwise strip everything before the first underscore, so that
e.g:
> someclass_some_method(PyObject* self, ...)
gets the name "some_method", and is invoked with:
> some_object.some_method(...)
"""
if entry_type == 'function':
return cpp_name
first_underscore = cpp_name.find('_')
assert(first_underscore != -1)
return cpp_name[first_underscore + 1:] |
def load_step_solve(n1,n2,inc=1):
"""
Solve from load step n1 to n2
"""
_lss = "LSSOLVE,%g,%g,%g"%(n1,n2,inc)
return _lss |
def _get_changed_items(baselist, comparelist):
"""Return changed items as they relate to baselist."""
return list(set(baselist) & set(set(baselist) ^ set(comparelist))) |
def pow(base, exp, mod): # pylint: disable=redefined-builtin
"""
Efficiently exponentiates an integer :math:`a^k (\\textrm{mod}\\ m)`.
The algorithm is more efficient than exponentiating first and then reducing modulo :math:`m`. This
is the integer equivalent of :func:`galois.poly_pow`.
Note
----
This function is an alias of :func:`pow` in the standard library.
Parameters
----------
base : int
The integer base :math:`a`.
exp : int
The integer exponent :math:`k`.
mod : int
The integer modulus :math:`m`.
Returns
-------
int
The modular exponentiation :math:`a^k (\\textrm{mod}\\ m)`.
Examples
--------
.. ipython:: python
galois.pow(3, 5, 7)
(3**5) % 7
"""
import builtins # pylint: disable=import-outside-toplevel
return builtins.pow(base, exp, mod) |
def filtered_objects(objects, typeid_filter_list=None, include_only_visible=False):
"""Filter list of objects."""
if typeid_filter_list is None:
typeid_filter_list = [
"App::Line",
"App::Plane",
"App::Origin",
# 'GeoFeature',
# 'PartDesign::CoordinateSystem',
# 'Sketcher::SketchObject',
]
result_objects = []
for obj in objects:
if obj.TypeId not in typeid_filter_list:
if include_only_visible:
if hasattr(obj, "Visibility"):
if obj.Visibility:
result_objects.append(obj)
else:
print(
"filtered_objects: "
"obj '{}' has no Visibility attribute."
"it is excluded from results."
"".format(obj.Name)
)
else:
result_objects.append(obj)
return result_objects |
def format_duration(sec):
""" Format duration in seconds
Args:
sec (int): seconds since 1970...
"""
hours,remainder = divmod(sec,3600)
min = remainder//60
ftime = "%s:%s" % (str(hours).rjust(2,'0'),str(min).rjust(2,'0'))
return str(ftime).rjust(5) |
def add_cocs(original, additional):
"""Add two tuples of COCs. Extend as needed."""
assert not (original is None and additional is None), "No COCs to add!"
if original is None:
return additional
elif additional is None:
return original
else:
common = tuple(lhs + rhs for lhs, rhs in zip(original, additional))
return (
common +
tuple(original[len(common):]) +
tuple(additional[len(common):])) |
def reverse_gray_code(g):
"""Restores number n from the gray code!"""
n = 0
while g:
n ^= g
g >>= 1
return n |
def unit_format(x_in):
"""
Define helper unit format function for axis
:param x_in: a number in decimal or float format
:return: the number rounded and in certain cases abbreviated in the thousands, millions, or billions
"""
# suffixes = ["", "Thousand", "Million", "Billion", "Trillion", "Quadrillion"]
number = str("{:,}".format(x_in))
n_commas = number.count(',')
# print(number.split(',')[0], suffixes[n_commas])
if n_commas >= 3:
x_out = f'{round(x_in/1000000000, 1)} bln'
elif n_commas == 2:
x_out = f'{round(x_in/1000000, 1)} mio'
elif n_commas == 1:
x_out = f'{round(x_in/1000, 1)} tsd'
else:
x_out = str(int(round(x_in, 0)))
return x_out |
def list_values(keys, dictionary):
"""Returns `dictionary` values orderd by `keys`.
>>> d = {'1': 1, '2': 2}
>>> list_values(['1', '2', '3'], d)
[1, 2, None]
"""
return [key in dictionary and dictionary[key] or None for key in keys] |
def classify(tree, input):
""" tree is our decision model and input is unknown
every time it recurse it choose a subtree """
# if this is a leaf node, return its value
if tree in [True, False]:
return tree
attribute, subtree_dict = tree
# see the attribute of input one by one
subtree_key = input.get(attribute)
if subtree_key not in subtree_dict:
subtree_key = None
subtree = subtree_dict[subtree_key]
return classify(subtree, input) |
def starting_regions(num_state_qubits):
"""
For use in bisection search for state preparation subroutine. Fill out the necessary region labels for num_state_qubits.
"""
sub_regions = []
sub_regions.append(['1'])
for d in range(1,num_state_qubits):
region = []
for i in range(2**d):
key = bin(i)[2:].zfill(d) + '1'
region.append(key)
sub_regions.append(region)
return sub_regions |
def snake_to_spaces(snake_cased_str):
"""
convert snake case into spaces seperated
"""
separator = "_"
components = snake_cased_str.split(separator)
if components[0] == "":
components = components[1:]
if components[-1] == "":
components = components[:-1]
if len(components) > 1:
spaced_str = components[0].lower()
for x in components[1:]:
spaced_str += " " + x.lower()
else:
spaced_str = components[0]
return spaced_str |
def check_for_essid(essid, lst):
"""Will check if there is an ESSID in the list and then send False to end the loop."""
check_status = True
# If no ESSIDs in list add the row
if len(lst) == 0:
return check_status
# This will only run if there are wireless access points in the list.
for item in lst:
# If True don't add to list. False will add it to list
if essid in item["ESSID"]:
check_status = False
return check_status |
def _valueish(val):
"""
Try to convert something Timetric sent back to a Python value.
"""
literals = {"null":None, "true":True, "false":False}
v = val.lower()
return v in literals and literals[v] or float(v) |
def get_colours(query, clusters):
"""Colour array for Plotly.js"""
colours = []
for clus in clusters:
if str(clus) == str(query):
colours.append('rgb(255,128,128)')
else:
colours.append('blue')
return colours |
def leap_year(year: int):
"""
The tricky thing here is that a leap year occurs:
on every year that is evenly divisible by 4
except every year that is evenly divisible by 100
except every year that is evenly divisible by 400
:param year:
:return:
"""
if year % 4 == 0:
if year % 100 == 0 and year % 400 == 0:
return True
if year % 100 != 0:
return True
return False |
def join_by_comma(iterable, key=None):
"""
Helper to create a comma separated label out of an iterable.
:param iterable: an iterable to be joined by comma
:param key: if the iterable contains dicts, which key would you want to extract
:return: comma separated string
"""
if key:
things_to_join = (item.get(key) for item in iterable)
return ", ".join(things_to_join)
else:
return ", ".join(iterable) |
def file_as(name: str) -> str:
"""Returns a human's name with the surname first, or tries to at least.
This may perform poorly with some names.
`file_as('Mary Wollstonecraft Shelley')` returns `'Shelley, Mary Wollstonecraft'`"""
parts = name.split()
if not parts or len(parts) == 1:
return name
name = parts[0]
for part in range(1, len(parts) - 1):
name = f'{name} {parts[part]}'
return f'{parts[len(parts) - 1]}, {name}' |
def round_off(value, digits=2):
"""
Rounding off the value
:param float value: Value to be rounded
:param digits: Digit to kept as after point
:return float: Rounded value
"""
return float(("{0:.%sf}" % digits).format(value)) |
def _dup(x): # pylint: disable=invalid-name
"""Helper: copy the top element of a list or a tuple."""
if isinstance(x, list):
return [x[0]] + x
assert isinstance(x, tuple)
return tuple([x[0]] + list(x)) |
def ArchForAsmFilename(filename):
"""Returns the architectures that a given asm file should be compiled for
based on substrings in the filename."""
if 'x86_64' in filename or 'avx2' in filename:
return ['x86_64']
elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
return ['x86']
elif 'armx' in filename:
return ['arm', 'aarch64']
elif 'armv8' in filename:
return ['aarch64']
elif 'arm' in filename:
return ['arm']
else:
raise ValueError('Unknown arch for asm filename: ' + filename) |
def rotate_axes(xs, ys, zs, zdir):
"""
Reorder coordinates so that the axes are rotated with zdir along
the original z axis. Prepending the axis with a '-' does the
inverse transform, so zdir can be x, -x, y, -y, z or -z
"""
if zdir == 'x':
return ys, zs, xs
elif zdir == '-x':
return zs, xs, ys
elif zdir == 'y':
return zs, xs, ys
elif zdir == '-y':
return ys, zs, xs
else:
return xs, ys, zs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.