content stringlengths 42 6.51k |
|---|
def combine_dict(*dicts):
"""
:param dict dicts:
:rtype: dict
"""
rst = dict()
for single_dict in dicts:
for key, value in single_dict.items():
assert key not in rst
rst[key] = value
return rst |
def sanitize_state(state):
"""
There's too many places where there's "cancelled" or "canceled" or other weird variants
in both narrative, UJS, and NJS. This is the central spot that attempts to deal with them.
It does this by ONLY returning "canceled" as the state string for use by the front end.
T... |
def deepupdate(original, update):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
elif isinstance(value, list):
update[key]... |
def student_form(students, sid_label, name_label):
"""Convert student dict to a table."""
data = [[sid_label, name_label]]
for key, value in students.items():
data.append([key, value])
return data |
def zfs_size(s):
"""
Convert a zfs size string to gigabytes (float)
"""
if len(s) == 0:
return 0.0
u = s[-1]; q = float(s[:-1])
if u == 'M':
q /= 1000
elif u == 'T':
q *= 1000
elif u == 'K':
q /= 1000000
return q |
def _ras_union_ ( self , another ) :
"""Get an union of two sets
>>> set1 = ...
>>> set2 = ...
>>> set3 = set1.union ( set2 )
"""
Type = type ( self )
result = Type ()
for arg in self : result.add ( arg )
for arg in another :
if not arg in self : result.add ( arg )
... |
def polygon_clip(subjectPolygon, clipPolygon):
"""Clip a polygon with another polygon.
Ref: https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python
Args:
subjectPolygon: a list of (x,y) 2d points, any polygon.
clipPolygon: a list of (x,y) 2d points, has to be *convex*
Note:... |
def default_transformer_poswise_net_hparams(output_dim=512):
"""Returns default hyperparameters of a
:class:`~texar.modules.FeedForwardNetwork` as a pos-wise network used
in :class:`~texar.modules.TransformerEncoder` and
:class:`~texar.modules.TransformerDecoder`.
This is a 2-layer dense network wi... |
def noll_to_zern(j):
"""
Convert linear Noll index to tuple of Zernike indices.
j is the linear Noll coordinate, n is the radial Zernike index and m is the azimuthal Zernike index.
@param [in] j Zernike mode Noll index
@return (n, m) tuple of Zernike indices
@see <https://oeis.org/A176988>.
... |
def matrix_multiply(a, b):
"""
Return the matrix product of a and b.
:param a: the left matrix operand
:param b: the right matrix operand
:return: the matrix product of a and b
"""
result = [[0 for x in range(len(b[0]))] for x in range(len(a))]
for a_row in range(len(a)):
... |
def _find_longest_key_length(dictionary: dict) -> int:
"""Returns the longest string length of a key in the given dictionary."""
length: int = 0
for key in dictionary.keys():
if len(key) > length: length = len(str(key))
return length |
def es_divisible(dividendo, divisor):
"""
(int, int) -> boolean
Determina si un numero es divisible entre otro
>>> es_divisible(10,2)
True
>>> es_divisible(5,4)
False
:param dividendo: el primer numero
:param divisor: el segundo nuemero
:return: True si es divisible, False de l... |
def calc_saturated_fraction(unsatStore, unsatStore_max, alpha):
""" Calculate the saturated fraction of the unsaturated zone
Parameters
----------
unsatStore : int or float
Storage in the unsaturated zone [mm]
unsatStore_max : int or float
Maximum storage in the unsaturated ... |
def decode(x):
"""Decode in case input is bytes-like
"""
try:
x = x.decode()
return x
except:
return x |
def configlet_factinfo(configlet_name, facts, debug=False):
"""
Get dictionary of configlet info from CVP.
Parameters
----------
configlet_name : string
Name of the container to look for on CVP side.
module : AnsibleModule
Ansible module to get access to cvp cient.
debug : b... |
def vhugo(p2, d1, p1, g):
"""
Calculates the velocity along the hugoniot
Input:
p2 - New pressure
d1 - Old density
p1 - Old pressure
g - Adiabatic index
"""
import math
return (math.sqrt(2)*(-p1 + p2))/math.sqrt(d1*((-1 + g)*p1 + (1 + g)*p2)) |
def convert_row_to_sql_tuple(row):
"""
Take an amended source CSV row:
['1', '01001', '2008-01-01', '268', '260', '4', '1', '0', '3', '2891']
and turn it into an SQL load tuple:
"(1,'01001','2008-01-01',268,260,4,1,0,3,2891)"
"""
return "({},'{}','{}',{},{},{},{},{},{},{})".format(*row) |
def get_a_from_coord(coord_row_num,num_of_deformations,a,scale=1):
"""
Routine to get node displacements based on coordinates.
:param int coord_row_num: Node coordinate row number
:param int num_of_deformations: Number of degrees of freedom per node
:param array a: Global displacement vector [1 x t... |
def GI_calc(AUC):
"""
Calculate Gini index.
:param AUC: Area under the ROC
:type AUC: float
:return: Gini index as float
"""
try:
return 2 * AUC - 1
except TypeError:
return "None" |
def _xyz_bc_spec(cell):
"""
Defines the specification for expressing the Boundary Conditions starting
from a cell vector.
Args:
cell (list): array of the (orthorhombic) cell. Should be 0.0 on
directions with free BC. If None is given, the BC are assumed to
be Free.
Return:
... |
def season_diff(x, s):
""" Make seasonal differential.
:param x: data (list)
:param s: length of a season (int)
:return: list
"""
size = len(x)
y = [0] * size
for i in range(size):
y[i] = x[i] - x[i-s] if i-s >= 0 else x[i]
return y |
def File_to_String(file_name):
"""Opens a file and returns the contents as a string"""
in_file=open(file_name,'r')
out_string=in_file.read()
in_file.close()
return out_string |
def int_or_str(value):
"""Returns int value of value when possible"""
try:
return int(value)
except ValueError:
return value |
def validate_triad_var_name(expr: str) -> bool:
"""Check if `expr` is a valid Triad variable name based on Triad standard:
it has to be a valid python identifier and it can't be purly `_`
:param expr: column name expression
:return: whether it is valid
"""
if not isinstance(expr, str) or not ex... |
def cut_suffix(s, suffix):
"""Cuts suffix from given string if it's present."""
return s[:-len(suffix)] if s.endswith(suffix) else s |
def E2L(energy):
"""
energy (ev) to wavelength in meter !!!
"""
return 12398.0 / energy * 1e-10 |
def rst(array):
"""
Returns all but the last element.
"""
*x, _ = array
return x |
def _parse_file(file):
""" parse a single file entry
"""
sfile = file.split(':')
if len(sfile) == 1: # no ':'
path, type = file, ''
elif len(sfile) == 2:
path, type = sfile
elif len(sfile) == 3:
basename, path, type = sfile
else:
raise ValueError('unknown... |
def busquedaBinaria(A, elemento):
"""Algoritmo de busqueda binaria."""
primero = 0
ultimo = len(A) - 1
posicion = -1
encontrado = False
while primero <= ultimo and not encontrado:
mitad = (primero + ultimo) // 2
if A[mitad] == elemento:
encontrado = True
... |
def prepare_params(sort=None, filter=None, params=None):
"""
Prepares the different parameters we want to send as the query in a request
:param sort: str
The sorting (used in list commands issued to the DNSimple API)
:param filter: dict
The filtering (used in list commands issued to the... |
def name2link(name: str):
"""Used for hyperlink anchors"""
if not isinstance(name, str):
name = str(name)
return "-".join([s.lower() for s in name.split(" ")]) |
def extract_history(history_list: list, field: str) -> list:
"""Extract the historical measurements contained in the alerts
for the parameter `field`.
Parameters
----------
history_list: list of dict
List of dictionary from alert['prv_candidates'].
field: str
The field name for ... |
def find_winner(state):
"""Return the winner"""
winning = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7],
[2, 5, 8], [0, 4, 8], [2, 4, 6]]
for combo in winning:
group = list(map(lambda i: state[i], combo))
for player in ['X', 'O']:
if all(x == player for ... |
def is_board_full(board: list) -> bool:
"""return true if board is full else false"""
return all([i != " " for i in board]) |
def _escape_pgpass(txt):
"""
Escape a fragment of a PostgreSQL .pgpass file.
"""
return txt.replace('\\', '\\\\').replace(':', '\\:') |
def escape_text(s):
"""Takes in a string and converts:
* ``&`` to ``&``
* ``>`` to ``>``
* ``<`` to ``<``
* ``\"`` to ``"``
* ``'`` to ``'``
* ``/`` to ``/``
Note: if ``s`` is ``None``, then we return ``None``.
>>> escape_text(None)
None
>>> escape... |
def checksum_handler(value, **kwargs):
"""
Return a list which contains the a checksum hash.
"""
return {'current_filerefs': value} |
def html(text, env={}):
"""Generate HTML for any object with a string representation
Parameters
----------
text : any
Object to be converted to HTML. If the object has a ``.get_html()``
method the result of this method is returned, otherwise ``str(text)``.
env : dict
Environ... |
def _file_name(p_pyhouse_obj, p_file_name):
""" Find the name of the file we will be using.
"""
l_file = 'xxx' # os.path.join(p_pyhouse_obj._Config.ConfigDir, 'Uuid', p_file_name)
return l_file |
def current_role(conn, info):
"""return current role of database"""
_c_role = "primary"
return _c_role |
def job_description(jobs):
"""Return description of jobs for usage string.
"""
job_last = len(jobs) - 1
if job_last <= 0:
return '', -1
job_list = 'Jobs:\n'
for j, descr in enumerate(jobs):
job_list += ' {:3d} {}\n'.format(j, descr)
return job_list, job_last |
def isnumber(num):
""" Checks whether argument is number"""
try:
float(num)
return True
except ValueError:
return False |
def lag_autocov(v, lag):
""" Compute lag autocovariance of a vector
"""
tmp = 0
N = len(v)-lag
for j in range(N):
tmp += v[j]*v[j+lag]
return tmp/N |
def list_diff(list_1, list_2):
"""
Returns the difference between two lists as a list.
Parameters
----------
list_1 : list
First list
list_2 : list
Second list.
Returns
-------
diff_list : list
List containing the diferences between the elements of
... |
def list_equal(_list1, _list2):
"""
are 2x lists equal (deep check)
"""
return len(_list1) == len(_list2) and sorted(_list1) == sorted(_list2) |
def get_setuptools_package_version(setuptools_version: str) -> str:
"""
Generate the right setuptools command for pip command
:param setuptools_version: Setuptools version obtained from
:return: A string formatted for pip install command (e.g setuptools==58.0.0)
"""
setuptools_version = setupto... |
def splitValues(txt, sep=",", lq='"<', rq='">'):
"""
Helper function returns list of delimited values in a string,
where delimiters in quotes are protected.
sep is string of separator
lq is string of opening quotes for strings within which separators are not recognized
rq is string of correspon... |
def fill_input(form: dict, curr_text_input: dict, string: str):
"""
This function makes a deep copy of a form and fills the specified text input with the specified string.
@param form: The current form.
@type form: dict
@param curr_text_input: The current text input tag.
@type curr_text_inp... |
def _derive_enum_name(key: str) -> str:
"""Derive a `CamelCase` name from the `underscore_separated_key`."""
words = key.split('_')
words.append('permission')
return ''.join(word.title() for word in words) |
def get_departuresMock(_stop_id, route, destination, api_key):
"""Mock TransportNSW departures loading."""
data = {
"stop_id": "209516",
"route": "199",
"due": 16,
"delay": 6,
"real_time": "y",
"destination": "Palm Beach",
"mode": "Bus",
}
return d... |
def exact_div(p, d, allow_divzero=False):
"""Find and return an integer n such that p == n * d
If no such integer exists, this function raises ValueError.
Both operands must be integers.
If the second operand is zero, this function will raise ZeroDivisionError
unless allow_divzero is true (defaul... |
def filter_names(
names,
text=""):
"""
Returns elements in a list that match a given substring.
Can be used in conjnction with compare_varnames to return a subset
of variable names pertaining to a given diagnostic type or species.
Args:
names: list of str
Input l... |
def asset_invariant(state: dict, i: int) -> float:
"""Invariant for specific asset"""
return state['R'][i] * state['Q'][i] |
def calc_check_digit(number):
"""Calculate the check digit for the number. The passed number should not
have the check digit included."""
number = number.replace('-', '')
return str(
sum((i + 1) * int(n) for i, n in enumerate(reversed(number))) % 10) |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
remain = []
for i in range(len(nums)):
if nums[i] in remain:
return [remain.index(nums[i]), i]
remain.append(target - nums[i]) |
def _mean(items):
"""Return average (aka mean) for sequence of items."""
return sum(items) / len(items) |
def odd(dim, cycle):
"""Check if dimension if odd and if so increase cycle number by one.
Args:
dim: Dimension of the matrix.
cycle: Number of the current cycle.
Returns:
Adapted cycle number.
"""
if dim%2 != 0:
cycle += 1
return cycle |
def is_empty_or_html(line):
"""Return True for HTML line and empty (or whitespace only) line.
line -- string
The Rfam adaptor that retrieves records inlcudes two HTML tags in
the record. These lines need to be ignored in addition to empty lines.
"""
if line.startswith('<pre') or line.startswi... |
def pad_sentences(sentences, padlen, padding_word="<PAD/>"):
"""
Pads all sentences to the same length. The length is defined by the longest sentence.
Returns padded sentences.
"""
if padlen==None:
sequence_length = max(len(x) for x in sentences)
else:
sequence_length=padlen
... |
def get_class(result, class_label='status'):
"""Get a normalized result for the specified class.
Get a normalized result for the specified class. Currently supported
classes are only one, 'status'. This returns a single value which
defines the class the example belongs to.
"""
if class_label ==... |
def extract_all_words_from_list_names(names_list):
"""
Extract all words from list with snake case names
:param names_list: list
:return: list
"""
word_list = []
for name in names_list:
word_list += name.split("_")
return word_list |
def collapse(list_of_iterables):
"""Reduces list of any iterable that can be converted to a set to non-redundant list of lists
Combines iterables with identical elements and returns list of lists.
**Example input**: [[1,2,3],[3,4],[5,6,7],[1,8,9,10],[11],[11,12],[13],[5,12]]
**Example output**: [[1,2,3... |
def is_palindrome(s: str) -> bool:
"""Determine if `s` is the same forwards and backwards."""
return s == s[::-1] |
def is_tagged_parameter(argument):
"""Return True if the directive argument defines a tagged parameter, and False otherwise."""
return argument.startswith('%') |
def gravity_effect(position, other_position):
"""Return effect other_position has on position."""
if position == other_position:
return 0
elif position > other_position:
return -1
return 1 |
def reflcoeff(Z, Z0=50):
"""
Return the reflection coefficient for a given load impedance Z and line impedance Z0
Returns:
.. math::
\Gamma = \\frac{Z-Z_0}{Z+Z_0}
:example:
.. code-block:: python
Z = 100.
Z0 = 50.
gam = smith.ReflCoeff(Z,Z0)
... |
def gmof(x, sigma):
"""Geman-McClure error function."""
x_squared = x**2
sigma_squared = sigma**2
return (sigma_squared * x_squared) / (sigma_squared + x_squared) |
def sec2hms(seconds):
"""
Convert seconds into a string with hours, minutes and seconds.
Parameters:
* seconds : float
Time in seconds
Returns:
* time : str
String in the format ``'%dh %dm %2.5fs'``
Example::
>>> print sec2hms(62.2)
0h 1m 2.20000s
... |
def build_string(list_of_strings):
"""
In some languages it can be handy to build a class,
commonly called StringBuilder, to mitigate the time
complexity of concatenating multiple strings.
In many languages, including python, a str3 = str1 + str2
operation copies str1 and str2 into a new string ... |
def check(p1, p2):
""" check() calcualtes the number of bulls (blacks) and cows (whites)
of two permutations """
blacks = 0
whites = 0
for i in range(len(p1)):
if p1[i] == p2[i]:
blacks += 1
else:
if p1[i] in p2:
whites += 1
return [blacks, whites] |
def get_group_set(policy):
"""Get the set of group names in a policy
Parameters
----------
policy : dict
Dictionary defining the policy
Returns
-------
set
The group names in the policy
"""
return set(policy.keys()) - {'shared'} |
def backward_propagation(x, theta):
"""
Computes the derivative of J with respect to theta (see Figure 1).
Arguments:
x -- a real-valued input
theta -- our parameter, a real number as well
Returns:
dtheta -- the gradient of the cost with respect to theta
"""
# (approx.... |
def _valid_headerline(l, model='firecloud'):
"""return true if the given string is a valid loadfile header"""
if not l:
return False
headers = l.split('\t')
first_col = headers[0]
tsplit = first_col.split(':')
if len(tsplit) != 2:
return False
if tsplit[0] in ('entity', 'u... |
def fix_path(path: str):
"""
Insert a 'magic prefix' to any path longer than 259 characters.
Workaround for python-Bugs-542314
(https://mail.python.org/pipermail/python-bugs-list/2007-March/037810.html)
:param path: the original path
:return: the fixed path including a prefix if necessary
""... |
def parse_version_string(version):
"""
Returns a tuple containing the major, minor, revision integers
"""
nums = version.split(".")
return int(nums[0]), int(nums[1]), int(nums[2]) |
def changeByteEndianness(inp):
"""
Takes the input string and returns the reverse,
effectively switching the endienness.
"""
return inp[::-1] |
def _c_null_pointer(p):
"""Returns true if ctypes pointer is null."""
return (not bool(p)) |
def sort_link(context, link_text, sort_field, visible_name=None):
"""Usage: {% sort_link "link text" "field_name" %}
Usage: {% sort_link "link text" "field_name" "Visible name" %}
"""
is_sorted = False
sort_order = None
orig_sort_field = sort_field
if context.get('current_sort_field') == ... |
def is_path_removed(patch, path):
"""Returns whether the patch includes removal of the path (or subpath of).
Args:
patch (list): HTTP PATCH request body.
path (str): the path to check.
Returns:
True if path or subpath being removed, False otherwise.
"""
path = path.rstrip("... |
def L_min(m,s):
""" Minimum spherical harmonic degree depends on (m,s). """
return max(abs(m),abs(s)) |
def build_xref_table(table, mini_index):
"""Display XREF table with additional links to objects """
ret = ''
for line, o_num in table:
ret += line.decode('ascii')
if line[:10] != b'0000000000' and o_num != None:
o_gen, o_ver = mini_index[o_num]
ret += ' '
... |
def escape_quotes(qstr):
"""
#FIXME: This *may* prove to be a performance bottleneck and should
perhaps be implemented in C (as it was in 4Suite RDF)
Ported from Ft.Lib.DbUtil
"""
if qstr is None:
return ''
tmp = qstr.replace("\\","\\\\")
tmp = tmp.replace("'", "\\'")... |
def parse_surname_comma_surname_prefix(surname):
"""Separates the surname prefix from the surname, expected input is 'Ham, van der'."""
names = surname.split(',')
surname = names[0].strip()
surname_prefix = ''
if len(names) == 2:
surname_prefix = names[1].strip()
return surname, surname_... |
def normal_range(mean, sd, treshold=1.28):
"""
Returns a bottom and a top limit based on a treshold.
Parameters
----------
treshold : float
maximum deviation (in terms of standart deviation). Following a gaussian distribution, 2.58 = keeping 99%, 2.33 = keeping 98%, 1.96 = 95% and 1.28 = ke... |
def myAtoi(str):
"""
:type str: str
:rtype: int
"""
to_return_val = 0
str = str.strip()
if not str:
return 0
n, sign, carry, start = len(str), 1, 0, 0
if str[0] in ["-", "+"]:
start = 1
if str[0] == "-":
sign = -1
for i in ... |
def find_next_matching_line(key, cursor):
"""
Determine the distance into a file (searching forward from the
given cursor) to the next match against a given key. Used to
determine which is the closest key to resync towards.
Returns None if there is no key or no line found.
If the key is alrea... |
def __warn__(err):
"""
Color an warning error message
**Positional Arguments:**
err:
- The message to be displayed
**Returns:**
- A yellowish colored message
"""
return "\x1B[33mWARNING: {}\x1B[0m".format(err) |
def verify_filename(filename: str) -> str:
""" Check file name is accurate
Args:
filename (str): String for file name with extension
Raises:
ValueError: Provide filename with extensions
ValueError: Specify a length > 0
Returns:
str: Verified file name
"""
if le... |
def draw_truth_table(boolean_fn):
""" This function prints a truth table for the given boolean function.
It is assumed that the supplied function has three arguments.
((bool, bool, bool) -> bool) -> None
If your function is working correctly, your console output should look
like th... |
def sum_series(n, n1=0, n2=1):
"""Find nth value in a mathematical series, starting with 2 arbitrary numbers.
input: n (int) n for nth value in sequence
input: n1 (int) optional, represents val at sequence n=0
input: n2 (int) optional, represents val at sequence n=1
returns: (int) representing valu... |
def status_value(
status_int # type: int
):
"""Parse InMon-defined transaction status"""
if status_int == 0:
return "Succeeded"
elif status_int == 1:
return "Generic Failure"
elif status_int == 2:
return "Out of Memory"
elif status_int == 3:
return "Timeout"
elif status_int == 4:
return "Not Permitted... |
def get_pgeom(aor, e):
"""
The geometric transit probability.
See e.g. Kipping (2014) for the eccentricity factor
http://arxiv.org/abs/1408.1393
:param aor: the dimensionless semi-major axis (scaled
by the stellar radius)
:param e: the orbital eccentricity
"""
... |
def process_param(param, offset):
"""Process a single parameter produced by `get_function_parameter_names`."""
# Ignore args with default values, since Rope considers them assignments.
if "=" in param:
return []
# Strip off any type annotation.
first_colon_index = param.find(":")
if fir... |
def solve(task):
"""Solve puzzle.
Args:
task (str): Puzzle input
Returns:
int: Puzzle solution
"""
return task.count("(") - task.count(")") |
def date_from(days, relative_to=(2020, 1, 1)):
"""
Converts a date into a number of days.
:arg days: A :class:`float` the number of days since ``relative_to``.
:arg relative_to: A :class:`tuple` specifying the date to which ``date``
will be compared when computing the number of days.
D... |
def unique(iterable):
"""Uniquify elements to construct a new list.
Parameters
----------
iterable : collections.Iterable[any]
The collection to be uniquified.
Returns
-------
list[any]
Unique elements as a list, whose orders are preserved.
"""
def small():
... |
def insertion_sort(A):
"""
Sort list A into order, in place.
From Cormen/Leiserson/Rivest/Stein,
Introduction to Algorithms (second edition), page 17,
modified to adjust for fact that Python arrays use
0-indexing.
"""
for j in range(len(A)):
key = A[j]
# inse... |
def check_equal_sequence(sup_token_list, entity_token_list):
"""
Whether two sequence lists are identical
:param sup_token_list:
:param entity_token_list:
:return:
"""
import operator as op
for i in range(0, len(entity_token_list)):
if op.eq(sup_token_list[i].lower(), entity_toke... |
def _flatten(list_):
"""Flatten a list of lists into a 1D list."""
return [item for sublist in list_ for item in sublist] |
def normalize_archive_entry_name(name):
"""
Get the normalized name of an archive file entry.
Args:
name (str): Name of the archive file entry.
Returns:
str: The normalized name.
"""
return name.replace('\\', '/') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.