content stringlengths 42 6.51k |
|---|
def _apply_labels(__data__, labels):
"""
Filters out the tests whose label doesn't match the labels given when
running audit and returns a new data structure with only labelled tests.
"""
if labels:
labelled_data = []
for item in __data__['fdg']:
if isinstance(item, dict)... |
def print_settings(settings):
"""
This function returns the harmonic approximation settings .
Returns
-------
text: str
Pretty-printed settings for the current Quantas run.
"""
text = '\nCalculator: Equation of state (EoS) fitting\n'
text += '\nMeasurement units\n'
text +... |
def select_id_from_scores_dic(id1, id2, sc_dic,
get_worse=False,
rev_filter=False):
"""
Based on ID to score mapping, return better (or worse) scoring ID.
>>> id1 = "id1"
>>> id2 = "id2"
>>> id3 = "id3"
>>> sc_dic = {'id1' : 5, 'id2': ... |
def check(status, check_item):
"""
Check the status for a specific type of item (by prefix).
:returns: a string containing the number of items matching and an
explanation of the status.
"""
states = {}
state_descriptions = {
"ImagePullBackOff": "Unable to pull the image spe... |
def _data_available(param: str) -> bool:
"""
Tests whether data is available or not
:param param: The data to test
:return: Whether it's available or not
"""
return not (param is None or param == "") |
def clip_cdr3s(cdr3s,clip):
"""Clip amino acids from the ends of the given cdr3s, clip[0] from beginning and clip[1] from the end.
Clipping should be done after the alignment."""
for i in range(len(cdr3s)):
cdr3s[i]=cdr3s[i][clip[0]:-clip[1]]
return cdr3s |
def extractClassBody(body:str):
"""
This method takes everthing after the first curly bracket until the last curly bracket.
It is intended to be used for Java Classes that have the first curly bracket after class XZ
and with a last closing bracket.
It does not work as intended for files with mult... |
def combine(hi, lo):
# type: (int, int) -> int
"""Combine the hi and lo bytes into the final ip address."""
return (hi << 64) + lo |
def find_uniq(arr):
"""Return unique integer in array."""
sort = sorted(arr)
if (sort[0] < sort[len(sort) - 1] and sort[0] < sort[len(sort) - 2]):
n = sort[0]
else:
n = sort[len(sort) - 1]
return n |
def match_one_regex(string: str, patterns) -> bool: # type: ignore
"""
If string matches one or more from patterns
:param string: string
:param patterns: List of regex pattern
:return:
"""
if not isinstance(string, str):
return False
if len(patterns) == 0:
return False
... |
def format_arg_value(arg_val):
""" Return a string representing a (name, value) pair.
>>> format_arg_value(('x', (1, 2, 3)))
'x=(1, 2, 3)'
"""
arg, val = arg_val
return "%s=%r" % (arg, val) |
def _to_ns(val, unit):
"""
Convert an input time in the specified units to nanoseconds
Parameters
----------
val: int
Input time value
unit : str
Time units of `val`.
One of 's', 'ms', 'us', 'ns'
Returns
-------
int
Time val in nanoseconds
"""
... |
def original_id(individualized_id):
"""
Gets the original id of an ingredient that has been transformed by individualize_ingredients()
Args:
individualized_id (str):
Returns:
str:
Examples:
>>> original_id('en:water**')
'en:water'
>>> original_id('en:sugar'... |
def merge(d1, d2, merge_fn=lambda x,y: x+y):
"""
Merges two dictionaries, non-destructively, combining
values on duplicate keys as defined by the optional merge
function. The default behavior replaces the values in d1
with corresponding values in d2. (There is no other generally
applicable me... |
def get_cex_prefixes(cex, automaton_type):
"""
Returns all prefixes of the stochastic automaton.
Args:
cex: counterexample
automaton_type: `mdp` or `smm`
Returns:
all prefixes of the counterexample based on the `automaton_type`
"""
if automaton_type == 'mdp':
r... |
def _get_parents(folds, linenum):
"""
Get the parents at a given linenum.
If parents is empty, then the linenum belongs to the module.
Parameters
----------
folds : list of :class:`FoldScopeHelper`
linenum : int
The line number to get parents for. Typically this would be the
... |
def pop_param(request_values, name, default=None):
""" Helper to pop one param from a key-value list
"""
for param_name, value in request_values:
if param_name.lower() == name:
request_values.remove((param_name, value))
return value
return default |
def RT_BIT_64(iBit): # pylint: disable=C0103
""" 64-bit one bit mask. """
return 1 << iBit; |
def gen_anonymous_varname(column_number: int) -> str:
"""Generate a Stata varname based on the column number.
Stata columns are 1-indexed.
"""
return f'v{column_number}' |
def frequency_score(code):
"""
Scores letter frequency of an code represented as a bytes object. Starts with code_score = 1, then for each character in the code, multiplies the code_score by the frequency of that letter. If not a space or a letter, multiplies by .0001 to penalize weird characters.
Higher Fr... |
def search_improved(L, e):
"""Assume L is a List, teh elemets in teh list are ordered in ascending order.
Return True if e is in L and False otherwise."""
for i in range(len(L)):
if L[i] == e:
return True
if L[i] > e:
return False
return False |
def min_threshold(x, thresh, fallback):
"""Returns x or `fallback` if it doesn't meet the threshold. Note, if you want to turn a hyper "off" below,
set it to "outside the threshold", rather than 0.
"""
return x if (x and x > thresh) else fallback |
def _is_output(part):
""" Returns whether the given part represents an output variable. """
if part[0].lower() == 'o':
return True
elif part[0][:2].lower() == 'o:':
return True
elif part[0][:2].lower() == 'o.':
return True
else:
return False |
def delete_list_of_keys( d, *keys ):
"""
elimina las keys de un dicionario
Parameters
==========
d: dict
dicionario del que se eliminaran las keys
keys: tuple
llaves a eliminar
Examples
========
>>>origin = { 'a': 'a', 'b': 'b': 'c': 'c' }
>>>delete_list_of_keys... |
def MakeDateRevision(date):
"""Returns a revision representing the latest revision before the given
date."""
return "{" + date + "}" |
def get_slope(x1, y1, x2, y2):
""""Get slope between 2 points"""
num = y2 - y1
den = x2 - x1
return float(num) / float(den) |
def answer_dict(my_list):
"""Get an item from a list"""
for i in my_list:
return i |
def prepare_ids_str(ids: dict) -> str:
"""Prepare string with EntitySet IDs."""
if isinstance(ids, dict):
# Generate ID string (id1='value',id2='value')
ids_str = ','.join("{}='{}'".format(k, v) for k, v in ids.items())
ids_str = '({})'.format(ids_str)
return ids_str
elif ids... |
def dict_fields(obj, parent=[]):
"""
reads a dictionary and returns a list of fields cojoined with a dot
notation
args:
obj: the dictionary to parse
parent: name for a parent key. used with a recursive call
"""
rtn_obj = {}
for key, value in obj.items():
n... |
def bound(x, m, M=None):
"""Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR*
have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1].
Args:
x: scalar
Returns:
x: scalar, bound between min (m) and Max (M)
"""
if M is None:
... |
def bash_quote(text):
"""Quotes a string for bash, by using single quotes."""
if text == None:
return ""
return "'%s'" % text.replace("'", "'\\''") |
def replace_ext(path):
"""
Replace the extension (.jpg or .png) of path to .npy
parameters
----------
path: path that we want to replace the extension to .npy
returns
-------
path: new path whose extension is already changed to .npy
"""
if ".jpg" in path:
path = p... |
def waste_timeseries(isotopes, mass_timeseries, duration):
"""Given an isotope, mass and time list, creates a dictionary
With key as isotope and time series of the isotope mass.
Parameters
----------
isotopes: list
list with all the isotopes from resources table
mass_timeseries: list... |
def merge(source, destination):
"""
run me with nosetests --with-doctest file.py
a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
merge(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'n... |
def ones(m,n):
"""Return an m-by-n arrayList consisting of all ones.
>>> ones(2,3)
[[1, 1, 1], [1, 1, 1]]
"""
return m * [n * [1]] |
def cli_echo(argv: list):
""" Help message here """
message = f"argv: {argv}"
return message |
def binary_to_decimal(decimal_num: str):
"""
Converts binary number to decimal number.
@return: <int> int of the decimal number
"""
decimal_string = str(decimal_num)
if len(decimal_string) > 0:
first = decimal_string[0]
current = 2**(len(decimal_string) - 1) if first == '1' else ... |
def _between_symbols(string, c1, c2):
"""Grab characters between symbols in a string.
Will return empty string if nothing is between c1 and c2."""
for char in [c1, c2]:
if char not in string:
raise ValueError("Couldn't find character {} in string {}".format(
char, string)... |
def format_content(_content, _language="brainfuck"):
"""
some fancy highlighting.
"""
return f"```{_language}\n{_content}```" |
def ReadableSize(num):
"""Get a human-readable size."""
for unit in ['B', 'KB', 'MB', 'GB']:
if abs(num) <= 1024.0:
return '%3.2f%s' % (num, unit)
num /= 1024.0
return '%.1f TB' % (num,) |
def get_equivalence_expressions(strings):
"""
get a list of strings in the format of name=some expression from a list of strings. It is expected that a whole string is split by space to form the input string list
:param strings: the input string list. It is assumed to be once a whole string with space delimiter
:re... |
def trimLines(lines, stats=False):
"""Remove leading and trailing blank lines from a seqence of lines.
:Parameters:
lines
The lines to be trimmed. May be a sequences or generator.
stats
If supplied and true then trimmed lines statistics are include in the
return value.
... |
def _or(queries):
"""
Returns a query item matching the "or" of all query items.
Args:
queries (List[str]): A list of query terms to or.
Returns:
The query string.
"""
if len(queries) == 1:
return queries[0]
return "{" + ' '.join(queries) + "}" |
def divide_sizes(count, n): # pylint: disable=invalid-name
"""Evenly divide a count.
Arguments
---------
count : integer
The number to be evenly divided
n : integer
The number of buckets in which to divide the number
Returns
-------
A list of int... |
def insertion_sort(lst):
"""Insertion sort."""
for i in range(0, len(lst) - 1):
if lst[i] > lst[i+1]:
# import pdb; pdb.set_trace()
lst[i], lst[i + 1] = lst[i + 1], lst[i]
j = i
if j - 1 != -1:
while lst[j] < lst[j - 1]:
... |
def abbrToID(data):
"""
This function is designed to convert abbreviations to their airportID. For use with non-SparkDF datatypes.
Input: A String, representing the airport Code
Output: an Integer, representing the airportID
"""
if data == "ATL":
data = 10397
elif data == "BOS":
data = 10721
... |
def validate_notification(notification, valid_events):
"""
Validate a notification
"""
for item in notification:
if item not in ('event', 'type'):
return (False, 'invalid item "%s" in notifications' % item)
if item == 'event':
if notification[item] not in valid_ev... |
def backtrack2(f0, g0, x1, f1, b1=0.1, b2=0.5):
""" Safeguarded parabolic backtrack
"""
# parabolic backtrack
x2 = -g0*x1**2/(2*(f1-f0-g0*x1))
# apply safeguards
if x2 > b2*x1:
x2 = b2*x1
elif x2 < b1*x1:
x2 = b1*x1
return x2 |
def cipher(number):
"""cipher the number if not present return number"""
code = {
'1': '9',
'2': '8',
'3': '7',
'4': '6',
'5': '0',
'6': '4',
'7': '3',
'8': '2',
'9': '1',
'0': '5',
}
return code.get(number, number) |
def get_unique_patterns(query_result):
"""
Sorts all node names,
then returns a set of tuples with only unique node names.
:param query_result: Neo4j query outcome (list of dictionaries)
:return:
"""
all_motifs = [[y['name'] for y in x['p'] if type(y) == dict] for x in query_result]
if '... |
def _generate_summary(sentences, sentenceValue, threshold):
"""get the summary: if value above the threshold
Args:
sentences (list): all sentences
sentenceValue (dict): the dict storing its value
threshold (int): threshold to select sentences
Returns:
(str): summary
"""... |
def replace_dictated(data):
"""
This is a workaround to handle dictation (spoken word audio containing punctuation),
in case the cloud api does not provide adequate support for properly converting dictation to punctuation.
:param data:
:return:
"""
return data.replace(" period", ".") \
... |
def getMag(mb, MS):
"""
:param mb:
:param MS:
:return: The available magnitude, or the average if both exist.
"""
if mb > 0 and MS > 0:
return (mb + MS) / 2
elif mb == 0:
return MS
else:
return mb |
def get_default_titles(combine, plot_data, nfunc_list, **kwargs):
"""Get some default titles for the plots."""
adfam = kwargs.pop('adfam', False)
adfam_nn = kwargs.pop('adfam_nn', False)
true_signal = kwargs.pop('true_signal', True)
if kwargs:
raise TypeError('Unexpected **kwargs: {0}'.forma... |
def getMatrixMinor(m,i,j):
"""
returns minors of a mtrix
"""
return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])] |
def format_strings_for_cmd(input_list):
"""Transform a list of string into cmd compatible command.
Parameters
----------
input_list : list of strings
Strings to transform.
Returns
-------
str
Command like string to be passed as command option.
"""
return "['" + "', ... |
def generate_file(size_in_mb: int) -> bool:
"""
Generate a file of a given size in MB
Max size is 5 GB
"""
if size_in_mb > 5000:
raise ValueError("File size cannot be greater than 5GB")
with open(f"{size_in_mb}MB.bin", "wb") as f:
f.seek(size_in_mb * 1024 * 1024 - 1)
f.w... |
def get_item_details(item):
"""
This function finds packgen details using item
:param item: item is a string containing packgen content type
:return: it returns dict of details of packgen.
"""
details = {'Estimated Time of Delivery':'Na','priority':'Na','cost':'Na','item':'Na'}
if item == u... |
def intToBin(i):
""" Integer to two bytes """
# devide in two parts (bytes)
i1 = i % 256
i2 = int(i / 256)
# make string (little endian)
return chr(i1) + chr(i2) |
def flatten(l):
"""Make a list of dict with unique keys into one dict."""
if not isinstance(l, list):
return l
flat = {}
for d in l:
flat.update(d)
return flat |
def get_signature(*args, **kwargs):
""" Gets printable function signature"""
args_repr = [repr(a) for a in args]
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
signature = ", ".join(args_repr + kwargs_repr)
return signature |
def edit_distance(s: str, t: str):
"""
Return the edit distance between the strings s and t.
The edit distance is the sum of the numbers of insertions, deletions,
and mismatches that is minimally necessary to transform one string
into the other.
"""
m = len(s) # index i
n = len(t) # in... |
def merge_and_count_inversions(first_array, second_array):
"""Merges two arrays into one, forming sorted array. Counts split inversions
Uses results array for return.
Args:
first_array: first merged array
second_array: second merged array
Returns:
tuple: first element is sorted... |
def parse_and_validate_ipv4(argument, name):
"""
Each address must have 4
"""
if len(argument.split(".")) != 4:
print("Invalid %s, must be of the form xxx.yyy.zzz.www" % name)
exit(-1)
parsed = ""
for x in argument.split("."):
if len(x) > 3:
print("Invalid %s... |
def flipra(coordinate):
"""Flips RA coordinates by 180 degrees"""
coordinate = coordinate + 180
if coordinate > 360:
coordinate = coordinate - 360
return coordinate |
def multiset(list_):
"""Returns a multiset (a dictionary) from the input iterable list_."""
mset = dict()
for elem in list_:
try:
mset[elem] += 1
except KeyError:
mset[elem] = 1
return mset |
def torsion_stress(T, r, J):
""" Torsion stresses
:param float T: Cross section torque
:param float r: Stress radius coordinate
:param float J: Cross section polar moment of inertia
:returns: Torsion Stress at r
:rtype: float
"""
return (T * r) / J |
def _hasattr(subklass, attr):
"""Determine if subklass, or any ancestor class, has an attribute.
Copied shamelessly from the abc portion of collections.py.
"""
try:
return any(attr in B.__dict__ for B in subklass.__mro__)
except AttributeError:
# Old-style class
return hasatt... |
def color_diff_par(pair):
"""
Find the difference between two colors. This is part of `closest_color_parallel`
below, but multiprocessing cannot pickle nested functions.
Parameters
----------
pair : (rgb, pixel)
Check how close `rgb` is to `pixel`.
Returns
-------
int
... |
def moeda(preco=0, moeda='R$'):
"""
-> Formata um preco com o padrao real brasileiro
:param preco: o valor a ser formatado
:param moeda: a sigla da moeda
:return: retorna uma string formatada de acordo com o padrao monetario do Brasil
"""
return f'{moeda}{preco:.2f}'.replace('.', ',') |
def B(u,bits):
"""
B(u,bits)
Map too small values into attractor.
This function differs from the one defined in [Pisarchik].
"""
return u & ((1 << bits) - 1) |
def remove2(str_lst: list, sub: str) -> tuple:
"""Write a function that accepts a list of strings and another string that removes that string from the list
without list iteration or list methods (aka only string methods).
It should return a tuple with the updated string, number of deletions, and the indexes of the ... |
def permute(idx, values):
"""Find all possible arrangement of a given set of letters.
When we choose a pair we apply backtracking to verify if that exact pair
has already been created or not. If not already created, the pair is added
to the answer list else it is ignored.
Arguments:
idx {int... |
def postprocess_misc_args(misc_args):
"""
Postprocesses the misc_args dict to include any new keys.
"""
new_keys = ['optimize_targets',
'model_value_targets',
'direct_targets',
'off_policy_targets',
'target_inf_value_targets',
... |
def str_point(point: tuple, precision: int = 1):
"""Return a printed tuple with precision"""
prec_str = "{:." + str(precision) + "f}"
format_str = "(" + prec_str + ", " + prec_str + ")"
x, y = point
return format_str.format(x, y) |
def find_spelling(n):
"""
Finds d, r s.t. n-1 = 2^r * d
"""
r = 0
d = n - 1
# divmod used for large numbers
quotient, remainder = divmod(d, 2)
# while we can still divide 2's into n-1...
while remainder != 1:
r += 1
d = quotient # previous quotient before ... |
def _get_image_number(image_file_name: str) -> int:
"""Get the number of the image file with a particular pattern at a particular site.
Args:
image_file_name (str): Name of the file
Examples:
>>> _get_image_number('Ni Patterns 0 Deformation Specimen 1 Speed2 Map Data 2_0001.tiff')
... |
def appendAssignToNullCommand(Command: str) -> str:
"""pipe the given string Command with assign to null Command\n
Return type: String
"""
return f'{Command} > /dev/null' |
def is_buggy_ua(agent):
"""Discrimiate CSS served to clients based on User Agent
Due to QTBUG-3467, @font-face is not supported in QtWebKit.
This may get fixed in the future, but for right now we can
just serve the more conservative CSS to all our desktop apps.
"""
return ("Humbug Desktop/" in ... |
def delete_com_line(line : str) -> str:
"""Deletes comments from line"""
comm_start = line.find("//")
if comm_start != -1:
line = line[:comm_start]
return line |
def server_parse(server, default_port):
"""
Convert a server string to a tuple suitable for passing to connect, for
example converting 'www.google.com:443' to ('www.google.com', 443).
:param str server: The server string to convert.
:param int default_port: The port to use in case one is not specified
in the se... |
def create_tables(name,string_columns):
"""Returns string used to produce
CREATE statement.
Parameters
----------
name : string
indicates the name of the table to create.
string_columns : string
list of columns to create.
Returns
-------
query : string
"""
c... |
def parse_slice(token):
"""Parse a single slice string
:param token: A string containing a number [3], a range [3:7] or a colon [:]
:returns: An integer for simple numbers, or a slice object
"""
try:
return int(token)
except ValueError:
if token == ':':
return ...
... |
def tuples_to_spans(tree):
"""
Returns list of spans, that are (start, size).
"""
result = []
def helper(tr, pos=0):
if isinstance(tr, str):
return 1
size = 0
for x in tr:
subsize = helper(x, pos=pos+size)
size += subsize
result.a... |
def get_fact_path_str(fact):
"""
return a string like `BEVZ20(GES:GESM,ALTX20:ALT075UM)` to describe the
selection of dimensions (without region & time) for this fact
[sort args alphabetically]
"""
# FIXME implementation
attributes = [k for k, v in fact.items() if k.isupper() and isinstance(... |
def list_to_string(lst):
"""Takes a list of items (strings) and returns a string of items separated
by semicolons.
e.g.
list_to_string(['John', 'Alice'])
#=> 'John; Alice'
"""
return "; ".join(lst) |
def basefolder(path: str) -> str:
"""
get 'train_folder/train/o' from 'train_folder/train/o/17asdfasdf2d_0_0.jpg'
Args:
path (str): [description]
Returns:
str: [description]
"""
return "/".join(path.split("/")[:-1]) |
def convert_time_to_ms(driver_dict):
"""
This function loops through the race results and converts a string with the time in the format mm:ss:msms
to a single value in milliseconds (ms).
Parameters:
driver_dict (dict): A dictionary representation of a driver's race result.
Returns:
... |
def dict_to_tuple_key(dictionary):
"""Converts a dictionary to a tuple that can be used as an immutable key.
The resulting key is always sorted so that logically equivalent dictionaries
always produce an identical tuple for a key.
Args:
dictionary: the dictionary to use as the key.
Returns:
A tuple... |
def _make_divisible(v, divisor, min_value=None):
"""
It ensures that all layers have a channel number that is divisible by 8
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down... |
def name_to_number(name):
"""
Helper function that converts the string "name" into
a "number" between "0" and "4" in the way described below.
0 - rock
1 - Spock
2 - paper
3 - lizard
4 - scissors
"""
# Define a variable that will hold the computed "number"
... |
def square_digits(num):
"""
Welcome. In this kata, you are asked to square every digit of a number.
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
Note: The function accepts an integer and returns an integer
:param num: input integer value.
... |
def encode(text):
"""
Replace special symbols as per https://api.slack.com/docs/message-formatting.
"""
return text.replace('&', '&').replace('<', '<').replace('>', '>') |
def define_engine(engine_option_value):
"""
Define engine files, and options.
"""
optdict = {}
engineinfo = {'cmd': None, 'opt': optdict}
for eng_opt_val in engine_option_value:
for value in eng_opt_val:
if 'cmd=' in value:
engineinfo.update({'cmd': value.spl... |
def bs(s: int) -> str:
"""Converts an int to its bits representation as a string of 0's and 1's.
"""
return str(s) if s <= 1 else bs(s >> 1) + str(s & 1) |
def ipv4_cidr_to_netmask(bits):
"""Convert CIDR bits to netmask """
netmask = ''
for i in range(4):
if i:
netmask += '.'
if bits >= 8:
netmask += '%d' % (2**8-1)
bits -= 8
else:
netmask += '%d' % (256-2**(8-bits))
... |
def apply_function(fn, *args):
"""Deprecated function, equivalent to fn(*args).
In previous versions of tf.Transform, it was necessary to wrap function
application in `apply_function`, that is call apply_function(fn, *args)
instead of calling fn(*args) directly. This was necessary due to limitations
in the ... |
def matchSimilarity(s1, s2):
"""
Calcualte the match similarity.
"""
if s1==s2:
return 1.0
else:
return 0.0 |
def add(v, w) :
"""Adds corresponding elements"""
assert len(v) == len(w), "vectors must be the same length"
return [v_i + w_i for v_i, w_i in zip(v, w)] |
def get_private_ips_for_instances(instances):
"""" Take list of instances (as returned by create_instances), return private IPs. """
return [instance.private_ip_address for instance in instances] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.