content stringlengths 42 6.51k |
|---|
def ProcessName(name, isedge):
"""
Process the name of the node.
:param name: name of the node
:param isedge: whether this is a edge
:return: new name
"""
if isedge:
firstnode, secondnode = name.split("--")
firstnode = firstnode.strip()
secondnode = secondnode.strip(... |
def _legend_add_subtitle(handles, labels, text, func):
"""Add a subtitle to legend handles."""
if text and len(handles) > 1:
# Create a blank handle that's not visible, the
# invisibillity will be used to discern which are subtitles
# or not:
blank_handle = func([], [], label=tex... |
def is_runtime_parameter(argument):
"""Return True if the directive argument defines a runtime parameter, and False otherwise."""
return argument.startswith('$') |
def name_to_uri(name):
"""
Transforms the name of a file into a URI
"""
return name.split(".")[0].replace(" ", "-").lower(); |
def numCorrects(trueCoops, inferredCoops):
"""
Count the number of correct predictions given the true and inferred
cooperator pairs.
"""
numCorrects = 0
if trueCoops['AC'] == inferredCoops['AC']:
numCorrects += 1
if trueCoops['AB'] == inferredCoops['AB']:
numCorrects += 1
... |
def camel_case_to_separate_words(camel_case_string: str) -> str:
"""Convert CamelCase string into a string with words separated by spaces"""
words = [[camel_case_string[0]]]
for character in camel_case_string[1:]:
if words[-1][-1].islower() and character.isupper():
words.append(list(cha... |
def load_dotted(name):
""" Imports and return the given dot-notated python object """
components = name.split('.')
path = [components.pop(0)]
obj = __import__(path[0])
while components:
comp = components.pop(0)
path.append(comp)
try:
obj = getattr(obj, comp)
... |
def escape(s, quote=None):
"""Replace special characters '&', '<' and '>' by SGML entities."""
s = s.replace("&", "&") # Must be done first!
s = s.replace("<", "<")
s = s.replace(">", ">")
if quote:
s = s.replace('"', """)
return s |
def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
... |
def _next_power_of_2_or_max(n: int, max_n: int) -> int:
"""Return the smallest power of 2 greater than or equal to n, with a limit.
Useful when used in splitting a tensor into chunks with power-of-2 sizes.
"""
# special case, just split to 1 element chunks.
if n == 0:
return 1
orig_n = ... |
def fileheader2dic(head):
"""
Convert fileheader list into a Python dictionary
"""
dic = dict()
dic["nblocks"] = head[0]
dic["ntraces"] = head[1]
dic["np"] = head[2]
dic["ebytes"] = head[3]
dic["tbytes"] = head[4]
dic["bbytes"] = head[5]
dic["vers_id"] = head[6]
dic["stat... |
def get_unique_value_from_summary(test_summary, index):
""" Gets list of unique target names
"""
result = []
for test in test_summary:
target_name = test[index]
if target_name not in result:
result.append(target_name)
return sorted(result) |
def ensure_datetime(datetime_obj):
"""If possible/needed, return a real datetime."""
try:
return datetime_obj._to_real_datetime()
except AttributeError:
return datetime_obj |
def canPublish_func(val):
"""
:Description:
Example callback function used to populate a jinja2 variable. Note that
this function must be reentrant for threaded applications.
Args:
val (object): generic object for the example
Returns:
example content (True)
"""
... |
def only_true(*elts):
"""Returns the sublist of elements that evaluate to True."""
return [elt for elt in elts if elt] |
def _format_servers_list_power_state(state):
"""Return a formatted string of a server's power state
:param state: the power state number of a server
:rtype: a string mapped to the power state number
"""
power_states = [
'NOSTATE', # 0x00
'Running', # 0x01
'', # 0x02
... |
def nested_get(input_dict, keys_list):
"""Get method for nested dictionaries.
Parameters
----------
input_dict : dict
Nested dictionary we want to get a value from.
keys_list : list
List of of keys pointing to the value to extract.
Returns
----------
internal_dict_value... |
def cocktail_shaker_sort(unsorted: list) -> list:
"""
Pure implementation of the cocktail shaker sort algorithm in Python.
>>> cocktail_shaker_sort([4, 5, 2, 1, 2])
[1, 2, 2, 4, 5]
>>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11])
[-4, 0, 1, 2, 5, 11]
>>> cocktail_shaker_sort([0.1, -2.4, 4.4,... |
def graph_filename_url(site_id, base_graph_name):
"""This function returns a two-tuple: graph file name, graph URL.
The graph file name is used to save the graph to the file system; the
graph URL is used in an HTML site report to load the graph into an
image tag.
Parameters:
'site_id': the Site ... |
def vocab_unfold(desc, xs, oov0):
"""Covert a description to a list of word indices."""
# assume desc is the unfolded version of the start of xs
unfold = {}
for i, unfold_idx in enumerate(desc):
fold_idx = xs[i]
if fold_idx >= oov0:
unfold[fold_idx] = unfold_idx
return [u... |
def navigation(obj):
"""
Goes through json file and shows its structure
"""
if isinstance(obj,dict):
print()
print("This object is dictionary")
keys = list(obj.keys())
print()
print(keys)
print()
user_choice = input("Here are keys of this dictionar... |
def add_intf_to_map(intf_map, bridge_or_bond, config_type, intf_index,
lacp=False):
"""Adds an interface to the interface map, after performing validation
interface_map has a specific structure. this method checks and inserts
keys if they're missing for the bridge or interface being add... |
def encode_file_name(file_name):
"""
encodes the file name - i.e ignoring non ASCII chars and removing backslashes
Args:
file_name (str): name of the file
Returns: encoded file name
"""
return file_name.encode('ascii', 'ignore') |
def simple_one_default(one, two='hi'):
"""Expected simple_one_default __doc__"""
return "simple_one_default - Expected result: %s, %s" % (one, two) |
def _extract_first_field(data):
"""Extract first field from a list of fields."""
return list(next(iter(zip(*data)))) |
def get_person_box_at_frame(tracking_results, target_frame_idx):
"""Get all the box from the tracking result at frameIdx."""
data = []
for frame_idx, track_id, left, top, width, height in tracking_results:
if frame_idx == target_frame_idx:
data.append({
"track_id": track_id,
"bbox": ... |
def is_analytics_type(odk_type):
"""Test if an odk type is suitable for tracking in analytics.
Args:
odk_type (str): The type to test
Returns:
Return true if and only if odk_type is good for analytics
"""
bad_types = (
"type",
"calculate",
"hidden",
... |
def int_list_to_str(int_list):
""" Reverses a list of utf8 encoded bytes into a string. """
byte_list = [bytes([c]) for c in int_list]
return ''.join([c.decode() for c in byte_list]) |
def find_best_step(v):
"""
Returns best solution for given value
:param v: value
:return: best solution or None when no any solutions available
"""
s = bin(v)[2:]
r = s.find("0")
l = len(s) - r
if (r == -1) or ((l - 1) < 0):
return None
return 1 << (l - 1) |
def parse_bool(name, value):
"""Parse an environment variable value as a boolean."""
value = value.lower()
if value in ("false", "off", "no", "0"):
return False
if value in ("true", "on", "yes", "1"):
return True
raise ValueError(f"Invalid boolean environment variable: {name}={value}... |
def rotate_jump_code_sql(jumpcode, rotation):
"""
Create a piece of SQL command that rotates the jumpcode
to the right value
"""
q = str(jumpcode) + "-" + str(jumpcode) + "%12"
q += "+(" + str(jumpcode) + "%12+" +str(rotation) + ")%12"
return q |
def factorial(n):
"""
On this function we'll calculate the factorial of a number n using recursion
"""
if n == 1:
#base case. Avoiding the infinity loop
return 1
else:
#calling itself
result = ((n) * (factorial(n-1)))
#returning the value of n!
return... |
def is_mostl_numeric(token):
"""
Checks whether the string contains at least 50% numbers
:param token:
:return:
"""
a = len(token)
for i in range(0, 10):
token = token.replace(str(i), "")
if len(token) < 0.5*a and len(token) != a:
return True
else:
return Fals... |
def Func_MakeShellWord(str_python):
""" Func_MakeShellWord(str_python)
Adds shell escape charakters to Python strings
"""
return str_python.replace('?','\\?').replace('=','\\=').replace(' ','\\ ').replace('&','\\&').replace(':','\\:') |
def calcExpGrowth(mgr, asym):
"""Calculate exponential growth value 'r'"""
return 4 * mgr / asym |
def encode_time(time):
""" Converts a time string in HH:MM format into minutes """
time_list = time.split(":")
if len(time_list) >= 2:
return (int(time_list[0]) * 60) + int(time_list[1])
return 0 |
def _combine_overlapping_cities_hashed(my_list):
"""If two cities' markers overlap, combine them into a single entry.
Explanation: Use latitude and longitude rounded to N_DIGITS to create
a PKEY for each city. Rounding will cause nearby cities to have the
same PKEY.
Largest city chosen: As SQL queries m... |
def sort_012(input_list):
"""
Sort a list containing the integers 0, 1, and 2, in a single traversal
:param input_list: list
:return: list
"""
current_index = 0
zero_index = 0
two_index = len(input_list) - 1
while current_index <= two_index:
if input_list[current_index] is ... |
def score(goal, test_string):
"""compare two input strings and return decimal value of quotient likeness"""
#goal = 'methinks it is like a weasel'
num_equal = 0
for i in range(len(goal)):
if goal[i] == test_string[i]:
num_equal += 1
return num_equal / len(goal) |
def bi_var_equal(var1, unifier1, var2, unifier2):
"""Check var equality.
Returns True iff variable VAR1 in unifier UNIFIER1 is the same
variable as VAR2 in UNIFIER2.
"""
return (var1 == var2 and unifier1 is unifier2) |
def arraysize(x):
"""
Returns the number of elements in x, where x is an array.
Args:
x: the array for which you want to get the number of elements.
Returns:
int: the size of the array. If **x** is not an array, this function returns 0.
"""
if '__len__' in dir(x):
ret... |
def test_policy_category_value(recipe):
"""Test that policy category is Testing.
Args:
recipe: Recipe object.
Returns:
Tuple of Bool: Failure or success, and a string describing the
test and result.
"""
result = False
description = "POLICY_CATEGORY is 'Testing'."
r... |
def is_valid_position(position: str) -> bool:
"""Filters out players without a valid position.
Args:
position (str): Player's current position
Returns:
bool: True if the player has a valid position, False otherwise
"""
valid_position_values = ["TE", "RB", "WR", "QB"]
if positio... |
def dot(A, b, transpose=False):
""" usual dot product of "matrix" A with "vector" b.
``A[i]`` is the i-th row of A. With ``transpose=True``, A transposed
is used.
"""
if not transpose:
return [sum(A[i][j] * b[j] for j in range(len(b)))
for i in range(len(A))]
else:
... |
def is_multiply_of(value, multiply):
"""Check if value is multiply of multiply."""
return value % multiply == 0 |
def _check_value(expected_value, received_value):
"""Check that the received value contains the expected value.
Checks that the received value (a hex string) contains the expected value
(a string). If the received value is longer than the expected value, make
sure any remaining characters are zeros.
... |
def isMatchDontCare(ttGold, testRow):
""" Helper function for comparing truth table entries - accounting for don't cares
Arguments:
ttGold {[str]} -- Row from the LUT tt that may contain don't care inputs
testRow {[str]} -- Row from other function to check as a match against ttGold
Returns... |
def check_fibonacci(n):
"""Returns the nth Fibonacci number for n up to 40"""
fib = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088... |
def defect(p=1/3, n=1):
"""
return the probability of 1st defect is found during the nth inspection
"""
return (1-p)**(n-1)*p |
def escape(s, quote=True):
"""
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default), the quotation mark
characters, both double quote (") and single quote (') characters are also
translated.
"""
s = s.replace('&', '&')
s... |
def gcf(m: int, n: int) -> int:
"""Find gcf of m and n."""
while n:
m, n = n, m % n
return m |
def without_duplicates(seq):
"""Returns a copy of the list with duplicates removed while preserving order.
As seen in http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order
"""
seen = set()
seen_add = seen.add
return [x for x in seq i... |
def to_csv(data, headers):
""" convert a set of data to a csv, based on header column names"""
rows = [",".join(headers)]
for datarow in data:
rowdata = [str(datarow.get(h, "")) for h in headers]
rows += [",".join(rowdata)]
csv = "\n".join(rows)
return csv.encode() |
def twos_comp(val, bits):
"""compute the 2's compliment of int value val"""
if( (val&(1<<(bits-1))) != 0 ):
val = val - (1<<bits)
return val |
def cleansignature(value):
"""
**Filter**
Removes ``?`` and everything after from urls.
for example:
.. code-block:: html
{{object.file.url|cleansignature}}
"""
if '?' not in value:
return value
t = value.index('?')
return value[0:t] |
def cascade(s1,s2):
"""Cascade returns the cascaded sparameters of s1 and s2. s1 and s2 should be in complex list form
[[f,S11,S12,S21,S22]...] and the returned sparameters will be in the same format. Assumes that s1,s2 have the
same frequencies. If 1-S2_22*S1_11 is zero we add a small non zero real part or... |
def energy_value(h, J, sol):
"""
Obtain energy of an Ising solution for a given Ising problem (h,J).
:param h: External magnectic term of the Ising problem. List.
:param J: Interaction term of the Ising problem. Dictionary.
:param sol: Ising solution. List.
:return: Energy of the Ising string.
... |
def consecutiveSlopes(ys, xs):
"""
Get slopes of consecutive data points.
"""
slopes = []
samplePeriod = xs[1]-xs[0]
for i in range(len(ys)-1):
slope = (ys[i+1]-ys[i])/(samplePeriod)
slopes.append(slope)
return slopes |
def switch_string_to_numeric(argument):
"""
Switch status string to numeric status (FLAT - POOR: 0, POOR - POOR TO FAIR = 1, FAIR TO GOOD - EPIC = 2)
"""
switcher = {
"FLAT": 0,
"VERY POOR": 0,
"POOR": 0,
"POOR TO FAIR":1,
"FAIR":1,
"FAIR TO GOOD":2,
... |
def frenchText(frenchInput):
"""
This function returns translation if input matches
"""
if frenchInput == 'Bonjour':
return 'Hello' |
def page_data(total_count: int, paginator: dict) -> dict:
"""Build a payload object out of paginator data."""
return {
"total_count": total_count,
"page": paginator["page"],
"max_per_page": paginator["max_per_page"],
} |
def get_bottle_message(num_of_bottles):
""" Parse Bottle Message """
return (
"No more bottles"
if num_of_bottles == 0
else f"{num_of_bottles} bottle"
if num_of_bottles == 1
else f"{num_of_bottles} bottles"
) |
def filter_by_title_summary(strict, gse_gsm_info):
"""
Filter GSE by title and/or summary
Args:
strict: boolean to indicate if filter by both title and summary
gse_gsm_info: the GSE and GSM info tuple
Returns:
filtered results
"""
gse_id, gsm_info = gse_gsm_info
is_p... |
def format_cpf(value):
"""
This function returns the Brazilian CPF with the normal format.
:param value is a string with the number of Brazilian CPF like 12345678911
:return: Return a sting with teh number in the normal format like 123.456.789-11
"""
return f'{value[:3]}.{value[3:6]}.{value[6:9]... |
def rgb_to_RGB(r, g, b):
"""
Convert rgb values to RGB values
:param r,g,b: (0,1) range floats
:return: a 3 element tuple of RGB values in the range (0, 255)
"""
return (int(r * 255), int(g * 255), int(b * 255)) |
def make_seqs(a, b):
""" Makes mutliple sequences of length b, from 0 to a. The sequences are represented
as tuples with start and stop numbers. Note that the stop number of one sequence is
the start number for the next one, meaning that the stop number is NOT included.
"""
seqs = []
x ... |
def format_size(size_bytes):
"""
Format size in bytes approximately as B/kB/MB/GB/...
>>> format_size(2094521)
2.1 MB
"""
if size_bytes < 1e3:
return "{} B".format(size_bytes)
elif size_bytes < 1e6:
return "{:.1} kB".format(size_bytes / 1e3)
elif size_bytes < 1e9:
... |
def count_set_bits_with_bitwise_and_simple(number):
"""Counts set bits in a decimal number
Parameters
----------
number : int
decimal number e.g
Returns
-------
int
a count of set bits in a number
>>> count_set_bits_with_bitwise_and_simple(125)
6
"""
set_bi... |
def order(x, count=0):
"""Returns the base 10 order of magnitude of a number"""
if x / 10 >= 1:
count += order(x / 10, count) + 1
return count |
def i_to_n(i, n):
"""
Translate index i, ranging from 0 to n-1
into a number from -(n-1)/2 through (n-1)/2
This is necessary to translate from an index to a physical
Fourier mode number.
"""
cutoff = (n-1)/2
return i-cutoff |
def BackslashEscape(s, meta_chars):
# type: (str, str) -> str
"""Escaped certain characters with backslashes.
Used for shell syntax (i.e. quoting completed filenames), globs, and EREs.
"""
escaped = []
for c in s:
if c in meta_chars:
escaped.append('\\')
escaped.append(c)
return ''.join(esc... |
def unescape(s):
"""Replace escaped HTML-special characters by their originals"""
if '&' not in s:
return s
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("'", "'")
s = s.replace(""", '"')
s = s.replace("&", "&") # Must be last
return s |
def compute_time(sign, FS):
"""Creates the signal correspondent time array.
"""
time = range(len(sign))
time = [float(x)/FS for x in time]
return time |
def parse_comment(r):
""" Used to parse the extra comment.
"""
return str(r.get("opmerk", "")) |
def count_substring(string, sub_string):
"""
Cuenta cuantas veces aparece el sub_string
en el string
Args:
string: (string)
sub_string: (string)
rerturn : int
"""
return string.count(sub_string) |
def getAllStreetPointsLookingForName(allStreetInfoOSM,
streetName):
""" getAllStreetPointsLookingForName(allStreetInfoOSM, streetName)
Get list of points of all streets which all Streets in Info OSM
are the same as streetName
Parameters
----------
al... |
def remove_end_from_pathname(filen, end='.image'):
"""
Retrieve the file name excluding an ending extension or terminating string.
Parameters
----------
filen : str
end : str
End to file name to remove. If an extension, include the period, e.g.
".image".
"""
if not filen... |
def convert_to_underscores(name):
"""
This function will convert name to underscores_name
:param name: name to convert
:return: parsed name
"""
return "_".join(name.lower().split(" ")) |
def noun(name: str, num: int) -> str:
"""
This function returns a noun in it's right for a specific quantity
:param name:
:param num:
:return:
"""
if num == 0 or num > 1:
return name + "s"
return name |
def check_if_errors_exist(error_dict):
"""This function checks that all the values of the
`error_dict` dictionary evaluate to `None`. If they don't, it means that
there exists errors and it returns `True`, otherwise `False`."""
if error_dict is None:
# there are no errors
return False
... |
def chopping_frequency(frequency1, frequency2):
"""Compute the chopping frequency
Parameters
----------
frequency1: int, float
frequency2: int, float
Returns
-------
out: int, float
"""
return 2 * (frequency2 - frequency1) |
def _vectorize_input_string(input_ingredient: str, word_index: dict):
"""
Converts parsed input ingredient to a list of indexs.
Where each word is converted into a number
:param input_ingredients: Ingredient String e.g. "1 red apple"
:param word_index:
:return: List of words numeric representat... |
def is_dna(a):
"""Return True if input contains only DNA characters, otherwise return False
Args:
a (str): string to test
Returns:
bool: True if all characters are DNA, otherwise False
"""
if len(a) == 0:
return(False)
dna_chars = 'atcgnATCGN'
return all(i in dna_ch... |
def create_param_string(data, cols):
""" Create a param string given the provided data and the columns that were determined to exist in the provided
csv. We don't want NULL values to be inserted into the param string.
Args:
data: One row of data from the provided csv
cols: T... |
def distance(a, b):
"""Returns the manhattan distance between the two points a and b."""
return abs(a[0] - b[0]) + abs(a[1] - b[1]) |
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "fro... |
def sindex(i,j,qi,qj):
"""
Returns the location of {i,j} in the set {{0,0},{0,1},...,{0,qj-1},...{qi-1,qj-1}}.
"""
return int((i * qj) + j) |
def factorial2(x):
"""
second method with exploating recursion
"""
if x == 1:
return 1
else:
return x*factorial2(x-1) |
def update_ave_depth(leaf_depth_sum, set_of_leaves):
"""
Average tree depth update.
Inputs: - leaf_depth_sum: The sum of the depth values of all leaf nodes.
- set_of_leaves: A python set of leaf node ids.
Output: - ave_depth: The average depth of the tree.
"""
ave_depth = leaf_dept... |
def _norm_path(path):
"""Returns a path with '/' and remove the trailing slash."""
path = path.replace("\\", "/")
if path[-1] == "/":
path = path[:-1]
return path |
def _split_uri(uri):
"""
Split the scheme and the remainder of the URI.
>>> _split_uri('http://test.com/something.txt')
('http', '//test.com/something.txt')
>>> _split_uri('eods:LS7_ETM_SYS_P31_GALPGS01-002_101_065_20160127')
('eods', 'LS7_ETM_SYS_P31_GALPGS01-002_101_065_20160127')
>>> _sp... |
def unpack_bits(bits):
"""Unpack ID3's syncsafe 7bit number format."""
value = 0
for chunk in bits:
value = value << 7
value = value | chunk
return value |
def str2bool(v):
"""
Convert strings with Boolean meaning to Boolean variables.
:param v: a string to be converted.
:return: a boolean variable that corresponds to the input string
"""
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', ... |
def _splitext(p):
"""
"""
from os.path import splitext
try:
s = splitext(p)
except (AttributeError, TypeError): # Added TypeError for python>=3.6
s = (None, None)
return s |
def fill_gap_to_win(board, ai_mark):
"""Put a third mark ('ai_mark) to win in the gap on the line
if doing so returns True, otherwise False."""
# copy of board
board_copy = board.copy()
# Changing 'board' lines from vertical to horizontal and put in 'tmp_list',
# this means that the vertical li... |
def get_aparc_aseg(files):
"""Return the aparc+aseg.mgz file"""
for name in files:
if 'aparc+aseg' in name:
return name
raise ValueError('aparc+aseg.mgz not found') |
def body(prg):
"""
Code body
"""
return prg[2:] |
def ihead(store, n=1):
"""Get the first item of an iterable, or a list of the first n items"""
if n == 1:
for item in iter(store):
return item
else:
return [item for i, item in enumerate(store) if i < n] |
def build_flavor_dict(flavor_list):
"""
Returns a dictionary of flavors. Key - flavor id, value - flavor object.
:param flavor_list: a list of flavors as returned from nova client.
:type flavor_list: list
:return: Dictionary containing flavors. Key - flavor id, value - flavor object
"""
fl... |
def formset_model_name(value):
"""
Return the model verbose name of a formset
"""
try:
return value.model._meta.verbose_name
except AttributeError:
return str(value.__class__.__name__) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.