content stringlengths 42 6.51k |
|---|
def ValidateDomain(url):
"""
This function returns domain name removing http:// and https://
returns domain name only with or without www as user provided.
"""
# Check if http:// or https:// present remove it if present
domain_name = url.split('/')
if 'http:' in domain_name or 'htt... |
def list_sum(alist):
"""
Helper function to return the sum of all elements in the given list.
"""
sum = 0
for i in alist:
sum += i
return sum |
def _safely_get_members(component, member_names=None):
"""Gather stable members of a component.
Args:
component (object): The component from which to get the members from.
member_names (list): List of names of members to gather.
Returns:
list: of stable component members as tuples (member name... |
def split_import_components(import_statement):
"""
Given a (multi-line) import statement, return the base and components
from x.y import a, b, c
->
('x.y', ['a', 'b', 'c'])
"""
left, right = import_statement.split('import')
right = right \
.replace('(', '') \
... |
def retention_rate(customers_repurchasing_current_period,
customers_purchasing_previous_period):
"""Return the retention rate of customers acquired in one period who repurchased in another.
Args:
customers_repurchasing_current_period (int): The number of customers acquired in p1, who... |
def _format_text(n, length=20):
"""
Return a string with a certain length for readability
:param n: A string
:return: The string padded with spaces or trimmed
"""
return f'{n: >{length}}' |
def is_bijection(dictionary):
"""Check if a dictionary is a proper one-to-one mapping."""
return len(set(dictionary.keys())) == len(set(dictionary.values())) |
def exact_change_recursive(amount,coins):
""" Return the number of different ways a change of 'amount' can be
given using denominations given in the list of 'coins'
>>> exact_change_recursive(10,[50,20,10,5,2,1])
11
>>> exact_change_recursive(100,[100,50,20,10,5,2,1])
4563
... |
def to_ini_value(v):
"""
Provide a string or a Python built-in list or dict.
Variables may be complex built-in data structures, so format the
value to a string to determine if it contains a valid data
structure.
This will default `v` to an _empty_ string. It does so to be
functionality equ... |
def check_state_num(file_type, ifile):
""" check how many states in the input file """
states = []
with open(ifile, "r") as f:
if file_type == "seg":
for line in f:
line_split = line.strip().split('\t')
state = line_split[3]
if state not in... |
def direction_shorthand(direction: str):
"""
Process direction shorthand (e.g. out-> Outbound)
"""
if direction.lower() in ["out", "outbound"]:
return "Outbound"
elif direction.lower() in ["in", "inbound"]:
return "Inbound" |
def url(path=''):
"""Return URL with relative path appended."""
return f'https://helion.pl/autelion/{path.lstrip("/")}' |
def lowest(t1,t2):
"""Find consistent lowest of two tuples/lists"""
compare_len = min(len(t1), len(t2))
for i in range(0,compare_len):
if t1[i] < t2[i]:
return t1
elif t1[i] > t2[i]:
return t2
# if here, identical to compare_len; just pick one
return t1 |
def count_character(target_character, long_string):
"""Count target_character appearance in string
"""
count = 0
for character in long_string:
if target_character == character:
count += 1
return count |
def build_source_string(topic, message_type, strategy, slot=None, value_min=None, value_max=None):
"""
Builds source strings with some wizardry
"""
# both are required
ret = topic + ':' + message_type
# only add sub slots if parent slots exist
if slot:
ret += '-' + slot
# require... |
def contains_fragment(path):
"""True if path contains fragment id ('#' part)."""
return path.count('#') != 0 |
def _diff_serialiser(d):
"""Serialise diffenator's diff object"""
for k in d:
if isinstance(d[k], dict):
_diff_serialiser(d[k])
if isinstance(d[k], list):
for idx, item in enumerate(d[k]):
_diff_serialiser(item)
if hasattr(d[k], 'font'):
... |
def byte_to_str(data):
"""
convert data to str
:param data: data
:return: str(data)
"""
return str(
data if isinstance(data, str) else data.decode() if data is not None else ""
) |
def _gen_table_cols(colList):
"""Generate Dash table columns in the expected format.
:param colList: list of columns; must be in format <table-alias.name>,
like "s.serial_number"
"""
return [{'id' : col, 'name' : col} for col in colList] |
def contains_opposing_wording(text):
"""Words found in news articles that relates companies to nonprofits in a negative way:
criticism
criticized
"""
opposing_words = ['critic']
for word in opposing_words:
if word in text:
return True
return False |
def check_length(attributes):
"""
Check if the given list of element consists only 2 unique keys
:params: attribues - list of string
:return: True/False - whether exactly 2 unique key included
"""
cur_set = set()
for attribute in attributes:
cur_set.add(attribute)
return len(cur... |
def rgb_to_hex(red_component=None, green_component=None, blue_component=None):
"""Return color as #rrggbb for the given color tuple or component
values. Can be called as
TUPLE VERSION:
rgb_to_hex(COLORS['white']) or rgb_to_hex((128, 63, 96))
COMPONENT VERSION
rgb_to_hex(64, 183, 22)
... |
def move_up_right(columns, t):
""" A method that takes number of columns of the matrix
and coordinates of the bomb and returns coordinates of
neighbour which is located at the right-hand side and
above the bomb. It returns None if there isn't such a
neighbour """
x, y = t
if x == 0 or y == ... |
def byte_to_zwave_brightness(value: int) -> int:
"""Convert brightness in 0-255 scale to 0-99 scale.
`value` -- (int) Brightness byte value from 0-255.
"""
if value > 0:
return max(1, round((value / 255) * 99))
return 0 |
def build_friends_page_from_id(user_id):
"""
>>> build_friends_page_from_id(123)
'https://mbasic.facebook.com/profile.php?v=friends&id=123'
"""
return "https://mbasic.facebook.com/profile.php?v=friends&" + \
"id={0}".format(user_id) |
def map_ids(dict_list):
"""
Converts a list of dictionaries to a dictionary of dictionaries (i.e., a map), where the key is the ID ('id')
given as a key in the dictionaries.
Parameters
----------
dict_list : list of dicts
List of dictionaries containing the key 'id'.
Returns
--... |
def get_image_param(rnd):
"""
Assemble params for get_validate_image
:param rnd: rnd from LOGIN_EX_URL
:return: Param in dict
"""
param_dict = dict()
param_dict['rnd_code'] = "1"
param_dict['rnd'] = rnd
return param_dict |
def read_from_file(file_path :str, mode :str, clean_data = False) -> list:
"""
Function to read data from a specific and return it.
"""
file = open(file_path, mode)
file_data = file.readlines()
file.close()
if clean_data:
file = open(file_path, "w")
file.close()
... |
def to_compression_header(compression):
"""
Converts a compression string to the four byte field in a block
header.
"""
if not compression:
return b''
if isinstance(compression, str):
return compression.encode('ascii')
return compression |
def _format_timedelta(timedelta):
"""Returns human friendly audio stream duration."""
hours, seconds = divmod(timedelta, 3600)
minutes, seconds = divmod(seconds, 60)
return '{0:02.0f}:{1:02.0f}:{2:02.0f}'.format(hours, minutes, seconds) |
def cmake_cache_option(name, boolean_value, comment=""):
"""Generate a string for a cmake configuration option"""
value = "ON" if boolean_value else "OFF"
return 'set(%s %s CACHE BOOL "%s")\n\n' % (name, value, comment) |
def issue_2957():
"""
This is a very very very long line within a docstring that should trigger a pylint C0301 error line-too-long
Even spread on multiple lines, the disable command is still effective on very very very, maybe too much long docstring
"""#pylint: disable=line-too-long
return Tr... |
def amp_clamp(val):
"""
Clamps an incoming value to either -1 or 1.
:param val: Value to clamp
:type val: float
:return: Clamped value
:rtype: float
"""
if val > 1.0:
# Too big, clamp it
return 1.0
if val < -1.0:
# Too small, clamp it... |
def major_segments(s):
"""
Perform major segmenting on a string. Split the string by all of the major
breaks, and return the set of everything found. The breaks in this implementation
are single characters, but in Splunk proper they can be multiple characters.
A set is used because ordering doesn't ... |
def matches_tag(scenario_tags, tag_list):
"""If tags indicated on command line, returns True if a Scenario_tag matches
one given on the command line"""
if not tag_list:
return True
else:
return set(scenario_tags).intersection(tag_list) |
def isolate_fastener_type(target_fastener: str, fastener_data: dict) -> dict:
"""Split the fastener data 'type:value' strings into dictionary elements"""
result = {}
for size, parameters in fastener_data.items():
dimension_dict = {}
for type_dimension, value in parameters.items():
... |
def is_genotyped_or_well_imputed(info, r2=0):
"""Determine if the current variant was genotyped or was well-imputed
Parameters
----------
info : str
Data from the INFO column of an imputed VCF file
r2 : float
R-squared threshold for inclusion based on imputation quality
... |
def slice_axes(zdir):
"""Get volume dimensions corresponding to x and z axes of slice."""
if zdir == 0:
return (1, 2)
elif zdir == 1:
return (0, 2)
elif zdir == 2:
return (0, 1)
else:
raise Exception("Invalid zdir argument: " + zdir) |
def _validate_str_format_arg_and_kwargs_keys(args_keys, kwargs_keys):
"""check that str_format is entirely manual or entirely automatic field specification"""
if any(not x for x in kwargs_keys): # {} (automatic field numbering) show up as '' in args_keys
# so need to check that args_keys is empty and k... |
def depth_first_traverse_inorder(root):
"""
Traverse a binary tree in inorder
:param root: root node of the binary tree
:type root: TreeNode
:return: traversed list
:rtype: list[TreeNode]
"""
node_list = []
if root is not None:
node_list.extend(depth_first_traverse_inorder(r... |
def get_overall_misclassifications(H, training_points, classifier_to_misclassified):
"""Given an overall classifier H, a list of all training points, and a
dictionary mapping classifiers to the training points they misclassify,
returns a set containing the training points that H misclassifies.
H is repr... |
def format_number(x):
"""Format number to string
Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print
the entire floating point number. Any padding zeros will be removed at the end of the number.
See :ref:`user-guide:int` and :ref:`user-guide... |
def StartedButUnfinishedExtrapolations(TopLevelOutputDir, SubdirectoriesAndDataFiles):
"""Find directories with extrapolations that started but didn't finish."""
from os.path import exists
Unfinished = []
for Subdirectory, DataFile in SubdirectoriesAndDataFiles:
StartedFile = "{}/{}/.started_{}... |
def is_json_array(typename):
""" Check if a property type is an array.
For example: [int], [uuid4] are array
"""
return typename and typename.startswith('[') and typename.endswith(']') |
def parse_address(con):
"""
con: str for argument like "127.0.0.1:2379/deploy"
return: Tuple[str, str] like ("127.0.0.1:2379", "/deploy")
"""
pos = con.find('/')
return (con[:pos], con[pos:]) |
def get_text(raw):
"""Converts a raw bytestring to an ASCII string"""
ba = bytearray(raw)
s = ba.decode('ascii')
return s |
def mongo_convert(sch):
"""Converts a schema dictionary into a mongo-usable form."""
out = {}
for k in sch.keys():
if k == 'type':
out["bsonType"] = sch[k]
elif isinstance(sch[k], list):
out["minimum"] = sch[k][0]
out["maximum"] = sch[k][1]
elif is... |
def mimetype_to_msgtype(mimetype: str) -> str:
"""Turn a mimetype into a matrix message type."""
if mimetype.startswith("image"):
return "m.image"
elif mimetype.startswith("video"):
return "m.video"
elif mimetype.startswith("audio"):
return "m.audio"
return "m.file" |
def Copy(*_args, **_kw):
"""Fake Copy"""
return ["fake"] |
def bytes_xor(bytes_a: bytes, bytes_b: bytes) -> bytes:
"""Return the XOR between A and B."""
if len(bytes_a) != len(bytes_b):
raise ValueError('Expected equal length octet strings')
return bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) |
def LastNItems(iterable, n, dropLastN=0):
"""
Generator yielding the final n items of a finite stream. Of those
final items, the last dropLastN items are omitted if dropLastN > 0.
The number of items yielded is max(0, min(n, N) - dropLastN)) where
N is the number of items yielded by the input iter... |
def min_spacing(mylist):
"""
Find the minimum spacing in the list.
Args:
mylist (list): A list of integer/float.
Returns:
int/float: Minimum spacing within the list.
"""
# Set the maximum of the minimum spacing.
min_space = max(mylist) - min(mylist)
# Iteratively find ... |
def params_schedule_fn_constant_07_03(outside_info):
"""
In this preliminary version, the outside information is ignored
"""
mdp_default_gen_params = {
"inner_shape": (7, 5),
"prop_empty": 0.7,
"prop_feats": 0.3,
"start_all_orders": [
{"ingredients": ["onion",... |
def remove_subject(subject, metric, dict_exclude_subj):
"""
Check if subject should be removed
:param subject:
:param metric:
:param dict_exclude_subj: dictionary with subjects to exclude from analysis (due to bad data quality, etc.)
:return: Bool
"""
if metric in dict_exclude_subj.keys(... |
def measure_option(measure_func,
number=1,
repeat=1,
timeout=60,
parallel_num=1,
do_fork=True,
build_func='default',
check_correctness=False,
replay_db=None):
"""Co... |
def function_arg_count(fn):
""" returns how many arguments a funciton has """
assert callable(fn), 'function_arg_count needed a callable function, not {0}'.format(repr(fn))
if hasattr(fn, '__code__') and hasattr(fn.__code__, 'co_argcount'):
return fn.__code__.co_argcount
else:
return 1 |
def test_function(x):
"""
A scalar test function with a single minimum value on [-1,1]
"""
x_zero = 0.1234
return (x - x_zero)*(x - x_zero) |
def tryint(value: str) -> int:
"""Try Parse Int.
Attempts to parse a string integer into an integer, returns 0 if
string is not a number.
"""
if isinstance(value, int):
return value
if isinstance(value, str):
if value.isdecimal():
return int(value)
return 0 |
def bytes_to_text(byte_array, encoding='UTF-8'):
"""
Decode a byte array to a string following the given encoding.
:param byte_array: Byte array to decode.
:param encoding: String encoding (default UTF-8)
:return: a decoded string
"""
return bytes(byte_array).decode(encoding) |
def is_palindrome(some_str: str) -> bool:
"""
Accepts a string
Returns whether or not string is palindrome
:param some_str:
:return:
"""
return some_str == some_str[::-1] |
def MI_Tuple(value, Is):
"""
Define function for obtaining multiindex tuple from index value
value: flattened index position, Is: Number of values for each index dimension
Example: MI_Tuple(10, [3,4,2,6]) returns [0,0,1,4]
MI_Tuple is the inverse of Tuple_MI.
"""
IsValuesRev = []
Cu... |
def in_range(x: int, minimum: int, maximum: int) -> bool:
""" Return True if x is >= minimum and <= maximum. """
return (x >= minimum and x <= maximum) |
def encode_pdf(pdf):
"""Encode the probability density function."""
count = len(pdf)
pdf = map(lambda x: '(' + str(x[0]) + ', ' + str(x[1]) + ')', pdf)
pdf = '[' + ', '.join(pdf) + ']'
return pdf |
def fnsplit(fn):
"""/path/fnr.x -> (/path/fnr, x) when possible. Non-str treated as None."""
if not (isinstance(fn, str) and fn):
return (None, None)
fn = fn.strip()
if not fn:
return (None, None)
x = fn.rfind('.')
if x == -1:
return fn, None
return (fn[:x], fn[x:]) |
def _get_dbg_fn_vis(code):
"""
Create a wrapper for the python statements, that encodes the debugging
logic for the matcher.
"""
spacer_basic = ' '
wrapped_code = "def debug_fn(): \n"
wrapped_code += spacer_basic + "node_list = []\n"
upd_code = [spacer_basic + e + "\n" for e in code]... |
def point_in_polygon(polygon, point):
"""
Raycasting Algorithm to find out whether a point is in a given polygon.
Performs the even-odd-rule Algorithm to find out whether a point is in a given polygon.
This runs in O(n) where n is the number of edges of the polygon.
*
:param polygon: an array r... |
def truncate_name(text):
"""Ensure the comic name does not exceed 50 characters."""
return text[:50] |
def cf_and(a, b):
"""The AND of two certainty factors."""
return min(a, b) |
def _cleanup_path(path):
"""Return a cleaned-up Subversion filesystem path"""
return '/'.join([pp for pp in path.split('/') if pp]) |
def clean_dict(orig_dict: dict) -> dict:
"""Removes items with null values from dict."""
return {k: v for k, v in orig_dict.items() if v is not None} |
def post_process(rect, confidence="Unknown"):
"""
rect: list of 2 tuples (x, y)
"""
# l = min(rect[0][0], rect[1][0])
# t = min(rect[0][1], rect[1][1])
# r = max(rect[0][0], rect[1][0])
# b = max(rect[0][1], rect[1][1])
l = rect[0][0]
t = rect[0][1]
r = rect[1][0]
b = rect[1]... |
def FlattenList(list):
"""Flattens a list of lists."""
return [item for sublist in list for item in sublist] |
def fv_f(pv,r,n):
"""
Objective : estimate furuew value
pv : present value
r : discount period rate
n : number of periods
formula : pv*(1+r)**n
e.g.,
>>>fv_f(100,0.1,1)
110.00000000000001
"""
return pv*(1+r)**n |
def validate_float(user_input):
"""Check if value passed is a float.
Args:
user_input: input passed by the user.
Returns:
value passed as a float, or the string 'invalid_input'
Raises:
ValueError: if value passed is not a float.
"""
try:
retu... |
def oxfordcomma(listed, condition):
"""Format a list into a sentance"""
listed = [f"'{str(entry)}'" for entry in listed]
if len(listed) == 0:
return ""
if len(listed) == 1:
return listed[0]
if len(listed) == 2:
return f"{listed[0]} {condition} {listed[1]}"
return f"{', '.... |
def _convert_js_files_to_amd_modules(ctx, js_protoc_outputs):
"""
Calls the convert_to_amd tool to convert the generated JS code into AMD modules.
"""
js_outputs = []
for js_file in js_protoc_outputs:
file_path = "/".join([p for p in [
ctx.workspace_name,
ctx.label.p... |
def get_sum(num1, num2):
"""
Adds two numbers.
Args:
num1 (int/float): The first number.
num2 (int/float): The second number.
Returns:
int/float: The sum of two numbers.
"""
if isinstance(num1, str) or isinstance(num2, str):
return None
return (num... |
def compress(years):
"""
Given a list of years like [2003, 2004, 2007],
compress it into string like '2003-2004, 2007'
>>> compress([2002])
'2002'
>>> compress([2003, 2002])
'2002-2003'
>>> compress([2009, 2004, 2005, 2006, 2007])
'2004-2007, 2009'
>>> compress([2001, 2003, 2004, 2005])
'2001, 20... |
def findLinkLabel(label, links):
"""Checks if given label exists in list of link labels.
**Arguments**
*label*
the label to search for
*links*
list with link labels collected so far,
list contains tuples of (label, filename, line nr., description, is_duplicate)
**Returns**
Tuple with existing... |
def merge_dicts(*dict_args):
"""
https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
... |
def __get_invite_dataset(_query_uri):
"""This function identifies the appropriate invite dataset."""
_dataset = "invite"
if 'invites/event' in _query_uri:
_dataset = "event_invite"
return _dataset |
def moffat(x,p0,p1,p2):
"""
Moffat profile
This 3 parameter formulation assumes the trace is known
Args:
x (float or ndarray): x values
p0 (float): Amplitude
p1 (float):
Width scaling
p2 : float
Returns:
float or ndarray: Evaluated Moffat
"""
... |
def translate_libnames(modules, module_to_libname):
"""Translate module names into library names using the mapping."""
if modules is None:
modules = []
libnames = []
for name in modules:
if name in module_to_libname:
name = module_to_libname[name]
libnames.append(name)
return libnames |
def join_l(l, sep):
"""Join list with seperator"""
li = iter(l)
string = str(next(li))
for i in li:
string += str(sep) + str(i)
return string |
def log_to_stdout(level=15):
"""
Adds the stdout to the logging stream and sets the level to 15 by default
"""
import logging
logger = logging.getLogger("fetch_data")
# remove existing file handlers
for handler in logger.handlers:
if isinstance(handler, logging.StreamHandler):
... |
def get_prefix_number(num):
"""
Getting the prefix for the new name
e.g, '0' for 12 so it becomes '012'
"""
prefix = '0'
if num < 10:
prefix = '00'
elif num >= 100:
prefix = ''
else:
prefix = '0'
return prefix |
def to_int(i):
"""
convert to integer, if possible
"""
try:
return int(i)
except:
return i |
def GL2PL(gl):
""" Converts Genotype likelyhoods to phred scaled (PL) genotype likelyhoods. """
return -int(gl*10) |
def list_to_string(list, delimiter=" "):
"""
Converts a string to a list.
"""
string = "[" + delimiter.join(map(str, list)) + "]"
return string |
def _mb(value):
"""Convert bytes to mebibytes"""
return value / 1024**2 |
def sgn(s):
"""return (-1)**(s)"""
return 1 - ((s & 1) << 1) |
def extract_retryable(error):
"""
Extract a retryable status from an error.
It's not usually helpful to retry on an error, but it's useful to do so
when the application knows it might.
"""
return getattr(error, "retryable", False) |
def _int_to_hex(value, upper=False):
"""
Convert int value to hex.
"""
result = ('0' + hex(value)[2:])[-2:]
return result.upper() if upper else result |
def x_calculate_enrichment_score(gene_set, expressions, omega):
"""
Given a gene set, a map of gene names to expression levels, and a weight omega, returns the ssGSEA
enrichment score for the gene set as described by *D. Barbie et al 2009*
:requires: every member of gene_set is a key in expressions
... |
def unique(seq):
"""Remove duplicate elements from seq. Assumes hashable elements.
Ex: unique([1, 2, 3, 2, 1]) ==> [1, 2, 3] # order may vary"""
return list(set(seq)) |
def complex_compare(a, b):
"""
Comparison function for complex numbers that compares real part, then imaginary part.
Parameters
----------
a : complex
b : complex
Returns
-------
-1 if a < b
0 if a == b
+1 if a > b
"""
if a.real < b.real: return -1
elif a.r... |
def byte_notation(size: int, acc=2, ntn=0):
"""Decimal Notation: take an integer, converts it to a string with the
requested decimal accuracy, and appends either single (default), double,
or full word character notation.
- Args:
- size (int): the size to convert
- acc (int, optional): n... |
def _process_opt(opt):
"""
Helper function that extracts certain fields from the opt dict and assembles the processed dict
"""
return {'password': opt.get('password'),
'user': opt.get('user'),
'indexer': opt.get('indexer'),
'port': str(opt.get('port', '8080')),
... |
def dms_to_dmm(d, m, s):
"""Converts degrees, minutes and decimal seconds to degrees and decimal minutes.
Example: (41, 24, 12.2) -> (41, 24.2033)
:param int d: degrees
:param int m: minutes
:param float s: decimal seconds
:rtype: str
"""
return d, m + s / 60 |
def unique_name(container, name, ext):
"""Generate unique name for container file."""
filename = '{}.{}'.format(name, ext)
i = 0
while filename in container:
i += 1
filename = '{}.{}.{}'.format(name, i, ext)
return filename |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.