content stringlengths 42 6.51k |
|---|
def set_pox_opts(
components, info_level, logfile_opts,
log_format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'):
"""Generate a string with custom pox options.
:components: dot notation paths (eg: forwarding.l2_learning web.webcore --port=8888)
:info_level: DEBUG, INFO, etc.
... |
def mutate(mushroom, i):
""" Randomly flips one bit in a mushroom bit string"""
return mushroom ^ 1 << i |
def slicer(s: str, slice_pos: int) -> tuple:
"""Return a tuple of strings which are the parm string cleaved at its parm slice position."""
return s[0:slice_pos], s[slice_pos:] |
def get_codebook(ad_bits, codebook):
"""Returns the exhaustive codebooks for a given codeword length
:param ad_bits: codewor length
:type ad_bits: int
:return: Codebook
:rtype: list(str)
"""
return codebook[ad_bits-2] |
def get_getmodel_cov_cmd(
number_of_samples, gul_threshold, use_random_number_file,
coverage_output, item_output,
process_id, max_process_id, **kwargs):
"""
Gets the getmodel ktools command (version < 3.0.8) gulcalc coverage stream
:param number_of_samples: The number of samples to r... |
def fst(l):
"""Returns the first item in any list
Parameters
---------
l : list
the list we want to extract the first item from
Returns
-------
first item in list
"""
if isinstance(l, list):
return fst(l[0])
else:
return l |
def rank_names(names):
"""
Given a list of tuples with ranking, male name and female return a list of male and female names with their ranking.
:param names: the tuple with the data.
:return: a list with names and its ranking
"""
names_rank = []
for i in range(len(names)):
names_ran... |
def merge_paths_and_videos(paths, videos):
"""Merge paths and videos, playback orders"""
for i, path in enumerate(paths, 1):
path["id"] = i
path["videos"] = []
for video in videos:
if path.get("PK") == video.get("PK"):
_d = {}
_d["uri"] = video... |
def sw_id_to_pos_index(id):
"""Switch ID (ex: 4 if SW4) to row/col"""
if id < 1 or id > 33:
raise Exception("Invalid index: {}".format(id))
# From here, we can calculate the row/col by mod operation
col_offset = 0
if id > 18:
col_offset = 3
id_0 = int(id) - 1
row = id_0 % 3
... |
def tz_syntax(string):
""" returns 'good' and clean reply if reply to adjust the current time zone is fine """
signs = ['+','-']
cond = all(len(s) <= 2 for s in string[1:].replace(',','.').split('.'))
if string[0] in signs and cond == True or string == '0':
return 'good', string.replace(',','.').strip()
else:
... |
def findDuplicates(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
i = 0
repeat = []
for j in range(len(nums)):
if nums[j] == j+1:
continue
temp = nums[j]
nums[j] = 0
while temp != 0:
if nums[temp-1] == temp:
repe... |
def isNestedInstance(obj, cl):
""" Test for sub-classes types
I could not find a universal test
keywords
--------
obj: object instance
object to test
cl: Class
top level class to test
returns
-------
r: bool
True ... |
def f4(N):
"""Fragment for exercise."""
ct = 1
while N >= 2:
ct = ct + 1
N = N ** 0.5
return ct |
def hex_to_rgb(hex_colors,):
"""
"""
res = []
for color in hex_colors:
res.append([int(color[i:i+2], 16) for i in (1, 3, 5)])
return res |
def uneven(value):
"""Returns the closest uneven value equal to or lower than provided"""
if value == 0:
newvalue = 1
else:
newvalue = value -1 if value % 2 == 0 else value
return newvalue |
def echo(ctx, text, newline):
""" Echo back arguments passed in. Strips extra whitespace. """
if not text:
text = [ctx.obj['stdout']]
joiner = ' ' if not newline else '\n'
return joiner.join(text) |
def format_timedelta(td):
"""
Format timedelta object nicely.
Args:
td: timedelta object
"""
if td is None:
return ''
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
return '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), ... |
def hashcode(s):
"""Compute hash for a string, in uint32_t"""
hash = 2166136261
for c in s.encode('utf8'):
hash = ((hash ^ c) * 16777619) & 0xFFFFFFFF
return hash |
def format_milestone_class(issue_data):
"""Return the correct class for a milestone, depending on state."""
state = issue_data.get('state')
milestone = issue_data.get('milestone')
title = ''
if state == 'closed':
return 'closed'
elif milestone:
title = milestone.get('title')
... |
def filter_out_none(**kwargs) -> dict:
"""Filters out all None values from parameters passed."""
for key in list(kwargs):
if kwargs[key] is None:
kwargs.pop(key)
return kwargs |
def parse_environment(env_string):
"""
Parse the output of 'env -0' into a dictionary.
"""
if isinstance(env_string, bytes):
env_string = env_string.decode()
return dict(
item.split('=', 1)
for item in env_string.rstrip('\0').split('\0')
) |
def write_lines(new_lines, lines, edit_index):
"""
Inserts new lines where specified
:param new_lines: the new lines to be added
:param lines: holds all the current lines of output html file
:param edit_index: the index to insert new lines
:return: new contents of output htm... |
def normalize_directory_path(path):
"""Normalizes a directory path."""
return path.rstrip('/') |
def strict_between(q, qmin, qmax):
"""
>>> strict_between(2, 1, 3)
True
>>> strict_between(2, 3, 1)
True
>>> strict_between(4, 1, 3)
False
>>> strict_between(4, 3, 1)
False
>>> strict_between(0, 1, 3)
False
>>> strict_between(0, 1, 3)
False
>>> strict_between(1, 1... |
def checkMultipleOptions(content):
""" Print list of links for available pages for a search
content = list of html elements
outputs a list of lists """
paragraphs = ""
paragraphs += "<p>There were multiple things found for that item</p>"
for item in content:
#Get the lists of links provided by the page
i... |
def _search(name, obj):
"""Breadth-first search for name in the JSON response and return value."""
q = []
q.append(obj)
while q:
obj = q.pop(0)
if hasattr(obj, '__iter__'):
isdict = type(obj) is dict
if isdict and name in obj:
return obj[name]
for k in obj:
q.append(obj[k] if isdict else k)
el... |
def check_if_already_found(key, result):
"""
checks if data element exists in result dict and if so, if the value is not None
:param key: key from result dict
:type key: basestring
:param result: dictionary of results
:return: boolean
"""
if key not in result.keys():
return False... |
def get_category(raw_outputs, threshold):
"""multi class"""
# in future, when list: result = [1 if p > threshold else 0 for p in raw_outputs[0]]
pred_dict_m = {2: 'Animals',
3: 'Environment',
1: 'People',
4: 'Politics',
5: 'Product... |
def is_safe(value: str) -> bool:
"""Evaluate if the given string is a fractional number safe for eval()"""
return len(value) <= 10 and all(c in "0123456789./ " for c in set(value)) |
def convert_dict_key_type(dict, type):
"""Convert keys in dictionary to ints
(loading json loads keys as strs)"""
return {type(k): v for k, v in dict.items()} |
def use_gpu(opt):
"""
Creates a boolean if gpu used
"""
return (hasattr(opt, "gpu_ranks") and len(opt.gpu_ranks) > 0) or (
hasattr(opt, "gpu") and opt.gpu > -1
) |
def str2bytes(string):
"""Converts '...' string into b'...' string. On PY2 they are equivalent. On PY3 its utf8 encoded."""
return string.encode("utf8") |
def suffix(pattern):
"""
return every symbol in pattern except the first
"""
if len(pattern) == 1:
return ""
Sufx = pattern[1:]
return Sufx |
def heuristic(network, node, goal, dist_func):
"""
Heuristic function for estimating distance from specified node to goal node.
Args:
network (object): Networkx representation of the network
node (int): Node for which to compute the heuristic
goal (int): Goal node
dist_func ... |
def maskStats(wins, last_win, mask, maxLen):
"""
return a three-element list with the first element being the total proportion of the window that is masked,
the second element being a list of masked positions that are relative to the windown start=0 and the window end = window length,
and the third bein... |
def splitdrive(p):
"""Split a pathname into drive and path. On Posix, drive is always
empty."""
return (
'', p) |
def table(line):
"""
Converting Org table to Md format
:param line:
:return:
"""
if line[:2] == '|-':
line = line.replace('+', '|') # format of the grid line
return line |
def _is_uint(candidate):
"""Returns whether a value is an unsigned integer."""
return isinstance(candidate, int) and candidate >= 0 |
def hyphenate(text: str) -> str:
"""
Converts underscores to hyphens.
Python functions use underscores while Argo uses hyphens for Argo template names by convention.
"""
return text.replace("_", "-") |
def curvature(x, dfunc, d2func, *args, **kwargs):
"""
Curvature of function:
`f''/(1+f'^2)^3/2`
Parameters
----------
x : array_like
Independent variable to evalute curvature
dfunc : callable
Function giving first derivative of function f: f', to be called `dfunc(x, *ar... |
def assort_values(d):
"""
Collect every values stored in dictionary, then return them as a set
:param d:
:return:
"""
values = set()
for key in d.keys():
values |= set(d[key])
return values |
def extract(input_data: str) -> tuple:
"""take input data and return the appropriate data structure"""
sheet = set()
folds = list()
s_instr, f_instr = input_data.split('\n\n')
for line in s_instr.split('\n'):
sheet.add(tuple(map(int, line.split(','))))
for line in f_instr.split('\n'):
... |
def match_args(macro, args):
"""
Match args names with their values
"""
if 'args' not in macro:
return {}
return dict(list(zip(macro['args'], args))) |
def get_content(filename):
""" Gets the content of a file and returns it as a string
Args:
filename(str): Name of file to pull content from
Returns:
str: Content from file
"""
with open(filename, "r") as full_description:
content = full_description.read()
return content |
def take_workers(dic, l = 10):
"""
return list of workers with more than l labels
"""
res = []
for (w, val) in dic.items():
if val[2] > l:
res.append(w)
return res |
def pool_to_HW(shape, data_frmt):
""" Convert from NHWC|NCHW => HW
"""
if len(shape) != 4:
return shape # Not NHWC|NCHW, return as is
if data_frmt == "NCHW":
return [shape[2], shape[3]]
return [shape[1], shape[2]] |
def fast_modular_multiply(g, k, p):
"""Calculates the value g^k mod p
Args:
g: an integer representing the base
k: an integer representing the exponent
p: an integer (prime number)
Returns:
an integer representing g^k mod p
"""
u = g
y = 1
while... |
def dict_pivot(x_in, key):
"""
Before:
>>>{"ts": 123, "A": "A", "B": "B", "sub": [{"C": 10}, {"C": 8}]}
After:
>>>[
>>> {'B': 'B', 'A': 'A', 'ts': 123, 'sub.C': 10},
>>> {'B': 'B', 'A': 'A', 'ts': 123, 'sub.C': 8}
>>>]
:param x_in:
:param key:
:return:
"""
... |
def mat_mul(mat1, mat2):
"""mat_mul: performs matrix multiplication
Args:
mat1: First matrix to multiplicate
mat2: First matrix to multiplicate
"""
result = []
if len(mat1[0]) == len(mat2):
for i in range(0, len(mat1)):
temp = []
for j in range(0, len... |
def ex_timeout():
"""Timeout error response in bytes."""
return b"SPAMD/1.5 79 EX_TIMEOUT\r\n\r\n" |
def _deal_time_units(unit='s'):
"""Return scaling factor and string representation for unit multiplier
modifications.
Parameters
----------
unit : 'str'
The unit to be used
Returns
-------
factor : float
Factor the data is to be multiplied with, i.e. 1e-3 for millisecon... |
def down(pos):
"""
Move down
"""
return (pos[0], pos[1]-1) |
def transform_response_if_html(text):
"""removes HTML code from skill response"""
if text.find("<a", 0) > -1 and text.find("</a", 0) > -1:
anchor_start = text.find("<a", 0)
anchor_end = text.find("/a>", anchor_start) + 3
text_begin = text.find(">", 0) + 1
text_end = text... |
def __num_digits(num: int):
"""internal helper to get the number of digits"""
return len(str(num)) |
def minmax(*data):
"""Return the minimum and maximum of a series of array/list/tuples
(or combination of these)
You can combine list/tuples/arrays pretty much any combination is allowed
:Example:
.. doctest:: utils_minmax
>>> s = range(7)
>>> vcs.minmax(s)
... |
def message(instance_id, state, changed=0):
"""Create a message function to send info back to the original function."""
# Changed parameter determines what message to return
if changed != 0:
return_message = ("Instance {} is in {} state").format(instance_id, state)
else:
return_message ... |
def mean(num_list):
"""
Computes the mean of a list of numbers
Parameters
----------
num_list: list of numbers
Returns
-------
res: float
Mean of the numbers in num_list
"""
if not isinstance(num_list, list):
raise TypeError('Invalid input %s Input must be a lis... |
def upper_first(text: str) -> str:
"""
Capitalizes the first letter of the text.
>>> upper_first(text='some text')
'Some text'
>>> upper_first(text='Some text')
'Some text'
>>> upper_first(text='')
''
>>> upper_first(text='_some text')
'_some text'
:param text: to be cap... |
def icingByteFcnPRB(c):
"""Return probability value of icing pixel.
Args:
c (unicode): Unicode icing pixel.
Returns:
int: Value of probability portion of icing pixel.
"""
return ord(c) & 0x07 |
def ChangeExtension(file_name, old_str, new_str):
"""
Change the 'extension' at the end a file or directory to a new type.
For example, change 'foo.pp' to 'foo.Data'
Do this by substituting the last occurance of 'old_str' in the file
name with 'new_str'. This is required because the file name may c... |
def wrap_degrees(a, da):
""" add da to a, but make sure that the resulting angle stays within the -180 to 180 range """
a2 = a + da
while a2 > 180:
a2 -= 360
while a2 < -180:
a2 += 360
return a2 |
def filter_logs(ip, log_lines):
"""Filter the log lines to only those relevant to a particular IP address."""
# First, collect all tokens used by the IP address.
tokens = []
for line in log_lines:
if ip and ip in line:
tok = line.split(', serving ', 1)[1]
tokens.append(tok)
# Filter to only l... |
def hex_str_to_bytes(s_in: str) -> bytes:
"""Used to convert a string from CLI to a bytearray object.
.. warning:: This function assumes that the string consists of only
hexadecimal characters.
"""
return bytes([int(i, 16) for i in s_in.split()]) |
def is_xmfa_blank_or_comment(x):
"""Checks if x is blank or an XMFA comment line."""
return (not x) or x.startswith("=") or x.isspace() |
def sortListsInDict(data, reverse=False):
"""Recursively loops through a dictionary and sorts all lists.
Args:
data(dict): data dictionary
reverse: (Default value = False)
Returns:
: dict -- sorted dictionary
"""
if isinstance(data, list):
if not data:
return... |
def _str2inttuple(s):
"""parse string as tuple of integers"""
return tuple([int(v) for v in s.split('(',1)[1].split(')',1)[0].split(',')]) |
def strtobool(val):
"""
This function was borrowed from distutils.utils. While distutils
is part of stdlib, it feels odd to use distutils in main application code.
The function was modified to walk its talk and actually return bool
and not int.
"""
val = val.lower()
if val in ("y", "yes... |
def valid(passport: dict) -> bool:
"""Return true if all required fields are in passport."""
required = set(["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"])
return required.issubset(set(passport.keys())) |
def strformatted(value, arg):
"""Perform non-magical format of `value` with the format in `arg`.
This is similar to Django's stringformat filter, but don't add the initial
'%' they do. Which allows you to put your value in the middle of other
string.
"""
try:
return str(arg) % value
... |
def element_setup(element_name: str, element_description: dict) -> dict:
"""This is where secondary processing of the YAML data takes place. These method is applied to
every widget.
:param element_name: The base name of the widget being added.
:param element_description: The name of the element being ad... |
def update_parameter_dict(source_dict, update_dict, copy=True):
"""Merges two dictionaries (source and update) together.
It is similar to pythons dict.update() method. Furthermore, it assures that all keys in the update dictionary are
already present in the source dictionary. Otherwise a KeyError is thrown... |
def print_cutoffs(cutoffs):
"""Print cutoff counts."""
lines = []
for key, val in sorted(cutoffs.items()):
lines.append(f' {key}: {val}')
return '\n'.join(lines) |
def complement_base(base, material='DNA'):
"""Return the Watson-Crick complement of a base"""
if base in 'Aa':
if material == 'DNA':
return 'T'
elif material == 'RNA':
return 'U'
elif base in 'TtUu':
return 'A'
elif base in 'Gg':
return 'C'
els... |
def parse_inputspec(input_spec):
"""input_spec=<path>[;rows=<rows>;cols=<cols>;type=<dtype>] (dtype as in cv_image.iterator)"""
parts = input_spec.split(';')
header = dict([tuple(part.split('=')) for part in parts if '=' in part])
rows = int(header['rows']) if 'rows' in header else None
cols = int(h... |
def dictDeleteEmptyKeys(dictionary, ignoreKeys):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
This alters the input so you may wish to ``copy`` the dict first.
Courtesy Chris Morgan and modified from:
https://stackoverflow.com/questions/4255400/exclude-empty-null-values-fr... |
def str_to_pos(chess_notation):
"""converts from chess notation to co-ordinates
>>> str_to_pos("A3")
(0, 5)
>>> str_to_pos("B6")
(1, 2)
"""
letter = chess_notation[0]
x = ord(letter) - ord("A")
y = 8 - int(chess_notation[1])
return x, y |
def _tuples(key, values):
"""list of key-value tuples"""
return [(key, value) for value in values] |
def list_minus(list1, list2):
"""
this function takes in two lists and will return a list containing
the values of list1 minus list2
"""
result = []
zip_object = zip(list1, list2)
for list1_i, list2_i in zip_object:
result.append(list1_i - list2_i)
return result |
def mulr(registers, opcodes):
"""mulr (multiply register) stores into register C
the result of multiplying register A and register B."""
test_result = registers[opcodes[1]] * registers[opcodes[2]]
return test_result |
def fahr_to_celsius(temp):
"""
Convert Fahrenheit to Celsius.
Parameters
----------
temp : int or double
The temperature in Fahrenheit.
Returns
-------
double
The temperature in Celsius.
Examples
--------
>>> from convertempPy import convertempPy as tmp
... |
def compute(x, y):
"""
Return the sum of two integers.
param x: a positive integer between 0-100
param y: a positive integer between 0-100
@return: an Integer representing the sum of the two numbers
"""
if not (isinstance(x, int) and isinstance(y, int)):
return 'Please enter only in... |
def _clockwise(pnt1, pnt2, pnt3):
"""Return True if pnt2->pnt2->pnt3 is clockwise"""
vec1 = (pnt2[0] - pnt1[0], pnt2[1] - pnt1[1])
vec2 = (pnt3[0] - pnt2[0], pnt3[1] - pnt2[1])
return vec1[0] * vec2[1] - vec1[1] * vec2[0] < 0 |
def get_cigar_by_color(cigar_code):
"""
***NOT USED YET***
:param is_in_support:
:return:
"""
if cigar_code == 254:
return 0
if cigar_code == 152:
return 1
if cigar_code == 76:
return 2 |
def simtelSingleMirrorListFileName(
site, telescopeModelName, modelVersion, mirrorNumber, label
):
"""
sim_telarray mirror list file with a single mirror.
Parameters
----------
site: str
South or North.
telescopeModelName: str
North-LST-1, South-MST-FlashCam, ...
modelVe... |
def _get_n_opt_and_check_type_list_argument(
candidate, scalar_type, argument_required, name
):
"""Calculate number of inputs and check input types for argument
that is expected as scalar or list/tuple.
Args:
candidate:
Argument
scalar_type:
Expected type of a s... |
def irangef(start, stop, step=1):
""" Inclusive range with floating point step. Returns a list.
Args:
start : First element
stop : Last element
step : Amount to increment by each time
Returns:
list
>>> irangef(0, 5, 1)
[0, 1, 2, 3, 4, 5]
"""
result = []
... |
def FilterFnTable(fn_table, symbol):
"""Remove a specific symbol from a fn_table."""
new_table = list()
for entry in fn_table:
# symbol[0] is a str with the symbol name
if entry[0] != symbol:
new_table.append(entry)
return new_table |
def _to_camel_case(label, divider = '_', joiner = ' '):
"""
Converts the given string to camel case, ie:
::
>>> _to_camel_case('I_LIKE_PEPPERJACK!')
'I Like Pepperjack!'
:param str label: input string to be converted
:param str divider: word boundary
:param str joiner: replacement for word bounda... |
def phpencode(text, quotechar="'"):
"""Convert Python string to PHP escaping.
The encoding is implemented for
`'single quote' <http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single>`_
and `"double quote" <http://www.php.net/manual/en/language.types.string.php#langua... |
def aliased(aliased_class):
"""
Decorator function that *must* be used in combination with @alias
decorator. This class will make the magic happen!
@aliased classes will have their aliased method (via @alias) actually
aliased.
This method simply iterates over the member attributes of 'aliased_cl... |
def eqn_of_line(x1: float, y1: float, x2: float, y2: float) -> str:
"""
Finds equation of a line passing through two given points.
Parameters:
x1, y1 : The x and y coordinates of first point
x2, y2 : The x and y coordinates of second point
Returns:
... |
def poly_integral(poly, C=0):
"""
Calculates the integral of a polynomial:
poly is a list of coefficients representing a polynomial
the index of the list represents the power of x that the coefficient
belongs to
Example: if [f(x) = x^3 + 3x +5] , poly is equal to [5, 3, 0, 1]
... |
def cmod(n, base):
"""
Compute the modulus of a number like in languages such as C.
:param n: the number to modulus
:param base: the divisor
"""
return n - int(n / base) * base |
def A12_5_2_1(A, Fy, GammaRTt):
"""
Fy = yield stress as defined in A.12.2.2
A = total cross-sectional area
GammaRTt = partial resistance factor for axial tension, 1,05
"""
# Tubular members subjected to axial tensile forces, Put,
# should satisfy:
Put = A * Fy / GammaRTt
#
retu... |
def _is_string(v):
"""
Returns True if the given value is a String.
:param v: the value to check.
:return: True if the value is a String, False if not.
"""
return isinstance(v, str) |
def stripnl(s):
"""remove newlines from a string"""
return str(s).replace("\n", " ") |
def uri_to_fname(uri):
"""
"""
fname = uri.strip().replace('http://', '')
fname = fname.replace('dbpedia.org/ontology', 'dbo')
fname = fname.replace('dbpedia.org/property', 'dbp')
fname = fname.replace('dbpedia.org/resource', 'dbr')
fname = fname.replace('xmlns.com/foaf/0.1', 'foaf')
fn... |
def count_kmers(k,genome,length):
"""
Summary -- Count the kmers of size k in a given sequence
Description -- Determine all of the possible kmers of size k for a
given sequence. Record and count all of the unique (observed) kmers for the sequence.
Parameters:
- k: size of the the subsets
... |
def format_url(url):
"""Fixes telegram url format"""
# Prevent e.g. www.example.com from being interpreted as relative url
if not url.startswith("http") and not url.startswith("//"):
url = f"//{url}"
return url |
def _crc_algo_define(opt, sym):
"""
Get the the identifier for header files.
"""
name = sym['crc_algorithm'].upper().replace('-', '_')
return 'CRC_ALGO_' + name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.