content stringlengths 42 6.51k |
|---|
def no_duplicates(seq):
""" Remove all duplicates from a sequence and preserve its order """
# source: https://www.peterbe.com/plog/uniqifiers-benchmark
# Author: Dave Kirby
# Order preserving
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)] |
def mrg(tr):
"""return constituency string."""
if isinstance(tr, str):
return tr + ' '
else:
s = '( '
for subtr in tr:
s += mrg(subtr)
s += ') '
return s |
def parse_file_to_bucket_and_filename(file_path):
"""Divides file path to bucket name and file name"""
path_parts = file_path.split("//")
if len(path_parts) >= 2:
main_part = path_parts[1]
if "/" in main_part:
divide_index = main_part.index("/")
bucket_name = main_par... |
def fib_recursive_mathy_cached(n):
"""Same function as "fib_recursive_mathy", but this is cached using a generic memoizer as decorator.
The decorator is implemented in "./util/cache.py".
"""
if n < 2:
return n
return fib_recursive_mathy_cached(n - 1) + fib_recursive_mathy_cached(n - 2) |
def centroid_points(points):
"""Compute the centroid of a set of points.
Warnings
--------
Duplicate points are **NOT** removed. If there are duplicates in the
sequence, they should be there intentionally.
Parameters
----------
points : sequence
A sequence of XYZ coordinates.
... |
def ext_on_list(name, lst):
""" Return True if `name` contains any extension in `lst` """
for ext in lst:
if name.rfind(ext) >= 0:
return True
return False |
def _release_to_path(release):
"""Compatibility function, allows us to use release identifiers like "3.0" and "3.1"
in the public API, and map these internally into storage path segments."""
if release == "3.0":
# special case
return "v3"
elif release.startswith("3."):
return f"v... |
def is_blocking(blocking: str) -> bool:
""" Returns True if the value of `blocking` parameter represents true else returns false.
:param blocking: Value of `blocking` parameter.
"""
return True if blocking.lower() == "true" else False |
def query_doctypes(doctypes):
"""ES query for specified doctypes
Args:
doctypes (list)
Returns:
ES query (JSON)
"""
return {"query": {"terms": {"doctype": doctypes}}} |
def flatten(d: dict, _key_prefix: tuple = tuple()) -> dict:
"""Convert nested dict `d` to a flat dict with tuple keys.
Input `_key_prefix` is prepended to the keys of the resulting dict,
and is used internally for recursively flattening the dict."""
result = {}
for key, value in d.items():
f... |
def change_semicolon(new_line_changed_batch):
"""Replace a semicolon character with a space
"""
return new_line_changed_batch.replace(':', ' ') |
def expected_value(win_loss_ratio, win_probability):
"""
Calculates expected value of a bet.
:return: Returns expected value.
:rtype: Float
"""
return win_loss_ratio * win_probability - (1 - win_probability) |
def metadata(data):
"""Convert a dictionary of strings into an RST metadata block."""
template = ":%s: %s\n"
return ''.join(template % (key, data[key]) for key in data) |
def urlunparse(data):
"""
Modified from urlparse.urlunparse to support file://./path/to urls
"""
scheme, netloc, url, params, query, fragment = data
if params:
url = "%s;%s" % (url, params)
if netloc:
url = '//' + (netloc or '') + url
if scheme:
url = scheme + ':' + u... |
def make_safe_id(idstr):
"""Make safe ID attribute used in HTML.
The following characters are escaped in strings:
- ``/``
- ``<``
- ``>``
"""
rv = idstr\
.replace(u'/', u'-')\
.replace(u'<', u'') \
.replace(u">", u'')
return rv |
def get_head_dict(heads):
"""
Takes a list of heads for a sentence and returns a dictionary that maps words to the set with their children
:param heads:
:return:
"""
#usually, you want to call get_head_dict(some_heads[1:]) #strip off -1
head_dict = dict()
for (m,h) in enumerate(heads):
... |
def _allowed_file(filename):
"""
Checks if the the filename belongs to a zip file.
:param filename: filename to check
:return: boolean value
"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ['zip'] |
def calculate_package_base_hazard_rate(n_active_pins: int) -> float:
"""Calculate the package base hazard rate (lambdaBP).
:param n_active_pins: the number of active (current carrying) pins.
:return: _lambda_bd; the calculated package base hazard rate.
:rtype: float
"""
return 0.0022 + (1.72e-5... |
def apply_to_field_if_exists(effect, field_name, fn, default):
"""
Apply function to specified field of effect if it is not None,
otherwise return default.
"""
value = getattr(effect, field_name, None)
if value is None:
return default
else:
return fn(value) |
def get_function_block(code, function_name):
"""
Simplistic string manipulation to find single function call 'block', for
example:
maven_artifact(
"group",
"artifact",
"version"
)
The logic below assumes the character ')' doesn't appear anywher... |
def CalculateInteraction2(dict1={}, dict2={}):
"""
Calculate the two interaction features by combining two different
features.
Usage:
res=CalculateInteraction(dict1,dict2)
Input: dict1 is a dict form containing features.
dict2 is a dict form containing features.
... |
def is_not_zero_divisor(var1):
""" Check if the given input is zero."""
tmp = list(var1) # Is it neended?
if tmp == ['0']:
print("\t##Zero cannot be a divisor!")
return False
return True |
def tablename_to_dict(table, separator="."):
"""Derive catalog, schema and table names from fully qualified table names"""
catalog_name = None
schema_name = None
table_name = table
s = table.split(separator)
if len(s) == 2:
schema_name = s[0]
table_name = s[1]
if len(s) > 2:... |
def igetattr(obj, attr, *args):
"""
Indexed getattr function
Examples:
>>> model = Model()
>>> igetattr(model, "weight[2]")
"""
if "[" in attr and "]" in attr:
attr = "".join("\t".join(attr.split("[")).split("]")).split("\t")
indexes = "[".join(attr[1:-1]).replace("[... |
def correct_grd_metadata_key(original_key: str) -> str:
"""
Change an upper case GRD key to it's SLC metadata equivalent.
By default this is uppercasing all keys; otherwise if the value in the
`special_keys` dict will be used.
Args:
original_key: input metadata key
special_keys: dic... |
def evaluate_bounding_box(ctrlpts):
""" Evaluates the bounding box of a curve or a surface.
:param ctrlpts: control points
:type ctrlpts: list, tuple
:return: bounding box
:rtype: list
"""
# Estimate dimension from the first element of the control points
dimension = len(ctrlpts[0])
... |
def nps_check(type, number):
"""
Check size of group and return 'GOOD' or 'BAD'.
"""
if type == 'promoters':
if number >= 200:
return 'GOOD'
else:
return 'BAD'
if type == 'passives':
if number >= 100:
return 'GOOD'
else:
... |
def complete(tab, opts):
"""
get options that start with tab
:param tab: query string
:param opts: list that needs to be completed
:return: a string that start with tab
"""
msg = "({0})"
if tab:
opts = [m[len(tab):] for m in opts if m.startswith(tab)]
if len(opts) == 1:
... |
def enumerate_times(list):
"""Enumerates through list to create list based off index values
This function takes a list of timestamp string values and creates
a new list containing index labels to be displayed in the
historical_ecg_label ECG combobox.
Args:
list (list): list of string value... |
def is_signed_int(num_str):
"""
Args:
num_str (str): The string that is checked to see if it represents a number
Returns:
bool
"""
# if the num_str is a digit, that means that there are no special characters within the num_str
# therefore making it a nonneg int
# to check if... |
def sum_1(strg):
"""Sums first 3 digits"""
sum = 0
for i in strg[:3]:
sum += int(i)
if sum == 0:
sum = 1
return sum |
def update_repository_name(repository):
"""Update given repository name so it won't contain any prefix(es)."""
lastSlash = repository.rfind("/")
# make sure we use just the repo name
if lastSlash >= 0 and lastSlash < len(repository) - 1:
return repository[1 + lastSlash:]
else:
retur... |
def parseBP(s):
"""
:param s: string
:return: string converted to number, taking account for kb or mb
"""
if not s:
return False
if s.isnumeric():
return int(s)
s = s.lower()
if "kb" in s:
n = s.split("kb")[0]
if not n.isnumeric():
return False... |
def float16(val):
"""Convert a 16-bit floating point value to a standard Python float."""
# Fraction is 10 LSB, Exponent middle 5, and Sign the MSB
frac = val & 0x03ff
exp = (val >> 10) & 0x1F
sign = val >> 15
if exp:
value = 2 ** (exp - 16) * (1 + float(frac) / 2**10)
else:
... |
def parse_gbi_yiqtol(tag):
"""Parse a GBI yiqtol tag into cohortative and jussives."""
if tag.endswith('Jm'):
return 'yqtl'
elif tag.endswith('Jt'):
return 'jussF'
elif tag.endswith('Cm'):
return 'yqtl'
elif tag.endswith('Ct'):
return 'cohoF' |
def private_ip_addresses(server):
"""
Get all private IPv4 addresses from the addresses section of a server.
:param dict server: A server body.
:return: List of IP addresses as strings.
"""
return [addr['addr'] for addr in server['server']['addresses']['private']
if addr['version'] ... |
def find_rds_instance(rds_list, db_name):
"""
:param rds_list:
:param db_name:
:return:
"""
db_info = None
for db_instance in rds_list:
if db_name == db_instance['db_name']:
db_info = db_instance
return db_info |
def isbn_13_check_digit(twelve_digits):
"""Function to get the check digit for a 13-digit ISBN"""
if len(twelve_digits) != 12: return None
try: int(twelve_digits)
except: return None
thirteenth_digit = 10 - int(sum((i % 2 * 2 + 1) * int(x) for i, x in enumerate(twelve_digits)) % 10)
if thi... |
def locale_to_lower_upper(locale):
"""
Take a locale, regardless of style, and format it like "en_US"
"""
if '-' in locale:
lang, country = locale.split('-', 1)
return '%s_%s' % (lang.lower(), country.upper())
elif '_' in locale:
lang, country = locale.split('_', 1)
r... |
def ring_area_factor(theta, r_in, r_out):
"""Compute ring area factor.
Parameters
----------
theta : float
On region radius
r_in : float
Inner ring radius
r_out : float
Outer ring radius
"""
return (r_out ** 2 - r_in ** 2) / theta ** 2 |
def true_smile_tokenizer(line):
"""Return each character or atom as the token."""
line = line.strip().replace(" ", "")
len_2_tokens = ["Cl", "Br"]
idx = 0
tokens = []
while idx < len(line):
if idx < len(line)-1 and line[idx:idx+2] in len_2_tokens:
token = line[idx:idx+2]
... |
def npv(rate, cashflows):
"""The total present value of a time series of cash flows.
>>> npv(0.1, [-100.0, 60.0, 60.0, 60.0])
49.211119459053322
"""
total = 0.0
for i, cashflow in enumerate(cashflows):
total += cashflow / (1 + rate)**i
return total |
def get_center_point(box_coordinates):
"""
Returns the center point coordinate of a rectangle.
Args:
box_coordinates (list): A list of four (int) coordinates,
representing a rectangle "box".
Returns:
list: A list with two (int) coordinates, the center poi... |
def get_rr_p_parameter_default(nn: int) -> float:
"""
Returns p for the default expression outlined in arXiv:2004:14766.
Args:
nn (int): number of features currently in chosen subset.
Returns:
float: the value for p.
"""
return max(0.1, 4.5 - 0.4 * nn ** 0.4) |
def short_hostname(hostname):
"""The first part of the hostname."""
return hostname.split(".")[0] |
def addAllnonempty(master,
smaller):
"""
Retrieve Non-empty Groups
"""
for s in smaller:
strim = s.strip()
if (len(strim) > 0):
master.append(strim)
return master |
def finditem(func, seq):
"""Finds and returns first item in iterable for which func(item) is True.
"""
return next((item for item in seq if func(item))) |
def common_languages(programmers):
"""Receive a dict of keys -> names and values -> a sequence of
of programming languages, return the common languages"""
programmers_list = [set(v) for v in programmers.values()]
result = programmers_list[0]
for programmer in programmers_list[1:]:
r... |
def dunder_get(_dict, key):
"""Returns value for a specified dunderkey
A "dunderkey" is just a fieldname that may or may not contain
double underscores (dunderscores!) for referrencing nested keys in
a dict. eg::
>>> data = {'a': {'b': 1}}
>>> nesget(data, 'a__b')
1
key... |
def num_neighbours(lag=1):
"""
Calculate number of neigbour pixels for a given lag.
Parameters
----------
lag : int
Lag distance, defaults to 1.
Returns
-------
int
Number of neighbours
"""
win_size = 2*lag + 1
neighbours = win_size**2 - (2*(lag-... |
def interleaved_sum(n, odd_term, even_term):
"""Compute the sum odd_term(1) + even_term(2) + odd_term(3) + ..., up
to n.
>>> # 1 + 2^2 + 3 + 4^2 + 5
... interleaved_sum(5, lambda x: x, lambda x: x*x)
29
"""
if n == 1:
return odd_term(1)
return (odd_term(n) if n % 2 == 1 else eve... |
def create_generator_of_subgroup(discriminant):
"""'Generator' as per Chia VDF competition.
See: https://www.chia.net/2018/11/07/chia-vdf-competition-guide.en.html
Note: This element generates a cyclic subgroup for given discriminant,
not per se the entire group.
"""
if (1 - discriminant... |
def exponential_growth(level, constant=1):
"""
The number of samples in an exponentially growing 1D quadrature rule of
a given level.
Parameters
----------
level : integer
The level of the quadrature rule
Return
------
num_samples_1d : integer
The number of samples i... |
def count_paragraphs(s):
"""Counts the number of paragraphs in the given string."""
last_line = ""
count = 0
for line in s.split("\n"):
if len(line) > 0 and (len(last_line) == 0 or last_line == "\n"):
count += 1
last_line = line
return count |
def prefix(string1, string2):
"""Return the prefix, if any, that appears in both string1 and
string2. In other words, return a string of the characters that
appear at the beginning of both string1 and string2. For example,
if string1 is "inconceivable" and string2 is "inconvenient", this
function wi... |
def interval(f,a,b,dx):
"""
This function creates an interval of form [f(a), f(a+dx), ..., f(b)]
Arguments f- any function of a single variable
a- left end point on [a,b]
b- right end point in [a,b]
dx- spacing between coordinates"""
k = 0
... |
def intToColorHex(color_number: int) -> str:
"""Convert an integer to a hexadecimal string compatible with :class:`QColor`
Args:
color_number: integer value of a RGB color
Returns:
:class:`QColor` compatible hex string in format '#rrggbb'
"""
return '#%0.6x' % (color_number) |
def mergeTwoDicts(x, y):
"""
Given two dicts, merge them into a new dict as a shallow copy
Assumes different keys in both dictionaries
Parameters
----------
x : dictionary
y : dictionary
Returns
-------
mergedDict : dictionary
"""
mergedDict = x.copy... |
def select_case(*args):
""":yaql:selectCase
Returns a zero-based index of the first predicate evaluated to true. If
there is no such predicate, returns the count of arguments. All the
predicates after the first one which was evaluated to true remain
unevaluated.
:signature: selectCase([args])
... |
def flatten_results(results):
"""Results structures from nested Gibbs samplers sometimes
need flattening for writing out purposes.
"""
lst = []
def recurse(r):
for i in iter(r):
if isinstance(i, list):
for j in flatten_results(i):
yield j
... |
def levenshtein(a,b):
"""Computes the Levenshtein distance between a and b."""
n, m = len(a), len(b)
if n > m:
# Make sure n <= m, to use O(min(n,m)) space
a,b = b,a
n,m = m,n
current = range(n+1)
for i in range(1,m+1):
previous, current = current, [i]+[0]*n
... |
def set_prior_6(para):
"""
set prior before the first data came in
doc details to be added
"""
n_shape = para['n_shape']
log_prob = [ [] for i_shape in range(n_shape) ]
delta_mean = [ [] for i_shape in range(n_shape) ]
delta_var = [ [] for i_shape in range(n_shape) ]
time_since_last... |
def getRanges(scol) :
"""Get sequence of ranges equal elements in a sorted array."""
ranges = []
low = 0
val = scol[low]
for i in range(0,len(scol)) :
if scol[i] != val :
ranges.append((low,i))
low = i
val = scol[i]
ranges.append((low,len... |
def convert_size(size_bytes, to, bsize=1024):
"""A function to convert bytes to a human friendly string.
"""
a = {"KB": 1, "MB": 2, "GB": 3, "TB": 4, "PB": 5, "EB": 6}
r = float(size_bytes)
for _ in range(a[to]):
r = r / bsize
return r |
def intStr(i, total=3):
""" Return a sting of the integer i begin with 0. """
return '0'*(total-len(str(i)))+str(i) |
def _build_where_clause(request):
"""builds the search mode query depending on if search is fuzzy or exact"""
variables = []
conditions = []
def _add_clause(column, value):
if request["search-mode"] == 'fuzzy':
conditions.append(f'{column} ILIKE %s')
variables.append(f'%{... |
def _bisect( a, x ):
"""
Modified 'bisect_right' from Python standard library.
"""
hi = len( a )
lo = 0
while lo < hi:
mid = ( lo + hi ) // 2
if x < a[ mid ][ 0 ]:
hi = mid
else:
lo = mid + 1
return lo |
def munge_field(arg):
"""
Take a naming field and remove extra white spaces.
"""
if arg:
res = re.sub(r'\s+', r' ', arg).strip()
else:
res = ''
return res |
def numDifference(y):
"""Takes First Difference Between Adjacent Points"""
diff = []
for i, yi in enumerate(y[:-1]):
d = y[i+1] - yi
diff.append(d)
diff.append(0)
return diff |
def get_cooling_duty(heat_utilities, filter_savings=True):
"""Return the total cooling duty of all heat utilities in GJ/hr."""
return - sum([i.duty for i in heat_utilities if i.flow * i.duty < 0]) / 1e6 |
def most_frequent(word):
"""Write a function called most_frequent that takes a string and prints the letters
in decreasing order of frequency"""
d = dict()
for letter in word:
d[letter] = d.setdefault(letter, 0) + 1
a = []
for letter, freq in d.items():
a.append((freq, letter))
... |
def getOverlap(a,b):
"""takes two arrays and return if they are overlapped
This is a numerical computation. [1,2.2222] is overlaped with
[2.2222,2.334]"""
return max(0,min(a[1],b[1]) - max(a[0],b[0])) |
def _has_valid_syntax(row):
"""
Check whether a given row in the CSV file has the required syntax, i.e.
- lemma is an existing string object
- example sentence is a string and contains at least one pair of lemma markers in the right order
- score is one of the following strings: '0', '1', '2', '3', ... |
def keyword_filter(url, keywords=None):
"""return true if url contains all keywords,
return false otherwise
"""
if not keywords: return True
return all(keyword in url for keyword in keywords) |
def get_sources_filters(provider, application):
"""
Return names to use to filer sources
Args:
provider (str): provider name.
application (str): Application type.
Returns:
list of str: sources names
"""
provider = provider or ''
return [key for key in
('... |
def make_target(objtype, targetid):
"""Create a target to an object of type objtype and id targetid"""
return "coq:{}.{}".format(objtype, targetid) |
def _make_contact_point(dataset):
"""De estar presentes las claves necesarias, genera el diccionario
"contactPoint" de un dataset."""
keys = [
k for k in ["contactPoint_fn", "contactPoint_hasEmail"] if k in dataset
]
if keys:
dataset["contactPoint"] = {
key.replace("conta... |
def _linear_matrix_index(ell, mp, m):
"""Index of array corresponding to matrix element
This gives the index based at the first element of the matrix, so
if the array is actually a series of matrices (linearized), then
that initial index for this matrix must be added.
This assumes that the input a... |
def pack_namedtuple_base_class(name: str, index: int) -> str:
"""Generate a name for a namedtuple proxy base class."""
return "namedtuple_%s_%d" % (name, index) |
def first_missing_positive(nums):
"""
Find the first missing positive integer in a list of integers.
This algorithm sorts the array by making swaps
and ignoring elements that are greater than the length
of the array or negative.
If the element is equal to the current index (start) then
it... |
def is_iterable(variable):
"""
Returns True if variable is a list, tuple or any other iterable object
"""
return hasattr(variable, '__iter__') |
def get_obj_from_list(identifer, obj_list, condition=lambda o: True):
"""
Return a dict the name of the object as its Key
e.g. {
"fn_mock_function_1": {...},
"fn_mock_function_2": {...}
}
:param identifer: The attribute of the object we use to identify it e.g. "programmatic_name"
... |
def get_overall_pixel_position(c):
""" returns the pixel position in terms of its location in the
new coordinate system, e.g., Top left == 'TL' """
if (c[1] >= 0.5):
if (c[0] >= 0.5): return "TR"
elif (c[0] <= -0.5): return "TL"
else: return "T"
elif (c[1] <= -0.5):
if (c[0] >= 0.5): return "BR"
elif ... |
def id_for_label(value):
"""generate a test id for labels"""
return f"labels->{value}" |
def _makeFunctionStatement(function_name, inputs):
"""
:param function_name: string name of the function to be created
:param inputs: list of column names that are input to the function
:return: statements
"""
statement = "def %s(" % function_name
statement += ", ".join(inputs)
statement += "):"
retur... |
def TransformMap(r):
"""Applies the next transform in the sequence to each resource list item.
Example:
list_field.map().foo().bar() applies foo() to each item in list_field and
then bar() to the resulting value. list_field.map().foo().map().bar()
applies foo() to each item in list_field and then bar()... |
def prepare_fractions_from_common_results_struct(results):
"""Prepare list of fraction values for passed/failed tests."""
correct = float(results["passed%"])
incorrect = float(results["failed%"])
return [correct, incorrect] |
def hosts_contain_id(hosts_data, host_id):
"""
True if host_id is id of a host.
:param hosts_data: list of hosts
:param host_id: id of a host
:return: True or False
"""
for host in hosts_data:
if host_id == host['id']:
return True
return False |
def printable_encode(bytez, replace='.'):
"""
Encodes bytes given into ascii characters
while non-printable characters are replaced
with <p>replace</p>
"""
chars = bytez.decode('ascii', 'replace').replace('\ufffD', replace)
return ''.join([c if c.isprintable() else '.' for c in chars]) |
def ucfirst(s):
"""Return a copy of string s with its first letter converted to upper case.
>>> ucfirst("this is a test")
'This is a test'
>>> ucfirst("come on, Eileen")
'Come on, Eileen'
"""
return s[0].upper()+s[1:] |
def isValidName(name):
"""
Determine if the given string is a valid name. i.e. does it conflict with
any of the other entities which may be on the filesystem?
@param name: a name which might be given to a calendar.
"""
return not name.startswith(".") |
def delta_f(kA, kB, NA, NB):
"""
Difference of frequencies
"""
return kA / NA - kB / NB |
def parse(entrypoint):
"""
Parse an entrypoint string
Args:
entrypoint (str): The entrypoint string to parse.
Returns:
name (str): The name of the entrypoint
package (str): The package path to access the entrypoint function
func (str): The name of the function
"""
... |
def get_dist_prob_suc(t1, t2, w1, w2, decay_factor):
"""
Get p_dist
"""
return 0.5 + 0.5 * w1 * w2 * decay_factor |
def first_line(s: str) -> str:
"""Returns the first line of a multi-line string"""
return s.splitlines()[0] |
def pred_thinness(depth, cuts=[0.1,0.2,0.4]):
"""
Rates object thinness/thickness based on measured depth
"""
if depth <= cuts[0]: return 'flat'
elif depth > cuts[0] and depth <= cuts[1]: return 'thin'
elif depth > cuts[1] and depth <= cuts[2]: return 'thick'
else: return 'bulky' |
def get_position_of_target(tag_sequence: str, start: int, end: int):
"""get index of the word that match some regex"""
# number of words befor matching string
prefix = len(list(tag_sequence[:start].split()))
# number of words in matching string
length = len(list(tag_sequence[start:end].split()))
... |
def analysis_vrn_usages(analysis):
"""
Returns a dictionary of Var usages by row.
This index can be used to quicky find a Var usage by row.
'vrn' stands for 'var row name'.
"""
return analysis.get("vrn_usages", {}) |
def truncate(text, length=30, indicator='...', whole_word=False):
"""Truncate ``text`` with replacement characters.
``length``
The maximum length of ``text`` before replacement
``indicator``
If ``text`` exceeds the ``length``, this string will replace
the end of the string
`... |
def format_cursor(cursor):
"""Format cursor inside double quotations as required by API"""
return '"{}"'.format(cursor) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.