content stringlengths 42 6.51k |
|---|
def update_label_lst(label_lst):
"""
Desc:
label_lst is a list of entity category such as: ["NS", "NT", "NM"]
after update, ["B-NS", "E-NS", "S-NS"]
"""
update_label_lst = []
for label_item in label_lst:
if label_item != "O":
update_label_lst.append("B-{}".format... |
def fix_dn(dn):
"""Fix a string DN to use ${CONFIGDN}"""
if dn.find("<Configuration NC Distinguished Name>") != -1:
dn = dn.replace("\n ", "")
return dn.replace("<Configuration NC Distinguished Name>", "${CONFIGDN}")
else:
return dn |
def progress_bar_class(p):
"""Decide which class to use for progress bar."""
p = int(p)
if p < 25:
return "progress-bar-danger"
elif p > 90:
return "progress-bar-success"
else:
return "progress-bar-warning" |
def is_palindrome_without_typecast(number):
# This condition is defined by the problem statement
"""
# When num < 0, num is not a palindrome
# Also if last digit is zero and number is not zero, it's not - since num can only be zero
"""
if number < 0 or (number % 10 == 0 and number != 0):
... |
def failed(message: str) -> str:
"""Simply attaches a failed marker to a message
:param message: The message
:return: String
"""
return "Failed: " + message |
def format_text(txt, size):
""" Format a given text in multiple lines.
Args:
txt: Text to format
size: Line size
Returns:
List of lines.
"""
res = []
sepchars = ' \t\n\r'
txt = txt.strip(sepchars)
while len(txt) > size:
# Search end of line
enx = ... |
def _same_dimension(x, y):
"""Determines if two `tf.Dimension`s are the same.
Args:
x: a `tf.Dimension` object.
y: a `tf.Dimension` object.
Returns:
True iff `x` and `y` are either both _unknown_ (i.e. `None`), or both have
the same value.
"""
if x is None:
return y is None
else:
r... |
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 document_requests_notifications_filter(record, action, **kwargs):
"""Filter notifications.
Returns if the notification should be sent for given action
"""
if action == "request_declined":
decline_reason = record.get("decline_reason", "")
action = "{}_{}".format(action, decline_reaso... |
def _next_power_of_two(x):
"""Calculates the smallest enclosing power of two for an input.
Args:
x: Positive float or integer number.
Returns:
Next largest power of two integer.
"""
return 1 if x == 0 else 2**(int(x) - 1).bit_length() |
def _xenumerate(iterable, reverse=False):
"""Return pairs (x,i) for x in iterable, where i is
the index of x in the iterable.
It's like enumerate(iterable), but each element is
(value, index) and not (index, value). This is
useful for sorting.
"""
if reverse:
indices = range(len(iter... |
def abs(var):
"""
Wrapper function for __abs__
"""
return var.__abs__() |
def range(array):
"""
Return the range between min and max values.
"""
if len(array) < 1:
return 0
return max(array) - min(array) |
def expandJSON(jsondata):
"""
In CMS lumi jsons LS a run can be (and are usually) compress by writing a range of valid
lumis [firstLumiinRange, lastLumiinRange] (inclusive of lastLumiinRange)
This function uncompresses that for easier internal handling.
Args:
jsondata (dict) : CMS json ... |
def dict_merge(dict1, dict2):
"""Merge two dicts.
"""
if not isinstance(dict1, dict) or not isinstance(dict2, dict):
return dict2
for k in dict2:
if k in dict1:
dict1[k] = dict_merge(dict1[k], dict2[k])
else:
dict1[k] = dict2[k]
return dict1 |
def add_lists(list1, list2):
"""
Add corresponding values of two lists together. The lists should have the same number of elements.
Parameters
----------
list1: list
the first list to add
list2: list
the second list to add
Return
----------
output: list
... |
def regional_indicator(c: str) -> str:
"""Returns a regional indicator emoji given a character."""
return chr(0x1f1e6 - ord('A') + ord(c.upper())) |
def switcher(switch_value, v0, v1, switch_state, verbose):
"""
It updates the switch state according inp values, either "left" of the switch value or "right",
respectively swith_state = 0 and switch_state = 1.
"""
if abs(v0) < switch_value < abs(v1):
switch_state = (switch_state + 1) % 2
... |
def get_abc(V, E, dE, ddE):
"""
Given the volume, energy, energy first derivative and energy
second derivative, return the a,b,c coefficients of
a parabola E = a*V^2 + b*V + c
"""
a = ddE / 2.
b = dE - ddE * V
c = E - V * dE + V ** 2 * ddE / 2.
return a, b, c |
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(fu... |
def read_converged(content):
"""Check if program terminated normally"""
error_msg = ['[ERROR] Program stopped due to fatal error',
'[WARNING] Runtime exception occurred',
'Error in Broyden matrix inversion!']
for line in reversed(content.split('\n')):
if any([... |
def no_codeblock(text: str) -> str:
"""
Removes codeblocks (grave accents), python and sql syntax highlight indicators from a text if present.
.. note:: only the start of a string is checked, the text is allowed to have grave accents in the middle
"""
if text.startswith('```'):
text = text[3... |
def parse_string(string, grep_for=None, multiple_grep=None, left_separator=None, right_separator=None, strip=False):
"""
parses string given as argument
greps lines containing grep_for string
splits the string and return the text between
left_separator and right_separator
grep_for can be a strin... |
def newline(lines=1):
"""Get linebreaks"""
return '\n' * lines |
def scale_list(c, l):
"""Scales vector l by constant c."""
return [c*li for li in l] |
def step(v, direction, step_size):
"""move step_size in the direction from v"""
return [v_i + step_size * direction_i
for v_i, direction_i in zip(v, direction)] |
def exists(file_name):
""" Checks whether a file with the given name exists. """
try:
f = open(file_name, "r")
f.close()
return True
except FileNotFoundError:
return False |
def is_feature_component_start(line):
"""Checks if a line starts with '/', ignoring whitespace."""
return line.lstrip().startswith("/") |
def bucket_by_length(words):
"""Bucket a list of words based on their lengths"""
num_buckets = list(set([len(x) for x in words]))
buckets = dict()
for x in num_buckets:
buckets[x] = list()
for word in words:
buckets[len(word)].append(word)
return buckets |
def getDimmedRGB(color, alpha=255):
"""Returns dimmed RGB values, with low and high pass to ensure LEDs are fully off or on"""
if alpha >= 253: # int is 1
return color
elif alpha <= 2: # int is 0
return 0, 0, 0
else:
p = alpha/255.0
r, g, b = color
return int(r*... |
def resolve_attribute(name, bases, default=None):
"""Find the first definition of an attribute according to MRO order."""
for base in bases:
if hasattr(base, name):
return getattr(base, name)
return default |
def factorial(numero):
"""Calcula el factorial de numero
numero int > 0
returns n!
"""
if numero == 1:
return 1
return numero * factorial(numero -1) |
def qs1 (al):
""" Algo quicksort for a list
"""
if not al:
return []
return (qs1([x for x in al if x < al[0]])
+ [x for x in al if x == al[0]]
+ qs1([x for x in al if x > al[0]])) |
def calculate_similarity(d1, d2):
"""
d1: frequency dictionary for one text
d2: frequency dictionary for another text
Returns a float representing how similar both
texts are to each other
"""
diff = 0
total = 0
# when word is in both dicts or just in d1
for word in d1.keys():
... |
def remove_duplicates(a, b,c):
"""
This function removes duplicate values from a list. The lists are passed as positional arguments. It returns a dictionary of unduplicated lists
"""
i = 0
while i < len(a):
j = i + 1
while j < len(a):
if a[i] == a[j]:
del ... |
def rivers_with_station(stations):
"""The function rivers_with_station returns a set of rivers which have an associated station."""
# creates an array of rivers
rivers = []
# appends river into river list for each station
for station in stations:
rivers.append(station.river)
# turn... |
def retab(text, newtab=' ', oldtab='\t'):
""" Replaces all occurrences of oldtab with newtab """
return text.replace(oldtab, newtab) |
def At_SO(at, charge):
"""
Returns atomic energy correction due to spin orbit coupling
Input:
at (str): Atomic symbol
charge (int): Atomic charge
Returns:
At_SO (float): Energy correction due to spin orbit coupling
"""
... |
def paragraphReplacements(tex):
"""
Replace the Latex command "\CONST{<argument>}" with just
argument.
"""
while (tex.find("\\paragraph") != -1):
index = tex.find("\\paragraph")
startBrace = tex.find("{", index)
endBrace = tex.find("}", startBrace)
tex = tex[:index... |
def convert_number(number):
"""
Convert number to , split
Ex: 123456 -> 123,456
:param number:
:return:
"""
if number is None or number == 0:
return 0
number = int(number)
return '{:20,}'.format(number) |
def next_question_id(next_ids, id_base):
"""
Incrementally fetches the next question ID based on the base passage ID.
Some questions have the same ID in the RACE dataset (if they are
in the same file). We try to make those unique by appending an
index before the id. @q_ids is used to keep the count... |
def split_path(path):
"""
Normalise GCSFS path string into bucket and key.
"""
if path.startswith('gs://'):
path = path[5:]
path = path.rstrip('/').lstrip('/')
if '/' not in path:
return path, ""
else:
return path.split('/', 1) |
def get1dgridsize(sz, tpb = 1024):
"""Return CUDA grid size for 1d arrays.
:param sz: input array size
:param tpb: (optional) threads per block
"""
return (sz + (tpb - 1)) // tpb, tpb |
def list_product(num_list):
"""Multiplies all of the numbers in a list
"""
product = 1
for x in num_list:
product *= x
return product |
def is_critical_error(alarm_name):
"""Is this a critical error (True) or just a warning (False)?"""
# Alarms for the API or Loris are always critical.
if any(p in alarm_name for p in ["catalogue-api", "loris", "storage-api"]):
return True
# Any alarms to do with healthy/unhealthy hosts are crit... |
def get_corrected_email(email, env_type):
"""
If you are transfering users from qa to qa, you have to add +migration to make the users unique.
(cheating a bit)
"""
if (env_type):
return email
# I should add functionality to handle an initial email with a +qa part
split_array = emai... |
def convert_to_list(element):
"""
This funciton...
:param element:
:return:
"""
if element is None:
return ""
return [element] |
def get_inactive_users(groups):
"""
Take group list and return groups only with inactive users
:param groups:
:return:
"""
inactive_users_list = []
for group in groups:
inactive_users = {
"group_name": group["group_name"],
"users": [
{"name": u... |
def printdict(d: dict) -> str:
"""print a dict in a json-like format"""
outstr = ""
for item in d.keys():
outstr += "\t" + item + ": " + str(d[item]) + "\n"
return outstr.rstrip("\n") |
def deep_get(deep_key, dictionary, sep=':'):
"""Fetches through multiple dictionary levels, splitting
the compound key using the specified separator.
"""
keys = deep_key.split(sep)
while keys:
dictionary = dictionary[keys.pop(0)]
return dictionary |
def is_hex(value):
"""
Returns True if value is a hexadecimal string, otherwise returns False
"""
try:
int(value, 16)
return True
except (TypeError, ValueError):
return False |
def is_in_adr_lexicon(text, adr_lexicon_dict):
"""checks if given text is present in ADR Lexicon dict
# Arguments
text - text to check
adr_lexicon_dict - dict with ADR Lexicon entries
# Returns
True if present, False otherwise
"""
for item in adr_lexicon_dict:
if it... |
def inverse_linear(variable, gradient, intercept, factor=1.0):
"""
Solution to linear function
Parameters
----------
integ: float
integral value
B, C: float
(Gradient, intercept) Calibration parameters
dil: float
Dilution factor.
IS: float
Internal standa... |
def get_invalid_reposlug(reposlugs):
"""
Checks invalid reposlug
"""
for x in reposlugs:
if len(x.split('/', 1)) != 2 or '' in x.split('/'):
return x
return None |
def count_doubles(val):
"""Count repeated pair of chars ins a string"""
total = 0
for c1, c2 in zip(val, val[1:]):
if c1 == c2:
total += 1
return total |
def ostr(string):
"""
Truncates to two decimal places. """
return '{:1.2e}'.format(string) |
def number(n):
""" Receive a number and print it only if is an integer """
return '%d is a number' % n |
def wrap_text_to_lines(string, max_chars):
"""wrap_text_to_lines function
A helper that will return a list of lines with word-break wrapping
:param str string: The text to be wrapped
:param int max_chars: The maximum number of characters on a line before wrapping
:return list the_lines: A l... |
def list_depth_count(input_list):
"""
This function count the maximum depth of a nested list (recursively)
This is used to check compatibility of users' input and system API
only to be used for list or tuple
"""
if not isinstance(input_list, (list, tuple)):
return 0
if len(input_list... |
def as_list(val):
"""
Helper function, always returns a list of the input value.
:param val: the input value.
:returns: the input value as a list.
:Example:
>>> as_list('test')
['test']
>>> as_list(['test1', 'test2'])
['test1', 'test2']
"""
treat_single_value = str
i... |
def remove_dice_from_roll(roll, dice_to_remove):
"""
This function remove the dice we got in a round if we got an existing combination.
"""
values = list(roll.values())
for eyes in dice_to_remove:
if eyes in values:
values.remove(eyes)
else:
raise ValueError("... |
def maybe(x, f):
"""Returns [f(x)], unless f(x) raises an exception. In that case, []."""
try:
result = f(x)
output = [result]
# pylint:disable=broad-except
except Exception:
# pylint:enable=broad-except
output = []
return output |
def get_last_pair(words):
"""
returns a tuple of the last two words in the list
"""
return tuple(words[-2:]) |
def combineImagePaths(centerImagePath, leftImagePath, rightImagePath, centerMeasurement, leftMeasurement, rightMeasurement):
"""
combines cnter/left/right images and measurements to one list
"""
# combine measurements
measurements = []
measurements.extend(centerMeasurement)
measurements.exte... |
def translate_param(val):
""" To use in get_params """
if val in ['taxonomy_terms']:
return '{0}[]'.format(val)
else:
return val |
def _read_quoted_string(s, start):
"""
start: offset to the first quote of the string to be read
A sort of loose super-set of the various quoted string specifications.
RFC6265 disallows backslashes or double quotes within quoted strings.
Prior RFCs use backslashes to escape. This l... |
def unique(seq):
"""Returns unique values in a sequence while preserving order"""
seen = set()
# Why assign seen.add to seen_add instead of just calling seen.add?
# Python is a dynamic language, and resolving seen.add each iteration is more costly
# than resolving a local variable.
seen_add = se... |
def fix_coord(screen_size, coord):
"""Fix coordinates for use in OpenCV's drawing functions
PIL images have upside-down co-ordinates and it shafts me
every goddamn time, so this function "deals with it"
Args:
screen_size (tuple): The screen size (width, height)
coord (tuple): The x, y ... |
def isa_temperature(flightlevel):
"""
International standard atmosphere temperature at the given flight level.
Reference:
For example, H. Kraus, Die Atmosphaere der Erde, Springer, 2001,
470pp., Sections II.1.4. and II.6.1.2.
Arguments:
flightlevel -- flight level in hft
Re... |
def mass(item):
"""Calculate the fuel required for an item, and the fuel required for that fuel, and so on"""
fuel = item // 3 - 2
if fuel < 0:
return 0
return fuel + mass(fuel) |
def error_j(Dj,Pap,Pdc,PolError,exp_loss_jt):
"""
Calculates the conditional probability for a pulse of intensity mu_j
to cause an error, after sifting, in the time slot t.
Defined as e_k in Sec. IV of [1].
Parameters
----------
Dj : float, array
Expected detection rate.
Pap : f... |
def get_prf(tp, fp, fn, get_str=False):
"""Get precision, recall, f1 from true pos, false pos, false neg."""
if tp + fp == 0:
precision = 0
else:
precision = float(tp) / (tp + fp)
if tp + fn == 0:
recall = 0
else:
recall = float(tp) / (tp + fn)
if precision + recall == 0:
f1 =... |
def process_state(term, valid_transitions):
"""Process a state and return next state."""
try:
return valid_transitions[term]
except KeyError as error:
raise KeyError(f"Indefinition , Invalid Transition: {error}.") |
def human_delta(duration):
"""Converts seconds into a human-readable delta"""
delta = []
if duration // (60**2 * 24 * 365) > 0:
delta.append(f"{duration // (60**2 * 24 * 365)} years")
duration %= 60**2 * 24 * 365
if duration // (60**2 * 24 * 30) > 0:
delta.append(f"{duration // (... |
def get_define(name, defines):
"""Return define value from defines list"""
try:
return next(d for d in defines if name in d).split('=')[-1]
except StopIteration:
return None |
def get_number(tokens, exclude_comment=True):
"""Given a list of tokens, gives a count of the number of
tokens which are not space tokens (such as ``NEWLINE``, ``INDENT``,
``DEDENT``, etc.)
By default, ``COMMMENT`` tokens are not included in the count.
If you wish to include them, set ``exclude_com... |
def compute_rotation_frequency(delta_exponent_b, f_rotation_b, delta_exponent_c, f_rotation_c):
"""Calculate the rotation frequency between two rotated power spectra.
Parameters
----------
delta_exponent_b : float
The applied change in exponent value for power spectrum 'B'.
f_rotation_b : f... |
def isPerfect(x):
"""Returns whether or not the given number x is perfect.
A number is said to be perfect if it is equal to the sum of all its
factors (for obvious reasons the list of factors being considered does
not include the number itself).
Example: 6 = 3 + 2 + 1, hence 6 is perfect.
Exam... |
def merge(config, defaults={}):
"""
Merge @config and @defaults
In the case of a conflict, the key from config will
overide the one in config.
"""
return dict(defaults, **config) |
def safe_split(text, split_chars=' ',
start_protected_chars='[', end_protected_chars=']'):
"""Safely split text even in split_chars are inside protected regions.
Protected regions starts with any character from the start_protected_chars
argument and ends with any character from the end_prote... |
def termTypeIdentifier(element, dataType):
"""
Identifies the termtype of the object 'element' based on itself and its datatype 'dataType' and returns it
"""
if(len(str(element).split(":")) == 2 or "http" in str(element) or dataType == "anyURI"):
return 'IRI', '~iri'
else:
return 'Li... |
def count_calls(callers):
"""Sum the caller statistics to get total number of calls received."""
nc = 0
for calls in callers.values():
nc += calls
return nc |
def strip_angle_brackets_from_url(url):
"""Normalize URL by stripping angle brackets."""
return url.lstrip("<").rstrip(">") |
def _make_value_divisible(value, factor, min_value=None):
"""
It ensures that all layers have a channel number that is divisible by 8
:param v: value to process
:param factor: divisor
:param min_value: new value always greater than the min_value
:return: new value
"""
if min_valu... |
def s(a,b):
"""
Similarity matrix
"""
if a == b:
return 2
elif a != b:
return -1 |
def python_include(filename: str):
"""Syntax conversion for python imports.
:param filename: filename to import
"""
return f'from {filename} import *' |
def convert_big_str_numbers(big_num):
"""Convert big number written with numbers and words to int.
Args:
big_num (str): number, written with numbers and words.
Returns:
int: same number as an int.
Examples:
>>>print(convert_big_str_numbers('101.11 billions'))
101110000... |
def rle_kenny(seq: str) -> str:
""" Run-length encoding """
compressed = ''
last_base = ''
rep = 1
for base in seq:
if base != last_base:
if rep > 1:
compressed += str(rep)
compressed += base
rep = 1
else:
rep += 1
... |
def parseNeighbors_rank(urls):
#Hve to fix this splitting and converting to string
"""Parses a urls pair string into urls pair."""
parts = urls.split(',')
res=float(float(parts[2])/float(parts[3]))
return parts[1], res |
def _build_link_header(links):
"""
Builds a Link header according to RFC 5988.
The format is a dict where the keys are the URI with the value being
a dict of link parameters:
{
'/page=3': {
'rel': 'next',
},
'/page=1': {
'rel': ... |
def uptime(total_seconds):
"""
Gives a human-readable uptime string
Thanks to http://thesmithfam.org/blog/2005/11/19/python-uptime-script/
(modified to look like the real uptime command)
"""
total_seconds = float(total_seconds)
# Helper vars:
MINUTE = 60
HOUR = MINUTE * 60
DAY =... |
def get_status_code_value(status_code):
"""function to return appropriate status code value from the dictionary"""
status_code_dict = {
"100": "Continue", "101": "Switching Protocols", "200": "OK", "201": "Created",
"202": "Accepted", "203": "Non-authoritative Information", "204": "No Conten... |
def ap(fs, xs):
"""ap applies a list of functions to a list of values.
Dispatches to the ap method of the second argument, if present. Also
treats curried functions as applicatives"""
acc = []
for f in fs:
for x in xs:
acc.append(f(x))
return acc |
def _get_sig_data(word: dict):
"""HELPER: extracts if the sig is in word dictionary
:param word: dictionary from the json word
:type word: dict
:return: if sig, ':' and '$' in the word dictionary, it returns it. otherwise it returns False.
:rtype: list
"""
if "sig" in word:
if ":" i... |
def str_to_int(s):
"""
Convert a fanfiction number string to an integer.
@param s: string to parse/convert
@type s: L{str}
@return: the number
@rtype: L{int}
"""
s = s.strip().lower()
s = s.replace("(", "")
s = s.replace(")", "")
if s.count(".") > 1:
# perio... |
def min_int(la,lb,ia,ib,tol=0.01):
"""
Given two complete drillholes A, B (no gaps and up to the end of
the drillhole), this function returns the smaller of two
intervals la = FromA[ia] lb = FromB[ib] and updates the
indices ia and ib. There are three possible outcomes
- FromA[ia] == FromB[ib]+... |
def _compute_size(start, stop, step):
"""Algorithm adapted from cpython rangeobject.c
"""
if step > 0:
lo = start
hi = stop
else:
lo = stop
hi = start
step = -step
if lo >= hi:
return 0
return (hi - lo - 1) // step + 1 |
def recorded_views(label):
"""
Get the dimensions of the view from recorded ones.
Parameters
----------
label: string
Dictionary key for the view.
Returns
-------
view: 4-tuple of floats
The view ('xmin', 'xmax', 'ymin', 'ymax').
"""
views = {}
views['snake'] = (-1.0, 2.0, -1.5, 1.5)
v... |
def roundToMultiple(x, y):
"""Return the largest multiple of y < x
Args:
x (int): the number to round
y (int): the multiplier
Returns:
int: largest multiple of y <= x
"""
r = (x+int(y/2)) & ~(y-1)
if r > x:
r = ... |
def construct_address(host, port, route, args):
"""
{host}:{port}{route}?{'&'.join(args)}
:param str host: '172.0.0.1'
:param str port: '5000'
:param str route: '/store/file/here'
:param list[str] args: ['a=b', 'c=d']
"""
return f"http://{host}:{port}{route}?{'&'.joi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.