content stringlengths 42 6.51k |
|---|
def diophantine_count(a, n):
"""Computes the number of nonnegative solutions (x) of the linear
Diophantine equation
a[0] * x[0] + ... a[N-1] * x[N-1] = n
Theory: For natural numbers a[0], a[2], ..., a[N - 1], n, and j,
let p(a, n, j) be the number of nonnegative solutions.
Then one has:
... |
def to_pages_by_lines(content: str, max_size: int):
"""Shortens the youtube video description"""
pages = ['']
i = 0
for line in content.splitlines(keepends=True):
if len(pages[i] + line) > max_size:
i += 1
pages.append('')
pages[i] += line
return pages |
def Repr(obj, as_ref=True):
"""A version of __repr__ that can distinguish references.
Sometimes we like to print an object's full representation
(e.g. with its fields) and sometimes we just want to reference an
object that was printed in full elsewhere. This function allows us
to make that distinction.
Ar... |
def seconds_to_human(sec):
"""
Converts seconds into human readable format
Input: seconds_to_human(142)
Output: 00h 02m 22.000s
"""
days = sec // (24 * 60 * 60)
sec -= days * (24 * 60 * 60)
hours = sec // (60 * 60)
sec -= hours * (60 * 60)
minutes = sec // 60
sec -= minute... |
def count_longest_run(lst):
"""
Return longest run in given experiment outcomes list
"""
Y_longest_run = count = 0
current = lst[0]
for outcome in lst:
if outcome == current:
count += 1
else:
count = 1
current = outcome
Y_longest_run = ... |
def min_max_tuples(fst, snd):
"""
Given two tuples (fst_min, fst_max) and (snd_min, snd_max) return
(min, max) where min is min(fst_min, snd_min) and
max is max(fst_max, snd_max).
:param fst: tuple
:type fst: tuple
:param fst: tuple
:type snd: tuple
:return: tuple
:rtype: tuple
... |
def kebab_case_to_human(word):
"""Should NOT be used to unslugify as '-' are
also used to replace other special characters"""
if word:
return word.replace("-", " ").title() |
def get_db_hostname(url, db_type):
"""Retreive db hostname from jdbc url
"""
if db_type == 'ORACLE':
hostname = url.split(':')[3].replace("@", "")
else:
hostname = url.split(':')[2].replace("//", "")
return hostname |
def get_sgr_from_api(security_group_rules, security_group_rule):
""" Check if a security_group_rule specs are present in security_group_rules
Return None if no rules match the specs
Return the rule if found
"""
for sgr in security_group_rules:
if (sgr['ip_range'] == security_group_ru... |
def generate_binary_tree(op_str, first_child, second_child):
"""
Given operator string and two child, creates tree.
"""
if op_str == "+":
return first_child + second_child
elif op_str == "-":
return first_child - second_child
elif op_str == "*":
return first_child * second_child
elif op_str ==... |
def answer(question):
"""
Evaluate expression
"""
if not question.startswith("What is"):
raise ValueError("unknown operation")
math = question[7:-1].replace("minus", "-").replace("plus", "+")
math = math.replace("multiplied by", "*").replace("divided by", "/")
math = math.split()... |
def id_tokenizer(words: list) -> list:
"""Function to convert all id like tokens to universal iiiPERCENTiii token.
words: Word tokenized text of pdf (preproccesed)
return: Converted list of tokens
"""
final_words = words[:]
for c,word in enumerate(final_words):
... |
def render_config_template(template):
"""
Generates a configuration from the provided template + variables defined in
current scope
:param template: a config content templated with {{variables}}
"""
all_vars = {k: v for d in [globals(), locals()] for k, v in d.items()}
return template.format... |
def _operation_name_without_postfix(operation_id):
"""
:param operation_id: operation name with optional postfix - text after / sign
:return: operation type - all characters before postfix (all characters if no postfix found)
"""
postfix_sign = '/'
# if the operation id has custom postfix
if... |
def copy_to_permanent_storage(overall_dir):
""" Calls script within directory to copy all files in directory to permanent
storage.
Args:
overall_dir (str): overall directory where everything is located.
Return:
None.
"""
"""
copy_executable = os.path.join(overall_dir, "copyall.sh")
lib.call("{0}".forma... |
def searchInsertB(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)-1
while high>=low:
middle = (low+high) // 2
if nums[middle] == target:
return middle
e... |
def is_unique_2(given_string):
"""
Assumes that lowercase and uppercase letters are SAME
E.g. Returns False for "AaBbCc"
"""
lowered_string = given_string.lower()
length_of_string = len(lowered_string)
converted_set = set(lowered_string)
length_of_set = len(converted_set)
if leng... |
def read_bytes(buf, size):
"""
Reads bytes from a buffer.
Returns a tuple with buffer less the read bytes, and the bytes.
"""
res = buf[0:size]
return (buf[size:], res) |
def _csr_filename(file_prefix):
"""
Construct the name of a file for use in storing a certificate signing
request.
:param str file_prefix: base file name for the certificate signing request
(without the extension)
:return: certificate signing request file name
:rtype: str
"""
re... |
def adjust_by_hours(num_hours, time):
"""Takes in military time as a string, and adjusts it by the specified number of hours"""
time = int(time)
time += num_hours*100
return str(time) |
def get_nested_dict(input_dict, key):
"""
Helper function to interpret a nested dict input.
"""
current = input_dict
toks = key.split("->")
n = len(toks)
for i, tok in enumerate(toks):
if tok not in current and i < n - 1:
current[tok] = {}
elif i == n - 1:
... |
def _f(field):
"""SQL for casting as float"""
return f"CAST({field} AS FLOAT)" |
def _combine_graph_data(graphs):
"""
Concatenate data series from multiple graphs into a single series
Returns
-------
val
List of the form [(x_0, [y_00, y_01, ...]), (x_1, ...)]
where the y-values are obtained by concatenating the data
series. When some of the graphs do not... |
def flatten_dicts(dicts):
"""
Flatten all the dicts, but assume there are no key conflicts.
"""
out = {}
for adict in dicts.values():
for key, value in adict.items():
out[key] = value
return out |
def is_vararg(param_name):
"""
Determine if a parameter is named as a (internal) vararg.
:param param_name: String with a parameter name
:returns: True iff the name has the form of an internal vararg name
"""
return param_name.startswith('*') |
def dec_to_ip(dec):
"""Convert decimal number back to IPv4 format.
This uses bit-shifting, which could also be used in conversion to a decimal value.
"""
return f"{(dec >> 24) & 0xFF}.{(dec >> 16) & 0xFF}.{(dec >> 8) & 0xFF}.{dec & 0xFF}" |
def word_vector(text):
"""
Calculates a word frequency vector given text input
:param input: string
:return:
"""
word_list = text.split()
word_vector = {}
for word in word_list:
word = word.lower()
if word in word_vector:
word_vector[word] += 1
else:
... |
def get_strings_from_seqs(seqs):
""" Extract strings from FASTA sequence records.
"""
strings = []
for s in seqs:
strings.append(s.getString())
return strings |
def min_longitude(coordinates):
"""
This function returns the minimum value of longitude
of a list with tuples [(lat, lon), (lat, lon)].
:param coordinates: list
list with tuples. Each tuple
has coordinates float values.
... |
def count_infected(pop):
"""
counts number of infected
"""
return sum(p.is_infected() for p in pop) |
def _remove_retweeted_tag(tweets):
"""
This method removes the "rt" of retweeted texts at the beginning
of a message.
"""
cleaned_tweets = []
for tweet in tweets:
if tweet.startswith('rt', 0, 2 ):
cleaned_tweets.append(tweet[3:])
else:
cleaned_tweets.appen... |
def next_departure_after(time, bus):
"""Return next bus departure after time."""
return time - (time % bus) + bus |
def dict_to_label_attr_map(input_dict):
"""
Converting python dict with one value into Params.label_attr_map format
"""
return {key+':': [key, type(val)] for key, val in input_dict.items()} |
def hex_life(is_alive:bool, live_neighbors:int) -> bool:
"""Work out the life status of a tile, given its current status and neighbors"""
if is_alive:
return live_neighbors in (1,2)
else:
return live_neighbors == 2 |
def langstring(value: str, language: str = "x-none") -> dict:
"""Langstring."""
return {
"langstring": {
"lang": language,
"#text": value,
}
} |
def GetStartingGapLength(sequence):
"""
This function takes in a sequence, and counts from the beginning how many
gaps exist at the beginning of that sequence, up till the first ATG (start
codon).
Parameters:
- sequence: a string along which you wish to count the number of gaps
"""
gaps = 0
for i, position i... |
def anagram2(S1,S2):
""" Checks if the two strings are anagram or not"""
S1 = S1.replace(' ', '').lower()
S2 = S2.replace(' ', '').lower()
if len(S1) != len(S2): return False # Edge case check
count = {}
for (x, y) in zip(S1,S2):
count[x] = count.get(x,0)+1
count[y] = count.g... |
def _build_response_body(contact_id, response):
"""Builds a dictionary representing the response body"""
contact_details = {
'contactId': contact_id
}
item = response['Item']
if 'name' in item:
contact_details['name'] = item['name']['S']
if 'telephone' in item:
contact... |
def delete_label(name,repos, session, origin):
"""
Deletes label
:param name: name of the label to delete
:param repos: name of the repository where is the label
:param session: session for communication
:param origin: from where the label came from
:return: message code 200 (int)
"""
... |
def is_subcmd(opts, args):
"""if sys.argv[1:] does not match any getopt options,
we simply assume it is a sub command to execute onecmd()"""
if not opts and args:
return True
return False |
def get_where_value(conds):
"""
[ [where_column, where_operator, where_value],
[where_column, where_operator, where_value], ...
]
"""
where_value = []
for cond in conds:
where_value.append(cond[2])
return where_value |
def divide_and_round(n):
"""
Divides an integer n by 2 and rounds
up to the nearest whole number
"""
print("4")
if n % 2 == 0:
n = n / 2
return int(n)
else:
n = (n + 1) / 2
return int(n) |
def __str__(self):
"""Override of default str() implementation."""
return dict(self).__str__() |
def convert_version_string_to_int(string, number_bits):
"""
Take in a verison string e.g. '3.0.1'
Store it as a converted int: 3*(2**number_bits[0])+0*(2**number_bits[1])+1*(2**number_bits[2])
>>> convert_version_string_to_int('3.0.1',[8,8,16])
50331649
"""
numbers = [int(number_string) for... |
def solve(n, t, indices):
"""
Solve the problem here.
:return: The expected output.
"""
def make_jump(arr, j):
for z in range(len(arr)):
arr[z] = (arr[z] + j) % t
return arr
def rotate_right(arr):
return [arr[-1]] + arr[0:len(arr) - 1]
indices = [indices[... |
def compute_mallows_insertion_distribution(length, phi):
"""
Helper function for the mallows distro above.
For Phi and a given number of candidates, compute the
insertion probability vectors.
Method mostly implemented from Lu, Tyler, and Craig Boutilier.
"Learning Mallows models with pairwise preferences.... |
def partition(nums, lo, hi):
""" Lomuto Partition Scheme
Picks the last element hi as a pivot
and returns the index of pivot value in the sorted array.
"""
pivot = nums[hi]
i = lo
for j in range(lo, hi):
if nums[j] < pivot:
nums[i], nums[j] = nums[j], nums[i]
... |
def chunker(big_lst):
"""
Breaks a big list into a list of lists. Removes any list with no data then turns remaining
lists into key: value pairs with first element from the list being the key.
Returns a dictionary.
"""
chunks = [big_lst[x:x + 27] for x in range(0, len(big_lst), 27)]
# Rem... |
def f2f1(f1, f2, *a, **k):
"""
Apply the second function after the first.
Call `f2` on the return value of `f1`.
Args and kwargs apply to `f1`.
Example
-------
>>> f2f1(str, int, 2)
2
"""
return f2(f1(*a, **k)) |
def scale(input_interval, output_interval, value):
"""
For two intervals (input and output)
Scales a specific value linear from [input_min, input_max] to [output_min, output_max].
"""
min_to, max_to = output_interval
min_from, max_from = input_interval
mapped_value = min_to + (max_to... |
def renameRes(res):
"""
This function will rename the string resname for grace, e.g. D will become a delta sign
"""
if "CD1" in res: return res.replace("CD1","\\xd1")
elif "CD2" in res: return res.replace("CD2","\\xd2")
elif "CG1" in res: return res.replace("CG1","\\xg1")
elif "CG2" in res: return res.replace("C... |
def friendly_size(size: float) -> str:
"""Convert a size in bytes (as float) to a size with unit (as a string)"""
unit = "B"
# Reminder: 1 KB = 1024 B, and 1 MB = 1024 KB, ...
for letter in "KMG":
if size >= 1024:
size /= 1024
unit = f"{letter}B"
# We want to keep 2 ... |
def _to_modifier(suffix: str, scope: str) -> str:
"""Return the C++ kSuffix{X} corresponding to the 'w', 's', and 'u'
suffix character in the TZ database files.
"""
if suffix == 'w':
return f'{scope}::ZoneContext::kSuffixW'
elif suffix == 's':
return f'{scope}::ZoneContext::kSuffixS'... |
def generate_reverse_graph(adj):
"""
This function is for used with the adj_graph defined in GEOMETRY_TASK_GRAPH
outputs
- adj_reversed: a reversed version of adj (All directed edges will be reversed.)
"""
adj_reversed = [[] for _ in range(len(adj))]
for nid_u in range(len(adj)):
... |
def v_equil(alpha, cli, cdi):
"""Calculate the equilibrium glide velocity.
Parameters
----------
alpha : float
Angle of attack in rad
cli : function
Returns Cl given angle of attack
cdi : function
Returns Cd given angle of attack
Returns
-------
vbar : float... |
def create_headers(bearer_token):
"""Create headers to make API call
Args:
bearer_token: Bearer token
Returns:
Header for API call
"""
headers = {"Authorization": f"Bearer {bearer_token}"}
return headers |
def by_range(blocks, block_range):
"""Sort blocks by Logical Erase Block number.
Arguments:
List:blocks -- List of block objects to sort.
List:block_range -- range[0] = start number, range[1] = length
Returns:
List -- Indexes of blocks sorted by LEB.
... |
def iou(box1, box2, denom="min"):
""" compute intersection over union score """
int_tb = min(box1[0]+0.5*box1[2], box2[0]+0.5*box2[2]) - \
max(box1[0]-0.5*box1[2], box2[0]-0.5*box2[2])
int_lr = min(box1[1]+0.5*box1[3], box2[1]+0.5*box2[3]) - \
max(box1[1]-0.5*box1[3], box2[1]-0.5*b... |
def get_settable_properties(cls):
"""Gets the settable properties of a class.
Only returns the explicitly defined properties with setters.
Args:
cls: A class in Python.
"""
results = []
for attr, value in vars(cls).items():
if isinstance(value, property) and value.fset is not None:
results.a... |
def buildUpdateFields(params):
"""Join fields and values for SQL update statement
"""
return ",".join(["%s = \"%s\"" % (k, v) for k, v in params.items()]) |
def extract_interface_info(
pgm, end_pgm, procedure_functions, current_modu, current_intr, line
):
"""This function extracts INTERFACE information, such as the name of
interface and procedure function names, and populates procedure_functions
dictionary.
Params:
pgm (tuple): Current program ... |
def split_table(test_case_details):
"""
Method to split tables from the Json stored in the test_case table.
Args:
test_case_details(Json): JSON from test_case table
Returns: splited table names in dictionary
"""
table_dict = {}
tables = test_case_details["table"]
for each_table... |
def codeToArray(code):
"""Splits code string into array separated by newline character"""
convList = []
code = code.split("\n")
for element in code:
convList.append(element.strip())
return convList |
def rhoair( dem, tday ):
"""Requires T in Kelvin"""
t = tday+273.15
b = ( ( t - ( 0.00627 * dem ) ) / t )
return( 349.467 * pow( b, 5.26 ) / t ) |
def mod_min(a, b):
"""
return r such that r = a (mod b), with minimum |r|
"""
# like divmod_min, just skipping a single add
r = (a % b)
diff = b - r
if abs(r) > abs(diff):
r = -diff
return r |
def stock_price_summary(price_changes):
""" (list of number) -> (number, number) tuple
price_changes contains a list of stock price changes. Return a 2-item
tuple where the first item is the sum of the gains in price_changes and
the second is the sum of the losses in price_changes.
>>> stock_price... |
def extract_pred(predictions):
"""
extract the model prediction without the label at the beginning
:param predictions: list of Strings / complete predicted output
:return: list of Strings / predicted output without labels
"""
array = []
for pred in predictions:
try:
x = p... |
def CRC_calc(data):
"""Sensirion Common CRC checksum for 2-byte packets. See ch 6.2
Parameters
----------
data : sequence of 2 bytes
Returns
-------
int, CRC check sum
"""
crc = 0xFF
for i in range (0, 2):
crc = crc ^ data[i]
for j in range(8, 0, -1):
... |
def position(x):
""" Function to calculate position bias """
position=list()
num_seqs = len(x)
num_bases = len(x[1])
for j in range(0,num_bases): #each base
count_A=0 ; count_T=0 ; count_C=0 ; count_G=0 ; count_other=0 ; total=0
for i in range(0,num_seqs): #each sequence
... |
def merge_text_meta(left_text, right_text, overwrite=False):
"""
Merge known text keys from right to left, add unknown text_keys.
"""
if overwrite:
left_text.update(right_text)
else:
for text_key in right_text.keys():
if not text_key in left_text:
left_tex... |
def loads(value: str) -> int:
""" """
if len(value) > 3:
raise ValueError("base25 input too large")
return int(value, 25) |
def ar(series, params, offset):
""" Calculate the auto regression part.
:param series: list with transactions
:param params: list of coefficients, last value is the constant
:param offset: index of last predicted value
:return: float
"""
return params[-1] + sum([params[i] * series[offset-i]... |
def hour_min_second(seconds):
"""Convert given numbers of seconds to the format hour:min:secs.
Args:
seconds(int): The number of seconds
Return:
str: a string on the format hours:mins:secs
"""
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return... |
def add_to_dict_if_not_present(target_dict, target_key, value):
"""Adds the given value to the give dict as the given key
only if the given key is not in the given dict yet.
"""
if target_key in target_dict:
return False
target_dict[target_key] = value
return True |
def getWordTag(wordTag):
"""
Split word and tag from word/tag pair
Example: good/JJ -> word: good, tag: JJ
"""
if wordTag == "///":
return "/", "/"
index = wordTag.rfind("/")
word = wordTag[:index].strip()
#tag = wordTag[index +1:].lower().strip()
tag = wordTag[in... |
def missing_remediation(rule_obj, r_type):
"""
For a rule object, check if it is missing a remediation of type r_type.
"""
rule_id = rule_obj['id']
check = len(rule_obj['remediations'][r_type]) > 0
if not check:
return "\trule_id:%s is missing %s remediations" % (rule_id, r_type) |
def html_escape(text):
"""Produce entities within text."""
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
return "".join(html_escape_table.get(c, c) for c in text) |
def misra_dict_to_text(misra_dict):
"""Convert dict to string readable by cppcheck's misra.py addon."""
misra_str = ''
for num1 in misra_dict:
for num2 in misra_dict[num1]:
misra_str += '\n{} {}.{}\n'.format(misra_dict[num1][num2]['type'], num1, num2)
misra_str += '{}\n... |
def _list_to_str(ticker_list):
"""parses/joins ticker list
Args:
ticker_list (:obj:`list` or str): ticker(s) to parse
Returns:
(str): list of tickers
"""
if isinstance(ticker_list, str):
return ticker_list.upper()
elif isinstance(ticker_list, list):
return ','.... |
def is_commanddictnode_defined(node):
"""
A child node is defined if it has either a helptext/callback/summary.
If a node's callback is None it can still be undefined.
"""
return (('callback' in node and not node['callback'] is None) or
'help_text' in node or
'summary' in node) |
def midpoint(startPt, endPt):
"""
Midpoint of segment
:param startPt: Starting point of segment
:param endPt: Ending point of segment
:return:
"""
return [(startPt[0]+endPt[0])/2, (startPt[1]+endPt[1])/2] |
def neg3D(v3D):
"""Returns the negative of the 3D vector"""
return -v3D[0], -v3D[1], -v3D[2] |
def unlist(given_list):
"""Convert the (possibly) single item list into a single item"""
list_size = len(given_list)
if list_size == 0:
return None
elif list_size == 1:
return given_list[0]
else:
raise ValueError(list_size) |
def _monotone_end_condition(inner_slope, secant_slope):
"""
Return the "outer" (i.e. first or last) slope given the "inner"
(i.e. second or penultimate) slope and the secant slope of the
first or last segment.
"""
# NB: This is a very ad-hoc algorithm meant to minimize the change in slope
... |
def native16_to_be(word, signed=False) -> bytes:
""" Packs an int into bytes after swapping endianness.
Args:
signed (bool): Whether or not `data` is signed
word (int): The integer representation to converted and packed into bytes
"""
return word.to_bytes(2, 'big', signed=signed) |
def is_invalid_call(s):
"""
Checks if a callsign is valid
"""
w = s.split('-')
if len(w) > 2:
return True
if len(w[0]) < 1 or len(w[0]) > 6:
return True
for p in w[0]:
if not (p.isalpha() or p.isdigit()):
return True
if w[0].is... |
def _sanitize_name(name: str) -> str:
"""The last part of the access path is the function/attribute name"""
return name.split(".")[-1] |
def steps_to_basement(instructions):
"""Determine number of steps needed to reach the basement."""
floor = 0
for step, instruction in enumerate(instructions):
if instruction == '(':
floor += 1
elif instruction == ')':
floor -= 1
if floor == -1:
ret... |
def midpoint(point1, point2):
""" calc midpoint between point1 and point2 """
return ((point1[0] + point2[0]) * .5, (point1[1] + point2[1]) * .5) |
def rectangle_intersects(recta, rectb):
"""
Return True if ``recta`` and ``rectb`` intersect.
>>> rectangle_intersects((5,5,20, 20), (10, 10, 1, 1))
True
>>> rectangle_intersects((40, 30, 10, 1), (1, 1, 1, 1))
False
"""
ax, ay, aw, ah = recta
bx, by, bw, bh = rectb
return ax <= ... |
def to_sequence_id(sequence_name) -> int:
"""
Turn an arbitrary value to a known sequence id.
Will return an integer in range 0-11 for a valid sequence, or -1 for all other values
Should handle names as integers, floats, any numeric, or strings.
:param sequence_name:
:return:
"""
try:
... |
def color_performance(column):
"""
color values in given column using green/red based on value>0
Args:
column:
Returns:
"""
color = 'green' if column > 0 else 'red'
return f'color: {color}' |
def generate_facial_features(facial_features, is_male):
"""
Generates a sentence based on the attributes that describe the facial features
"""
sentence = "He" if is_male else "She"
sentence += " has"
def nose_and_mouth(attribute):
"""
Returns a grammatically correct sentence ba... |
def _is_descriptor(obj):
"""
A copy of enum._is_descriptor from Python 3.6.
Returns True if obj is a descriptor, False otherwise.
"""
return (
hasattr(obj, '__get__') or
hasattr(obj, '__set__') or
hasattr(obj, '__delete__')) |
def cleanEOL(s):
"""Remove \r from the end of string `s'."""
return s.rstrip("\r") |
def assign_indent_numbers(lst, inum, dic):
""" Associate keywords with their respective indentation numbers
"""
for i in lst:
dic[i] = inum
return dic |
def input_colorpicker(field):
"""Return HTML markup for a color picker."""
return {"field": field} |
def get_wheel_package_name(provider_package_id: str) -> str:
"""
Returns PIP package name for the package id.
:param provider_package_id: id of the package
:return: the name of pip package
"""
return "apache_airflow_providers_" + provider_package_id.replace(".", "_") |
def validateSubSequence(array, sequence):
"""
### Description
validateSubSequence -> validates if a sequence of elements is a subsequence of a list.
### Parameters
- array: the list where it will validate the subsequence.
- sequence: the potential subsequence of elements
... |
def build_n_sequence_dictionary(n : int, txt : str) -> dict:
"""
Returns a dict counting appearances of n-long progressions
Parameters
----------
n : int
The length of progressions to count
txt : str
A comma-separated string of roman numerals
Returns
-------
dict
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.