content stringlengths 42 6.51k |
|---|
def is_list_filter(v):
"""
Check if variable is list
"""
return isinstance(v, list) |
def mody_list(x):
"""Take a list and print as a string with commas and 'and' before the last word ."""
i = 0
new = ''
while i < len(x)-2:
new = (new + str(x[i]) + ', ')
i = i + 1
new = (new + str(x[-2]) + ' and ' + str(x[-1]))
return new |
def process_chunk(chunk, func, *args):
""" Apply a function on each element of a iterable. """
L = []
for i, e in enumerate(chunk):
L.append(func(e, *args))
if i % 10 == 0:
print("Processing chunk", i)
return L |
def factorial(number):
"""
Calculates factorial for specified number
Args:
number (int): calculate factorial for this value
Returns:
int: factorial for provided value
"""
result = 1
for item in range(1, number + 1):
result *= item
return result |
def stencil(data, f, width):
"""
perform a stencil using the filter f with width w on list data
output the resulting list
note that if len(data) = k, len(output) = k - width + 1
f will accept as input a list of size width and return a single number
:param data: list
:param f: function... |
def _default_target(package):
"""Return the default target from a package string."""
return package[package.rfind('/')+1:] |
def is_ragged(array, res):
"""Is 'array' ragged?"""
def _len(array):
sz = -1
try:
sz = len(array)
except TypeError:
pass
return sz
if _len(array) <= 0:
return res
elem0_sz = _len(array[0])
for element in array:
if _len(element... |
def is_managed_by_cloudformation(physical_resource_id: str, resource_array: list) -> bool:
"""
Given a physical resource id and array of rources - returns if the resource is managed by cloudformation
Parameters:
physical_resource_id (string): The identifier of the resource - eg igw-09a7b4932e331edb... |
def sfi_pad_flag(b):
"""Return true if the Stuctured Field Introducer padding flag is set."""
return b & 0b00001000 > 0 |
def replace_oov_words_by_unk(tokenized_sentences, vocabulary, unknown_token="<unk>"):
"""
Replace words not in the given vocabulary with '<unk>' token.
Args:
tokenized_sentences: List of lists of strings
vocabulary: List of strings that we will use
unknown_token: A string repres... |
def myround(x, base=10):
"""Round to the near 10 minutes"""
nearest_five = int(base * round(float(x)/base))
if nearest_five ==0:
return 10 ## shortest trip is ten minutes
else:
return nearest_five |
def str2list(s):
"""Convert string to list of strs, split on _"""
return s.split('_') |
def decode_value(value: bytes or str, encoding=None) -> str:
"""Converts value to utf-8 encoding"""
if isinstance(encoding, str):
encoding = encoding.lower()
if isinstance(value, bytes):
try:
return value.decode(encoding or "utf-8", "ignore")
except LookupError: # unknow... |
def total_cost(J_content, J_style, alpha, beta):
"""
Computes the total cost function
Arguments:
J_content -- content cost coded above
J_style -- style cost coded above
alpha -- hyperparameter weighting the importance of the content cost
beta -- hyperparameter weighting the impo... |
def ros_unsubscribe_cmd(topic, _id=None):
"""
create a rosbridge unsubscribe command object
:param topic: the string name of the topic to publish to
:param _id: optional
"""
command = {
"op": "unsubscribe",
"topic": topic
}
if _id:
command["id"] = _id
retur... |
def parameter_code_sizer(opcode, raw_parameter_code_list):
"""Ensures parameter code list is the correct length, according to the particular opcode."""
parameter_lengths = {1: 3, 2: 3, 3: 1, 4: 1,
5: 2, 6: 2, 7: 3, 8: 3, 9: 1, 99: 0}
while len(raw_parameter_code_list) < parameter_le... |
def joinString (string1, string2):
""" Returns a continous string joining string1 and string2 in that order """
s_len = len(string1) + len(string2) # Length of the combined string
string = [0]*s_len
count = 0
for i in range(len(string1)):
if (count < s_len):
string[count] = str... |
def class_to_label(cath_class: int) -> str:
"""See http://www.cathdb.info/browse/tree"""
mapping = {
1: "Mainly Alpha",
2: "Mainly Beta",
3: "Alpha Beta",
4: "Few secondary structures",
6: "Special",
}
return mapping[cath_class] |
def get_vector11():
"""
Return the vector with ID 11.
"""
return [
0.6194425,
0.5000000,
0.3805575,
] |
def longest_valid_parentheses3(s):
"""
Solution 3
"""
max_len = 0
dp = [0 for i in range(len(s))]
for i in range(1, len(s)):
if s[i] == ")":
if s[i - 1] == "(":
if i >= 2:
dp[i] = dp[i - 2] + 2
else:
dp[i... |
def regen_rate(wert):
"""
Umwandlung von Inch/h in mm/h
:param wert: Int, float or None
:return: Float or None
"""
if isinstance(wert, (int, float)):
regenrate = wert * 25.4
regenrate = round(regenrate, 2)
return regenrate
else:
return None |
def count_words(text):
"""count the number of times each word occurs in text (str).
Return dictionary where keys are unique words and values are
word counts. skip punctuations"""
text = text.lower() #lowercase for the counting letters so the function can cont the same words whether it's capatilised or... |
def dict_to_capabilities(caps_dict):
"""Convert a dictionary into a string with the capabilities syntax."""
return ','.join("%s:%s" % tpl for tpl in caps_dict.items()) |
def create_entry(message_body, index):
"""Given a string message body, return a well-formatted entry for sending to SQS."""
return {
'Id': str(index), # Needs to be unique within message group.
'MessageBody': message_body
} |
def is_prime(n):
""" Checks if input is a prime number """
if n <= 3:
return n > 1
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i*i <= n):
if n % i == 0 or n % (i+2) == 0:
return False
i += 6
return True |
def gPrime(G):
"""
G is a graph
returns a graph with all edges reversed
"""
V, E = G;
gPrime = {};
for v in V:
for i in range(len(v)):
for j in range(len(v[0])):
gPrime[j][i] = v[i][j];
return (V, E); |
def EVTaxCredit(EV_credit, ev_credit_amt, EV_credit_c, c00100, EV_credit_ps, MARS,
EV_credit_prt, evtc):
"""
Computes nonrefundable full-electric vehicle tax credit.
"""
if EV_credit is True:
# not reflected in current law and records modified with imputation
elecv_credit... |
def _refang_common(ioc):
"""Remove artifacts from common defangs.
:param ioc: String IP/Email Address or URL netloc.
:rtype: str
"""
return ioc.replace('[dot]', '.').\
replace('(dot)', '.').\
replace('[.]', '.').\
replace('(', '').\
replac... |
def underline_to_dash(d):
"""Helper function to replace "_" to "-" in keys of specifed dictionary recursively.
Netapp API uses "-" in XML parameters.
:param d: dictionary of dictionaries or lists
:type d: dict
:return: new dictionary
:rtype: dict
"""
new = {}
for k, v in d.items():... |
def make_proximity_sensor(radius, occlusion):
"""
Returns string representation of the proximity sensor configuration.
For example: "proximity radius=5 occlusion_enabled=False"
Args:
radius (int or float)
occlusion (bool): True if consider occlusion
Returns:
str: St... |
def keygen(*args, **kwargs):
"""Joins strings together by a colon (default)
This function doesn't include empty strings in the final output.
"""
kwargs['sep'] = ':'
cleaned_list = [arg for arg in args if arg != '']
return kwargs['sep'].join(cleaned_list) |
def greater_than(x, y):
"""Returns True if x is greater than y, otherwise False."""
if x > y:
return True
else:
return False |
def create_reverse_complement(input_sequence):
"""
Given an input sequence, returns its reverse complement.
"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
bases = list(input_sequence)
bases = reversed([complement.get(base, base) for base in bases])
bases = ''.join(bases)
retur... |
def remove_comment(command):
"""
Return the contents of *command* appearing before #.
"""
return command.split('#')[0].strip() |
def next_collatz(n):
""" Takes an integer n and returns the following integer in the Collatz sequence.
If n is even, it returns n divided by 2.
If n is odd, it returns (3*n) + 1.
The end of a collatz sequence is traditionally 1, so we will raise an
exception if the n passed is 1.
... |
def no_of_passwords(k=0):
"""
All are lowercase english alphabet. So for each position we have 26 possibilities.
length_of_passwords = 5
each_position_no_of_possibilities = 26
"""
n = 26
k = 5
return n**k |
def validate_dice_seed(dice, min_length):
"""
Validate dice data (i.e. ensures all digits are between 1 and 6).
returns => <boolean>
dice: <string> representing list of dice rolls (e.g. "5261435236...")
"""
if len(dice) < min_length:
print("Error: You must provide at least {0} dice rol... |
def get_relation_id(relation):
"""Return id attribute of the object if it is relation, otherwise return given value."""
return relation.id if type(relation).__name__ == "Relation" else relation |
def fd(f):
"""Get a filedescriptor from something which could be a file or an fd."""
return f.fileno() if hasattr(f, 'fileno') else f |
def is_file_like(obj):
"""Check if the object is a file-like object.
For objects to be considered file-like, they must be an iterator AND have either a
`read` and/or `write` method as an attribute.
Note: file-like objects must be iterable, but iterable objects need not be file-like.
Arguments:
... |
def convert_thetas_to_dict(active_joint_names, thetas):
"""
Check if any pair of objects in the manager collide with one another.
Args:
active_joint_names (list): actuated joint names
thetas (sequence of float): If not dict, convert to dict ex. {joint names : thetas}
Returns:
... |
def insert_list(index: int, item, arr: list) -> list:
"""
helper to insert an item in a Python List without removing the item
"""
if index == -1:
return arr + [item]
return arr[:index] + [item] + arr[index:] |
def process_wildcard(fractions):
"""
Processes element with a wildcard ``?`` weight fraction and returns
composition balanced to 1.0.
"""
wildcard_zs = set()
total_fraction = 0.0
for z, fraction in fractions.items():
if fraction == "?":
wildcard_zs.add(z)
else:
... |
def alpha_abrupt(t, intensity=0.5):
"""
Correspond to the function alpha(t) of the sudden incident.
Parameters
----------
t : float,
Time.
intensity : float,
Intensity of the step of the function. The default is 1.
Returns
-------
float
The function \alpha(t... |
def encode_utf8(val):
"""encode_utf8."""
try:
return val.encode('utf8')
except Exception:
pass
try:
return val.decode('gbk').encode('utf8')
except Exception:
pass
try:
return val.decode('gb2312').encode('utf8')
except Exception:
raise |
def bg_repeat(value):
"""Convert value to one of: ('no-repeat', '')."""
if value == 'no-repeat':
return value
return '' |
def getStructureFactorLink(pdb_code):
"""Returns the html path to the structure factors file on the ebi server
"""
file_name = 'r' + pdb_code + 'sf.ent'
pdb_loc = 'https://www.ebi.ac.uk/pdbe/entry-files/download/' + file_name
return file_name, pdb_loc |
def file_get_contents_as_lines(path: str) -> list:
"""Returns a list of strings containing the file content."""
lines = []
with open(path, 'r') as file_handler:
for line in file_handler:
lines.append(line)
return lines |
def tagseq_to_entityseq(tags: list) -> list:
"""
Convert tags format:
[ "B-LOC", "I-LOC", "O", B-PER"] -> [(0, 2, "LOC"), (3, 4, "PER")]
"""
entity_seq = []
tag_name = ""
start, end = 0, 0
for index, tag in enumerate(tags):
if tag.startswith("B-"):
if tag_name != "":
... |
def version_string(ptuple):
"""Convert a version tuple such as (1, 2) to "1.2".
There is always at least one dot, so (1, ) becomes "1.0"."""
while len(ptuple) < 2:
ptuple += (0, )
return '.'.join(str(p) for p in ptuple) |
def ERR_PASSWDMISMATCH(sender, receipient, message):
""" Error Code 464 """
return "ERROR from <" + sender + ">: " + message |
def get_percent(part, whole):
"""
Get which percentage is a from b, and round it to 2 decimal numbers.
"""
return round(100 * float(part)/float(whole) if whole != 0 else 0.0, 2) |
def format_phone(n):
"""Formats phone number."""
return format(int(n[:-1]), ",").replace(",", "-") + n[-1] |
def validate_string(s):
"""
Check input has length and that length > 0
:param s:
:return: True if len(s) > 0 else False
"""
try:
return len(s) > 0
except TypeError:
return False |
def compute_corrected_and_normalized_cumulative_percentages(disc_peps_per_rank, rank_counts, normalization_factors):
"""
Compute corrected and normalized cumulative percentages for each species.
Note that this only includes species with specified normalization factors!
"""
percentages = {spname: (... |
def compare_content(fpath1, fpath2):
"""Tell if the content of both fpaths are equal.
This does not check modification times, just internal bytes.
"""
with open(fpath1, 'rb') as fh1:
with open(fpath2, 'rb') as fh2:
while True:
data1 = fh1.read(65536)
... |
def bubble_sort2(L):
"""(list) -> NoneType
Reorder the items in L from smallest to largest.
>>> bubble_sort([6, 5, 4, 3, 7, 1, 2])
[1, 2, 3, 4, 5, 6, 7]
"""
# keep sorted section at beginning of list
# repeated until all is sorted
for _ in L:
# traverse the list
for i in... |
def apmapr(a, a1, a2, b1, b2):
"""Vector linear transformation.
Map the range of pixel values ``a1, a2`` from ``a``
into the range ``b1, b2`` into ``b``.
It is assumed that ``a1 < a2`` and ``b1 < b2``.
Parameters
----------
a : float
The value to be mapped.
a1, a2 : float
... |
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' not set to a string")
dot = len(package)
for x in range(level, 1, -1):
try:
dot = package.rindex('.', 0, dot)
... |
def get_mapping_data_by_usernames(usernames):
""" Generate mapping data used in response """
return [{'username': username, 'remote_id': 'remote_' + username} for username in usernames] |
def invertir(palabra):
"""Esta funcion invierte un texto"""
tamano = len(palabra)
nueva_palabra = ""
for i in range( 1, ( tamano + 1 ) ):
nueva_palabra = nueva_palabra + palabra[-i]
return nueva_palabra |
def sum_of_even_nums(n):
"""Solution to exercise R-3.6.
What is the sum of all the even numbers from 0 to 2n, for any positive
integer n?
--------------------------------------------------------------------------
Solution:
-----------------------------------------------------------------------... |
def reverse(text):
"""Get the string, reversed."""
return text[::-1] |
def get_input_type_from_signature(op_signature):
"""Parses op_signature and returns a string denoting the input tensor type.
Args:
op_signature: a string specifying the signature of a particular operator.
The signature of an operator contains the input tensor's shape and type,
output tensor's shape... |
def findchain(pair, i, b):
"""Find chain."""
chain = []
for j in pair:
if j[0] in b[i[0]] and (i[1] == j[1] or i[1] == j[2]):
if i[1] == j[1]:
chain.append([j[0], j[2]])
else:
chain.append([j[0], j[1]])
return chain |
def expand_overload(overload_list, func):
"""
Allow some extra overload to ease integrations with OpenCL.
"""
return overload_list
# new_overload_list = list()
# for overload, attr in overload_list:
# new_overload_list.append([list([ty.replace("_fp16", "_float16") for ty in overload]),
... |
def parseDeviceName(deviceName):
""" Parse the device name, which is of the format card#.
Parameters:
deviceName -- DRM device name to parse
"""
return deviceName[4:] |
def _get_time_series_params(ts_value_names, ts_values):
"""_get_time_series_params
Converts data in ts_value_names and ts_values into the value_names
and time_series_value_counts properties of the Facet API.
ts_value_names is a dictionary mapping value names (such as True
or '10-19') to numbers by ... |
def basic_pyxll_function_22(x, y, z):
"""if z return x, else return y"""
if z:
# we're returning an integer, but the signature
# says we're returning a float.
# PyXLL will convert the integer to a float for us.
return x
return y |
def check_passport_id(val):
"""pid (Passport ID) - a nine-digit number, including leading zeroes."""
return len(val) == 9 and val.isdigit() |
def try_get_item(list, index):
"""
Returns an item from a list on the specified index.
If index is out or range, returns `None`.
Keyword arguments:
list -- the list
index -- the index of the item
"""
return list[index] if index < len(list) else None |
def vec_mul (v1,s):
"""scalar vector multiplication"""
return [ v1[0]*s, v1[1]*s, v1[2]*s ] |
def amountdiv(num, minnum, maxnum):
"""
Get the amount of numbers divisable by a number.
:type num: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum number to check.
... |
def sanitize(path):
"""
Clean up path arguments for use with MockFS
MockFS isn't happy with trailing slashes since it uses a dict
to simulate the file system.
"""
while '//' in path:
path = path.replace('//', '/')
while len(path) > 1 and path.endswith('/'):
path = path[:-1]... |
def searchAcqus(initdir):
""" search the acqus file in sub-directory of initdir"""
import os, fnmatch
pattern = 'acqus'
liste = []
for path, dirs, files in os.walk(os.path.abspath(initdir)):
for filename in fnmatch.filter(files, pattern):
liste.append(path)
return liste |
def security_battery(P_ctrl, SOC, capacity=7, time_step=0.25,
upper_bound=1, lower_bound=0.1):
"""
Security check for the battery control
:param P_ctrl: kW, control signal for charging power, output from RL controller,
positive for charging, negative for discharging
:param S... |
def validate_image_name(images, account_id, region):
"""Validate image name
Args:
images (list): includes image name
account_id (str)
region (str)
Returns:
validated images list
"""
validated_images = []
repository_prefix = f'{account_id}.dkr.ecr.{region}.amazo... |
def fast_power(b, n, m):
"""
Use the Fast-Power Algorithm to calculate the result of (b^n mod m).
:param b: integer, base nubmer.
:param n: integer, exponent number.
:param m: integer, the modulus.
:return: integer, the result of (b^n mod m).
"""
a = 1
while n: # n is represented a... |
def velocity(vo2):
"""
A regression equation relating VO2 with running velocity. Used in conjuction with the "vO2" equation to create the Jack Daniel's VDOT tables. Initially retrieved from "Oxygen Power: Performance Tables for Distance Runners" by Jack Daniels.
J., Daniels, and J. Daniels. Conditioning fo... |
def replace_in_string_list(the_list, the_dict):
"""
Replace all keys with their values in each string of 'the_list'.
:param the_list: a list of strings
:param the_dict: replacement dictionary
:return: processed list
"""
tmp = []
for line in the_list:
for key, val in the_dict.item... |
def printLeaf(counts):
"""
Returns the prediction values based on higher probability
:param counts: Dictionary of label counts
:return: Prediction
"""
total = sum(counts.values()) * 1.0
probs = {}
for lbl in counts.keys():
probs[lbl] = int(counts[lbl] / total * 100)
maxpr... |
def pochhammer(x, k):
"""Compute the pochhammer symbol (x)_k.
(x)_k = x * (x+1) * (x+2) *...* (x+k-1)
Args:
x: positive int
Returns:
float for (x)_k
"""
xf = float(x)
for n in range(x+1, x+k):
xf *= n
return xf |
def is_command(cmds):
"""Given one command returns its path, or None.
Given a list of commands returns the first recoverable path, or None.
"""
try:
from shutil import which # python3 only
except ImportError:
from distutils.spawn import find_executable as which
if isinstance(cm... |
def generate_flake8_command(file: str) -> str:
"""
Generate the flake8 command for a file.
Parameters
----------
file : str
The file to fix.
Returns
-------
str
The flake8 command.
"""
cmd = f"flake8 {file}"
return cmd |
def GetTickValues(start_val, end_val, subdivs):
"""We go from a value and subdivs to actual graph ticks
Args:
start_val: (int)
end_val: (int)
subdivs: (int)
Returns:
ticks_list = [[start_val, start_val + subdivs], [start_val + subdivs,...]
Specifically, this function s... |
def quadratic(V, a, b, c):
"""
Quadratic fit
"""
return a * V**2 + b * V + c |
def get_value_list(dict_list, k):
"""
return list of values for given key from a list of dicts
"""
return list(map(lambda x: x[k], dict_list)) |
def get_s3_filename(s3_path):
"""Fetches the filename of a key from S3
Args:
s3_path (str): 'production/output/file.txt'
Returns (str): 'file.txt'
"""
if s3_path.split('/')[-1] == '':
raise ValueError('Supplied S3 path: {} is a directory not a file path'.format(s3_path))
return s... |
def clean_splitlines(string):
"""Returns a string where \r\n is replaced with \n"""
if string is None:
return ''
else:
return "\n".join(string.splitlines()) |
def komogorov(r, r0):
"""Calculate the phase structure function D_phi in the komogorov approximation
Parameters
----------
r : `numpy.ndarray`
r, radial frequency parameter (object space)
r0 : `float`
Fried parameter
Returns
-------
`numpy.ndarray`
"""
return 6... |
def get_optarg(arglist, *opts, default=False):
"""Gets an optional command line argument and returns its value.
If default is not set, the flag is treated as boolean. Note that
that setting default to None or '' will still take an argument
after the flag.
Parameters
----------
arglist : ar... |
def compose(S, T):
"""\
Return the composition of two transformations S and T.
A transformation is a tuple of the form (x, y, A), which denotes
multiplying by matrix A and then translating by vector (x, y).
These tuples can be passed to pattern.__call__()."""
x = S[0]; y = S[1]; A = S[2]
s = T[0]; t = T... |
def inv(n: int, n_bits: int) -> int:
"""Compute the bitwise inverse.
Args:
n: An integer.
n_bits: The bit-width of the integers used.
Returns:
The binary inverse of the input.
"""
# We should only invert the bits that are within the bit-width of the
# integers we use. W... |
def scale(x, s):
"""Scales x by scaling factor s.
Parameters
----------
x : float
s : float
Returns
-------
x : float
"""
x *= s
return x |
def int2ip(ip_int):
"""
Convert integer to XXX.XXX.XXX.XXX representation
Args:
ip_int (int): Integer IP representation
Returns:
ip_str (str): IP in a XXX.XXX.XXX.XXX string format
"""
ip_str = None
if isinstance(ip_int,int):
octet = [0,0,0,0]
octet[0] = ip_... |
def get_editable_bot_configuration(current_app_configuration):
"""Get an editable bot configuration
:param current_app_configuration: Full JSON Dictionary definition of the bot instance from the server - not an array
:returns: Editable configuration
"""
config = current_app_configuration
editabl... |
def identify_course(url):
"""
Identify if the url references a course.
If possible, returns the referenced course, otherwise returns None.
"""
# Check for the position previous to the course
index = url.find("sigla=")
# Check if the position has been found and extracts the course from the... |
def extract_aggregator(aggregate_step, include_boolean=False):
"""Extract aggregator type from QDMR aggregate step string
Parameters
----------
aggregate_step : str
string of the QDMR aggregate step.
include_boolean : bool
flag whether to include true/false as operators.
used in COMPARISON opera... |
def count_digits_in_carray(digits):
"""
>>> digits = '37692837651902834128342341'
>>> ''.join(sorted(digits))
'01112222333334445667788899'
>>> count_digits_in_carray(map(int, digits))
[1, 3, 4, 5, 3, 1, 2, 2, 3, 2]
"""
counts = [0] * 10
for digit in digits:
assert 0 <= digit ... |
def clean_code(content):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith("```") and content.endswith("```"):
return "\n".join(content.split("\n")[1:])[:-3]
else:
return content |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.