content stringlengths 42 6.51k |
|---|
def my_evalf(expr, chop=False):
"""
Enhanced sympy evalf to handle lists of expressions
and catch eval failures without dropping out.
"""
if isinstance(expr, list):
try:
return [x.evalf(chop=chop) for x in expr]
except Exception: # pylint: disable=broad-except
... |
def city_country(city, country):
"""Return a string like 'Santiago, Chile'."""
return f"{city.title()}, {country.title()}" |
def generate_control_variables(value):
""" Generate some set values for control variables to test against """
return {'value': value,
'valueAlarm': {'lowAlarmLimit': 2, 'lowWarningLimit': 3, 'highAlarmLimit': 10, 'highWarningLimit': 8},
'alarm': {'severity': 0},
'display': {'... |
def re_ordering(s):
"""
Split the string into a list,
loop through the list, then loop through each word checking if any letter is capital
if so, obtain the index of the word insert it at the beginning and remove it from old position
"""
k, reorder = s.split(), ""
for x in k:
for y i... |
def calc_finesse(FSR, FWHM):
"""
Returns the FP Finesse.
Parameters
----------
FSR (float) : free-spectral-range in BCV or A
FWHM (float) : full-width-at-half-maximum in BCV or A
Returns
-------
F (float) : the finesse
Observations
------------
Both FSR and FWHM have t... |
def get_d_pair(n, cond1, cond2):
"""
"""
d1 = [cond1[x] - cond2[x] for x in range(n)]
d21 = [x**2 for x in d1]
sumd1 = sum(d1)
sumd21 = sum(d21)
d_ = sumd1 / n
sd = ((sumd21 - (n * (d_**2))) / (n - 1))**0.5
sd_error = sd / (n**0.5)
d = d_ / sd_error
return d |
def authInsert(user, role, group, site):
"""
Authorization function for general insert
"""
if not role:
return True
for k, v in user['roles'].iteritems():
for g in v['group']:
if k in role.get(g, '').split(':'):
return True
return False |
def validate_connection_providertype(connection_providertype):
"""
Validate ProviderType for Connection
Property: Connection.ProviderType
"""
VALID_CONNECTION_PROVIDERTYPE = ["Bitbucket", "GitHub", "GitHubEnterpriseServer"]
if connection_providertype not in VALID_CONNECTION_PROVIDERTYPE:
... |
def andify(list_of_strings):
"""
Given a list of strings will join them with commas
and a final "and" word.
>>> andify(['Apples', 'Oranges', 'Mangos'])
'Apples, Oranges and Mangos'
"""
result = ', '.join(list_of_strings)
comma_index = result.rfind(',')
if comma_index > -1: result = ... |
def decimalToFloat(obj):
"""
Function for/to <short description of `netpyne.sim.utils.decimalToFloat`>
Parameters
----------
obj : <type>
<Short description of obj>
**Default:** *required*
"""
from decimal import Decimal
if type(obj) == list:
for i,item in en... |
def remove_list_duplicates(input):
"""
"""
lis_out = []
for element in input:
if element not in lis_out:
lis_out.append(element)
return lis_out |
def h(p1, p2):
"""Manhattan distance"""
(x1, y1), (x2, y2) = p1, p2
return abs(x1 - x2) + abs(y1 - y2) |
def NonetoemptyList(XS):
"""
Convert a None type to empty list
@args XS: None type
@type XS: str
"""
return [] if XS is None else XS |
def binary_search(items_list, item,
recursive=False, first_ptr=-1, last_ptr=-1):
"""
Searches the list 'items_list' for an item 'item'
using binary search algorithm
>>> from pydsa import binary_search
>>> a = [1, 2, 7, 9, 10, 33, 56, 70, 99]
>>> binary_search(a, 9)
3
>... |
def update(config1, config2):
"""Merges configs 1 and 2 by section, which (unlike dict.update()) ensures
no fields in overlapping sections are lost. Result is in effect the
union of settings from both files, with settings from config2 overriding
those in config1. Does not modify either orig... |
def strFromPath(path):
"""
Construct a string that represents the Python code required to retrieve a value from
the structure.
"""
def fmt(x):
if type(x) == str:
return "['{}']".format(x)
elif type(x) == int:
return "[{}]".format(x)
else:
return x
return ''.join([fmt(x) for x in path]) |
def handle_quota_spec(quota):
"""
Process an arbitrary quota specification
Given a quota specification as a string,
returns the operation and amount.
The specification must be of the form:
[OPERATION]AMOUNT
where OPERATION is one of '=','+' or '-'
and defaults to '=' if not present.
... |
def _get_added_comment_id(src):
"""Returns comment ID from given request."""
if not src:
return None
actions = src.get('actions') or {}
related = actions.get('add_related') or []
if not related:
return None
related_obj = related[0]
if related_obj.get('type') != 'Comment':
return None
re... |
def perc_bounds(percent_filter):
"""
Convert +/- percentage to decimals to be used to determine bounds.
Parameters
----------
percent_filter : float or tuple, default None
Percentage or tuple of percentages used to filter around reporting
irradiance in the irr_rc_balanced function. ... |
def gridIndexToSingleGridIndex(ix, iy, iz, nx, ny, nz):
"""
Convert a grid index (3 indices) into a single grid index:
:param ix, iy, iz: (int) grid index in x-, y-, z-axis direction
:param nx, ny, nz: (int) number of grid cells in each direction
:return: i: (int) single grid index
... |
def get_party_info(info):
"""
Parse the info and return name, email.
"""
if not info:
return
if '@' in info and '<' in info:
splits = info.strip().strip(',').strip('>').split('<')
name = splits[0].strip()
email = splits[1].strip()
else:
name = info
... |
def init_nested_dict_zero(sector, first_level_keys, second_level_keys):
"""Initialise a nested dictionary with two levels
Arguments
----------
first_level_keys : list
First level data
second_level_keys : list
Data to add in nested dict
Returns
-------
nested_dict : dict... |
def sucrose (inverted_sugar_pre_hidrolisys, inverted_sugar_post_hidrolisys):
"""
Function to calculate the sucrose percentage in honey
"""
inverted_sugar_from_sucrose = inverted_sugar_post_hidrolisys - inverted_sugar_pre_hidrolisys
sucrose = inverted_sugar_from_sucrose * 0.95 ## 0.95 is the converti... |
def fallingfactorial(n, m):
"""
Return the falling factorial; n to the m falling, i.e. n(n-1)..(n-m+1).
For Example:
>>> fallingfactorial(7, 3)
210
"""
r = 1
for i in range(n, n-m, -1):
r *= i
return r |
def calc_growing_media(total_sales):
"""Calculate Growing Media costs Function
Args:
total_sales (list): The total sales as a annual time series
Returns:
cogs_cogs_media (list): Cost of Goods Sold expenditure on Growing Media as a time series for each year
To Do:
Currently take... |
def secs_to_string(secs):
"""Convert seconds to a string with days, hours, and minutes"""
str_list = []
for (label, interval) in (('day', 86400), ('hour', 3600), ('minute', 60)):
amt = int(secs / interval)
plural = u'' if amt == 1 else u's'
str_list.append(u"%d %s%s" % (amt, label, p... |
def getL(s):
"""
whether the given s is shell symbol
if it is, we return it's L Code
else return -1
"""
if s == "S" or s == "s":
return 0
elif s == "P" or s == "p":
return 1
elif s == "SP" or s == "sp":
return 100
elif s == "D" or s == "d":
return 2
... |
def find_line_eq(Z1, Z2):
"""Find the line equation (Ax+By=C)
Parameters
----------
Z1 : complex
Complex coordinate of a point on the line
Z2 : complex
Complex coordinate of another point on the line
Returns
-------
A, B, C : (float, float, float)
Line equation... |
def tuplify_json_list(list_object: list) -> tuple:
"""
JSON.dump() stores tuples as JSON lists. This function receives a list (with sub lists)
and creates a tuple of tuples from the list. The tuples are the preferred input type for py2neo.
E.g.
[[a, b], [c, d]] -> ((a, b), (c, d))
:param ... |
def orthogonal_vector(vector):
""" Given a vector, returns a orthogonal/perpendicular vector of equal length.
Returns
------
(float, float): A vector that points in the direction orthogonal to vector.
"""
return -1 * vector[1], vector[0] |
def get_app_or_pod_id(app_or_pod):
"""Gets the app or pod ID from the given app or pod
:param app_or_pod: app or pod definition
:type app_or_pod: requests.Response
:return: app or pod id
:rtype: str
"""
return app_or_pod.get('app', app_or_pod.get('pod', {})).get('id') |
def extractLats(listoftups):
"""Given a sequence of tuples the first two elements of which are
longitude and latitude, return list of lons"""
return [item[1] for item in listoftups] |
def pf_mobility(phi, gamma):
""" Phase field mobility function. """
# return gamma * (phi**2-1.)**2
# func = 1.-phi**2 + 0.0001
# return 0.75 * gamma * max_value(func, 0.)
return gamma
# Function to control PF mobility over time. |
def parse_album_header(album_header):
"""Split the album title in half, to retrieve its name an year.
Examples::
>>> album_title = 'His Young Heart (2011)'
>>> split_album_title(album_title)
(His Young Heart, 2011)
Args:
album_header (string): album header / title to s... |
def modular_inverse(a, p):
"""find the modular inverse s.t. aa^-1 mod p = 1"""
for b in range(1, p):
if (a * b) % p == 1:
return b |
def color_red(text):
"""
Applies terminal control sequence for red color
"""
result = "\033[31m{}\033[0m".format(text)
return result |
def _make_pointer_increments(name, nargs, sig):
"""Increments array pointers following each function call."""
inclist = ""
for i in range(nargs):
if sig[i] in "vpf":
inclist += "++%s%d; " % (name, i,)
return inclist |
def bytes2snap(nof_bytes: int) -> str:
"""
Convert nof bytes into snap-compatible Java options.
.. code-block:: python
>>> bytes2snap(32000)
'31K'
Args:
nof_bytes (int): Byte nb
Returns:
str: Human-readable in bits
"""
symbols = ("K", "M", "G", "T", "P", ... |
def job_dfn_list_dict(job_dict):
"""A job definition list represented as a dictionary."""
return {"jobs": [job_dict]} |
def get_value(values, keys: list, default=None):
"""
returns value from json based on given key hierarchy
Ex:
val_map = {'one' : {'two' : 123 }}
get_value(val_map, ['one', 'two']) returns 123
@param values: json object
@param keys: list keys from the hierarchy tree
@param defaul... |
def _GetOpIds(ops):
"""Returns C{OP_ID} for all opcodes in passed sequence.
"""
return sorted(opcls.OP_ID for opcls in ops) |
def split_and_strip(input_string, delim=","):
"""Convert a string into a list using the given delimiter"""
if not input_string: return list()
return map(str.strip, input_string.split(delim)) |
def _split_text_into_n_parts(n, text, output_dir):
"""
Splits text into `n` approximately equal parts.
The splitting is permformed only at paragraphs' boundaries.
"""
l = len(text) // n
texts = []
cur_part_start = 0
for i in range(len(text)):
if i >= cur_part_start + l and text... |
def get_prefix(n, factor=1024, prefixes=None):
"""Get magnitude prefix for number."""
if prefixes is None:
prefixes = ('',) + tuple('kMGTPEZY')
if abs(n) < factor or len(prefixes) == 1:
return n, prefixes[0]
return get_prefix(n / factor, factor=factor, prefixes=prefixes[1:]) |
def _break_long_text(text, maximum_length=75):
"""
Breaks into lines of 75 character maximum length that are terminated by a backslash.
"""
def next_line(remaining_text):
# Returns a line and the remaining text
if '\n' in remaining_text and remaining_text.index('\n') < maximum_length:... |
def identity(x):
"""This has the side-effect of bubbling any exceptions we failed to process
in C land
"""
import sys # noqa
return x |
def _moduleExist( moduleNames ):
"""Checks that the specified module can be loaded in the current python path.
moduleNames is a list containing every element of the module name. For example,
module 'Data.Character.Robot' would be [ 'Data', 'Character', 'Robot' ] """
import sys, os
for path in sys.pa... |
def filter_batch(batch, i):
"""check whether sample i should be included"""
return batch["lang"][i] in {"da"} and batch["passed_quality_filter"][i] is True |
def sum_digits(y):
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> a = sum_digits(123) # make sure that you are using return rather than print
>>> a
6
"""
"*** YOUR CODE HERE ***"... |
def to_spec(reg_id, kwargs):
"""Return build spec from id and arguments."""
return {
'type': reg_id,
'args': kwargs
} |
def find_groupby_names(url):
"""
Get the groupBy names
:return:
"""
return [name.strip("/") for name in url.split("groupBy")[1:]] |
def make_matrix_from_axes(x,y,z):
"""construct orientation matrix from basis vectors"""
return ( x[0], y[0], z[0],
x[1], y[1], z[1],
x[2], y[2], z[2] ) |
def extract_values(obj, key):
"""Recursively pull values of specified key from nested JSON."""
arr = []
def extract(obj, arr, key):
"""Return all matching values in an object."""
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
... |
def interval_prime_sieve(block_start_i, block_sz):
""" create a block where index 0 represents int block_start_i and the values
in the block are True iff the corresponding index is prime """
block = [True] * block_sz
for i in range(2, block_start_i):
# compute the offset from the first block... |
def class_name_from_module_name(module_name):
"""Takes a module name and returns the name of the class it
defines.
If the module name contains dashes, they are replaced with
underscores.
Example::
>>> class_name_from_module_name('with-dashes')
'WithDashes'
>>> class_name_f... |
def sales_growth_rate(sales_period_1, sales_period_2):
"""Return the sales growth rate for the current period versus the previous period.
Args:
sales_period_1 (float): Total company sales for previous the period.
sales_period_2 (float): Total company sales for the current period.
Returns:
... |
def string_remove(str1: str, str2: str) -> str:
"""
Remove all instances of the second string from the first string.
:param str1: The string from which to remove strings.
:param str2: The string to remove.
:returns: The string after removing desired strings.
"""
if not isinstance(str1, str)... |
def join_paths(path, files, extension):
"""Method to merge paths."""
if extension is not None:
return [path / (x + extension) for x in files]
return [path / x for x in files] |
def get_show_table_columns(table):
"""
Gets the query of SHOW COLUMNS for a given table.
:type str
:param table: A table name
:rtype str
:return A query
"""
return 'SHOW COLUMNS FROM `{:s}`'.format(table) |
def escape_filter_exp(filter_exp: str):
"""
Escapes the special characters in an LDAP filter based on RFC 4515.
:param str filter_exp: the unescaped filter expression.
:return: the escaped filter expression.
:rtype: str
"""
chars_to_escape = (
("\\", "\\5C"),
("*", "\\2A"),
... |
def velocity_move(x_coordinate, y_coordinate, velocity_x, velocity_y, boids_number):
"""Move according to velocities"""
for i in range(boids_number):
x_coordinate[i] = x_coordinate[i] + velocity_x[i]
y_coordinate[i] = y_coordinate[i] + velocity_y[i]
return x_coordinate, y_coordinate |
def get_reactions_producing(complexes, reactions):
""" dict: maps complexes to lists of reactions where they appear as a product. """
return {c: [r for r in reactions if (c in r.products)] for c in complexes} |
def descope_queue_name(scoped_name):
"""Descope Queue name with '.'.
Returns the queue name from the scoped name
which is of the form project-id.queue-name
"""
return scoped_name.split('.')[1] |
def splitAt( s, i, gap=0 ):
"""split s into two strings at index i with an optional gap"""
return s[:i], s[i+gap:] |
def _sharded_checkpoint_pattern(process_index, process_count):
"""Returns the sharded checkpoint prefix."""
return f"shard-{process_index:05d}-of-{process_count:05d}_checkpoint_" |
def zone_is_boost_active(zone):
"""
Is the boost active for the zone
"""
return zone["isboostactive"] |
def transform_lowercase(val, mode=None):
"""
Convert to lowercase
<dotted>|lowercase string to lowercase
<dotted>|lowercase:force string to lowercase or raises
"""
try:
return val.lower()
except TypeError:
if mode == 'force':
raise
return v... |
def title_formatter(title: str) -> str:
"""
This method builds a reusable title for each argument section
"""
return f"\n{title}" |
def file_scanning(paths):
"""
Args:
paths (str/list/tuple): a directory path or
a (potentially nested) list/tuple of directory paths
Returns:
A list of all files under `paths`
"""
import os
import typing
if isinstance(paths, typing.List) or isinstance(paths, typin... |
def count_bits(number):
"""This function is the solution to the Codewars Bit Counting that
can be found at:
https://www.codewars.com/kata/526571aae218b8ee490006f4/train/python"""
bits = []
quotient = number
while divmod(quotient, 2)[0] != 0:
quotient, remainder = divmod(quotient, 2)
... |
def terrain(x):
"""Interpolate the noise value and return the terrain type.
"""
if x <-1:
return {"name": "deep water", "color": (0, 0, 100),}
elif -1 <= x <= -0.5:
return {"name": "water", "color": (0, 0, 180)}
elif -0.5 < x <= -0.3:
return {"name": "shallow water", "color"... |
def pColorIa( color ):
""" returns the likelihood of observing
host galaxy with the given rest-frame
B-K color, assuming the SN is a Ia
RETURNS : P(B-K|Ia)
"""
if color < 3 : return( 0.240, 0.05, 0.05 )
elif color < 4 : return( 0.578, 0.05, 0.05 )
else : return( 0.183, ... |
def getTweetPlaceFullname(tweet):
""" If included, read out tweet full name place """
if 'place' in tweet and \
tweet['place'] is not None and \
'full_name' in tweet['place'] :
return tweet['place']['full_name']
else :
return None |
def pinpoint_event():
""" Generates A Pinpoint Event"""
return {
"Message": {},
"ApplicationId": "71b0f21869ac444eb0185d43539b97ea",
"CampaignId": "54115c33de414441b604a71f59a2ccc3",
"TreatmentId": "0",
"ActivityId": "ecf06111556d4c1ca09b1b197469a61a",
"ScheduledTime": "2020... |
def _cast(value):
"""
Cast input strings to their 'natural' types. Strip single quotes
from strings.
"""
try:
return int(value)
except ValueError:
pass
try:
return float(value)
except ValueError:
pass
if value.strip() == 'T':
return True
i... |
def style_str(s, color='black', weight=300):
"""
Style the supplied string with HTML tags
Args:
s (str):
string to format
color( str ):
color to show the string in
weight( int ):
how thick the string will be displayed
Returns:... |
def get_total_class_count(classes, idx2classes, old_total_class_count=None, removed_entry_dict=None):
"""
Function which calculates the counts for each of the classes - i.e. given the idx2classes dictionary, how many times
does each of the classes (defined by the classes list) appear?
This can... |
def filter_ldconfig_process(ps_rows):
"""
Sometimes an ldconfig process running under the django user shows up.
Filter it out.
:param ps_rows: A list of PsRow objects.
"""
return [row for row in ps_rows
if not (row.ruser == 'django' and 'ldconfig' in row.args)] |
def myconverter(o):
"""Use json.dumps(data, default=myconverter)."""
import datetime
if isinstance(o, datetime.datetime):
return o.__str__() |
def custom_format_old(source, language, class_name, options, md):
"""Custom format."""
return '<div lang="%s" class_name="class-%s", option="%s">%s</div>' % (language, class_name, options['opt'], source) |
def make_keyword_html(keywords):
"""This function makes a section of HTML code for a list of keywords.
Args:
keywords: A list of strings where each string is a keyword.
Returns:
A string containing HTML code for displaying keywords, for example:
'<strong>Ausgangswörter:</stro... |
def key_match(key1, key2):
"""determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *.
For example, "/foo/bar" matches "/foo/*"
"""
i = key2.find("*")
if i == -1:
return key1 == key2
if len(key1) > i:
return key1[:i] == key2[:i]
r... |
def get_block_devices(bdms=None):
"""
@type bdms: list
"""
ret = ""
if bdms:
for bdm in bdms:
ret += "{0}\n".format(bdm.get('DeviceName', '-'))
ebs = bdm.get('Ebs')
if ebs:
ret += " Status: {0}\n".format(ebs.get('Status', '-'))
... |
def bytes_r(b):
"""Reverse a bytes-like object."""
return bytes(reversed(b)) |
def target_index(source: int, target: int) -> int:
"""Returns the index of the target channel, skipping the index of the self channel.
Used in inter CKS/CKR communication"""
assert source != target
if target < source:
return target
return target - 1 |
def normalize_data(indata, prop):
"""
Transforms Wikidata results into the neccessary format
to be added to SoNAR
---------
indata : str
result of query
prop : str
type of property (birthdate, deathdate etc.)
Returns
---------
list.
"""
if prop == "b... |
def in_nested_list(my_list, item):
"""
Determines if an item is in my_list, even if nested in a lower-level list.
"""
if item in my_list:
return True
else:
return any(in_nested_list(sublist, item) for sublist in my_list if
isinstance(sublist, list)) |
def scrub(txt):
"""Returns sluggified string. e.g. `Sales Order` becomes `sales_order`."""
return txt.replace(' ','_').replace('-', '_').lower() |
def get_character_limit(pdf_field_tuple, char_width=6, row_height=12):
"""
Take the pdf_field_tuple and estimate the number of characters that can fit
in the field, based on the x/y bounding box.
0: horizontal start
1: vertical start
2: horizontal end
3: vertical end
"""
# Make sure it's the right ki... |
def get_attributes(obj):
"""Get and format the attributes of an object.
Parameters
----------
section
An object that has attributes.
Returns
-------
dict
The object's attributes.
"""
attrs = obj.__dict__.copy()
attrs_fmtd = {}
for key in attrs:
key_fmt... |
def __get_bit_string(value):
"""INTERNAL.
Get string representation of an int in binary
"""
return "{0:b}".format(value).zfill(8) |
def is_between(lo: float, x: float, hi: float) -> bool:
"""Checks if `x` is between the `lo` and `hi` arguments."""
return lo < x < hi or lo > x > hi |
def transform_eq(transformer, rhs):
"""
Return an object that can be compared to another object after transforming
that other object.
The returned object will keep a log of equality checks done to it, and when
formatted as a string (with ``repr``), will show the history of transformed
objects a... |
def word_distance(word1, word2):
"""Computes the number of differences between two words.
word1, word2: strings
Returns: integer
"""
assert len(word1) == len(word2)
count = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
count += 1
return count |
def gather(items, attribute):
"""Gather children DAOs into a list under a shared parent.
A+1 A+[1,3,5]
B+C B+[C, x]
A+3 -->
A+5
B+x
A shared parent (A or B in the example) is identified by
primary key.
1, 3, 5, C and x are joined DAOs n... |
def is_any_in_txt(txt_list, within_txt):
"""
Within (txt_list), is there one item contained in within_txt ?
Example: (['a', 'b'], 'ab') --> Yes, a is contained in ab
"""
for x in txt_list:
if x in within_txt:
return True
return False |
def lzip(*args):
"""
zip(...) but returns list of lists instead of list of tuples
"""
return [list(el) for el in zip(*args)] |
def decode_bigint_bitvec(bitvec):
"""Decode a Bit-Endian integer from a vector of bits"""
return int(''.join(str(bit) for bit in bitvec), 2) |
def join_condition(suburb_bound, forest_bound):
"""
Condition that suburb has intersection with the forest polygon
"""
def intersect(box_a, box_b):
a_min_x, a_min_y, a_max_x, a_max_y = box_a
b_min_x, b_min_y, b_max_x, b_max_y = box_b
return a_min_y <= b_max_y and \
... |
def inp(X):
"""
Allows to parameterize RMinimum with an INT or a list.
Automatically generates a list from the first X numbers, i.e. [0, ..., X-1].
:param X: Either an INT or a list
:return: list = [0,...,X] when X is INT, otherwise it returns X
"""
try:
return [i for i in range(X... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.