content stringlengths 42 6.51k |
|---|
def find_most_similar_paragraph(similar_paragraphs):
""" Some paragraphs in the C++ started are worded very similarly.
Sometimes, multiple paragraphs may be marked as similar. This function
picks the paragraph with the highest similarity ratio.
"""
max_i = 0
max_ratio = 0
for i in ran... |
def sumEvenNum(x):
# Function comments definition
""" Sum even number"""
num = 1
sum = 0
while num <= x:
if num % 2 == 0:
sum = sum + num
num += 1
return sum |
def _get_short_language_description(full_language_description):
"""Given one of the descriptions in constants.ALL_LANGUAGE_CODES, generates
the corresponding short description.
Args:
full_language_description: str. Short description of the language.
Returns:
str. Short description of t... |
def calculate_position(step_number, overlap, image_size=2048, resolution_factor=0.6215):
"""
:param step_number: 1-based step (x or y)
:param resolution_factor: of images (default is 0.6125)
:param overlap: percent overlap (whole number)
:param image_size: resolution of image
:return: absolute ... |
def get_next(it):
""" Ignore the pdf junk that delineates pages, and blank lines """
line = next(it)
while True:
if b"\x0c".decode('utf-8') in line.strip(): line = next(it)
elif "Downloaded from SAE International by" in line.strip(): line = next(it)
elif " "*34+"J1587" in line.strip(): line = next(it... |
def calculateIncomeHelper(income, pay_period):
"""Returns annual income based on income each pay_period"""
pay_multipliers = {'weekly':52, 'biweekly':25, 'semimonthly':24,'monthly':12}
return income*pay_multipliers[pay_period] if pay_period in pay_multipliers else income*pay_period*52 |
def __removeUnpopularIds(listOfIds, popularIds):
"""
:param listOfIds: List of ids
:param popularIds: Most popular agent over whole population
:return: listOfIds without agents that aren't popular
"""
res = []
for id in listOfIds:
if (id in popularIds.keys()):
res.append(... |
def missing_functions(messages):
"""Names of missing functions."""
prefix = "no body for function"
length = len(prefix)
return [warning[length:].strip() for warning in messages
if warning.startswith(prefix)] |
def length_wu(length, logprobs, alpha=0.):
"""
NMT length re-ranking score from
"Google's Neural Machine Translation System" :cite:`wu2016google`.
"""
modifier = (((5 + length) ** alpha) /
((5 + 1) ** alpha))
return logprobs / modifier |
def get_unique_ids_from_several_lists(*args) -> list:
"""
:param args:
:return:
"""
res = []
for my_list in args:
res += my_list
return res |
def sql_number_list(target):
"""
Returns a list of numbers suitable for placement after the SQL IN operator in
a query statement, as in "(1, 2, 3)".
"""
if not target:
raise ValueError
elif not isinstance(target, list):
target = [target]
return "(%s)" % (", ".join(["%d" % (i... |
def get_products_of_all_ints_except_at_index(ints):
"""
Time Complexity: O(n)
Space Complexity: O(n)
n: number of ints (length of the list)
"""
if len(ints) < 2:
raise IndexError('Getting the product of numbers at other indices requires at least 2 numbers')
result = []
forward_... |
def get_target_for_label(label: str) -> int:
"""Convert a label to `0` or `1`.
Args:
label(string) - Either "POSITIVE" or "NEGATIVE".
Returns:
`0` or `1`.
"""
return 1 if label=="POSITIVE" else 0 |
def any_item_in_string(items, test_string):
"""Return true if any item in items is in test_string"""
return any([True for item in items if item in test_string]) |
def thermal_conductivity_carbon_steel(temperature):
"""
DESCRIPTION:
[BS EN 1993-1-2:2005, 3.4.1.3]
PARAMETERS:
OUTPUTS:
REMARKS:
"""
temperature += 273.15
if 20 <= temperature <= 800:
return 54 - 0.0333 * temperature
elif 800 <= temperature <= 120... |
def isnumeric( numStr ):
""" Hack to determine if a non-unicode string is numeric or not """
numStr = str( numStr )
try:
int( numStr )
return True
except:
try:
float( numStr )
return True
except:
return False |
def prompt(question):
"""
ask a question (e.g 'Are you sure you want to do this (Y or N)? >')
return the answer
"""
try:
print(question)
foo = input()
return foo
except KeyboardInterrupt as e:
raise e
except:
return |
def mod10(list):
"""Implements the Luhn Algorithm (a.k.a. mod10), which
is a checksum formula to validade a variety of
identification numbers, such as credit card numbers.
Requires a list of integers with the numbers to be
validated.
"""
sum = 0
double = True
... |
def parse_num(tokens):
"""Parser function for numerical data
:param tokens: The grammar tokens
:type tokens: list
"""
return float(tokens[0]) |
def signed2unsigned(value, width=32):
""" convert a signed value to it's 2 complement unsigned
encoding """
if value >= 0:
return int(value)
else:
return int(value + 2**(width) ) |
def extended_gcd(aa, bb):
"""Extended greatest common divisor
from https://rosettacode.org/wiki/Modular_inverse#Python
"""
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder,... |
def rounding_filters(filters, w_multiplier):
""" Calculate and round number of filters based on width multiplier. """
if not w_multiplier:
return filters
divisor = 8
filters *= w_multiplier
new_filters = max(divisor, int(filters + divisor / 2) // divisor * divisor)
if new_filters < 0.9 *... |
def get_price_padding(closing_price: float) -> float:
"""
Calculate how far above and below to place your entry/stop
"""
if closing_price < 5:
return 0.01
elif 5 <= closing_price < 10:
return 0.02
elif 10 <= closing_price < 50:
return 0.03
elif 50 <= closing... |
def is_unknown(value: str) -> bool:
"""Returns True if val represents and unknown value"""
if not isinstance(value, str):
raise TypeError
if not value or value.upper() in ("UNKN", "UNK", "UKN"):
return True
for char in value:
if char not in ("/", "X", "."):
break
... |
def flatten(list_of_lists):
"""
>>> flatten([[1,2], [3,4,5]])
[1, 2, 3, 4, 5]
"""
return [item for sublist in list_of_lists for item in sublist] |
def vel_final_dist_helper(initial_velocity, acceleration, dist):
"""
Calculates the final velocity given the initial velocity, acceleration and the distance traveled. And is a helper
function to be called by vel_final_dist()
:param initial_velocity: Integer initial velocity
:param acceleration: Integer accelerati... |
def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args):
"""
Sort list of dicts by one or multiple keys.
If the key is not available, sort these to the end.
:param lst_of_dct: input structure. List of dicts.
:param keys: one or more keys in list
:param reverse:
:param sort_arg... |
def interpret_field(data):
"""
Convert data to int, if not possible, to float, otherwise return
data itself.
Parameters
----------
data : object
Some data object
Returns
-------
data : int, float or same data type as the input
Return the data object casted as an int, ... |
def quaternion_wxyz_to_xyzw_order(quat):
"""
Changes to {q.x, q.y, q.z, q.w} quaternion order from Isaac's {q.w, q.x, q.y, q.z}
"""
output_quaternion = [quat[1], quat[2], quat[3], quat[0]]
return output_quaternion |
def get_all_descendants(root, children_map):
"""
Returns all descendants in the tree of a given root node, recursively
visiting them based on the map from parents to children.
"""
return {root}.union(
*[get_all_descendants(child, children_map)
for child in children_map.get(root, ... |
def _create_group_to_col_position(column_groups):
"""Get mapping from column groups to column positions.
Args:
column_names (list): The column groups to display in the estimatino table.
Returns:
group_to_col_index(dict): The mapping from column group titles to column
positions.... |
def argmaxIndexWithTies(l, f = lambda x: x):
"""
@param l: C{List} of items
@param f: C{Procedure} that maps an item into a numeric score
@returns: the index of C{l} that has the highest score
"""
best = []; bestScore = f(l[0])
for i in range(len(l)):
xScore = f(l[i])
if xSco... |
def try_coerce_ascii(string_utf8):
"""Attempts to decode the given utf8-encoded string
as ASCII after coercing it to UTF-8, then return
the confirmed 7-bit ASCII string.
If the process fails (because the string
contains non-ASCII characters) returns ``None``.
"""
try:
st... |
def truncated(text, max_length=100, msg='...'):
"""
>>> truncated("hello world!", 5)
'hello...'
>>> truncated("hello world!", 25)
'hello world!'
>>> truncated("hello world!", 5, " [truncated]")
'hello [truncated]'
"""
if len(text) < max_length:
return text
else:
r... |
def stations_by_river(stations):
""" Given a list of station objects, this function returns a dictionary that maps river names
to a list of station objects on a given river.
"""
mapping = {}
for station in stations:
river = station.river
if river in mapping.keys():
mappin... |
def point_dist(p0, p1):
"""
Calculate distance between two points in 2D.
:param p0: first point, array like coordinates
:param p1: second point, array like coordinates
:return: distance, float
"""
return ((p1[0] - p0[0])**2 + (p1[1] - p0[1])**2)**(1/2) |
def remove_2x_compat_notes(matcher):
"""
A number of the files end in
{{{
#!html
<h2 class='compatibility'>Older versions</h2>
}}}
and everything after is garbage, so just remove it.
"""
r'\{\{\{\n#!html\n<h2(.|\n)*'
return '' |
def prepare_folders(output_directory: str, delete_existing: bool, add: bool) -> str:
"""
A general folder prep function to help with the preprocess steps, this will handle general file prep and delete_existing and add conflicts.
Parameters
----------
output_directory: The name of the output director... |
def num2alpha(num: int) -> str:
"""turn num to alpha"""
return "" if num == 0 else num2alpha((num - 1) // 26) + chr((num - 1) % 26 + ord('A')) |
def generateSuperItemsets(base_itemsets):
"""
combine tuples in the base itemsets list to generate the immediate super itemsets list
:param base_itemsets - [(a,b), (b,c), (a,c) ...]
:return super_itemsets - [(a,b,c), ...]
"""
if base_itemsets == []:
return []
# sort: make sure, in (... |
def solution(S, P, Q):
"""
We cum sum all impacts for each nucleotide at each position
then, for each query, we simply subtract the sum of the end minus the
sum until the start and start to check if this subtraction is higher
than 0.
If it is, then it means that that nucleotide exists within t... |
def hex_to_ipv6(hex):
"""
Takes a 128 bit hexidecimal string and returns that string formatted for IPv6
:param hex: Any 128 bit hexidecimal passed as string
:return: String formatted in IPv6
"""
return ':'.join(hex[i:i + 4] for i in range(0, len(hex), 4)) |
def _sequence_to_index(seq, dim_list):
"""
Inverse of _index_to_sequence.
Parameters
----------
seq : list of ints
List of coordinates for each particle.
dim_list : list of int
List of dimensions of consecutive particles.
Returns
-------
i : list
Index in a... |
def BitwiseOr(value1, value2) -> int:
"""Returns the result of the bitwise OR operation."""
return int(int(value1) | int(value2)) |
def is_set(value):
"""
Checks if the given value is a set object or not.
Args:
value (mixed): Value passed in by the user.
Returns:
bool: True if the given value is a set else False.
Example:
>>> is_set(set([1, 2]))
True
>>> is_set([1, 2, 3])
False... |
def get_patch_values(patch, path):
"""Get the patch values corresponding to the specified path.
If there are multiple values specified for the same path
(for example the patch is [{'op': 'add', 'path': '/name', 'value': 'abc'},
{'op': 'add', 'path': '/name', 'value': 'bca'}])... |
def fasta_to_histo(fastalines):
"""Reads fastaline tuples as produced by read_fasta(...) and retuns a histogram (a list) of
dict(tally=..., at_bases=..., gc_bases=...)
"""
res = list()
for fline in fastalines:
if fline.length > len(res) - 1:
res.extend( dict(tally=0, at_bases... |
def n64_to_n32(nonce):
"""
a 64 bit nonce in Python is actually constructed by n2 << 32 | n1
with n1 and n2 the next 32-bit random numbers
this function takes a nonce and return n1 and n2, the two 32-bit random numbers composing it
"""
n2 = nonce >> 32
n1 = (n2 << 32) ^ nonce
assert n... |
def expand_template(tmpl_text, values):
""" Simplest template expander. """
from string import Template
tmpl = Template(tmpl_text)
return tmpl.substitute(values) |
def search_event(query, hits, n_total_hits, query_time_ms, source_id=None):
"""Format the properties of the ``search`` event.
:param query: a dictionary that specifies the query and it's options
:type query: dict
:param hits: a list of the returned hits. Each item in the list should
co... |
def get_colour(image, p):
"""
Returns a char with the colour of given point
"""
# print('\n\n', image[p[0]+3, p[1]+3])
return '' |
def unzip(zipped_list, n):
"""returns n lists with the elems of zipped_list unsplitted.
The general case could be solved with zip(*zipped_list), but here we
are also dealing with:
- un-zipping empy list to n empty lists
- ensuring that all zipped items in zipped_list have lenght n, raising
... |
def ascertain_list(x):
"""
ascertain_list(x) blah blah returns [x] if x is not already a list, and x itself if it's already a list
Use: This is useful when a function expects a list, but you want to also input a single element without putting this
this element in a list
"""
if not isinstance(x, ... |
def cyclic(lst1, lst2):
"""Return the cyclic of 2 lists"""
if len(lst1) != len(lst2):
return False
lst2_first_in_lst1 = []
for i in range(len(lst1)):
if lst1[i] not in lst2:
return False
if lst1[i] == lst2[0]:
lst2_first_in_lst1.append(i)
if_cyclic = ... |
def set_fd_inheritable(fd, inheritable):
"""
disable the "inheritability" of a file descriptor
See Also:
https://docs.python.org/3/library/os.html#inheritance-of-file-descriptors
https://github.com/python/cpython/blob/65e6c1eff3/Python/fileutils.c#L846-L857
"""
from fcntl import ioc... |
def remove_duplicates(list_, func=None):
""" Remove all duplicates in a list.
Set func to use another value than a self hash for determining if duplicate.
Values must be hashable (If func is None) as they are passed through as dict keys. (Lists work but not Dicts) """
if func is None:
re... |
def _get_provenance_record(attributes, ancestor_files):
"""Return a provenance record describing the diagnostic data."""
record = attributes.copy()
record.update({
'ancestors': ancestor_files,
'realms': ['land'],
'domains': ['global'],
})
return record |
def _maybe_overlapping_memory(shape, strides):
"""Returns bool value indicating the array with such shape and strides
might have overlapping memory.
Args:
shape (tuple of int): The shape of output.
strides (tuple of int): The strides of output, given in the unit of steps.
storage_offset (int):
... |
def parse_header(line):
"""
Get all sample names present in the vcf header.
Assume each column is in format 'extra_info.samplename'.
Args:
line (str): Header line.
Returns:
samples (list of str): List of sample names.
"""
line = line.strip().split("\t")[9:]
samples = [... |
def __check_same(res, name, mdel, binel):
"""
Helper function for binary metadata cross-validation with JSON
If @mdel (JSON) and @binel (Binary) are not the same, return False
and display a formatted error with the given @name.
Else return @res
"""
if str(mdel) != str(bi... |
def is_clef(annotation_token: str) -> bool:
"""Returns true if the token is a clef"""
return annotation_token.startswith("clef.") |
def is_intel_email(email):
"""Checks that email is valid Intel email"""
return email and len(email) > 10 and ' ' not in email and email.lower().endswith('@intel.com') |
def transpose_report(report):
""" Splits & transposes the report
"""
l_o_l = [list(c for c in code) for code in report.split("\n") if len(code)]
return list(map(list, zip(*l_o_l))) |
def compound_interest(principal: int, interest: float, periods: int) -> float:
"""
Calculates the total return on a standard deposit and interest rate every period.
Args
principal: amount to be deposited every period
interest: expressed in decimal 3% = .03
periods: the number of per... |
def heavy(t):
""" Take sample from the heavyside function (a.ka. unit step function).
"""
return float(t > 0) |
def get_total(puntaje: str):
""" Borra el substring `Total: ` del puntaje """
return puntaje.replace("Total: ", "").replace(",", ".") |
def from_base_alphabet(value: str, alphabet: str) -> int:
"""Returns value in base 10 using base len(alphabet)
[bijective base]"""
ret = 0
for digit in value:
ret = len(alphabet) * ret + alphabet.find(digit)
return ret |
def positive_sum3(a: int, b: int, c: int=0):
"""Normal exposed function
Parameters
----------
a: int
b: int
c: int, default 0
All parameters are positive values.
If negative, an exception is raised.
Returns
----------
int
"""
if a<0 or b<0 or ... |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement.
Returns:
bool: True if the line is not blank, a comment, a URL, or
an included file
"""
return line and not line.startswith(('-r', '#', '-e', 'git+', '-c')) |
def _get_tips_from_string(tips_str):
"""Get list of tips from tips string."""
return [tip.strip() for tip in tips_str.split('*') if tip] |
def fib_memoization(ar, n):
"""
Top down approach
https://www.geeksforgeeks.org/tabulation-vs-memoization/
"""
if n == 0:
return 1
if ar[n] is not None:
return ar[n]
else:
print("call---" + str(n))
ar[n] = n * fib_memoization(ar, n - 1)
return ar[n] |
def getRGBListFromRGBStr(rgbStr):
""" returns [red, green, blue] that represents whether each led is on or off """
red, green, blue = rgbStr.split(',')
return [red, green, blue] |
def fix_read_order_keys(key, start_value=7):
"""fix reading restored ckpt order_dict keys, by Hao."""
return key[start_value:] |
def insertion_sort(l):
""" scan each item in a list and findout if the current position number is less than target """
sorted_list = []
for item_compare in l:
for offset, sorted_number in enumerate(sorted_list.copy()):
if item_compare <= sorted_number:
sorted_list.insert(... |
def cal_num_data_points(data: dict) -> int:
""" Calculate the number of data points in a dataset
Parameters
----------
data
dataset
Returns
-------
int
the number of data points in a dataset
"""
return sum([len(data_u) for u, data_u in data.items()]) |
def int_to_string(ints, inv_vocab):
"""
Output a machine readable list of characters based on a list of indexes in the machine's vocabulary
Arguments:
ints -- list of integers representing indexes in the machine's vocabulary
inv_vocab -- dictionary mapping machine readable indexes to machine re... |
def SGD(lr=0.001, momentum=0):
"""SGD Optimiser.
:param lr: Learning rate
:type lr: float
:param momentum: Momentum
:type momentum: float
"""
return {
"optimiser": "SGD",
"opt_args": {
"lr": lr,
"momentum": momentum
}... |
def GroupCheckBool(TagDict, TagGroupList):
"""
GroupCheckBool is a function to check whether the tag in TagDict.keys()
is in the TagGroupList. The key in TagDict is the tags and the value is
the corresponding colNum. TagGroupList is a List of List to specify the
group of the tag string.
... |
def value_and_ldj(fn, args):
"""Compute the value and log-det jacobian of function evaluated at args.
This assumes that `fn`'s `extra` output is a 2-tuple, where the first element
is arbitrary and the the last element is the log determinant of the jacobian
of the transformation.
Args:
fn: Function to ev... |
def SortClassAdsByElement(classads, element_name):
"""
Sort the classads (or any dictionary really) by an attribute
@param classads: list of classad objects
@param element_name: string of element name
"""
sorted_ads = sorted(classads, key=lambda ad: int(ad[element_name]))
return sorted_... |
def format_header_text(string: str):
"""Returns a header string that is centered within a space of 39 characters, bordered by "#".
Examples:
>>> format_header_text('ARRAY FUNCTIONS')\n
'########### ARRAY FUNCTIONS ###########'
"""
return "{0:#^39}".format(f" {string} ") |
def open_range_sublist(the_list, from_index, to_index):
"""
Returns an open range sublist of 'the_list', 'to_index' is not included.
:param the_list:
:param from_index:
:param to_index:
:return: sublist of 'the_list' or empty list if indexes are out of range
"""
tmp = []
list_len = l... |
def seconds_to_hour_min_sec(secs):
""" simple formatter
:param secs:
:return:
"""
hours = int(secs / 3600)
secs -= hours * 3600
mins = int(secs / 60)
secs -= mins * 60
return '{:02d}:{:02d}:{:02d}'.format(hours, mins, int(secs)) |
def replenerate_hostname(h):
"""
Apply sinusoidal repleneration to h, which might not be a FQDN,
ensuring it becomes a FQDN.
"""
return h if "." in h else f"{h}.wikimedia.org" |
def _buildTreeString(root, curr_index):
"""Recursively walk down the binary tree and build a pretty-print string.
In each recursive call, a "box" of characters visually representing the
current (sub)tree is constructed line by line. Each line is padded with
whitespaces to ensure all lines in the box ha... |
def validate_args(numargs, args):
"""
Check that there are enough args in the list, and truncate accordingly.
Raises ValueError if not.
"""
if len(args) < numargs:
raise ValueError("Not enough elements in list {}, need "
"{}.".format(args, numargs))
return args |
def get_layer_idx_for_vit(name, num_layers):
"""
Assign a parameter with its layer id
Following BEiT: https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33
"""
if name in ["cls_token", "pos_embed"]:
return 0
elif name.startswith("patch_embed"):
return 0
eli... |
def isWordGuessed(secretWord: str, lettersGuessed: list) -> bool:
"""Verify if secretWord was guessed
Args:
secretWord: the word the user is guessing
lettersGuessed: what letters have been guessed so far
Returns:
bool: True if all the letters of secretWord are in lettersGuessed,
... |
def _get_tolerance_line(line):
"""get a data item for a tolerance line with format (each line only one item):
i: type=rel, 1e-3
"""
assert line, 'Empty line!'
line = line.strip().replace(' ','')
stmp = line.split(':')
key = stmp[0]
_type, _val = stmp[1].split(',')
_type = _type.split... |
def convert_bbox_coord(coord, im_height_or_width=512):
""" Simple function designed to be used in a pd.apply() statement. Converts TF's
preferred format for bounding box coordinates (float percent to PASCAL VOC's
preferred format (pixel coordinates, top left origin).
NOTE: this currently... |
def sub_add(a, b, c=100):
"""
Should certainly explain the purpose of subadd here
"""
print(f"Subadd {a}-{b}+{c}={a-b+c}")
return a-b+c |
def str_to_list(data):
"""
Converts a string delimited by \n and \t to a list of lists.
:param data:
:type data: str
:return:
:rtype: List[List[str]]
"""
if isinstance(data, list):
return data
data = data.replace("'", '')
try:
if data[-1] == '\n':
d... |
def calculateBBCenter(bb):
"""
**SUMMARY**
(Dev Zone)
Calculates the center of the given bounding box
**PARAMETERS**
bb - Bounding Box represented through 2 points (x1,y1,x2,y2)
**RETURNS**
center - A tuple of two floating points
"""
center = (0.5*(b... |
def range_check(value, min_value, max_value, inc_value=0):
"""
:brief Determine if the input parameter is within range
:param value: input value
:param min_value: max value
:param max_value: min value
:param inc_value: step size, default=0
:return: Tru... |
def direct(deps):
""" Return the set of direct dependencies """
return {(a, b) for a, b, c in deps if c is False} |
def default_error_encode(
errors, encoding, msg, u, startingpos, endingpos):
"""A default handler, for tests"""
assert endingpos >= 0
if errors == 'replace':
return '?', endingpos
if errors == 'ignore':
return '', endingpos
raise ValueError |
def _require_version(server, version):
"""Check version of server
server[in] Server instance
version[in] minimal version of the server required
Returns boolean - True = version Ok, False = version < required
"""
if version is not None and server is not None:
major, minor... |
def date_mapper(date: float):
"""
map all dates from 20140101 to increasing naturals every
month
"""
date /= 100
month = int(date) - int(date / 100) * 100
date /= 100
year = int(date) - 2014
return year * 12 + month |
def clean_postcode(postcode):
"""
Returns `postcode` lowercase without spaces so that it can be used for comparisons.
"""
if not postcode:
return postcode
return postcode.lower().replace(' ', '').strip() |
def clear_process_data(process_data) -> dict:
""" Create a copy of the process data where all keys with a 'None'-value are removed.
"""
pd = {
'order': [],
'station': [],
'factory': process_data['factory']
}
for order in process_data['order']:
pd['order'].append({k... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.