content stringlengths 42 6.51k |
|---|
def cval(x,digits=2,py2=False) :
""" routine to convert value to "Kurucz-style" string, i.e. mXX or pXX
Args:
x (float) : value to put into output format
Returns :
(str) : string with output
"""
if x < -0.000001 :
prefix = 'm'
else :
prefix = 'p'
formstr='{{:0{:d... |
def sd(array):
"""
Calculates the standard deviation of an array/vector
"""
import statistics
return statistics.stdev(array) |
def make_plural(name):
"""Returns the plural version of the given name argument.
Originally developed for Stalker
"""
plural_name = name + "s"
if name[-1] == "y":
plural_name = name[:-1] + "ies"
elif name[-2:] == "ch":
plural_name = name + "es"
elif name[-1] == "f":
... |
def cxxs(q, ip):
"""
Single charge exchange cross section according to the Mueller Salzborn formula
Parameters
----------
q : int
Charge state of the colliding ion
ip : float
<eV>
Ionisation potential of the collision partner (neutral gas)
Returns
-------
fl... |
def myreplace(old, new, s):
""" Replace all occurrences of old with new in s. """
s = " ".join(s.split())
return new.join(s.split(old)) |
def require_package(name):
""" Set a required package in the actual working set.
Parameters
----------
name: str
The name of the package.
Returns
-------
bool:
True if the package exists, False otherwise.
"""
try:
import pkg_resources
pkg_resources.... |
def default_user_agent(name="python-requests"):
"""
Return a string representing the default user agent.
:rtype: str
"""
return f"{name}/1.0" |
def escape_content(string: str) -> str:
"""
Escapes given input to avoid tampering with engine/block behavior.
"""
if string is None:
return
return pattern.sub(_sub_match, string) |
def latin1_encode(text):
""" latin1 encode """
try:
text.encode("latin1")
except UnicodeEncodeError as err:
return str(err)
return None |
def descendants_to_path(path: str):
"""Get the descendants to a path.
:param path: The path to the value
:return: The descendants to the path
"""
parts = path.split(".")
return [path.rsplit(".", i)[0] for i in reversed(range(len(parts)))] |
def b_prolate(kappa):
"""
0 = prolate <= b_P <= -1 = oblate
Townes and Schawlow, Ch. 4
"""
return (kappa+1.)/(kappa-3.) |
def slack_escape(text: str) -> str:
"""
Escape special control characters in text formatted for Slack's markup.
This applies escaping rules as documented on
https://api.slack.com/reference/surfaces/formatting#escaping
"""
return text.replace("&", "&").replace("<", "<").replace(">", ">... |
def acceleration_to_dxl(value, model):
"""Converts from degrees/second^2 to ticks"""
return int(round(value / 8.583, 0)) |
def at(offset, source_bytes, search_bytes):
"""returns True if the exact bytes search_bytes was found in source_bytes at offset (no wildcards), otherwise False"""
return source_bytes[offset:offset+len(search_bytes)] == search_bytes |
def add_metadata_columns_to_schema(schema_message):
"""Metadata _sdc columns according to the stitch documentation at
https://www.stitchdata.com/docs/data-structure/integration-schemas#sdc-columns
Metadata columns gives information about data injections
"""
extended_schema_message = schema_message
... |
def num_digits(n):
"""
Given a number n, this function returns its number of digits in base 10.
"""
return len(str(n)) |
def vowelsRemover(words):
"""This function takes in a string
and returns a string back without vowels"""
m_vowels = ['a', 'e', 'i', 'o', 'u']
m_temp = ""
for letter in words:
if letter.lower() not in m_vowels:
m_temp += letter
return m_temp |
def duplicate_object_hook(ordered_pairs):
"""Make lists out of duplicate keys."""
json_dict = {}
for key, val in ordered_pairs:
existing_val = json_dict.get(key)
if not existing_val:
json_dict[key] = val
else:
if isinstance(existing_val, list):
... |
def public_dict(d: dict) -> dict:
"""Remove keys starting with '_' from dict."""
return {
k: v for k, v in d.items() if not (isinstance(k, str) and k.startswith("_"))
} |
def all_subclasses(cls):
"""Return a set of subclasses of a given cls."""
return set(cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in all_subclasses(c)]) |
def makelol(inlist):
"""
Converts a 1D list to a 2D list (i.e., a list-of-lists). Useful when you
want to use put() to write a 1D list one item per line in the file.
Usage: makelol(inlist)
Returns: if l = [1,2,'hi'] then returns [[1],[2],['hi']] etc.
"""
x = []
for item in inlist:
x.append([item... |
def batch_action_template(form, user, translations, locale):
"""Empty batch action, does nothing, only used for documentation.
:arg BatchActionsForm form:
the form containing parameters passed to the view
:arg User user: the User object of the currently logged-in user
:arg QuerySet translations... |
def validateDict(user_cfg={}, defaults={}):# dict
"""
validates a dictionary by comparing it to the default values from another
given dict.
"""
validated = {}
for each in defaults:
try:
validated[each] = user_cfg[each]
except KeyError:
validated[each] = d... |
def lcs(a, b):
"""Longest common substring of two strings."""
lengths = [[0 for j in range(len(b) + 1)] for i in range(len(a) + 1)]
# row 0 and column 0 are initialized to 0 already
for i, x in enumerate(a):
for j, y in enumerate(b):
if x == y:
lengths[i + 1][j + 1] =... |
def _GetFailedRevisionFromCompileResult(compile_result):
"""Determines the failed revision given compile_result.
Args:
compile_result: A dict containing the results from a compile. Please refer
to try_job_result_format.md for format check.
Returns:
The failed revision from compile_results, or None i... |
def type(record):
"""
Put the type into lower case.
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "type" in record:
record["type"] = record["type"].lower()
return record |
def switch_block_hash(switch_block) -> str:
"""Returns hash of most recent switch block.
"""
return switch_block["hash"] |
def get_pred_item(list_, index, key):
""" retrieves value of key from dicts in a list"""
dict_ = list_[index]
return dict_.get(key) |
def get_story_memcache_key(story_id, version=None):
"""Returns a memcache key for the story.
Args:
story_id: str. ID of the story.
version: str. Schema version of the story.
Returns:
str. The memcache key of the story.
"""
if version:
return 'story-version:%s:%s' % ... |
def flatten_dict(data, sep='.', prefix=''):
"""Flattens a nested dict into a dict.
eg. {'a': 2, 'b': {'c': 20}} -> {'a': 2, 'b.c': 20}
"""
x = {}
for key, val in data.items():
if isinstance(val, dict):
x.update(flatten_dict(val, sep=sep, prefix=key))
else:
x[f... |
def lte(value, arg):
"""Returns a boolean of whether the value is less than or equal to the
argument.
"""
return value <= int(arg) |
def prep_grid(D):
"""
:param D: Dict of dicts
:return:
"""
try:
return {key:[{key:val} for val in D[key]] for key in D}
except:
return {} |
def tap(callback, func, *args, **kwargs):
"""What does this even accomplish..."""
result = func(*args, **kwargs)
callback(result)
return result |
def calc_num_opening_mismatches(matches):
"""(Internal) Count the number of -1 entries at the beginning of a list of numbers.
These -1 correspond to mismatches in the sequence to sequence search.
"""
if matches[0] != -1:
return 0
num = 1
while matches[num] == -1:
num += 1
re... |
def derive_model_combinations(model_template, algorithm_definition):
"""
A model can have two formats:
1. "model" : "./a001_model.json" : the result is simply one option with one possibility
2. "model": "./a002_2_@@parameter@@_model.json"
In the second case the template describes n ... |
def to_string_list(iterable):
"""Utility function to produce a string like: "'A', 'B', 'C'" from ['B', 'A', 'C'].
>>> to_string_list(['B', 'A', 'C'])
"'A', 'B', 'C'"
"""
return ', '.join(map(repr, sorted(iterable))) |
def _remove_nulls(output):
"""Remove nulls from dict. Temporary until we fix this in cosmos
:param output: dict with possible null values
:type output: dict
:returns: dict without null
:rtype: dict
"""
return {k: v for k, v in output.items() if v} |
def idFormat(id_num):
"""Format a numeric id into 5-digit string.
Paramters
---------
id_num: str
A unique string number assigned to a User or Request.
"""
if len(id_num) == 1:
id_num = "0000" + id_num
elif len(id_num) == 2:
id_num = "000" + id_num
e... |
def mix_columns(state):
"""
Compute MixColumns of state.
"""
return [state[0] ^ state[2] ^ state[3], \
state[0], \
state[1] ^ state[2], \
state[0] ^ state[2]] |
def is_identity_matrix(L):
"""
Returns True if the input matrix is an identity matrix, False otherwise.
"""
result = len(L) == len(L[0])
for i in range(len(L)):
for j in range(len(L)):
if i == j:
result *= (L[i][j] == 1)
else:
result *=... |
def get_candidate_type_and_position(e, idx):
"""Returns type and position info for the candidate at the given index."""
if idx == -1:
return "[NoLongAnswer]"
else:
return e["long_answer_candidates"][idx]["type_and_position"] |
def prettify(method):
"""Return a pretty representation of a method for use with logging
Args:
method Bound method instance
Returns:
string in the form MyClass.my_method
"""
rs = ""
if hasattr(method, "im_self") and method.__dict__.has_key('__self__'):... |
def string_parse(input_str):
"""
Converts passed string, into *args, **kwargs:
Args:
input_str(str): input string in format -
"1, 2, 3, a\nvalue3=4, value1=arg1, value2=arg2"
Returns:
tuple(*args, **kwargs): parsed args, and kwargs values... |
def reversedigits(i, base=10):
"""
>>> reversedigits(0)
0
>>> reversedigits(9)
9
>>> reversedigits(13)
31
>>> reversedigits(80891492769135132)
23153196729419808L
"""
j = 0
while i:
j *= base
j += i % base
i //= base
return j |
def xform_entity(entity_dict, data):
"""
Applies transformation functions specified by the entity dictionary (first
param) to the user-supplied data (second param). If no user data is
supplied for the given field in the entity dictionary, then the default
value for the field is supplied.
Parame... |
def binary_search(arr, target):
"""
ATTENTION: THE PROVIDED ARRAY MUST BE SORTED!
Searches for an item using binary search algorithm. Run time: O(log n)
"""
if arr == []:
return False
mid_ind = int(len(arr) / 2)
if (target < arr[mid_ind]):
return binary_search(arr[:m... |
def lower_tokens(tokens):
"""
Lowers the type case of a list of tokens
:param tokens: A list of tokens
:return: A comparable list of tokens to the input but all lower case
"""
cleaned_tokens = []
for token in tokens:
token = token.lower()
cleaned_tokens.append(token)
re... |
def default(value):
"""
Given a python object, return the default value
of that object.
:param value: The value to get the default of
:returns: The default value
"""
return type(value)() |
def unique_list(lst):
"""
Removes duplicates from a list while preserving order
"""
res = []
for i, item in enumerate(lst):
if i == len(lst) - 1 or lst[i + 1] != item:
res.append(item)
return res |
def extract_results_in_range(start_index, end_index, keys, total_results):
"""
Given the indexes and keys this method loop between indexes
:param start_index:
:param end_index:
:param keys:
:param total_results:
:return:
"""
return {k: total_results[k] for k in keys[start_index:end_i... |
def get_logs(self):
"""
returns list of logs for the object
"""
if hasattr(self, 'logs'):
return self.logs
return [] |
def _num_dividends(P, K):
"""
Returns the number of multiples of K for a 0 index sequence P.
:param P:
:param K:
:return:
"""
return (P // K) + 1 |
def progress_bar(label, value, max):
"""Render a Bootstrap progress bar.
:param label:
:param value:
:param max:
Example usage:
{% progress_bar label='Toner: 448 pages remaining' value=448 max=24000 %}
"""
return {
'label': label,
'percent': int((value / max) * 100)... |
def win_check(hidden_word, guessed_letters):
"""
hidden_word: string, the hidden word to guess
guessed_letters: list, with all letters user have used
return: boolean, True if all letters of hidden_word exist in guessed_letters otherwise False
"""
for letter in hidden_word:
if letter not ... |
def first(iterable, *default):
"""Returns the first value of anything iterable, or throws StopIteration
if it is empty. Or, if you specify a default argument, it will return that.
"""
return next(iter(iterable), *default) |
def power(base, exp):
"""Finding the power"""
assert exp >=0 and int(exp) == exp, 'The exponential must be positive integers only'
if exp == 0:
return 1
if exp == 1:
return base
return base * power(base, exp-1) |
def fold(s): # function fold: auxiliary function: shorten long option values for output
"""auxiliary function: shorten long option values for output"""
offset = 64 * " "
maxlen = 70
sep = "|" # separator for ... |
def paren_int(number):
"""
returns an integer from a string "([0-9]+)"
"""
return int(number.replace('(', '').replace(')', '')) |
def pwin(e1, e2):
"""probability e1 beats e2"""
return (1.0/(1+(10**((e2-e1)/float(400))))) |
def div(n, d):
"""Divide, with a useful interpretation of division by zero."""
try:
return n/d
except ZeroDivisionError:
if n:
return n*float('inf')
return float('nan') |
def isInt(value):
"""Returns True if convertible to integer"""
try:
int(value)
return True
except (ValueError, TypeError):
return False |
def revert_old_country_names(c: str) -> str:
"""Reverting country full names to old ones, as some datasets are not updated on the issue."""
if c == "North Macedonia":
return "Macedonia"
if c == "Czechia":
return "Czech Republic"
return c |
def AsList(val):
"""Ensures the JSON-LD object is a list."""
if isinstance(val, list):
return val
elif val is None:
return []
else:
return [val] |
def ibits(ival,ipos,ilen):
"""Same usage as Fortran ibits function."""
ones = ((1 << ilen)-1)
return ( ival & (ones << ipos) ) >> ipos |
def scala_T(input_T):
"""
Helper function for building Inception layers. Transforms a list of numbers to a dictionary with ascending keys
and 0 appended to the front. Ignores dictionary inputs.
:param input_T: either list or dict
:return: dictionary with ascending keys and 0 appended to... |
def unique_values(seq):
"""
Return unique values of sequence seq, according to ID function idfun.
From http://www.peterbe.com/plog/uniqifiers-benchmark and modified. Values in seq must be hashable for this to work
"""
seen = {}
result = []
for item in seq:
if item in seen:
... |
def _af_parity(pi):
"""
Computes the parity of a permutation in array form.
The parity of a permutation reflects the parity of the
number of inversions in the permutation, i.e., the
number of pairs of x and y such that x > y but p[x] < p[y].
Examples
========
>>> from sympy.combinator... |
def get_material_requires_texcoords(glTF, index):
"""
Query function, if a material "needs" texture cooridnates. This is the case, if a texture is present and used.
"""
if glTF.get('materials') is None:
return False
materials = glTF['materials']
if index < 0 or index >= len(ma... |
def hex_to_rgb(hex: str) -> tuple:
"""
Args:
hex (str):
"""
return tuple(int(hex.lstrip("#")[i : i + 2], 16) for i in (0, 2, 4)) |
def is_stupid_header_row(row):
"""returns true if we believe row is what the EPN-TAP people used
as section separators in the columns table.
That is: the text is red:-)
"""
try:
perhaps_p = row.contents[0].contents[0]
perhaps_span = perhaps_p.contents[0]
if perhaps_span.get("style")=='color: rgb(... |
def Clamp(value, low=0.0, high=1.0):
"""Clamp a value between some low and high value."""
return min(max(value, low), high) |
def _get_snap_name(snapshot):
"""Return the name of the snapshot that Purity will use."""
return "%s-cinder.%s" % (snapshot["volume_name"], snapshot["name"]) |
def _calc_ts_complexity(tss, pers):
""" Calculates the complexity of a TS schema
Complexity = (Number of Schemas + Number of Permutable Symbols + Lenght of each Permutable Symbol)
"""
return len(tss) + sum([len(per) for ts, per in zip(tss, pers)]) |
def Crosses(ps, thresh):
"""Tests whether a sequence of p-values ever drops below thresh."""
if thresh is None:
return False
for p in ps:
if p <= thresh:
return True
return False |
def step_name_str(yaml_stem: str, i: int, step_key: str) -> str:
"""Returns a string which uniquely and hierarchically identifies a step in a workflow
Args:
yaml_stem (str): The name of the workflow (filepath stem)
i (int): The (zero-based) step number
step_key (str): The name of the st... |
def isclose(a, b, rel_tol=1e-02, abs_tol=0.0):
"""
Parameters
----------
a : int/float
first value
b : int/float
second value
rel_tol : float, (optional)
relative tolerance
abs_tol : float, (optional)
the absolute tolerance
Returns
-------
"""
... |
def actions(elements, **kwargs):
"""
Define a block "action".
API: https://api.slack.com/reference/messaging/blocks#actions
Other Parameters
----------------
block_id : str
Returns
-------
dict
"""
return {'type': 'actions',
'elements': elements,
**k... |
def assert_(condition, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg
"""
Return `value` if the `condition` is satisfied and raise an `AssertionError` with the specified
`message` and `args` if not.
"""
message = None
if args:
message = args[0]
args = args[1:]
... |
def pi_using_float(precision):
"""Get value of pi via BBP formula to specified precision using floats.
See: https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
:param precision: Precision to retrieve.
:return: Pi value with specified precision.
"""
value = 0
for k i... |
def get_version(program: str) -> str:
"""
Return version of a program.
:param program: program's name.
:return: version.
"""
import subprocess
cmd = "dpkg -l | grep '{}'".format(program)
process = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE,
... |
def fibonacci(n):
"""
Returns nth fibonacci number F(n)
F(n) = F(n-2) + F(n-1)
"""
k, m = 1, 1
if n < 2:
return n
for i in range(2, n):
k, m = m, k + m
return m |
def rescaleInput(input):
"""
scales input's elements down to range 0.1 to 1.0.
"""
return (0.99 * input / 255.0) + .1 |
def filter_techniques_by_platform(tech_list, platforms):
"""Given a technique list and a platforms list, filter out techniques
that are not part of the platforms"""
if not platforms:
return tech_list
filtered_list = []
# Map to easily find objs and avoid duplicates
ids_for_duplicate... |
def get_secret_variables(app_config: dict) -> dict:
"""Returns the secret variables from configuration."""
secret_variables = app_config.get("variables", {}).get("secret", {})
formatted_secret_variables = {
secret_name: {
"secretKeyRef": {
"name": secret_variables[secret... |
def _prefix_statistics(prefix, stats):
"""Prefix all keys in a statistic dictionary."""
for key in list(stats.keys()):
stats['{}/{}'.format(prefix, key)] = stats.pop(key)
return stats |
def _normalize_jsonpath(jsonpath):
"""Changes jsonpath starting with a `.` character with a `$`"""
if jsonpath == '.':
jsonpath = '$'
elif jsonpath.startswith('.'):
jsonpath = '$' + jsonpath
return jsonpath |
def get_top_grossing_directors(top_grossing, top_casts):
"""
Gets all directors who directed top grossing movies
:param top_grossing: dictionary of top grossing movies
:param top_casts: dictionary of top casts
:return: sorted list of top grossing movie directors
"""
top_directors = {}
fo... |
def check_for_newline(s, pos):
"""This function, given a string s (probably a long string, like a line or a file)
and a position 'pos', in the string, eats up all the whitespace it can
and records whether a newline was among that whitespace.
It returns a tuple
(saw_newline, new_pos)
... |
def sign(value):
"""Return the sign of a value as 1 or -1.
Args:
value (int): The value to check
Returns: int: -1 if `value` is negative, and 1 if `value` is positive
"""
if value < 0:
return -1
else:
return 1 |
def get_kwargs_set(args, exp_elem2dflt):
"""Return user-specified keyword args in a dictionary and a set (for True/False items)."""
arg_set = set() # For arguments that are True or False (present in set if True)
# Add user items if True
for key, val in args.items():
if exp_elem2dflt is not None... |
def value_of_card(card):
"""
:param card: str - given card.
:return: int - value of a given card (J, Q, K = 10, numerical value otherwise).
"""
if card == 'J' or card == 'Q' or card == 'K':
value = 10
else:
value = int(card)
return value |
def fix_postcode(pc):
""" convert postcodes to standard form
standard form is upper case with no spaces
>>> pcs = ["LA1 4YF", "LA14YF", " LA1 4YF", "L A 1 4 Y f"]
>>> [fix_postcode(pc) for pc in pcs]
['LA14YF', 'LA14YF', 'LA14YF', 'LA14YF']
"""
return pc.upper().replace(" ","") |
def is_even(num : int) -> bool:
"""
Check if a number is even or not.
Parameters:
num: the number to be checked
Returns:
True if number is even, otherwise False
"""
if (num%2) == 0:
return True
else:
return False |
def rep_to_raw(rep):
"""Convert a UI-ready rep score back into its approx raw value."""
if not isinstance(rep, (str, float, int)):
return 0
if float(rep) == 25:
return 0
rep = float(rep) - 25
rep = rep / 9
sign = 1 if rep >= 0 else -1
rep = abs(rep) + 9
return int(sign * ... |
def introduction():
"""Handle a request for the "Introduction" page.
This function really doesn't do much, but it returns the data contained at
views/introduction.tpl which contains some detail on the project and useful
links to other information.
Returns:
(string) A web page (via the @vie... |
def format_pct(p):
"""Format a percentage value for the HTML reports."""
return "%.0f" % p |
def construct_supervisor_command_line(supervisor_ip, cols, rows, area_size, traffic, road_cells, nodes, apn):
"""Creates the command to start up the supervisor.
:type supervisor_ip: str
:param supervisor_ip: the private IP address of supervisor
:type cols: int
:param cols: city cols
:type rows:... |
def reversing_words3(s):
"""
>>> reversing_words('buffy is awesome')
'awesome is buffy'
"""
words = s.split(' ')
words.reverse()
return ' '.join(words) |
def toggle_collapse(n, is_open):
"""
Simple callback that will toggle the collapse
:param n: The initial state of n_clicks
:param is_open: The initial state of is_open
:return: The result state of is_open after it is toggled
"""
if n:
return not is_open
return is_open |
def is_dict_subset_of(sub_dict, super_dict):
"""Checks if sub_dict is contained in the super_dict.
:param sub_dict: A mapping. This is looked for in the super_dict.
:param super_dict: A mapping. May or may not contain the sub_dict.
:return: True, if all the key-value pairs of sub_dict ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.