content stringlengths 42 6.51k |
|---|
def is_ref(frag):
""" Test whether a given Bokeh object graph fragment is a reference.
A Bokeh "reference" is a ``dict`` with ``"type"`` and ``"id"`` keys.
Args:
frag (dict) : a fragment of a Bokeh object graph
Returns:
True, if the fragment is a reference, otherwise False
"""
... |
def cut_rod_bottom_up_extended(p, n):
"""
Only difference from book is p[i-1] instead of p[i] due to indexing, also
create to arrays to n+1 since range doesn't include end bound.
"""
r = [0 for k in range(n+1)]
s = [0 for k in range(n+1)]
for j in range(1, n+1):
q = -100000
f... |
def askwargs(kwargs_str):
"""Convenience function to read function args as string, all passed via keyword, and returned as the resulting
namespace as dictionary"""
toEval = lambda **kwargs : kwargs
return eval("toEval({})".format(kwargs_str)) |
def Bresenham(k,n):
"""Compute Euclidean rhythm of k pulses and length n."""
list = []
cumDiff = -k
for x in range(n):
if cumDiff < 0:
cumDiff += n
list.append(1)
else:
list.append(0)
cumDiff -= k
return(list) |
def score(word, f):
"""
word, a string of length > 1 of alphabetical
characters (upper and lowercase)
f, a function that takes in two int arguments and returns an int
Returns the score of word as defined by the method:
1) Score for each letter is its location in the alphabet... |
def normalize_social_kind(shape, properties, fid, zoom):
"""
Social facilities have an `amenity=social_facility` tag, but more
information is generally available in the `social_facility=*` tag, so it
is more informative to put that as the `kind`. We keep the old tag as
well, for disambiguation.
... |
def query_by_string(search_string: str, limit: int = 5) -> dict:
"""query to search wikipedia for pages containing search string.
options for search found here: https://www.mediawiki.org/wiki/API:Search
and for query here: https://www.mediawiki.org/wiki/API:Query"""
if not 0 < limit <= 500:
rai... |
def merge_dicts(dicts):
"""Combine multiple dictionaries.
> merge_dicts([{"a": 2}, {"b": 3}])
> {"a": 2, "b": 3}
"""
super_dict = {}
keys = []
for d in dicts:
for key, val in d.items():
super_dict[key] = val
return super_dict |
def format_for_latex(x, p=3):
"""Convert a float to a LaTeX-formatted string displaying the value to p significant
digits and in standard form.
Args:
x (float): Value.
p (:obj:`int`, optional): Number of significant digits. Default is 3.
Return:
s (str): Formatted value.
""... |
def zeroPrepender(source, length):
"""
Append extra zeros to a source number based on the specified length
"""
if (not source and source != 0) or not length:
return None
result = str(source)
if len(result) >= length:
return result
for i in range(length - len(result)):
... |
def capitalize_first_character(some_string):
"""Description: Capitalizes the first character of a string"""
return " ".join("".join([w[0].upper(), w[1:].lower()]) for w in some_string.split()) |
def subfields(type_field):
"""
Get a list of sub-fields from an avro record field.
"""
if isinstance(type_field, dict):
return type_field
else:
for avro_type in type_field:
if isinstance(avro_type, dict):
return avro_type |
def find_modified_cluster(clusters, added_items):
"""
Method to find cluster that changed when appending an item
:param clusters: List of clusters of chips
:param added_items: Item(s) that were added to the board
:return: clusters in which added item is found
"""
changed_clusters = []
fo... |
def getColor (value):
"""Returns a color name dependent on value.
:param value: The integer that determines the color
:type value: int
:return: The color appropriate to the integer
:rtype: str
"""
if 95 <= value <= 100:
return "darkred"
if 90 <= value <= 94:
return "red"... |
def poet_name_of(dir_name):
"""
Get the poet name from directory name
"""
if '_' not in dir_name:
return None
split_index = dir_name.rfind('_')
return dir_name[:split_index] |
def check_not_empty_list(lis1):
"""Checks for empty list.
Returns 1 when the list is not empty."""
if not lis1:
return 0
else:
return 1 |
def rit_interactions(all_rit_tree_data):
"""
Extracts all interactions produced by one run of RIT
To get interactions across many runs of RIT (like when we do bootstrap \
sampling for stability),
first concantenate those dictionaries into one
Parameters
------
all_rit_tree_data ... |
def convert_collection_to_path_param(collection):
"""
Convert a list of elements to a valid path parameter by concatenating
with ",".
This is used when calling some endpoints that require a list of instance ids.
If the collection parameter is not of type ``list``, ``tuple``, ``str`` or ``int``, ``N... |
def build_ohsome_filters(layer: dict):
"""
Builds the filter string based a dictionary of tags
:param layer: Dictionary containing tags, geoms and type information for ohsome request
:return:
"""
tag_filters = []
for key, values in layer["tags"].items():
if isinstance(values, list):
... |
def get_hap_vals(hap_hits, hap_vals, _type):
"""Returns list of haplotype name or frequency values
for a given variant, using the boolean array and
list of possible values"""
haps = []
for i, hap_hit in enumerate(hap_hits):
if hap_hit:
if _type is float:
hap... |
def check_wildcard(term):
"""Returns True if term is a wildcard term
"""
wildcard = True
letters = "zxcvbnmasdfghjklqwertyuiop"
letter = 0
while letter < len(letters) and term.lower() != "?" + letters[letter]:
letter += 1
if letter == len(letters):
# got to the end so not a w... |
def extract_name_path(file_path):
"""String formatting to update the prefix of the ERA5 store location to Azure"""
tgt = "az://cmip6/ERA5/" + file_path.split("/zarr/")[1].replace("/data", "")
return tgt |
def validacion_entero(entero):
"""float -> bool
OBJ: Validar si el dato introducido por el usuario es un numero entero"""
try:
elem = int(entero)
validacion = True
except:
print("El dato introducido no es un numero entero.")
validacion = False
return validacion |
def combine_filters(collections, languages, preservations):
"""Make filter dictionary from user inputs. Used to filter catalogue data.
Args:
collections (list of str): List of terms that should be ....
languages (list of str):
preservations (list of str):
Return:
filters (... |
def find_first(l, k):
""" Assumes that 'l' is a list of integars and is sorted """
# Input checks
if len(l) is 0:
return -1
# Initialize binary search params
result = -1
upper = len(l) - 1
lower = 0
# Search loop
while lower <= upper:
# Calculate middle index
... |
def single_pcrosstalk(total_pcrosstalk: float) -> float:
"""
Inverse formula to ``total_pcrosstalk''
Parameters
----------
total_pcrosstalk : float
The probability of total crosstalk events.
Returns
-------
p_crosstalk : float
The probability of a single crosstalk event... |
def propset_dict(propset):
"""Turn a propset list into a dictionary
PropSet is an optional attribute on ObjectContent objects
that are returned by the VMware API.
You can read more about these at:
| http://pubs.vmware.com/vsphere-51/index.jsp
| #com.vmware.wssdk.apiref.doc/
| vmo... |
def parameter_print(parameters_in):
"""
Takes a list of parameters and turns it into a single string (with line breaks)
The first item in the list is the parameter name and the second is the description.
pre-condition: cursor is at the end of the previous line
post-condition: cursor is at the end o... |
def validate_name(name: str) -> str:
"""
Validates the name of an object.
:param name: The name of the object.
:return: The validated name.
"""
if not name:
raise ValueError("Name must not be empty.")
if len(name) > 255:
raise ValueError("Name must not be longer than 255 cha... |
def high_nibble(n: int) -> int:
"""
>>> bin(high_nibble(0b10010000))
'0b1001'
"""
return (n >> 4) & 0x0F |
def allowed_file(app, filename):
"""
For a given file, return whether it's an allowed type or not
"""
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] |
def muli(registers, opcodes):
"""muli (multiply immediate) stores into register C the
result of multiplying register A and value B."""
test_result = registers[opcodes[1]] * opcodes[2]
return test_result |
def _is_num(data):
"""Verify if data is either int or float.
Could be replaced by:
from numbers import Number as number
isinstance(data, number)
but that requires Python v2.6+.
"""
return isinstance(data, int) or isinstance(data, float) |
def fibonacci(n):
"""
Use this function to get CPU usage
"""
return n if n < 2 else fibonacci(n-1) + fibonacci(n-2) |
def get_ip(record, direction):
"""
Return required IPv4 or IPv6 address (source or destination) from given record.
:param record: JSON record searched for IP
:param direction: string from which IP will be searched (e.g. "source" => ipfix.sourceIPv4Address or
"destination" => ipfix... |
def mro_lookup(cls, attr, stop=(), monkey_patched=[]):
"""Return the first node by MRO order that defines an attribute.
:keyword stop: A list of types that if reached will stop the search.
:keyword monkey_patched: Use one of the stop classes if the attr's
module origin is not in this list, this to ... |
def l42(pos, b, l):
""" Find out if position is over line 4
left
"""
x, y = pos
if (x >= 0):
return True
else:
return False |
def find_out_of_order_packet_indices(packet_ns):
"""
Return indices of packets which have apparently arrived out-of-order.
Specifically: return indices of any packet number which was less than the
previous packet number. For example, for the list of packet numbers:
0, 1, 2, 3, 5, 4, 6, 7.
re... |
def get_rules_list(warnings):
"""This function gets a list of the rules contained in a set of warnings.
Inputs:
- warnings: List of warnings to be examined [list of dicts]
Outputs:
- rules_list: List of queries contained in the list of warnings [list of strings]
"""
# Initialize v... |
def get_unique_tokens(geneset_name):
"""
Delimit the input `geneset_name` by "; ", and return a new string
that includes only unique tokens delimited by "; ".
"""
tokens = geneset_name.split("; ")
uniq_tokens = []
for t in tokens:
if t not in uniq_tokens:
uniq_tokens.app... |
def get_current_site(request):
"""
Return current site.
This is a copy of Open edX's `openedx.core.djangoapps.theming.helpers.get_current_site`.
Returns:
(django.contrib.sites.models.Site): returns current site
"""
return getattr(request, 'site', None) |
def validate_identifier(key: str):
"""Check if key starts with alphabetic or underscore character."""
key = key.strip()
return key[0].isalpha() or key.startswith("_") |
def is_rad_pair(a: int, b: int) -> bool:
"""Return True if and only if the pair (a, b) is a RadPair."""
assert type(a) == int
assert type(b) == int
assert 1 <= a <= b <= 9
ab = a * b
ones_digit_ab = ab % 10
tens_digit_ab = ab // 10
d_exists: bool = False
for d in range(1, 10):
... |
def _(value: str) -> bytes:
"""Convert ``str`` to bytes"""
return value.encode('utf-8') |
def convert(num):
"""
format the number like "0001","0012","0123","1234"
-------------------------------------------------------------------------
parameter:
num: int, the number to be formatted
-------------------------------------------------------------------------
return:
num... |
def _get_docs(all_lines, index_1, func_lines):
"""function _get_docs
Args:
all_lines:
index_1:
func_lines:
Returns:
"""
response=[]
detect_block = False
start = ''
for line in all_lines[index_1-1:]:
# print(line)
# start block com... |
def insertion_sort(li):
""" [list of int] => [list of int]
Insertion sort: works by taking elements from the list one
by one and inserting them in their correct position into a
new sorted list similar to how we put money in our wallet.
"""
# append first item of li
sorted_list = [li[0]]
... |
def change_color(color):
""" Prints escape code to change text color
"""
color_code = {'red':91, 'green':92, 'yellow':93, 'blue':94,
'magenta':95, 'cyan':96, 'white':98, 'none':0}
return '\033[{}m'.format(color_code[color]) |
def condition_2(arg):
"""
CONDITION 2: It contains at least 3 vowels out of 5(a,e,i,o,u) like 'aei'.
:param arg:
:return:
"""
vowel = "aeiou"
count = 0
for letters in arg:
if letters in vowel:
count += 1
if count >= 3:
return True
else:... |
def wrap(x, m, M):
"""Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
For example, m = -180, M = 180 (degrees), x = 360 --> returns 0.
Args:
x: a scalar
m: minimum possible value in range
M: ma... |
def flatten_routes(routes):
"""
Flattens the grouped routes into a single list of routes.
"""
route_collection = []
for route in routes:
# Check if a route is a list of routes
if isinstance(route, list):
for r in flatten_routes(route):
route_collection.app... |
def gen_mask(n: int) -> int:
"""
Will create a n bit long mask.
This works by creating a byte with a 1 at the n+1 place.
Subtracting this with one will make all previus bits 1, thus creating
a byte with the first n bits set.
>>> bin(gen_mask(3))
'0b111'
>>> bin(gen_mask(2))
'0b11'
... |
def permutations(iterable):
"""permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)"""
out=[]
pool = tuple(iterable)
n = len(pool)
r = n
indices = list(range(n))
cycles = list(range(n-r+1, n+1))[::-1]
out.append( tuple([pool[i] for i in indices[:r]]))
while 1:
fo... |
def base_validator(name, value, conditions):
"""Validates value based on dictionary of conditions"""
msg = f"""Input {name} must be one of `{tuple(conditions.keys())},`
received {value!r} instead.
"""
assert value in conditions.keys(), msg
return conditions[value] |
def sign(x) -> int:
"""Sign function.
:return -1 if x < 0, else return 1
"""
if x < 0:
return -1
else:
return 1 |
def to_int(value):
"""Convert binary sysctl value to integer."""
return int.from_bytes(value, byteorder="little") |
def Do_from_WT(Di, WT):
"""Calculate pipe outer diameter from inner diameter and wall thickness.
"""
return Di + 2 * WT |
def dist_mapper(dist, package):
"""
Add download_url from source tag, if present. Typically only present in
composer.lock
"""
url = dist.get('url')
if not url:
return package
package.download_url = url
return package |
def to_ternary_int(val) -> int:
"""Convert a value to the ternary 1/0/-1 int used for True/None/False in
attributes such as SENT_START: True/1/1.0 is 1 (True), None/0/0.0 is 0
(None), any other values are -1 (False).
"""
if val is True:
return 1
elif val is None:
return 0
eli... |
def get_system_manager_services(base_services, optional_services):
"""Services the status of which we keep track of.
:return: a dict of {service_name: label}
"""
services = {}
# Use updates to avoid mutating the 'constant'
services.update(base_services)
services.update(optional_services)
... |
def parse_tags(raw_tags_list):
"""Parse AWS tags.
Examples:
>>> from pprint import pprint
>>> pprint(parse_tags(['name="Peanut Pug"', 'age=5']))
[{'Key': 'name', 'Value': '"Peanut Pug"'}, {'Key': 'age', 'Value': '5'}]
"""
tags_dict_list = []
for raw_tag in raw_tags_list:
... |
def jenkins_api_query_build_statuses(jenkins_url):
"""Construct API query to Jenkins (CI)."""
return "{url}/api/json?tree=builds[result,number]".format(url=jenkins_url) |
def _combine_prg_roles(user_prg_roles, startup_prg_roles):
"""
Collapse two dictionaries with list values into one by merging
lists having the same key
"""
for key, value in startup_prg_roles.items():
if user_prg_roles.get(key):
user_prg_roles[key] = user_prg_roles[key] + value
... |
def calculate(byteArray):
"""calculates the CRC from the byte array"""
# 32 bit shift register for CRC generation
# D0 - D15 :CRC shift register
# D16 : MSB after shift
# D17 - D31 : not used
# shift register preset with all ones
shiftReg = 0x0000FFFF
# generator polynom D0-D15: X^16 + X^12 + ... |
def sum_fibonaci_minus_sum_powers_of_two(total_lambs):
"""
I don't remember the original formulation.
Given total_lambs, an integer between 1 and 1000000000.
It computes the largest sum of consecutive (modified) Fibonaci numbers
which is not greater than total_lambs, the sum of powers of 2
whic... |
def lerp(startPos, endPos, percent):
"""Lerp function to move the player avatar object along with the main game loop.
:param startPos: The position of the player avatar object before the move.
:type startPos: list
:param endPos: The position that the player avatar object needs to move towards.
:typ... |
def concatenate_or_append(value, output): # O(1)
"""
Either concatenate a list or append to it, in order to keep list flattened
as list of lists
>>> concatenate_or_append([42], [])
[[42]]
>>> concatenate_or_append([[42, 49]], [[23, 35]])
[[23, 35], [42, 49]]
""... |
def _kamb_radius(n, sigma):
"""Radius of kernel for Kamb-style smoothing."""
a = sigma ** 2 / (float(n) + sigma ** 2)
return 1 - a |
def pawnModify(lst, pieceid):
"""Modifies a list based on piece id to take out invalid moves for pawns"""
assert len(lst) == 4, 'List size MUST be four for this to return valid results!'
if pieceid == 0:# If it's a white pawn, it can only move to top left and top right
lst = lst[:2]
if pieceid =... |
def send_chunk(fp, val, blocksize, start, end):
"""
(start, end): Inclusive lower bound, exclusive upper bound.
"""
for i in range(start, end, blocksize):
fp.write(
val[i:min(i + blocksize, end)]
)
return end - start |
def check_install(action):
"""Skip install check action
Parameters
----------
action : list
Returns
-------
bool
"""
return action not in ['install', 'upgrade', 'uninstall', 'verify'] |
def calculate_intrusion_aware_edge(img_shape, intrusion_ratio):
"""Calculate top and bottom edges of intrusion aware areas"""
height = img_shape[0]
if isinstance(intrusion_ratio, list):
return (int(height * intrusion_ratio[0]), int(height - height * intrusion_ratio[1]))
return (int(height * intr... |
def keep_lesser_x0_y0_zbt0_pair_in_dict(p, p1, p2):
"""Defines x0, y0, and zbt0 based on the group associated with the
lowest x0. Thus the new constants represent the point at the left-most
end of the combined plot.
:param p: plot to combine p1 and p2 into
:param p1: 1st plot to combine
:param p... |
def bits_to_base(x):
"""convert integer representation of two bits to correct base"""
if x == 0:
return 'T'
elif x == 1:
return 'C'
elif x == 2:
return 'A'
elif x == 3:
return 'G'
else:
raise ValueError('Only integers 0-3 are valid inputs') |
def relative_url(url_a: str, url_b: str) -> str:
"""Compute the relative path from URL A to URL B.
Arguments:
url_a: URL A.
url_b: URL B.
Returns:
The relative URL to go from A to B.
"""
parts_a = url_a.split("/")
url_b, anchor = url_b.split("#", 1)
parts_b = url_b.... |
def dict_to_str(d, val_sep=' ', item_sep=' '):
"""Convert dict to string"""
str_list = [f'{k}{val_sep}{v}' for k, v in d.items()]
s = item_sep.join(str_list)
return s |
def is_yaml_file(file_name):
"""Verifies if a file ends in a valid yaml extension
Args:
file_name (string): The file name
Returns:
boolean: Whether it ends in the supported yaml extensions
"""
return file_name.endswith((".yaml", ".yml")) |
def split_tag(chunk_tag):
"""
split chunk tag into IOBES prefix and chunk_type
e.g.
B-PER -> (B, PER)
O -> (O, None)
"""
if chunk_tag == 'O':
return ('O', None)
return chunk_tag.split('-', maxsplit=1) |
def escape_string(string):
""" Escape a string for use in Gerrit commands.
Adds necessary escapes and surrounding double quotes to a
string so that it can be passed to any of the Gerrit commands
that require double-quoted strings.
"""
result = string
result = result.replace('\\', '\\\\')
... |
def disjunction_value(e, d):
"""The value of example e under disjunction d"""
for k, v in d.items():
if v[0] == '!':
# v is a NOT expression
# e[k], thus, should not be equal to v
if e[k] == v[1:]:
return False
elif e[k] != v:
retur... |
def is_the_original_invokation(event):
"""
Check if this is the original invokation or not.
"""
return False if 'domains' in event else True |
def _get_services_in_permissions(permissions_set):
"""
Given a set of permissions, return a sorted set of services
Args:
permissions_set
Returns:
services_set
"""
services_set = set()
for permission in permissions_set:
try:
service = permission.split(':'... |
def flip(txt: str, spec: str) -> str:
"""Flip the string, based on the word or sentence."""
if spec.lower() == 'word':
return " ".join(["".join(reversed(word)) for word in txt.split(' ')])
if spec.lower() == 'sentence':
return " ".join(txt.split(' ')[::-1])
raise ValueError(
f"Th... |
def get_file_mode_for_writing(context_tar):
"""Get file mode for writing from tar['format'].
This should return w:, w:gz, w:bz2 or w:xz. If user specified something
wacky in tar.Format, that's their business.
"""
format = context_tar.get('format', None)
# slightly weird double-check because fal... |
def simplify_path(path):
"""
:type path: str
:rtype: str
"""
skip = {"..", ".", ""}
stack = []
paths = path.split("/")
for tok in paths:
if tok == "..":
if stack:
stack.pop()
elif tok not in skip:
stack.append(tok)
return "/" + ... |
def _has_file(mod):
"""
:return: If given module has a not None __file__ attribute.
:rtype: ``bool``
"""
return hasattr(mod, '__file__') and mod.__file__ is not None |
def dict_key(d, k):
"""Returns the given key from a dictionary, or an empty list."""
return d.get(k, []) |
def add_open_source_license(answer):
"""Enable prompt for OS license type and author(s)"""
if not answer['check_license']:
return answer['gen_license']
else:
return False |
def lambda_tuple_converter(func):
"""
Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y
"""
if func is not None and func.__code__.co_argcount == 1:
return lambda *args: func(args[0] if len(args) == 1 else args)
else:
return... |
def external_trigger_slope(session, Type='Int32', RepCap='', AttrID=1150012, buffsize=0, action=['Get', '']):
"""[External Trigger Slope]
The required slope of the input signal as it crosses the trigger level to generate an External trigger.
Allowable values are Rising and Falling. The value on reset is: R... |
def get_web_url_from_stage(stage):
"""Return the full URL of given web environment.
:param stage: environment name. Can be one of 'preview', 'staging',
'production' or 'dev' (aliases: 'local', 'development').
"""
if stage in ['local', 'dev', 'development']:
return 'http://loca... |
def _ClassifySchemaNode(node_name, api):
"""Attempt to classify |node_name| in an API, determining whether |node_name|
refers to a type, function, event, or property in |api|.
"""
if '.' in node_name:
node_name, rest = node_name.split('.', 1)
else:
rest = None
for key, group in [('types', 'type'),
... |
def ifuse(inputs, pred_extent=None):
"""Fuse iterators"""
value, extent = 0, 1
for i, ext in inputs:
value = value * ext + i
extent = extent * ext
return value, extent if pred_extent is None else pred_extent |
def student_ranking(student_scores, student_names):
"""
:param student_scores: list of scores in descending order.
:param student_names: list of names in descending order by exam score.
:return: list of strings in format ["<rank>. <student name>: <score>"].
"""
student_ranking = []
for index... |
def key_to_rna(key):
"""Sets key to uppercase RNA."""
return key.upper().replace('T', 'U') |
def _board_is_full(board):
"""
Returns True if all positions in given board are occupied.
:param board: Game board.
"""
return all(['-' not in row for row in board]) |
def isiterable(variable):
"""
Check whether the given variable is iterable.
Lists, tuples, NumPy arrays, but strings as well are iterable. Integers,
however, are not.
Parameters
----------
variable :
variable to check for being iterable
Returns
-------
answer : :class:... |
def fixUri(uri, name, version=0):
"""
Conditions a URI to be suitable for freesitemgr
"""
# step 1 - lose any 'freenet:'
uri = uri.split("freenet:")[-1]
# step 2 - convert SSK@ to USK@
uri = uri.replace("SSK@", "USK@")
# step 3 - lose the path info
uri = uri.split("/")[0]
... |
def sumList(inList):
"""
calculates sum of the list
INPUT:
inList: input list
OUTPUT:
sum: sum of the input list
"""
sum = 0
for num in inList:
sum += num
return sum |
def total_xor(a):
""" Calculates the XOR total run from [0, a] """
# Special case:
if (a <= 0):
return 0
res = [a,1,a+1,0]
return res[a%4] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.