content stringlengths 42 6.51k |
|---|
def forward_box(box):
"""Increase box level (max 4)
Parameters
----------
box: int
question box level
Returns
-------
int: updated box
"""
if box < 4:
box += 1
return box |
def escape(x):
"""
Shell escape the given string
Implementation borrowed from now-deprecated commands.mkarg() in the stdlib
"""
if '\'' not in x:
return '\'' + x + '\''
s = '"'
for c in x:
if c in '\\$"`':
s = s + '\\'
s = s + c
s = s + '"'
return... |
def _encode_features(features: dict) -> str:
"""Encodes features from a dictionary/JSON to CONLLU format."""
return '|'.join(map(lambda kv: f'{kv[0]}={kv[1]}', features.items())) |
def gen_jump_url(message_id, channel_id, guild_id=None):
"""Generates a jump URL for a particular message in a particular channel in an optional guild."""
BASE = "https://discord.com/channels/"
if guild_id:
return BASE + f"{guild_id}/{channel_id}/{message_id}"
else:
return BASE + f"{channel_id}/{message_id}" |
def length_compare(s1, s2):
"""Returns a number between 0 and 1:
How similiar len(s1) is to len(s2).
If s1 is more than 2X the length of s2 similiarity is 0.
If s1 is shorter than s2, similiarity is the ratio of len(s1) to len(s2).
If s1 is longer than s2, but less than double:
similiari... |
def first_line(text):
"""
Return only the first line of a text block.
"""
return text.split('\n')[0] |
def ortho_direction(p, base):
"""
Returns the orthogonal direction to (base - p)
pstar = p2 + step*(p2-p1)
"""
dp = (base[0] - p[0], base[1] - p[1])
direction = (-dp[1], dp[0])
return direction |
def inspect_subprocess(obj):
"""Print stdout and stdout of a process."""
msg = ''
if hasattr(obj, 'process'):
process = obj.process
msg += 'Failure of subprocess \n' + ' '.join(process.args)
msg += '\n Standard output:\n'
msg += process.stdout
msg += '\n Standard ... |
def change_dicts_dates_format(list_of_dicts):
"""Function change dates format in all dictionaries on list
Args:
list_of_dicts (list): List of dictionaries with dates to correct
Returns:
list: List of dictionaries with corrected dates format
"""
for dictionary in list_of_dicts:
... |
def l2str(list_var, spacing=8):
"""Converts a list into string, that will be
written into the text table.
Parameters
==========
list_var: list
List to be converted
spacing: int, optional
Defines the size of one cell of the table
Returns
=======
s: string
Str... |
def get_response(text):
"""Generate robot response based on user speech input. Not implemented.
Parameters:
text (string): Result from listen() function
Returns:
(string): robot response
"""
respone = ""
return respone |
def count(seq):
"""Count the number of items in sequence that are interpreted as true."""
return sum(map(bool, seq)) |
def three_way_quick_sort(array, low, high):
"""
Sort array in ascending order by quick sort
:param array: given unsorted array
:type array: list
:param low: starting index of array to sort
:type low: int
:param high: ending index of array to sort
:type high: int
:return: sorted arra... |
def unixify(path):
"""Convert a DOS style path to Unix style path.
Args:
path (str): A windows style path.
Returns:
str: A Unix style path.
"""
return path.replace('\\', '/') |
def rchop(the_string, ending):
"""If 'the_string' has the 'ending', chop it"""
if the_string.endswith(ending):
return the_string[:-len(ending)]
return the_string |
def three_sum_problem(numbers, sum_val):
"""
Returns a triplet (x1,x2, x3) in list of numbers if found, whose sum equals sum_val, or None
"""
# Sort the given list of numbers
# Time complexity: O(N.logN)
numbers.sort()
size = len(numbers)
# Two nested loops
# Time complexity: O... |
def add(a, b):
"""
"""
if isinstance(a, int) and isinstance(b, int):
return a + b
else:
raise ValueError("a/b must be exact integer") |
def A000110(n: int) -> int:
"""Bell or exponential numbers.
Number of ways to partition a set of n labeled elements.
"""
bell = [[0 for i in range(n + 1)] for j in range(n + 1)]
bell[0][0] = 1
for i in range(1, n + 1):
bell[i][0] = bell[i - 1][i - 1]
for j in range(1, i + 1):
... |
def sum_divisors(n):
""""
Return the sum of all divisors of n, not including n
"""
return sum(i for i in range(1, n) if n % i == 0) |
def remove_whitespace_from_str(string):
""" docstring tbd """
string = ' '.join(string.split())
string = ' '.join(string.split('\n'))
return string |
def play_verifier(play):
"""this function is so the player can enter more than one possible
value, and the programmer can act like they only recieve the
cleanest of data entries. Would you call this an elegant solution?
For a noob, at least."""
if play.lower()[0] == "r" or play[0] == 1:
pla... |
def PersonaOverlappingClustering(non_overlapping_clustering, persona_id_mapping, min_component_size):
"""Computes an overlapping clustering of graph using the Ego-Splitting method.
Args:
non_overlapping_clustering: persona graph clustering
persona_id_mapping: a dict of the persona node ids to the node ids ... |
def no_hidden(files):
"""Removes files that start with periods.
"""
return([x for x in files if not x.startswith('.')]) |
def humanize_path(path):
""" Replace python dotted path to directory-like one.
ex. foo.bar.baz -> foo/bar/baz
:param str path: path to humanize
:return str: humanized path
"""
return path.replace(".", "/") |
def array_to_concatenated_string(array):
"""DO NOT MODIFY THIS FUNCTION.
Turns an array of integers into a concatenated string of integers
separated by commas. (Inverse of concatenated_string_to_array).
"""
return ",".join(str(x) for x in array) |
def redshift_num2str(z: float):
"""
Converts the redshift of the snapshot from numerical to
text, in a format compatible with the file names.
E.g. float z = 2.16 ---> str z = 'z002p160'.
"""
z = round(z, 3)
integer_z, decimal_z = str(z).split('.')
integer_z = int(integer_z)
decimal_z... |
def indent(string_in: str, tabs: int = 0):
"""Returns the str intended using spaces"""
return str(" " * tabs) + string_in |
def completeLine(dic):
"""This function completes the line from analizeResponse()
It takes a dic obj as an argument;
It returns a string.
"""
line=""
#for move
if dic['action']=='move' :
if dic['direction']=='X' :
line+="towards the "
... |
def getUnigram(words):
"""
Input: a list of words, e.g., ['I', 'am', 'Denny']
Output: a list of unigram
"""
assert type(words) == list
return words |
def _clean_timeformat(text):
"""returns an ISO date format from a funny calibre date format"""
if text.endswith("+00:00"):
text = text[:-6] + "+0000"
if text[10] == " ":
text = text.replace(" ", "T", 1)
return text |
def author_from_user(usr):
"""author_from_user returns an author string from a user object."""
if usr and usr.username and usr.email:
return f"{usr.username} <{usr.email}>"
# default to generic user
return "nautobot <nautobot@ntc.com>" |
def _command_to_string(cmd):
"""Convert a list with command raw bytes to string."""
return ' '.join(cmd) |
def color_diff(contents: str) -> str:
"""Inject the ANSI color codes to the diff."""
lines = contents.split("\n")
for i, line in enumerate(lines):
if line.startswith("+++") or line.startswith("---"):
line = "\033[1;37m" + line + "\033[0m" # bold white, reset
elif line.startswith... |
def pad_subtokens(seq, pad_symb):
"""
batch is a list of lists (seq - subtokens)
"""
max_len = max([len(elem) for elem in seq])
seq = [elem+[pad_symb]*(max_len-len(elem)) for elem in seq]
return seq |
def time_to_num(time):
"""
time: a string representing a time, with hour and minute separated by a colon (:)
Returns a number
e.g. time_to_num("9:00") -> 9 * 2 = 18
time_to_num("21:00") -> 21 * 2 = 42
time_to_num("12:30") -> 12.5 * 2 = 25
"""
time_comps = time.split(":")
... |
def combine_comments(comments):
"""
Given a list of comments, or a comment submitted as a string, return a
single line of text containing all of the comments.
"""
if isinstance(comments, list):
comments = [c if isinstance(c, str) else str(c) for c in comments]
else:
if not isinst... |
def first_non_none(*args): # type: ignore[no-untyped-def] # noqa: F811 # pylint: disable=missing-return-type-doc
"""Return the first non-:data:`None` value from a list of values.
Args:
*args: variable length argument list
* If one positional argument is provided, it should be an iterabl... |
def getZC(rawEMGSignal, threshold):
""" How many times does the signal crosses the 0 (+-threshold).::
ZC = sum([sgn(x[i] X x[i+1]) intersecated |x[i] - x[i+1]| >= threshold]) for i = 1 --> N - 1
sign(x) = {
1, if x >= threshold
0, otherwise
... |
def make_shard_meta_common_prefix(table_prefix):
"""Construct the key for an individual shard's meta."""
key = "{}_meta_.".format(table_prefix)
return key |
def string_to_format(value, target_format):
"""Convert string to specified format"""
if target_format == float:
try:
ret = float(value)
except ValueError:
ret = value
elif target_format == int:
try:
ret = float(value)
ret = int(ret)
... |
def f1_from_confusion(tp , fp , fn , tn):
""" Compute the F1 score from a confusion matrix.
Parameters
----------
tp : int
Number of true positives
fp : int
Number of false positives
fn : int
Number of false negatives
tn : int
Numbe... |
def find_mid(list1):
"""integer division to find "mid" value of list or string"""
length = len(list1)
mid = length // 2
return mid |
def OP_calc(ACC, TPR, TNR):
"""
Calculate OP (Optimized precision).
:param ACC: accuracy
:type ACC : float
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: OP as float
"""
... |
def sir_dydt(t, y, beta, gamma, N):
"""
Defines the differential equations for the SIR model system.
Arguments:
t : time
y : vector of state variables:
y = [S, I, R]
beta, gamma, N : model parameters
"""
S, I, R = y
# Output array of form f = (S',... |
def halvorsen(XYZ, t, a=1.4):
"""
The Halvorsen Attractor.
x0 = (-5,0,0)
"""
x, y, z = XYZ
x_dt = -a * x - 4 * y - 4 * z - y**2
y_dt = -a * y - 4 * z - 4 * x - z**2
z_dt = -a * z - 4 * x - 4 * y - x**2
return x_dt, y_dt, z_dt |
def get_data(aTuple):
"""
aTuple, tuple of tuples (int, string)
Extracts all integers from aTuple and sets
them as elements in a new tuple.
Extracts all unique strings from from aTuple
and sets them as elements in a new tuple.
Returns a tuple of the minimum integer, the
maximum intege... |
def _encode_string(s: str) -> bytes:
"""
Encode a python string into a bencoded string.
"""
return f"{len(s)}:{s}".encode("utf-8") |
def euler_totient(n) :
"""
Returns the value for euler totient function for positive integer n
Parameters
----------
n : int
denotes positive integer n for which euler totient function value is needed
return : int
return euler totient value
"""
if(n<1 or n!=int(n)):
... |
def reversal_algorithm (ar, k):
"""
ar is array of ints
k is and positve int value
"""
n = len(ar)
k = k % n
temp = []
final = []
temp = ar + ar
return temp[n-k:n+k]
"""
for i in range(0, n):
if i < n-k:
temp.append(ar[i])
else:
final.append(ar[i])
for i in range(0, len(temp)):
final.append(te... |
def transform_dict_to_kv_list(options):
"""
{"key": None, "key2": None} becomes 'key, key2'
{"key": "\"\"", "key2": "3.5in", tocbibind: None} becomes 'key="", key2=3.5in, tocbibind'
"""
assert isinstance(options, dict)
return ", ".join(["{}={}".format(k,v) if v is not None else k for k,v in opti... |
def yes_no(value):
"""For a yes or no question, returns a boolean.
"""
if value.lower() in ('yes','y'):
return True
if value.lower() in ('no','n'):
return False
raise ValueError("value should be 'yes' or 'no'") |
def intClamp(v, low, high):
"""Clamps a value to the integer range [low, high] (inclusive).
Args:
v: Number to be clamped.
low: Lower bound.
high: Upper bound.
Returns:
An integer closest to v in the range [low, high].
"""
return max(int(low), min(int(v), int(high))) |
def special_mode(v):
"""decode Olympus SpecialMode tag in MakerNote"""
mode1 = {
0: 'Normal',
1: 'Unknown',
2: 'Fast',
3: 'Panorama',
}
mode2 = {
0: 'Non-panoramic',
1: 'Left to right',
2: 'Right to left',
3: 'Bottom to top',
4: 'To... |
def _strip_oid_from_list(oids, strip):
"""Iterates through list of oids and strips snmp tree off index.
Returns sorted list of indexes.
Keyword Arguments:
self --
oid -- Regular numeric oid index
strip -- Value to be stripped off index
"""
sorted_oids = []
for index in oids:
... |
def parse_property(name,value):
"""
Parses properties in the format 'name(;|\n)key=value(;|\n)key=value'
Used by HDB++ config and archivers
"""
if '\n' in value:
value = value.split('\n')
elif ';' in value:
value = value.split(';')
else:
value = [value]
r = {'nam... |
def check_request(request):
"""
Validates that our request is well formatted
Returns:
- assertion value: True if request is ok, False otherwise
- error message: empty if request is ok, False otherwise
"""
if "id" not in request:
error = "Field `id` missi... |
def lcs_dp(strA, strB):
"""Determine the length of the Longest Common Subsequence of 2 strings."""
rows = len(strA) + 1
cols = len(strB) + 1
dp_table = [[0 for j in range(cols)] for i in range(rows)]
for row in range(rows):
for col in range(cols):
if row == 0 or col == 0:
... |
def get_pressed_button(mx, my, buttons):
"""Checking if the mouse is pressing a button"""
for button in buttons:
if button.x <= mx <= button.x + button.length and button.y <= my <= button.y + button.height:
return button
return None |
def merge_headers(event):
"""
Merge the values of headers and multiValueHeaders into a single dict.
Opens up support for multivalue headers via API Gateway and ALB.
See: https://github.com/Miserlou/Zappa/pull/1756
"""
headers = event.get('headers') or {}
multi_headers = (event.get('multiValu... |
def get_KPP_PL_tag(last_tag, tag_prefix='T'):
""" Get the next P/L tag in a format T??? """
assert (len(last_tag) == 4), "Tag must be 4 characers long! (e.g. T???)"
last_tag_num = int(last_tag[1:])
return '{}{:0>3}'.format(tag_prefix, last_tag_num+1) |
def get_rst_header(text, level=1):
"""
Return a header in the RST format
"""
linestyles = {1: "=", 2: "-", 3: "~"}
linestyle = linestyles.get(level, '-')
header = str(text) + '\n'
header += linestyle*len(text) + '\n\n'
return header |
def divide(a, b):
"""
Divide two numbers
Parameters:
a (float): counter
b (float): denominator
Returns:
float: division of a and b
"""
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b |
def neighbors(row, col, matrix):
"""returns all neighbors of the cell as a list"""
n = len(matrix)
m = len(matrix[0])
return [matrix[r][c] for r in range(max(row - 1, 0), min(n, row + 2)) for c in range(max(col - 1, 0), min(m, col + 2)) if r != row or c != col] |
def get_split_parts(num, num_part):
"""get split parts"""
same_part = num // num_part
remain_num = num % num_part
if remain_num == 0:
return [same_part] * num_part
return [same_part] * num_part + [remain_num] |
def get_filterquerylanguage(options):
"""
Get the filterquery language based on what is in the filterquery option
and the filterquerylanguage options.
If filterquery exists but filterquerylanguage does not, use DMTF as
the filter query language.
if filterquery does not exist but filterquerylangu... |
def bold_blue(text: str) -> str:
"""
Format the given text with a bold blue style.
"""
return '<b style="color:blue">' + text + '</b>' |
def trianglePoints(x, z, h, w):
"""
Takes the geometric parameters of the triangle and returns the position of the 3 points of the triagles. Format : [[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]]
"""
P1 = [x,0,z+h]
P2 = [x,-w/2,z]
P3 = [x,w/2,z]
return [P1,P2,P3] |
def isValidID(id: str) -> bool:
""" Check for valid ID. """
#return len(id) > 0 and '/' not in id # pi might be ""
return '/' not in id |
def jaccards_index(set1, set2):
"""
Calculates Jaccard's index between two sets, used to compute overlap
between a word context and a definition's signature.
@param set1 - First set
@param set2 - Second set
@return Jaccard's index
"""
set1 = set(set1)
set2 = set(set2)
return float(len(set1 & set2)) / len(se... |
def centerel(elsize, contsize):
"""Centers an element of the given size in the container of the given size.
Returns the coordinates of the top-left corner of the element relative to
the container."""
w, h = elsize
W, H = contsize
x = (W-w)//2
y = (H-h)//2
return (x, y) |
def ConstructOrderedSet(A):
"""Sorts coefficient list into descending order.
Inputs:
A: A list, containing the coefficients to sort.
Returns:
An index set for the ordered coefficients.
A list containing the ordered coefficients.
A list containing a mapping from the sorted c... |
def _keep_extensions(files, extension):
""" Filters by file extension, this can be more than the extension!
E.g. .png is the extension, gray.png is a possible extension"""
if isinstance(extension, str):
extension = [extension]
def one_equal_extension(some_string, extension_list):
return... |
def convert_number_to_letters(input : int) -> str:
""" Convert numbers to letters, e.g. 1 to 'a' or 137 to 'eg' """
def number_to_letter(number: int) -> str:
if number == 0: return ''
return chr(ord('`')+number)
quotient, remainder = divmod(input,26)
output = f'{number_to_letter(quotie... |
def fwhm(lambda_, d, alpha1=1.3):
"""
The nominal Full Width Half Maximum (FWHM) of a LOFAR Station beam.
:param lambda_: wavelength in meters
:param d: station diameter.
:param alpha1: depends on the tapering intrinsic to the layout of the station,
and any additional tapering which... |
def mean(nums):
"""
Our own mean function, as Python 2 doesn't include the statistics module.
"""
return float(sum(nums)) / len(nums) |
def hex2rgb(value):
"""Hex to RGB"""
value = value.lstrip('#')
length_v = len(value)
return tuple(int(value[i:i+length_v//3], 16)
for i in range(0, length_v, length_v//3)) |
def scalar_clip(x, min, max):
"""
input: scalar
"""
if x < min:
return min
if x > max:
return max
return x |
def convert_to_list_with_index(items: list) -> list:
"""
Prepare simple list to inquirer list.
Convert to dicts list, with 2 keys: index and value from original list
Args:
items (list): Original items list which needs to convert
Return:
list: List of dicts with index key and item
... |
def clean_Es(Es):
""" Auxiliary method """
return [ x for x in Es if x != 0 ] |
def flatten(dictionary, delim='.'):
"""Depth first redundantly flatten a nested dictionary.
Arguments
---------
dictionary : dict
The dictionary to traverse and linearize.
delim : str, default='.'
The delimiter used to indicate nested keys.
"""
out = dict()
for key in d... |
def plural(value, singular_str, plural_str):
"""Return value with singular or plural form.
``{{ l|length|plural('Items', 'Items') }}``
"""
if not isinstance(value, (int, int)):
return singular_str
if value == 1:
return singular_str
return plural_str |
def clean_status_string(incoming: str) -> str:
"""Format the status string for output."""
stats = []
stat_val = incoming.replace("_", " ").split()
for val in stat_val:
new_val = val.title()
stats.append(new_val)
return " ".join(stats) |
def cloud_cover_to_ghi_linear(cloud_cover, ghi_clear, offset=35):
"""
Convert cloud cover to GHI using a linear relationship.
0% cloud cover returns ghi_clear.
100% cloud cover returns offset*ghi_clear.
Parameters
----------
cloud_cover: numeric
Cloud cover in %.
ghi_clear: nu... |
def _snake_case_to_camel_case(str_snake_case: str) -> str:
"""Convert string in snake case to camel case.
>>> _snake_case_to_camel_case("")
''
>>> _snake_case_to_camel_case("making")
'making'
>>> _snake_case_to_camel_case("making_the_web_programmable")
'makingTheWebProgrammable'
>>> _sn... |
def Km(cw, R, M, L, P_phot):
"""
Calculate the Kawaler coefficient.
params:
------
cw: (float)
Centrifugal correction. Since stars usually rotate fairly slowly this
is usually set to 1.
R: (float)
Stellar radius in Solar radii.
M: (float)
Stellar mass in Solar... |
def get(obj, field):
"""Extracts field value from nested object
Args:
obj (dict): The object to extract the field from
field (str): The field to extract from the object, given in dot notation
Returns:
str: The value of the extracted field
"""
parts = field.split(".")
for par... |
def soundex(db, value):
"""Return the soundex string of a value.
Args:
db: gluon.dal.DAL instance
value: string, soundex string
Returns:
string, the soundex of value.
"""
# C0103: *Invalid name "%%s" (should match %%s)*
# pylint: disable=C0103
if not value:
... |
def ndvi_calc(nir, red):
"""
Normalized
difference
vegetation index
"""
return (nir - red) / (nir + red + 1) |
def _list_to_freq_dict(words):
"""Convert between a list which of "words" and a dictionary
which shows how many times each word appears in word
Args:
words (list): list of words
Returns:
dict : how many times a word appears. key is word, value is multiplicity
"""
return {i: word... |
def nLabelStr2IntTuple(nLabelStr):
"""converts an legal nodeList string to a to a tuple consists of integer
labels of those nodes
nLabelStr: a string of Abaqus nodeList
format of nodeList is same as the one used to create nodal path in
Abaqus visualization
return: a tuple... |
def add_suffix(s: str, suffix: str, max_length: int = -1):
"""Add a suffix to a string, optionally specifying a maximum string length
and giving priority to the suffix if maximum string length is reached. ::
>>> add_suffix("testing", "suffix", 7)
"tsuffix"
>>> add_suffix("testing", "suf... |
def format_chores(chores):
"""
Formats the chores to properly utilize the Oxford comma
:param list chores: list of chores
"""
if len(chores) == 1:
return f'{chores[0]}'
elif len(chores) == 2:
return f'{chores[0]} and {chores[1]}'
else:
chores[-1] = 'and ' + chores[-1... |
def count_all_characters_of_the_pyramid(chars):
"""Count all block in the pyramid."""
if chars:
return sum([(x * 2 + 1) ** 2 for x in range(len(chars))])
else:
return -1 |
def build_validation_result(is_valid, violated_slot, message_content):
"""
Define a result message structured as Lex response.
"""
if message_content is None:
return {"isValid": is_valid, "violatedSlot": violated_slot}
return {
"isValid": is_valid,
"violatedSlot": violated_s... |
def quicksort(vec):
"""
x is an integer array of length 0 to i. quicksort returns a list with
[1] array of length i in ascending order
[2] number of assignments made during the function call
[3] number of conditionals evaluated in the function call.
QuickSort works by recursively partitioning a... |
def hsv_to_rgb(hue, sat, val):
# pylint: disable=too-many-return-statements
"""
Convert HSV colour to RGB
:param hue: hue; 0.0-1.0
:param sat: saturation; 0.0-1.0
:param val: value; 0.0-1.0
"""
if sat == 0.0:
return val, val, val
i = int(hue * 6.0)
p = ... |
def MigrateUSBPDSpec(spec):
"""Migrate spec from old schema to newest schema.
Args:
spec: An object satisfies USB_PD_SPEC_SCHEMA.
Returns:
An object satisfies USB_PD_SPEC_SCHEMA_V3.
"""
if isinstance(spec, int):
return {
'port': spec
}
if isinstance(spec, (list, tuple)):
return... |
def add_to_dict(dic, fill_in_defaults=True, default_value=None, **kwargs):
"""
Helper function to add key-values to dictionary @dic where each entry is its own array (list).
Args:
dic (dict): Dictionary to which new key / value pairs will be added. If the key already exists,
will append ... |
def cbrack(prio):
"""Create a priority tuple for a closing bracket."""
return (0, prio + 1) |
def copy_keys(source, destination, keys=None):
"""
Add keys in source to destination
Parameters
----------
source : dict
destination: dict
keys : None | iterable
The keys in source to be copied into destination. If
None, then `keys = destination.keys()`
"""
if keys... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.