content stringlengths 42 6.51k |
|---|
def get_mode(elements):
"""The element(s) that occur most frequently in a data set."""
dictionary = {}
elements.sort()
for element in elements:
if element in dictionary:
dictionary[element] += 1
else:
dictionary[element] = 1
# Get the max value
max_value ... |
def backslash(path):
""" Convert the path to backslash-seperated one """
p = str(path)
ps = p.split('\\')
return '/'.join(ps) |
def get_opt_attr(obj_pyxb, attr_str, default_val=None):
"""Get an optional attribute value from a PyXB element.
The attributes for elements that are optional according to the schema and
not set in the PyXB object are present and set to None.
PyXB validation will fail if required elements are missing.
... |
def Expand2D(n):
"""
Encodes the 64 bit morton code for a 31 bit number in the 2D space using
a divide and conquer approach for separating the bits.
1 bit is not used because the integers are not unsigned
Args:
n (int): a 2D dimension
Returns:
int: 64 bit... |
def _is_greater(list1: list, list2: list):
"""
return True if `list1[i] > list2[i]` for each `i`
"""
return all([list1[i] > list2[i] for i in range(len(list1))]) |
def minify_sql(lines):
"""eliminate whitespace in sql queries"""
return '\n'.join(line.strip() for line in lines) |
def transform_case(input_string):
"""
Lowercase string fields
"""
return input_string.lower() |
def get_tag(tags, key):
""" Returns a specific value in aws tags, from specified key
"""
names = [item['Value'] for item in tags if item['Key'] == key]
if not names:
return ''
return names[0] |
def process_route_table(route_table):
"""Strip off unneeeded header information."""
route_table = route_table['TABLE_vrf']['ROW_vrf']['TABLE_addrf']['ROW_addrf']
return route_table['TABLE_prefix']['ROW_prefix'] |
def inConvergenceCorridor(d_struct, d_gc, BS_d_struct, BS_d_gc):
"""
Check if a solutions qualities are within the convergence corridor
"""
struct_var = ((BS_d_struct / float(4)) + 3) * 4
gc_var = (BS_d_gc + 1 / float(100) * 5) + BS_d_gc + 1
if d_struct <= struct_var and d_gc <= gc_var:
... |
def combat(health, damage):
"""Find remaining health after taking damage."""
return 0 if health - damage < 0 else health - damage |
def contract_range(seq):
"""
Contract a sequence of consecutive integers
[9, 10, 11, 12] --> '{09..12}'
"""
first, *rest = seq
if not rest:
return str(first)
# zfill first, embrace: eg: {09..12}
*middle, last = rest
sep = '..' if middle else ','
first, last = str(... |
def get_reference_cache_path(local: str, refcounty: str) -> str:
"""Gets the filename of the (house number) reference cache file."""
return local + "-" + refcounty + "-v1.pickle" |
def custom_distance(a, b):
"""calculate distance between two list by custom way"""
return sum([abs(i - j) ** 2 for (i, j) in zip(a, b)]) / len(a) |
def spectral_data_remap_samples(samples):
"""
The NOAA API has 5 different spectral data sets that have different meaning but are encoded
in a similar way. This function parses the data lines for each of the spectral data set
:param samples: An array of samples
:return: A array of sample pair a... |
def autorange_xy(img, axx, axy, data, xy_limits, xy_pad):
""" Adjust axx and axy vertical range.
xy_limits:
None or "auto" # matplotlib default range
(min, max) # vrange to specified values
"data" # vrange to min and max of data -/+ xy_pad
"... |
def sum2(a,b):
"""
:param a: (float) Primer variable a sumar
:param b: (float) Segunda varaible a sumar
:return c: (float) c=a+b
"""
c = a + b
return c |
def replaceFuncObj(obj):
"""
Function for/to <short description of `netpyne.sim.utils.replaceFuncObj`>
Parameters
----------
obj : <type>
<Short description of obj>
**Default:** *required*
"""
if type(obj) == list:
for item in obj:
if type(item) in [l... |
def reciprocal(b, c, d):
"""
>>> reciprocal(0, 0, 1)
>>> reciprocal(0, 1, 1)
(0, -1, 1)
"""
if b == c == 0:
return None
return (d*b, 0-d*c, b*b + c*c) |
def sanitize_user_name(username):
"""Format user name.
Remove the @ if a string starts with it.
"""
if username.startswith("@"):
username = username[1:] # remove "@"
return username.lower() |
def quadraticEquationV1(m, x, b):
"""
equation: y = m*x + b
params:
m = slope
x = position on x axis
b = y intercept
returns:
y = position on the y axis
"""
# multiply m and x and store the value into a variable
# add the product of m and x to ... |
def test_func_annotations(module, skiplist=None):
"""Code quality: Test that all functions in module have annotations"""
from inspect import getmembers
from inspect import isfunction
from inspect import getfullargspec
# Modify this to skip certain functions:
skip_list = skiplist or []
# fa... |
def coulomb(r, q1, q2, lam, charge_coeff):
"""
Computes the Coulomb potential
Parameters
----------
q1: float
Coulomb charge for particle 1
q2: float
Coulomb charge for particle 1
grid.ri: ndarray
In the context of rism, ri corresponds to grid points upon which
... |
def trim_from_start(s, substring):
"""Trims a substring from the target string (if it exists) returning the trimmed string.
Otherwise returns original target string."""
if s.startswith(substring):
s = s[len(substring) :]
return s |
def filter_unicode(unistr):
"""
Sometimes unicode chars can cause problems
"""
return "".join([i if ord(i) < 128 else ' ' for i in unistr]) |
def clean_errors(errors):
"""
"""
new_errors = dict()
for k, v in errors.items():
if v is not None:
new_errors[k] = v
return new_errors |
def format_devices_table(devlist):
""" put devices list into HTML table """
table = '<table border="1" cellpadding="5" cellspacing="5">'
table += '<caption>List of available resources:</caption>'
table += '<tr> <th>Device(s)</th> </tr>'
for i in devlist:
table += '<tr> <td>{}</td> </tr... |
def isInteger(n, epsilon=1e-6):
"""
Returns True if n is integer within error epsilon
"""
return (n - int(n)) < epsilon |
def dectobin(dec_string):
"""Convert a decimal string to binary string"""
bin_string = bin(int(dec_string))
return bin_string[2:] |
def calc_received_power(eirp, path_loss, receiver_gain, losses):
"""
Calculates the power received at the User Equipment (UE).
Parameters
----------
eirp : float
The Equivalent Isotropically Radiated Power in dB.
path_loss : float
The free space path loss over the given distance... |
def _positivify(index, size):
"""Return a positive index offset from a Sequence's start."""
if index is None or index >= 0:
return index
elif index < 0:
return size + index |
def sizeof_fmt(num, suffix='B'):
""" Converts byte size to human-readable format """
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix) |
def fzs(*args):
"""
Generate a set of frozensets of args. This is needed, because set cannot be a member of a set.
>>> fzs({'a', 'b'}, 'c') == {frozenset({'a', 'b'}), frozenset({'c'})}
"""
return {frozenset(s) if isinstance(s, set) else frozenset({s}) for s in args} |
def _escape_json_string(raw_str) :
""" Escape special characters """
result = ""
index = 0
begin_index = 0
for char in raw_str :
escaped = None
if char == '\b' :
escaped = "\\b"
elif char == '\f' :
escaped = "\\f"
elif char == '\n' :
escaped = "\\n"
elif char == '\r' :
... |
def get_next_active_day(days, current_day, active_days):
"""Gets the next active day, often this will simply be the next day, i.e. if you set the active days as Mon - Fri
and today is Mon, then the next active day is Tue. However is today is Fri then the next active day will be Mon.
If say our active days ... |
def test_exif(h, f):
"""JPEG data in Exif format"""
if h[6:10] == 'Exif':
return 'jpeg' |
def riffle(deck):
"""Produces a single, perfect riffle shuffle of DECK, consisting of
DECK[0], DECK[M], DECK[1], DECK[M+1], ... where M is position of the
second half of the deck. Assume that len(DECK) is even.
>>> riffle([3, 4, 5, 6])
[3, 5, 4, 6]
>>> riffle(range(20))
[0, 10, 1, 11, 2, 12... |
def choicify(values):
"""Takes an iterable and makes an iterable of tuples with it"""
return [(v, v) for v in values] |
def make_chipmatch_shortlists(qreq_, cm_list, nNameShortList, nAnnotPerName, score_method='nsum'):
"""
Makes shortlists for reranking
CommandLine:
python -m ibeis.algo.hots.scoring --test-make_chipmatch_shortlists --show
Example:
>>> # ENABLE_DOCTEST
>>> from ibeis.algo.hots.sc... |
def solve(N, p, q, r, s):
""" solve the problem """
#print(N, p, q, r, s)
items = [(i * p + q) % r + s for i in range(N)]
#print('items: ', items)
_sum = sum(items)
part = _sum / 3
#print(part)
part1 = 0
part2 = 0
part3 = 0
i = 0
j = N-1
while part1 + items[i] < pa... |
def resta_complejos (a,b,c,d):
"""
int,int,int,int --> bool
OBJ: resta de 2 complejos
"""
return a-c, b-d |
def norm_ws(s):
"""Normalize whitespace in the given string."""
return ' '.join(s.strip().split()) |
def result_file_name(outdir, label):
""" Returns the standard filename used for a result file
Parameters
----------
outdir: str
Name of the output directory
label: str
Naming scheme of the output file
Returns
-------
str: File name of the output file
"""
return ... |
def breadcrumbs(items, title):
"""
Breadcrumbs widget, to help user navigate.
Home > Users > John > Privacy
:param items: list of the links, from root to last child
:param title: A title (non-clickable) of the last child
"""
return {
"class": "breadcrumbs",
"links": items,
... |
def parse_acc_type(infodict):
"""
tell if this entry is a gsm accesion or a srx accession
"""
for acc, info in infodict.items():
if acc.startswith("SRX"):
info["type"] = "srx"
elif acc.startswith("GSM"):
info["type"] = "gsm"
else:
ValueError("I... |
def kdelta(i: int, j: int):
"""
kronecker delta function
"""
return 1. if i == j else 0. |
def _arg_to_empty(name: str) -> str:
"""
Convert an argument name to an "empty" placeholder
for an argument to later be filled in. Used by the jobmon TaskTemplate.
E.g. takes something that looks like "model_version_id" and
converts it to "{model_version_id}"
Parameters
----------
name
... |
def is_curie_type(o):
"""return True if object is a python jsonschema class that represents
a CURIE, e.g., sequence_id
"""
return o.__class__.__name__.endswith("/CURIE") |
def to_lsp_name(method_name):
"""Convert method name to LSP real name
Example:
text_document__did_open -> textDocument/didOpen
"""
method_name = method_name.replace('__', '/')
m_chars = list(method_name)
m_replaced = []
for i, ch in enumerate(m_chars):
if ch == '_':
... |
def parse_gs_spin(gs_spin):
"""Parses nubase style spin information
returns dictionary {value, extrapolated} """
result = {}
gs_spin = gs_spin.strip()
result['extrapolated'] = True if gs_spin.count('#') > 0 else False
if result['extrapolated']:
gs_spin = gs_spin.replace('#', ' ')
... |
def try_import(module):
"""Try to import and return module, or return
None if the module does not exist."""
from importlib import import_module
try:
return import_module(module)
except ImportError:
pass |
def _default_json_serializer(obj):
"""Create serialization method."""
try:
return obj.__dict__
except AttributeError:
return str(obj) |
def validate_key_parse(data):
"""
Validate key is a numerical value string and parse it.
:param dict data: Data to be validated
"""
validated_data = {int(key): str(value) for key, value
in data.items() if key.isdigit()}
return validated_data if len(validated_data) == len(... |
def _GaeBuilderPackagePath(runtime):
"""GCR package path for a builder that works on the given appengine runtime.
Args:
runtime: Name of a runtime from app.yaml, e.g. 'python38'.
Returns:
gcr.io image path.
"""
return 'gcr.io/gae-runtimes/buildpacks/%s/builder:latest' % runtime |
def get_cmdb_detail_apps(cmdb_detail):
"""
Iterate over CMDB details from response.
This method is used in "risksense-get-apps" command.
:param cmdb_detail: CMDB details from response
:return: List of CMDB elements which includes required fields from resp.
"""
return {
'Manufactured... |
def make_numbered_prefix(file_number,number_digits=5):
"""
returns a number string designed to be used in the prefix of
systematic outputs.
example use case
"00001example_output_file.txt"
"00002example_output_file.txt"
input::
file_number (int):
the numb... |
def GetColorWidthLod(street_type):
"""Returns a list of color, width and minLodPixels for a given street type
"""
d = {
'ACCESS' : ['7fff0000', 4, 2048], # blue
'COLLECTOR' : ['7f336699', 4, 2048], # brown
'HIGHWAY' : ['7fffff00', 4, 512], # cyan
'LANE' : ['7f00ff00', 4, 4096], # green
... |
def to_units(td):
"""Pretty prints the time in the right units.
Parameters
----------
td : float
The time to be printed.
Returns
-------
str
The printed time
"""
if td > 1e-6:
return "%.4f us" % (td * 1e6)
if td > 1e-9:
return "%.4f ns" % (t... |
def picker(items, item_name="choice"):
"""A picker for a list of items
Args:
items (list[any]): The list to pick from
item_name (str, optional): A friendly name of what an item is. Defaults to "choice".
Raises:
ValueError: If the user enters invalid input
Returns:
any:... |
def load_l8_clouds_fmask(l8bqa):
"""
https://www.usgs.gov/land-resources/nli/landsat/landsat-collection-1-level-1-quality-assessment-band
https://www.usgs.gov/land-resources/nli/landsat/cfmask-algorithm
:param l8bqa:
:return:
"""
return (l8bqa & (1 << 4)) != 0 |
def str2min(time_str):
"""
Convert hh:mm:ss to minutes since midnight
"""
spl = time_str.strip().split(":")
h, m, s = spl
return int(h) * 60 + int(m) |
def factorial(n):
"""
Calcula el factorial de n.
n int > 0
return n!
"""
print(n)
if n == 1:
return 1
else:
return (n * factorial(n - 1)) |
def to_int(toks):
""" Parser action for converting strings of digits to int. """
return int(toks[0]) |
def hello(name='world'):
"""
Return a greeting for the given name
"""
return 'Hello, {}'.format(name) |
def parse_key(keys, v, defaults):
"""
>>> parse_key(['a', 'b'], '1', {'a': {'b': 2}})
{'a': {'b': 1}}
"""
key, *keys = keys
if key not in defaults:
raise ValueError("Unknown key: ", key)
if not keys:
return {key: type(defaults[key])(v)}
return {key: parse_key(keys, v, def... |
def make_contract_jsons(contract_blob, date, division):
"""
parse a day's worth of contracts in JSON format to be a list of
dictionaries where every single contract announcement (blob) is parsed and
made into a row of a dataframe.
Returns: Array (most will be len 1) of parsed-out json strings.
... |
def mode(vec):
"""Returning most occuring number
of a given array"""
Map = {} # Adding to hash
count = 0
val = 0
for i in vec: # O(n)
if i in Map.keys():
Map[i] += 1 # O(1)
else:
Map[i] = 1 # O(1)
for i in Map: ... |
def _infer_proplot_dict(kw_params):
"""
Infer values for proplot's "added" parameters from stylesheet parameters.
"""
kw_proplot = {}
mpl_to_proplot = {
'xtick.labelsize': (
'tick.labelsize', 'grid.labelsize',
),
'ytick.labelsize': (
'tick.labelsize', ... |
def locate_moves(moves, all_possible_moves):
"""Index moves into the total possible set of moves."""
index = []
for m in moves:
try:
i = all_possible_moves.index(m)
index.append(i)
except ValueError:
pass
return index |
def updateState(posPlayer, posBox, action):
"""Return updated game state after an action is taken"""
xPlayer, yPlayer = posPlayer # the previous position of player
newPosPlayer = [xPlayer + action[0], yPlayer + action[1]] # the current position of player
posBox = [list(x) for x in posBox]
if action[... |
def is_Winding_dict(obj_dict):
"""Check if the object need to be updated for Winding"""
return (
"__class__" in obj_dict.keys()
and obj_dict["__class__"]
in [
"WindingCW1L",
"WindingCW2LR",
"WindingCW2LT",
"WindingDW1L",
"Windin... |
def email_subject_stix_pattern_producer(data):
"""Convert a host from TC to a STIX pattern."""
return f"[email-message:subject = '{data.get('summary')}']" |
def timedelta_to_seconds(td):
"""
Converts a timedelta to total seconds.
(This is built-in in Python 2.7)
"""
# we ignore microseconds for this
if not td:
return None
return td.seconds + td.days * 24 * 3600 |
def chemin_vers(s, dist_a, arc_vers):
"""Renvoie le chemin vers le sommet s."""
if dist_a[s] == None:
return None
chemin = []
arc = arc_vers[s]
while arc != None:
predecesseur = arc.origine
chemin.insert(0, predecesseur)
arc = arc_vers[predecesseur]
return chemi... |
def str_is_int(value: str) -> bool:
"""
:param value:
:return:
"""
if not value or isinstance(value, bool):
return False
if value[0] in ['-', '+']:
value = value[1:]
return value.isdigit() |
def to_string(buffer):
"""
This function makes a string of the data received, separating them with commas.
Args:
buffer (list): A list with the data received
Returns:
string: The string created
"""
for (pos, value) in enumerate(buffer):
if isinstance(value, flo... |
def duplication_consistency(set_one, set_two):
"""
Calculates the duplication consistency score for two sets of species
:param set_one: set/list of species
:param set_two: set/list of species
:return: float with duplication consistency score
"""
union_size = len(set(set_one).union(set(set_t... |
def isPower2(n):
"""
Check if num is power of two
"""
return ((n & (n - 1)) == 0) and n > 0 |
def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
:type num1: number
:param num1: The first number to find the lcm for
:type num2: number
:param num2: The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
... |
def sanitize(guid: str) -> str:
"""
Removes dashes and replaces ambiguous characters
:param guid: guid with either dashes or lowercase letters or ambiguous letters
:return: sanitized guid
"""
if not guid:
return ''
guid = guid.replace('-', '').upper().replace('I', '1').replace('L', ... |
def check_arrangement(d1, d2):
"""
Check if arrangements follow the rules
"""
rules = [[[1,4,9],[1,4,6]],[[0,6,8],[0,9,8]],[[5]],[[6],[9]],[[6],[9]],[[2]],[[0,1,3,4]],[None],[[1]]]
rule_followed = True
rule_index = 0
while rule_followed and rule_index<len(rules):
if rules[rule_index]... |
def _get_function_name_and_args(str_to_split):
"""
Split a string of into a meta-function name and list of arguments.
@param IN str_to_split String to split
@return Function name and list of arguments, as a pair
"""
parts = [s.strip() for s in str_to_split.split(" | ")]
if len(parts) < 2:
... |
def search_linears(a, x):
"""
Returns the index of x in a if present, None elsewhere.
"""
d = a[-1]
a[-1] = x
i = 0
while a[i] != x:
i += 1
a[-1] = d
if i == len(a) - 1 and d != x:
return None
else:
return i |
def egcd(a, b):
""" Calculate extended greatest common divisor """
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y) |
def ts_wavecal(pixels,tserSim=False,
obsFilter='F444W',subarray='SUBGRISM64',grism='GRISM0'):
"""
Simple analytic wavelength calibration for NIRCam grism time series
"""
disp = -0.0010035 ## microns per pixel (toward positive X in raw detector pixels, used in pynrc)
undevWav = 4.0 ## ... |
def bubble_sort(alist):
"""
:param alist:
:return:
"""
length = len(alist)
n = 0
n2 = 0
for i in range(length):
for j in range(i):
n += 1
if alist[j] > alist[i]:
n2 += 1
alist[i], alist[j] = alist[j], alist[i]
return al... |
def check_option_string(value, options):
"""Validate that a string is in a list of options.
Args:
value (string): The string value to test.
options (list): A list of strings to test against.
Returns:
A string error message if ``value`` is not in ``options``. ``None``
other... |
def dRackId(rackId):
"""Return rack id if valid, raise an exception in other case"""
if rackId >= 0:
return rackId
else:
raise ValueError(
'{} is not a valid Rack Id, Rack Id must be >= 0'.format(rackId)) |
def isSolved(problem):
"""
Given a two-dimensional list of sets, checks if every set contains exactly
one element.
:param list problem: list of sets
:return: True if every set contains exactly one element
:rtype: bool
"""
return all((len(col) == 1 for row in problem for col in row)) |
def build_all_reduce_device_prefixes(job_name, num_tasks):
"""Build list of device prefix names for all_reduce.
Args:
job_name: 'worker', 'ps' or 'localhost'.
num_tasks: number of jobs across which device names should be generated.
Returns:
A list of device name prefix strings. Each element spell... |
def isnum(num):
"""
Returns true if the inputted argument can be converted into a float or int
:param num:
:return: Boolean value
"""
try:
float(num)
except ValueError:
return False
return True |
def rivers_with_station(stations):
"""takes station object list.
returns a set of rivers which have stations."""
set_rivers = set()
for i in stations:
set_rivers.add(i.river)
return sorted(set_rivers) |
def galois_multiplication(a, b):
"""Galois multiplication of 8 bit characters a and b."""
p = 0
for counter in range(8):
if b & 1: p ^= a
hi_bit_set = a & 0x80
a <<= 1
# keep a 8 bit
a &= 0xFF
if hi_bit_set:
... |
def _op_name(tensor_name):
"""Get the op name from a tensor name."""
# control dependency inputs start with ^
if tensor_name[0] == '^':
tensor_name = tensor_name[1:]
if ':' in tensor_name:
op_name, _ = tensor_name.split(':')
return op_name
return tensor_name |
def lemmatize(tokens):
"""
A simple lemmatizer
"""
return [token.lower() for token in tokens] |
def is_bool(s):
""" Returns true if the object is a boolean value. """
return isinstance(s, bool) or str(s).lower() in ['true', 'false'] |
def remap(indices, mapping):
"""
Converts array of index values back into category values
"""
# values = []
# for i in range(0, len(indices)):
# values.append(mapping[indices[i]])
values = [mapping[indices[i]] for i in range(len(indices))]
return values |
def get_first_last_elem(sorted_list, nb_elem: int):
"""Return lists with first/last <nb_elem> elements
Args:
sorted_list(list): list of elements
nb_elem(int): number of first/last elements
Return:
first(list): first nb_elem elements of sorted_list
last(list): last nb_elem e... |
def process_character_space(text):
"""
:return text: cleaned text (either unchanged/ concatenated by character)
:return bool: whether text is procesesd by this func
"""
tokens = text.split()
tokens_len = [len(token) for token in tokens]
if all([_len == 1 for _len in tokens_len]) and len(toke... |
def count_construct_tbl(target, word_bank):
"""Counts the number of ways that 'target' can be constructed.
Args:
target (str): The string to be constructed.
word_bank (Iterable[str]): Collection of string from which 'target'
can be constructed.
Returns:
int: The number ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.