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
... |
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("KeyP... |
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 h... |
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())
retu... |
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]
... |
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 - n... |
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
n... |
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 ... |
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 =... |
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>, "lim... |
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.
Exampl... |
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 == ... |
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 = 'KENNZIFF... |
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
... |
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)... |
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)
... |
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
... |
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:
... |
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():
f... |
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 _:
... |
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 '... |
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:
patc... |
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 ... |
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
r... |
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 inve... |
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
... |
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 ... |
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 bloc... |
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 : ... |
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'
... |
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 inde... |
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 functio... |
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... |
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 out... |
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... |
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_a... |
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(':')):
retur... |
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 byt... |
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 ... |
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_... |
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.'... |
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)))
dat... |
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/a... |
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.
entr... |
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.