content stringlengths 42 6.51k |
|---|
def _exp_warn_msg(cls):
"""Generate a warning message experimental features"""
pfx = cls
if isinstance(cls, type):
pfx = cls.__name__
msg = ('%s is experimental -- it may be removed in the future and '
'is not guaranteed to maintain backward compatibility') % pfx
return msg |
def check_comp(comp=None):
"""
Checks if the given competition url is properly formatted
"""
if(comp==None):
return(None)
if comp.endswith('/'):
comp = comp[:-1]
if comp.startswith('/'):
pass
else:
comp = '/' + comp
return(comp) |
def _sql_params(sql):
"""
Identify `sql` as either SQL string or 2-tuple of SQL and params.
Same format as supported by Django's RunSQL operation for sql/reverse_sql.
"""
params = None
if isinstance(sql, (list, tuple)):
elements = len(sql)
if elements == 2:
sql, param... |
def object_list_types(object_type):
"""return a dictionary of jamf API objects and their corresponding xml keys"""
# define the relationship between the object types and the xml key in a GET request
# of all objects we could make this shorter with some regex but I think this way is clearer
object_list_t... |
def gen_len(gen):
"""
Get genreator's length.
"""
return sum(1 for _ in gen) |
def phasename(phaseID):
"""
Take a phase ID and return the name of the phase.
Parameters
------------
phaseID : :class:`str`
ID for the particular phase (e.g. 'olivine_0')
Returns
--------
:class:`str`
Name of the phase.
"""
if phaseID.find("_") > 0:
n =... |
def frmt_db_lctn(location):
""" Formats the database location into nicer, more readable style
:param location: sms deposit location
:returns: Formated sms deposit location
"""
if location:
return location.replace("_", " ").replace('-', ' ').title() |
def get_selector_and_on_what_action(raw_code: str) -> tuple:
"""Find event selector & triggering action in raw JS event registration code
:return: ('#header-sign-in-link', 'click')
"""
selector_line_start = "$("
register_event_call = ").on("
event_function_start = ", function"
if ").on(" in... |
def partition(arr, low, high, key=None):
"""
This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot.
The optional *key* argument is a... |
def scale_list(l, x):
"""
scale_list(l, x)
Scales all values in a list l, by x.
"""
return [i*x for i in l] |
def Yes_No_reverse(value, collection):
""" True -> "Yes", Red background ; False->"No",green, None to "-",no color """
if value:
return ("Yes", "black; background-color:red;")
if value == None:
return ("-", "black")
return ("No", "black; background-color:green;") |
def entitiesByListing(entities):
"""Group entities from database by annotation id"""
groups = {}
for e in entities:
if e['annotation_id'] not in groups:
groups[e['annotation_id']] = []
entity = {}
for k, v in e.items():
if k != ['annotation_id']:
... |
def param_to_tuple(param):
"""
Convert param dictionary to a list of keys and a list of values.
Parameters
----------
param : dictionary
parameters
Returns
-------
list
the keys of param
list
the values of param
"""
if param is not None:
... |
def uniqueify(reqs):
"""Make a list of requirements unique."""
return list(set(reqs)) |
def commify(n):
"""
Add commas to an integer `n`.
>>> commify(1)
'1'
>>> commify(123)
'123'
>>> commify(1234)
'1,234'
>>> commify(1234567890)
'1,234,567,890'
>>> commify(123.0)
'123.0'
>>> commify(1234.5)
'1,234.5'
... |
def list_mean(values):
"""Function to calculate mean from list"""
sum_values = 0
i = 0
for value in values:
if value["value"] > 0:
sum_values += value["value"]
i += 1
return round(sum_values / i, 2) |
def parse_min_year(eligible_year):
"""
Parse minimum eligible year
:param eligible_year: string
:return: int
"""
if not eligible_year:
return -1
if eligible_year[0].isdigit():
return int(eligible_year[0])
return -1 |
def str_in_list(l1, l2):
"""Check if one element of l1 is in l2 and if yes, returns the name of
that element in a list (could be more than one.
Examples
--------
>>> print(str_in_list(['time', 'lon'], ['temp','time','prcp']))
['time']
>>> print(str_in_list(['time', 'lon'], ['temp','time','p... |
def prune_nones(mydict):
"""
Remove keys from `mydict` whose values are `None`
:arg mydict: The dictionary to act on
:rtype: dict
"""
# Test for `None` instead of existence or zero values will be caught
return dict([(k, v) for k, v in mydict.items() if v != None and v != 'None']) |
def pointToGridIndex(x, y, z, sx=1.0, sy=1.0, sz=1.0, ox=0.0, oy=0.0, oz=0.0):
"""
Convert real point coordinates to index grid:
:param x, y, z: (float) coordinates of a point
:param nx, ny, nz: (int) number of grid cells in each direction
:param sx, sy, sz: (float) cell size in each directio... |
def collect_src_frechet_files(py, search_directoy, output_directory):
"""
collect src_frechet files
"""
script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.collect_src_frechet --search_directoy {search_directoy} --output_directory {output_directory}; \n"
return script |
def squares_list(N):
"""This function takes an integer N, and returns a list of the squares from 0 up to (N*N) using list comprehension."""
return [i * i for i in range(N + 1)] |
def left_d_threshold_sequence(n, m):
"""
Create a skewed threshold graph with a given number
of vertices (n) and a given number of edges (m).
The routine returns an unlabeled creation sequence
for the threshold graph.
FIXME: describe algorithm
"""
cs = ['d'] + ['i'] * (n - 1) # creat... |
def value_of_ace(hand_value):
"""
:param hand_value: int - current hand value.
:return: int - value of the upcoming ace card (either 1 or 11).
"""
if hand_value + 11 > 21:
value = 1
else:
value = 11
return value |
def word_count(text):
""" The word-count of the given text. Goes through the string exactly
once and has constant memory usage. Not super sophisticated though.
"""
if not text:
return 0
count = 0
inside_word = False
for char in text:
if char.isspace():
inside_w... |
def ratios_to_coordinates(bx, by, bw, bh, width, height):
"""
Convert relative coordinates to actual coordinates.
Args:
bx: Relative center x coordinate.
by: Relative center y coordinate.
bw: Relative box width.
bh: Relative box height.
width: Image batch width.
... |
def convert_to_c_type_array_size(json_type):
"""
convert the json type to c type
:param json_type: the json type
:return: c type.
"""
if json_type == "boolean":
return 0
if json_type == "number":
return 0
if json_type == "integer":
return 0
if json... |
def update_file_info_in_job(job, file_infos):
"""
Update the 'setup.package.fileInformations' data in the JSON to append new file information.
"""
for file_info in file_infos:
try:
job['setup']['package']['fileInformations'].append(file_info)
except (KeyError, TypeError, Attr... |
def flatten_list(ls: list) -> list:
"""Flattens list with sublists.
Arguments:
ls {list} -- List to flatten
Returns:
flattened {list} -- Flattened list"""
flattened = [item for sublist in ls for item in sublist]
return flattened |
def parse_shape_change_input(s: str):
"""The input should be like 'input 1 1 224 224'.
"""
s_list = s.split(' ')
if len(s_list) < 2:
print("Cannot parse the shape change input: {}".format(s))
return None
shape = []
for i in range(1, len(s_list)):
shape.append(int(s_list[i... |
def to_lower( tokens ):
"""Convert all tokens to lower case.
Args:
tokens (list): List of tokens generated using a tokenizer.
Returns:
list: List of all tokens converted to lowercase.
"""
return [w.lower() for w in tokens] |
def clock_to_float(s):
"""given '7:30' return 7.5"""
if ":" in s:
M,S=[int(x) for x in s.split(":")]
return round(float(M+S/60.0),2)
else:
return float(s) |
def make_table(sequences):
"""
Make a table of all non-rotated elements.
- Column 1: seq -> The element itself.
- Column 2: rotate -> List all of the rotated elements which are between the
current element and the next non-rotated element.
Then delete all rotated elements in the seq column
... |
def changeCompilerCommand(cmdline: str) -> str:
"""
add -MM, delete -o
"""
# if cmdline.find('\\') >= 0:
# raise Exception('\\ found in cmdline: {}'.format(cmdline))
parts = cmdline.split()
o_idx = -1
o_n = 0
for i, p in enumerate(parts):
if p == '-o':
o_idx ... |
def to_object(data):
"""Data to object"""
iterable = (list, tuple, set)
if isinstance(data, iterable):
return [to_object(i) for i in data]
if not isinstance(data, dict):
return data
global Obj
class Obj: pass
obj = Obj()
for k, v in data.items():
setattr(obj,... |
def split_inversions(left, right):
"""
Count the number of inversions where i <= n // 2 <= j, and a[i] > a[j]
"""
total = 0
result = []
while len(left) != 0 and len(right) != 0:
if left[0] < right[0]:
result.append(left.pop(0))
else:
result.append(right.po... |
def float2(val, min_repeat=6):
"""Increase number of decimal places of a repeating decimal.
e.g. 34.111111 -> 34.1111111111111111"""
repeat = 0
lc = ""
for i in range(len(val)):
c = val[i]
if c == lc:
repeat += 1
if repeat == min_repeat:
return float(val[:i+1] + c * 10)
else... |
def unbind_method(f):
"""Take something that might be a method or a function and return the
underlying function."""
return getattr(f, 'im_func', getattr(f, '__func__', f)) |
def pytorch_default(device='cpu:0'):
"""Format options for pytorch."""
if device == 'cuda':
device = 'cuda:0'
if device == 'cpu':
device = 'cpu:0'
return dict(device=device) |
def extract_slug(url):
"""Extract `this-is-the-slug` given an url for the form `https://blog.kitware.com/this-is-the-slug/`
or `https://blog.kitware.com/this-is-the-slug`
"""
if url.endswith("/"):
url = url[:-1]
return url.split("/")[-1] |
def calcL1Ainterval(rate):
"""
Returns the L1Ainterval in BX associated with a given rate in Hz
"""
from math import floor
return floor((1.0 / rate) * (1e9 / 25)) |
def is_iter(obj):
"""Check whether an object is iterable."""
try:
iter(obj)
return True
except:
return False |
def handle_not_implemented_error(e: NotImplementedError):
"""
Raise exception: not implemented error.
Raise an exception if the operation is not supported by the backend.
"""
return "Not Implemented: %s" % e, 510 |
def process_card_name(name: str) -> str:
"""convert card_name to a uniform format"""
return name.strip().lower().replace(" ", "_").rstrip("+1") |
def normalize_probability(probabilities):
"""Rescale a collection of probabilityes so that they sum up to 1.
Args:
probabilities (dict): a dictionary of Probabilities, where keys are k-mers and values are the probabilities of these k-mers (which do no necessarily sum up to 1).
Returns:
Dic... |
def happy_color(health):
"""Return pyplot color for health percentage."""
if health > 0.8:
return 'g'
if health > 0.6:
return 'y'
return 'r' |
def finalize_labels(labels):
"""Keep '__value__', and '__topic__' but remove all other labels starting with '__'"""
labels['value'] = labels['__value__']
labels['topic'] = labels['__topic__']
return {k: v for k, v in labels.items() if not k.startswith('__')} |
def strip_quotes(word):
"""Strip all quotations marks from a word"""
return str(word).strip("\"\'") |
def linear(x, m, c):
""" linear function in x, y = m*x + c """
return m*x + c |
def STD_DEV_POP(*expression):
"""
Calculates the population standard deviation of the input values.
Use if the values encompass the entire population of data you want to represent
and do not wish to generalize about a larger population.
See https://docs.mongodb.com/manual/reference/operator/aggregat... |
def int_as_ip(ip_address):
"""convert int to dot notation
"""
return ".".join(map(str, [ip_address >> 24,
(ip_address & 0b111111111111111111111111) >> 16,
(ip_address & 0b1111111111111111) >> 8,
ip_address & 0b1111111... |
def _builtin_attrs(name):
""" These attributes are ignored when checking ABC types for emptyness.
"""
return name in ('__doc__', '__module__', '__qualname__', '__abstractmethods__', '__dict__',
'__metaclass__', '__weakref__', '__subclasshook__',
'_abc_cache', '_abc_im... |
def is_empty(sq):
"""Is this an empty square (no letters, but a valid position on board; excludes the border)."""
return sq == '.' or sq == '*' or isinstance(sq, set) |
def phi_square_calc(chi_square, POP):
"""
Calculate phi-squared.
:param chi_square: chi squared
:type chi_square : float
:param POP: population
:type POP : int
:return: phi_squared as float
"""
try:
return chi_square / POP
except Exception:
return "None" |
def two_of_three(x, y, z):
"""Return a*a + b*b, where a and b are the two smallest members of the
positive numbers x, y, and z.
>>> two_of_three(1, 2, 3)
5
>>> two_of_three(5, 3, 1)
10
>>> two_of_three(10, 2, 8)
68
>>> two_of_three(5, 5, 5)
50
>>> # check that your code cons... |
def discount_arpu(arpu, timestep, global_parameters):
"""
Discount arpu based on return period.
192,744 = 23,773 / (1 + 0.05) ** (0:9)
Parameters
----------
arpu : float
Average revenue per user.
timestep : int
Time period (year) to discount against.
global_parameters :... |
def try_int(s, *args):
"""Convert to integer if possible."""
#pylint: disable=invalid-name
try:
return int(s)
except (TypeError, ValueError):
return args[0] if args else s |
def BBoxIOU(boxA, boxB):
"""BBoxIOU implements the IOU ratio.
Args:
boxA: the first bbox in shape (4,) of (x1, y1, x2, y2)
boxB: the second bbox in shape (4,) of (x1, y1, x2, y2)
Returns:
iou: a float value represents the IOU ratio
"""
iou = 0.0
# determine the coordinates of the intersection... |
def parse_num(num_str):
"""
Convert a string into a number.
The string may contain spaces.
"""
return int(num_str.replace(' ', '')) |
def calc_mass(nu_max, delta_nu, teff):
""" asteroseismic scaling relations """
NU_MAX = 3140.0 # microHz
DELTA_NU = 135.03 # microHz
TEFF = 5777.0
return (nu_max/NU_MAX)**3 * (delta_nu/DELTA_NU)**(-4) * (teff/TEFF)**1.5 |
def partition_average(partition):
"""Given a partition, calculates the expected number of words sharing the same hint"""
score = 0
total = 0
for hint in partition:
score += len(partition[hint])**2
total += len(partition[hint])
return score / total |
def get_dict_info(dictionary, info_to_get):
"""Returns list containing data from given dictionary."""
return [dictionary.get(info) for info in info_to_get] |
def class_to_path(class_name, class_to_path_dic):
""" Return path to test file basing on class name
Parameters:
- class_name - test to find,
- class_to_path_dic - dict with class -> path key/values
Return:
- path to test file
"""
from fnmatch import fnmatch
for c, p in class_to_path_... |
def geojson_to_tuples_betydb(bounding_box):
"""Convert GeoJSON from BETYdb to
( lat (y) min, lat (y) max,
long (x) min, long (x) max) for geotiff creation"""
min_x, min_y, max_x, max_y = None, None, None, None
if isinstance(bounding_box, dict):
bounding_box = bounding_box["coordi... |
def entry_point(target: int) -> int:
"""Get number of possible combinations
>>> entry_point(3)
2
>>> entry_point(4)
4
>>> entry_point(7)
14
>>> entry_point(61)
1121504
>>> entry_point(79)
13848649
"""
ways = []
ways.append(1)
target += 1
for current_n... |
def is_bounded(coord, shape):
"""
Checks if a coord (x,y) is within bounds.
"""
x, y = coord
g, h = shape
lesser = x < 0 or y < 0
greater = x >= g or y >= h
if lesser or greater:
return False
return True |
def cook(obj, rep):
"""Create an object exactly like obj, except its repr() is rep. This
lets us easily use repr() for URLs."""
_class = type("Cooked", (type(obj),), {'__repr__': lambda self: rep})
return _class(obj) |
def long_repeat(line: str) -> int:
"""
length the longest substring that consists of the same char
"""
num = 0
maxnum = 1
keychr = ""
if not line: return 0
else:
for chara in line:
if keychr != chara:
keychr = chara
num = 1
... |
def shortest_unweighted_path(graph, start, end):
"""
Finds the shortest path from "start" to "end" in an unweighted graph, where all distances are equal to 1
:param graph: Graph where graph[node] is a list of indices where there is a path from the node to each index
:param start: Starting point of the... |
def api_error(api, error):
"""format error message for api error, if error is present"""
if error is not None:
return "calling: %s: got %s" % (api, error)
return None |
def get_continuation_tables_headers(
cols_widths, index_name=None, space=2, max_width=1e100
):
"""
returns column headers for continuation tables segmented to not exceed max_width
Parameters
----------
cols_widths : list
[[col_name, length of longest string], ...]
index_name : str
... |
def format_decimal(value):
"""Format value to 2 decimal places"""
formatter = "{0:.2f}"
return float(formatter.format(value)) |
def make_no_diff_deleted_header(path, old_tag, new_tag):
"""Generate the expected diff header for a deleted file PATH when in
'no-diff-deleted' mode. (In that mode, no further details appear after the
header.) Return the header as an array of newline-terminated strings."""
path_as_shown = path.replace('\\', '/'... |
def clean_tag(tag):
"""Clean supercell tag"""
t = tag
t = t.upper()
t = t.replace('O', '0')
t = t.replace('B', '8')
t = t.replace('#', '')
return t |
def normalize_encoding(encoding):
""" Normalize an encoding name.
Normalization works as follows: all non-alphanumeric
characters except the dot used for Python package names are
collapsed and replaced with a single underscore, e.g. ' -;#'
becomes '_'. Leading and trailing undersc... |
def coinify(atoms):
"""
Convert the smallest unit of a coin into its coin value.
Args:
atoms (int): 1e8 division of a coin.
Returns:
float: The coin value.
"""
return round(atoms / 1e8, 8) |
def swap(array, size=0):
""" size=0: [2, 3, 5, 7, 11] -> [11, 7, 5, 3, 2] ; size=2: [2, 3, 5, 7, 11] -> [3, 2, 7, 5, 11] """
if size == 0: size = len(array)
a = [array[i:i + size] for i in range(0, len(array), size)]
a = [item[::-1] for item in a]
return [item for sublist in a for item in sublist] |
def _get_external_id(account_info):
"""Get external id from account info."""
if all(k in account_info for k in ('external_id', 'external_method')):
return dict(
id=account_info['external_id'],
method=account_info['external_method'])
return None |
def union(a, b):
"""
union(list, list):
"""
# Copy a
c = a[:]
for i in b:
if (i not in c):
c.append(i)
return c |
def dict_is_song(info_dict):
""" Determine if a dictionary returned by youtube_dl is from a song (and not an album for example). """
if "full album" in info_dict["title"].lower():
return False
if int(info_dict["duration"]) > 7200:
return False
return True |
def get_utm_zone(pos_longlat):
"""
Return the UTM zone number corresponding to the supplied position
Arguments:
pos_longlat: position as tuple (This in (long, lat)
Returns:
The UTM zone number (+ve for North, -ve for South)
"""
lon, lat = pos_longlat
z = int(lon/6) + 31
... |
def list_math_multiplication_number(a, b):
"""!
@brief Multiplication between list and number.
@details Each element from list 'a' is multiplied by number 'b'.
@param[in] a (list): List of elements that supports mathematic division.
@param[in] b (double): Number that supports mathematic d... |
def _to_list(x, n):
"""Converts x into list by repeating it n times.
If x is already a list and it has length n, returns x.
Else, if x is a list and has different length, raises ValueError."""
if isinstance(x, list):
if len(x) != n:
raise ValueError(
'''If list is pas... |
def _is_in(obj, sequence):
"""
A helper function to do identity ("is") checks instead of equality ("==")
when using X in [A, B, C] type constructs. So you would write:
if _is_in(type(foo), [int, long]):
instead of:
if type(foo) in [int, long]:
"""
for item in sequence:
if obj is item:
retu... |
def conv_decibels_to_power_ratio(decibels):
"""
Calculate the power ratio P2/P1 where P1 = 1.
Returns
-------
double : no units
"""
return 10 ** (decibels / 10) |
def moffat(coords, y0, x0, amplitude, alpha, beta=1.5):
"""Moffat Function
Symmetric 2D Moffat function:
.. math::
A (1+\frac{(x-x0)^2+(y-y0)^2}{\alpha^2})^{-\beta}
"""
Y,X = coords
return (amplitude*(1+((X-x0)**2+(Y-y0)**2)/alpha**2)**-beta) |
def RiemanSum(f, a, b, Increment = 0.0001):
"""One dimensional function that returns the riemansum between two points; This implies that the function has the property of Rieman integrability."""
if not callable(f):
raise TypeError("[Rieman.py]: Function RiemanSum needs the input function f to be callabe... |
def format_time(seconds):
"""
Formats a time in seconds
:param seconds:
:return: Time formatted as hh:mm:ss
"""
format_zero = lambda x: str(int(x)) if int(x) > 9 else "0{}".format(int(x))
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "{}:{}:{}".format(format_zero(h)... |
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korea... |
def split_to_list(event_lists):
"""
like unit split, but input has True, False as well
:param event_lists:
:return:
"""
lists = []
for event_list, deviant in event_lists:
lists.append((event_list.split("-"), deviant))
return lists |
def split_on_attribute_values(tester,rows):
"""
Given a function 'tester' which, given a row, returns either
True or False, and a collection of rows, returns
(trues,falses)
where trues is a list of the rows where tester returned True,
and falses is a list of the rows where tester returned False.
"""... |
def human_size(bytes_num: int, units=None) -> str:
""" Returns a human readable string representation of bytes """
units = [' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'] if not units else units
return str(bytes_num) + units[0] if bytes_num < 1024 else human_size(bytes_num >> 10, units[1:]) |
def no_change_start_menu(on=0):
"""Desabilitar o "Drag-and-Drop" no Menu Iniciar
DESCRIPTION
Esta restricao previne que os usuarios modifiquem o menu Iniciar,
atraves do recurso "Drag-and-Drop".
COMPATIBILITY
Windows 98/Me/2000/XP
MODIFIED VALUES
NoChangeS... |
def predict(observationVector, theta):
""" Given a fitted theta and observation vector, we can make a regression prediction.
We assume observationVector and theta are lists. """
observationVector.insert(0, 1) # add the intercept value
return sum([observationVector[i] * theta[i] for i in range(len(... |
def is_prime(n):
"""
Miller-Rabin primality test
for n < 2 ** 64
"""
test_vals = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
if n in test_vals:
return True
d = n - 1
s = 0
while not d & 1:
d = d >> 1
s += 1
for a in test_vals:
for r in range(0, s):
if (a ** (d * (1 << r))) % ... |
def normalize_versions(versions):
"""Return version dict with keys normalized to lowercase.
PyPI is case-insensitive and not all distributions are consistent in
their own naming.
"""
return dict([(k.lower(), v) for (k, v) in versions.items()]) |
def is_empty(string):
""" Return True if the given string contains no characters.
:param string: (str) a string to check
:returns: bool
"""
# Clean the string: remove tabs, carriage returns...
s = string.strip()
# Check the length of the cleaned string
return len(s) == 0 |
def _is_valid_image(file_path):
"""
**Checks if given file is .jpg, .jpeg or .png file.** Internal function.
"""
if file_path.endswith(".jpg") or file_path.endswith(".jpeg") or file_path.endswith(".png"):
return True
else:
return False |
def _get_pcode_comments(pcode):
"""
Pull out comments from the given p-code disassembly.
pcode - (str) The p-code disassembly.
return - (set) The set of comments.
"""
# Look at each line of the disassembly.
comments = set()
for line in pcode.split("\n"):
# Is this a comment i... |
def remove_return(str):
""" Returns a string without the return clause"""
return str.rstrip('\r\n') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.