content
stringlengths 42
6.51k
|
|---|
def calc_pixel_solid_angle(gsd,
altitude):
"""
Calculate the pixel solid angle. gsd assumed equal along and cross track.
Returns
-------
double : Steradians
"""
return (gsd / altitude)**2
|
def is_sim_meas(op1: str, op2: str) -> bool:
"""Returns True if op1 and op2 can be simultaneously measured.
Args:
op1: Pauli string on n qubits.
op2: Pauli string on n qubits.
Examples:
is_sim_meas("IZI", "XIX") -> True
is_sim_meas("XZ", "XX") -> False
"""
if len(op1) != len(op2):
raise ValueError(
"Pauli operators act on different numbers of qubits."
)
for (a, b) in zip(op1, op2):
if a != b and a != "I" and b != "I":
return False
return True
|
def sequence_to_accelerator(sequence):
"""Translates Tk event sequence to customary shortcut string
for showing in the menu"""
if not sequence:
return ""
if not sequence.startswith("<"):
return sequence
accelerator = (
sequence.strip("<>").replace("Key-", "").replace("KeyPress-", "").replace("Control", "Ctrl")
)
# Tweaking individual parts
parts = accelerator.split("-")
# tkinter shows shift with capital letter, but in shortcuts it's customary to include it explicitly
if len(parts[-1]) == 1 and parts[-1].isupper() and not "Shift" in parts:
parts.insert(-1, "Shift")
# even when shift is not required, it's customary to show shortcut with capital letter
if len(parts[-1]) == 1:
parts[-1] = parts[-1].upper()
accelerator = "+".join(parts)
# Post processing
accelerator = (
accelerator.replace("Minus", "-")
.replace("minus", "-")
.replace("Plus", "+")
.replace("plus", "+")
)
return accelerator
|
def convective_and_conductive_heat_fluxes(HEC, T1, T2) -> float:
"""Convective and conductive heat fluxes
Equation 8.40
:param float HEC: the heat exchange coefficient between object 1 and 2
:param float T1: the temperature of object 1
:param float T2: the temperature of object 2
:return: The heat flow from object 1 to object 2 [W m^-2]
"""
return HEC * (T1 - T2)
|
def isrst(filename):
"""
Returns true if filename is an rst
"""
return filename[-4:] == '.rst'
|
def subtract_one(arg):
"""Subtracts one from the provided number."""
num = int(arg)
return num-1
|
def arguments_from_dict(arguments):
"""
dict to list of CLI options
"""
args_list = []
for key in sorted(arguments):
args_list.append("--" + key)
args_list.append(str(arguments[key]))
return args_list
|
def walk(fn, obj, *args, **kwargs):
"""Recursively walk an object graph applying `fn`/`args` to objects."""
if type(obj) in [list, tuple]:
return list(walk(fn, o, *args) for o in obj)
if type(obj) is dict:
return dict((walk(fn, k, *args), walk(fn, v, *args)) for k, v in obj.items())
return fn(obj, *args, **kwargs)
|
def _knapsack_0(W, vs, ws):
"""
This is an O(pow(2, n)) inefficient solution that lists all subsets
"""
value, weight = 0, 0
for i in range(1, pow(2, len(vs))):
v, w = 0, 0
j, k = i, 0
while j:
if j % 2:
v += vs[k]
w += ws[k]
k += 1
j //= 2
if w > W:
break
if value <= v and w <= W:
value, weight = v, w
return value
|
def calculate_mathematical_expression(num1, num2, sgn):
"""Solve math equation and return the answer.
if sgn is not arithmetic sign or the user try to divide in zero return none"""
if num2 == 0:
return None
elif sgn == "+":
return num1 + num2
elif sgn == "-":
return num2 - num1
elif sgn == "/":
return num1 / num2
elif sgn == "*":
return num1 * num2
else:
return None
|
def sort_totals(cust):
""" dict[dict] -> list[list] """
trans_list = []
for i in cust:
trans_list.append([cust[i]['total'], i])
trans_list = sorted(trans_list, reverse=True)
return trans_list
|
def no_duplicates(passphrase):
"""Checks if passphrase doesn't contain duplicated words."""
return len(passphrase) == len(set(passphrase))
|
def get_hours(time_str : str) -> float:
"""Get hours from time."""
h, m, s = time_str.split(':')
s = s.split('.')[0]
return int(h) + int(m) / 60 + int(s) / 3600
|
def is_a_number(x):
"""This function determines if its argument, x, is in the
format of a number. It can be number can be in integer, floating
point, scientific, or engineering format. The function returns True if the
argument is formattted like a number, and False otherwise."""
import re
num_re = re.compile(r'^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?$')
mo = num_re.match(str(x))
if mo:
return True
else:
return False
|
def find_index_neg_num(lis):
""" This func. returns position (0 to n) of negative number in
lis, and None if there is no negative no. """
return next((index for index, val in enumerate(lis) if val < 0), None)
|
def RF(a,b,c):
"""
Compute Carlson's elliptic integral RF(a, b, c).
1 /\oo dx
RF(a, b, c) = - | ------------------------------
2 | 1/2 1/2 1/2
\/0 (x + a) (x + b) (x + c)
The parameters a, b, and c may be complex numbers.
"""
A, B, C = a, b, c
for k in range(5):
gms = (A**0.5)*(B**0.5) + (A**0.5)*(C**0.5) + (B**0.5)*(C**0.5)
A, B, C = (A+gms)/4, (B+gms)/4, (C+gms)/4
avg0, avg = (a+b+c)/3., (A+B+C)/3
X = (avg0 - a)/(avg * 4**5)
Y = (avg0 - b)/(avg * 4**5)
Z = -X - Y
E2, E3 = X*Y - Z*Z, X*Y*Z
return avg**-0.5 * (1. - E2/10. + E3/14. + E2*E2/24. - E2*E3*3./44.)
|
def EWT_beta(x):
"""
Beta = EWT_beta(x)
function used in the construction of Meyer's wavelet
"""
if x<0:
bm=0
elif x>1:
bm=1
else:
bm=(x**4)*(35.-84.*x+70.*(x**2)-20.*(x**3))
return bm
|
def startEndPosition(args):
"""
gets coordinates as String separated by a comma and returns the coordinates as numeric values
@param args: coordinates as string
@return: coordinates as coordinates
"""
try:
x, y = args.split(",", 2)
x, y = int(x), int(y)
except:
x, y = 0, 0
return (x, y)
|
def get_service_image(image_name: str) -> str:
"""Build image string."""
return f"{image_name}:latest"
|
def __pagination_handler(query_set, model, params):
"""
Handle user-provided pagination requests.
Args:
query_set: SQLAlchemy query set to be paginated.
model: Data model from which given query set is generated.
params: User-provided filter params, with format {"offset": <int>, "limit": <int>, ...}.
Returns:
A query set with user-provided pagination applied.
"""
# Offset
offset = params.get("offset")
if offset!=None:
query_set = query_set.offset(offset)
# Limit
limit = params.get("limit")
if limit!=None:
query_set = query_set.limit(limit)
return query_set
|
def str2bool(string):
""" Convert string to boolean. """
return string in ['true', 'True', '1', 'yes'] if string else None
|
def get_index(x, xmin, xrng, xres):
""" map coordinate to array index """
return int((x-xmin)/xrng * (xres-1))
|
def map(arr:list, func) -> list:
"""Function to create a new list based on callback function return
Args:
arr ( list ) : a list to be iterated
func ( function ) : a callback function that will be executed every iteration and should return something for reduce assemble new list.
Examples:
>>> map([1, 2, 3, 4], lambda item, index: item if item % 2 == 0 else None)
[2, 4]
"""
_arr = []
for index in range(len(arr)):
call = func(arr[index], index)
if call and call != None:
_arr.append(call)
return _arr
|
def splitparams(path):
"""Split off parameter part from path.
Returns tuple (path-without-param, param)
"""
if '/' in path:
i = path.find(';', path.rfind('/'))
else:
i = path.find(';')
if i < 0:
return path, ''
return path[:i], path[i + 1:]
|
def isabs(s):
"""Test whether a path is absolute. """
return s.startswith('/')
|
def normalizeSentiment(sentiment):
"""
Normalizes the provider's polarity score the match the format of our thesis.
Arguments:
sentiment {Double} -- Polarity score
Returns:
Double -- Normalized polarity score
"""
return (sentiment + 1) * 0.5
|
def normalize_query_param(query_param):
"""Normalize query parameter to lower case"""
return query_param.lower() if query_param else None
|
def break_words(stuff):
"""this function will break up words for us.
Args:
stuff ([string]): [the string to break]
"""
words = stuff.split(' ')
return words
|
def edgeCheck(yedges, xedges, coord, sp_buffer):
"""Identify edge cases to make merging events quicker later"""
y = coord[0]
x = coord[1]
if y in yedges:
edge = True
elif x in xedges:
edge = True
else:
edge = False
return edge
|
def recursive_refs(envs, name):
"""
Return set of recursive refs for given env name
>>> local_refs = sorted(recursive_refs([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'local'))
>>> local_refs == ['base', 'test']
True
"""
refs_by_name = {
env['name']: set(env['refs'])
for env in envs
}
refs = refs_by_name[name]
if refs:
indirect_refs = set(
subref
for ref in refs
for subref in recursive_refs(envs, ref)
)
else:
indirect_refs = set()
return set.union(refs, indirect_refs)
|
def rndstr(N):
"""
random string of N lower case ascii letters and numbers
"""
import random
import string
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=N))
|
def parse_version(revision):
"""Convert semver string `revision` to a tuple of integers"""
return tuple(map(int, revision.split(".")))
|
def problem_29(lim=100):
""" a^b 2<=a,b<=100, number of distinct vals for all possible a,b """
# derp...
derp = set()
for a in range(2, lim + 1):
for b in range(2, lim + 1):
derp.add(a ** b)
return len(derp)
|
def character(b):
"""
Returns the decoded character ``b``.
"""
return b.decode('latin1')
|
def prepare_columns_for_sql(column_list, data_code=100):
"""
Creates a string with all the columns for a new tuple
:param column_list: The column names that need to be added
:param data_code: the data code to add at the column names
:return: string with all the columns
"""
string = 'KENNZIFFER, RAUMEINHEIT, AGGREGAT, YEAR, '
for i in column_list:
if len(i) >= 50:
new_label = i[:50] + '_' + str(data_code)
string = string + '`' + new_label + '`' + ', '
else:
string = string + '`' + i + '_' + str(data_code) + '`' + ', '
string = string.replace("None", "Null")
return string[:-2]
|
def add(numbers):
"""Sums all the numbers in the specified iterable"""
the_sum = 0
for number in numbers:
the_sum += int(number)
return the_sum
|
def name_to_platform(names):
"""
Converts one or more full names to a string containing one or more
<platform> elements.
"""
if isinstance(names, str):
return "<platform>%s</platform>" % names
return "\n".join(map(name_to_platform, names))
|
def _keyword_parse_fulltext(fulltext_string):
"""
Returned parsed version of input string
"""
parsed_words = set()
for word in fulltext_string.split():
parsed_words.add(word.strip("()[]\{\}!?,.\"':;-_"))
return " ".join(parsed_words)
|
def format_syntax_error(e: SyntaxError) -> str:
""" Formats a SyntaxError. """
if e.text is None:
return "```py\n{0.__class__.__name__}: {0}\n```".format(e)
# display a nice arrow
return "```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```".format(
e, "^", type(e).__name__)
|
def cleanup(fulllist, newlist):
"""Remove duplicates on the list (in case the web is switched)"""
# indexcounter = -1
for elm in fulllist:
# indexcounter +=1
for item in newlist:
if elm == item:
newlist.remove(item)
return newlist
|
def _get_generator_recipe(config):
"""
Creates dict with Password Generator Recipe settings
:param config: Dict[str, Any]
:return: dict
"""
if not config:
# Returning none/empty dict when "generate_value" is True
# tells the server to use recipe defaults
return None
character_sets = []
if config.get("include_digits") is not False:
character_sets.append("DIGITS")
if config.get("include_letters") is not False:
character_sets.append("LETTERS")
if config.get("include_symbols") is not False:
character_sets.append("SYMBOLS")
return dict(
length=config["length"],
characterSets=character_sets
)
|
def comment(self=str('')):
"""Generate a single-line QASM 2.0 comment from a string.
Args:
self(str): String to add as a comment in QASM 2.0 (default str(''))
Returns:
str: Generated QASM 2.0 comment."""
# Generate QASM 2.0 comment from self parameter.
qasm_comment = f'// {str(self)}'
# Return generated QASM 2.0.
return qasm_comment
|
def getSubString(string, firstChar, secondChar,start=0):
"""
Gives the substring of string between firstChar and secondChar. Starts looking from start. If it is unable to find a substring returns an empty string.
"""
front = string.find(firstChar,start)
back = string.find(secondChar,front+1)
if front > -1 and back > -1:
return (string[front+1:back],back)
else:
return ("",-1)
|
def isPal(x):
"""Assumes x is a list
Returns True if the list is a palindrome; False otherwise"""
temp = x
temp.reverse
if temp == x:
return True
else:
return False
|
def _unlParseNodePart(nodePart):
"""
Parse the Node part of a UNL
Arguments:
nodePart: The node part of a UNL
Returns:
unlList: List of node part parameters
in root to position order.
"""
if not nodePart:
if nodePart is None:
return None
else:
return ['']
return nodePart.split('-->')
|
def maybe_remove_new_line(code):
"""
Remove new line if code snippet is a
Python code snippet
"""
lines = code.split("\n")
if lines[0] in ["py", "python"]:
# add new line before last line being ```
lines = lines[:-2] + lines[-1:]
return "\n".join(lines)
|
def create_expected_output(parameters, actual_data):
"""
This function creates the dict using given parameter and actual data
:param parameters:
:param actual_data:
:return: expected data
:type: dict
"""
expected_output = {}
for key in parameters:
for value in actual_data:
expected_output[key] = value
actual_data.remove(value)
break
return expected_output
|
def flatten_dict(y, key_filter=None, seperator="."):
"""
flatten given dictionary, if filter is provided only given values are
returned
"""
res = {}
def flatten(x, name="", seperator=""):
if isinstance(x, dict):
# --- dict ---
for k in x.keys():
flatten(x[k], "{}{}{}".format(name, k, seperator), seperator)
elif isinstance(x, list):
# --- list ---
for no, k in enumerate(x):
flatten(k, "{}{}{}".format(name, no, seperator), seperator)
else:
# --- value ---
key = name[:-1]
if (key_filter is None) or (key in key_filter):
res[key] = x
flatten(y, seperator=".")
return res
|
def is_special_uri(uri):
"""
For cumstomize
"""
if len(uri) == 0:
return False
return False
|
def host(value):
"""Validates that the value is a valid network location"""
if not value:
return (True, "")
try:
host, port = value.split(":")
except ValueError as _:
return (False, "value needs to be <host>:<port>")
try:
int(port)
except ValueError as _:
return (False, "port component of the host address needs to be a number")
return (True, "")
|
def format_interface_name(intf_type, port, ch_grp=0):
"""Method to format interface name given type, port.
Given interface type, port, and channel-group, this
method formats an interface name. If channel-group is
non-zero, then port-channel is configured.
:param intf_type: Such as 'ethernet' or 'port-channel'
:param port: unique identification -- 1/32 or 1
:ch_grp: If non-zero, ignore other params and format
port-channel<ch_grp>
:returns: the full formatted interface name.
ex: ethernet:1/32, port-channel:1
"""
if ch_grp > 0:
return 'port-channel:%s' % str(ch_grp)
return '%s:%s' % (intf_type.lower(), port)
|
def foo(a, b):
"""Docs? Contribution is welcome."""
return {"a": a, "b": b}
|
def BitofWord(tag):
"""
Test if the user is trying to write to a bit of a word
ex. Tag.1 returns True (Tag = DINT)
"""
s = tag.split('.')
if s[len(s)-1].isdigit():
return True
else:
return False
|
def double_quote(string):
"""Place double quotes around the given string"""
return '"' + string + '"'
|
def average(total, day):
"""
:param total: The sum of temperature data.
:param day: The sum of days.
:return: The average temperature.
"""
avg = total/day
return avg
|
def determine_final_official_and_dev_version(tag_list):
"""
Determine official version i.e 4.1.0 , 4.2.2..etc using oxauths repo
@param tag_list:
@return:
"""
# Check for the highest major.minor.patch i.e 4.2.0 vs 4.2.2
dev_image = ""
patch_list = []
for tag in tag_list:
patch_list.append(int(tag[4:5]))
# Remove duplicates
patch_list = list(set(patch_list))
# Sort
patch_list.sort()
highest_major_minor_patch_number = str(patch_list[-1])
versions_list = []
for tag in tag_list:
if "dev" in tag and tag[4:5] == highest_major_minor_patch_number:
dev_image = tag[0:5] + "_dev"
# Exclude any tag with the following
if "dev" not in tag and "a" not in tag and tag[4:5] == highest_major_minor_patch_number:
versions_list.append(int(tag[6:8]))
# A case were only a dev version of a new patch is available then a lower stable patch should be checked.
# i.e there is no 4.3.0_01 but there is 4.2.2_dev
if not versions_list:
highest_major_minor_patch_number = str(int(highest_major_minor_patch_number) - 1)
for tag in tag_list:
if not dev_image and "dev" in tag and tag[4:5] == highest_major_minor_patch_number:
dev_image = tag[0:5] + "_dev"
# Exclude any tag with the following
if "dev" not in tag and "a" not in tag and tag[4:5] == highest_major_minor_patch_number:
versions_list.append(int(tag[6:8]))
# Remove duplicates
versions_list = list(set(versions_list))
# Sort
versions_list.sort()
# Return highest patch
highest_major_minor_patch_image_patch = str(versions_list[-1])
if len(highest_major_minor_patch_image_patch) == 1:
highest_major_minor_patch_image_patch = "0" + highest_major_minor_patch_image_patch
highest_major_minor_patch_image = ""
for tag in tag_list:
if "dev" not in tag and highest_major_minor_patch_image_patch in tag \
and tag[4:5] == highest_major_minor_patch_number:
highest_major_minor_patch_image = tag
return highest_major_minor_patch_image, dev_image
|
def list2set(seq):
"""
Return a new list without duplicates.
Preserves the order, unlike set(seq)
"""
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
|
def normalize_axis_selection(item, l):
"""Convenience function to normalize a selection within a single axis
of size `l`."""
if isinstance(item, int):
if item < 0:
# handle wraparound
item = l + item
if item > (l - 1) or item < 0:
raise IndexError('index out of bounds: %s' % item)
return item
elif isinstance(item, slice):
if item.step is not None and item.step != 1:
raise NotImplementedError('slice with step not supported')
start = 0 if item.start is None else item.start
stop = l if item.stop is None else item.stop
if start < 0:
start = l + start
if stop < 0:
stop = l + stop
if start < 0 or stop < 0:
raise IndexError('index out of bounds: %s, %s' % (start, stop))
if start >= l:
raise IndexError('index out of bounds: %s, %s' % (start, stop))
if stop > l:
stop = l
if stop < start:
raise IndexError('index out of bounds: %s, %s' % (start, stop))
return slice(start, stop)
else:
raise TypeError('expected integer or slice, found: %r' % item)
|
def value_label_formatter(x, pos):
"""Inputs
-------
x : (float) value of tick label
pos : () position of tick label
outputs
-------
(str) formatted tick label"""
if x > 100000000:
# 100,000,000
return '{:1.0e}'.format(x)
if x > 1000000:
# 1,000,000
return '{:1.0f}M'.format(x / 1e7)
elif x >= 1000:
return '{:1.0f}k'.format(x / 1e3)
else:
return '{:1.0f}'.format(x)
return str(x)
|
def get_inventory_roles_to_hosts(inventory, roles, fqdn=False):
"""Return a map of roles to host lists, e.g.
roles_to_hosts['CephStorage'] = ['oc0-ceph-0', 'oc0-ceph-1']
roles_to_hosts['Controller'] = ['oc0-controller-0']
roles_to_hosts['Compute'] = ['oc0-compute-0']
Uses ansible inventory as source
"""
roles_to_hosts = {}
for key in inventory:
if key in roles:
roles_to_hosts[key] = []
for host in inventory[key]['hosts']:
if fqdn:
hostname = inventory[key]['hosts'][host]['canonical_hostname']
else:
hostname = host
roles_to_hosts[key].append(hostname)
return roles_to_hosts
|
def MD5_f2(b, c, d):
""" Second ternary bitwise operation."""
return ((b & d) | (c & (~d))) & 0xFFFFFFFF
|
def binaryToDecimal(binary):
"""
Calculates the decimal equivalent of binary input
"""
binary = int(binary)
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary // 10
i += 1
return(decimal)
|
def default_scale(method='forward', n=1, order=2):
"""Returns good scale for MinStepGenerator"""
high_order = int(n > 1 or order >= 4)
order2 = max(order // 2 - 1, 0)
n_4 = n // 4
n_mod_4 = n % 4
c = ([n_4 * (10 + 1.5 * int(n > 10)),
3.65 + n_4 * (5 + 1.5 ** n_4),
3.65 + n_4 * (5 + 1.7 ** n_4),
7.30 + n_4 * (5 + 2.1 ** n_4)][n_mod_4]) if high_order else 0
return (dict(multicomplex=1.06, complex=1.06 + c).get(method, 2.5) +
int(n - 1) * dict(multicomplex=0, complex=0.0).get(method, 1.3) +
order2 * dict(central=3, forward=2, backward=2).get(method, 0))
|
def cin(c, s):
""" is c in s? If c is empty, return False.
@param c [string] = a character or ''
@param s [string] = a string; c must match one char in s
@return [bool]
"""
if c=='': return False
return c in s
|
def parsepatchoutput(output_line):
"""parses the output produced by patch and returns the filename"""
pf = output_line[14:]
if pf[0] == '`':
pf = pf[1:-1] # Remove the quotes
return pf
|
def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder
# because after we begin a code block, Python requires at least one line of code)
return round(num,2)
|
def carreau(x, eta_0=1.0, gammadot_crit=1.0, n=0.5, prefix="carreau"):
"""carreau Model
Note:
.. math::
\sigma=\dot\gamma \cdot \eta_0 \cdot (1+(\dot\gamma/\dot\gamma_c)^2)^{(n-1)/2}
Args:
eta_0: low shear viscosity [Pa s]
gammadot_crit: critical shear rate [1/s]
n : shear thinning exponent
Returns:
stress : Shear Stress, [Pa]
"""
return x * eta_0 * (1 + (x / gammadot_crit) ** 2) ** ((n - 1) / 2)
|
def get_test_type(text):
"""
:param text:
:return: one of (ALGORITHMS, CYBERSECURITY, DATABASE, NETWORKING)
"""
text = text.lower()
test_type = None
if 'algo' in text:
test_type = 'ALGORITHMS'
elif ('cyber' in text) or ('security' in text):
test_type = 'CYBERSECURITY'
elif 'network' in text:
test_type = 'NETWORKING'
elif ('database' in text) or ('db' in text):
test_type = 'DATABASE'
return test_type
|
def match(query, text) -> bool:
"""
Match test with query.
"""
if len(query) < 3 or len(text) == 0:
return False
return query.lower() in text.lower()
|
def flatten(lis):
""" Take a list and flatten it. """
# Here a list containing 0 to length of the list is Zipped together
# into tuple pairs. Now each element is mapped to an index and is sorted.
temp_zip = zip(sorted(lis), range(len(lis)))
# From the tuples we create a hash table mapped to the index value
# as the keys. This is a dictionary comprehension.
temp_dict = {k: v for (k, v) in temp_zip}
# An empty array to keep the return value.
flat_list = []
for num in lis:
# Here using the get() method we call the hash table and
# append the appropriate value to the new list.
flat_list.append(temp_dict.get(num))
return flat_list
|
def _distance2(v, u):
"""Compute the square distance between points defined by vectors *v* and *u*."""
return sum(((v[i] - u[i]) * (v[i] - u[i]) for i in range(len(v))))
|
def get_row_doc(row_json):
"""
Gets the document for the given parsed JSON row.
Use this function in custom :class:`~.RowProcessor`
implementations to extract the actual document. The document
itself is stored within a private field of the row itself, and
should only be accessed by this function.
:param dict row_json: The parsed row (passed to the processor)
:return: The document, or None
"""
return row_json.get('__DOCRESULT__')
|
def pic_get(pic, tag, default=None):
"""Get single tag ignoring exceptions"""
try:
return pic[tag]
except Exception:
return default
|
def rgb2gray_linear(rgb):
"""
Convert *linear* RGB values to *linear* grayscale values.
"""
return 0.2126*rgb[0] + 0.7152*rgb[1] + 0.0722*rgb[2]
|
def flatten(l):
""" Merges a list of lists into a single list. """
return [item for sublist in l for item in sublist]
|
def wildcard_string_match(val,pattern,wildcard='?',wildcard_exclude=''):
"""Generate a TRUE / FALSE for matching the given value against a pattern. Enables wildcard searching & excludable characters from wildcard.
Args:
val (string): Value to check if matches.
pattern (string): Pattern to check the val against.
wildcard (str, optional): Wildcard character used in pattern. Defaults to '?'.
wildcard_exclude (str, optional): Characters to exclude from wildcard. Defaults to ''.
Returns:
bool : TRUE == match, FALSE == no match
"""
if len(val) == 0 or len(pattern) == 0:
return True
if val[0] in wildcard_exclude:
return False
elif pattern[0] == wildcard or pattern[0] == val[0]:
return wildcard_string_match(val[1:],pattern[1:],wildcard,wildcard_exclude)
else:
return False
|
def add_(string = ''):
"""
Add an _ if string is not empty
"""
s = ''
if string:
s = string + '_'
return s
|
def listXor(b,c):
"""Returns elements in lists b and c that they don't share"""
A = [a for a in b+c if (a not in b) or (a not in c)]
return A
|
def is_iterable(obj):
"""Tells whether an instance is iterable or not.
:param obj: the instance to test
:type obj: object
:return: True if the object is iterable
:rtype: bool
"""
try:
iter(obj)
return True
except TypeError:
return False
|
def enabled_bool(enabled_statuses):
"""Switch from enabled_status to bool"""
return [True if s == 'ENABLED_STATUS_ENABLED' else False for s in enabled_statuses]
|
def ha_write_config_file(config, path):
"""Connects to the Harmony huband generates a text file containing all activities and commands programmed to hub.
Args:
config (dict): Dictionary object containing configuration information obtained from function ha_get_config
path (str): Full path to output file
Returns:
True
"""
with open(path, 'w+', encoding='utf-8') as file_out:
file_out.write('Activities\n')
for activity in config['activity']:
file_out.write(' ' + activity['id'] + ' - ' + activity['label'] + '\n')
file_out.write('\nDevice Commands\n')
for device in config['device']:
file_out.write(' ' + device['id'] + ' - ' + device['label'] + '\n')
for controlGroup in device['controlGroup']:
for function in controlGroup['function']:
file_out.write(' ' + function['name'] + '\n')
return True
|
def correct_thresholds(p):
"""
Checks that the thresholds are ordered th_lo < th < th_hi
"""
return ( (p['th_lo'] < p['th']) or p['th'] == -1 ) and \
( (p['th'] < p['th_hi']) or p['th_hi'] == -1 )
|
def has_routes(obj):
"""
Checks if the given `obj` has an attribute `routes`.
:param obj: The obj to be checked.
:return: True if the `obj` has the attribute.
"""
return hasattr(obj, 'routes')
|
def validate_age(age):
""" Validate the age
Determine if the input age of patient is valid. If it os too small (<=0) or
too big (>=150) it is determined as a invalid number.
Args:
age (int): The age of the new patient
Returns:
"""
if age <= 0:
return "Invalid age, must be greater than 0!"
if age >= 150:
return "Invalid age, human can't live so long!"
else:
return True
|
def fibo_iter(num):
"""Iterative Fibo."""
if num == 0:
return 0
second_to_last = 0
last = 1
for _ in range(1, num):
second_to_last, last = last, second_to_last + last
return last
|
def parse_group_authors(group_authors):
"""
Given a raw group author value from the data files,
check for empty, whitespace, zero
If not empty, remove extra numbers from the end of the string
Return a dictionary of dict[author_position] = collab_name
"""
group_author_dict = {}
if group_authors.strip() == "":
group_author_dict = None
elif group_authors.strip() == "0":
group_author_dict = None
else:
# Parse out elements into a list, clean and
# add the the dictionary using some steps
# Split the string on the first delimiter
group_author_list = group_authors.split('order_start')
for group_author_string in group_author_list:
if group_author_string == "":
continue
# Now split on the second delimiter
position_and_name = group_author_string.split('order_end')
author_position = position_and_name[0]
# Strip numbers at the end
if len(position_and_name) > 1:
group_author = position_and_name[1].rstrip("1234567890")
# Finally, add to the dict noting the authors position
group_author_dict[author_position] = group_author
return group_author_dict
|
def encode_features(features: dict) -> str:
"""Encodes features from a dictionary/JSON to CONLLU format."""
return '|'.join(map(lambda kv: f'{kv[0]}={kv[1]}', features.items())) if features else '_'
|
def count_pos(L):
"""
(list) -> int
Counts the number of positive values in a list
Restriction: L must be a list with numbers in it
"""
counter = 0
for i in L:
if i > 0:
counter += 1
else:
continue
return counter
|
def _is_shorthand_ip(ip_str):
"""Determine if the address is shortened.
Args:
ip_str: A string, the IPv6 address.
Returns:
A boolean, True if the address is shortened.
"""
if ip_str.count('::') == 1:
return True
if any(len(x) < 4 for x in ip_str.split(':')):
return True
return False
|
def h(s):
""" Cal the hash for the password"""
p = 131
m = pow(10, 9) +7
tmp = 0
s = s [::-1] # invert the string
for i in range(len(s)):
tmp += ord(s[i]) * pow(p, i)
return int(tmp % m)
|
def dgKey(pre, dig):
"""
Returns bytes DB key from concatenation of '.' with qualified Base64 prefix
bytes pre and qualified Base64 bytes digest of serialized event
If pre or dig are str then converts to bytes
"""
if hasattr(pre, "encode"):
pre = pre.encode("utf-8") # convert str to bytes
if hasattr(dig, "encode"):
dig = dig.encode("utf-8") # convert str to bytes
return (b'%s.%s' % (pre, dig))
|
def format_key_list(keys_str):
"""
Format the key list
:param keys_str: a string containing the keys separated by spaces
:return: a string containing the keys ordered and separated by a coma and a space
"""
key_list = keys_str.split(" ")
key_list.sort()
return ", ".join(key_list)
|
def mean(num_list):
"""
Calculate the man of a list of numbers
Parameters
----------
num_list: list
The list to take average of
Returns
-------
avg: float
The mean of a list
Examples
--------
>>> mean([1, 2, 3, 4, 5])
3.0
"""
# Check that user passes list
if not isinstance(num_list, list):
raise TypeError('Input must be type list')
# Check that list has length
if len(num_list) == 0:
raise ZeroDivisionError('Cannot calculate mean of empty list')
try:
avg = sum(num_list) / len(num_list)
except TypeError:
raise TypeError('Values of list must be type int or float')
return avg
|
def parse_line(line):
"""
Parses lines of the following form
Line #| Hits| Time| Time per hit| %|Source code
------+----------+-------------+-------------+-------+-----------
1| 2| 4.1008e-05| 2.0504e-05| 0.00%|import os
Extracts a dict of (line_number, hits, time, time_per_hit, percentage, code)
:param line: string
:return: tuple
"""
columns = line.split('|')
return {'line_number': int(columns[0]),
'hits': int(columns[1]),
'time': float(columns[2]),
'time_per_hit': float(columns[3]),
'percentage': float(columns[4][:-1]),
'code': '|'.join(columns[5:]),
'calls': list(),
'calls_from': dict()
}
|
def norm_whitespace(s: str) -> str:
"""normalize whitespace in the given string.
Example:
>>> from hearth.text.utils import norm_whitespace
>>>
>>> norm_whitespace('\tthere\t\tshould only be one space between \twords. ')
'there should only be one space between words.'
"""
return ' '.join(s.split())
|
def extract_mapping(mapping, params):
"""get tests associated with a list of params from mapping"""
data = {}
selected_tests = []
for p in params:
if p in mapping:
tests = mapping[p]
print(">>>>[ctest_core] parameter {} has {} tests".format(p, len(tests)))
data[p] = tests
selected_tests = selected_tests + tests
else:
print(">>>>[ctest_core] parameter {} has 0 tests".format(p))
return data, set(selected_tests)
|
def verify(url):
"""
To check whether `url` belongs to YouTube, if yes returns True
else False
"""
if "youtube.com" in url or "youtu.be" in url:
return True
return False
|
def extract_arxiv_url(system_control_numbers):
"""Extract any arxiv URLs from the system_control_number field
"""
if isinstance(system_control_numbers, dict):
system_control_numbers = [system_control_numbers,]
arxiv_urls = [
number['value'].replace('oai:arXiv.org:', 'https://arxiv.org/abs/')
for number in system_control_numbers if number.get('institute', '') == 'arXiv' and 'value' in number
]
if not arxiv_urls:
return ''
return arxiv_urls[0]
|
def dict2str(
in_dict,
entry_sep=',',
key_val_sep='=',
pre_decor='{',
post_decor='}',
strip_key_str=None,
strip_val_str=None,
sorting=None):
"""
Convert a dictionary to a string.
Args:
in_dict (dict): The input dictionary.
entry_sep (str): The entry separator.
key_val_sep (str): The key-value separator.
pre_decor (str): initial decorator (to be appended to the output).
post_decor (str): final decorator (to be appended to the output).
strip_key_str (str): Chars to be stripped from both ends of the key.
If None, whitespaces are stripped. Empty string for no stripping.
strip_val_str (str): Chars to be stripped from both ends of the value.
If None, whitespaces are stripped. Empty string for no stripping.
sorting (callable): Sorting function passed to 'sorted' via `key` arg.
Used for sorting the dictionary keys.
Returns:
out_str (str): The output string generated from the dictionary.
Examples:
>>> dict2str({'a': 10, 'b': 20, 'c': 'test'})
'{a=10,b=20,c=test}'
See Also:
str2dict
"""
keys = sorted(in_dict.keys(), key=sorting)
out_list = []
for key in keys:
key = key.strip(strip_key_str)
val = str(in_dict[key]).strip(strip_val_str)
out_list.append(key_val_sep.join([key, val]))
out_str = pre_decor + entry_sep.join(out_list) + post_decor
return out_str
|
def url_build(*parts):
"""Join parts of a url into a string."""
return "/".join(p.strip("/") for p in parts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.