content stringlengths 42 6.51k |
|---|
def CheckListForSameTypeOfObjects( l, e ) :
"""For internal use only."""
if( l == e ) : return 0
t = type( l[0] )
for i in l :
if ( t != type( i ) ) : return 1
return 0 |
def color_to_html(color):
"""
Convert color to HTML color code.
:param color: (int, int, int)
:return: str
"""
if len(color) != 3:
raise Exception('Three color properties required')
return '#' + ('{:0<2}'*3).format(*map(lambda s: format(s, 'x'), color)).upper() |
def add_to_dictionary(dictionary: dict, key: str, value) -> dict:
"""
Adds a value to a dictionary with a given key
Parameters
----------
dictionary:
The dictionary to add the key-value pair to.
key:
The key to be added for the value to be added.
Value:
... |
def clean_names(lines, ensure_unique_names=False, strip_prefix=False,
make_database_safe=False):
"""
Clean the names.
Options to:
- strip prefixes on names
- enforce unique names
- make database safe names by converting - to _
"""
names = {}
for row in lines:
... |
def desired_caps(apk_path, apk_name,
platform_version='4.4',
device_name='Android Emulator'):
"""Return capabilities related to sauce devices."""
return {
'name': apk_name,
'app': 'sauce-storage:{}'.format(apk_name),
'platformName': 'Android',
'd... |
def map_transactions(transactions, mapping):
"""
Compare all transactions to a dictionary with payees and categories
"""
mappedtransactions = []
mapcounter = 0
for date, amount, desc, payee, category in transactions:
for identifier in mapping.keys():
if identifier.lower() in ... |
def get_cont_dist(ins_1, ins_2, norm=2):
""" get dimensional distance for continuous data
Parameters: ins_1 (nd-array) - array 1
ins_2 (nd-array) - array 2
norm (int) - type of norm use, default is 2
Returns: dist (array) - the dimenional distance between ins_1 and ins_2
... |
def abspath(path):
"""Convert the given path to an absolute path.
Since FS objects have no concept of a 'current directory' this simply
adds a leading '/' character if the path doesn't already have one.
"""
if not path.startswith('/'):
return u'/' + path
return path |
def can_concat(feds):
"""
Determines whether or not FED3_Files can be concatenated, (based on whether
their start and end times overlap).
Parameters
----------
feds : array
an array of FED3_Files
Returns
-------
bool
"""
sorted_feds = sorted(feds, key=lambda x: x.s... |
def rhombus_area(diagonal_1, diagonal_2):
"""Returns the area of a rhombus"""
# You have to code here
# REMEMBER: Tests first!!!
area = (diagonal_1 * diagonal_2) / 2
return area |
def get_service_value(v, s, c):
"""Get service value.
Returns a specified value from a
given Portainer service.
Args:
v: Key for the service value
s: Portainer service name
c: Lisf of containers
Returns:
Service value.
"""
return list(map(lambda x: x[v], fi... |
def reward_min_waiting_time(state, *args):
"""Minimizing the waiting time.
Params:
------
* state: ilurl.state.State
captures the delay experienced by phases.
Returns:
--------
* ret: dict<str, float>
keys: tls_ids, values: rewards
"""
try:
wait_times = sta... |
def get_ng_build_env(env: str) -> str:
""" Translate the env string for angular that uses a more verbose string. """
return "production" if env == "prod" else "" |
def InRange(val, valMin, valMax):
"""
Returns whether the value `val` is between `valMin` and `valMax`.
:param `val`: the value to test;
:param `valMin`: the minimum range value;
:param `valMax`: the maximum range value.
"""
return val >= valMin and val <= valMax |
def is_prefix(x, pref) -> bool:
"""Check if pref is a prefix of x.
Args:
x: Label ID sequence.
pref: Prefix label ID sequence.
Returns:
: Whether pref is a prefix of x.
"""
if len(pref) >= len(x):
return False
for i in range(len(pref)):
if p... |
def is_variable(var):
"""Checks if the variable is saved in either local or global variables.
# uncomment to test
>>> is_variable('__doc__')
True
"""
return ( var in locals() or var in globals() ) |
def primes_sieve(limit):
""" Sieve of Eratosthenes. """
limitn = limit + 1
not_prime = set()
primes = []
for i in range(2, limitn):
if i in not_prime:
continue
for f in range(i * 2, limitn, i):
not_prime.add(f)
primes.append(i)
return primes |
def getMax(array):
"""
Maximum of an array of floats or ints with positive values
"""
maximum = 0
for v in array:
maximum = max(v, maximum)
return maximum |
def freq_dict(lst):
"""Returns a dictionary with keys of unique values in the given list and values representing the count of occurances.
Parameters
----------
lst (list)
a list of items to determine number of occurances for.
Returns
-------
dict
a dictionary of the forma... |
def _update_col_names(x, i):
"""Internal helper function to convert the names of the initial dataset headers
Keyword Arguments:
x {string} -- name of the column (can be None)
i {integer} -- integer representing the number of the column
Returns:
string - returns simplified string ver... |
def find_digits(n):
"""
:type n: int
:rtype: int
"""
return sum(1 for d in n if int(d) != 0 and int(n) % int(d) == 0) |
def to_kwh(m):
"""
This function converts a mass flow rate in klbs/hr of steam
to an energy in kWh. Known values are currently hard coded.
Parameters:
-----------
m : float
This is the mass of Abbott steam in klbs/hr
Returns:
--------
kwh : float
The energy equivale... |
def get_line_indentation_spacecount(line: str) -> int:
""" How many spaces is the provided line indented? """
spaces: int = 0
if (len(line) > 0):
if (line[0] == ' '):
for letter_idx in range(len(line)):
if (line[letter_idx + 1] != ' '):
spaces = letter... |
def time_to_seconds(days: int = 0, hours:int = 0, minutes:int = 0, seconds: float = 5):
"""
Converts argument's time to pure seconds
"""
hours = hours + 24*days
minutes = minutes + 60*hours
seconds = seconds + 60*minutes
return seconds |
def flatten_array(a):
"""Return a mapping from a yaml array of mappings."""
return dict((next(iter(item.keys())), item[next(iter(item.keys()))]) for item in a) |
def replace_other_char (strings):
"""
Replaces characters other than Chinese characters and identifiers
:param strings: need replaces string
:return: new string
"""
new_string = ''
for i in strings:
if u'\u4e00' <= i <= u'\u9fff':
new_string += i
elif i.... |
def _delays_to_slice(delays):
"""Find the slice to be taken in order to remove missing values."""
# Negative values == cut off rows at the end
min_delay = None if delays[-1] <= 0 else delays[-1]
# Positive values == cut off rows at the end
max_delay = None if delays[0] >= 0 else delays[0]
return... |
def replace_empty(x):
"""
replace the empty value with unknown
"""
if x.strip() == '':
return 'Unknown'
else:
return x |
def ntp2ms(ntp: int) -> int:
"""Convert NTP time to milliseconds."""
return ((ntp >> 10) * 1000) >> 22 |
def build_insert(table, to_insert):
"""
Build an insert request.
Parameters
----------
table : str
Table where query will be directed.
to_insert: iterable
The list of columns where the values will be inserted.
Returns
-------
str
Built query.
"""
sq... |
def snake_to_camel_case(snake_str: str) -> str:
"""
Convert a `snake_case` string to `CamelCase`.
.. code-block:: python
>>> snake_to_camel_case("snake_case")
"SnakeCase"
Args:
snake_str (str): String formatted in snake_case
Returns:
str: String formatted in Camel... |
def next_perm(digits):
"""Generate next Lexographic permutation."""
i = -1
for i_ in range(1, len(digits)):
if digits[i_-1] < digits[i_]:
i = i_
if i == -1:
return False
suffix = digits[i:]
prefix = digits[:i-1]
pivot = digits[i-1]
j = 0
for j_ in range(i,... |
def _indexes(gumt, gdmt, gwmt, gdnt):
"""Count Understemming Index (UI), Overstemming Index (OI) and Stemming Weight (SW).
:param gumt, gdmt, gwmt, gdnt: Global unachieved merge total (gumt),
global desired merge total (gdmt),
global wrongly merged total (gwmt) and
global desired non-merge to... |
def _truncate_decimal(num, precision):
"""To avoid coordinates whose precision greatly exceeds their accuracy."""
return int(num * 10**precision) / 10**precision |
def _q_regs_2q_qasm_gate(qasm_gate):
"""Obtains a a list of tuples *[(q_reg, q_arg), (q_reg, q_arg)]* from a two qubit gate QASM string,
where *q_reg* is a quantum register name and *q_arg* is the quantum register index.
Args:
qasm_gate (str): a two qubit gate QASM string
R... |
def to_snake_case(name):
"""Convert a name from camelCase to snake_case. Names that already are
snake_case remain the same.
"""
name2 = ""
for c in name:
c2 = c.lower()
if c2 != c and len(name2) > 0 and name2[-1] != "_":
name2 += "_"
name2 += c2
return name2 |
def _individual_settings(update_result):
"""Helper that returns the number of settings that were updated."""
return sum(
len(settings_in_a_group)
for settings_in_a_group in update_result.values()
) |
def _trim(_vector):
"""Return _vector with all trailing zeros removed."""
if not _vector or len(_vector) == 1:
return _vector
ind = len(_vector)
while _vector[ind - 1] == 0 and ind > 0:
ind -= 1
return _vector[:ind] |
def remove_beginend_whitespaces(input_string):
"""
Applies lstrip and rstrip methods to input_string
:param input_string: string to be stripped
:return: stripped input_string or None, if string is None or ""
"""
if input_string:
input_string = input_string.lstrip()
return input_... |
def _format_maven_jar_name(group_id, artifact_id):
"""
group_id: str
artifact_id: str
"""
return ("%s_%s" % (group_id, artifact_id)).replace(".", "_").replace("-", "_") |
def cut_follow(deck_size, position, cut_value):
"""Get new position after cutting deck at cut_value."""
return (position - cut_value) % deck_size |
def build_input_args(mts_groups:dict) -> dict:
"""
build ffmpeg input arguments based on mts_groups directory
"""
groups_args = {}
for group, files in mts_groups.items():
if len(files) > 1:
cmd = " -i \"concat:"
else:
cmd = " -i \""
is_first = True
... |
def timeval(string):
"""Returns the numeric version of a time.
Inputs:
string (str): String representing a time.
Returns:
String representing the absolute time.
"""
if string.endswith("am") or string.endswith(
"pm") and string[:-2].isdigit():
numval = int(string... |
def pct_gc(seq, points=2):
"""return percent GC of sequence (2 decimal points)"""
seq = seq.upper()
return round((seq.count('G') + seq.count('C')) / len(seq) * 100, points) |
def findClosest(targetVal, valList):
""" Searches valList for closest match to targetVal and returns the
corresponding valList index"""
diffs = [abs(x-targetVal) for x in valList]
return diffs.index(min(diffs)) |
def visitor_name(node_name: str) -> str:
"""
Returns the visitor_method name for `node_name`, e.g.::
>>> visitor_name('expression')
'on_expression'
"""
# assert re.match(r'\w+$', node_name)
return 'on_' + node_name |
def get_entities_bio(seq):
"""Gets entities from sequence.
note: BIO
Args:
seq (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
seq = ['B-PER', 'I-PER', 'O', 'B-LOC', 'I-PER']
get_entity_bio(seq)
#output
... |
def getattrrec(object, name, *default):
"""Extract the underlying data from an onion of wrapper objects.
``r = object.name``, and then get ``r.name`` recursively, as long as
it exists. Return the final result.
The ``default`` parameter acts as in ``getattr``.
See also ``setattrrec``.
"""
... |
def match_candidate_span_keyphrase(segment_span, candidate_span_segment, keyphrases):
"""Receive element from dataset and return keyphrases ids with token indices"""
start, end = segment_span
token_keyphrases_ids = map(lambda token: token[3], candidate_span_segment)
keyphrases_ids = set(kpid for kps_ids... |
def add_object_attribute(new_obj_attribute_list, output_xml):
"""
Check if input list is not empty, write in xml for each element and return update list if some
updates has been made
Parameters:
new_obj_attribute_list ([Attribute, (Object, value)]) : New described attributes
... |
def sorted_array(len_arr):
"""
Function generates a sorted array of size 2 ** n.
"""
array = []
for i in range(len_arr):
array.append(i)
return array |
def Moffat2D(x, y, amplitude=1.0, x_0=0.0, y_0=0.0, gamma=1.0, alpha=1.0):
"""Two dimensional Moffat function."""
rr_gg = ((x - x_0) ** 2 + (y - y_0) ** 2) / gamma ** 2
return amplitude * (1 + rr_gg) ** (-alpha) |
def _completeness_todo(columns, df):
"""
Returns what to compute for each column in dict form, given the metric parameters.
:param columns:
:type columns: list
:param df:
:type df: DataFrame
:return: Dict containing what to run (pandas functions names or named lambdas) for each column.
... |
def sents_sync(ck_sents, sj_sents):
"""
check if two sentences are same.
if there're differences, return the list to banish.
:param ck_sents:
:param sj_sents:
:return:
"""
# ck_sents = mk_sents_with_lemma(ck_file, 3)
# sj_sents = mk_sents_with_lemma(sj_file, 2)
# ck_sents = mk_s... |
def transpose(a):
"""
transposes a matrix
>>> m = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> transpose(m)
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
"""
return list(zip(*a)) |
def clean_dropbox_link(dropbox_url):
"""
Dropbox links should be en-mass downloaed from dl.dropbox
DEPRICATE?
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_grabdata import * # NOQA
>>> dropbox_url = 'www.dropbox.com/s/123456789abcdef/foobar.zip?dl=0'
>>> cleaned_ur... |
def find_interface_with_greater_ip(topo, router, loopback=True, interface=True):
"""
Returns highest interface ip for ipv4/ipv6. If loopback is there then
it will return highest IP from loopback IPs otherwise from physical
interface IPs.
* `topo` : json file data
* `router` : router for which h... |
def get_num_from_bond(bond_symbol: str) -> int:
"""Retrieves the bond multiplicity from a SMILES symbol representing
a bond. If ``bond_symbol`` is not known, 1 is returned by default.
:param bond_symbol: a SMILES symbol representing a bond.
:return: the bond multiplicity of ``bond_symbol``, or 1 if
... |
def calcGoldenNumber(year):
""" Returns the Golden Number (Aureus numerus) for a given year
"""
golden_num = (year + 1) % 19
if golden_num == 0:
golden_num = 19
return golden_num |
def division_euclidienne_decimale(a, b):
"""renvoie le quotient et le reste de la division euclidiennede a par b"""
q = 0
while a > b:
n = 0
while 10 ** n * b <= a:
n += 1
n -= 1
c = 0
while c * 10 ** n * b <= a:
c += 1
c -= 1
q... |
def los2lol(listOsets):
""" Convert a list of sets [{},{},..,{}] to a list of of lists [[], [], ..., []].
"""
lists = []
for i in listOsets:
lists.append(list(i))
return lists |
def get_divisible_by(numbers, divisor):
"""d)"""
numbers_divisible_by = []
for number in numbers:
if number % divisor == 0:
numbers_divisible_by.append(number)
return numbers_divisible_by |
def _is_arg_safe(ss):
"""Check if `str` is safe as argument to `argparse`."""
if len(ss) == 0:
return False
safe = ss[0] != "-"
return safe |
def separate_phoneme_tone(pinyin_str):
"""
separate phoneme and tone from given pinyin string. tone is set to 0 if there is not any
:param pinyin_str: pinyin string
:return:
phoneme(str) and tone(int)
example:
print(separate_phoneme_tone('wan3')) => ('wan', 3)
print(separate_... |
def flatlistindex2doublelist(flatlist, indexarray):
"""
Takes a flattened list and an index array, returns a list of lists
:param flatlist: flat list of objects (preserving order)
:param indexarray: array indexing which original list it came from
:return listlist: list of lists of objects
"""
... |
def _get_base(obj):
"""Unwrap decorators to retrieve the base object.
Parameters
----------
obj : object
Object.
Returns
-------
object
The base object found or the input object otherwise.
"""
if hasattr(obj, "__func__"):
obj = obj.__func__
elif isinstan... |
def _make_urls(row):
"""
Supports up to 5 URLS per row as defined in the spec
"""
urls = []
for i in range(9, 17, 2):
try:
if len(row[i]) > 0 and len(row[i+1]) > 0:
urls.append({'title': row[i],
'href': row[i + 1]})
except Inde... |
def sort_versions(versions):
""" Returns list of sorted
versions of format x.x.x
"""
return sorted(versions, key=(lambda x: list(map(int, x.split('.'))))) |
def count_sequential_elem_increases(arr: list) -> int:
"""
Args:
arr (list): list of numeric values
Returns:
count of the number of times that a value increases from the previous array entry
"""
return sum(arr[i-1] < arr[i] for i in range(1, len(arr))) |
def estimate_gain(halite, dis, t, collect_rate=0.25, regen_rate=0.02):
"""
Calculate halite gain for given number of turn.
"""
if dis >= t:
return 0
else:
# Halite will regenerate before ship arrives
new_halite = halite * (1 + regen_rate) ** max(0, dis - 1)
# Ship cos... |
def get_contiguous_strides(shape):
"""Returns a new strides that corresponds to a contiguous traversal of shape"""
stride = [0] * len(shape)
s = 1
for i in reversed(range(len(shape))):
stride[i] = s
s *= shape[i]
return tuple(stride) |
def longest_common_subsequence(s1: str, s2: str) -> int:
"""
Space-optimized version of LCS.
Let m and n be the lengths of two strings.
Runtime: O(mn)
Space Complexity: O(min(m, n))
"""
m, n = len(s1), len(s2)
if m < n:
s1, s2 = s2, s1
L = [0] * (n + 1)
for a in s1:
... |
def isEOS( path ):
"""Tests whether this path is a CMS EOS (name starts with /eos...)"""
return path.startswith('/eos') or path.startswith('root://eoscms.cern.ch//eos/cms') |
def isLastPage(page_num, count_of_combos, per_page):
"""Return True if this is the last page in the pagination"""
if count_of_combos <= (page_num * per_page):
return True
return False |
def filter_dict_by_key(d, keys):
"""Filter the dict *d* to remove keys not in *keys*."""
return {k: v for k, v in d.items() if k in keys} |
def add_ngram(sequences, token_indice, ngram_range=2):
"""
Augment the input list of list (sequences) by appending n-grams values.
Example: adding bi-gram
>>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]]
>>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017}
>>> add_ngram(sequences, token_in... |
def cube(x):
""" Returns cube of an integer input value """
if isinstance(x, int):
return x*x*x
else:
raise TypeError |
def is_png(data: bytes) -> bool:
"""
Check if the given data is a PNG.
Parameters:
data (bytes): The data to check.
Returns:
True if the data is a PNG, False otherwise.
"""
return data[:8] == b"\211PNG\r\n\032\n" |
def intadd(num1: int, num2: int) -> int:
"""Adds two numbers, assuming they're both positive integers.
Parameters
----------
num1, num2 : int
Positive integers
Returns
-------
int
Resulting positive integer
Raises
------
ValueError
If either number is n... |
def extract_features_in_order(feature_dict, model_features):
"""
Returns the model features in the order the model requires them.
"""
return [feature_dict[feature] for feature in model_features] |
def calc_hash(lst: list) -> str:
"""
Internal use only.
Calculates md5sum of given command with it's byte-string.
"""
to_hash = " ".join(lst).encode("ascii")
return __import__("hashlib").md5(to_hash).hexdigest() |
def parse_values(s):
"""Parse `key: value` lines"""
lines = s.splitlines()
return {k.strip(): v.strip() for k, v in (l.split(':') for l in lines)} |
def sublists(alist):
"""
All sublists of the given list.
"""
if not alist:
return [[]]
subsub = sublists(alist[1:])
return subsub + [[alist[0]] + x for x in subsub] |
def dictionary_has_data(dictionary_to_check: dict) -> bool:
"""
Check to see if the dictionary has any data.
:param dictionary_to_check: The dictionary to check.
:return: True if there is any data. False otherwise.
"""
return len(dictionary_to_check.values()) > 0 |
def find_volume(radar, lidar):
"""
>>> find_volume([[100]],[[210]])
21.0
>>> find_volume([[99]],[[100]])
0.0
>>> find_volume([[0]],[[100]])
0.0
>>> find_volume([[150]],[[0]])
0.0
"""
volume = 0
for y in range(len(radar)):
for x in range(len(radar[y])):
... |
def prettylist(list_):
"""
Filter out duplicate values while keeping order.
"""
if not list_:
return ''
values = set()
uniqueList = []
for entry in list_:
if not entry in values:
values.add(entry)
uniqueList.append(entry)
return uniqueList[0] if... |
def state2tuple(key):
"""
:returns: the separated agent name and feature from the given key
:rtype: (str,str)
"""
index = key.find("'")
if index < 0:
return None
else:
return key[:index],key[index+3:] |
def unpack(s):
"""Convenience function to get a list as a string without the braces.
Parameters
----------
s : list
The list to be turned into a string.
Returns
-------
string
The list as a string.
"""
x = " ".join(map(str, s))
return x |
def simplify_name(name):
"""Remove host/port part from an image name"""
i = name.find('/')
if i < 0:
return name
maybe_url = name[:i]
if '.' in maybe_url or ':' in maybe_url:
return name[i + 1:]
return name |
def space_boundaries_re(regex):
"""Wrap regex with space or end of string."""
return rf"(?:^|\s)({regex})(?:\s|$)" |
def fibSeqToNth(n):
"""Returns the Fibonacci sequences to the nth entry as a list of
integers."""
if not isinstance(n, int):
raise TypeError('n should be a positive integer.')
return None
if n < 0:
raise ValueError('n should be a positive integer.')
return None
res... |
def fibonacci(n):
"""
Returns the next Fibonacci sequence for a given `n`.
"""
if n <= 2:
f = 1
else:
f = fibonacci(n - 1) + fibonacci(n - 2)
return f |
def readVector(text):
"""Reads a length-prepended vector from text 'n v1 ... vn'"""
items = text.split()
if int(items[0])+1 != len(items):
raise ValueError("Invalid number of items")
return [float(v) for v in items[1:]] |
def units_map(param, mm=False):
"""
Units of parameters
"""
L = "cm"
if mm:
L = "mm"
if param in ("temps", "Tl", "Tt", "T"):
unit = " [mK]"
elif param[0] == "I":
unit = " [A]"
elif (
param[:2] == "r0"
or param[0] in ("L", "W", "R", "A")
or ... |
def float_string(s, verbose=True):
"""Try parsing a string as float, fixing errors if the string is #.######-### (e.g. not #.######E-###, missing E). Return the correct string."""
try:
float(s)
except ValueError:
x = s.split('-')
new_s = ''.join(x[:-1]) + 'E-' + x[-1]
... |
def flipCC(codelChooser: int) -> int:
"""
Flips the codelChooser 0 -> 1, 1 -> 0
:param codelChooser: unflipped codelChooser
:return: flipped codelChooser
"""
return int(not codelChooser) |
def img_coords_to_coords(dx, dy):
"""Converts image coordinates to real-world coordinates"""
dphi, dth = dx, dy
return dphi, dth |
def cpu_count(sinfo_data):
"""Compute the number of cores per node.
This function is obsolete. Change to compute the number of cores per
partition.
"""
count = {}
for i,node_name in enumerate(sinfo_data['nodehost']):
ncpus = sinfo_data['allcpus'][i]
count.setdefault(node_name,... |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the in... |
def calc_ber(tpr, fpr):
"""calculate the balanced error rate
Args:
tpr (array or int): true positives
fpr (array or int): false positives
Returns:
array or int: balanced error rate
"""
return 0.5 * ((1- tpr)+fpr) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.