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
:param width: int
:return: list
"""
# Fill in\\
k = len(data)
r = data.copy()
new = []
t =[]
for i in range(0,k - width):
z = 0
while z < width <= len(data):
t.append(r[z])
z += 1
x = f(t)
del(r[0])
t = []
new.append(x)
return new
pass |
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) != elem0_sz:
res = True
break
for element in array:
res = res or is_ragged(element, res)
return res |
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-09a7b4932e331edb2 or vpc-054a63a50efe678b3
resource_array (list): an array of cloudformation stack resources
Returns:
boolean - if the resource is found in the list of resource_array
"""
for resource in resource_array:
if resource['PhysicalResourceId'] == physical_resource_id:
return True
else:
return False |
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 representing unknown (out-of-vocabulary) words
Returns:
List of lists of strings, with words not in the vocabulary replaced
"""
# Place vocabulary into a set for faster search
vocabulary = set(vocabulary)
# Initialize a list that will hold the sentences
# after less frequent words are replaced by the unknown token
replaced_tokenized_sentences = []
# Go through each sentence
for sentence in tokenized_sentences:
# Initialize the list that will contain
# a single sentence with "unknown_token" replacements
replaced_sentence = []
# for each token in the sentence
for token in sentence: # complete this line
# Check if the token is in the closed vocabulary
if token in vocabulary: # complete this line
# If so, append the word to the replaced_sentence
replaced_sentence.append(token)
else:
# otherwise, append the unknown token instead
replaced_sentence.append(unknown_token)
# Append the list of tokens to the list of lists
replaced_tokenized_sentences.append(replaced_sentence)
return replaced_tokenized_sentences |
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: # unknown encoding
return value.decode("utf-8", "ignore")
return value |
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 importance of the style cost
Returns:
J -- total cost as defined by the formula above.
"""
J = alpha * J_content + beta * J_style
return J |
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
return command |
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_lengths[opcode]:
raw_parameter_code_list.append(0)
return raw_parameter_code_list |
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] = string1[i] # Reading string 1
count = count + 1
for j in range(len(string2)):
if (count < s_len):
string[count] = string2[j] # Reading string 2
count = count + 1
return string |
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] = 2
elif i - dp[i - 1] > 0 and s[i - dp[i - 1] - 1] == "(":
if i - dp[i - 1] >= 2:
dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
else:
dp[i] = dp[i - 1] + 2
max_len = max(max_len, dp[i])
return max_len |
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 not
skips = [".", ",", ";", ":", "'", '"'] #skipping all the punctuations to not be counted with the words that come bfore them
for ch in skips:
text = text.replace(ch,"")
word_counts = {}
for word in text.split(" "):
if word in word_counts: #known word case
word_counts[word] += 1
else:
word_counts[word] = 1 #unknown word case
return word_counts |
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 = max(0., min(ev_credit_amt, EV_credit_c))
# phaseout based on agi
posevagi = max(c00100, 0.)
ev_max = EV_credit_ps[MARS - 1]
if posevagi < ev_max:
evtc = elecv_credit
else:
evtc_reduced = max(0., evtc - EV_credit_prt * (posevagi - ev_max))
evtc = min(evtc, evtc_reduced)
return evtc |
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('(', '').\
replace(')', '').\
replace(',', '.').\
replace(' ', '').\
replace(u'\u30fb', '.') |
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():
if isinstance(v, dict):
v = underline_to_dash(v)
if isinstance(v, list):
for i in v:
v = [underline_to_dash(i)]
new[k.replace('_', '-')] = v
return new |
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: String representation of the proximity sensor configuration.
"""
radiustr = "radius=%s" % str(radius)
occstr = "occlusion_enabled=%s" % str(occlusion)
return "proximity %s %s" % (radiustr, occstr) |
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)
return bases |
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.
"""
if n <= 1:
raise ValueError('eular14.next_collatz: n must be a positive integer larger than 1!')
elif n % 2 == 0:
return n // 2
else:
return (3 * n) + 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 rolls".format(min_length))
return False
for die in dice:
try:
i = int(die)
if i < 1 or i > 6:
print("Error: Dice rolls must be between 1 and 6.")
return False
except ValueError:
print("Error: Dice rolls must be numbers between 1 and 6")
return False
return True |
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:
obj {any} --The object to check.
Returns:
[boolean] -- [description]
Examples:
--------
>>> buffer(StringIO("data"))
>>> is_file_like(buffer)
True
>>> is_file_like([1, 2, 3])
False
"""
if not (hasattr(obj, 'read') or hasattr(obj, 'write')):
return False
if not hasattr(obj, '__iter__'):
return False
return True |
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:
thetas (dict): Dictionary of actuated joint angles
"""
if not isinstance(thetas, dict):
assert len(active_joint_names) == len(thetas
), f"""the number of robot joint's angle is {len(active_joint_names)},
but the number of input joint's angle is {len(thetas)}"""
thetas = dict((j, thetas[i]) for i, j in enumerate(active_joint_names))
return thetas |
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:
total_fraction += fraction
if not wildcard_zs:
return fractions
balance_fraction = (1.0 - total_fraction) / len(wildcard_zs)
for z in wildcard_zs:
fractions[z] = balance_fraction
return fractions |
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).
"""
if int(t/30) % 2 != 0:
return 1.5
return 1.5+2*intensity |
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 != "":
end = index
entity_seq.append((start, end, tag_name))
tag_name = tag[2:]
start = index
elif tag.startswith("I-"):
if tag_name == "" or tag_name == tag[2:]:
continue
else:
end = index
entity_seq.append((start, end, tag_name))
tag_name = ""
else: # "O"
if tag_name == "":
continue
else:
end = index
entity_seq.append((start, end, tag_name))
tag_name = ""
return entity_seq |
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: (cum_count/rank_counts[rank], rank) for cum_count, count, rank, spname in disc_peps_per_rank}
pre_normalized_corrected_percentages = {}
for spname, percentage_rank in percentages.items():
percentage, rank = percentage_rank
if spname in normalization_factors:
pre_normalized_corrected_percentages[spname] = percentage/normalization_factors[spname]
pre_normalization_sum = sum(p for p in pre_normalized_corrected_percentages.values())
normalized_percentages = {spname: p/pre_normalization_sum for spname, p in pre_normalized_corrected_percentages.items()}
return normalized_percentages |
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)
data2 = fh2.read(65536)
if data1 != data2:
return False
if not data1:
return True |
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 range(1, len(L)):
# compare pairs
if L[i] < L[i - 1]:
# swap smaller elements into the lower position
# a, b = b, a
L[i], L[i - 1] = L[i - 1], L[i]
return L |
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
The numbers specifying the input data range.
b1, b2 : float
The numbers specifying the output data range.
Returns
-------
b : float
Mapped value.
"""
scalar = (b2 - b1) / (a2 - a1)
return max(b1, min(b2, (a - a1) * scalar + b1)) |
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)
except ValueError:
raise ValueError("attempted relative import beyond top-level\
package")
return "%s.%s" % (package[:dot], name) |
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:
--------------------------------------------------------------------------
We know from Proposition 3.3 that for any integer n >= 1, the sum of the
first n integers is n * (n + 1) / 2.
However, because only even numbers are being summed, this is an arithmetic
progression with a common difference of 2. The sum of a finite arithmetic
progression is given by:
n * (a_1 + a_n) / 2 Where a_1 is the first term and a_n is the nth term
If we are summing the first 2n even numbers, then n is the number of even
terms, a_1 is 2, and a_n is 2n. Therefore the solution is:
n * (2 + 2*n) / 2
"""
return n * (2 + 2*n) / 2 |
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 and type, operator's name and its version. It has
the following schema:
INPUT:input_1_shape::input_1_type::input_2_shape::input_2_type::..
::OUTPUT:output_1_shape::output_1_type::output_2_shape::output_2_type::
..::NAME:operator_name ::VERSION:operator_version
An example of an operator signature is:
INPUT:[1,73,73,160]::float::[64,1,1,160]::float::[64]::float::
OUTPUT:[1,73,73,64]::float::NAME:Conv::VERSION:1
Returns:
A string denoting the input tensors' type. In the form of shape/type
separated
by comma. For example:
shape:[1,73,73,160],type:float,shape:[64,1,1,160],type:float,shape:[64],
type:float
"""
start = op_signature.find(":")
end = op_signature.find("::OUTPUT")
inputs = op_signature[start + 1:end]
lst = inputs.split("::")
out_str = ""
for i in range(len(lst)):
if i % 2 == 0:
out_str += "shape:"
else:
out_str += "type:"
out_str += lst[i]
out_str += ","
return out_str[:-1] |
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]),
# attr])
# # new_overload_list.append([list([ty.replace("_fp16", "_float16") for ty in overload]),
# # attr])
# return new_overload_list |
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 which to sort the value names in the
array final value_names array.
ts_values contains a time-indexed array of pairs of arrays giving
value names and counts, and is converted into the 2-dimensional
array time_series_value_counts.
Sample input:
ts_value_names = {True: -5, False: -7}
ts_values = [[[True, False], [4, 5]],
[[True, False], [1, 0]],
[[True, False], [0, 2]]]
Sample output:
value_names = [False, True]
value_counts = [[5, 4],
[0, 1],
[2, 0]]
"""
srt = sorted([(ts_value_names[i], i) for i in ts_value_names])
value_names = [interval for value, interval in srt]
for i in range(len(srt)):
value, interval = srt[i]
ts_value_names[interval] = i
time_series_value_counts = []
for entry in ts_values:
cur_value_names = entry[0]
cur_value_counts = entry[1]
entry_array = [0 for name in value_names]
for i in range(len(cur_value_names)):
entry_array[ts_value_names[
cur_value_names[i]]] = cur_value_counts[i]
time_series_value_counts.append(entry_array)
return value_names, time_series_value_counts |
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.
>>> amountdiv(20, 1, 15)
5
"""
# Set the amount to 0
amount = 0
# For each item in range of minimum and maximum
for i in range(minnum, maxnum + 1):
# If the remainder of the divided number is 0
if num % i == 0:
# Add 1 to the total amount
amount += 1
# Return the result
return amount |
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]
return path |
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 SOC: State of Charge
:param capacity: kWh, capacity of battery, 7kWh as default
:param timestep: h, timestep for each control, 15min as default
:param upper_bound: upper bound of the SOC of the battery, 1 as default
:param lower_bound: lower bound of the SOC of the battery, 0.1 as default
:return P: output of charging rate of the battery for this time step
"""
if P_ctrl >= 0: # charging the battery
P_max = (upper_bound-SOC)*capacity/time_step
P = min(P_ctrl, P_max)
else: # discharging the battery
P_min = (lower_bound-SOC)*capacity/time_step
P = max(P_ctrl,P_min)
return P |
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}.amazonaws.com'
for image_name in images:
if repository_prefix in image_name:
validated_images.append(image_name)
else:
if image_name.startswith('/'):
validated_image = f'{repository_prefix}{image_name}'
else:
validated_image = f'{repository_prefix}/{image_name}'
validated_images.append(validated_image)
return validated_images |
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 as a 2's complement number
if n & 1: # test the lowest bit of n
a = (a * b) % m
b = (b * b) % m
n //= 2 # right shift 1 bit
return 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 for Distance Running: The Scientific Aspects. New York: John Wiley and Sons., n.d. Print.
args:
vo2 (float): VO2, given in mL/kg/minute
Returns:
float: velocity, in meters/minute
"""
return 29.54 + 5.000663 * vo2 - 0.007546 * pow(vo2, 2) |
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.items():
line = line.replace(key, val)
tmp.append(line)
return tmp |
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)
maxprob = max(probs.values()) # Max probability label
for key, value in probs.items():
if value == maxprob:
return key |
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(cmds, str):
return which(cmds)
for cmd in cmds:
path = which(cmd)
if path is not None:
return path
return None |
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 starts from start_val and adds subdiv until reaching
end_val. Note that difference between start_val and end_val does not
need t
"""
# First we get a list of just each tick, not the start and end ticks (no dbl)
init_tick_list = [start_val]
crnt_val = start_val + subdivs
while crnt_val < end_val:
init_tick_list.append(crnt_val)
crnt_val = crnt_val + subdivs
init_tick_list.append(end_val)
# Now we make list with starts and ends
ticks_list = []
# Note init_tick_list has at least 2 values
for i in range(len(init_tick_list) - 1):
ticks_list.append([init_tick_list[i], init_tick_list[i+1]])
return ticks_list |
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 s3_path.split('/')[-1] |
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.88 * (r/r0) ** (5/3) |
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 : array_like
The command line argument list to be parsed.
opts : list
The arguments searched for in arglist.
default : str or bool
The default value if opts are not found in arglist. If default
is False (default), then True is returned if opts are found.
Returns
-------
str or bool
The argument value in arglist or its default value.
"""
for op in opts:
if op in arglist:
ind = arglist.index(op)
arglist.remove(op)
if default is False:
return True
else:
return arglist.pop(ind)
return default |
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[1]; B = T[2]
return (x * B[0] + y * B[1] + s, x * B[2] + y * B[3] + t,
(A[0] * B[0] + A[2] * B[1], A[1] * B[0] + A[3] * B[1],
A[0] * B[2] + A[2] * B[3], A[1] * B[2] + A[3] * B[3])) |
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. We set this mask to set the other bits to zero.
bit_mask = (1 << n_bits) - 1 # e.g. 0b111 for n_bits = 3
return ~n & bit_mask |
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_int // pow(256,3)
ip_int -= octet[0] * pow(256,3)
octet[1] = ip_int // pow(256,2)
ip_int -= octet[1] * pow(256,2)
octet[2] = ip_int // 256
ip_int -= octet[2] * 256
octet[3] = ip_int
octet = map(int,octet)
octet = map(str,octet)
ip_str = '.'.join(octet)
return ip_str |
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
editable = {'app': {}}
try:
editable['app']['access'] = config['access']
except:
pass
else:
try:
editable['app']['communications'] = config['communications']
except:
pass
else:
try:
editable['app']['nickname'] = config['nickname']
except:
pass
try:
editable['app']['nickname'] = config['timezone']
except:
pass
return editable |
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 string.
# Otherwise returns None
if index != -1:
init_position = index + len("sigla=")
course = url[init_position:len(url)]
# Return statement
return course
# None statement
return None |
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 operators.
Returns
-------
str
string of the aggregate operation (sum/max/min/average/count).
"""
if 'number of' in aggregate_step:
return 'COUNT'
elif ('max' in aggregate_step) or ('highest' in aggregate_step) or \
('largest' in aggregate_step) or ('most' in aggregate_step) or \
('longest' in aggregate_step) or ('biggest' in aggregate_step) or \
('more' in aggregate_step) or ('last' in aggregate_step) or \
('longer' in aggregate_step) or ('higher' in aggregate_step) or \
('larger' in aggregate_step):
return 'MAX'
elif ('min' in aggregate_step) or ('lowest' in aggregate_step) or \
('smallest' in aggregate_step) or ('least' in aggregate_step) or \
('shortest' in aggregate_step) or ('less' in aggregate_step) or \
('first' in aggregate_step) or ('shorter' in aggregate_step) or \
('lower' in aggregate_step) or ('fewer' in aggregate_step) or \
('smaller' in aggregate_step):
return 'MIN'
elif ('sum' in aggregate_step) or ('total' in aggregate_step):
return 'SUM'
elif ('average' in aggregate_step) or ('avg' in aggregate_step) or \
('mean ' in aggregate_step):
return 'AVG'
if include_boolean:
if 'true ' in aggregate_step:
return 'TRUE'
elif 'false ' in aggregate_step:
return 'FALSE'
else:
return None
else:
return None
return None |
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 <= 9
counts[digit] += 1
return counts |
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.