content stringlengths 42 6.51k |
|---|
def EscapeHtml(text):
"""Escape symbols so that text may be safely embedded in HTML."""
return text.replace('&', '&').replace('>', '>').replace('<', '<') |
def reindent(txt):
""" reindents according to { and } braces. strips all whitespace,
possibly not smartest thing to do. oh well.
"""
res = ''
indent = 0
for l in txt.split("\n"):
l = l.strip()
if l.startswith("}"):
indent -= 1
if indent < 0:
... |
def create_ltm_config(partition, config):
"""Extract a BIG-IP configuration from the LTM configuration.
Args:
config: BigIP config
"""
ltm = {}
if 'resources' in config and partition in config['resources']:
ltm = config['resources'][partition]
return ltm |
def Loss_selectwhere_startend_v2(score_select_column, s_sa, s_wn, s_wc, s_wo,
s_wv, ground_truth_select_column, g_sa, g_wn, g_wc, g_wo, g_wvi):
"""
:param s_wv: score [ B, n_conds, T, score]
:param g_wn: [ B ]
:param g_wvi: [B, conds, pnt], e.g. [[[0, 6, 7, 8, 15], [0, 1, 2, 3, 4, 15]],... |
def to_bool(value):
##############################################
"""
Converts 'something' to boolean. Raises exception for invalid formats
Possible True values: 1, True, "1", "TRue", "yes", "y", "t"
Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0,... |
def r_to_p(r, d, rtype='EI'):
"""
Inverse of the p_to_r function.
Parameters
----------
r : float
The RB error rate
d : int
Number of dimensions of the Hilbert space
rtype : {'EI','AGI'}, optional
The RB error rate rescaling convention.
Returns
-------
... |
def compress_string(s):
"""
Assumes that 's' is a string of only alphabetical characters.
"""
comp_s = ""
count = 1
for idx in range(len(s)):
# Check if character is a repeat or if we are at the end of the string
if idx + 1 == len(s) or s[idx] != s[idx+1]:
comp_s += s... |
def CreateMsgLabels(label_list):
"""Create object to update labels.
Returns:
A label update object.
"""
return {'removeLabelIds': [], 'addLabelIds': label_list } |
def get_tier(score):
"""
"""
cat = 'Tin'
if score == 5: # ranges
cat = "Platinum"
elif score == 4:
cat = "Gold"
elif score == 3:
cat = 'Silver'
elif score == 2:
cat = "Bronze"
elif score == 1:
cat = "Tin"
else:
cat = "No Ranking"
re... |
def findMaxAverage(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
if len(nums) == k:
return sum(nums)/k
first=0
temp=total=sum(nums[:k])
for i in range(k,len(nums)):
temp=temp-nums[first]+nums[i]
total = temp if temp > total else total
first+=1
return total/k |
def printDendrogram(T, sep=3):
"""Print dendrogram of a binary tree. Each tree node is represented by a length-2 tuple.
printDendrogram is written and provided by David Eppstein 2002. Accessed on 14 April 2014:
http://code.activestate.com/recipes/139422-dendrogram-drawing/ """
def isPair(T):
... |
def shift_bit_eps(bit: int, eps: float = 0.5) -> float:
"""Shift the bit from 0 to 1-eps, and from 1 to eps"""
assert bit in [0,1], "Bit must be 0 or 1"
return (2 * eps - 1) * bit + 1 - eps |
def max(a,b):
"""Esta funcion calcula el maximo entre dos numeros"""
if a>b:
maximo=a
else:
maximo=b
return maximo |
def _ofc(id):
"""OFC ID converter."""
return "ofc-%s" % id |
def change_suffix(filename, suffix):
"""
Change suffix into a new one.
:param filename: str - filename
:param suffix: str - string to append
:return: str - new filename with new suffix
"""
return filename[:filename.rfind('.')] + suffix |
def canonize_cmd(cmd_str):
"""
Canonize the command string into 'plugin:command' format
"""
if ':' in cmd_str:
return cmd_str
return '*:' + cmd_str |
def binto(b):
"""
Maps a bin index into a starting ray index. Inverse of "tobin(i)."
"""
return (4**b - 1) // 3 |
def update_state(old_object, old_data, warnings):
"""Update `old_data` and `warnings` with the contents of `old_object`,
where `old_object` is the OLD resource-as-object/dict that was derived from
a LingSync document.
"""
# Add our primary "old_resource" `old_data`
if old_object['old_resource'... |
def parse(data: str):
"""
Check if <data> needs explicit conversion.
"""
if data.startswith("str:"):
return str(data.partition('str:')[2])
elif data.startswith("int:"):
return int(data.partition('int:')[2])
elif data.startswith("float:"):
return float(data.partition('f... |
def pass_thru_block(ds):
"""each blob is read as a block"""
if isinstance(ds, str):
return ds
return "\n".join([r for r in ds]) |
def length(listed):
"""
return length of list
"""
count = 0
for item in listed:
count += 1
return count |
def check_if_stem_exists(stem, length_in_pk, stems_dic, stems_shortened_dic):
""" Function: check_if_stem_exists()
Purpose: Check if a shortened stem was deleted in the filtering step.
Input: Stem and its length, dictionaries of stems and shortened stems.
... |
def bold(text):
""" Return the text in bold (Linux console only).
@param text: The text to bold
"""
return "\033[1m" + str(text) + "\033[0m" |
def first(predicate, iterable):
"""return first element in iterable that satisfies given predicate.
Args:
predicate: a function that takes one parameter and return a truth value.
iterable: any iterable, the items to check.
Return:
first element in iterable that satisfies predicate,... |
def calories_per_portion(input):
"""
>>> calories_per_portion("For 7 portions your meal has 1752 calories.")
'250.29'
>>> calories_per_portion("For 4 portions your meal has 1000 calories.")
'250.0'
>>> calories_per_portion("For 1 portions your meal has 1 calories.")
'1.0'
>>> cal... |
def evens(lst):
"""
Returns a copy of lst, containing only the even elements
Example: evens([1,2,3,4,5]) returns [2,4]
events([1,3,5]) returns []
Parameter lst: The list to copy
Precondition: lst is a list of all numbers (either floats
or ints), or an empty list
"""
# LIST... |
def __accumulate_events__(trace_events, events):
"""
Accumulates the trace events. Calculates the amount of appearances.
:param trace_events: Events found in the trace (filtered by family).
:param events: Event ids to accumulate
:return: Accumulated trace
"""
accumulated = {}
for line i... |
def upper_left_to_zero_center(x, y, width, height):
""" Change referential from center to upper left """
return (x - int(width/2), y - int(height/2)) |
def fahrenheit_to_celcius(fahrenheit):
"""Convert a Fahrenheit temperature to Celsius."""
return (fahrenheit - 32.0) / 1.8 |
def xp(
name: str, *, suffix="_exp", adv_suffix="_advancementExp", tot_suffix="_totalExp"
) -> str:
"""
Generate the HTML for the Xp parts of arts & abilities
"""
return f"""[<input type="text" class="number_3" name="attr_{name}{suffix}" value="0"/>/<input type="text" class="number_3 advance" name="... |
def add(B, x):
"""Helper for binary_bracketings. Adds x to the indices of the brackets.
"""
return [[(a_b2[0]+x,a_b2[1]+x) for a_b2 in s] for s in B] |
def leading_zeros(value, desired_digits):
"""
Given an integer, returns a string representation, padded with [desired_digits] zeros.
"""
num_zeros = int(desired_digits) - len(str(value))
padded_value = []
while num_zeros >= 1:
padded_value.append("0")
num_zeros = num_zeros - 1
... |
def is_iterable(obj):
""" Check if object is an iterable (list, tuple, etc.) and not a string
Args:
obj (:obj:`object`): object
Returns:
:obj:`bool`: Whether or not object is iterable
"""
return hasattr(obj, '__iter__') \
and not isinstance(obj, (str, dict)) \
and n... |
def att_to_s(att):
"""
Constructs a "wordification" word for the given attribute
@param att Orange attribute
"""
return str(att).title().replace(' ','').replace('_','') |
def hyphenize_service_id(service_id):
"""Translate the form used for event emitters.
:param service_id: The service_id to convert.
"""
return service_id.replace(' ', '-').lower() |
def among(m,x,v):
"""
among(m,x,v)
Requires exactly m variables in x to take one of the values in v.
"""
return [m == sum([x[i] == j for i in range(len(x)) for j in v])] |
def unchanged(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
No argument implies empty string ("").
"""
if argument is None:
return u''
else:
return argument |
def normilize_list(ilist):
""" Normilizes the list to [-0.5, 0.5], according to the min and max values in the list.
E.g. each of these inputs return [-0.5, -0.25, 0.0, 0.25, 0.5] :
[1, 2, 3, 4, 5]
[-5, -4, -3, -2, -1]
[-2, -1, 0, 1, 2]
Args:
ilist (list of floats): sh... |
def test_bit(num, offset):
"""
Test the num(int) if at the given offset bit is 1
"""
mask = 1 << offset
return num & mask |
def get_h5_dataset_shape_from_descriptor_shape(
descriptor_shape, ep_data_key, ep_data_list
):
"""
Return the initial shape of the h5 dataset corresponding to the specified data_key.
Initially the dataset will have length 0. It will be resized when data is appended.
The descriptor shape will be eit... |
def build_run_url(base_url: str, experiment_id: str) -> str:
"""
Build the URL for a journal to be pushed to.
"""
return '/'.join([base_url, 'experiment', experiment_id, 'execution']) |
def parseList(txt):
"""
Parse a comma-separated line into a list.
:param str txt: String from config file to parse.
:return: List, based on the input string.
:rtype: list
"""
return txt.split(',') |
def reverse_dict(orig_dict):
"""Reverse a dict."""
return {_v: _k for _k, _v in orig_dict.items()} |
def concat_fields(one, two, sep):
"""
(str, str, str) -> str
Function concat two multiline strings
"""
line = ""
s_one, s_two = one.split("\n"), two.split("\n")
for i in range(len(s_one)):
line += (s_one[i]+sep+s_two[i]+"\n")
return line |
def isCR800(filename):
"""
Checks whether a file is ASCII CR800 txt file format.
"""
try:
temp = open(filename, 'rt').readline()
except:
return False
try:
elem = temp.split()
except:
return False
try:
if not elem[2] == "CR800":
return F... |
def get_max_jobs(queue_dict):
"""Given a queue list, get the max number of possible jobs."""
return max(
[
queue_dict[r]["max_jobs"]
for r in queue_dict
if "max_jobs" in queue_dict[r]
]
) |
def quoted_string(string):
"""
The function ``quoted_string`` determines whether a string begins and ends
with quotes or not. If not, it closes the input ``string`` in quotes.
"""
if string:
new_string = string
if string[0] != '\"':
new_string = '\"' + new_string
... |
def ncbf_recursive(group1, group2, n_elements, path=[]):
"""
DESCRIPTION:
The algorithm that computes all the possible NCBF for a given node.
:param group1: [list] possible layers to build a NCBF. Initially this
group was the activators.
:param group2: [list] possible layers to build a NCBF. Ini... |
def cast_tuple_index_to_type(index, target_type, *tuples):
"""Cast tuple index to type.
Return list of tuples same as received but with index item casted to
tagret_type.
"""
result = []
for _tuple in tuples:
to_result = []
try:
for i, entry in enumerate(_tuple):
... |
def bytes_to_int(bs):
""" converts a big-endian byte array into a single integer """
v = 0
p = 0
for b in reversed(bs):
v += b * (2**p)
p += 8
return v |
def gtf_kv(s):
"""Convert the last gtf section of key/value pairs into a dict."""
d = {}
a = s.split(';')
for key_val in a:
if key_val.strip():
eq_i = key_val.find('=')
if eq_i != -1 and key_val[eq_i-1] != '"':
kvs = key_val.split('=')
else:
kvs = key_val.split()
ke... |
def company(number):
""" Determine issuing company based on some number rules. """
# AMEX
if (
(number.startswith("34")
or number.startswith("37"))
and len(number) == 15
):
return "AMEX"
# Discover
if number.startswith("6011") and len(number) ==... |
def _clip_subrange(ab, dom, x):
"""Return `ab` clipped to `dom`."""
a, b = ab
u, v = dom
assert a <= b, (a, b)
assert u <= v, (u, v)
# assert not disjoint ranges
assert a <= v and b >= u, (ab, dom, x)
a = max(a, u)
b = min(b, v)
assert a <= b, (a, b)
if a == u and v == b:
... |
def swap_nibbles(data: str) -> str:
"""
Swaps nibbles (semi-octets) in the PDU hex string and returns the result.
Example:
>>> swap_nibbles('0123')
'1032'
"""
res = ''
for k in range(0, len(data), 2):
res += data[k+1] + data[k]
return res |
def quoteStr(astr, escChar='\\', quoteChar='"'):
"""Escape all instances of quoteChar and escChar in astr
with a preceding escChar and surrounds the result with quoteChar.
Examples:
astr = 'foo" \bar'
quoteStr(astr) = '"foo\" \\bar"'
quoteStr(astr, escChar = '"') = '"foo"" \bar"'
This prep... |
def comment_uuid(results):
""" get comment unique id """
comment_id = results['id']
return comment_id |
def _adjust_doy(doys, start, freq):
"""Adjust the day of year based on start day.
Args:
doys (numpy.ndarray): an array of DOY.
start (int): a start DOY.
freq (int): the frequency of the year, e.g. 365.
Returns:
list: an array of adjusted DOYs.
"""
doys = list(map(la... |
def get_subs_tes_chp(chp_ratio, v_tes, tes_invest, p_nom):
"""
Calculate KWKG subsidy for TES in combination with CHP
Parameters
----------
chp_ratio : chp_heat/total_heat per year
v_tes : tes volume in liter
tes_invest
p_nom : el. power in kW
Returns
-------
kwkg_subs_tes ... |
def prep_data(filename: str, task: str) -> str:
""" read JSON data from jobs -- each line is valid JSON object
:param task: The task the user has selected to explore optimizations for
:param filename: path to job data
:return string path for cleansed data"""
base = 'https://raw.githubuse... |
def is_valid(array, index):
"""Verify that the index is in range of the data structure's contents."""
row, column = index
return 0 <= row < len(array) and 0 <= column < len(array[row]) |
def expand(v):
"""Split a 24 bit integer into 3 bytes
>>> expand(0xff2001)
(255, 32, 1)
"""
return ( ((v)>>16 & 0xFF), ((v)>>8 & 0xFF), ((v)>>0 & 0xFF) ) |
def get_execution_type(d):
"""
support testcase option automation/manual by using "flag-green"
:param d: testcase topic
:return: 2 is automation, 1 is manual
"""
#winter add to get automation flag "flag_green"
if isinstance(d['makers'], list):
if 'flag-green' in d['makers']:
... |
def strip_alligators(string):
"""
This will strip all < > from a string and return it so that a JSON linter quits barking at me
Args:
string (str) : string to strip
Return:
string : original strin minus < and >
"""
try:
first_replace = str(string).replace("<", "[")
... |
def promo_phones(phones):
""" Retrieve all phones who are currently under a discount/promotion
:param: list of phones
"""
lista = []
for phone in phones:
if 'desconto' in phone['tags']:
lista.append(phone)
return lista |
def IoU(X, Y):
"""
Calculates the Intersection over Union for two bounding boxes, X and Y, which are 4D vectos containing the top left and bottom right positions of the bounding box
"""
max_tl_x = max(X[0], Y[0])
max_tl_y = max(X[1], Y[1])
min_br_x = min(X[2], Y[2])
min_br_y = min(X[3], Y[3... |
def build_new_argument(L):
"""
:param L: a list of satellite id in string
:return: a string of satellite id that includes comma delimiter and range
"""
LI = [int(x) for x in L]
LI.sort()
lrange = len(LI) - 1
if lrange == 0:
arg = str(LI[0])
else:
# walk thru the li... |
def differ_paths(old, new):
""" Compare old and new paths """
if old and old.endswith(("\\", "/")):
old = old[:-1]
old = old.replace("\\", "/")
if new and new.endswith(("\\", "/")):
new = new[:-1]
new = new.replace("\\", "/")
return new != old |
def resource_match_selectors(resource, resource_selectors):
"""
Check if a resource match a resourceSelector
:param dict resource: a dict representation of the resource to match
:param list resource_selectors: a list of dict representing the selectors
:returns: a tuple with the first value being a b... |
def normalize(x, y, viewbox):
"""Normalize so that the origin is at the bottom center of the image,
and the height of the image is 1
"""
xi, yi, width, height = viewbox
return (x - xi - width / 2) / height, (yi + height - y) / height |
def valid_move(game_state, loc):
"""Returns if a move in a board is valid."""
if game_state[int(loc / 3)][loc % 3] != " ":
return False
return True |
def reconstruct_uri(environ):
"""
Reconstruct the relative part of the request URI. I.e. if the requested URL
is https://foo.bar/spam?eggs, ``reconstruct_uri`` returns ``'/spam?eggs'``.
"""
uri = environ.get('SCRIPT_NAME', '') + environ['PATH_INFO']
if environ.get('QUERY_STRING'):
uri +=... |
def extract_and_blast(region, het_fasta, output_folder):
"""Create commands for blasting a region (format "name:start-stop") against all the other het regions (needs a fasta
file with all the het regions: "het_fasta").
This will be use with multiprocessing
Returns the commands (strings) to:
... |
def conv_name_to_c(name):
"""Convert a device-tree name to a C identifier
This uses multiple replace() calls instead of re.sub() since it is faster
(400ms for 1m calls versus 1000ms for the 're' version).
Args:
name (str): Name to convert
Return:
str: String containing the C versio... |
def tupleToDictRGB(rgb_list: list) -> dict:
"""
Converts RGB values from a tuple to a dict object
:param list rgb_list: RGB value to convert
:return: JSON object as a dictionary
"""
return {"r": rgb_list[0], "g": rgb_list[1], "b": rgb_list[2]} |
def balance_on_constant_pay(balance: float, payment: float, rate: float, n: int):
"""
:param balance:
:param payment:
:param rate:
:param n:
:return:
"""
balance_portion = (balance * (1 + rate / 12 / 100) ** n)
payment_portion = (payment * sum((1 + rate / 12 / 100) ** i for i in ran... |
def valid_options(kwargs, allowed_options):
""" Checks that kwargs are valid API options"""
diff = set(kwargs) - set(allowed_options)
if diff:
print("Invalid option(s): ", ', '.join(diff))
return False
return True |
def scrub_pii(arg_dict, padding="..."):
"""
The input is a dict with semantic keys,
and the output will be a dict with PII values replaced by padding.
"""
pii = set([ # Personally Identifiable Information
"subject",
"upn", # i.e. user name
"given_name", "family_name... |
def get_vulnerabilities_hr(vulnerability_list):
"""
Extract attributes for human readable from each vulnerabilities. Used in the 'risksense-get-unique-cves' command.
:param vulnerability_list: List of vulnerabilities.
:return: List represent vulnerabilities detail in human readable form.
"""
re... |
def bearing_delta(bearing_a, bearing_b):
"""Returns the angle difference in degrees between two bearing angles (in degrees)
"""
return (bearing_a - bearing_b + 180) % 360 - 180 |
def clean_data(data):
"""Clean up unwanted markup in data"""
data = data.strip()
data = data.replace('\n', ' ')
return data |
def calculate_number_of_pay_periods(period_payment, frequency, max_tax):
"""
Calculate the number of pay periods that it will take to pay off a tax burden
Param: period_payment: (float)
How much is being taken off per pay
Param: frequency: (int)
How many payments per year
Param: ma... |
def is_str_repr_of_int(string: str) -> bool:
"""
Returns True for strings like: '123i', '+123i', '-123i'
"""
if string.startswith('-') or string.startswith('+'):
if string[1:-1].isdigit() and string.endswith('i'):
return True
if string[0:-1].isdigit() and string.endswith('i'):
... |
def _clip(x, low, high):
"""Clips coordinate between high and low.
This method was created so that `hessian_det_appx` does not have to make
a Python call.
Parameters
----------
x : int
Coordinate to be clipped.
low : int
The lower bound.
high : int
The higher bo... |
def btranslate_bitstring(b, d):
"""Translates the bitstring b by d positions."""
b1 = b[0:d]
b2 = b[d:]
return b2 + b1 |
def clock_to_seconds_remaining(clock_str):
"""Translates a clock string to a number of seconds remaining"""
minutes, seconds = clock_str.split(":")
return float(minutes) * 60 + float(seconds) |
def set_options(*, require_id=False, register_id=False):
"""Convert boolean options to a bitmasked integer."""
opts = 0
opts |= require_id
opts |= (register_id << 1)
return opts |
def remove_decimals(words):
"""
Removes decimals
Parameters
-----------
words: list of words to process
Returns
-------
Processed list of words where decimals have been removed
"""
return [word for word in words if not '.' in word and not ',' in word] |
def encode_inpt(row, col):
"""
Converts integers row, col to chess piece string in form "a1"
:param row: int
:param col: int
:return: string in form "a1"
"""
num = str(row + 1)
letter = chr(col + ord("a"))
return letter + num |
def fmt_row_data(raw_data, fmt_str):
""" Formats the values in the dicts in the given list of raw data using
the given format string.
*This may not be needed at all*
Now that I'm using csv.QUOTE_NONNUMERIC, generally don't want to format floats to strings
@param raw_data: The list of dicts to form... |
def _valdiate_ValueEntriesPositive(strInput : str, acttyp) -> bool:
"""
Description
-----------
Helper method used for validation of entry widgets with only one positive
parameter.
Parameters
----------
`strInput` : string
Input string which should be validated
Return
-... |
def queens_solved(organisms):
"""Determine if we have solved the problem.
We just search through the population for an organism that has a
fitness that is equal to the number of queens in the population.
If so, we have a solution, otherwise we need to keep looking.
"""
for org in organisms:
... |
def bool_decode(s):
""" Decodes a boolean. """
return False if s == '0' or s == '' else True |
def _idempotent_append(element, data):
"""Append to a list if that element is not already in the list.
:param element: The element to add to the list.
:param data: `List` the list to add to.
:returns: `List` the list with the element in it.
"""
if element not in data:
data.append(elemen... |
def get_key(i):
"""Returns the corresponding hotkey of the card
Args:
i (int): card's position
Returns:
str: card's hotkey
"""
return "123qweasdzxcrtyfghvbn"[i] |
def calculate_percentages(counts):
"""
Given a list of (word, count) tuples, create a new list (word, count,
percentage) where percentage is the percentage number of occurrences
of this word compared to the total number of words.
"""
total = 0
for count in counts:
total += count[1]
... |
def gql_projects(fragment: str):
"""
Return the GraphQL projects query
"""
return f'''
query($where: ProjectWhere!, $first: PageSize!, $skip: Int!) {{
data: projects(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
''' |
def generate_custom_color_ramp_divisions_interval(dataset, interval=9):
"""
Generate custom elevation divisions.
Args:
dataset: given dataset
interval(int): number of interval.
Returns:
data_list: list of std deviation range.
"""
data_list = []
if len(dataset) > 2:
... |
def calculate_perf_counter_100ns_queuelen_type(previous, current, property_name):
"""
PERF_COUNTER_100NS_QUEUELEN_TYPE
Average length of a queue to a resource over time in 100 nanosecond units.
https://msdn.microsoft.com/en-us/library/aa392905(v=vs.85).aspx
Formula (n1 - n0) / (d1 - d0)
"""
... |
def hexstr_to_byte(string: str, pad: bool = True) -> int:
"""Converts a hexstring to a byte; items less than 4 characters 'wide' are padded"""
if pad:
return int(string.rjust(4, '0'), 16)
return int(string, 16) |
def realtime(time):
"""
Converts times in the format XXX.xxx into h m s ms
"""
ms = int(time * 1000)
s, ms = divmod(ms, 1000)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
ms = "{:03d}".format(ms)
s = "{:02d}".format(s)
if h > 0:
m = "{:02d}".format(m)
return (
((... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.