content stringlengths 42 6.51k |
|---|
def get_power_level( coords, serial_num ):
"""
Find the fuel cell's rack ID, which is its X coordinate plus 10.
Begin with a power level of the rack ID times the Y coordinate.
Increase the power level by the value of the grid serial number (your puzzle input).
Set the power level to itself multiplied by the rack I... |
def is_iterable(a):
"""
Test if something is iterable.
"""
return hasattr(a, '__iter__') |
def getBandNumber(band):
"""
Returns band number from the band string in the spreadsheet.
This assumes the band format is in ALMA_RB_NN.
If there is an error, then 0 is return.
"""
try :
bn = int(band.split('_')[-1])
except:
bn = 0
return bn |
def shutdown_without_logon(on=0):
"""Habilitar Desligamento a Partir da Caixa de Dialogo de Logon
DESCRIPTION
Quando este ajuste esta habilitado, o botao de desligamento e mostrado
na caixa de dialogo de autenticacao quando o sistema inicia. Isto permite
que o sistema seja desligado se... |
def sort_in_wave(array):
"""
Given an unsorted array of integers, sort the array
into a wave like array.
An array arr[0..n-1] is sorted in wave form
if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >=
"""
n = len(array)
for i in range(n - 1):
if i % 2 == 0 and array[i] < array[i+1]:
array[i], array[i+... |
def parse_story_file(content):
"""
Remove article highlights and unnecessary white characters.
"""
content_raw = content.split("@highlight")[0]
content = " ".join(filter(None, [x.strip() for x in content_raw.split("\n")]))
return content |
def lensing_channels(config):
"""
Returns number of channels associated with a given lensing config string
:param config: Lensing config string
:return: int number of channels
"""
if config == "g":
return 2
if config == "k":
return 1
if config == "kg":
return 3
... |
def comma_formatter(name_list: list) -> str:
"""Return a properly formatted strings from a list
Args:
name_list (list): list of dog names
Returns:
str: a string in the form of name1, name2, and name3
"""
if len(name_list) == 2:
return " and ".join(name_list)
else:
... |
def get_extent(gtws):
"""Returns extent of gateways (parameter gtws)."""
minx = float("inf")
miny = float("inf")
maxx = float("-inf")
maxy = float("-inf")
for gtw in gtws:
if gtws[gtw][0] < minx:
minx = gtws[gtw][0]
if gtws[gtw][0] > maxx:
maxx = gtws[gt... |
def _positive_slice(slicer):
""" Return full slice `slicer` enforcing positive step size
`slicer` assumed full in the sense of :func:`fill_slicer`
"""
start, stop, step = slicer.start, slicer.stop, slicer.step
if step > 0:
return slicer
if stop is None:
stop = -1
gap = stop ... |
def _rectangle_small_p(a, b, eps):
"""Return ``True`` if the given rectangle is small enough."""
(u, v), (s, t) = a, b
if eps is not None:
return s - u < eps and t - v < eps
else:
return True |
def plugin_init(config):
""" Initialise the plugin.
Args:
config: JSON configuration document for the device configuration category
Returns:
handle: JSON object to be used in future calls to the plugin
Raises:
"""
handle = config['gpiopin']['value']
return handle |
def isEven(v):
"""
>>> isEven(2)
True
>>> isEven(1)
False
"""
return v%2 == 0 |
def create_reventail_axioms(relations_to_pairs, relation='hyponym'):
"""
For every linguistic relationship, check if 'relation' is present.
If it is present, then create an entry named:
Axiom ax_relation_token1_token2 : forall x, _token2 x -> _token1 x.
Note how the predicates are reversed.
"""
... |
def binomial_coefficient(n, k):
"""Finds the binomial coefficient n choose k. See
https://en.wikipedia.org/wiki/Binomial_coefficient for details.
Args:
n (int): An integer.
k (int): An integer.
Returns:
t (int): The binomial coefficient, n choose k.
"""
if not (-1 < k <... |
def raw_synctable_data2(*args, **kwargs):
"""Returns table formatted data for display in the Sync table """
# pylint: disable=unused-argument
return {
"columns": [
{"title": "Visibility Time"},
{"title": "AWS Region"},
{"title": "Action"},
{"title": "I... |
def bin_to_velocity(_bin, step=4):
"""
Takes a binned velocity, i.e., a value from 0 to 31, and converts it to a
proper midi velocity
"""
assert (0 <= _bin * step <= 127), f"bin * step must be between 0 and 127 to be a midi velocity\
not {_bin*step}"
... |
def parse_str_with_space(var: str) -> str:
"""return string without multiply whitespaces
Example: var = 'My name is John '
Return var = 'My name is John'
"""
str_list = list(filter(None, var.split(' ')))
return ' '.join(x for x in str_list) |
def overwrite_options_text(docstring: str, options: dict) -> str:
"""Overwrite the options if there is extra info in the docstring"""
# loop through the options and see if we have an override
if ":option:" in docstring:
docstring_lines = docstring.split("\n")
for line in docstring_lines:
... |
def parse_timezone(text):
"""Parse a timezone text fragment (e.g. '+0100').
Args:
text: Text to parse.
Returns: Tuple with timezone as seconds difference to UTC
and a boolean indicating whether this was a UTC timezone
prefixed with a negative sign (-0000).
"""
# cgit parses th... |
def _fix_dimensions(flat_observations):
"""Temporary ugly hack to work around missing fields in some observations"""
optional_fields = ['taxon.complete_rank', 'taxon.preferred_common_name']
headers = set(flat_observations[0].keys()) | set(optional_fields)
for obs in flat_observations:
for field ... |
def build_plane_map_from_ranges(z_range, t_range):
""" Determines the plane to load. """
plane_map = []
for t in t_range:
for z in z_range:
plane_map.append([t, z])
return plane_map |
def cookie_name_from_auth_name(auth_name: str) -> str:
"""Takes an auth name and returns what the name of the cookie will be.
At the moment we are just prepending _"""
cookie_auth_name = auth_name
if not cookie_auth_name.startswith("_"):
cookie_auth_name = f"_{auth_name.lower()}"
return c... |
def get_reverse_bit(number: int) -> str:
"""
return bit string dari integer
>>> get_reverse_bit(9)
'10010000000000000000000000000000'
>>> get_reverse_bit(43)
'11010100000000000000000000000000'
>>> get_reverse_bit(2873)
'10011100110100000000000000000000'
>>> get_reverse_bit(9)
'10... |
def F(A, n, k):
"""
:param A: Cells list
:param n: the [last-1] princess - 1
:param k: kills left (the beauty of the ([last-1] princess - 1) - 1)
:return: matrix with values of gold coins that the Knight can collect while he is in the cell i and left j kills
"""
matrix = [[0 for _ in ... |
def is_func_argument(i, clue):
"""
Returns True if clue sub-part i is the argument of a directional function (like 'ana_r' or 'sub_l').
We do this because insertion always happens after other functions have been resolved.
"""
return (i > 0 and '_r' in clue[i - 1][1]) or (i < len(clue) - 1 and '_l' ... |
def reautokelv(reaumur):
""" This function converts Reaumur to kelvin, with Reaumur as parameter."""
kelvin = (reaumur * 1.25) + 273.15
return kelvin |
def find_shift_amount(A):
"""
find_shift_amount assumes A is a sorted array that has been cyclically
shifted, and finds the shift amount.
"""
l = 0
r = len(A)-1
if A[l] < A[r]:
return 0
while r-l > 1 and A[l] >= A[r]:
m = l + (r-l)//2
if A[l] > A[m]:
r... |
def _ne(prop_value, cmp_value, ignore_case=False):
"""
Helper function that take two arguments and checks if :param prop_value:
is not equal to :param cmp_value:
:param prop_value: Property value that you are checking.
:type prop_value: :class:`str`
:param cmp_value: Value that you are checking... |
def get_input(text: str):
"""Handle user input.
The function exits cleanly on ``KeyboardInterrupt`` and ``EOFError``
(ctrl-c and ctrl-d).
Args:
Text (str): Prompt to print. A greater than symbol (">") is appended to
the end and escape codes are used to make the prompt bold.
Re... |
def check_for_motif(motifs, seq):
"""
Check if motif exists.
"""
for motif in motifs:
idx = seq.find(motif)
if idx > -1:
return True, seq[idx:] + seq[:idx]
# Did not find any motifs
return False, seq |
def get_consensus(sets, quorum):
"""
Given an iterable of sets of items, find the set containing all items
which appear in at least the quorum number of sets.
Parameters
----------
sets : iterable
Iterable of sets of items.
quorum : integer
Minimum number of sets an item mu... |
def _aws_parameters(use_localstack, localstack_host, region):
"""Constructs a configuration dict that can be used to create an aws client.
Parameters
----------
use_localstack : bool
Whether to use the localstack in this environment.
localstack_host : str
The hostname of the localst... |
def hidden_loc(obj, name):
"""
Generate the location of a hidden attribute.
Importantly deals with attributes beginning with an underscore.
"""
return ("_" + obj.__class__.__name__ + "__" + name).replace("___", "__") |
def averageVelocity(positionEquation, startTime, endTime):
"""
The position equation is in the form of a one variable lambda and the
averagevelocity=(changeinposition)/(timeelapsed)
"""
startTime=float(startTime)
endTime=float(endTime)
vAvg=(positionEquation(startTime)-positionEquation(endTime))/(star... |
def normalize(signal):
"""
This function normalizes all values from -1 to 1
:param list signal: input signal
:return list norm_signal: normalized signal
"""
import logging as log
log.debug("Normalizing signal.\n")
# Let's find the maximum and minimum values
maximum = max(signal)
... |
def add_value(attr_dict, key, value):
"""Add a value to the attribute dict if non-empty.
Args:
attr_dict (dict): The dictionary to add the values to
key (str): The key for the new value
value (str): The value to add
Returns:
The updated attribute dictionary
"""
if v... |
def numerical_function(val_in):
"""Desciption of the function"""
val_in = float(val_in)
local_val = val_in + 1
val_out = local_val - 1
return val_out |
def sum_series(n, n0=0, n1=1):
"""
Compute the nth value of a summation series.
:param n0=0: value of zeroth element in the series
:param n1=1: value of first element in the series
This function should generalize the fibonacci() and the lucas(),
so that this function works for any first two nu... |
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text |
def parse_get(response):
"""Parse get response. Used by TS.GET."""
if not response:
return None
return int(response[0]), float(response[1]) |
def pack_byte(b):
"""Pack one integer byte in a byte array."""
return bytes([b]) |
def ordinal(value):
"""
Converts zero or a *postive* integer (or their string
representations) to an ordinal value.
>>> for i in range(1,13):
... ordinal(i)
...
u'1st'
u'2nd'
u'3rd'
u'4th'
u'5th'
u'6th'
u'7th'
u'8th'
u'9th'
u'10th'
u'11th'
... |
def add_label(key, value, k8s_yaml):
"""Add 'domain: `domain`' label to k8s object.
Args:
key (str): Label key.
value (str): Label value.
k8s_yaml (dict): Loaded Kubernetes object (e.g. deployment, service, ...)
"""
k8s_yaml["metadata"]["labels"][key] = value
return k8s_yaml |
def get_item_attr(idmap, access):
"""
Utility for accessing dict by different key types (for get).
For example::
>>> idmap = {(1,): 2}
>>> get_item_attr(idmap, 1)
2
>>> idmap = {(1,): 2}
>>> get_item_attr(idmap, {"pk": 1})
2
>>> get_item_attr(idmap, (... |
def get_group_from_table(metatable_dict_entry):
"""
Return the appropriate group title based on either the SGID table name or
the shelved category.
"""
sgid_name, _, item_category, _ = metatable_dict_entry
if item_category == 'shelved':
group = 'UGRC Shelf'
else:
table_cate... |
def evlexp(a : int, b : int, op : str) -> int:
""" Evaluates basic arithmetic operation and returns it. """
o = {'+' : a + b, '-' : a - b, '*' : a * b, '/' : a / b, '^' : a**b}
return o[op] |
def is_iterable(obj) -> bool:
"""Check whether object has an iterator."""
try:
iter(obj)
except Exception:
return False
return True |
def compare_members(group, team, attribute="username"):
"""
Compare users in GitHub and the User Directory to see which users need to be added or removed
:param group:
:param team:
:param attribute:
:return: sync_state
:rtype: dict
"""
directory_list = [x[attribute].lower() for x in ... |
def inverse_of(a: int, b: int) -> int:
"""Returns n^-1 (mod p)."""
x0, x1, y0, y1 = 1, 0, 0, 1
oa, ob = a, b
while b != 0:
q = a // b
a, b = b, a % b
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
if x0 < 0:
x0 += ob
if y0 < 0:
y0 += oa
... |
def compute_squared_error_distribution(predicted_values, real_values, normalize=False):
"""Given aligned predicted and real values, computes
the distribution of squared errors between them
"""
distribution = [(p - r)**2 for p, r in zip(predicted_values, real_values)]
if not normalize:
return... |
def get_pitch_min_max(note_tracks):
"""
In order not to waste space,
we may want to know in advance what the highest and lowest
pitches of the MIDI notes are.
"""
pitch_min = 128
pitch_max = 0
for t in note_tracks:
for pitch_list in t:
for note in pitch_list:
... |
def permalink_to_full_link(link: str) -> str:
"""Turns permalinks returned by Praw 4.0+ into full links"""
return "https://www.reddit.com" + link |
def file_to_dict(file_name):
"""Read decklist and create a dictionary of name->amount entries"""
try:
cards = dict()
with open(file_name, 'r') as file:
for line_number, line in enumerate(file):
try:
line = line.strip()
first_spa... |
def right(direction):
"""rotates the direction clockwise"""
return (direction + 1) % 4 |
def get_class_name(obj):
"""
A simple template tag to retrieve the class name of
an object.
:param obj: an input object
"""
return obj.__class__.__name__ |
def split_arguments(args):
"""Returns the 2-tuple (args[:-1], args[-1]) if args[-1] exists and
is a dict; otherwise returns (args, {}).
"""
if args and isinstance(args[-1], dict):
return args[:-1], args[-1]
else:
return args, {} |
def testIfNodesDuplicates(nodes):
"""
Tests if there are dupicates in nodes list
:param nodes: list of node objects
:return: bool passing or failing test
"""
for i in range(0, len(nodes)):
for j in range(0, len(nodes)):
if nodes[i].nodeid == nodes[j].nodeid and i != j:
... |
def is_in_scope(plugin_id, url, out_of_scope_dict):
""" Returns True if the url is in scope for the specified plugin_id """
if '*' in out_of_scope_dict:
for oos_prog in out_of_scope_dict['*']:
#print('OOS Compare ' + oos_url + ' vs ' + 'url)
if oos_prog.match(url):
... |
def dicts_equal(d1, d2):
"""
Perform a deep comparison of two dictionaries
Handles:
- Primitives
- Nested dicts
- Lists of primitives
"""
# check for different sizes
if len(d1) != len(d2):
return False
# check for different keys
for k in d1:
if k not in d2:
return Fa... |
def swap_positions(lst: list, pos_one: int, pos_two: int) -> list:
"""Intercambiate specific elements in a list"""
new_lst = lst.copy()
new_lst[pos_one], new_lst[pos_two] = lst[pos_two], lst[pos_one]
return new_lst |
def convert_category(cat):
"""Talking = 6"""
if cat == '6':
return 1
return 0 |
def bucket_fill(bucket_a_capacity, bucket_a_contents, bucket_b_capacity, bucket_b_contents):
"""
Perform a step in the measure bucket process and return the contents of each bucket.
:param bucket_a_capacity int - The maximum amount of fluid bucket A can have.
:param bucket_a_contents int - The amount o... |
def cloudfront_viewer_protocol_policy(viewer_protocol_policy):
"""
Property: CacheBehavior.ViewerProtocolPolicy
Property: DefaultCacheBehavior.ViewerProtocolPolicy
"""
valid_values = ["allow-all", "redirect-to-https", "https-only"]
if viewer_protocol_policy not in valid_values:
raise Val... |
def editDistance(x ,y):
""" use dynamic programming for edit distance, every edit distance = 1 """
# init matrix D
D = [[0]*(len(y)+1)] * (len(x)+1)
"""
D = []
for i in range(len(x)+1):
D.append([0] * (len(y)+1))
"""
for i in range(len(x)+1):
D[i][0] = i
for i i... |
def utility_columnletter2num(text):
"""
Takes excel column header string and returns the equivalent column count
:param str text: excel column (ex: 'AAA' will return 703)
:return: int of column count
"""
letter_pos = len(text) - 1
val = 0
try:
val = (ord(text[0].upper(... |
def fahrenheit_to_kelvin(a):
"""
Function to compute Fahrenheit from Kelvin
"""
kelvin = (a-32.0)*5/9 + 273.15
return kelvin |
def fix_multi_T1w_source_name(in_files):
"""
Make up a generic source name when there are multiple T1s
>>> fix_multi_T1w_source_name([
... '/path/to/sub-045_ses-test_T1w.nii.gz',
... '/path/to/sub-045_ses-retest_T1w.nii.gz'])
'/path/to/sub-045_T1w.nii.gz'
"""
import os
if n... |
def _encode_to_utf8(s):
"""
Required because h5py does not support python3 strings
converts byte type to string
"""
return s.encode('utf-8') |
def correct_file_name(file_name):
""" Correct for some bad window user's habit
:param file_name: the file name to correct
:return: the corrected file name
"""
file_name = file_name.replace(" ", "\ ")
file_name = file_name.replace("(", "\(")
file_name = file_name.replace(")", "\)")
return... |
def update_formats(formats, ext, format_name):
"""Update the format list with the given format name"""
updated_formats = []
found_ext = False
for org_ext, org_format_name in formats:
if org_ext != ext:
updated_formats.append((org_ext, org_format_name))
elif not found_ext:
... |
def validate_vpc_id(value):
"""Raise exception if VPC id has invalid length."""
if len(value) > 64:
return "have length less than or equal to 64"
return "" |
def hawaii_transform(xy):
"""Transform Hawaii's geographical placement so fits on US map"""
x, y = xy
return (x + 5250000, y-1400000) |
def keys(dict):
"""Returns a list containing the names of all the enumerable own properties of
the supplied object.
Note that the order of the output array is not guaranteed to be consistent
across different JS platforms"""
return list(dict.keys()) |
def nukenewlines(string):
"""Strip newlines and any trailing/following whitespace; rejoin
with a single space where the newlines were.
Bug: This routine will completely butcher any whitespace-formatted
text."""
if not string:
return ""
lines = string.splitlines()
return " ".join([l... |
def solution2(A):
"""
Similar to solution(), but without using sort().
"""
# Define a variable to store the previous element in an iteration
previous_int = 1
while True:
if previous_int+1 in A:
previous_int += 1
continue
else:
return previous_... |
def optimize_regex(regex):
"""
Reduce overly verbose parts of a generated regex expression.
Args:
regex - The regex expressio to optimize
"""
regex = str(regex)
for n in range(9):
regex = regex.replace('[' + str(n) + '-' + str(n+1) + ']','[' + str(n) + str(n+1) + ']')
for n ... |
def MAX(*expression):
"""
Returns the maximum value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/max/
for more details
:param expression: expression/expressions or variables
:return: Aggregation operator
"""
return {'$max': list(expression)} if len(expression) > 1 ... |
def check_db_for_feature(feature, db_features=None):
"""
Args:
feature: A feature to be checked for.
db_features: All of the db features (see get_all_db_features).
Returns:
The feature if it matches, otherwise None.
"""
fulcrum_id = feature.get('properties').get('... |
def insertion_sort(list):
"""
This is a function that sorts the given list using the insertion algorithm.
"""
if not list or len(list) == 0:
return []
if len(list) == 1:
return list
print(f"input list = {list}")
for i in range(len(list) - 1):
if list[i+1] < list[i]:... |
def return_clean_date(timestamp: str) -> str:
"""
Return YYYY-MM-DD
:param timestamp: str of the date
:return: Return YYYY-MM-DD
"""
if timestamp and len(timestamp) > 10:
return timestamp[:10]
else:
return "" |
def query(query_string, data):
"""
Return a query string for use in HTML links. For example, if
query_string is "?page=foo" and data is "date=200807" this function
will return "?page=foo&date=200807" while if query_string were "" it
would return "?date=200807".
"""
if query_s... |
def categories_to_json(categories):
"""
categories_to_json converts categories SQLAlchemy object to json object
works by simply looping over collection of objects and manually mapping
each Object key to a native Python dict
"""
main = {}
main['categories'] = []
for cat in categories:
... |
def detokenize(sent):
""" Roughly detokenizes (mainly undoes wordpiece) """
new_sent = []
for i, tok in enumerate(sent):
if tok.startswith("##"):
new_sent[len(new_sent) - 1] = new_sent[len(new_sent) - 1] + tok[2:]
else:
new_sent.append(tok)... |
def DecodeEncode(tRaw, filetype):
"""return the decoded string or False
used by readAnything, also see testreadanything in miscqh/test scripts
"""
try:
tDecoded = tRaw.decode(filetype)
except UnicodeDecodeError:
return False
encodedAgain = tDecoded.encode(filetype)
... |
def skewed_lorentzian(x, bkg, bkg_slp, skw, mintrans, res_f, Q):
""" Skewed Lorentzian model.
Parameters
----------
x : float
The x-data to build the skewed Lorentzian
bkg : float
The DC value of the skewed Lorentzian
bkg_slp : float
The slope of the skewed Lorentzian
... |
def DistanceOfPointToRange( point, range ):
"""Calculate the distance from a point to a range.
Assumes point is covered by lines in the range.
Returns 0 if point is already inside range. """
start = range[ 'start' ]
end = range[ 'end' ]
# Single-line range.
if start[ 'line' ] == end[ 'line' ]:
# 0 i... |
def convert_index_to_int(adj_lists):
"""Function to convert the node indices to int
"""
new_adj_lists = {}
for node, neigh in adj_lists.items():
new_adj_lists[int(node)] = neigh
return new_adj_lists |
def predicate_info(logic, start, equals_ind):
"""Returns information about predicate logic from string form"""
var = logic[0:equals_ind]
operator = "="
if var[-1]=="<" or var[-1]==">":
operator = var[-1] + operator
var = var[:-1]
return var, operator |
def solveit(test):
""" test, a function that takes an int parameter and returns a Boolean
Assumes there exists an int, x, such that test(x) is True
Returns an int, x, with the smallest absolute value such that test(x) is True
In case of ties, return any one of them.
"""
# IMPLEMENT T... |
def get_sched_func_name(stackname):
"""
:param stackname:
:return:
"""
name=stackname+"-lambda-sched-event"
return name[-63:len(name)] |
def extract_object(dictionary, key_sequence):
"""
Extract the object inside the dictionary at a specific path
:param dictionary (Dict): dictionary to extract from
:param key_sequence (List[str]): list of strings represetning key accesses
:return: the value inside dictionary specified by key_sequence... |
def conFirmColorCov(nclicks, r, g, b, dataset, backup):
""" Callback to confirm a color. This will overwrite the previous one.
Positional arguments:
nclicks -- Button value.
r -- Red value.
g -- Green value.
b -- Blue value.
dataset -- Dataset to overwrite color of.
backup -- Previous v... |
def get_rotated_index(start: int, size: int, index: int) -> int:
"""Get the rotated index of the array"""
return (index + start) % size |
def get_mask(seg):
"""
get corresponding upper/lower tag of given seg
Hello -> ULLLL
:param seg:
:return:
"""
mask = ""
for e in seg:
if e.isupper():
mask += "U"
elif e.islower():
mask += "L"
else:
mask += "L"
return mask |
def profile_to_encoded_str(profile):
"""
Encode profile to '&' and '=' separated string.
Return the encoded string.
"""
return '&'.join(["{}={}".format(k,v) for k,v in profile.items()]) |
def SplitNamespace(ref):
"""Returns (namespace, entity) from |ref|, e.g. app.window.AppWindow ->
(app.window, AppWindow). If |ref| isn't qualified then returns (None, ref).
"""
if '.' in ref:
return tuple(ref.rsplit('.', 1))
return (None, ref) |
def compute_rate(old, new, seconds):
"""Compute a rate that makes sense"""
delta = new - old
if delta < 0:
delta = new
return delta / seconds |
def encodeMsg(aStr):
"""Encode a message for transmission to the hub
such that multiple lines show up as one command.
"""
return aStr.replace("\n", "\v") |
def test_module_import(module_name):
""" Import module or return false"""
try:
__import__(module_name)
return True
except:
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.