content stringlengths 42 6.51k |
|---|
def is_isogram(string):
"""
Check whether given string is an isogram or not.
Isogram is a word which contains only unique letters,
ignoring whitespaces and hyphens.
Also, upper/lower case differences are ignored.
>>> is_isogram("first")
True
>>> is_isogram("FIRST word")
False
"... |
def clean_userinput(text:str, conversion_dict: dict, before=None) -> str:
"""Userinput cleaning
Translate words from a text using a conversion dictionary
source: https://stackoverflow.com/questions/14156473/can-you-write-a-str-replace-using-dictionary-values-in-python
Arguments:
text: the ... |
def toCMISValue(value):
"""
Utility function to convert Python values to CMIS string values
"""
if value is False:
return 'false'
elif value is True:
return 'true'
elif value is None:
return 'none'
else:
return value |
def lookup(collection, key):
"""
Lookup a key in a dictionary or list.
Returns None if dictionary is None or key is not found.
Arguments:
dictionary (dict|list)
key (str|int)
Returns: object
"""
if collection:
try:
return collection[key]
except ... |
def jaccard(a, b):
"""
Jaccard of sets a and b.
"""
if len(a | b) == 0:
return 0
return len(a & b) / len(a | b) |
def l0(p_initial, p_matrix, m):
""" Compute the L0 function.
:param p_initial: The initial state distribution.
:type p_initial: list(number)
:param p_matrix: A matrix of transition probabilities.
:type p_matrix: list(list(number))
:param m: The m values.
:type m: list(number)
:ret... |
def strip_begin_end_key(key) :
"""
Strips off newline chars, BEGIN PUBLIC KEY and END PUBLIC KEY.
"""
return key.replace("\n", "")\
.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "") |
def normalize_parameter(kv):
"""
Translate a parameter into standard form.
"""
(k, v) = kv
if k[0] == 'requiressl' and v in ('1', True):
k[0] = 'sslmode'
v = 'require'
elif k[0] == 'dbname':
k[0] = 'database'
elif k[0] == 'sslmode':
v = v.lower()
return (tuple(k),v) |
def check_last_names(nj_to_r_rows, directory):
"""Check from the previous run of this parser if there are new names,
returns a dictionary of names to number of rows"""
from os.path import exists, join
from csv import DictReader, DictWriter
last_names = {}
# Read the last names
if exists... |
def isPrime(n):
"""
Checks if a natural number is prime
:param n: the number (a positive integer) being checked
:return: boolean
"""
# prime larger than sqrt(n) cannot divide n (Number Theory 101)
cap = int( n**(.5) )
if n % 2 == 0: # remove the single even case
return False
for i in range(3, cap, 2): #... |
def hash_index(v, group):
"""
Hash values to store hierarchical index
:param v: index value
:param group: variables from which index was derived
:return: str
v = [1, 2]
group = ['q1', 'q2]
return 'q1::1__q2::2'
"""
if not isinstance(v, (list, tuple)):
_hash = list(zip(... |
def build_thru_float(packs, max_dv=None):
"""
Takes a pack [1,7,2] and converts it into fields used by a SET card.
The values correspond to the first value, last value, and delta in the
list. This means that [1,1001,2] represents 500 values.
[1,1001,1] represents 1001 values and will be written as ... |
def coordinates_to_indices(x, dx=1, offset=0):
"""dx = (X.max() - X.min()) / (N - 1) + offset
X is an array of x's
N is the length X
"""
return int( (x - offset) / dx ) |
def notebook_header(text):
"""
Insert section header into a jinja file, formatted as notebook cell.
Leave 2 blank lines before the header.
"""
return f"""# # {text}
""" |
def reverse_scl_map(x_elem):
"""Maps one element from x to the given class on SCL standart
Parameters:
x_elem (int): class value from the classification
Returns:
int: class number in the SCL format
"""
if x_elem == 2:
return 1
if x_elem == 3:
return 2
if x_ele... |
def _format_inline_pr_link(pr_num):
"""Return an inline link to the PR `pr_num`. The corresponding
`_format_ref_pr_link` text must appear later in the file."""
return f"[#{pr_num}][_#{pr_num}]" |
def import_seach_callback(ea, name, ord):
"""
Callback for enum_import_names, tries to find the valve profiler
EnterScope function for later use. Stops searching when its found
"""
global ENTER_SCOPE
if name:
if "EnterScope@CVProfile" in name:
print(name)
... |
def verse(num_of_bottles):
"""bottle verse"""
b = "bottle" if num_of_bottles == 1 else "bottles"
if num_of_bottles==1:
last = "No more bottles"
elif num_of_bottles==2:
last = "1 bottle"
else:
last = f'{num_of_bottles-1} bottles'
return '\n'.join([
f'{num_of_bot... |
def has_encountered_output_source(context):
"""Return True if the current context has already encountered an @output_source directive."""
return 'output_source' in context |
def calculate_multiscale_sampling(grid, sampling):
""" calculate_multiscale_sampling(grid, sampling)
Calculate the minimal and maximal sampling from user input.
"""
if isinstance(sampling, (float, int)):
# Find maximal sampling for this grid
# Set min and init max
s... |
def grade(value):
"""
Returns a string based grade from a number.
1: God
2: Fair
3: Fair
4: Poor
"""
if value == 1:
return 'good'
if value == 2 or value == 3:
return 'fair'
if value == 4:
return 'poor' |
def _count_dupes_ahead(string, index):
"""
Counts the number of repeated characters in 'string', starting at 'index'
"""
ret = 0
i = index
end = len(string) - 1
while (i < end) and (string[i + 1] == string[i]):
i += 1
ret += 1
return ret |
def version_to_tuple(v):
"""Quick-and-dirty sort function to handle simple semantic versions like 1.7.12 or 1.8.7."""
return tuple(map(int, (v.split('.')))) |
def main(input):
"""
"""
valid_password = 0
for i in input:
limit, char, password = i.split(" ")
char_count = password.count(char[0])
min, max = limit.split("-")
if char_count >= int(min) and char_count <= int(max):
valid_password += 1
return valid_password |
def beale(position):
"""
optimum at (3.0, 0.5) = 0
:param position:
:return:
"""
x, y = position
return (1.5 - x + x * y) ** 2 + (2.25 - x + x * y ** 2) ** 2 + (2.625 - x + x * y ** 3) ** 2 |
def int_to_roman(int_input):
"""
from http://code.activestate.com/recipes/81611-roman-numerals/
Convert an integer to Roman numerals.
:param int_input: an integer between 1 and 3999
:returns result: roman equivalent string of passed :param{int_input}
Examples:
>>> int_to_roman(0)
Trace... |
def ignore_command(command, ignore):
"""
Checks command if it contains words from ignore list.
command - string, command to check,
ignore - list of words.
Return True if command contains word from ignore list, False otherwise.
"""
return any(word in command for word in ignore) |
def get_target_host(string):
"""Print and return the first address of the target.
Example:
"10.10.42.197 10.10.42.203 10.10.42.204" -> "10.10.42.197"
"10.10.42.203" -> "10.10.42.203"
"""
tmp = string.split(" ")[0]
print(tmp, end="")
return tmp |
def as_variable_key(key):
"""Returns ``key`` as a tuple of the form
``('process_name', 'var_name')``.
If ``key`` is given as a string, then process name and variable
name must be separated unambiguously by '__' (double underscore)
and must not be empty.
"""
key_tuple = None
if isinsta... |
def flags_to_direction(flags):
"""
Returns a str indicating the direction of the packet (H2C or C2H)
"""
assert flags in [0,1,2,3]
if flags in [0,2]:
return ">" # host->controller (or h2d?)
elif flags in [1, 3]:
return "<" |
def job_array_unfinished(jobs):
""" Check the status of 'jobs' dictionary and decide if the array is
finished or not.
Args:
jobs (dict): Job dictionary with key [jobid, jobindex]
Returns: bool
"""
for jobid in jobs:
job = jobs[jobid]
if not job.finished:
r... |
def normalize_m11(x):
"""Normalizes RGB images to [-1, 1]."""
return x / 127.5 - 1 |
def normalize_value(value, level=0):
"""Normalize a value to one compatible with Pavilion variables. This
means it must be a dict of strings, a list of strings, a list of dicts of
strings, or just a string. Returns None on failure.
:param value: The value to normalize.
:param level: Controls what st... |
def find_tracing_flags(current_flags):
"""Finds tracing flags on the current command line."""
tracing_flag_prefixes = ['--trace-startup', '--enable-tracing']
tracing_flags = []
for flag in current_flags:
for prefix in tracing_flag_prefixes:
if flag.startswith(prefix):
tracing_flags.append(flag... |
def hex_to_color(color):
"""Convert color in the "#rrggbb" format to a color tuple."""
red = color[1:3]
green = color[3:5]
blue = color[5:7]
return int(red, 16), int(green, 16), int(blue, 16) |
def case_default_panels(case_obj):
"""Get a list of case default panels from a case dictionary
Args:
case_obj(dict): a case object
Returns:
case_panels(list): a list of panels (panel_name)
"""
case_panels = [
panel["panel_name"]
for panel in case_obj.get("panels", [... |
def arbit(x,y):
"""this function is just doing a simple calculation"""
z=x**2+y
return z |
def getPropertyMap(line, property_names):
"""Build the property map. Here we could add more complex behaviour later on.
"""
properties = {}
property_values = line.split("\t")
for i in range(0, len(property_names)): #do not exclude first col (filename), the schema checks for it
##remove trailing newline, and re... |
def string_upper(string):
"""**string_upper(string)** -> return the upercase value of the string
* string: (string) string to upper case.
<code>
Example:
string_upper('linux')
Returns:
'LINUX'
</code>
"""
return string.upper() |
def get_annotationstatetype(layer_kws):
"""Get alpha values from the interface APIs."""
# This function gets alpha/transparency values.
layer_statetype = layer_kws.get("annotationstatetype", 'precomputed')
return layer_statetype |
def build_latest_versions(version_data):
"""Builds a dict with greatest version keyed for each major version"""
ret = {}
for version in reversed(version_data):
major_version = int(version.split('.')[0])
if major_version not in ret:
ret[major_version] = version
return ret |
def label_fixer(i, ncols, nrows):
"""label_fixer
Description:
Create cube of WindSpeeds for all ensemble members
Args:
i (int): plot number (iterable)
ncols (int): number of columns from find_subplot_dims
nrows (int): number of rows from find_subplot_dims
Return:
... |
def char_to_grayscale(char):
"""Converts the character in a number to be represented in a pixel"""
bit = "".join("{:8b}".format(ord(char)))
pixel = (int(bit, 2))
return pixel |
def flat_dict(dict_or_list):
"""
if is dict, return list of dict keys,
if is list, return the list
"""
return list(dict_or_list.keys()) if isinstance(dict_or_list, dict) else dict_or_list |
def htheta_function(x, theta_0, theta_1):
"""
Linear function that is to optimized
"""
return theta_0 + theta_1 * x |
def author(entry):
""" Convert author field to list """
if 'author' in entry:
entry['author'] = [name for name in entry['author'].replace('\n', ' ').split(' and ')
if name.strip()]
return entry |
def TFloat(val):
"""Checks if the given value is a float.
"""
return isinstance(val, float) |
def create_day_set(phrase, recurrence_dict):
"""Create a Set of recurrence days from utterance.
Arguments:
phrase (Str): user utterance
recurrence_dict (Dict): map of strings to recurrence patterns
Returns:
Set: days as integers
"""
recur = set()
for recurrence in recur... |
def _SubForCompoundDescriptors(cExpr, varList, dictName):
""" replace compound variables with the appropriate list index
*Not intended for client use*
"""
for i in range(len(varList)):
cExpr = cExpr.replace('$%s' % chr(ord('a') + i), '%s["%s"]' % (dictName, varList[i]))
return cExpr |
def _get_num_coefficients(function_dict):
"""
Returns the number of coeffecients according to the IRAF fits format defined
here: http://iraf.net/irafdocs/specwcs.php
"""
function_type = function_dict["type"]
if function_type in ["legendre", "chebyshev"]:
return function_dict["order"]
... |
def get_image_format(filename):
"""Returns image format from filename."""
filename = filename.lower()
if filename.endswith('jpeg') or filename.endswith('jpg'):
return 'jpeg'
elif filename.endswith('png'):
return 'png'
else:
raise ValueError('Unrecognized file format: %s' % filename) |
def coerce_value(type, value):
"""
Coerce a value to an expected type.
:param type: The type to coerce the value to (any type).
:param value: The value to coerce (any Python value).
:returns: The coerced value or :data:`None` if an exception is raised
during coercion.
Used by :cl... |
def get_filename(file_list):
""" find csv file from IPEDS download. If a revised file exists ("_rv"), return
that, otherwise, return the csv."""
match = [s for s in file_list if "_rv" in s]
answer = file_list[0]
if len(match) > 0:
answer = match[0]
return(answer) |
def add_padding(data, block_size=16):
"""add PKCS#7 padding"""
size = block_size - (len(data) % block_size)
return data + bytes([size]*size) |
def empty_attribute(node, selector):
"""Test if the given attribute (of dictionary) is empty after stripping whitespaces."""
return node[selector].strip() == "" |
def extract_text(node):
"""Extract the text from a single text node and its descendants."""
if node['type'] == 'text':
return node['text']
elif node['type'] == 'doc':
return '\n'.join([extract_text(child) for child in node['content']])
else:
return ''.join([extract_text(child) fo... |
def sign(x):
"""
Returns 1 or -1 depending on the sign of x
"""
if(x >= 0):
return 1
else:
return -1 |
def _check_weights(weights):
"""Check to make sure weights are valid"""
if weights in (None, 'uniform', 'distance'):
return weights
elif callable(weights):
return weights
else:
raise ValueError("weights not recognized: should be 'uniform', 'distance', or a callable function") |
def cell_ends_with_code(lines):
"""Is the last line of the cell a line with code?"""
if not lines:
return False
if not lines[-1].strip():
return False
if lines[-1].startswith('#'):
return False
return True |
def extract_dims(array, ndim=1):
"""Decrease the dimensionality of ``array`` by extracting ``ndim`` leading singleton dimensions."""
for _ in range(ndim):
assert len(array) == 1, len(array)
array = array[0]
return array |
def check_for_win(board, win_rows, player_mark, game_status):
""" Checks to see if a winning row is present """
row_list = []
for row in win_rows:
for s in row:
row_list.append(board[s])
# print 'row_list = ' + str(row_list)
if row_list.count(player_mark) == 3:
... |
def quickSort(li):
"""Sort a list by choosing a pivot and putting all lesser elements to one
side and all greater elements to the other side. Repeat on each side and
add them back together.
>>> quickSort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> quickSort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>>... |
def _LineRangesToSet(line_ranges):
"""Return a set of lines in the range."""
if line_ranges is None:
return None
line_set = set()
for low, high in sorted(line_ranges):
line_set.update(range(low, high + 1))
return line_set |
def get_overall_misclassifications(H, training_points, classifier_to_misclassified):
"""Given an overall classifier H, a list of all training points, and a
dictionary mapping classifiers to the training points they misclassify,
returns a set containing the training points that H misclassifies.
H is repr... |
def _exchange_amount(amount, rate):
"""
Returns rounded exchange value of amount
"""
return '%.2f' % round(float(amount) * float(rate), 2) |
def clean_msisdn(msisdn):
"""
returns a number without preceeding '+' if it has one
"""
return msisdn.replace("+", "") |
def olivine(piezometer=None):
""" Data base for calcite piezometers. It returns the material parameter,
the exponent parameter and a warn with the "average" grain size measure to be use.
Parameter
---------
piezometer : string or None
the piezometric relation
References
----------
... |
def squash_spaces(inp):
""" Convert multiple ' ' chars to a single space.
:param inp: (str)
:return: same string with only one space where multiple spaces were.
"""
return ' '.join(inp.split()) |
def nested_getitem(obj, *keys, default=None):
"""
>>> nested_getitem({1:{2:{3:"foo"}}}, 1, 2, 3)
'foo'
"""
for key in keys:
if key in obj:
obj = obj[key]
else:
return default
return obj |
def find_years(date):
"""Used to find the year within the string."""
date_length = len(date)
if date[date_length - 4:].find('.') == -1:
year = date[date_length - 4:]
elif date[date_length - 4].find('.') != -1 and date_length != 10:
year = date[:date_length - 7]
else:
year =... |
def fibSumThree(n0):
"""
Created on Mon Aug 23 07:40:53 2021
@author: Ezra
fibSumThree(n0) function to find the sum of all the terms in the
Fibonacci sequence divisible by three whih do not exceed n0.
Input: n0 is the largest natural number considered
Output: fibSumThree- the sum of the Fibonac... |
def modevaltoint(mode_val):
""" convert mode_val value that can be either xeh string or int to int """
if isinstance(mode_val, str):
return int(mode_val, 16)
if isinstance(mode_val, int):
return mode_val
return None |
def rem_slash(string_in):
"""
A simple function which takes in a string and returns it stripped of double backslashes, single forward slashes, and spaces.
"""
return str(string_in).replace("\\", "").replace("/", "").replace(" ", "") |
def make_iter(obj):
""" Makes an iterable
"""
return obj if hasattr(obj, '__iter__') else [obj] |
def parse_dict(dict_str):
"""
, => delimiter
: => key value separator.
"""
tokens = dict_str.split(',')
output = {}
for token in tokens:
k, v = token.split(':')
output[k] = v
return output |
def remaining_zero (matrix):
"""Verifie si il reste des zeros non Encadre ou Barre dans la matrice"""
rest = False
for y_elt in matrix:
for x_elt in y_elt:
if x_elt == 0:
rest = True
break
return rest |
def find_closest_points(a_list, a_number, num_of_points):
"""
some_list -> (list of ints) A list of x or y coordinates
a_number -> (int) a specific number that will be our base
num_of_points -> (int) how many numbers we should looking for
"""
closest_points = []
while num_of_points > 0:
... |
def stemWord(w):
"""Renders a word in to its generic form.
This function is used preprocess words for NLP.
It removes all trailing punctuation marks "';-?.,!:".
It also removes the possessive "'s" from words.
And it converts it to all lower case
Args:
w (str): A string containi... |
def _consolidate_descriptive_type(descriptive_type: str) -> str:
"""Convert type descriptions with "or" into respective type signature.
"x or y" -> "x | y"
Arguments:
descriptive_type: Descriptions of an item's type.
Returns:
Type signature for descriptive type.
"""
return des... |
def repository_tag_is_valid( filename, line ):
"""
Checks changes made to <repository> tags in a dependency definition file being pushed to the tool shed from the command line to ensure that
all required attributes exist.
"""
required_attributes = [ 'toolshed', 'name', 'owner', 'changeset_revision' ... |
def twoPointerSum(nums, target):
"""
Given a sorted array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
"""
l = 0
r = len(nums) - 1
while l... |
def find_an_even(L):
"""Assumes L is a list of integers
Returns the first even number in L
Raises ValueError if L does not contain an even
number"""
for i in L:
if i % 2 == 0:
return i
raise ValueError('L does not contain an even number.') |
def is_valid(message):
"""Check if message is not part of certain invalid labels."""
invalid_labels_set = {"CHAT"}
message_labels_set = set(message['labelIds'])
# return False is set intersection is empty.
return not bool(message_labels_set.intersection(invalid_labels_set)) |
def webhook_body(creator: str, video_link: str):
"""returns a dict containing the data needed for a webhook notification.
"""
return {
"content": f"**{creator}** just uploaded a new video, [check it out!]({video_link})",
"embeds": None,
"username": "DiscordSubHub",
"avatar_ur... |
def log_minor_tick_formatter(y: int, pos: float) -> str:
""" Provide reasonable minor tick formatting for a log y axis.
Provides ticks on the 2, 3, and 5 for every decade.
Args:
y: Tick value.
pos: Tick position.
Returns:
Formatted label.
"""
ret_val = ""
# The posi... |
def main(stdin):
"""
Take sorted standard in from Hadoop and return lines.
Value is just a place holder.
"""
for line_num in stdin:
# Remove trailing newlines.
line_num = line_num.rstrip()
# Omit empty lines.
try:
(line, num) = line_num.rsplit('\t', 1)
... |
def safestr(s: str) -> str:
"""Outputs a string where special characters have been replaced with
'_', which can be safely used in file and path names."""
for c in r'[]/\;,><&*:%=+@!#^()|?^':
s = s.replace(c, '_')
return ''.join([i if ord(i) < 128 else '_' for i in s]) |
def time_string(seconds):
"""Returns time in seconds as a string formatted HHHH:MM:SS."""
s = int(round(seconds)) # round to nearest second
h, s = divmod(s, 3600) # get hours and remainder
m, s = divmod(s, 60) # split remainder into minutes and seconds
return "%2i:%02i:%02i" % (h, m, s) |
def algebraic_equasion_function(x):
"""
This function makes a calculation for an Algebraic equasion
It calculates f(x) with the given equasion and x as a parameter
"""
formula = x**2 + 6*x + 9
return formula |
def _deep_merge_dict(dict_x, dict_y, path=None):
"""Recursively merges dict_y into dict_x.
Adapted from
https://github.com/google/seq2seq/blob/master/seq2seq/configurable.py#L69
"""
if path is None:
path = []
for key in dict_y:
if key in dict_x:
if isinstance(dict_x[... |
def biofile(itisbio):
"""
Returns string containing ".bio" or empty string depending on fasta sequence employed
Parameters
----------
itisbio : bool
Contains information about the nature of fasta sequence.
Returns
-------
bio_path : str
Either ".bio" or empty string.
... |
def _StringListConverter(s):
"""Option value converter for a comma-separated list of strings."""
return [part.strip() for part in s.split(',')] |
def calc_crop_coordinates(store, shapes):
"""
Calculate how each images should be cropped.
Take output from calc_jitters_multiple and return (start, end) coordinates for x, y for each image.
"""
max_w = max(i[0] for i in store)
start_w = [max_w - i[0] for i in store]
size_w = min([shapes[1] ... |
def eta_functional_form(func_type='well-behaved'):
"""
Get line with the correct functional form of Sigma(w)
"""
if func_type == 'power law':
form = r'$\eta(w)=w^{\beta\delta}$'
elif func_type == 'truncated':
form = (r'$\eta(w)='
r'\big{(}\frac{1}{w}+B\big{)}^{B \lamb... |
def real_dirname(path):
"""Python's os.path.dirname is not dirname."""
return path.rsplit('/', 1)[0] |
def lcs_table(source, target):
"""Returns the Longest Common Subsequence dynamic programming table."""
rows = len(source)
cols = len(target)
lcs_table = [[0] * (cols + 1) for _ in range(rows + 1)]
for i in range(1, rows + 1):
for j in range(1, cols + 1):
if source[i - 1] == targe... |
def find_fills(liters, containers, containers_used):
"""Find combinations of containers to fit entirely liters of eggnog."""
if liters == 0:
return [containers_used]
elif liters < 0 or not containers:
return []
cur_containers = containers_used + [containers[0]]
results = []
next... |
def inv(a, m):
"""Compute 1/a mod m."""
s, t, x2, x1, = a, m, 1, 0
while t > 0:
q, r = divmod(s, t)
x = x2 - q * x1
s, t, x2, x1 = t, r, x1, x
return x2 if x2 > 0 else x2 + m |
def decrypt_symmetric_modulo(k: int, ciphertext: str) -> str:
"""Return the decrypted message of ciphertext using the key k.
Preconditions:
- math.gcd(k, len(ciphertext)) == 1
>>> decrypt_symmetric_modulo(2, 'Dsa vciodo li')
'David is cool'
Hint: this one is easier to implement than encry... |
def isEdge(size, i, j):
""" Returns true if the given position is an edge """
return (i == 0) or (j == 0) or (i == size) or (j == size) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.