content stringlengths 42 6.51k |
|---|
def merge(nums1, nums2):
"""
:param nums1: Sorted list of numbers.
:param nums2: Sorted list of numbers.
:return: Combined sorted list of numbers.
"""
merged = list()
while len(nums1) != 0 and len(nums2) != 0:
if nums1[0] <= nums2[0]:
merged.append(nums1.pop(0))
... |
def clean_text(raw_text):
""" Clean text by removing extra spaces between words
Args:
raw texts
Returns:
Cleaned text
"""
token_words = raw_text.split()
cleaned_text = ' '.join(token_words)
return cleaned_text |
def try_number(value):
"""Try converting the value to a number."""
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
return value |
def deep_encode(e, encoding='ascii'):
"""
Encodes all strings using encoding, default ascii.
"""
if isinstance(e, dict):
return dict((i, deep_encode(j, encoding)) for (i, j) in e.items())
elif isinstance(e, list):
return [deep_encode(i, encoding) for i in e]
elif isinstance(e, str):
e = e.encode... |
def split_by_value(total, nodes, headdivisor=2.0):
"""Produce, (sum,head),(sum,tail) for nodes to attempt binary partition"""
head_sum, tail_sum = 0, 0
divider = 0
for node in nodes[::-1]:
if head_sum < total/headdivisor:
head_sum += node[0]
divider -= 1
else:
... |
def infinitve(conjugate, infinitive_map):
"""Get infinitive form of a conjugated verb.
Given a mapping of conjugate to infinitive, this function computes
the infinitive form of a conjugate verb. We provide models available
for downloading, so you do not have to worry about the ``infinitive_map``.
R... |
def egcd(b, n):
"""Calculates GCD iteratively, using Euclid's algorithm."""
x0, x1, y0, y1 = 1, 0, 0, 1
while n != 0:
q, b, n = b // n, n, b % n
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return b, x0, y0 |
def output(node):
""" outputs a string with the textual representation of the node and it's children"""
if (node == None):
return ""
if node.syntax is None:
o = " (" + "TabooNone"
print("Warning: outputting TabooNone")
else:
o = " (" + node.syntax
if (node.wo... |
def remove_extension(file_path):
"""
Removes extension of the given file path
For example, C:/test/rig.py will return rig
:param file_path: str
:return: str
"""
split_path = file_path.split('.')
new_name = file_path
if len(split_path) > 1:
new_name = '.'.join(split_path[:-1]... |
def cp_to_str(cp):
"""
Convert a code point (int) to a string.
"""
return "%04X" % cp |
def sort_hyps(hyps, vocab_size, key_token_ids, complete_hyps):
"""
Return a list of Hypothesis objects, sorted by descending average log probability.
"""
return sorted(
hyps,
key=lambda h: h.score(vocab_size, key_token_ids, complete_hyps),
reverse=True,
) |
def treeify(dependencies):
"""Treeify a list of dependencies."""
tree = {}
ancestors = []
for dependency in dependencies:
# Dependency is the root of the tree.
if dependency["level"] == 0 and tree == {}:
tree = {
"children": None,
"level": 0,
... |
def segments_overlap(a, b):
"""Returns True if GPS segment ``a`` overlaps GPS segment ``b``
"""
return (a[1] > b[0]) and (a[0] < b[1]) |
def _parse_boolean(xml_boolean):
"""Converts strings "true" and "false" from XML files to Python bool"""
if xml_boolean is not None:
assert xml_boolean in ["true", "false"], \
"The boolean string must be \"true\" or \"false\""
return {"true": True, "false": False}[xml_boolean] |
def remove_exclusion(failed_tasks: list, playbook_exclusion: list):
"""
Checks if one of the failed tasks is from an excluded playbook and if so removes it from the list.
Args:
failed_tasks: A list of failed tasks.
playbook_exclusion: A list of names of playbooks to exclude.
Returns:
... |
def partition_subtokens(subtokens):
"""Return list of (start, end , [list of subtokens]) for each token."""
words = []
last = 0
for i, token in enumerate(subtokens):
if token[-1] == '_':
words.append((last, i + 1, subtokens[last:i + 1]))
last = i + 1
return words |
def margin2(contingency_table, i):
"""Calculate the margin distribution of classifier 2."""
return sum([contingency_table[i][j]
for j in range(len(contingency_table))]) |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
step_unit = 1000.0 # 1024?
results=[]
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
results.append("%3.2f %s" % (num, x))
num /= step_unit
return results |
def check_type(data, dtype):
"""
ckeck data type
:param data: data
:param dtype: data type
:return: error
"""
error = ''
for item in data:
if not isinstance(item, type(dtype)):
error = '{0} data type is error!'.format(item)
break
return error |
def changes_record(bucket_id, collection_id):
"""Utility function to gin up something that is kind of like a kinto-changes record."""
return {
'id': 'abcd',
'last_modified': 123,
'bucket': bucket_id,
'collection': collection_id,
'host': 'http://localhost',
} |
def getDistance (origin, point):
"""
Returns the distance between two points.
"""
dist = ((origin[0]-point[0])**2 + (origin[1]-point[1])**2)**0.5
return dist |
def repeat_last_operation(calc):
"""
Returns the result of the last operation executed in the history.
"""
if calc['history']:
return calc['history'][-1][3] |
def compute_checksum(line):
"""Compute the TLE checksum for the given line."""
return sum((int(c) if c.isdigit() else c == '-') for c in line[0:68]) % 10 |
def mean(feature_vector):
"""
:param feature_vector: List of integer/float/double..
:return: Mean of the feature vector.
"""
return sum(f for f in feature_vector)/len(feature_vector) |
def get_attribute_terms(product):
"""
Function to iterate through all variants of a variable product and compile a list of attribute terms from them.
:param product: Variable product and variants information
:return: list of term names
"""
attribute_terms = list()
for variation in product['... |
def get_sqlserver_hashed_sample_clause(id_clause, sample_pct):
"""Get SQL Server-valid synthax for hashed-sampling an id clause.on
Takes as imput a given sample_pct in (0, 1).
Parameters
----------
id_clause :
sample_pct :
Returns
-------
"""
assert 0 < sample_pct < 1, f'{s... |
def elide(text: str, length: int) -> str:
"""Elide text so it uses a maximum of length chars."""
if length < 1:
raise ValueError("length must be >= 1!")
if len(text) <= length:
return text
else:
return text[:length - 1] + '\u2026' |
def get_prefixes(snodes):
"""
snodes: List. List of suffix nodes for a header
"""
all_prefixes = []
for node in snodes:
prefix = []
count = node.node_count
while node.parent is not None:
prefix.append(tuple([node.item, count]))
node = node.parent
... |
def triggers_to_event_id(triggers):
"""Convert list or dict of triggers to MNE-style event_id"""
# Convert list to dict with triggers as condition names
if isinstance(triggers, list):
triggers = {str(trigger): trigger for trigger in triggers}
else:
assert isinstance(triggers, dict), \
... |
def are_eq(A,B,tolerance=1e-4):
"""Check two arrays for tolerance [1,2,3]==[1,2,3]; but [1,3,2]!=[1,2,3]
Args:
A, B (lists): 1-D list of values for approximate equality comparison
tolerance: numerical precision for equality condition
Returns:
boolean
"""
are_eq = Tr... |
def highlight_positives(test_result: bool) -> str:
"""
Highlight positive values in red.
Parameters
----------
test_result : bool
Observed test result
Returns
-------
str
Cell background color definition
"""
color = "red" if test_result else "white"
return ... |
def hamming_distance(lhs, rhs):
"""Returns the Hamming Distance of Two Equal Strings
Usage
>>> nt.hamming_distance('Pear','Pearls')
"""
return len([(x, y) for x, y in zip(lhs, rhs) if x != y]) |
def intersection_of_arrays(l1,l2):
"""
O(n) time
O(n) space
"""
set1 = set()
for elem in l1:
set1.add(elem)
set2 = set()
for elem in l2:
set1.add(elem)
res = []
for elem in set1:
if elem in set2:
res.append(elem)
return res |
def flatten2Class(*args):
"""
The flatten2Class method answers the class string, made from space separated class names. If
cssClass is a tuple or list, then merge the content. Check recursively in
case the names are nested. If the classes is empty or None or contain an empty
element, then this is i... |
def words_to_sentence(words: list) -> str:
""" This function create a string from a list of strings, separated by space. """
return ' '.join(words) |
def double_quotes(unquoted):
"""
Display String like redis-cli.
escape inner double quotes.
add outer double quotes.
:param unquoted: list, or str
"""
if isinstance(unquoted, str):
# escape double quote
escaped = unquoted.replace('"', '\\"')
return f'"{escaped}"' # ... |
def authors_to_string(names):
"""
creates a single string with all authors with only first letter of the firstname followed by a dot and surname.
Author names are sperated by comma except for the last author which is seperated via 'and'.
"""
string_authors = ''
d = ', '
for idx, name in enu... |
def osm_length_sql(grid, osm, cat):
"""
Returns a sql fragment that sums the length of OSM line features per grid
cell by category
Args:
grid (string): a PostGIS table name containing the grid
osm (string): a PostGIS table name containing the OSM line features
cat (string): a Po... |
def env_value_student(input_version):
"""Return the Student version Environment Variable name based on an input version string
Parameters
----------
input_version : str
Returns
-------
str
Examples
--------
>>> env_value_student("2021.1")
"ANSYSEMSV_ROOT211"
"""
v... |
def make_dict(inp):
"""
Transform the instance ``inp`` into a python dictionary.
If inp is already a dictionary, it perfroms a copy.
Args:
inp (dict): a instance of a Class which inherits from dict
Returns:
dict: the copy of the class, converted as a dictionary
"""
import cop... |
def ENDS_WITH(rule_value, tran_value):
"""Return True if tran_value ends with rule_value
Parameters:
rule_value: Value from the rule file to check for.
tran_value: Value from transaction.
Return:
bool: Will return true if `tran_value` ends with `rule_value`.
"""
rule_value ... |
def convert_to_celsius(fahrenheit: float) -> float:
"""
>>> convert_to_celsius(75)
23.88888888888889
"""
return fahrenheit - 32.0 * 5.0 / 9.0 |
def slice_data(data, info, split):
"""Slice data according to the instances belonging to each split."""
if split is None:
return data
elif split == 'train':
return data[:info['train_len']]
elif split == 'val':
train_n = info['train_len']
val_n = train_n + info['val_len']
... |
def add_trailing_slash(s):
"""Add trailing slash. """
if not s.endswith('/'):
s = s + '/'
return(s) |
def fib2(n): # return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below
a, b = b, a + b
return result |
def api_response(data, status, code=200):
"""
Return json response to user.
If the data is a list, return a response of the json of all objects in that list.
If the data is a json blob, return that as the data.
If the data is None, just return the given status.
"""
if type(data) == list:
... |
def remove_app(INSTALLED_APPS, app):
""" remove app from installed_apps """
if app in INSTALLED_APPS:
apps = list(INSTALLED_APPS)
apps.remove(app)
return tuple(apps)
return INSTALLED_APPS |
def _organize_requests_by_external_key(enrollment_requests):
"""
Get dict of enrollment requests by external key.
External keys associated with more than one request are split out into a set,
and their enrollment requests thrown away.
Arguments:
enrollment_requests (list[dict])
Ret... |
def _clean_label(label):
"""Replaces all underscores with spaces and capitalizes first letter"""
return label.replace("_", " ").capitalize() if label is not None else None |
def transfer_function_Rec2020_12bit_to_linear(v):
"""
The Rec.2020 12-bit transfer function.
Parameters
----------
v : float
The normalized value to pass through the function.
Returns
-------
float
A converted value.
"""
a = 1.0993
b = 0.0181
d = 4.5
... |
def normalize(arr, total=1.0):
"""Normalizes an array to have given total sum"""
try:
fac = total/float(sum([abs(v) for v in arr]))
except ZeroDivisionError: fac = 1.0
return [v*fac for v in arr] |
def option_str_list(argument):
"""
An option validator for parsing a comma-separated option argument. Similar to
the validators found in `docutils.parsers.rst.directives`.
"""
if argument is None:
raise ValueError("argument required but none supplied")
else:
return [s.strip() fo... |
def splitDateTime(string):
""" split Sun May 10 18:23:32 +0000 2015 into NameOfDay Month Day Hour TimeZone Year"""
d = string.split(" ")
return d |
def split(text):
"""
Convenience function to parse a string into a list using two or more spaces
as the delimiter.
Parameters
----------
text : string
Contains text to be parsed
Returns
-------
textout : list
list of strings containing the parsed input ... |
def get_indx(scrub_input, frames_in_1D_file):
"""
Method to get the list of time
frames that are to be included
Parameters
----------
in_file : string
path to file containing the valid time frames
Returns
-------
scrub_input_string : string
input string for 3dCalc i... |
def check_size(grid):
"""
Checks if user input grid is 9x9.
"""
row_count = 0
col_count = 0
for row in grid:
row_count += 1
for col in grid[row]:
col_count += 1
if col_count != 9:
return False
else:
col_count = 0
... |
def win_path_join(dirname: str, basename: str) -> str:
"""Join path Windows style"""
d = dirname.rstrip("\\")
return f'{d}\\{basename}' |
def comma_join(items):
"""
Joins an iterable of strings with commas.
"""
return ', '.join(items) |
def is_concept_id_col(col):
"""
Determine if column is a concept_id column
:param col: name of the column
:return: True if column is a concept_id column, False otherwise
"""
return col.endswith('concept_id') |
def canonicalize_eol(text, eol):
"""Replace any end-of-line sequences in TEXT with the string EOL."""
text = text.replace('\r\n', '\n')
text = text.replace('\r', '\n')
if eol != '\n':
text = text.replace('\n', eol)
return text |
def _join_parameters(parameters):
"""
Takes list of parameter and returns a string with ', ' between parameters
:param parameters: list
:return: parameters concatenated by a semicolon
:rtype: string
"""
parameter_string = ''
for p in parameters:
if p != '':
parameter_... |
def fewest_cities_needed(total, items):
"""Sum largest cities first until sum exceeds total."""
for i in range(len(items)):
s = sum(items[:i])
if s > total:
return i
return 0 |
def amatch(s: str, pat: str) -> int:
"""
Returns number of matching characters in `s` and `pat` before
a "*" or "#" character in pat. Returns -1 if strings do not match
Example:
amatch("abc", "a*") -> 1
amatch("wx", "wx") -> 2
amatch("xy", "xz") -> -1
"""
for count, (c, p) in enumerate(zip(s, pat)):
if p ... |
def check_afm(afm):
"""Check the validity of an AFM number (Greek VAT code).
Check if input is a valid AFM number via its check digit (not if it is actually used).
Return either True of False.
Input should be given as a string. An integer, under certain conditions, could through an exception.
"""
if not... |
def ods_bool_value(value):
"""convert a boolean value to text"""
if value is True:
return "true"
else:
return "false" |
def calc_w_from_q(q):
"""Calculate water vapor mixing ratio (1) from specific humidity q
(1)."""
return q/(1. - q) |
def calculate_beta(diffusivity,node_spacing,time_interval):
"""
Calculate beta, a substitution term based on diffusivity, the spacing
of nodes within the modeled grain, and the timestep. After Ketcham, 2005.
Parameters
----------
diffusivity : float
Diffusivity.
node_spacing : float... |
def recover_escape(text: str) -> str:
"""Converts named character references in the given string to the corresponding
Unicode characters. I didn't notice any numeric character references in this
dataset.
Args:
text (str): text to unescape.
Returns:
str: unescaped string.
"""
... |
def find_two_sum(numbers, target_sum):
"""
:param numbers: (list of ints) The list of numbers.
:param target_sum: (int) The required target sum.
:returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum
"""
taken = {}
for i, num in enumerate(numbers):
... |
def frequency_interaction_fingerprint(fp_list):
"""
Create frequency fingerprint from list of fingerprints.
"""
count_fp = [sum(i) for i in zip(*fp_list)]
frequency_fp = [float(i) / len(fp_list) for i in count_fp]
return frequency_fp |
def parse_readable_size_str(size_str):
"""Convert a human-readable str representation to number of bytes.
Only the units "kB", "MB", "GB" are supported. The "B character at the end
of the input `str` may be omitted.
Args:
size_str: (`str`) A human-readable str representing a number of bytes
... |
def madau_17(z):
"""
returns star formation rate as a function of supplied redshift
Parameters
----------
z : `float or numpy.array`
redshift
Returns
-------
sfr : `float or numpy.array`
star formation rate [Msun/yr]
"""
sfr = 0.01 * (1 + z) ** (2.6) / (1 + ((1... |
def get_http_method_type(method: str):
"""Return lowercase http method name, if valid. Else, raise Exception."""
supported_methods = ["get", "post", "put", "delete" # , "head", "connect", "options", "trace", "patch"
]
m = str(method).lower()
if not m in supported_methods:
... |
def _sim_texture(r1, r2):
"""
calculate the sum of histogram intersection of texture
"""
return sum([min(a, b) for a, b in zip(r1["hist_t"], r2["hist_t"])]) |
def MAP(_input, _as, _in):
"""
Applies an expression to each item in an array and returns an array with the applied results.
See https://docs.mongodb.com/manual/reference/operator/aggregation/map/
for more details
:param _input: An expression that resolves to an array.
:param _as: A name for the... |
def sizeof_fmt(num):
"""
Convert file size to human readable format.
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "{0:.2f} {1}".format(num, x)
num /= 1024.0 |
def int_to_str(item: int) -> str:
"""[summary]
Args:
item (int): [description]
Returns:
str: [description]
"""
"""Converts an int to a str."""
return str(item) |
def _split_choices_in_list(choices_string):
"""
Riceve una stringa e la splitta ogni ';'
creando una lista di scelte
"""
str_split = choices_string.split(';')
return str_split |
def evi_func(blue, red, nir):
"""Compute enhanced vegetation index
Parameters
----------
blue : array_like
Blue band (band 1 on Landsat 5/7, band 2 on Landsat 8).
red :
Red band (band 3 on Landsat 5/7, band 4 on Landsat 8).
nir : array_like
Near infrared band (band 4 on ... |
def file_is_ipython_notebook(path):
"""Check whether a file is an iPython Notebook.
Args:
path (str): path to the file.
Examples:
path : source path with .ipynb file '/path/src/my_file.ipynb.
"""
return path.lower().endswith(".ipynb") |
def remove_dropped(ps_lst):
"""
@brief Removes every item of ps_lst which is marked to drop
@param ps_lst List of PseudoInstructions
@return List of PseudoInstructions
"""
ret = []
for item in ps_lst:
if not item.drop:
ret.append(item)
else:
del item
... |
def calculate_tva(price, tva=20):
"""Calculates the tax on a product
Formula
-------
price * (1 + (tax / 100))
"""
return round(float(price) * (1 + (tva / 100)), 2) |
def parse_viewed_courses(json):
"""
Parse course viewed statements.
Extract the students that have viewed the course from the course viewed statements.
Return a list of those students.
:param json: All the course viewed statements since a certain time.
:type json: dict(str, str)
:return: L... |
def is_sound_valid(wav_file: str) -> bool:
"""Asserts if sound file is valid.
Args:
wav_file (str): Path to wav file
Returns:
bool: If file is valid
"""
return wav_file.endswith(".wav") |
def bubble_sort(collection):
"""
contoh
>>> bubble_sort([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
True
"""
panjang = len(collection)
for i in range(panjang - 1):
swap = False
for j in range(panjang - 1 - i):
... |
def convert_rotate(rotate):
""" 8. Rotate 90,180, 270 degree """
if rotate > 0:
command = "-rotate " + str(rotate)
else:
command = ""
return command |
def get_decimals(value) -> int:
"""Get the number of decimal places required to represent a value.
Parameters
----------
value : :class:`int` or :class:`float`
The value.
Returns
-------
:class:`int`
The number of decimal places.
"""
val = abs(value)
fraction = ... |
def bisection_search2(L, e):
"""
Implementation 2 for the divide-and-conquer algorithm
Complexity: O(log n)
:param L: List-object
:param e: Element to look for
:return: Boolean value if element has been found
"""
def helper(L, e, low, high):
if high == low:
... |
def is_valid_str(s: str) -> bool:
"""
Check if the input string is not empty.
:param s: Input string.
:return: True if the string is not empty.
"""
if s is None:
return False
if not isinstance(s, str):
return False
if len(s) <= 0:
return False
return True |
def update_odds_with_evidence( prevalence, testPower, evdnc ):
""" Compute a new odds of an outcome """
evPos = evdnc
evNeg = 1 - evdnc
oddsPos = prevalence[evPos]/prevalence[evNeg] * testPower[evdnc][evPos]/testPower[evdnc][evNeg]
oddsNeg = float('nan')
if oddsPos > 1:
oddsNeg = 1.0... |
def read_16bit_size(data, little_endian=True):
""" Read next two bytes as a 16-bit value """
if little_endian:
return data[0] + data[1] * 256
else:
return data[1] + data[0] * 256 |
def get_reading_level_from_flesch(flesch_score):
"""
Thresholds taken from https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests
:param flesch_score:
:return: A reading level and difficulty for a given flesch score
"""
if flesch_score < 30:
return "Very difficult to read... |
def replace_range(old_lines, new_lines, r=None):
"""
>>> a = list(range(10))
>>> b = list(range(11, 13))
>>> replace_range(a, b, (0, 2))
[11, 12, 2, 3, 4, 5, 6, 7, 8, 9]
>>> replace_range(a, b, (8, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 11, 12]
>>> replace_range(a, b, (0, 10))
[11, 12]
>>... |
def verify_integer(filter_value):
"""Used to verify that <input> type textboxes that should be integers actually are."""
try:
int(filter_value)
return True
except:
return False |
def html(module, tag):
"""Mapping for html tags.
Maps tags to title case, so you can type html tags as ``<audio>``
or ``<AuDiO>`` or whichever way.
"""
title = tag.title()
if title in {
"A",
"Abbr",
"Acronym",
"Address",
"Area",
"Article",
... |
def get_repo_from_tool(tool):
"""
Get the minimum items required for re-installing a (list of) tools
"""
if not tool.get('tool_shed_repository', None):
# Tool or Data Manager not installed from a tool shed
return {}
tsr = tool['tool_shed_repository']
repo = {'name': tsr['name'],
... |
def _split_arrays(arrays, extra_args, nparts):
"""
Split the coordinate arrays into nparts. Add extra_args to each part.
Example::
>>> chunks = _split_arrays([[1, 2, 3, 4, 5, 6]], ['meh'], 3)
>>> chunks[0]
[[1, 2], 'meh']
>>> chunks[1]
[[3, 4], 'meh']
>>> chunks[2]
[[5, 6], 'me... |
def format_docstring(docstring):
"""
Taken from https://github.com/fecgov/openFEC/blob/master/webservices/spec.py
"""
if not docstring or not docstring.strip():
return ""
formatted = []
lines = docstring.expandtabs().splitlines()
for line in lines:
if line == "":
... |
def suck_out_editions(reporters):
"""Builds a dictionary mapping edition keys to their root name.
The dictionary takes the form of:
{
"A.": "A.",
"A.2d": "A.",
"A.3d": "A.",
"A.D.": "A.D.",
...
}
In other words, this lets you go from an editio... |
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = {}
res_list = []
for i in range(len(nums)):
seen = {}
seen[nums[i]] = 1
for j in range(len(nums)):
if j == i:
continue
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.