content
stringlengths 42
6.51k
|
---|
def get_svm_model_name(model_dict, rd=None, rev=None):
"""
Helper function to get model name from <model_dict>, <rd> and <rev>
"""
model_name = 'svm_{}_cls{}'.format(
model_dict['svm_type'],
model_dict['classes'])
if model_dict['preprocess'] is not None:
model_name += ('_' + model_dict['preprocess'])
if rd is not None:
model_name += '_{}{}'.format(model_dict['dim_red'], rd)
if rev is not None:
model_name += '_rev'
model_name += '_{}_C{:.0e}'.format(model_dict['penalty'],
model_dict['penconst'])
return model_name
|
def _tl_type_ ( leaf ) :
"""Get a type for TLeaf object
>>> tree = ...
>>> leaf = t.leaf ( 'QQQ' )
>>> print leaf.get_type ( )
"""
if not leaf : return 'NULL'
branch = leaf.GetBranch ()
typename = leaf.GetTypeName ()
name = branch.GetTitle()
p1 = name. find ( '[' )
p2 = name.rfind ( ']' )
if 0 < p1 < p2 :
typename = '%s [%s]' % ( typename , name [ p1 + 1 : p2 ] )
elif 0 < p1 :
typename = '%s [%s]' % ( typename , name [ p1 : ] )
typename = typename.replace ( 'Float_t' , 'float' )
typename = typename.replace ( 'Double_t' , 'double' )
typename = typename.replace ( 'Bool_t' , 'bool' )
return typename
|
def valsplit(p: str):
"""Split value from path"""
parts = p.split("=", maxsplit=1)
if len(parts) == 1:
return parts[0], None
return parts[0], parts[1]
|
def _compute_checksum(packet):
"""Computes the checksum byte of a packet.
Packet must not contain a checksum already
Args:
packet (list):
List of bytes for a packet.
packet must not contain a checksum
as the last element
Returns:
The computed checksum byte.
"""
# checksum is the sum of the bytes
# from device id to the end of the data
# mod (%) 256 and bit negated (~) (1's compliment)
# and (&) with 0xFF to make sure it is a byte.
return ~(sum(packet[2:]) % 0x100) & 0xFF
|
def logistic_equation(_, x, k, g):
"""
ode for the logistic equation
:param _: place holder for time, not used
:param x: x value
:param k: slope of logistic equation
:param g: upper bound of logistic equation
:return: slope dx/dt
"""
dx = k * x * (g - x)
return dx
|
def find_best(strings, criteria):
"""
Parse a list of `strings` and return the "best" element based on `criteria`.
:param strings: List of string where best will be found based on `criteria`.
:type strings: List[str]
:param criteria: '>'-separated substrings sought in descending order.
'+' is a logical 'and', '=' substitutes: `A=B` returns B if A is found.
:type criteria: str
:return: Best string based on given `criteria` or `` if no best found.
:rtype: str
"""
criterion, _, further_criteria = criteria.partition('>')
wanted = criterion.partition('=')[0].split('+')
if all(w in strings or w is '' for w in wanted):
return criterion.rpartition('=')[2]
else:
return find_best(strings, further_criteria)
|
def BitFlip(n, N, pos):
"""Flips bit value at position pos from the left of the length-N bit-representation of n"""
return (n ^ (1 << (N-1-pos)))
|
def flatten_dict(d, parent_key=tuple()):
"""Flatten a nested dict `d` into a shallow dict with tuples as keys.
Parameters
----------
d : dict
Returns
-------
dict
Note
-----
Based on https://stackoverflow.com/a/6027615/
by user https://stackoverflow.com/users/1897/imran
.. versionadded:: 0.18.0
"""
items = []
for k, v in d.items():
if type(k) != tuple:
new_key = parent_key + (k, )
else:
new_key = parent_key + k
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key).items())
else:
items.append((new_key, v))
return dict(items)
|
def get_duplicated_sc_names(validated_data: dict):
"""
Validates if all Stop Condition names are unique.
:validated_data: dict. Dictionary for validation.
:return: list of duplicates.
"""
sc_names = []
for sc in validated_data["StopCondition"]:
sc_names.append(sc["Name"])
duplicates = []
if len(sc_names) > len(set(sc_names)):
duplicates = set([x for x in sc_names if sc_names.count(x) > 1])
return duplicates
|
def remove_dups(seq):
"""
https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
def findClosestSubPath(hdf5Object, path):
"""Find the closest existing path from the hdf5Object using a subset of the
provided path.
Returns None if no path found. It is possible if the path is a relative
path.
:param h5py.Node hdf5Object: An HDF5 node
:param str path: A path
:rtype: str
"""
if path in ["", "/"]:
return "/"
names = path.split("/")
if path[0] == "/":
names.pop(0)
for i in range(len(names)):
n = len(names) - i
path2 = "/".join(names[0:n])
if path2 == "":
return ""
if path2 in hdf5Object:
return path2
if path[0] == "/":
return "/"
return None
|
def get_explicit_entries(config_projects):
"""Pull out and return the projects in the config that were explicitly entered.
The projects in the returned dict are deleted from config_projects.
"""
explicit_projects = {
name: details
for name, details in config_projects.items()
if details.purpose == "explicit"
}
for project in explicit_projects:
del config_projects[project]
return explicit_projects
|
def convertImageIDToPaddedString(n, numCharacters=10):
"""
Converts the integer n to a padded string with leading zeros
"""
t = str(n)
return t.rjust(numCharacters, '0')
|
def encode_data(name, form):
"""Right now, this is stupid.
This will need to be fixed to generate a proper URL to REDcap
Most likely we'll hit the REDCap db, filter to get a record ID
and plunk it into the URL."""
google_url = 'https://www.google.com/#q={}'.format(name + form)
return google_url
|
def unpack(packed_data):
"""
Decompresses image data using a very simple algorithm described in 'pack'.
Returns a bytearray.
"""
i = 0 # index for the unpacked bytearray element that we're currently on
# checking the compression format version, for future compatibility in case this algo changes significantly
if packed_data[0] != 1:
print("Don't know how to decompress this image, format version:", packed_data[0])
return None
# pre-creating a bytearray of the length we need, initially filled with zeroes
# to avoid creating too many useless objects and wasting memory as we unpack
unpacked_data = bytearray(packed_data[1])
for element in packed_data[2:]: # need to skip two elements - version and length
if isinstance(element, int): # just an int, simply putting it into the bytearray
unpacked_data[i] = element
i += 1
else:
value, count = element
if value == 0: # small optimization
# skipping zero-filling since bytearrays are pre-filled with zeroes
i += count
else:
for _ in range(count):
unpacked_data[i] = value
i += 1
return unpacked_data
|
def _check_callable(func, value):
"""Return true if func(value) returns is true or if *func* is
*value*.
"""
return value is func or func(value)
|
def find_manual_auto_name_mismatches(manual_to_auto_map):
"""Finds the manual FOVs with names that do not match their corresponding auto FOV
Args:
manual_to_auto_map (dict):
defines the mapping of manual to auto FOV names
Returns:
list:
contains tuples with elements:
- `str`: the manual FOV
- `str`: the corresponding auto FOV
"""
# find the manual FOVs that don't match their corresponding closest_auto_fov name
# NOTE: this method maintains the original manual FOV ordering which is already sorted
manual_auto_mismatches = [
(k, v)
for (k, v) in manual_to_auto_map.items() if k != v
]
return manual_auto_mismatches
|
def make_rule_key(prefix, rule, group_id, cidr_ip):
"""Creates a unique key for an individual group rule"""
if isinstance(rule, dict):
proto, from_port, to_port = [rule.get(x, None) for x in ('proto', 'from_port', 'to_port')]
#fix for 11177
if proto not in ['icmp', 'tcp', 'udp'] and from_port == -1 and to_port == -1:
from_port = 'none'
to_port = 'none'
else: # isinstance boto.ec2.securitygroup.IPPermissions
proto, from_port, to_port = [getattr(rule, x, None) for x in ('ip_protocol', 'from_port', 'to_port')]
key = "%s-%s-%s-%s-%s-%s" % (prefix, proto, from_port, to_port, group_id, cidr_ip)
return key.lower().replace('-none', '-None')
|
def no_set_folders(on=0):
"""Esconder as Configuracoes Painel de Controle, Impressoras e Conexoes de
Rede
DESCRIPTION
Esta restricao remove as configuracoes Painel de Controle, Impressoras
e Conexoes de Rede do menu Iniciar. Se as configuracoes da Barra de Tarefas
tambem estiverem escondidas, acarretara na completa remocao das
configuracoes.
COMPATIBILITY
Todos.
MODIFIED VALUES
NoSetFolders : dword : 00000000 = Desabilita restricao;
00000001 = Habilita restricao.
OBSERVATION
Esta restricao deve desabilitar tambem a hotkey do Windows Explorer
(SUPER + E).
"""
if on:
return '''[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\\
CurrentVersion\\Policies\\Explorer]
"NoSetFolders"=dword:00000001'''
else:
return '''[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\\
CurrentVersion\\Policies\\Explorer]
"NoSetFolders"=dword:00000000'''
|
def getAddressClass(binaryString):
""" This will calculate the address class of the IP address based on bits of binary string
A: 0...
B: 10..
C: 110.
D: 1110
E: 1111
"""
# initialize variable
addressClass=""
# troubleshooting
# print(binaryString)
# determine the address class
if binaryString[0] == "0":
addressClass = "A"
elif binaryString[0:2] == "10":
addressClass = "B"
elif binaryString[0:3] == "110":
addressClass = "C"
elif binaryString[0:4] == "1110":
addressClass = "D"
elif binaryString[0:4] == "1111":
addressClass = "E"
return addressClass
|
def uX_to_bin(v, x):
"""Create a binary set of valued."""
if(v < 0):
v += (1 << x)
return bin(v)[2:].rjust(x, '0')
|
def _add_dot_prefix(meta_value):
"""Add dot as the prefix if missing"""
if meta_value and not meta_value.startswith("."):
return ".{0}".format(meta_value)
return meta_value
|
def color_text(c: str, txt):
"""
To edit the text color.
:param c: color.
:param txt: text
"""
if c == 'red':
return '\033[91m{}\033[m'.format(txt)
elif c == 'white':
return '\033[97m{}\033[m'.format(txt)
elif c == 'green':
return '\033[92m{}\033[m'.format(txt)
elif c == 'yellow':
return '\033[93m{}\033[m'.format(txt)
elif c == 'blue':
return '\033[94m{}\033[m'.format(txt)
elif c == 'cyan':
return '\033[96m{}\033[m'.format(txt)
elif c == 'magenta':
return '\033[95m{}\033[m'.format(txt)
|
def rsa_blind(message, randint, exponent, modulus):
"""
Return message RSA-blinded with integer randint for a keypair
with the provided public exponent and modulus.
"""
return (message * pow(randint, exponent, modulus)) % modulus
|
def parse_hex(text):
"""Parse a hex number from text or fail
:param text: Text to parse hex number from
:type text: str
:return: Parsed hex number
:rtype: int
:raise RuntimeError: If text does not contain a valid hexadecimal number
"""
try:
return int(text, 0)
except ValueError as ex:
raise RuntimeError(f"Could not parse hex number '{text}': {ex}")
|
def stripperiods(aText):
"""Remove periods from text."""
import re
# Replace by a space in case comma directly connects two words.
aText = re.sub(r"\.", " ", aText)
# Remove any multi-space sections (some may result from the above step)
return re.sub(" {2,}", " ", aText)
|
def bizz_fuzz(num):
"""
BizzFuzz template tag.
:param num: Integer
:return: String or number depends on multiples conditions.
"""
output = ''
if num % 3 == 0:
output += 'Bizz'
if num % 5 == 0:
output += 'Fuzz'
return output or num
|
def lcs(x, y):
"""
Finds longest common subsequence
Code adopted from https://en.wikibooks.org/wiki/Algorithm_Implementation/
Strings/Longest_common_subsequence#Python
"""
m = len(x)
n = len(y)
# An (m+1) times (n+1) matrix
c = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
c[i][j] = c[i - 1][j - 1] + 1
else:
c[i][j] = max(c[i][j - 1], c[i - 1][j])
def back_track(i, j):
if i == 0 or j == 0:
return ""
elif x[i - 1] == y[j - 1]:
return back_track(i - 1, j - 1) + x[i - 1]
else:
if c[i][j - 1] > c[i - 1][j]:
return back_track(i, j - 1)
else:
return back_track(i - 1, j)
return len(back_track(m, n))
|
def EF_unsteady_states(Names):
"""
Constructs a CTL formula that queries whether for every variables v specified in *Names* there is a path to a state x in which v is unsteady.
.. note::
Typically this query is used to find out if the variables given in *Names* are oscillating in a given attractor.
**arguments**:
* *Names* (list): a list of names of variables
**returns**:
* *Formula* (str): the CTL formula
**example**::
>>> names = ["v1","v2"]
>>> EF_unsteady_states(names)
'EF(v1_steady!=0) & EF(v2_steady!=0))'
"""
Names = [x for x in Names if x.strip()]
if Names==[]:
return 'TRUE'
return ' & '.join(['EF(!%s_STEADY)'%x for x in Names])
|
def sessions(request):
"""# Cookies prepeocessor """
context = {}
# site_description = 'Asesalud Laboral 2727 C.A'
# context['site_description'] = site_description
return context
|
def has_argument(arg, arguments):
"""
Verifica se ci sono argument con la classe.
"""
try:
if not isinstance(arguments, list):
arguments = arguments.__arguments__
for idx, (args, kwargs) in enumerate(arguments):
arg_name = kwargs.get(
'dest', args[-1].lstrip('-').replace('-', '_'))
if arg_name == arg:
return idx
idx = False
except (ValueError, AttributeError):
idx = False
return idx
|
def evaluate(pred_joins, gt_joins):
""" Evaluate the performance of fuzzy joins
Parameters
----------
pred_joins: list
A list of tuple pairs (id_l, id_r) that are predicted to be matches
gt_joins:
The ground truth matches
Returns
-------
precision: float
Precision score
recall: float
Recall score
f1: float
F1 score
"""
pred = {(l, r) for l, r in pred_joins}
gt = {(l, r) for l, r in gt_joins}
tp = pred.intersection(gt)
precision = len(tp) / len(pred)
recall = len(tp) / len(gt)
f1 = 2 * precision * recall / (precision + recall)
return precision, recall, f1
|
def cigar_score(pairs, match_score=1, mismatch_score=-1, gap_score=-1):
"""
Find a custom score for cigar
:param pairs:
:return: number
"""
total = 0
for c,i in pairs:
if c in ["="]:
total += i*match_score
elif c in ["X"]:
total += i * mismatch_score
elif c in ["I", "D", "N", "S", "H", "P"]:
total += i * gap_score
return total
|
def _next_power_of_two(x):
"""Calculates the smallest enclosing power of two for an input.
Args:
x: Positive float or integer number.
Returns:
Next largest power of two integer.
"""
return 1 if x == 0 else 2**(int(x) - 1).bit_length()
|
def __zero_mat_list__(n=3):
"""Return a zero mat in list format.
Args:
n (int, optional):
Length of the edge.
Defaults to 3.
Returns:
list:
List[List[int]]
"""
ret_list = [[0] * n for _ in range(n)]
return ret_list
|
def dir1(obj):
"""
get the attributes of an object that are not interpreter-related
"""
return [{a: getattr(obj, a)} for a in dir(obj) if not a.startswith('__')]
|
def rws(t):
"""Remove white spaces, tabs, and new lines from a string"""
for c in ['\n', '\t', ' ']:
t = t.replace(c,'')
return t
|
def int_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval .
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
An int that results from scaling `maxval` according to `level`.
"""
return int(level * maxval / 10)
|
def clean_str(str_,
illegal_chars=(' ', '\t', ',', ';', '|'),
replacement_char='_'):
"""
Return a copy of string that has all non-allowed characters replaced by a new character (default: underscore).
:param str_:
:param illegal_chars:
:param replacement_char:
:return: str;
"""
new_string = str(str_)
for illegal_char in illegal_chars:
new_string = new_string.replace(illegal_char, replacement_char)
return new_string
|
def merge_dict(this, other, cb):
"""
Merge dicts by key
:param this:
:param other:
:param cb:
:return:
"""
# assert isinstance(this, dict)
# assert isinstance(other, dict)
result = {}
result.update(this)
result.update(other)
for key in this.keys() & other:
ret = cb(this[key], other[key])
result[key] = ret
return result
|
def html_color(color):
"""Interpret 'color' as an HTML color."""
if isinstance(color, str):
if color.lower() == "r":
return "#ff0000"
elif color.lower() == "g":
return "#00ff00"
elif color.lower() == "b":
return "#0000ff"
elif color.startswith("#"):
return color
elif len(color) == 3:
return '#' + ''.join([hex(int(float_color*255))[2:].zfill(2) for float_color in color])
else:
raise Exception("Color not recognized: " + str(color))
|
def sql_name(raw_name):
""" Cleaned column name.
Args:
raw_name: raw column name
Returns:
cleaned name suitable for SQL column
"""
sql_name = raw_name
for to_replace in ['"', ' ', '\\', '/', '(', ')', '.']:
sql_name = sql_name.replace(to_replace, '_')
return sql_name.strip()
|
def has_open_sequence(text: str) -> bool:
"""Figures out if the given text has any unclosed ANSI sequences.
It supports standard SGR (`\\x1b[1mHello`), OSC (`\\x1b[30;2ST\\x1b\\\\`) and Kitty APC codes
(`\x1b_Garguments;hex_data\\x1b\\\\`). It also recognizes incorrect syntax; it only considers
a tag closed when it is using the right closing sequence, e.g. `m` or `H` for SGR, `\\x1b\\\\`
for OSC and APC types.
Args:
text: The text to test.
Returns:
True if there is at least one tag that hasn't been closed, False otherwise.
"""
is_osc = False
is_sgr = False
is_apc = False
open_count = 0
sequence = ""
for char in text:
if char == "\x1b":
open_count += 1
sequence += char
continue
if len(sequence) == 0:
continue
# Ignore OSC and APC closers as new openers
if char == "\\" and sequence[-1] == "\x1b":
open_count -= 1
is_osc = is_osc or sequence[:2] == "\x1b]"
is_sgr = is_sgr or sequence[:2] == "\x1b["
is_apc = is_apc or sequence[:3] == "\x1b_G"
sequence += char
if (is_osc or is_apc) and sequence[-2:] == "\x1b\\":
sequence = ""
open_count -= 1
elif is_sgr and char in {"m", "H"}:
sequence = ""
open_count -= 1
return len(sequence) != 0 or open_count != 0
|
def _test(transformation, word1, word2):
"""Tries transforming word1 and word2 with the given transform function.
It tries swapping the words if the transformation fails.
This function returnsthe transformed words or false if
the transformation failed both ways."""
result = transformation(word1, word2)
if not result:
result = transformation(word2, word1)
if result:
return (result[1], result[0])
return result
|
def decrypt_block(n, suffix, length, oracle):
"""
Decrypts one block of the hidden suffix appended to the user input in the
oracle.
"""
for i in range(16):
# If length of suffix is equal to the length of the suffix, return.
if len(suffix) == length:
return suffix
# Generate input.
inp = 'A' * (15 - i)
# Build dictionary and find next byte in the suffix.
inp_len = len(inp + suffix) + 1
inputs = {
oracle(inp + suffix + chr(j))[:inp_len]:(inp + suffix + chr(j))
for j in range(256)
}
suffix += inputs[oracle(inp)[:inp_len]][-1]
return suffix
|
def splitdir(idx):
""" Return a subdirectory used when a big case is split into several pieces """
name = ''
if len(idx) == 0:
return ''
for ii, n in enumerate(idx[0:]):
name += 'sp%d-split-%d/' % (ii, n)
name = name[0:-1]
return name
|
def map1to8(v):
"""
Limit v to the range 1-8 or None, with 0 being converted to 8 (straight ahead).
This is necessary because the back-calculation to degree7 will negative values
yet the input to calculate_average_instruction must use 1-8 to weight forward
instructions correctly.
:param v:
:return: v, in the range 1-8 or None
"""
if v is None or v > 0:
return v
return v + 8
|
def convertgoogle(ui):
"""function to convert user information returned by google auth service in expected format:
returns this format:
e.g.:{'name':'John Smith','id': '12345', 'email': '[email protected]','provider','google',...}
"""
myui = {'name':ui['name'],'given_name':ui['given_name'],'family_name':ui['family_name'],
'provider':ui['iss'],'email':ui['email'],'id':ui['sub']}
return myui
|
def to_dict(arr, id_='id'):
""" convert array to dict """
result = {}
if isinstance(arr, dict):
return arr
for row in arr:
result[row[id_]] = row
return result
|
def _get_module_tag(namespace, directive):
"""Get the project-relative path to some Python class, method, or function.
Args:
namespace (str):
The importable Python location of some class, method, or function.
Example: "foo.bar.ClassName.get_method_data".
directive (str):
The Python type that `namespace` is. Example: "py:method".
Raises:
EnvironmentError:
If `directive` and `namespace` were both found properly but,
for some reason, the top-level website / file path for the
Sphinx project stored by intersphinx could not be found.
Returns:
tuple[str, str]:
The exact path, relative to a Sphinx project's root
directory, where this module is tagged, followed by a tag
like "foo" which will be later used to get a permalink to
some header in the HTML file.
"""
tokens = namespace.split(".")
if directive in {"py:method"}:
base = "/".join(tokens[:-2])
return "_modules/{base}.html".format(base=base), ".".join(tokens[-2:])
base = "/".join(tokens[:-1])
return "_modules/{base}.html".format(base=base), tokens[-1]
|
def mock_token(bona_fide, permissions, auth):
"""Mock a processed token."""
return {"bona_fide_status": bona_fide,
"permissions": permissions,
"authenticated": auth}
|
def score_word(a, b):
""" Scores a word relative to another word. Score is defined as
the number of letters that match both in value and position."""
return sum([a[i] == b[i] for i in range(len(a))])
|
def match_ints(ref, val):
"""
Todo
"""
return 100 if ref == val else 0
|
def join_urls(first_url, second_url):
""" Function that returns one url if two aren't given else joins the two urls and
returns them.
"""
if not first_url:
return second_url
if not second_url:
return first_url
first_url = first_url.strip("/")
second_url = second_url.lstrip("/")
return "/".join([first_url, second_url])
|
def text_to_bits(text, encoding="utf-8", errors="surrogatepass"):
"""
>>> text_to_bits("msg")
'011011010111001101100111'
"""
bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
|
def _make_rank(fitness):
""" make ranking according to fitness
Arguments:
----------
fitness {list[float]} -- each indivisuals' fitness
Returns:
--------
rank {list[int]} -- rank
Examples:
---------
>>> fitness = [5, 3, 4, 1, 2]
>>> rank = _make_rank(fitness)
>>> rank
[3, 4, 1, 2, 0]
"""
rank_dict = {i: _fitness for i, _fitness in enumerate(fitness)}
rank = []
for k, _ in sorted(rank_dict.items(), key=lambda x: x[1]):
rank.append(k)
return rank
|
def count_false_positives_within_list(class_predictions, LIST_c):
"""
Count the number of false positives from classes in the list LIST_c
LIST_c: List of classes whose predictions in class_predictions we are interested in
"""
false_positive_count = 0
for item in range(len(class_predictions)):
if item in LIST_c:
false_positive_count += class_predictions[item]
# Return the false positive count
return false_positive_count
|
def zero_one_loss_calc(TP, POP):
"""
Calculate zero-one loss.
:param TP: true Positive
:type TP : dict
:param POP: population
:type POP : int
:return: zero_one loss as integer
"""
try:
length = POP
return (length - sum(TP.values()))
except Exception:
return "None"
|
def calculate_standard_deviation(pessimistic, optimistic):
""" Calculate the standard deviation of a task. """
return round((pessimistic - optimistic) / 6, 1)
|
def _vertically_expand_bounding_box(bbox: tuple, increase: int) -> tuple:
"""
Expand the bounding box by a given amount in the vertical direction.
Keyword arguments:
bbox -- the bounding box to expand
increase -- the amount to expand the bounding box
Returns: the expanded bounding box
"""
return (
bbox[0],
bbox[1],
bbox[2],
bbox[3] + increase,
)
|
def validate_config(config, service_class):
"""
Validates that a discovery config is valid for a specific service class
"""
header = config.setdefault('header', {})
if service_class != header.get('service_class'):
raise Exception(
"Cannot store config hash of type %s in service class %s: %s" %
(header.get('service_class'), service_class, config))
return config
|
def get(server_id, **kwargs):
"""Return one server."""
url = '/servers/{server_id}'.format(server_id=server_id)
return url, {}
|
def shorten(text):
"""Shortens width of text."""
text = text.split("\n", 1)[0]
if len(text) > 50:
return text[:50 - 3] + '...'
return text
|
def is_true(value):
"""
Return ``True`` if the input value is ``'1'``, ``'true'`` or ``'yes'`` (case insensitive)
:param str value: value to be evaluated
:returns: bool
Example
_______
>>> is_true('1')
True
"""
return str(value).lower() in ['true', '1', 'yes']
|
def good_unit_cell(uc_params, target_unit_cell, uc_tol):
"""check unit cell."""
flag_good_uc = False
if (
abs(uc_params[0] - target_unit_cell[0]) <= (uc_tol * target_unit_cell[0] / 100)
and abs(uc_params[1] - target_unit_cell[1])
<= (uc_tol * target_unit_cell[1] / 100)
and abs(uc_params[2] - target_unit_cell[2])
<= (uc_tol * target_unit_cell[2] / 100)
and abs(uc_params[3] - target_unit_cell[3])
<= (uc_tol * target_unit_cell[3] / 100)
and abs(uc_params[4] - target_unit_cell[4])
<= (uc_tol * target_unit_cell[4] / 100)
and abs(uc_params[5] - target_unit_cell[5])
<= (uc_tol * target_unit_cell[5] / 100)
):
flag_good_uc = True
return flag_good_uc
|
def create_order(order_data):
"""
This is a stubbed method of retrieving a resource. It doesn't actually do anything.
"""
# Do something to create the resource
return order_data
|
def html_link(text, url):
"""Creates an html link element from the given text and url
:returns: html link element as string
"""
return '<a href="' + url + '">' + text + "</a>"
|
def transformation_remove_nl(text, *args):
"""
:param text: the text to run the transformation on
:type text: str
:return: the transformed text
:type return: str
"""
text = text.replace('\r\n', '').replace('\n', '')
return text
|
def bgr_int_to_rgb(bgr_int):
"""Convert an integer in BGR format to an ``(r, g, b)`` tuple.
``bgr_int`` is an integer representation of an RGB color, where the R, G,
and B values are in the range (0, 255), and the three channels are comined
into ``bgr_int`` by a bitwise ``red | (green << 8) | (blue << 16)``. This
leaves the red channel in the least-significant bits, making a direct
translation to a QColor difficult (the QColor constructor accepts an
integer form, but it assumes the *blue* channel is in the least-significant
bits).
Examples:
>>> bgr_int_to_rgb(4227327)
(255, 128, 64)
"""
red, green, blue = (
bgr_int & 0xFF,
(bgr_int >> 8) & 0xFF,
(bgr_int >> 16) & 0xFF,
)
return (red, green, blue)
|
def reverse_hashify(s):
"""Splits the given string s and returns a hash mapping the words to their
word position in the string"""
d = {}
for i, word in enumerate(s.split()):
d[word] = i
return d
|
def combine_two_measurement_mean(new_mean: float, prev_mean: float, new_std: float, prev_std: float):
""" Combine two measurement means using inverse-variance weighting
Source: https://en.wikipedia.org/wiki/Inverse-variance_weighting
:return:
"""
new_w = 1 / (new_std * new_std)
prev_w = 1 / (prev_std * prev_std)
combined_mean = (new_w * new_mean + prev_w * prev_mean) / (new_w + prev_w)
return combined_mean
|
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
possiblewin = [[[0,0],[1,1],[2,2]],[[0,0],[0,1],[0,2]],
[[1,0],[1,1],[1,2]],
[[2,0],[2,1],[2,2]],
[[0,0],[1,0],[2,0]],
[[0,1],[1,1],[2,1]],
[[0,2],[1,2],[2,2]],
[[0,2],[1,1],[2,0]]]
for i in possiblewin :
if board[i[0][0]][i[0][1]] is not None and board[i[0][0]][i[0][1]] == board[i[1][0]][i[1][1]] and board[i[0][0]][i[0][1]] == board[i[2][0]][i[2][1]] :
return board[i[0][0]][i[0][1]]
return None
|
def _udev(udev_info, key):
"""
Return the value for a udev key.
The `key` parameter is a lower case text joined by dots. For
example, 'e.id_bus' will represent the key for
`udev_info['E']['ID_BUS']`.
"""
k, _, r = key.partition(".")
if not k:
return udev_info
if not isinstance(udev_info, dict):
return "n/a"
if not r:
return udev_info.get(k.upper(), "n/a")
return _udev(udev_info.get(k.upper(), {}), r)
|
def merge(left, right):
"""Merges two sorted sublists into a single sorted list."""
ret = []
li = ri =0
while li < len(left) and ri < len(right):
if left[li] <= right[ri]:
ret.append(left[li])
li += 1
else:
ret.append(right[ri])
ri += 1
if li == len(left):
ret.extend(right[ri:])
else:
ret.extend(left[li:])
return ret
|
def divide_set_value(state, config):
"""Set Value Divider
Args:
'state': value
Returns:
A list ``[value, value]``. No copying is performed.
"""
value = config['value']
return [value, value]
|
def get_transceiver_sensor_description(name, lane_number, if_alias):
"""
:param name: sensor name
:param lane_number: lane number of this sensor
:param if_alias: interface alias
:return: description string about sensor
"""
if lane_number == 0:
port_name = if_alias
else:
port_name = "{}/{}".format(if_alias, lane_number)
return "DOM {} Sensor for {}".format(name, port_name)
|
def dedup_unique(molecular_barcodes):
"""
Unique duplicate removal
Count all unique UMIs.
Parameters
----------
molecular_barcodes : dict
dictionary with UMIs as keys and UMI counts as values
Returns
----------
int
Number of UMI groups
"""
return len(molecular_barcodes.keys())
|
def user_authorization(packet):
"""
Returns the user's authorized duration in seconds, if unauthorized the return value
will be 0.
"""
minute = 60
return 3 * minute
|
def is_falsy(x):
"""
Check if argument is falsy.
This is the same as calling ``not bool(x)``
"""
return not bool(x)
|
def sweep_info_table(sweep_results) -> str:
"""Return a string that is the summary of all sweep configurations and averages that ran."""
info_str = (
"<H2>Sweep Results</H2>\n"
'<TABLE border="1">\n'
' <TR align="center">\n'
" <TH>Pretap</TH><TH>Posttap</TH><TH>Mean(bit errors)</TH><TH>StdDev(bit errors)</TH>\n"
" </TR>\n"
)
if sweep_results:
for settings, bit_error_mean, bit_error_std in sweep_results:
info_str += ' <TR align="center">\n'
info_str += (
f" <TD>{settings[0]}</TD><TD>{settings[1:]}</TD><TD>{bit_error_mean}</TD><TD>{bit_error_std}</TD>\n"
)
info_str += " </TR>\n"
info_str += "</TABLE>\n"
return info_str
|
def cut_levels(nodes, level):
"""
For cutting the nav_extender levels if you have a from_level in the navigation.
"""
result = []
if nodes:
if nodes[0].level == level:
return nodes
for node in nodes:
result += cut_levels(node.childrens, level)
return result
|
def manipulatePartialChargesTag(charges):
"""Transform charges from float to string format."""
value = ''
for charge in charges:
value += str(charge) + '\n'
return value
|
def to_bool(s):
"""Converts a string to a boolean"""
from distutils.util import strtobool
return bool(strtobool(s))
|
def make_car(
manufacturer,
type,
**additions):
"""
Build a car profile.
:param manufacturer:
:param type:
:param additions:
:return car:
"""
car = dict()
car['manufacturer'] = manufacturer
car['type'] = type
for k, v in additions.items():
car[k] = v
return car
|
def split_list(alist, wanted_parts=1):
"""
split list
Parameters
----------
alist: list
the split list
wanted_parts: int
the number of parts (default: {1})
Returns
-------
list
"""
length = len(alist)
#return all parts in a list, like [[],[],[]]
return [
alist[i * length // wanted_parts:(i + 1) * length // wanted_parts]
for i in range(wanted_parts)
]
|
def glob_to_regex(pattern):
"""Convert a 'glob' pattern for file name matching to a regular
expression. E.g. "foo.? bar*" -> "foo\.. \bar.*" """
return "^"+pattern.replace(".","\.").replace("*",".*").replace("?",".")+"$"
|
def expand_segment(num_frames, num_target_frames, start_frame, stop_frame):
""" expand the segment"""
num_frames_seg = stop_frame - start_frame + 1
changes = False
num_target_frames = min(num_target_frames, num_frames)
if num_frames_seg < num_target_frames:
while True:
if start_frame > 0:
start_frame -= 1
num_frames_seg += 1
changes = True
if num_frames_seg == num_target_frames:
break
if stop_frame < num_frames - 1:
stop_frame += 1
num_frames_seg += 1
changes = True
if num_frames_seg == num_target_frames:
break
return start_frame, stop_frame, changes
|
def latest_output(link, status=None):
"""get the latest output that each archive method produced for link"""
latest = {
'title': None,
'favicon': None,
'wget': None,
'warc': None,
'pdf': None,
'screenshot': None,
'dom': None,
'git': None,
'media': None,
'archive_org': None,
}
for archive_method in latest.keys():
# get most recent succesful result in history for each archive method
history = link.get('history', {}).get(archive_method) or []
history = filter(lambda result: result['output'], reversed(history))
if status is not None:
history = filter(lambda result: result['status'] == status, history)
history = list(history)
if history:
latest[archive_method] = history[0]['output']
return latest
|
def pad(val: str, spaces: int = 2) -> str:
"""Pad val on left and right with `spaces` whitespace chars
Arguments:
val {str} -- string to pad
Keyword Arguments:
spaces {int} -- number of spaces to pad on either side (default: {2})
Returns:
str -- padded string
"""
pad_str = ' ' * spaces
return '{0}{1}{0}'.format(pad_str, val)
|
def base64_encode(encvalue):
""" Base64 encode the specified value. Example Format: SGVsbG8gV29ybGQ= """
try:
basedata = encvalue.encode("Base64")
except:
basedata = "There was an error"
return(basedata)
|
def adjust_axial_sz_px(n: int, base_multiplier: int = 16) -> int:
"""Increase a input integer to be a multiple of mase_multiplier."""
remainder = n % base_multiplier
if remainder == 0:
return n
else:
return n + base_multiplier - remainder
|
def count_pattern(genome: str, pattern: str) -> int:
"""
Medium (half the time of counter like 9.5 sec for 10000 runs like below)
"""
count = 0
for i in range(0, len(genome) + 1 - len(pattern)):
if genome[i: i + len(pattern)] == pattern:
count += 1
return count
|
def _identify_tag_combination(tags_dict, test_tags_dict, true_value=True, none_value=None,
**unused):
"""Test whether there all of a particular combination of tags are in ``tags_dict``.
tags_dict : :obj:`dict`
Dictionary of tags related to OSM element
test_tags_dict : :obj:`dict`
Dictionary of tags (key:value pairs) that must be present in ``tags_dict``
true_value : any type, optional, default = ``True``
Value to return if all specified tags are found.
none_value : any type, optional, default = ``None``
Value to return if not all of the specified tags are found.
Returns
-------
``true_value`` or ``none_value``
"""
findings = []
for key, value in test_tags_dict.items():
if key in tags_dict and value == tags_dict[key]:
findings.append(True)
else:
findings.append(False)
if all(findings):
return true_value
else:
return none_value
|
def join_infile_path(*paths):
"""
Join path components using '/' as separator.
This method is defined as an alternative to os.path.join, which uses '\\'
as separator in Windows environments and is therefore not valid to navigate
within data files.
Parameters:
-----------
*paths: all strings with path components to join
Returns:
--------
A string with the complete path using '/' as separator.
"""
# Join path components
path = '/'.join(paths)
# Correct double slashes, if any is present
path = path.replace('//', '/')
return path
|
def compress(s):
"""
This solution compresses without checking. Known as the RunLength Compression algorithm.
"""
# Begin Run as empty string
r = ""
l = len(s)
# Check for length 0
if l == 0:
return ""
# Check for length 1
if l == 1:
return s + "1"
#Intialize Values
last = s[0]
cnt = 1
i = 1
while i < l:
# Check to see if it is the same letter
if s[i] == s[i - 1]:
# Add a count if same as previous
cnt += 1
else:
# Otherwise store the previous data
r = r + s[i - 1] + str(cnt)
cnt = 1
# Add to index count to terminate while loop
i += 1
# Put everything back into run
r = r + s[i - 1] + str(cnt)
return r
|
def resize_pts(pts, ow, oh, nw, nh, pos_w, pos_h):
"""
calculate coo of points in a resized img
in pts pair of coo (x,y)
"""
new_pts = []
for p in pts:
ox = p[0]
oy = p[1]
newx = (ox/float(ow)*nw) + pos_w
newy = (oy/float(oh)*nh) + pos_h
new_pts.append((newx, newy))
return new_pts
|
def max_contig_sum(L):
""" L, a list of integers, at least one positive
Returns the maximum sum of a contiguous subsequence in L """
#YOUR CODE HERE
work_L = L
max_value = 0
current_value = 0
max_current_combo = []
current_combo = []
while len(work_L) > 0:
for i in range(len(work_L)):
current_combo.append(work_L[i])
current_value += work_L[i]
if current_value > max_value:
max_value = current_value
max_current_combo = current_combo[:]
del current_combo[:]
current_value = 0
del work_L[0]
print(max_current_combo)
return max_value
|
def reverse_string(string):
"""
Given a string, recursively returns a reversed copy of the string.
For example, if the string is 'abc', the function returns 'cba'.
The only string operations you are allowed to use are indexing,
slicing, and concatenation.
string: a string
returns: a reversed string
"""
if string == "":
return ""
else:
return string[-1] + reverse_string(string[:-1])
|
def get(attribute_name, json_response, default=None):
"""
Get an attribute from a dictionary given its key name.
:param attribute_name: Attribute name.
:param json_response: Dictionary where the attribute should be.
:param default: Value that has to be returned if the attribute is not there.
:return: Attribute value.
"""
return default if not json_response or attribute_name not in json_response else json_response[attribute_name]
|
def change_parameter_unit(parameter_dict, multiplier):
"""
used to adapt the latency parameters from the earlier functions according to whether they are needed as by year
rather than by day
:param parameter_dict: dict
dictionary whose values need to be adjusted
:param multiplier: float
multiplier
:return: dict
dictionary with values multiplied by the multiplier argument
"""
return {
param_key: param_value * multiplier for param_key, param_value in parameter_dict.items()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.