content stringlengths 42 6.51k |
|---|
def IsTelemetryCommand(command):
"""Attempts to discern whether or not a given command is running telemetry."""
return 'tools/perf/run_' in command or 'tools\\perf\\run_' in command |
def count_change(total):
"""Return the number of ways to make change for total.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
>>> from construct_check import check
>>> # ban iteration
>>> check(HW_SOURCE_FILE, 'count_cha... |
def clean_parses(parses):
"""
Remove the stuff we don't need from a list of parses
Arguments
parses : list of (bis,buffer,route,k)
Returns
list of (bis,route)
"""
return [ (bis,route) for (bis,_,route,_) in parses ] |
def find_arg_end(field_name):
"""
Returns the index of the end of an attribute name or element index.
field_name: the field being looked up, e.g. "0.name"
or "lookup[3]"
"""
dot_idx = field_name.find(".")
lbrack_idx = field_name.find("[")
if dot_idx == -1:
return ... |
def sum_digits(n : int) -> int:
"""
Given a non-negative integer n, return the sum of its digits.
Parameters
----------
n : int
number to return the sum of
Returns
-------
int
sum of numbers digits
"""
sum = 0
for i in [int(i) for i in ... |
def create_approval_email(user: dict) -> str:
"""
Creates the registration approval email.
Arguments:
user {dict} -- User record from /accounts
Returns:
str -- Formatted email.
"""
return '''
Dear %s %s:
Your registration for the CIMAC-CIDC DATA Portal has now been app... |
def map(inp,x_min,x_max,y_min,y_max):
"""
Resets neopixels by sweeping red
than green and finally turns off all
"""
return (inp-x_min) / (x_max-x_min) * (y_max-y_min) + y_min |
def _str_to_list(val):
"""If val is str, return list with single entry, else return as-is."""
l = []
if val.__class__ == str:
l.append(val)
return l
else:
return val |
def param_cleaner(param_dict):
"""
Helper function for random_generator, cleans the given param_dict of 'empty' values
:param param_dict: param_dict from random_generator
:return: param_dict_cleaned
"""
def generate_number_from_type(type, to_from, value):
if value == 0 or value == '':
... |
def unescape_glob(string):
"""Unescape glob pattern in `string`."""
def unescape(s):
for pattern in '*[]!?':
s = s.replace(r'\{0}'.format(pattern), pattern)
return s
return '\\'.join(map(unescape, string.split('\\\\'))) |
def _tgt_set(tgt):
"""
Return the tgt as a set of literal names
"""
try:
# A comma-delimited string
return set(tgt.split(","))
except AttributeError:
# Assume tgt is already a non-string iterable.
return set(tgt) |
def str2floats(s):
"""Look for single float or comma-separated floats."""
return tuple(float(f) for f in s.split(',')) |
def get_product(product_db, product_id):
"""Returns Feature at given location or None."""
print('hello')
# return 'hello'
for product in product_db:
if product.product_num == product_id:
return product
return None |
def parse_metric(metric, coords, coords2=None, coords3=None):
"""
Convert a string metric into the corresponding enum to pass to the C code.
"""
if coords2 is None:
auto = True
else:
auto = False
# Special Rlens doesn't care about the distance to the sources, so spherical is ... |
def get_license(license, settings):
"""Modify license for file type
Args:
license (str): License to be inserted
settings (Dict): File type settings
Returns:
str: Modified license to be inserted in the file
"""
lines = []
header_start_line = settings["headerStartLine"]
... |
def _get_TZIDs(lines):
"""from a list of strings, get all unique strings that start with TZID"""
return sorted(line for line in lines if line.startswith('TZID')) |
def get_active_nodes(response_json):
"""
Get the active node list and parse for ID and namne
return node_dict for comparison
"""
node_dict = {}
node_list_json = response_json
for node in node_list_json['result']['nodes']:
node_id = node['nodeID']
node_name = node['name']
... |
def set_comment(s: str) -> str:
"""set the indent of each line in `s` `indent`"""
lines = s.splitlines(False)
new_lines = []
for line in lines:
line = '// ' + line
new_lines.append(line)
return '\n'.join(new_lines)+'\n' |
def squeeze(shape, n=0):
"""Removes all 1-dimensional entries for all dimensions > ``n``.
For negative ``n`` the last ``|n|`` dimensions are sequeezed.
"""
dims = list(shape[:n])
for dim in shape[n:]:
if dim > 1:
dims.append(dim)
return type(shape)(dims) |
def lib1_cons2_neutral3(x):
"""Rearrange questions where 3 is neutral."""
return -3 + x if x != 1 else x |
def version_dicttotuple(dict_version):
""" Converts a version dictionary into a tuple
"""
return (int(dict_version['major']),
int(dict_version['minor']),
int(dict_version['release'])) |
def makeDirectoryEntry(name, size, isdir = False, readonly = False):
"""Utility class for returning a dictionary of directory content information."""
out = {"name": name,
"size": size,
"isDir": isdir,
"readonly": readonly
}
return out |
def convert_to_float(value):
"""Attempts to convert a string or a number to a float. If unsuccessful
returns the value unchanged. Note that this function will return True for
boolean values, faux string boolean values (e.g., "true"), "NaN",
exponential notation, etc.
Parameters:
value (str|... |
def isiter(x):
"""
Returns `True` if the given value implements an valid iterable
interface.
Arguments:
x (mixed): value to check if it is an iterable.
Returns:
bool
"""
return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) |
def convert_old_time(time: str, revert_12hour=False, truncate_minute=False) -> str:
"""
Convert previous float-formatted times to 24-hour, full format
Parameters
----------
time:
a time from the previous CourseTable format
revert_12hour:
whether or not to convert back to 12-hour... |
def shell_quote(s):
"""Given bl"a, returns "bl\\"a".
Returns bytes.
"""
if not isinstance(s, bytes):
s = s.encode('utf-8')
if any(c in s for c in b' \t\n\r\x0b\x0c*$\\"\''):
return b'"' + (s.replace(b'\\', b'\\\\')
.replace(b'"', b'\\"')
... |
def write_encrypted_file(filename, encrypted_data):
"""
Write an encrypted bytestring to file
"""
filename = filename + '.enc'
with open(filename, "wb") as file:
file.write(encrypted_data)
return filename |
def current_iteration(parent_iteration, child_iteration):
"""
:param parent_iteration:
:param child_iteration:
:return:
"""
return str(parent_iteration) + '-' + str(child_iteration) |
def dbKeys(db):
"""
Fetch name, CAS, and formula from db and return them as a list of tuples
Parameters:
db, nested dictionary like {'<name>':{'CAS':'', 'formula':'', ...}}
Returns:
nCF, list of tuples like [('name0','CAS0','formula0'),
('name1','C... |
def fix_indentation(text, indent_chars):
"""Replace tabs by spaces"""
return text.replace('\t', indent_chars) |
def unhex(str):
"""Converts an 'ethereum' style hex value to decimal"""
if str == "0x":
return 0
return int(str, 16) |
def kappa_confusion_matrix(rater_a, rater_b, min_rating=None, max_rating=None):
"""
Returns the confusion matrix between rater's ratings
"""
assert (len(rater_a) == len(rater_b))
if min_rating is None:
min_rating = min(rater_a + rater_b)
if max_rating is None:
max_rating = max(rater_a + rater_b)
num... |
def default(x, default):
""" Returns x if x is not none, otherwise default. """
return x if x is not None else default |
def job_wrapper_generic(param, user_defined_work_func, register_cleanup, touch_files_only):
"""
run func
"""
assert(user_defined_work_func)
#try:
# print sys._MEIPASS
# os.system("rm -rf %s"%(sys._MEIPASS))
#except Exception:
# pass
return user_defined_work_func(*param) |
def apply_if_callable(maybe_callable, obj, **kwargs):
"""
Evaluate possibly callable input using obj and kwargs if it is callable,
otherwise return as it is.
Parameters
----------
maybe_callable : possibly a callable
obj : NDFrame
**kwargs
"""
if callable(maybe_callable):
... |
def ltypeOfLaueGroup(tag):
"""
See quatOfLaueGroup
"""
if not isinstance(tag, str):
raise RuntimeError("entered flag is not a string!")
if tag.lower() == 'ci' or tag.lower() == 's2':
ltype = 'triclinic'
elif tag.lower() == 'c2h':
ltype = 'monoclinic'
elif tag.lower(... |
def is_valid_unicode(text):
"""Check if a string is valid unicode. Did we slice on an invalid boundary?"""
try:
text.decode("utf-8")
return True
except UnicodeDecodeError:
return False |
def split_list(l, n):
"""
:param l: (nested) list
:param n: n chunks to be split by
:return: list of size n
"""
d, r = divmod(len(l), n)
mylist = []
for i in range(n):
si = (d + 1) * (i if i < r else r) + d * (0 if i < r else i - r)
# yield l[si:si + (d + 1 if i < r else ... |
def flatten(x):
"""
Flatten list of lists
"""
import itertools
flatted_list = list(itertools.chain(*x))
return flatted_list |
def gain_mode_index_from_fractions(grp_prob):
"""Returns int gain mode index or None from list of gain group fractions."""
return next((i for i,p in enumerate(grp_prob) if p>0.5), None) |
def bool_eval(token_lst):
"""token_lst has length 3 and format: [left_arg, operator, right_arg]
operator(left_arg, right_arg) is returned"""
return token_lst[1](token_lst[0], token_lst[2]) |
def print_value(value, ndigits=3):
"""Prepare a parameter value for printing, used in CyclingParams.__str__"""
if len(value) == 1:
return format(value[0], '.%df' % ndigits)
else:
return 'array(%d)' % len(value) |
def parse_url_subdomains(url):
"""Parses site, area, and category from Craigslist query URL."""
parsed_url = url.split("https://")[1].split(".")
parsed_suburl = parsed_url[2].split("/")
site = parsed_url[0]
# `parsed_suburl` will have len == 5 if query has no area.
# `parsed_suburl` will have le... |
def _skip_nonwhitespace(data, pos):
"""Return first position not before pos which contains a non-whitespace character."""
for i, x in enumerate(data[pos:]):
if x.isspace():
return pos + i
return len(data) |
def module_level_function(param1, param2=None, *args, **kwargs):
"""This is an example of a module level function.
Function parameters should be documented in the ``Parameters`` section.
The name of each parameter is required. The type and description of each
parameter is optional, but should be includ... |
def get_species_counts(individuals):
"""
Returns a dictionary with species name as the key and the number of
individuals in that species as the value.
:param individuals:
:return:
"""
species_counts = {}
for individual in individuals:
species = individual.split("_")... |
def multiprocessing_func(fn_to_eval, random_var_gen, i):
"""Allows monte carlo to run on multiple CPUs."""
random_vars = random_var_gen(i)
result = fn_to_eval(*random_vars)
return result |
def argument_names(args):
"""Give arguments alpha-numeric names.
>>> names = argument_names(range(100))
>>> [names[i] for i in range(0,100,26)]
[u'?a', u'?a1', u'?a2', u'?a3']
>>> [names[i] for i in range(1,100,26)]
[u'?b', u'?b1', u'?b2', u'?b3']
"""
# Argument naming scheme: intege... |
def reverse_lookup( d, val ):
"""Builds and Returns a list of all keys that map to val,
or an empty list if there are none.
val: value in dictionary
"""
keys_list = []
for key in d:
if d[key] == val:
keys_list.append( key )
return keys_list |
def read_bytes_sync(sock, nbytes):
""" Read number of bytes from a blocking socket
This is not typically used, see IOStream.read_bytes instead
"""
frames = []
while nbytes:
frame = sock.recv(nbytes)
frames.append(frame)
nbytes -= len(frame)
if len(frames) == 1:
... |
def ip_received(data=None):
"""
Construct a template for IP incoming packet
"""
tpl = { 'ip-event': 'received' }
if data is not None:
tpl['ip-data'] = data
return tpl |
def quote(toquote):
"""quote('abc def') -> 'abc%20def'
Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted.
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.
reserved = ";... |
def autodoc_skip_member_handler(app, what, name, obj, skip, options):
"""Manually exclude certain methods/functions from docs"""
# exclude special methods from unittest
excludes = ["setUp", "setUpClass", "tearDown", "tearDownClass"]
return name.startswith("_") or name in excludes |
def latex_parse_eq(eq):
"""Tests cases :
- v = d/t
- 2piRC
- 1/(2piRC)
- use of sqrt, quad
- parse lmbda, nu, exp
"""
#if "$" in eq:
# return eq
#if "=" in eq:
# left, right = eq.split("=")
# res = "=".join([str(sp.latex(sp.sympify(left))), str(sp.latex(sp... |
def hexRot(ch):
""" rotate hex character by 8 """
return format((int(ch, base=16) + 8) % 16, 'x') |
def make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:par... |
def cryptMessage(mode, message, shiftKey):
""" The encryption / decryption action is here """
if mode[0] == 'd':
shiftKey = -shiftKey
translated = ''
for symbol in message: # The encryption stuff
if symbol.isalpha():
num = ord(symbol)
num += shiftKey
... |
def parse_ignore_patterns_from_dict(ignore_patterns_dict) -> tuple:
"""Parse dictionary containing (file_name_pattern, exclude_patterns) key value pairs
to return an output consistent with ignore patterns parsed by `parse_ignore_names_file`
Parameters
----------
ignore_patterns_dict: Dict
A... |
def get_input_config_by_name(model_config, name):
"""Get input properties corresponding to the input
with given `name`
Parameters
----------
model_config : dict
dictionary object containing the model configuration
name : str
name of the input object
Returns
-------
di... |
def _adjust_component(r, g, b)-> tuple:
"""
Created by Eric Muzzo.
Returns a tuple conatining the midpoint values of the quadrant in
which each color lies when given an RGB value.
>>>mypic = load_image(choose_file())
>>>show(posterizing(mypic))
"""
mid1 = 31
mid2 = 95
... |
def library_sqrt(x):
"""Uses math library"""
from math import sqrt
return sqrt(x) |
def convertStrand(strand):
"""convert various strand notations into [+-.].
"""
s = str(strand)
if s in ("-", "0", "-1"):
return "-"
elif s in ("+", "1"):
return "+"
else:
return "." |
def wc(file):
"""Get number of lines in a file"""
with open(file, mode='rb') as fd:
return sum(1 for _ in fd) |
def is_dir_hidden(dir):
"""this code tests if a directory is hidden (has a ./<name> format) and returns true if it is hidden"""
slash_id=[]
for i in range(0, len(dir)):
if dir[i]=="/":
slash_id.append(i)
if dir[slash_id[len(slash_id)-1]+1]==".":
return True
else :
... |
def center(size, fit_size, offset):
"""
Center a given area within another area at an offset.
Arguments:
size: a tuple containing the width and height of the area to be centered.
fit_size: a tuple containing the width and heigh of the area in which to
center 'size'
offset: a tuple represent... |
def build_bsub_command(command_template, lsf_args):
"""Build and return a lsf batch command template
The structure will be 'bsub -s <key> <value> <command_template>'
where <key> and <value> refer to items in lsf_args
"""
if command_template is None:
return ""
full_command = 'bsub -o... |
def lineincols (inlist, colsize):
"""
Returns a string composed of elements in inlist, with each element
right-aligned in columns of (fixed) colsize.
Usage: lineincols (inlist,colsize) where colsize is an integer
"""
outstr = ''
for item in inlist:
if not isinstance(item, str):
item... |
def _isint(string):
"""
returns true if string can be cast as an int,
returns zero otherwise
"""
try:
f = float(string)
except:
return False
if round(f) - f == 0:
return True
return False |
def explode_string(text):
"""Returns a list containing all the chars in <txt> one by one"""
chars = []
for char in text:
chars.append(char)
return chars |
def column_converter(cname, gn2conv):
"""
helper function to apply to each of the
column names in the geno dataframe (i.e., the
gene network names of each BXD
"""
if cname == "marker": return cname
else:
if cname in gn2conv: return gn2conv[cname]
else: return "NOT_IN_METADATA... |
def get_baji(b, a, j, i, no):
"""Function:
Search the position for baji in the spin-adapted index
Author(s): Takashi Tsuchimochi
"""
bj = b*no + j
ai = a*no + i
if bj > ai:
baji = bj*(bj+1)//2 + ai
else:
baji = ai*(ai+1)//2 + bj
return baji |
def conjx(x, *args):
"""Return the conjugate of x multiplied by arguments *args."""
result = x.conjugate()
for y in args:
result *= y
return result |
def s_sort_rec(seq, i=None):
""" perform selection sort recursively """
# if the sequence is empty return it
if not seq:
return seq
if i is None:
i = len(seq)-1
if i == 0:
return
max_ind, _ = max(enumerate(seq[0:i+1]), key=lambda x: x[1])
seq[max_ind], seq[i] = seq[i]... |
def parsePeakIntensity(lines):
"""#!/usr/bin/python
Args:
lines: all information on all identified molecular lines (nested list)
Returns:
list of peak intensity of all identified molecular lines (list)
"""
result = []
for line in lines:
peakIntensity = line["peakintensity... |
def convertFromRavenComment(msg):
"""
Converts fake comment nodes back into real comments
@ In, msg, converted file contents as a string (with line seperators)
@ Out, string, string contents of a file
"""
msg=msg.replace('<ravenTEMPcomment>','<!--')
msg=msg.replace('</ravenTEMPcomment>','-->')
ret... |
def write_float_11e(val: float) -> str:
"""writes a Nastran formatted 11.4 float"""
v2 = '%11.4E' % val
if v2 in (' 0.0000E+00', '-0.0000E+00'):
v2 = ' 0.0'
return v2 |
def _bounce(open, close, level, previous_touch):
"""
did we bounce above the given level
:param open:
:param close:
:param level:
:param previous_touch
:return:
"""
if previous_touch == 1 and open > level and close > level:
return 1
elif previous_touch == 1 and open < le... |
def wipe_out_eol(line):
""" wipe out EOL. """
assert line[-1:] == '\n'
if line[-2:-1] == '\r':
return line[:-2]
else:
return line[:-1] |
def luaquote(string):
"""Quotes a python string as a Lua string literal."""
replacements = [
('\\', '\\\\'),
('\'', '\\\''),
('\n', '\\n'),
]
for old, new in replacements:
string = string.replace(old, new)
return '\'' + string + '\'' |
def known_domain_data(known_uid, known_verbose_name, known_os_type):
"""Known domain data fields."""
return {
'id': known_uid,
'verbose_name': known_verbose_name,
'os_type': known_os_type
} |
def histogram(data):
"""Returns a histogram of your data.
:param data: The data to histogram
:type data: list[object]
:return: The histogram
:rtype: dict[object, int]
"""
ret = {}
for datum in data:
if datum in ret:
ret[datum] += 1
else:
ret[datum... |
def triplets(a, b, c):
"""
Time: O(n)
Space: O(n lg n), for sorting
-
n = a_len + b_len + c_len
"""
a = list(sorted(set(a)))
b = list(sorted(set(b)))
c = list(sorted(set(c)))
ai = bi = ci = 0
a_len, c_len = len(a), len(c)
answer = 0
while bi < len(b):
while ... |
def get_json_field(json_data, field_names):
"""This function retrieves a value for a specific field from the JSON data for a user.
.. versionchanged:: 3.1.0
Refactored the function to be more efficient.
:param json_data: The JSON data from which the field value must be retrieved
:type json_data... |
def rename_labels_to_internal(x):
"""Shorten labels and convert them to lower-case."""
return x.replace("Experience", "exp").lower() |
def list_resources(technologies):
"""List resources (there are no technologies that produce them)."""
inputs = set(i.name for t in technologies for i in t.inputs)
outputs = set(i.name for t in technologies for i in t.outputs)
return inputs - outputs |
def unload_fields( obj, fields ):
"""
The complement of load_fields().
@param obj Source object to read
@param fields Field definition list
@return List of data fields suitable for a binary pack
"""
data = []
for field in fields:
value = 0
for ... |
def clean_int(s):
""" Clean an integer """
while len(s)>0:
if s[0]==' ':
s=s[1:]
continue
if s[-1] in " ,":
s=s[0:-1]
continue
break
return int(s) |
def _rstrip(line, JUNK='\n \t'):
"""Return line stripped of trailing spaces, tabs, newlines.
Note that line.rstrip() instead also strips sundry control characters,
but at least one known Emacs user expects to keep junk like that, not
mentioning Barry by name or anything <wink>.
"""
i = len(lin... |
def sort_states(state, columns, reverse=True):
"""
Sort the states according to the list given by prioritize_jobs.
prioritize_jobs (or columns in this case) is list of according to
which state should be prioritized for job submission. The position
in the list indicates the prioritization. columns =... |
def evaluateCondition(instructionLine, dict):
"""
Evaluate the condition for a line of instruction
"""
register,sign,num = [el for el in instructionLine.split()][-3:]
return eval(f'dict["{register}"] {sign} {num}') |
def get_prev_page_pointer(words, line_breaks):
"""
Finds the start position of the last word in the page
immediately preceding the current one.
Parameters
----------
words: list
The words in the previous page
line_breaks:
The words split across a line in the previous page
... |
def bernoulli_prob(var, bias=0.5):
""" Returns Sympy-expression of a Bernoulli PMF for var at specified bias.
:param var: boolean symbol to express pmf
:param bias: bias probability (float ranging from 0 to 1).
:return bias*var + (1-bias)*(1-var)
"""
# bv + (1-b)(1-v) = bv + 1 - v - b + bv = 2bv - v - b +... |
def find(f, seq):
"""
Search for item in a list
Returns: Boolean
"""
for item in seq:
if (f == item):
return True
return False |
def _filter_pairs_in (pair_list,dict_context) :
"""Filter the pairs based on the fact that some pronouns allow pairs where the
pronoun is the first and the mention appears after"""
good_pair_list=[]
for pair in pair_list :
pron=pair[1][0]
difference=int(pair[1][-1])-int(pair[0][-1])
... |
def total_cost(J_content, J_style, alpha = 10, beta = 40):
"""
Arguments:
J_content -- content cost coded above
J_style -- style cost coded above
alpha -- hyperparameter weighting the importance of the content cost
beta -- hyperparameter weighting the importance of the style cost
Returns:
... |
def decode_str(string):
"""Convert a bytestring to a string. Is a no-op for strings.
This is necessary because python3 distinguishes between
bytestrings and unicode strings, and uses the former for
operations that read from files or other operations. In general
programmatically we're fine with just... |
def delete_fav_msg(bus_stop_code):
"""
Message that will be sent if user delete a bus stop code from their favourites
"""
return 'Bus Stop Code /{} has been deleted! \n\n' \
'To add another bus stop code, type: /add_favourites [BUS STOP CODE]' \
'\n\n e.g: /add_favourites 14141'.f... |
def dict_key_filter(function, dictionary):
"""
Filter dictionary by its key.
Args:
function: takes key as argument and returns True if that item should be
included
dictionary: python dict to filter
"""
return {k: v for k, v in dictionary.items() if function(k)} |
def _parse_or(t):
"""Evaluate OR t."""
try:
return t[0]["lhs"]
except KeyError:
try:
return t[0]["rhs"]
except KeyError:
return False |
def ij2M(ij):
"""
Convert (i, j) indices of a symmetric
2nd-order tensor to its vector index
"""
if ij == "11":
return 0
elif ij == "22":
return 1
elif ij == "33":
return 2
elif ij == "12" or ij == "21":
return 3
elif ij == "23" or ij == "32":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.