content stringlengths 42 6.51k |
|---|
def get_node(node_name, nodes):
"""Gets the index of the node"""
for i in range(0, len(nodes)):
if nodes[i][0] == node_name:
return nodes[i] |
def makeFuture(key):
"""
:returns: a reference to the given state features' projected future value
:rtype: str
"""
if key[-1] == "'":
raise ValueError('%s is already a future key' % (key))
else:
return key+"'" |
def rgb_to_html(r: float, g: float, b: float) -> str:
"""Convert given rgb color to an HTML code"""
return "#%02X%02X%02X" % (r, g, b) |
def intersect(lhs_list, rhs_list):
"""Return the common elements of two lists
Parameters
----------
lhs_list : list
A list of some type that can be compared using `in`
rhs_list : list
A list of some type that can be compared using `in`
Returns
-------
list
A lis... |
def str2list(s, sep=',', d_type=int):
"""
Change a {sep} separated string into a list of items with d_type
:param s: input string
:param sep: separator for string
:param d_type: data type of each element
:return:
"""
if type(s) is not list:
s = [d_type(a) for a in s.split(sep)]
... |
def longest_palin_subsequence(str1):
"""
dp[size][i] = dp[size-2][i+1] + 2 if str[i] == str[j]
else
dp[size][i] = max(dp[size-1][i], dp[size-1][i+1])
where dp[size][i] = answer for substring of size `size` starting at index `i`.
"""
str_len = len(str1)
longest_palin = [[0 for j in range(... |
def clean_email(raw_email):
"""Clean a raw email address from the log file.
Arguments:
raw_email [string] -- from=<user@domain.com>
Returns:
[string] -- user@domain.com
"""
temp1 = raw_email.split('from=<')[1]
return temp1.rstrip('>') |
def preprocess_cif_category(cif, label):
"""
The mmcif dictionary values are either str or list(), which is a bit
tricky to work with. This method makes list() of all of them in
order to parse all of the in the same way.
Args:
vif (dict): mmcif category with the parser output.
label... |
def check_validity_of_kings(played_cards):
"""
Helper function used to check validity of played packs of kings.
:param played_cards: list of tuples with played by player cards
:return: True if play is valid, False otherwise
"""
valid = True
first_card = played_cards[0]
active_colors, nor... |
def merge_names(names):
"""Merge names of environments by leaving the last non-blank one"""
actual_names = [name for name in names if name]
if actual_names:
return actual_names[-1] |
def _dedup_list(input_list):
"""
Function that removes duplicates from a list
"""
deduped = []
for idx, item in enumerate(input_list):
if item not in input_list[idx + 1:]:
deduped.append(item)
return deduped |
def _filter_keys(keys, indices):
"""
Returns the list of keys at specified indices.
`keys` is a list.
`indices` is slice or iterable.
"""
if isinstance(indices, slice):
return keys[indices]
else:
return [keys[i] for i in indices] |
def _parse_enum(type, item):
"""Try to parse 'item' (string or integer) to enum 'type'"""
try:
return type[item]
except:
return type(item) |
def get_coverage(bb1, bb2):
"""
Calculate the coverage of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb2 : dict
Keys: {'x... |
def calc_num_weights3(num_inputs, layer_sizes, num_outputs, m_trainable_arr, b_trainable_arr):
"""
accounts for fact that certain weight matrices / bias vectors may not be
trainable
"""
n = 0
if len(layer_sizes) == 0:
if m_trainable_arr[0]:
n += num_inputs * num_outputs
if b_trainable_arr[0]:
n += num_o... |
def get_host_from_metadata(metadata, name):
"""
Get host definition from job metadata base on name.
Returns:
(host, domain)
"""
domains = metadata.get("domains", [])
for domain in domains:
for host in domain.get("hosts", []):
if host["name"] == name:
retu... |
def title_case(sentence):
"""
Convert a string to title case.
Title case means that the first character of every word is capitalized. Otherwise,
lowercase.
Parameters
----------
sentence: string
String to be converted to title case
Returns
-------
ret: string
I... |
def bytes2human(num):
"""
Convert a size into a human readable format.
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
nume = ''
if num < 0:
num = num * -1
nume = '-'
for pos, sym in enumerate(symbols):
prefix[sym] = 1 << (pos+1)*10
for sym ... |
def get_target(i, nns):
"""
Used in the reordering routine, determines which 'class' we
actually want in the given index [i]. See more details in the
description of reorder_inplace
inputs:
i, i8, index
nns, i8[4], cumulative sum of number of points in each class
returns:
... |
def hex_array_to_ascii(__hex_array):
"""
translates array of hex integers into ascii string
"""
return ''.join(chr(c) for c in __hex_array) |
def is_int(string):
"""
Check if `string` can be converted
into an int.
Parameters
----------
string : str
String to check.
Returns
-------
check : bool
True if `string` can be converted.
"""
try:
int(string)
return True
except ValueError:
return False |
def get_spaced_colors(n):
"""
Creates and array of n different colors -- code found at the following link:
https://www.quora.com/How-do-I-generate-n-visually-distinct-RGB-colours-in-Python
"""
max_value = 16581375 #255**3
interval = int(max_value / n)
colors = [hex(I)[2:].zfill(6) for I in... |
def is_digit(s: str) -> bool:
"""Alternative to s.isdigit() that handles negative integers
Args:
s (str): A string
Returns:
bool: Flag indicating if the input string is a signed int
"""
try:
int(s)
return True
except:
return False |
def onecase(case):
"""Check if the binary string is all ones"""
if case == "1" * len(case):
return True
else:
return False |
def quote_with_backticks(identifier):
"""Quote the given identifier with backticks, converting backticks (`) in
the identifier name with the correct escape sequence (``).
identifier[in] identifier to quote.
Returns string with the identifier quoted with backticks.
"""
return "`" + identifier.r... |
def Unwrap(data, mod):
"""Returns `data` unwrapped modulo `mod`. Does not modify data.
Adds integer multiples of mod to all elements of data except the
first, such that all pairs of consecutive elements (a, b) satisfy
-mod / 2 <= b - a < mod / 2.
E.g. Unwrap([0, 1, 2, 0, 1, 2, 7, 8], 3) -> [0, 1, 2, 3,
4,... |
def percentage(part, whole):
"""
Returns percentage with 2 decimals. If `whole` <= 0, returns -1.00.
"""
if whole <= 0:
return -1.00
return format(100 * (float(part) / (float(whole) if whole != 0 else 1)), '.2f') |
def parse_with_variable_name(stack_frames, constructor_name):
"""Analyses the provided stack frames and parses Python with expressions like
with `constructor_name`(...) as variable_name:
from the caller's call site and returns the name of the variable named in the statement as a string.
If a with s... |
def is_callable_default(x):
"""Checks if a value is a callable default."""
return callable(x) and getattr(x, '_xonsh_callable_default', False) |
def IsNestedField(d, field_list):
"""Examine a dict of dicts, to see if the nested field name exists."""
for f in field_list:
try:
d = d[f]
except (KeyError, ValueError):
return False
return True |
def slice_list(in_list, lens):
"""Slice a list into several sub lists by a list of given length.
Args:
in_list (list): The list to be sliced.
lens(int or list): The expected length of each out list.
Returns:
list: A list of sliced list.
"""
if isinstance(lens, int):
a... |
def as_uppercase(tokens):
""" Converts the token to uppercase if possible. """
return ''.join(tokens).upper() if tokens else None |
def optimal_row_and_column_count_for_subplots(n):
"""Returns the optimal number of rows and columns for a given number of subplots
:param int n: number of subplots required
:return: n_cols, n_rows
"""
n_cols = 1
n_rows = 1
increase_next = 'cols'
while n_rows * n_cols < n:
if inc... |
def no_errors(status: int) -> bool:
"""
>>> no_errors(0)
True
>>> no_errors(0b11111111111)
False
"""
return status == 0
# above is a shortcut for:
# (daq_err, sensor_err), overloaded, (_, errs) = decode(status)
# return (
# daq_err == sensor_err == 'no error'
# ... |
def max_quantity(remain, coin, qty):
"""
Calculate max quantity of a coin type to give change
"""
max_qty = 0
while remain >= coin and qty - max_qty > 0:
remain = remain-coin
max_qty += 1
return max_qty |
def check_special_chroms(name):
"""
:param name:
:return:
"""
# check for chimp exceptions
if name in ['chr2A', '2A', '2a', 'chr2a']:
return 21
elif name in ['chr2B', '2B', '2b', 'chr2b']:
return 22
elif name in ['chrX', 'X', 'chrZ', 'Z']:
return 1000
elif nam... |
def convert2(s, numRows):
""" Time complexity: O(len(s)), Space complexity: O(2)
String: P A Y P A L I S H I R I N G
index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13
row: 1 2 3 4 3 2 1 2 3 4 3 2 1 2
period: 2 * (numRows - 1)
"""
if numRows <= 1:
return s
n = len(s)
if num... |
def minimumAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a minimum value above n.
Example:
.. code-block:: none
&target=minimumAbove(system.interface.eth*.packetsSent,1000)
This would only display interfaces ... |
def _subtract_or_na(mdict, x, y):
"""
Shortcut for build_metric_list
"""
try:
return round(mdict[x] - mdict[y], 4)
except:
return "n/a" |
def is_number(s):
"""
Check and parse entered value as a number
"""
try:
int(s)
return True
except ValueError:
return False |
def process_settings(pelicanobj):
"""Sets user specified settings (see README for more details)"""
# Default settings
inline_settings = {}
inline_settings['config'] = {'[]':('', 'pelican-inline')}
# Get the user specified settings
try:
settings = pelicanobj.settings['MD_INLINE']
ex... |
def angleAbsDistance(a, b):
"""Magnitude of the difference between two angles.
Result should always be between 0 and 180.
"""
distanceA = abs((a - b) % 360)
distanceB = abs((b - a) % 360)
return min(distanceA, distanceB) |
def fact_loop(n):
"""
Returns the factorial of a given positive, non-zero integer
using loops.
"""
fact = 1
while n > 0:
fact *= n
n -= 1
return fact |
def truncated_range(value, values):
""" Provides a validator function that returns the value
if it is in the range. Otherwise it returns the closest
range bound.
:param value: A value to test
:param values: A set of values that are valid
"""
if min(values) <= value <= max(values):
r... |
def g(r):
"""
Initial velocity. Radial symmetry so, for this problem, initial velocity
is only a functin of radial position.
Parameters
----------
r : float64
radial position.
Returns
-------
float64 - initial velocity at a given radial position.
"""
b = 0.2;
... |
def CDATA(cdata):
"""Create a CDATA section
Args:
arbitrary_text: as the name suggests
Returns:
<![CDATA[arbitrary_text]]>
"""
return '<![CDATA[%s]]>' % cdata |
def haproxy_backend_masters(hosts, port):
""" This takes an array of dicts and returns an array of dicts
to be used as a backend for the haproxy role
"""
servers = []
for idx, host_info in enumerate(hosts):
server = dict(name="master%s" % idx)
server_ip = host_info['openshift']['... |
def invert_dict(d):
"""
Exchanges keys and values in a dictionary
:param d: dictionary for invertion
:return: inverted dictionary
"""
res = {}
for k, v in d.items():
res[v] = k
return res |
def centroid(vertices):
"""
Returns the centroid of a series of `vertices`.
"""
k, c_x, c_y = 0, 0, 0
for x, y in vertices:
c_x += x
c_y += y
k += 1
return c_x / k, c_y / k |
def find_critical_ratio_av(tau_1,tau_2,tau_3):
"""returns critical ratio defined as the benefit to cost ratio (b/c) at which cooperation is neutral"""
return tau_2/(tau_3-tau_1) |
def startswith(prefix, sequence):
"""
Check if a sequence starts with the prefix.
"""
return len(prefix) <= len(sequence) and all(a == b for a, b in zip(sequence, prefix)) |
def load(row, minimum, maximum):
"""Returns how many numbers lie within `maximum` and `minimum` in a given `row`"""
count = 0
for n in row:
if minimum <= n <= maximum:
count = count + 1
return count |
def is_select(status):
"""Returns true if the first word in status is 'select'."""
if not status:
return False
return status.split(None, 1)[0].lower() == 'select' |
def _parse_line_(line):
""" """
try:
filename, rest = line.split('(')
info, what = rest.split(")")
what = what.replace(":", "")
return [filename.replace(" ","")]+info.split("/")+[what.replace(" [A]","").strip()]
except:
return None |
def splitAt(n, xs):
"""``splitAt :: Int -> [a] -> ([a], [a])``
Returns a tuple where first element is `xs` prefix of length `n` and
second element is the remainder of the list.
"""
return xs[:n], xs[n:] |
def hamming_distance(input_bytes_1: bytes, input_bytes_2: bytes):
"""Takes in two byte strings. Outputs the hamming distance (https://www.tutorialspoint.com/what-is-hamming-distance) between those strings"""
xor_result = ((a ^ b) for (a, b) in zip(input_bytes_1, input_bytes_2))
joined_binary_string = "".join([bin(nu... |
def strip_extension(file_name):
"""
Returns file without extension
"""
return ".".join(file_name.split(".")[:-1]) if file_name else "" |
def return_last(responses):
"""Return last item of a list."""
return responses[-1] |
def format_filename(prefix, suffix, bsz_per_host, seq_len, lower_case=False):
"""docs."""
if lower_case:
case_str = "lower."
else:
case_str = ""
file_name = "{}.lm.seq-{}.bsz-{}.{}{}".format(
prefix, seq_len, bsz_per_host, case_str, suffix)
return file_name |
def drop_probable_entities(X):
"""
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> drop_empty_lists(drop_arabic_numeric(drop_probable_entities([['Catullus'], ['C.', 'VALERIVS', 'CATVLLVS'],['1','2', '2b', '3' ],['I.', 'ad', 'Cornelium'],['Cui... |
def func_eligible_first(k_idx,slack_closed,greedy_closed):
""" Computes an approximation to the expected value of the o.f. value reached by the elegible first algorithm.
Computes the expression (37) en Corollary 16.
Args:
k_idx: Int. Knapsack capacity.
slack_closed: float. The expected... |
def _as_key(name):
"""Convert names to upper case and replace duplicated spaces with one;
return ints unchanged.
"""
if isinstance(name, int):
return name
name = name.upper().strip()
while (' ' in name):
name = name.replace(' ', ' ')
return name |
def last_word(string):
"""Function to get the last word of a sentence in lower case"""
try: return (string.rsplit(None, 1)[-1]).lower()
except: return None |
def list_to_csv(x):
"""Converts a list of str to a comma-separated string."""
return ",".join(x) |
def sumsq(vals):
"""return the sum of the squared values"""
ssq = 0
for val in vals: ssq += (val*val)
return ssq |
def breakArgs(string):
"""turns name(arg1,arg2) into ('name','arg1,arg2')"""
split = string.split('(')
split[1]=split[1][:-1]
return tuple(split) |
def _set_complexity_risk_icon(risk):
"""
Function to find the index risk level icon for complexity risk.
:param float risk: the Software complexity risk factor.
:return: _index
:rtype: int
"""
_index = 0
if risk >= 0.8 and risk < 1.0:
_index = 1
elif risk >= 1.0 and risk <... |
def dict_tags_to_list_tags(tags):
"""
:type tags: typing.Dict[str, str]
:rtype: typing.List[typing.Dict[str, str]]
"""
return [
{
"Key": key, "Value": value
}
for key, value in tags.items()
] |
def dotND(v1, v2):
"""Returns dot product of two nD vectors
(same as itemwise multiplication followed by summation)."""
return sum(vv1 * vv2 for vv1, vv2 in zip(v1, v2)) |
def kld_scaling(iter):
"""
Define a function with which to scale the KL-divergence loss term
as a function of the current iteration.
Parameters
----------
iter : int
Current training iteration
Returns
----------
scaling : float
KL-divergence scaling factor for the curre... |
def _is_data_center_line(line):
"""Determines if line introduces nodes from a Datacenter."""
return line.startswith('Datacenter: ') |
def FriendRequestToJson(requesting_author, requested_author):
"""
Converts a Friend Request object into a JSON-compatible dictionary.
Return None on failure.
"""
if not requesting_author:
return None
if not requested_author:
return None
try:
json_dict = {
... |
def get_line_mode(day_range):
"""
Returns "line" if day range is less than a
certain threshold, otherwise "spline". This
prevents the charts from doing spline interpolation
when heavily zoomed-in, which looks really bad.
"""
if day_range[1] - day_range[0] > 90:
return "spline"
... |
def concat(a, b):
"""Same as a + b, for a and b sequences."""
if not hasattr(a, '__getitem__'):
msg = "'%s' object can't be concatenated" % type(a).__name__
raise TypeError(msg)
return a + b |
def sort_selective(list):
"""
brief : Sort a list with the selective strategy
args :
list : a list of numeric value
Return :
Sorted list in ascending order
Raises :
"""
iLastCompare = len(list)-1 #last position to be compared
for iNotSorted in ran... |
def is_link_field(field):
"""Return boolean whether field should be considered a link."""
return '.' in field |
def asint(text):
"""
Safely converts a string to an integer, returning ``None`` if the string is ``None``.
:type text: str
:rtype: int
"""
if text is not None:
return int(text) |
def get_flat_function(List, idx):
"""Get the idx index of List. If idx >= len(List), return the last element"""
if idx < 0:
return List[0]
elif idx < len(List):
return List[idx]
else:
return List[-1] |
def offset_saturation(hsv, offset):
"""
Offsets the saturation value in 0-1 range by the given offset amount
:param hsv: list(float, float, float), list or tuple representing the hue saturation and value color
:param offset: float, offset value to offset the saturation
:return: list(float, float, fl... |
def merge_disjoint_dicts( dicts ):
"""
Merge a list of dictionaries where none of them share any keys
"""
result = {}
for mapping in dicts:
for key, value in mapping.items():
if key in result:
raise Exception(
"key `{}` defined in two dict... |
def set_limit_into_range(limit, lower, upper):
"""
"limit" must be inside the "lower" and "upper" range, if not, this function returns
the lower or upper values.
"""
return min(max(lower, limit), upper) |
def combine(func, list_of_dict, key):
"""Apply the given function over the values retrieved
by the given key for each item in a of dictionaries"""
values = [_dict[key] for _dict in list_of_dict
if _dict[key] is not None]
if len(values) == 0:
return None
return func(values) |
def isPalindrome(head):
"""
:type head: ListNode
:rtype: bool
"""
stack = []
while head is not None:
print("head.val: " + str(head.val))
if head.val not in stack:
stack.append(head.val)
else:
if head.val is not stack[-1]:
retur... |
def jsob(inmap):
"""Return a json'able map."""
ret = None
if inmap is not None:
ret = {}
for key in inmap:
if key in [u'minelap', u'maxelap']:
ret[key] = inmap[key].rawtime()
else:
ret[key] = inmap[key]
return ret |
def meet_list(l1, l2):
"""Return the sublist of l1, intersecting l2."""
return list(filter(lambda e: e in l2, l1)) |
def filter_debt_to_income(monthly_debt_ratio, bank_list):
"""Filters the bank list by the maximum debt-to-income ratio allowed by the bank.
Args:
monthly_debt_ratio (float): The applicant's monthly debt ratio.
bank_list (list of lists): The available bank loans.
Returns:
A list of ... |
def is_nested_dictionary(dictionary: dict) -> bool:
"""
Determines whether a dictionary is nested or not
:param dictionary: dictionary to examine
:return: True if dictionary is nested, false otherwise
"""
return any(isinstance(_, dict) for _ in dictionary.values()) |
def attrs_all_equal(iterable, attr_name):
"""
Return true if everything in the iterable has the same value for `attr_name`.
:rtype: bool
"""
return len({getattr(item, attr_name, float('nan')) for item in iterable}) <= 1 |
def get_color(score: float) -> str:
"""Get color for shield"""
if score < 6:
return "critical"
elif score < 8:
return "orange"
elif score < 9:
return "yellow"
elif score < 9.5:
return "yellowgreen"
else:
return "brightgreen" |
def _build_user_auth(token=None, user_id=None, username=None,
password=None, tenant_id=None, tenant_name=None,
trust_id=None):
"""Build auth dictionary.
It will create an auth dictionary based on all the arguments
that it receives.
"""
auth_json = {}
if... |
def pin(point, rect):
"""
is point inside rectange
"""
(x, y) = point
(x1, y1, x2, y2) = rect
if x1 < x and x < x2:
if y1 < y and y < y2:
return True
return False |
def count(value, vector):
"""
Returns number of instaces of `value` in `vector`
"""
return sum(1 for num in vector if num == value) |
def check_ALL_DS(DS_ES_X_Map):
"""
ES used with ALL as DS can not be used with any other DS.
This function checks if this is true.
"""
ES_with_ALL = [row[1] for row in DS_ES_X_Map if row[0] == "ALL"]
ES_without_ALL = [ES for ES in ES_with_ALL
for row in DS_ES_X_Map if row[0... |
def find_start(lines, start_str, reverse=True):
"""Find the start of a block, iterate backwards by default,
Usually the last one is wanted
If not found, return -1
"""
start = -1
# Iterate backwards until the last value is found
if reverse:
for i, line in reversed(list(enumerate(lines... |
def sort_ships_by_size(ships, reverse=False):
"""
Sort received ships by size (number of vertices) in non-decreasing order by default. The reverse flag can be set to
True for non-increasing order.
"""
return sorted(ships, key=lambda s: len(s.vertices_ids), reverse=reverse) |
def is_valid_floating_point_response(response):
"""
Returns true if a floating_point response is valid.
str -> bool
"""
try:
return float(response)
except ValueError:
return False |
def y_minority_con_majority_211(by_grps):
"""
Examples:
PASS - [[S,S],[N,N,S,O]]
FAIL - [[S,N],[N,N,S,O]]
FAIL - [[S,S],[N,N,O,O]]
FAIL - [[S,S],[S,S,N,O]]
"""
if by_grps[0][0]!=by_grps[0][1]:
print("Failed y_minority_con_majority_211 -- small groups do not match")
r... |
def _nonzero_strength(x):
"""make sure a dictionary has only nonzero values"""
for k in list(x.keys()):
if x[k] == 0:
x.pop(k)
return x |
def build_complement(dna):
"""
Loop the character in DNA. Concatenating the complement character in ans list.
:param dna: string, the strand we need to complement.
:return: ans: string, the complement strand of DNA sequence.
"""
ans = ''
for nucleotide in dna:
if nucleotide == 'A':
... |
def otherCheckers(checker):
"""Return a string of the opponent's checkers."""
return {'x': ('o', 'O'), 'X': ('o', 'O'),
'o': ('x', 'X'), 'O': ('x', 'X')}[checker] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.