content stringlengths 42 6.51k |
|---|
def get_payloads(data):
"""
Generates a dictionary which specifies which payloads are active in a given profile and what their current
version numbers are.
:param data: Form data (Dictionary)
:returns: Dictionary of payload versions
"""
types = ['store', 'siri', 'desktop', 'dock', 'energy',... |
def _build_url(*args):
"""Build string url
Disappointed in urllib.parse library because it does give the richness to build
arbitrary URLs"""
return "/".join(args) |
def compare_and_swap(src, dst, knapsack=None):
"""
:param dict src:
:param dict dst:
:param set knapsack:
:return: dict
"""
knapsack = knapsack or set()
if set(src.keys()) <= set(dst.keys()):
for key in src:
item = dst[key]
if isinstanc... |
def set_ext_api(file_path):
"""Smart Function to set Extension."""
ext = file_path.split('.')[-1]
if ext == 'plist':
return 'plist'
elif ext == 'xml':
return 'xml'
elif ext in ['sqlitedb', 'db', 'sqlite']:
return 'db'
elif ext == 'm':
return 'm'
else:
... |
def mdot(snu, nu=10, Te=1e4, vinf=2000, mue=1.3, d=1):
"""
[snu] = mJy
nu = 10 GHz (frequency)
Te = 10^4 K (ionized gas temp)
vinf = 2000 km/s (maximum wind speed)
mue = 1.3 (mean atomic weight per free electron)
d = distance (kpc)
return: mdot in Msun/yr
"""
mdot = ( snu / 7.26... |
def chat_words_conversion(text, chat_words_list, chat_words_map_dict):
"""Function to convert the chat words"""
new_text = []
for w in text.split():
if w.upper() in chat_words_list:
new_text.append(chat_words_map_dict[w.upper()])
else:
new_text.append(w)
return " ... |
def checkbox_property(question):
"""
Convert a checkbox question into JSON Schema.
"""
return {question['id']: {
"type": "array",
"uniqueItems": True,
"minItems": 0 if question.get('optional') else 1,
"maxItems": question.get('number_of_items', len(question['options'])),
... |
def _format_ip6(addr):
"""Return a string holding the human-friendly version of the IPv6
address *addr* in an integer representation.
"""
power = 112
res = ""
while power > 0:
# in format strings the arguments must be numbered before python2.7
res = res + "{0:04x}".format((addr >... |
def three_way_radix_quicksort(sorting: list) -> list:
"""
Three-way radix quicksort:
https://en.wikipedia.org/wiki/Quicksort#Three-way_radix_quicksort
First divide the list into three parts.
Then recursively sort the "less than" and "greater than" partitions.
>>> three_way_radix_quicksort([])
... |
def isSectionSingular(hints, i, j, e):
"""Check if a section contains only one cell that is valid for e"""
count = 0
secTopX, secTopY = 3 * (i//3), 3 * (j//3)
for x in range(secTopX, secTopX+3):
for y in range(secTopY, secTopY+3):
count += hints[x][y].count(e)
return count == 1 |
def hex_str_to_int(input_str):
"""
Converts a string with hex bytes to a numeric value
"""
try:
val_to_return = int(input_str, 16)
except Exception as e:
val_to_return = 0
print('Exception converting hex to int: {}'.format(e))
return val_to_return |
def get_steer_angle(list_angles_pairs, max_allowed_angle):
"""
:param list_angles_pairs: list of tuples, where each tuple represents angular bounds of navigable-beam (in degrees)
:param max_allowed_angle: maximum value for angular direction in degrees. in rover terms, left corresponds to positive, right neg... |
def strtofloat(aList):
""" Converts string elements in list to float """
x = []
try:
x = list(map(float,aList))
except ValueError:
print("Error! Check if financial data is available. Common" +
" culprits: interest expense, tax expense.")
raise
return x |
def ignore_retention_enabled(configurations):
"""Given a bunch of configs, check for special 'ignore retention' flag"""
for config in configurations:
ignored = config.get('ignore_retention', False)
return bool(ignored)
return False |
def iris_classifier(verbose=True):
"""Iris classifier trained model loader."""
model = None
return model |
def int_to_hex(integer: int, width: int = 8) -> str:
"""Converts integer to hex string
Parameters
----------
integer : int
integer to convert
width : int, optional
width of hex output (used for zero padding), default=8
Returns
-------
str
hexadecimal array as s... |
def normalize_deps(dep_map):
"""Returns a copy of *dep_map* with no duplicate dependencies for a
given target, and all dependencies properly represented as targets.
"""
ret = type(dep_map)() # work with dict/OrderedDict/etc.
for k, _deps in dep_map.items():
cur_seen = set()
ret[k] ... |
def GastonJ(Z, p=None, Z0=None, ET=None):
""" Z = GastonJ(Z, p)
Args:
Z: real or complex matrix, array
p: real or complex parameters (matrix, array)
Returns:
Z: the result (complex)
workable parameters:
separable = 0.7958 + 0.1893j
iconic = 0.7757 + 0.1234j
s... |
def join_smoothed_files(smoothed_normalized_files):
"""
Joins outputs
"""
return [[x for smooth in subject for x in smooth] for subject in zip(*smoothed_normalized_files)] |
def get_acc_block_for_time(time_first_sample,list_acc_frontiers):
"""
Get accumulation block id.
Parameters
----------
time_first_sample : float
[s].
list_acc_frontiers : list of floats
generated with get_list_acc_frontiers().
Returns
-------
index_fron... |
def countSetBits(m):
"""Counts the number of bits that are set to 1 in a given integer."""
count = 0
while (m):
count += m & 1
m >>= 1
return count |
def is_text_string(obj):
"""Return True if `obj` is a text string, False if it is anything else,
like binary data."""
return isinstance(obj, str) |
def ApplyMaxPerRun(tests, max_per_run):
"""Rearrange the tests so that no group contains more than max_per_run tests.
Args:
tests:
max_per_run:
Returns:
A list of tests with no more than max_per_run per run.
"""
tests_expanded = []
for test_group in tests:
if type(test_group) != str:
... |
def nbr_virgule(s):
""" Compte le nombre de virgule dans un mot"""
n = 0
for k in s:
if k == ',':
n+=1
return n |
def build_property_list(config_dict):
""" Build a list of properties and values that will end up in junit xml. This should only
be used for testing purposes to set expectations.
Args:
config_dict: a python object representation of pytest_zigzag config json
Returns:
props: a flatten... |
def _create_bonus_deck(highest_tile=3):
"""Bonus Deck for game of Threes!
The smallest bonus tile is 6. The maximum number of tiles in a bonus
deck is 3. The values of the bonus deck tiles are 1/8, 1/16 and 1/32
of the highest tile value on the board. If any of the bonus deck
tile values would b... |
def words(word_statement):
"""
function that counts the number of word occurance in the input and return a dictionary
the dictionary contains the word as the key and the total number of occurance as the value
"""
wordcount={}
for word in word_statement.split():
"""
type cast ... |
def read_k_bytes(sock, remaining=0):
"""
Read exactly `remaining` bytes from the socket.
Blocks until the required bytes are available and
return the data read as raw bytes. Call to this
function blocks until required bytes are available
in the socket.
Arguments
---------
sock : So... |
def circle_line_segment_intersection(circle_center, circle_radius, pt1, pt2, full_line=True, tangent_tol=1e-13):
""" Find the points at which a circle intersects a line-segment. This can happen at 0, 1, or 2 points.
:param circle_center: The (x, y) location of the circle center
:param circle_radius: T... |
def lorentz(v, v0, I, w):
"""
A lorentz function that takes linewidth at half intensity (w) as a
parameter.
:param v: Array of values at which to evaluate distribution.
:param v0: Center of the distribution.
:param w: Peak width at half max intensity
:returns: Distribution evaluated at poin... |
def scale(x: float, original: float, new: float) -> float:
"""
Scale a value "x" from the "original" to the "new" frame of reference.
"""
return (x * new) / original |
def convert_py_namespace_to_cpp_header_def(python_namespace: str) -> str:
"""Convert a Python namespace into a C++ header def token.
Parameters
----------
python_namespace : `str`
A string describing a Python namespace. For example,
``'lsst.example'``.
Returns
-------
cpp_h... |
def xoRef(game_result):
"""
This module is intended to accept a list of rows from a tic-tac-toe game and
determine who the winner is. It will return X, O or D for X, O or Draw
a sample result would be:
game_result=[u'OO.', u'XOX', u'XOX']
"""
winner='D'
#check horiz winner... |
def find_unfinished_neighbors(board, n_bomb, squares):
"""
Returns a list of squares that have not discovered all their bombs yet
and are neighbors to the squares parsed in the 'squares' list.
"""
unfinished = []
for row, column in squares:
for i in range(max(0, row - 1), min(len... |
def find_files_recursive(directory, pattern='*'):
"""
Return matched filenames list in a given directory (including subdirectories) for a given pattern
https://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python
"""
import os, fnmatch
matches = []
for root, _, ... |
def int_to_bytes(integer):
"""
Convert an int to bytes
:param integer:
:return: bytes
"""
return integer.to_bytes((integer.bit_length() + 7) // 8, 'big')
# alternatively
# return bytes.fromhex(hex(integer)[2:]) |
def edgelist_to_adjacency(edgelist):
"""Converts an iterator of edges to an adjacency dict.
Args:
edgelist (iterable): An iterator over 2-tuples where
each 2-tuple is an edge.
Returns:
dict: The adjacency dict. A dict of the form {v: Nv, ...} where
v is a node in a grap... |
def first_index_not_below(arr, t):
"""Return first index of array >= t, or len(arr) if no such found"""
for i, x in enumerate(arr):
if x >= t:
return i
return len(arr) |
def parser_cell_list_Descriptor(data,i,length,end):
"""\
parser_cell_list_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "cell_list", "contents" : unparsed_descriptor_contents }
(Defined in ... |
def concatenate_delete_returns(*args):
"""
This method allow to concatenate the return values of multiple deletes.
This is useful when we override a delete method so it automatically deletes other objects we can then return
an accurate result of the number of entities deleted.
"""
# the return o... |
def give_back_array_full_of_empty_string(table):
"""
give_back_array_full_of_empty_string
"""
for posX in range(0,len(table)):
for posY in range(0,len(table[posX])):
table[posX][posY]=''
return table |
def urldecode(s, ignore_invalid = False):
"""urldecodes a string"""
import re
res = ''
n = 0
while n < len(s):
if s[n] != '%':
res += s[n]
n += 1
else:
cur = s[n+1:n+3]
if re.match('[0-9a-fA-F]{2}', cur):
res += chr(int(... |
def make_course_key_str(org, number, run='test-run'):
"""
Helper method to create a string representation of a CourseKey
"""
return 'course-v1:{}+{}+{}'.format(org, number, run) |
def SetEnumerable(service, enum, value):
"""This method will generate and return an instance of enum.value."""
if enum == None or value == None:
return None
else:
return getattr(service.factory.create(enum), value) |
def get_line_thickness(weight):
"""
Determine radius of cylinder based on weight of contact edge
Parameters
----------
weight: float
Edge weight
Return
------
radius: float
Radius of sphere
"""
min_width = 0.01
max_width = 0.5
radius = float(weight)*max_... |
def break_words(stuff, sep = " "):
"""This function breaks up words for us."""
words = stuff.split(sep)
return words |
def is_anagram(s,t):
"""True if strings s and t are anagrams.
"""
# We can use sorted() on a string, which will give a list of characters
# == will then compare two lists of characters, now sorted.
return sorted(s)==sorted(t) |
def get_overlay_position(argument):
"""
Determines the position the user wants the watermark overlay to be in.
Returns a string containing the shorthand version of the four valied positions.
Returns "br" if no valid position can be found in `argument`.
"""
if argument:
if "tl" in argumen... |
def dict_slice(Dict, *keys):
"""Returns a shallow copy of the subset of a given dict (or a dict-like
object) with a given set of keys.
The return object is a dict.
No keys may be missing from Dict.
Example: if d = {'abc': 12, 'def': 7, 'ghi': 32, 'jkl': 98 }
then dict_slice(d, 'abc', 'ghi') will yield {'ab... |
def has_duplicates(input_list):
"""
:rtype: bool
:param input_list: A list of values
:return: returns True if there are any duplicate elements
"""
if input_list is None:
return False
unique = set(input_list)
if len(unique) == len(input_list):
return False
return True |
def convert_to_list(string):
"""
Takes in a string of numbers and returns a list of numbers.
>>> convert_to_list("4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 5")
[4, 5, 5, 6, 7, 3, 7, 5, 8, 6, 8, 9, 9, 8, 5, 5]
"""
lst = []
for i in string.replace(' ', ''):
lst.append(int(i))
return lst |
def search_url_from_id(gebid, raumartid = None):
"""
returns the url for a search on the university website based on one building and one room type
"""
template = 'https://www-sbhome1.zv.uni-wuerzburg.de/qisserver/rds?state=wsearchv&search=3&raum.gebid={}&P_start=0&P_anzahl=50&_form=display'
url = t... |
def add_weights_to_samples(weights, unweighted_samples):
"""
Combine weights and unweighted samples into a list of lists:
[[w1, [particle_state]], [w2, [particle_state2]], ...]
:param weights: Sample weights
:param unweighted_samples: Sample states
:return: list of lists
"""
weighted_sam... |
def markup_line(text, offset, marker='>>!<<'):
"""Insert `marker` at `offset` into `text`, and return the marked
line.
.. code-block:: python
>>> markup_line('0\\n1234\\n56', 3)
1>>!<<234
"""
begin = text.rfind('\n', 0, offset)
begin += 1
end = text.find('\n', offset)
... |
def argmin(l, f):
"""
@param l: C{List} of items
@param f: C{Procedure} that maps an item into a numeric score
@returns: the element of C{l} that has the lowest score
"""
vals = [f(x) for x in l]
return l[vals.index(min(vals))] |
def reason(store, reasoner="rdfs++"):
"""
Create a session spec that adds reasoning support to another session.
:param store: Base session spec.
:type store: string
:param reasoner: Reasoning type (e.g. `"rdfs++"`or `"restriction"`).
:type reasoner: string
:return: A session spec string.
... |
def get_time_in_seconds(timeval, unit):
"""
Convert a time from 'unit' to seconds
"""
if 'nyear' in unit:
dmult = 365 * 24 * 3600
elif 'nmonth' in unit:
dmult = 30 * 24 * 3600
elif 'nday' in unit:
dmult = 24 * 3600
elif 'nhour' in unit:
dmult = 3600
elif '... |
def get_binding(config_dict):
"""Get the binding for the WeeWX database."""
# Extract our binding from the StdArchive section of the config file. If
# it's missing, return None.
if 'StdArchive' in config_dict:
db_binding_wx = config_dict['StdArchive'].get('data_binding',
... |
def toCamel(name):
"""
Return a string formatted to 'camelCase'
"""
split = name.split()
split[0] = '{0}{1}'.format(split[0][0].lower(), split[0][1:])
return ''.join(split) |
def is_str_int_float_bool(value):
"""Is value str, int, float, bool."""
return isinstance(value, (int, str, float)) |
def parse_file(path):
"""
Analisys text file,return space, tab, row and so on.
:arg path: parse text file path
:return: include count space, tab, row and so on for tuple
"""
fd = open(path)
i = 0
spaces = 0
tabs = 0
for i,line in enumerate(fd):
spaces += line.count(' ')
... |
def truncate_text(text: str, length: int) -> str:
"""
Truncate the text to the given length. Append an ellipsis to make it clear the
text was truncated.
Args:
text: The text to truncate.
length: Maximum length of the truncated text.
Returns:
The truncated text.
"""
trunc... |
def id_to_index(seqid):
"""
Convert a string to a poisitive integer
:param seqid: The sequence ID
:type seqid: str
:return: The positive integer corresponding to the ID
:rtype: int
"""
return hash(seqid) & 0x7FFFFFFF |
def inCol(i,j,n):
"""Gibt an, ob sich die Felder i und j auf einem n*n Schachbrett in der
selben Spalte befinden.
"""
return (i%n)==(j%n) |
def part_1b_under_equilb_design_ensemble_run_limit(job):
"""Check that the equilbrium design ensemble run is under it's run limit."""
try:
if (
job.doc.equilb_design_ensemble_number
>= job.doc.equilb_design_ensemble_max_number
):
job.doc.equilb_design_ensemble... |
def minutes_to_human_duration(minutes_duration):
"""
Convert a duration in minutes into a duration in a cool format human readable
"""
try:
hours,minutes = divmod(minutes_duration,60)
return "%sh %smin" %(hours,minutes)
except TypeError:
return None |
def getCommonTimeOffsets(arr1, arr2, timeStep):
"""
this function is useful for aligning data points from discontinuous
data arrays with different start times but common sampling
frequencies. For instance, call this function to find synchronized
data values in F0 and SPL analysis data as calculated via the modu... |
def matrixProd(_mat1, _mat2):
"""Columns of first matrix must be equal to rows of the second matrix"""
assert(len(_mat1[0]) == len(_mat2))
"""Initialize the result matrix"""
result = [[0 for col in range(len(_mat2[0]))] for row in range(len(_mat1))]
for i in range(len(_mat1)):
for j in rang... |
def delete_mapping(module, sdk, cloud, mapping):
"""
Attempt to delete a Mapping
returns: the "Changed" state
"""
if mapping is None:
return False
if module.check_mode:
return True
try:
cloud.identity.delete_mapping(mapping)
except sdk.exceptions.OpenStackCloud... |
def cleanurl(s):
"""
Change /path/index.html to /path/.
"""
if s.endswith('/index.html'):
return s[:-10]
return s |
def prime(num):
"""
Takes a number and returns True if the number is prime, otherwise False
:param num: int
:return: bool
"""
prime = []
ans = True
for n in range(1, num+1):
if num % n == 0:
prime.append(n)
if len(prime) > 2:
ans = False
return ans |
def getmaxlens(rows):
"""Get most length in rows and cols"""
maxrowlen = 0
maxcollen = 0
for r in rows:
maxrowlen = max(maxrowlen, len(r))
for c in r:
maxcollen = max(maxcollen, len(c))
return maxrowlen, maxcollen |
def has_juniper_error(s):
"""Test whether a string seems to contain an Juniper error."""
tests = (
'unknown command.' in s,
'syntax error, ' in s,
'invalid value.' in s,
'missing argument.' in s,
)
return any(tests) |
def parse_anchor_spec(s):
"""
Return a tuple, or None on error.
"""
if "=" not in s:
return None
return tuple(s.split("=", 1)) |
def walk(path, container):
"""
Recurse over the ActBlue JSON object, and get the values that we need,
based on the settings file.
Returns a single value for each path.
"""
if not container or isinstance(container, str):
return None
key = path[0]
if len(path) == 1:
if key... |
def to_fractional_rgb(rgb: tuple) -> tuple:
"""
Convert color (h, s, l) to a fractional form (fr, foreground, fb) where fr foreground and fb are float values
between 0 and 1. This is useful when interfacing with the in built python library colorsys
:param rgb: rgb tuple (h, s, l) where h s and l lie be... |
def single_defcom_extract(start_from, srcls, is_class_begin=False):
"""
to extract a def function/class/method comments body
Args:
start_from(int): the line num of "def" header
srcls(list): the source file in lines
is_class_begin(bool): whether the start_from is a beginning a class.... |
def float_or_star(value):
""" Parses a string value that is either a floating point value or the '*'
character. Raises a `ValueError` if no float could be parsed.
"""
if value == "*":
return None
return float(value) |
def extensionize(ext: str) -> str:
"""Ensure extensions are prefixed with a dot."""
return f".{ext}" if ext[0].isalpha() else ext |
def hex_str_to_int(hex_str: str):
"""'#ffffff' -> 0xffffff"""
if "#" in hex_str:
return int(hex_str[1:], 16)
else:
return int(hex_str, 16) |
def cleanup_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:-1])
# remove `foo`
return content.strip("` \n") |
def to_similarity(distance, length):
"""Calculate a similarity measure from an edit distance.
**Args**:
* distance (int): The edit distance between two strings.
* length (int): The length of the longer of the two strings the\
edit distance is from.
**Returns**:
A similarity value from... |
def splitHeight(total_height):
"""
Takes a single integer value, the total height in inches, and
returns a tuple of integers representing the total height
in terms of feet and inches.
Example:
splitHeight(68) = (5, 8)
"""
feet = total_height // 12
inches = total_height % 12
return (feet,... |
def get_phase_start_stop(data):
"""
Get start and stop for a phase or subphase from the input time series data where start is
indicated by a value of 1 and stop is indicated by a value of 0 in the time series data
:param data: the time series data list
:return: the indices in the data list for ... |
def xvariation(C0: float, er: float, area_cm: float):
"""
Estimates the quantity
eps*A / C0 = x_e + eps*F_e/rho_e
which corresponds to variations in the depletion width over approximately
the same distance scale.
Parameters
----------
C0: float
The fitted value of... |
def radix_sort_decimal_integers(arr):
"""Radix sort implementation for integers
d = len(str(max_value))
k = 10 as decimals (base 10)"""
max_value = max(arr) # use to know number of digits
digits = len(str(max_value)) # fo... |
def sum_(s):
"""
Sum items of a list
:param s:
:return:
"""
sumd = 0
for l in s:
sumd += l
return sumd |
def tupleize(x):
"""
Coverts x into a tuple, either as a direct cast or by making it the sole
element of a tuple.
Parameters
----------
x : object
Returns
-------
tuple
"""
try:
return tuple(x)
except TypeError:
return (x,) |
def bound(pair, x):
"""
@returns Whether parameter in bound
"""
return pair[0] - 3. * pair[1] <= x <= pair[0] + 3. * pair[1] |
def display_dup(dup_result):
"""Display the duplication check results."""
lines = [k + ": " + ", ".join(v) for k, v in dup_result]
return lines |
def add_lowercase_context_to_sequences(seq, uc_s, uc_e,
convert_to_rna=False):
"""
Given a sequence and uppercase middle region start (uc_s) and end (uc_e),
make context region upstream + downstream lowercase.
Two coordinates should be one-based.
Return lowerca... |
def calculate_boundaries(dist_args1, dist_args2, dist_type, shift):
"""
Calculate minimum and maximum reward possible for certain distribution types.
For normal distribution take 3 times standard deviation. These minimum and maximum
are used to determine the bin sizes.
:param dist_args1: parameter o... |
def get_pairs(dims):
"""
Get unique combinations of indices for the specified dimensions
>>> get_pairs(4)
((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3))
"""
return tuple((i, j) for i in range(dims) for j in range(i+1, dims)) |
def isCacheFile(filePath):
"""Checks if the file is a cache type file without an extension, given:
filePath: The file path (string)
"""
index = filePath.rfind(".")
return index == -1 |
def remove_command(commands: str, output: str) -> str:
"""Remove anything before the command if found in output."""
_output = output.strip().split("\n")
for command in commands:
for line in _output:
if command in line:
idx = _output.index(line) + 1
_outpu... |
def t_bold(s):
"""
Returns string s wrapped in terminal bold font code
"""
return '\033[1m' + s + '\033[0m' |
def rstrip(s, ch):
"""Replacement for str.rstrip (support for arbitrary chars to strip was
added in Python 2.2.2)."""
try:
if s[-1] != ch:
return s
i = -2
while s[i] == ch:
i = i-1
return s[:i+1]
except IndexError:
return "" |
def second_part(txt):
"""Second logical part for password."""
return txt[0].lower() |
def add(a, b):
"""add task"""
c = a + b
print("{} + {} = {}".format(a, b, c))
return c |
def _require_hash(value):
"""
Utility function that tries to take the hash value of the value normally,
otherwise, returns its object ID.
Basically a way to force a value to produce some kind of hash,
with less worry as to whether that hash reflects its true equality.
Indeed, not every class tha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.