content stringlengths 42 6.51k |
|---|
def k(x,y,z):
"""
This function does stuff inside our compressionFunction
it should be (~x XOR y) v (z ^ ~x)
"""
a = (~x ^ y) | (z ^ ~x)
return a |
def format_setting_name(setting_name):
"""
Return the given setting name formatted for compatibility
for "nordvpn set" command
"""
return setting_name.replace(' ', '').replace('-', '').lower() |
def get_robot_number_and_alliance(team_num, match_data):
"""Gets the robot number (e.g. the `1` in initLineRobot1) and alliance color."""
team_key = f'frc{team_num}'
for alliance in ['red', 'blue']:
for i, key in enumerate(match_data['alliances'][alliance]['team_keys'], start=1):
if team... |
def format_puzzle(grid):
"""Formats the puzzle for printing."""
puzzle = ""
for line in grid:
puzzle += " ".join(line) + "\n"
return puzzle |
def delete_one_before_mainword(sentence, mainword, **kwargs):
"""Delete every word starting from (and including) one word before
<mainword>. Used in ambiguity detection e.g. 'there is scarring vs
atelectasis' -->mainword 'vs' --> 'there is' (delete both scarring and
atelectasis)"""
if mainword in se... |
def build_object(cfg, parent, default=None, args=[], **kwargs):
"""
Build an object from a dict.
The dict must contain a key ``type``, which is a indicating the object
type. Remaining fields are treated as the arguments for constructing the
object.
Args:
cfg (any): The object, object c... |
def convert_to_bits(n):
"""converts an integer `n` to bit array
ex) convert_to_bits(3) -> [1,1] """
result = []
if n == 0:
return [0]
while n > 0:
result = [(n % 2)] + result
n = n / 2
return result |
def range_check(val, lb, ub):
"""
Data range validation.
'val' should have attribute __lt__ and __gt__.
'lb', 'ub' should be of the same type as 'val'.
'lb' means lowerbound and 'ub' means upperbound.
"""
return True if hasattr(val, '__lt__') and hasattr(val, '__gt__') and \
... |
def exponent(attrs, inputs, proto_obj):
"""Elementwise exponent of input array."""
return 'exp', attrs, inputs |
def _substitute(template, fuzzer, benchmark):
"""Replaces {fuzzer} or {benchmark} with |fuzzer| or |benchmark| in
|template| string."""
return template.format(fuzzer=fuzzer, benchmark=benchmark) |
def list_index(xs):
"""
Return a mapping from each element of xs to its index
"""
m = {}
for (i, x) in enumerate(xs):
m[x] = i
return m |
def getopts(argv):
"""Collect command line options in a dictionary.
We cannot use sys.getopt as it is supported only in Python3.
"""
opts = {}
while argv:
if argv[0][0] == '-':
if len(argv) > 1:
opts[argv[0]] = argv[1]
else:
opts[a... |
def discretisation_length(N, d):
"""Returns the length of a linspace where there are N points with d intermediate (in-between) points."""
return (N - 1) * (d + 1) + 1 |
def char_delta(c: str, d: str) -> int:
""" find int difference between to characters """
if len(c) == 1 and len(d) == 1:
return ord(c) - ord(d)
else:
SyntaxError(f'the inputs need to be char not string: {c}, {d}')
return 0 |
def listify(obj):
""" Wraps all non-list or tuple objects in a list; provides a simple
way to accept flexible arguments. """
if obj is None:
return []
else:
return obj if isinstance(obj, (list, tuple, type(None))) else [obj] |
def _is_valid(queens):
"""Check current queen position is valid."""
current_row, current_col = len(queens) - 1, queens[-1]
# Check any queens can attack the current queen.
for row, col in enumerate(queens[:-1]):
col_diff = abs(current_col - col)
row_diff = abs(current_row - row)
... |
def clean_int(
i: int,
ub: int,
lb: int = 0,
) -> int:
"""Clean an integer according to a given upper and lower bound
Parameters
----------
i : int
The integer to be cleaned
ub : int
The inclusive upper bound
lb : int, optional
The exclusive lower bound, ... |
def radix_sort(array):
"""
Radix Sort
Complexity: O((N + B) * logb(max)
Where B is the base for representing numbers and
max is the maximum element of the input array. We
basically try to lower the complexity of counting sort.
Even though it seems good, it's good in specific cases o... |
def in_place_swap(a, b):
""" Interchange two numbers without an extra variable.
Based on the ideea that a^b^b = a
"""
a = a ^ b
b = b ^ a
a = a ^ b
return (a, b) |
def cvi(nir, red, green):
"""
Compute Chlorophyl Vegetation Index from red and NIR bands
CVI = \\frac { NIR }{ GREEN } - (RED + GREEN)
:param nir: Near-Infrared band
:param red: Red band
:param green: Green band
:return: CVI
"""
return (nir/green) - (red + gree... |
def _gauss_first_equation(y, s, w):
"""Evaluates Gauss' first equation.
Parameters
----------
y: float
The dependent variable.
s: float
First auxiliary variable.
w: float
Second auxiliary variable.
Returns
-------
x: float
The independent variable or... |
def update_block_dropdown(block):
"""
Limit esate to sensible values.
Notes
-----
Townhouse and block should be mutually exclusive.
"""
if block:
opts = [{'label': 'No', 'value': 0}]
else:
opts = [{'label': 'Yes', 'value': 1},
{'label': 'No', '... |
def exclude_subsets(iter_of_sets):
""" This function takes an interable of sets and returns a new list with all
sets that are a subset of any other eliminated """
keep_sets = []
for si in iter_of_sets:
si = set(si)
any_subset = False
for sj in iter_of_sets:
sj = s... |
def xoxo(stringer):
"""
check whether the string x or the string o is present, if so, check the count
else, return false
"""
stringer = stringer.lower()
if stringer.find("x") != -1 and stringer.find("o") != -1:
return stringer.count("x") == stringer.count("o")
return False |
def is_plus_option(string):
"""Whether that string looks like an option
>>> is_plus_option('+/sought')
True
"""
return string[0] == '+' |
def write_sentence_list_to_file(filename, sen_l):
"""
Writes fiven list of sentences to a given file name
Removes double quotation if they are in odd number
"""
with open(filename, mode="w", encoding="utf-16") as fl:
for ln_edit1 in sen_l:
ln_edit1 = " ".join(ln_edit1.split())
... |
def location(host=None, user=None, path=None, forssh=False):
"""Construct an appropriate ssh/scp path spec based on the combination of
parameters. Supply host, user, and path.
"""
sep = "" if forssh else ":"
if host is None:
if user is None:
if path is None:
raise... |
def bytes_per_pixel(pixel_type):
"""
Return the number of bytes per pixel for the given pixel type
@param pixel_type: The OMERO pixel type
@type pixel_type: String
"""
if (pixel_type == "int8" or pixel_type == "uint8"):
return 1
elif (pixel_type == "int16" or pixel_type == "uint1... |
def tuple_is_smaller(t1,t2):
"""
Checks whether the tuple t1 is smaller than t2
"""
t1_forward = t1[1] > t1[0]
t2_forward = t2[1] > t2[0]
i,j,x,y = t1[0], t1[1], t2[0], t2[1]
# Edge comparison
if t1_forward and t2_forward:
if j < y or (j == y and i > x):
return Tr... |
def _make_arm_parameter_values(key_values: dict) -> dict:
"""Transform a key-value dictionary into ARM template parameter data."""
result = dict()
for k, v in key_values.items():
result[k] = {"value": v}
return result |
def subprocess_open(args):
"""Execute subprocess by using Popen."""
from subprocess import Popen, PIPE
chld = Popen(args, stdout=PIPE)
data = chld.communicate()[0]
return (chld.returncode, data.rstrip().decode("utf8")) |
def get_all_pr_between_two_set_of_HOGs(graph, list_hogs1, list_hogs2):
"""
return the numbers of extant orthologous relations between two set of hogs
:param graph:
:param list_hogs1:
:param list_hogs2:
:return:
"""
pairwise_relations = 0
for hog1 in list_hogs1:
for hog2 in li... |
def to_ordinal(n):
"""Get the suffixed number.
Returns: a string with then number and the appropriate suffix.
>>> to_ordinal(1)
'1st'
>>> to_ordinal(2)
'2nd'
>>> to_ordinal(3)
'3rd'
>>> to_ordinal(4)
'4th'
>>> to_ordinal(11)
'11th'
>>> to_ordinal(12)
'12th'
... |
def subtract(one, two):
"""Helper function for subtracting"""
return(one - two) |
def esc_format(text):
"""Return text with formatting escaped
Markdown requires a backslash before literal underscores or asterisk, to
avoid formatting to bold or italics.
"""
for symbol in ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!']:
text = str... |
def _axis_id_to_slice(axis_id: int, tile_length: int, n_px: int) -> slice:
"""Take the axis_id from a dask block_id and create the corresponding
tile slice, taking into account edge tiles."""
if (axis_id * tile_length) + tile_length <= n_px:
return slice(axis_id * tile_length, (axis_id * tile_length... |
def reverse_string(input):
"""
Return reversed input string
Examples:
reverse_string("abc") returns "cba"
Args:
input(str): string to be reversed
Returns:
a string that is the reverse of input
"""
if len(input) == 0:
return ""
first = input[0]
next_input... |
def cube(edge_length):
"""A cube has six square faces and twelve edges.
The function will return triangular facets rather than quadrilateral facets, so
each square face will become two triangles, giving twelve facets.
This solid is also known as:
- a square parallelepiped
- an equilateral cubo... |
def add2_sub2_res(res):
"""function that takes entire output as an input"""
if isinstance(res, list):
return [r["out"] + 2 for r in res], [r["out"] - 2 for r in res]
return res["out"] + 2, res["out"] - 2 |
def purple(text):
""" Return this text formatted purple """
return '\x0306%s\x03' % text |
def match_basis(basis):
"""
Converts a string representations of basis angular momenta
to the cardinal number
"""
# Remove the supplemental functions from the string as they don't
# refer to the cardinal number
basis = basis.replace("AUG-PC", "")
basis = basis.replace("P", "")
basis ... |
def test_for_small_float(value: float, precision: int) -> bool:
"""
Returns True if 'value' is a float whose rounded str representation
has fewer significant figures than the number in 'precision'.
Return False otherwise.
"""
if not isinstance(value, (float)):
return False
if value ... |
def elements_to_species(element_set):
"""
Get species that are placeholders for the elements, and adds H2O
"""
species = {ELEMENT_SPECIES_MAP[el] for el in element_set
if el not in ['O', 'H']}
species.add('H2O')
return species |
def compress(v):
"""Docstring."""
u = ""
for elt in v:
s = "1" if elt > 0 else "0"
s += format((abs(elt) % (1 << 7)), '#09b')[:1:-1]
s += "0" * (abs(elt) >> 7) + "1"
u += s
u += "0" * ((8 - len(u)) % 8)
return [int(u[8 * i: 8 * i + 8], 2) for i in range(len(u) // 8)] |
def DeleteSmallIntervals( intervals, min_length ):
"""combine a list of non-overlapping intervals,
and delete those that are too small.
"""
if not intervals: return []
new_intervals = []
for this_from, this_to in intervals:
if (this_to - this_from + 1) >= min_length:
n... |
def _observed_name(field, name):
"""Adjust field name to reflect `dump_to` and `load_from` attributes.
:param Field field: A marshmallow field.
:param str name: Field name
:rtype: str
"""
# use getattr in case we're running against older versions of marshmallow.
dump_to = getattr(field, 'du... |
def xor_hex_strings(str1, str2):
"""
Return xor of two hex strings.
An XOR of two pieces of data will be as random as the input with the most randomness.
We can thus combine two entropy sources in this way as a safeguard against one source being
compromised in some way.
For details, see http://c... |
def searchkw(text_list, kw_lists):
"""Search for targeted elements in the list based on the lw_lists"""
mentions_list = []
for i, x in enumerate(text_list):
if any(n in x.lower() for n in kw_lists):
mentions_list.append(i)
return mentions_list |
def option2tuple(opt):
"""Return a tuple of option, taking possible presence of level into account"""
if isinstance(opt[0], int):
tup = opt[1], opt[2:]
else:
tup = opt[0], opt[1:]
return tup |
def check_if_packs_can_be_played(packs, possible_plays):
"""
Function used to check if player can play a pack of cards in turn.
:param packs: list with packs of cards on hand
:param possible_plays: list with all possible cards to play
:return: list with possible to play packs
"""
possible_pa... |
def strip_string(value):
"""Remove all blank spaces from the ends of a given value."""
return value.strip() |
def get_classmap(anno_data, classmap):
"""
Find classmap from middle format annotation data
:param anno_list: [{'size':(width, height), 'objects':[{'name': '', 'bndbox':[xmin,ymin,xmax,ymax]}, ...]}, ...]
:param classmap: Existing class name and number map
:return: {'a': 0, 'b':1 ,...}
"""
f... |
def return_agar_plates(wells=6):
"""Returns a dict of all agar plates available that can be purchased.
Parameters
----------
wells : integer
Optional, default 6 for 6-well plate
Returns
-------
dict
plates with plate identity as key and kit_id as value
Raises
-----... |
def update_strategy(strat1, strat2):
"""
Updates strategy 1 by adding key/value pairs of strategy 2.
:param strat1: Old strategy.
:param strat2: Strategy to add.
:return: A new strategy which merges strategies 1 and 2 (2 overwrites 1 in case of duplicate keys)
"""
new_strat = strat1.copy()
... |
def euler_problem_19(n=2000):
"""
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain ... |
def serialize_biomass_table_v1(analysis, type):
"""Convert the output of the biomass_loss analysis to json"""
rows = []
for year in analysis.get('biomass_loss_by_year'):
rows.append({'year': year,
'biomassLossByYear': analysis.get('biomass_loss_by_year', None).get(year, None),
... |
def is_slice(x):
"""Tests if something is a slice"""
return isinstance(x, slice) |
def build_logname(input_filename, process_type='svm'):
"""Build the log filename based on the input filename"""
suffix = '.{}'.format(input_filename.split('.')[-1])
if isinstance(input_filename, str): # input file is a poller file -- easy case
logname = input_filename.replace(suffix, '.log')
e... |
def init_actions_(service, args):
"""
This needs to return an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install']
} |
def getPoint(arr):
"""get ponit"""
if len(arr) < 2:
return
tag = 1
help = []
while tag < len(arr):
sum = 0
sum_after = 0
for i in range(tag):
sum += arr[i]
for i in range(tag+1, len(arr)):
sum_after += arr[i]
if sum == sum_after... |
def mutiply_values(iterable, indexes):
"""Mutliplies the values of the iterable given by a list of indexes"""
indexes = set(indexes)
product = 1
for i, x in enumerate(iterable):
if i in indexes:
product *= x
indexes.remove(i)
if len(indexes) == 0:
b... |
def unordered_equality(seq1, seq2):
"""
Tests to see if the contents of one sequence is contained in the other
and that they are of the same length.
"""
if len(seq1) != len(seq2):
return False
# if isinstance(seq1, dict) and isinstance(seq2, dict):
# seq1 =... |
def siso_sequential(io_lst):
"""Connects in a serial connection a list of dictionaries of the inputs and
outputs encoding single-input single-output search spaces.
Args:
io_lst (list[(dict[str,deep_architect.core.Input], dict[str,deep_architect.core.Output])]):
List of single-input sing... |
def check_palindrome(n: int) -> str:
"""Checks if n is a palindrome"""
if str(n) == str(n)[::-1]:
return 'Palindrome Number'
return 'Not Palindrome Number' |
def create_job_folder_name(job_config, app_config):
"""create standardized job folder path given application configuration"""
local_job_folder = f"{app_config['JOB_PATH']}/{job_config['jobname']}"
return(local_job_folder) |
def identity(*args):
"""Return the first argument provided to it.
Args:
*args (mixed): Arguments.
Returns:
mixed: First argument or ``None``.
Example:
>>> identity(1)
1
>>> identity(1, 2, 3)
1
>>> identity() is None
True
.. version... |
def squareDistance(p1, p2):
"""Answers the square of the distance for relative comparison and to
save the time of the **sqrt**."""
tx, ty = p2[0]-p1[0], p2[1]-p1[1]
return tx*tx + ty*ty |
def valid_file(file_name):
"""
Returns True if file_name matches the condition assigned.
False otherwise.
"""
condition = (
file_name.endswith(".py")
and not(file_name.startswith("_")) or file_name == "__init__.py"
)
return condition |
def calculate_bin(memory):
"""Calculates the memory bin (EC2 Instance type) according to the amount of memory in gigabytes needed to process the job."""
if memory < 1.792:
mem_bin = 0
elif memory < 7.168:
mem_bin = 1
elif memory < 14.336:
mem_bin = 2
elif memory >= 14.336:
... |
def _ends_in_by(word):
"""
Returns True if word ends in .by, else False
Args:
word (str): Filename to check
Returns:
boolean: Whether 'word' ends with 'by' or not
"""
return word[-3:] == ".by" |
def get_keys(dictionary: dict, value):
"""
get_keys() collects all the keys that share a value
Syntax:
get_keys(dictionary, value)
Example usage:
from readyCode package import get_keys
d = {"Alice": 45, "Bob": 25, "Charlie": 45, "Doug": 15, "Ellie": 75}
keys_with_45 = get_keys(d, 45... |
def is_cmt(line,cmt):
"""Test if it is an comment line"""
if len(line)==1:
return False
else:
for i in range(len(line)):
if line[i]!=' ' and line[i]!='\t':
if len(line[i:])>len(cmt):
if line[i:i+len(cmt)]==cmt:
return T... |
def removesuffix(somestring, suffix):
"""Removed a suffix from a string
Arguments
---------
somestring : str
Any string.
suffix : str
Suffix to be removed from somestring.
Returns
------
string resulting from suffix removed from somestring, if found, unchanged otherwise
... |
def bad_fibonacci(n):
"""Return the nth Fibonacci number."""
if n <= 1:
return n
return bad_fibonacci(n - 2) + bad_fibonacci(n - 1) |
def sort_and_format_dict(l, reverse=False):
"""
{
'asks': [
{
'price': 0,
'amount': 0,
}
],
'bids': [
{
'price': 0,
'amount': 0,
}
]
}
"""
l.sort(key=lambda... |
def non_simple_values(obj1, obj2, obj3, obj4):
"""
>>> non_simple_values(1, 2, 3, 4)
(7, 3, 7, 3, 7, 7, 5, 5)
>>> non_simple_values(0, 0, 3, 4)
(0, 7, 4, 4, 4, 4, 4, 4)
>>> non_simple_values(0, 0, 1, -1)
(0, 0, -1, 0, -1, -1, 0, 0)
>>> non_simple_values(1, -1, 1, -1)
(0, 0, 0, 0, 0, ... |
def _fmt(x, pos):
"""
Used for nice formatting of powers of 10 when plotting logarithmic
"""
a, b = '{:.2e}'.format(x).split('e')
b = int(b)
if abs(float(a) - 1) < 0.01:
return r'$10^{{{}}}$'.format(b)
else:
return r'${} \times 10^{{{}}}$'.format(a, b) |
def _getMeta(data,type="header"):
"""
"""
name=data['name']
meta=data['meta']
value=""
if type=="header":
if "standard_name" in meta:value=meta['standard_name']
else:value=name
if not 'calendar' in meta and "units" in meta and meta['units']!="" :value="{},{}".format(value,meta['units'])
els... |
def identity(attrs, inputs, proto_obj):
"""Returns the identity function of the the input."""
return 'identity', attrs, inputs |
def url_join(*parts):
"""
helper function to join a URL from a number of parts/fragments.
Implemented because urllib.parse.urljoin strips subpaths from
host urls if they are specified
Per https://github.com/geopython/pygeoapi/issues/695
:param parts: list of parts to join
:returns: str of... |
def or_(arg, *args):
"""Lisp style or. Evaluates expressions from left to right
and returns the value of the first truthy expression.
If all expressions evaluate to False, returns the value of the last expression.
usage
>>> or_(True, True, False)
True
>>> or_(True, False, False)
True
... |
def solution2(nums, K):
"""sum_til record sum from begining
sum between (i, j] sum_til[j] - sum_til[i]
"""
s = 0
sum_til = []
for n in nums:
s += n
sum_til.append(s)
l = len(nums)
for i in range(l):
for j in range(i+1, l):
sum_ij = sum_til[j] if i == ... |
def latest(scores):
"""
Return the latest scores from the list
"""
return scores[-1] |
def convert (hour):
"""
converts Hours in to seconds (hours * 3600)
Args: hours(int)
return: (int value) number of seconds in hours
"""
seconds = 3600
result = hour * seconds
return result |
def str2bool(value):
"""Parse a string into a boolean value"""
return value.lower() in ("yes", "y", "true", "t", "1") |
def downcase(val: str) -> str:
"""Make all characters in a string lower case."""
return val.lower() |
def get_api_id(stack_outputs, api_logical_id):
"""Obtains an API ID from given stack outputs.
:type stack_outputs: str
:param stack_outputs: stack outputs.
:type api_logical_id: str
:param api_logical_id: logical ID of the API.
:rtype: str
:return: API ID.
"""
return stack_outputs... |
def comparison_marker_from_obj(obj):
"""Mark all nested objects for comparison."""
if isinstance(obj, list):
marker = []
for elem in obj:
marker.append(comparison_marker_from_obj(elem))
elif isinstance(obj, dict):
marker = {}
for k, v in obj.items():
m... |
def calc_f1(prec, recall):
""" Helper function to calculate the F1 Score
Parameters:
prec (int): precision
recall (int): recall
Returns:
f1 score (int)
"""
return 2*(prec*recall)/(prec+recall) if recall and prec else 0 |
def bytesHiLo(word):
"""Converts from 16-bit word to 8-bit bytes, hi & lo"""
if word > 255: # more than 1 byte
word_hi, word_lo = word >> 8, word & 0xFF # high byte and low byte
else:
word_hi, word_lo = 0, word # make sure two bytes always sent
return word_hi, word_lo |
def big_o_nn(n_base, m=1, o=1, i=1, nodes=(100, 8), t=1, method='scikit', inv=False):
"""
Calculates the expected computation effort compared to n_time
:param n_base: Calculation time for baseline n
:param algo: algorithm to calculate computation effort for
:param m: features
:param o: output n... |
def get_option(packet, option_code):
"""
Parses for the option_code's data from ipconfig output
packet:
the packet data from "ipconfig getpacket"
option_code:
the DHCP option code to parse, for example "option_121"
Returns a list populated with each line of packet data correspondi... |
def lerp(x: float, in_min: float, in_max: float, out_min: float, out_max: float) -> float:
"""Linearly interpolate from in to out.
If both in values are the same, ZeroDivisionError is raised.
"""
return out_min + ((x - in_min) * (out_max - out_min)) / (in_max - in_min) |
def _absolute_path(repo_root, path):
"""Converts path relative to the repo root into an absolute file path."""
return repo_root + "/" + path |
def factorial2(n):
""" factorial """
if n != 0:
return n * factorial2(n - 1)
elif n == 1:
return 1 * factorial2(n - 1)
else:
return 1 |
def gcovOutputGen(gcovFileLineData):
"""Returns the string of the results of .gcov text file"""
import re
functionData = []
callData = []
branchData = []
outputString = ''
for line in gcovFileLineData:
if re.search('^(function)', line):
functionData.append(li... |
def wordify_open(p, word_chars):
"""Prepend the word start markers."""
return r"(?<![{0}]){1}".format(word_chars, p) |
def _allow_skipping(ancestors, variable, config_user):
"""Allow skipping of datasets."""
allow_skipping = all([
config_user.get('skip_nonexistent'),
not ancestors,
variable['dataset'] != variable.get('reference_dataset'),
])
return allow_skipping |
def fresnel_number(a, L, lambda_):
"""Compute the Fresnel number.
Notes
-----
if the fresnel number is << 1, paraxial assumptions hold for propagation
Parameters
----------
a : `float`
characteristic size ("radius") of an aperture
L : `float`
distance of observation
... |
def dict_factory(colnames, rows):
"""
Returns each row as a dict.
Example::
>>> from cassandra.query import dict_factory
>>> session = cluster.connect('mykeyspace')
>>> session.row_factory = dict_factory
>>> rows = session.execute("SELECT name, age FROM users LIMIT 1")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.