content stringlengths 42 6.51k |
|---|
def _dic_of_conflicting_args(cli_model, command):
"""
Creates a dictionary object with argument as a key and a set of its non-conflicting args as value.
Parameters
----------
cli_model(dict): A dictonary object which contains CLI arguments and sub-commands at each command level.
command(str... |
def max_char(s):
"""
Given a string, return the character that has the most
occurrences in the string.
max_char("abccccccd") == "c"
max_char("apple 1231111") == "1"
"""
max_val = 0
max_c = ''
c_map = dict()
for c in s:
if c not in c_map.keys():
c_map[c] = 0
... |
def quick_sort(arr):
""" Sorts an array by choosing a pivot point, then placing all values
less than the pivot point value before the pivot point, and all
values greater than the pivot point value after the pivot point.
Returns a list in acescending order.
"""
if len(arr) < 2:
... |
def length_sort(items, lengths, descending=True):
"""In order to use pytorch variable length sequence package"""
items = list(zip(items, lengths))
items.sort(key=lambda x: x[1], reverse=True)
items, lengths = zip(*items)
return list(items), list(lengths) |
def format_oneline(s, max_width=65):
""" Return a string formatted for a line print """
if len(s) > max_width:
padding = " ... "
n = (max_width - len(padding)) // 2
q = (max_width - len(padding)) % 2
if q == 0:
return "".join([s[0:n], padding, s[-n:]])
else:
... |
def ordinal(value):
"""
Converts zero or a *positive* integer (or its string
representation) to an ordinal value.
"""
try:
value = int(value)
except ValueError:
return value
if value % 100 // 10 != 1:
if value % 10 == 1:
ordval = u"%d%s" % (value, "st")
... |
def compute_orientation_price(start_orientation: int, wanted_orientation: int) -> int:
"""
Return price o rotating bot from start orientation to wanted_orientation.
:param start_orientation: Starting orientation of rotating.
:param wanted_orientation: Ending orientation of rotating.
:return: price o... |
def foo2(value):
"""
foo2 Bare return statement implies `return None`
:param value:
:return:
"""
if value:
return value
else:
return |
def trick_for_cartpole(done, reward):
"""
trick for speed up cartpole training
if done, which means agent died, set negtive reward,
which help agent learn control method faster.
"""
if done:
return -100
return reward |
def to_language(locale):
"""Turns a locale name (en_US) into a language name (en-us)."""
p = locale.find('_')
if p >= 0:
return locale[:p].lower() + '-' + locale[p + 1:].lower() |
def get_dims(plot_objs):
"""
Gets the appropriate dimensions for the amount of objects going to be plotted.
Adds columns before rows.
"""
total = len(plot_objs)
row, col = 1, 1
while True:
if row * col >= total:
break
elif col == row:
col += 1
... |
def extract_user_gql(data):
"""For Public GraphQL API
"""
return {
"pk": int(data["id"]),
"username": data["username"],
"full_name": data["full_name"],
"is_private": data["is_private"],
"profile_pic_url": data["profile_pic_url"],
"is_verified": data.get("is_ve... |
def combine_extensions(lst):
"""Combine extensions with their compressed versions in a list.
This is a basic solution to combining extensions with their
compressed versions in a list. Something more robust could
be written in the future.
Parameters
----------
lst : list of str
"""
... |
def extract_params(params):
"""
Extracts the values of a set of parameters, recursing into nested dictionaries.
"""
values = []
if isinstance(params, dict):
for key, value in params.items():
values.extend(extract_params(value))
elif isinstance(params, list):
for value... |
def from_list(commands):
"""
Given a list of tuples of form (depth, text)
that represents a DFS traversal of a command tree,
returns a dictionary representing command tree.
"""
def subtrees(commands, level):
if not commands:
return
acc = []
parent, *commands... |
def is_int(s):
""" :return True iff s can be converted to an integer using int() """
try:
int(s)
return True
except ValueError:
return False |
def _exceeded_threshold(number_of_retries: int, maximum_retries: int) -> bool:
"""Return True if the number of retries has been exceeded.
Args:
number_of_retries: The number of retry attempts made already.
maximum_retries: The maximum number of retry attempts to make.
Returns:
True... |
def _convert_text_to_logs_format(text: str) -> str:
"""Convert text into format that is suitable for logs.
Arguments:
text: text that should be formatted.
Returns:
Shape for logging in loguru.
"""
max_log_text_length = 50
start_text_index = 15
end_text_index = 5
return... |
def lower_case(text: str) -> str:
"""Convert `text` to lower case.
Args:
text (str): The text to convert to lower case.
Returns:
The converted text.
"""
return text.lower() |
def longestString(listOfStrings):
"""
return longest string from a non-empty list of strings, False otherwise
By "longest", we mean a value that is no shorter than any other value in the list
There may be more than one string that would qualify,
For example in the list ["dog","bear","wolf","cat"... |
def getWindow(lst, index, window):
"""
:param lst: Some list
:param index: index at senter of window
:param window: window size -> +- window on each side
Total size of 2*window+1
"""
min_idx = index-window if index-window >= 0 else 0
max_idx = index+window if index+window < len(lst) else l... |
def is_pythagorean_triplet(a,b,c):
"""
This function takes 3 integers a, b and c and returns whether or not
those three numbers are a pythagorean triplet (i-e sum of square of a and b equel square of c).
"""
return a**2 + b**2 == c**2 |
def get_txtfilename(ID, era):
""" Return the txtfilename given by station ID and era in correct format."""
return era+'_'+ID+'.txt' |
def is_palindrome(palindrome):
"""
validates that the string palindrome is a
palindrome (it is a word or phrase that
read equal to right and back
param str palindrome is a word or Phrase
returns True if the word or phrase is a
palindorme or False if not.
"""
reversed_lette... |
def cmd(arg1, arg2):
"""
This is a command that does things. Yay!
@param arg1: The first argument.
@type arg1: L{something}
@param arg2: The second argument. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaa
@return: A thingy.
@rtype: L{Deferred}
"""
a = 1
a += 2
return a |
def keep_t2(filenames):
"""
Keeps only filenames which pertain to T2 weighted images and labels
Args:
filenames (list): a list of a list of filenames. T2 images are found
in indexes filenames[i][2].
Returns:
list of list: a list with len(filenames). Each element is a list of... |
def BuildCommitPosition(branch, value):
"""Returns: A constructed commit position.
An example commit position for branch 'refs/heads/master' value '12345' is:
refs/heads/master@{#12345}
This value can be parsed via 'ParseCommitPosition'.
Args:
branch: (str) The name of the commit position branch
va... |
def compare_strings_in_list(list_of_strings):
"""Compares the list of strings recursively, failing fast when it finds more than 1 non-matching character.
:param list_of_strings: The list of strings to iterate through, which gets smaller by one with each loop.
:return: The two strings that match.
-----... |
def _year_month_filter(threads, year=None, month=None):
"""
Filter a queryset containing a 'postdate' field by year/month.
"""
if month is not None and not 1 <= month <= 12:
return None
if year is not None:
threads = threads.filter(postdate__year = year)
# nested since there... |
def text_to_ascii(text):
"""Return list of integers corresponding to the ascii codes of
the characters of the text.
"""
output = []
for char in text:
output.append(ord(char))
return output |
def is_viewed_reminder_last_in_sequence(events, tag):
"""This function checks if the tag being viewed is a reminder.
If No it returns show=None.
If yes it creates a list of existing reminders in sequence,
if tag being viewed is the last item in the sorted existing reminders it returns show=true else fal... |
def reference_cluster(envs, name):
"""
Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'tes... |
def dict_diff(first, second):
""" Return a dict of keys that differ with another config object. If a value is
not found in one fo the configs, it will be represented by KEYNOTFOUND.
@param first: Fist dictionary to diff.
@param second: Second dicationary to diff.
@return diff: ... |
def ref_tuple_to_str(key, val):
"""Tuple like ('a', 'b') to string like 'a:b'."""
return '%s:%s' % (key, val) |
def check_uniqueness_in_rows(board: list):
"""
Check buildings of unique height in each row.
Return True if buildings in all rows have unique height, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215',\
'*35214*', '*41532*', '*... |
def parse_mailboxes(imap_mailboxes):
"""Translates the twisted imap4 result of listing mailboxes into a
list of names of mailboxes.
"""
return [entry[2] for entry in imap_mailboxes] |
def non_decreasing(L):
"""
https://stackoverflow.com/questions/4983258/python-how-to-check-list-monotonicity
"""
return all(x<=y for x, y in zip(L, L[1:])) |
def split_by_content_type(list_of_files, supported_extensions):
"""Split the files into a dict by type."""
d = {}
for file_type in supported_extensions:
d[file_type] = [f for f in list_of_files if file_type in f]
return d |
def cleanColnames(colnames):
"""
Fixes column names by deleting '[', ']'
Parameters
----------
colnames: list-str
Returns
-------
list-str
"""
return [s[1:-1] if s[0] == '[' else s for s in colnames] |
def clean_line(string, stop_char):
"""
# clean_line :: String char -> String
Receives a String and a 'stop_char'.
Scans the string backwards and cuts at the first 'stop_char', returning the new String
ex:
clean_line("this is a # string", '#') --> "thi... |
def split_choices(choices_string):
"""
Convert a comma separated choices string to a list.
"""
return [x.strip() for x in choices_string.split(",") if x.strip()] |
def outformat(data, defaultChannel='#kamtest'):
"""\
Takes tuple output from IRC_Client and formats for easier reading.
If a plaintext is received, outformat treats it as a privmsg intended for
defaultChannel (default "#kamtest").
"""
msgtype, sender, recipient, body = data
end = '\n'
if... |
def SFSeries(v):
"""
SFxxx series selector
:param v:
:type v: dict
:return:
:rtype: bool
"""
return "SF" in v["platform"] |
def create_event(event_type, data):
"""Return a dictionary containing the properties required when defining an
event.
Keyword arguments:
event_type -- the type of event, used to distinguish multiple events apart.
data -- a dictionary of key/value pairs containing custom data.
"""
return {
... |
def standardize_action(org_action):
"""if status is not book or change the flight number will be empty.
name is always required."""
# some human raters will end a name with . or ,
# since names in intent are standarlized (with - being replaced by space),
# it will not be necessary to consider - again in the a... |
def str2int(s):
"""converts a string to an integer with the same bit pattern (little endian!!!)"""
r = 0
for c in s:
r <<= 8
r += ord(c)
return r |
def find_brute(T, P):
"""Return the lowest index of T at which substring P begins (or else -1)."""
n, m = len(T), len(P) # introduce convenient notations
for i in range(n-m+1): # try every potential starting index within T
k = 0 # an index into pa... |
def update_postcode(postcode_value):
"""Update postcodes using mapping dictionary.
Takes postcode value, updates using postcode_mapping
dictionary and returns updated value.
"""
postcode_mapping = {'78621' : '78681', '787664' : '78664', '78728-1275' : '78728'}
if postcode_val... |
def _domreverse(r):
"""Reverse domain name, for proper sorting.
Input is string, output is list.
www.foo.com -> [com, foo, www]"""
r = r.split('.')
r.reverse()
return r |
def _get_normalized_query(data, query):
"""If you query with an _ in a query (e.g. from a wikipedia url, then wikipedia will "normalize" it,
so that it doesn't have the _ or other characters in it"""
normalized = data.get("query", {}).get("normalized")
if normalized:
for n in normalized:
... |
def assertion_with_name(name):
"""Returns a control assertion by name."""
all_control_assertions = ["Confidentiality", "Integrity", "Availability",
"Security", "Privacy"]
return next(assertion for assertion in all_control_assertions
if assertion == name.title()) |
def has_changes(new_data, old_data, chosen_cities=None):
"""
A (hopefully) useful method to quickly check if the state has changed.
"""
cities = chosen_cities or new_data.keys()
return any(old_data[c]['free_slots'] != new_data[c]['free_slots'] for c in cities) |
def _create_documents_per_words(freq_matrix):
"""create documents for each word
Args:
frequency matrix (dict)
Returns:
document per word
"""
word_per_doc_table = {}
# start counting
for sent, f_table in freq_matrix.items():
for word, count in f_table.items()... |
def _str_or_none(data):
"""Return str representation or None."""
return str(data) if data is not None else data |
def wakeWord(text):
""" function to check for wake word(s)
:type text:
:param text:text to check wake word
:rtype booleen
"""
WAKE_WORDS = ['hey computer', 'okay computer']
# Convert the text to all lower case words
text = text.lower()
# Check to see if the users command/text contain... |
def get_bgpvpn_differences(current_dict, old_dict):
"""Compare 2 BGP VPN
- added keys
- removed keys
- changed values for keys in both dictionaries
"""
set_current = set(current_dict.keys())
set_old = set(old_dict.keys())
intersect = set_current.intersection(set_old)
added = set_cu... |
def get_character_ngrams(w, n):
"""Map a word to its character-level n-grams, with boundary
symbols '<w>' and '</w>'.
Parameters
----------
w : str
n : int
The n-gram size.
Returns
-------
list of str
"""
if n > 1:
w = ["<w>"] + list(w) + ... |
def generate_new_amount(
amount: float, percentage_financial_amount_variation: int
) -> float:
"""
| Generate new amount from current amount.
| percentage_financial_amount_variation which is randomly sampled in `generate` between 1 and 20 to ensure coherence.
Parameters:
amount: The float r... |
def conv_out_size(i, p, k, s):
"""
Gets the output size for a 2D convolution. (Assumes square input and kernel).
@param i: The side length of the input.
@param p: The padding type (either 'SAME' or 'VALID').
@param k: The side length of the kernel.
@param s: The stride.
@type i: int
@t... |
def contains_str(attr, value, str_match):
""" return True if str_match is in 'value' of a given attribute, else False
"""
if isinstance(value, str): # if value is just a string
if str_match in value:
return True
elif isinstance(value, dict):
if str_match in str(value):
... |
def is_unique_id(lst):
"""To test if the generated IDs are unique."""
if len(lst) == len(set(lst)):
return True
return False |
def stdDevOfLengths(L):
"""
L: a list of strings
returns: float, the standard deviation of the lengths of the strings,
or NaN if L is empty.
"""
if not L:
return float('NaN')
mean = sum([len(t) for t in L]) / float(len(L))
quantities = [(len(t) - mean)**2 for t in L]
stdD... |
def pedersenOpen(n,g,h,m,r,c):
"""Open a pedersen commit. Arguments:
n modulus (i.e. Z*_n)
g generator 1
h generator 2
m message
r random
c commit generated by pedersenCommit() to verify"""
if c == g**m*h**r % n:
return True
else:
r... |
def sanitize(value):
"""Cleans up the url.
"""
if value.startswith('testgit::'):
value = value[9:]
return value |
def _check_convert_version(tup):
"""Create a PEP 386 pseudo-format conformant string from tuple tup."""
ret_val = str(tup[0]) # first is always digit
next_sep = '.' # separator for next extension, can be "" or "."
nr_digits = 0 # nr of adjacent digits in rest, to verify
post_dev = False # are we... |
def to_float(s):
"""Convert variable string to float."""
try:
return float(s.replace("d", "e"))
except ValueError:
# It's probably something like "0.0001-001"
significand, exponent = s[:-4], s[-4:]
return float("{}e{}".format(significand, exponent)) |
def sizeof_fmt(num, suffix='B'):
"""
Convert number of bytes in `num` into human-readable string representation.
Taken from https://stackoverflow.com/a/1094933
"""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
... |
def intersectIntervals(left, right):
"""Returns the intersection of two sorted lists of intervals.
Returns a sorted list of intervals"""
if left == []: return []
if right == []: return []
l0, l1 = left[0]
r0, r1 = right[0]
if l1 < r1: # l0,l1 will disappear first
rest = intersectIntervals(left[1:], right)
els... |
def ks_convert_llurl(ll_url: str) -> str:
"""
Convert a landsat look url to an S3 url
"""
return ll_url.replace('https://landsatlook.usgs.gov/data', 's3://usgs-landsat') |
def NumToDIM(x):
"""
Associates database dimensions with numerical values for iteration
Parameters:
x: (int) a number in a loop that is to be associated with a dimension ex(0->cycle)
"""
return {
0: 'cycle',
1: 'geo',
2: 'office',
3: 'party'
}.get(x) |
def make_divisible(value, divisor, min_value=None, min_ratio=0.9):
"""Make divisible function.
This function rounds the channel number to the nearest value that can be
divisible by the divisor. It is taken from the original tf repo. It ensures
that all layers have a channel number that is divisible by d... |
def split_sentence_id(sentence_id):
"""
Returns the original document ID and sentence number of a sentence ID.
"""
separator_index = sentence_id.rfind('_')
doc_id = sentence_id[:separator_index]
sent_num = int(sentence_id[separator_index + 1:])
return doc_id, sent_num |
def expand_field(field: str) -> str:
"""
Converts the dotted field notation expected in JSON
field-names into the dunder-style expected by Django.
:param field: The dotted field-name.
:return: The dunder-style field-name.
"""
return field.replace(".", "__") |
def default_range_3(n):
"""[1, 2, ..., n - 1]"""
return range(1, n) |
def get_variables(obj):
"""Tries to get variables in an object."""
if hasattr(obj, "get_variables"):
return obj.get_variables()
return set([]) |
def cleanup(data):
"""
Cleans up the data by removing whitespaces.
:param data:
:return:
"""
for key, val in data.items():
new_val = []
for ele in val:
item = [tok.strip() for tok in ele]
item = [tok for tok in item if tok != "\""]
item = [tok.... |
def _spec_arg(k, kwargs, v):
"""
Specify default argument for class constructors created from .mat files.
Used in autogenerated classes like ModelParameters.
Parameters
----------
k : string
Name of variable whose value will be assigned
kwargs : dict
Dictionary of keyword ... |
def make_wellcome_message(login) -> str:
"""This function format message during login procedure."""
return 'hello {}'.format('my love' if login == 'johnny' else login) |
def editInvoiceObject(account_data: dict, invoice_data: dict) -> dict:
"""
example: https://wiki.wayforpay.com/view/13271051
param: account_data: dict
merchant_account: str
merchant_password: str
param: invoice_data
reqularMode -> one of [
... |
def check_identifier(identifier):
"""Check if identifier is a valid name for a vector component"""
valid_chars = \
''.join(
(
'abcdefghijklmnopqrstuvwxyz', # latin lc
'ABCDEFGHIJKLMNOPQRSTUVWXYZ', # latin uc
''.join(chr(i) for i in range(0x0... |
def conv_to_float(indata, inf_str=''):
"""Try to convert an arbitrary string to a float. Specify what will be replaced with "Inf".
Args:
indata (str): String which contains a float
inf_str (str): If string contains something other than a float, and you want to replace it with float("Inf"), ... |
def constrain_cell(lattice_class, cell):
"""Constrain cell to fit lattice class x."""
a, b, c, alpha, beta, gamma = cell
if lattice_class == "a":
return (a, b, c, alpha, beta, gamma)
elif lattice_class == "m":
return (a, b, c, 90.0, beta, 90.0)
elif lattice_class == "o":
re... |
def calc_fnr(false_neg, true_pos):
"""
function to calculate false negative rate
Args:
true_pos: Number of true positives
false_neg: Number of false negatives
Returns:
None
"""
try:
fnr = false_neg / float(true_pos + false_neg)
return round(fnr, 3)
except BaseException:
return No... |
def argToInt(value):
""" Given a size or addresse of the type passed in args (ie 512KB or 1MB) then return the value in bytes.
In case of neither KB or MB was specified, 0x prefix can be used.
"""
for letter, multiplier in [("kb", 1024), ("mb", 1024 * 1024)]:
if value.lower().endswith(letter):
return int(value... |
def selectSupportedDiodes(diodeType):
""" Returns footprint name of the supported diode, returns an error if not supported
Returned object will have this form:
{
"lib_dir":"",
"footprint_ref": "",
}
"""
def selectTHTDiode():
""" ... |
def fillna(cp, cp0):
"""
This fills in conditional probability with count 0
if the word does not exist in the training set
"""
if cp == None: return cp0
else: return cp |
def replace(s, old, new, maxsplit=-1):
"""replace (str, old, new[, maxsplit]) -> string
Return a copy of string str with all occurrences of substring
old replaced by new. If the optional argument maxsplit is
given, only the first maxsplit occurrences are replaced.
"""
return s.replace(old, new... |
def get_neighbors(y, x, H, W):
""" Return indices of valid neighbors of (y, x).
Return indices of all the valid neighbors of (y, x) in an array of
shape (H, W). An index (i, j) of a valid neighbor should satisfy
the following:
1. i >= 0 and i < H
2. j >= 0 and j < W
3. (i, j) !=... |
def bytes2str(data):
"""
Convert bytes to string
>>> bytes2str(b'Pwning')
'Pwning'
>>>
"""
data = "".join(map(chr, data))
return data |
def canonicalize(path):
"""Canonicalize the input path.
Args:
path: The path to canonicalize
Returns:
The canonicalized path
"""
if not path:
return path
# Strip ./ from the beginning if specified.
# There is no way to handle .// correctly (no function that would make
... |
def get_dlats_from_case(case: dict):
"""pull list of latitudes from test case"""
dlats = [geo[0] for geo in case["destinations"]]
return dlats |
def _same_function(func1, func2):
"""
Helper function, used during namespace resolution for comparing whether to
functions are the same. This takes care of treating a function and a
`Function` variables whose `Function.pyfunc` attribute matches as the
same. This prevents the user from getting spurio... |
def _persistence(x, y):
"""Auxiliary function for calculating persistence of a tuple."""
return abs(x - y) |
def z_to_d_approx(z, H_0=67.74):
"""
Calculate distance in Gpc from a redshift.
Only holds for z <= 2. Formulas from 'An Introduction to Modern
Astrophysics (2nd Edition)' by Bradley W. Carroll, Dale A. Ostlie.
(Eq. 27.7)
Args:
z (float): Redshift
H_0 (float, optional): Hubble ... |
def dict_of_opts(options):
"""
Convert list of plugin options from the arg_parser to a dict.
Single keyword options are inserted as dict[keyword] = True,
key=val options are inserted as dict[key] = val.
"""
if not options:
return {}
result = {}
for opt in options:
if '=... |
def get_total_n_points(d):
"""
Returns the total number of data points in values of dict.
Paramters
---------
d : dict
"""
n = 0
for di in d.values():
n += len(di)
return n |
def crop_address(place):
"""
Crops address and returns new variant
>>> crop_address("Jo's Cafe, San Marcos, Texas, USA")
' San Marcos, Texas, USA'
>>> crop_address("San Marcos, Texas, USA")
' Texas, USA'
>>> crop_address(" Texas, USA")
' USA'
"""
place = place.split(",")
pla... |
def matrix_transpose(matrix):
"""
Function to transpose a Matrix
Returns the transpose of a 2D matrix
"""
return [[matrix[j][i] for j in range(len(matrix))]
for i in range(len(matrix[0]))] |
def parseInstructions(rawInstructions):
"""
Given a list of uppercase strings, parses the strings into instruction
tuples.
@param rawInstructions A list of uppercase strings representing
instructions from the input file
@return A list of tuples in a standard format with all pertinent
inform... |
def name_to_number(name):
""" helper method to translate names on cmd line to numbers
>>>name_to_number('rock')
0
>>>name_to_number('nonsense')
None
"""
if (name == 'rock'):
return 0
elif (name == 'spock'):
return 1
elif (name == 'paper'):
return 2
elif (name == 'lizard'):
return 3
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.