content stringlengths 42 6.51k |
|---|
def move_over_floors(instructions):
"""Moves over floors up and down by given instructions
:param instructions: string of '(' (up) and ')' (down) characters
:return: floor: number of floor where we stop
basement_enter: number of first instruction where we entered negative values
"""
flo... |
def make_task_key(x, y):
"""
Creates a key from the coordinates of a given task.
The key is used to identify the tasks within a dictionary
:param x: x coordinate
:param y: y coordinate
:return: the created key
"""
key = (x, y)
return key |
def maximumBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a maximum value below n.
Example:
.. code-block:: none
&target=maximumBelow(system.interface.eth*.packetsSent,1000)
This would only display interfaces ... |
def get_sentence_entities(beg, end, annotations):
"""Get annotation for each individual sentence and adjust indices to start from 0 for each sentence.
Args:
beg (int): begin index of sentence in text
end (int): end index of sentence in text
annotation (dictionary): annotation dictionary... |
def calc_max_length(dictionary):
"""
:param dictionary: an object of set, indicates all of the keywords. e.g
:return: the max length of keyword
"""
max_length = 1
for _ in dictionary:
if len(_) > max_length:
max_length = len(_)
return max_length |
def determine_triggers(triggers, add_triggers, use_triggers):
"""Determine set of effective triggers.
:param triggers: list of configured triggers.
:type triggers: List[str]
:param add_triggers: additional triggers.
:type add_triggers: List[str]
:param use_triggers: triggers shall be applied.
... |
def _write_string_to_hex(string_to_write: str) -> str:
""" Write any string to hex.
As mentioned above, numbers get padded because all numbers are a fixed size in keytabs.
However, strings are super free-form, like principals and realms. They're not constrained to a fixed size ever, and
so instead all s... |
def login_user_block(username, ssh_keys, create_password=True):
"""
Helper function for creating Server.login_user blocks.
(see: https://www.upcloud.com/api/8-servers/#create-server)
"""
block = {
'create_password': 'yes' if create_password is True else 'no',
'ssh_keys': {
... |
def transparent(value, function, *args, **kwargs):
"""
Invoke ``function`` with ``value`` and other arguments, return ``value``.
Use this to add a function to a callback chain without disrupting the
value of the callback chain::
d = defer.succeed(42)
d.addCallback(transparent, print)
... |
def map_nested_attrs(nested_dict, split_attr_name, query_data):
"""
A function that can be called recursively to map attributes from related
entities to the associated data
:param nested_dict: Dictionary to insert data into
:type nested_dict: :class:`dict`
:param split_attr_name: List of parts ... |
def alpha(algorithm_period_return, treasury_period_return,
benchmark_period_returns, beta):
"""
http://en.wikipedia.org/wiki/Alpha_(investment)
Args:
algorithm_period_return (float):
Return percentage from algorithm period.
treasury_period_return (float):
R... |
def dicts_equal(lhs, rhs):
"""
Check dicts' equality.
"""
if len(lhs.keys()) != len(rhs.keys()):
return False
for key, val in rhs.items():
val_ref = lhs.get(key, None)
if val != val_ref:
return False
return True |
def change_angle_origin(angles, max_positive_angle):
"""
Angles in DICOM are all positive values, but there is typically no mechanical continuity in across 180 degrees
:param angles: angles to be converted
:type angles list
:param max_positive_angle: the maximum positive angle, angles greater than t... |
def patch_attributes(new_attrs, obj):
"""Updates attribute values.
Ignored if new_attrs is None
"""
if new_attrs:
if obj.attributes is None:
obj.attributes = new_attrs
else:
for attr_name in new_attrs:
obj.attributes[attr_name] = new_attrs[attr_nam... |
def islambda(v):
""" Checks if v is a lambda function """
LAMBDA = lambda:0
return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__ |
def business_logic(product_id, sku_id):
"""Example of service."""
if product_id == 'Secure Firewall' and sku_id == 'Ingress network traffic':
return 1 + 1
if product_id == 'Secure Firewall' and sku_id == 'Egress network traffic':
return 1 * 1
return 0 |
def compareVersions(verA, verB):
"""Given two versions formatted as 'major.minor.build' (i.e. 2.0.1), compares
A to B and returns B if B is larger than A, else returns None
A version is larger if stepping down from major -> build results in a larger
difference.
Ex:
1.0.1 > 1.0.0
2.2.1 > 1.0.5
2.2.1 > 2.1.3
... |
def typeFullName(o):
"""This function takes any user defined object or class of any type and
returns a string absolute identifier of the provided type.
Args:
o (Any): object of any type to be inspected
Returns:
str: The full dotted path of the provided type
"""
module = o.__cla... |
def scale(pix, pixMax, floatMin, floatMax):
""" scale takes in
pix, the CURRENT pixel column (or row)
pixMax, the total # of pixel columns
floatMin, the min floating-point value
floatMax, the max floating-point value
scale returns the floating-point value that
corresp... |
def escape_dot_syntax(key):
"""
Take a table name and check for dot syntax. Escape
the table name properly with quotes; this currently
only supports the MySQL syntax, but will hopefully
be abstracted away soon.
"""
dot_index = key.find('.')
if(dot_index == -1):
if not(key.startswith('`')):
key = '`%s`' % k... |
def enpunycode(domain: str) -> str:
"""
convert utf8 domain to punycode
"""
result = []
for _ in domain.split("."):
try:
_.encode("ascii")
result.append(_)
except UnicodeEncodeError:
result.append("xn--" + _.encode("punycode").decode("ascii"))
... |
def even_fibonacci(n):
"""Return the sum of even elements of the fibonacci series"""
fibo = [1, 1]
even = 0
if n < 2 or n > 2_000_000:
return 0
while n > 2:
n -= 1
f = sum(fibo)
if f % 2 == 0:
even += f
fibo = [fibo[-1], f]
return even |
def determin_meetw(meetw_processes, sample_processes, repeat_cutoff=2):
"""Determine meetwaarde and meetwaarde herhaling (reapeat) based on list of processes and repeat cutoff."""
meetw = 'N'
meetw_herh = 'N'
for process in meetw_processes:
if process in sample_processes:
if len(sam... |
def gen_fov_chan_names(num_fovs, num_chans, return_imgs=False, use_delimiter=False):
"""Generate fov and channel names
Names have the format 'fov0', 'fov1', ..., 'fovN' for fovs and 'chan0', 'chan1', ...,
'chanM' for channels.
Args:
num_fovs (int):
Number of fov names to create
... |
def calc_lithostat(z,p=2700.0,g=9.80665):
"""
Lithostatic stress according to Pylith's definition of g=9.80665
"""
litho = p*g*z
print('%.3e' % litho)
return litho |
def labels():
"""
Returns a dict with relevant labels as keys and their index as value.
"""
labels = {"car": 7, "bus": 6, "motorcycle": 14, "bicycle": 2, "person": 15}
return labels |
def _unique(seq):
"""Return unique elements of ``seq`` in order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] |
def mean(*args):
"""
Calculates the mean of a list of numbers
:param args: List of numbers
:return: The mean of a list of numbers
"""
index = 0
sum_index = 0
for i in args:
index += 1
sum_index += float(i)
return (sum_index / index) if index != 0 else "Division by z... |
def chao1_var_bias_corrected(singles, doubles):
"""Calculates chao1 variance, bias-corrected.
From EstimateS manual, equation 6.
"""
s, d = float(singles), float(doubles)
return s*(s-1)/(2*(d+1)) + (s*(2*s-1)**2)/(4*(d+1)**2) + \
(s**2 * d * (s-1)**2)/(4*(d+1)**4) |
def any(list):
"""Is any of the elements of the list true?"""
for x in list:
if x: return True
return False |
def ByteToHex( byteStr ):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
# Uses list comprehension which is a fractionally faster implementation than
# the alternative, more readable, implementation below
#
# hex = []
# for aChar in byteStr... |
def validate_recoveryoption_name(recoveryoption_name):
"""
Validate Name for RecoveryOption
Property: RecoveryOption.Name
"""
VALID_RECOVERYOPTION_NAME = (
"admin_only",
"verified_email",
"verified_phone_number",
)
if recoveryoption_name not in VALID_RECOVERYOPTION_... |
def find_kaprecar_numbers(p, q):
"""
:type p: int
:type q: int
:rtype: list[int]
"""
kaprecar_numbers = list()
for i in range(p, q + 1):
square = str(i ** 2)
l_piece = square[:len(square) // 2] if len(square) > 1 else "0"
r_piece = square[len(l_piece):] if len(square)... |
def b128_decode(data):
""" Performs the MSB base-128 decoding of a given value. Used to decode variable integers (varints) from the LevelDB.
The code is a port from the Bitcoin Core C++ source. Notice that the code is not exactly the same since the original
one reads directly from the LevelDB.
The deco... |
def remove_parentheses(inv, replace_with=''):
"""
function used to remove/replace top-level matching parenthesis from a string
:param inv: input string
:param replace_with: string to replace matching parenthesis with
:return: input string without first set of matching parentheses
"""
k = ... |
def valid_cluster_name(name):
"""
Return valid qsub ID by removing semicolons, converting
them into underscores.
"""
name = name.replace(';', '_')
return name |
def count_true_args(*args):
"""Count number of list of arguments that evaluate True"""
count = 0
for arg in args:
if (arg):
count += 1
return(count) |
def format_message(message: str) -> str:
"""Formats the Message to remove redundant Spaces and Newline chars"""
msg_l = message.split(" ")
new = []
for x in msg_l:
if "\n" in x:
x = x.replace("\n", "")
new.append(x) if not len(x) == 0 else None
elif len(x) != 0:
... |
def get_initial_cholcovs_index_tuples(n_mixtures, factors):
"""Index tuples for initial_cov.
Args:
n_mixtures (int): Number of elements in the mixture distribution of the factors.
factors (list): The latent factors of the model
Returns:
ind_tups (list)
"""
ind_tups = []
... |
def convert_arrays_to_dict(speciesNames,moleFractions):
"""
Converts two vectors, one containing species names and
one containing mole fractions, into a species dictionary
"""
d = {}
assert len(speciesNames) == len(moleFractions)
for name, amt in zip(speciesNames,moleFractions):
if ... |
def parse_ref(ref):
"""
Convenience method that removes the "#/definitions/" prefix from the
reference name to a REST definition.
"""
ref = ref.replace('#/definitions/', '')
ref = ref.replace('#/x-stream-definitions/', '')
# Workaround for nested messages that the Swagger generator doesn't... |
def Dot(v1,v2):
""" Returns the Dot product between two vectors:
**Arguments**:
- two vectors (sequences of bit ids)
**Returns**: an integer
**Notes**
- the vectors must be sorted
- duplicate bit IDs are counted more than once
>>> Dot( (1,2,3,4,10), (2,4,6) )
2
Here's how duplicates ar... |
def _zfill(v, l = 5):
"""zfill a string by padding 0s to the left of the string till it is the link
specified by l.
"""
return "0" * (l - len(v)) + v |
def swap_bits(x, j, k):
"""
Question 5.2: Swap bits in a number
"""
if (x >> j) & 1 != (x >> k) & 1:
mask = (1 << j) | (1 << k)
x ^= mask
return x |
def blend_exclusion(cb: float, cs: float) -> float:
"""Blend mode 'exclusion'."""
return cb + cs - 2 * cb * cs |
def dayAbbrevFormat(day: int) -> str:
"""
Formats a (0-6) weekday number as an abbreviated week day name, according to the current locale.
For example: dayAbbrevFormat(0) -> "Sun".
"""
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
return days[day % 7] |
def do_truncate(s, length=255, killwords=False, end='...'):
"""
Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will try to save the last word. ... |
def substr_in_list(sub,list,fetch=False):
"""Returns the first string containing the substring if fetch = True. Otherwise it returns a bool that evalutes to true if the substring is present in any string in the list"""
for s in list:
if sub in s:
if fetch:
return s
return True
if fetch:
return ... |
def to_bytes(something, encoding='utf8') -> bytes:
"""
cast string to bytes() like object, but for python2 support it's bytearray copy
"""
if isinstance(something, bytes):
return something
if isinstance(something, str):
return something.encode(encoding)
elif isinstance(something,... |
def fac(num):
"""fac: Returns an array of factors for the given number
Args:
num (int): number to list factors for
Returns:
array: factors of num
"""
output = []
# Creates inlist for output
for x in range(1, num + 1):
# Loop with variable x
if num % x == 0 and not num ... |
def determine_num_ranges(N, max_n):
"""Calculates the number of scatters given max_n from N.
To increase the speed of the LIONESS analysis, we use split the expression
matrix and operate on smaller subsets (e.g. like a map-reduce).
To limit the number of samples in a given shard, we specify `max_n`.
... |
def get_nested_dict_key(nested_dict):
"""Get all keys of nested dict
Parameters
----------
nested_dict : dict
Nested dictionary
Return
------
all_nested_keys : list
Key of nested dict
"""
all_nested_keys = []
for entry in nested_dict:
for value in nested... |
def valid_urgency():
"""Returns a list of valid urgency levels, all lowercase.
:return: A list of valid urgency levels.
:rtype: list[str]
"""
return ["Immediate", "Expected", "Future", "Past", "Unknown"] |
def diamond_db_name(config):
"""Generate filtered diamond database name."""
name = "reference_proteomes"
parts = ["diamond", name]
return ".".join(parts) |
def normal_hostname(hostname: str):
"""Convert ansible hostname to normal format"""
return hostname.replace("_", "-") |
def _str_to_unit(string):
"""
translates to the string representation of the `astropy.units`
quantity from the Vizier format for the unit.
Parameters
----------
string : str
`s`, `m` or `d`
Returns
-------
string equivalent of the corresponding `astropy` unit.
"""
s... |
def merge(large_array, small_array):
"""
Merges 2 given arrays (large and small indicate length) by
combining them in ascending order and returning the one big array.
"""
merged = []
small_index = 0
large_index = 0
merging = True
while merging:
if large_index + 1 > len(larg... |
def list2dict(infos):
"""We want a mapping name: char/service for convenience, not a list."""
info_dict = {}
for info in infos:
info_dict[info["Name"]] = info
del info["Name"]
return info_dict |
def tohlist(s):
"""
convert sofa string to list of hexa
"""
sl= s.replace('[','').split(']')
hlist=list()
for h in sl:
if len(h)!=0 :
hlist.append(map(int,h.split(',')))
return hlist |
def _cast(value):
"""
Attempt to convert ``value`` to an ``int`` or ``float``. If unable, return
the value unchanged.
"""
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
return value |
def _positive(value):
""" Validate positive key value. """
return isinstance(value, int) and value > 0 |
def generate_dictionary(**kwargs):
""" Silly function #2 """
dictionary = {}
for entry in kwargs:
dictionary[entry] = kwargs[entry]
return dictionary |
def get_id(repo):
"""
:param str repo: the url to the compressed file contained the google id
:return the google drive id of the file to be downloaded
:rtype str
"""
start_id_index = repo.index("d/") + 2
end_id_index = repo.index("/view")
return repo[start_id_index:end_id_index] |
def cve_harvest(text):
"""
looks for anything with 'CVE' inside a text and returns a list of it
"""
array = []
#look inside split by whitespace
for word in text.split():
if 'CVE' in word:
array.append(word)
return array |
def get_filename(file: str):
"""returns image file name"""
return file.split("\\")[-1] |
def ishl7(line):
"""Determines whether a *line* looks like an HL7 message.
This method only does a cursory check and does not fully
validate the message.
:rtype: bool
"""
## Prevent issues if the line is empty
return line.strip().startswith('MSH') if line else False |
def max_in_sliding_window(array, window_width):
"""
:param array: numbers
:param window_width:sliding window size
:return: all max number
"""
if not array or window_width < 1:
return None
max_i = []
res = []
for i in range(len(array)):
while max_i and array[i] >= arra... |
def finn_flest(antall):
"""
Finner og returnerer hvilken terningverdi som
forekommer flest ganger
"""
return max(antall, key = antall.count) |
def remove_quotes(s):
"""
Where a string starts and ends with a quote, remove the quote
"""
if len(s) > 1 and s[0] == s[-1] and s[0] in ['"', "'"]:
return s[1:-1]
return s |
def calculate_code_lines_count(code: str) -> int:
""" Calculate number of code lines. """
if isinstance(code, str):
return len(code.split('\n'))
return 0 |
def removeElt(items, i):
"""
non-destructively remove the element at index i from a list;
returns a copy; if the result is a list of length 1, just return
the element
"""
result = items[:i] + items[i+1:]
if len(result) == 1:
return result[0]
else:
return result |
def is_odd(n):
"""Returns True if n is odd, and False if n is even.
Assumes integer.
"""
return bool(n & 1) |
def flatten(v):
"""
Flatten a list of lists/tuples
"""
return [x for y in v for x in y] |
def split_iativer(version_str):
"""Split an IATIver-format version number into numeric representations of its components.
Args:
version_str (string): An IATIver-format string.
Returns:
list of int: A list containing numeric representations of the Integer and Decimal components.
"""
... |
def read_table_header_left(table):
"""
Read a table whit header in first column.
@param table Matrix format
@return dict Dictionary with header as key
"""
data = {}
for row in table:
data[row[0]] = row[1:]
return data |
def alpha(m_med, m_f):
"""Convenience function that implements part of the spin-1 width formula.
:param m_med: mediator mass
:type m_med: float
:param m_f: fermion mass
:type m_f: float
"""
return 1 + 2 * m_f**2 / m_med**2 |
def _convert_display_size(size):
"""
Convert filesize into human-readable size using unit suffixes
"""
unit_gigabyte = 1024 * 1024 * 1024.0
unit_megabyte = 1024 * 1024.0
unit_kilobyte = 1024.0
if size > unit_gigabyte:
return "{:.2f} GB".format(
size / unit_gigabyte)
... |
def sciNot(x):
"""Returns scientific notation of x value"""
return '%.2E' % x |
def bool_option(s):
"""
Command-line option str which must resolve to [true|false]
"""
s = s.lower()
if s=='true':
return True
elif s=='false':
return False
else:
raise TypeError |
def appn(s1, s2):
"""Append two strings, adding a space between them if either is nonempty.
Args:
s1 (str): The first string
s2 (str): The second string
Returns:
str: The two strings concatenated and separated by a space.
"""
if not s1: return s2
elif not s2: return s1
else: return s1 ... |
def find_scaling_factor(tile_num):
""" For a given number of tiles composing the EPU atlas, determine the number of basis vector lengths span from the center of the image to an edge.
PARAMETERS
tile_num = int(), number of tiles of which the atlas is composed
RETURNS
scaling_factor = float()
... |
def calc_insert_point(source, body, part):
""" Calculates start of line of "part. Usefull for identation."""
if len(body) >= part:
startOffset = body[part].start
ret = startOffset
while source[ret] != '\n':
ret -= 1
newline = ret
ret += 1
while source[... |
def serial_to_station(x: int) -> int:
"""Convert serialized chamber id to station."""
return ((x >> 8) & 0x00000003) + 1 |
def none_to_zero(x):
"""Return 0 if value is None"""
if x is None:
return 0
return x |
def make_cybox_object_list(objects):
"""
Makes an object list out of cybox objects to put in a cybox container
"""
cybox_objects = {}
for i in range(len(objects)):
cybox_objects[str(i)] = objects[i]
return cybox_objects |
def Underline(string):
"""Returns string wrapped in escape codes representing underlines."""
return '\x1F%s\x0F' % string |
def bubbleSort(unsort: list) -> list:
"""bubble sort"""
arr = unsort.copy()
last = len(arr) - 1
for i in range(0, last):
for j in range(0, last - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j] # swap
return arr |
def DES3500(v):
"""
DES-3500-series
:param v:
:return:
"""
return v["platform"].startswith("DES-35") |
def stellar_radius(M, logg):
"""Calculate stellar radius given mass and logg"""
if not isinstance(M, (int, float)):
raise TypeError('Mass must be int or float. {} type given'.format(type(M)))
if not isinstance(logg, (int, float)):
raise TypeError('logg must be int or float. {} type given'.fo... |
def allowed_file_history(filename: str) -> bool:
"""Check whether the type is allowed for a file history file.
:param filename: name of the file
:return: True or False
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ['json'] |
def round_channels(channels, divisor=8):
"""
Round weighted channel number (make divisible operation).
Parameters:
----------
channels : int or float
Original number of channels.
divisor : int, default 8
Alignment value.
Returns
-------
int
Weighted number of ... |
def to_fully_staffed_matrix_3(d):
"""
Parameters
----------
d : dict<object, object>
Returns
-------
dict<object, object>
"""
for key, val in d.items():
d[val] = key
return d |
def process_gene_line(gene_line):
"""Parse gene line."""
# contain [gene_id]=[intersected_chain_id] blocks
# remove "gene" and "", get (gene. chain) tuples
# is not necessary really
data = [(x.split("=")[1], x.split("=")[0]) for x in gene_line[1:-1]]
chain = data[0][0] # chain is equal everywhe... |
def getList(start,end):
"""
Strictly Ymd format no spaces or slashes
"""
import datetime
start = datetime.datetime.strptime(str(start),'%Y%m%d')
end = datetime.datetime.strptime(str(end),'%Y%m%d')
dateList = [start + datetime.timedelta(days=x) for x in range(0, (end-start).day... |
def rchop(s, sub):
"""
Remove `sub` from the end of `s`.
"""
return s[:-len(sub)] if s.endswith(sub) else s |
def stripTrailingNL(s):
"""If s ends with a newline, drop it; else return s intact"""
return s[:-1] if s.endswith('\n') else s |
def check_conditions(line, category, method, thresh=0.3):
"""Check conditions of our or m3d txt file"""
check = False
assert category in ['pedestrian', 'cyclist', 'all']
if category == 'all':
category = ['pedestrian', 'person_sitting', 'cyclist']
if method == 'gt':
if line.split()... |
def p_assist(assist):
"""
String of assist operator
:param assist: assist operator
:return: lowercase assist operator
"""
return str(assist).lower() |
def action(maximize, total_util, payoffs):
"""
>>> action(True, 0.9, [1.1, 0, 1, 0.4])
0
>>> action(True, 1.1, [1.1, 0, 1, 0.4])
1
>>> action(False, 0.9, [1.1, 0, 1, 0.4])
0.9
"""
if maximize:
return int(total_util > payoffs[2])
else:
return total_util |
def big_l_prime_array(p, n):
""" Compile L' array (Gusfield theorem 2.2.2) using p and N array.
L'[i] = largest index j less than n such that N[j] = |P[i:]| """
lp = [0] * len(p)
for j in range(len(p)-1):
i = len(p) - n[j]
if i < len(p):
lp[i] = j + 1
return lp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.