content stringlengths 42 6.51k |
|---|
def csv_row_station_bssid(row):
"""
Provide associated bssid of given station.
:param row: list of strings representing one row of csv file generated by airodump-ng during scanning
:return: string bssid
"""
return row[5].strip() |
def many_to_one(input_dict):
"""Convert a many-to-one mapping to a one-to-one mapping"""
return dict((key, val)
for keys, val in input_dict.items()
for key in keys) |
def __get_sourceforge_url(pkg_info):
"""
Get git repo url of package
"""
url = pkg_info["src_repo"]
return url |
def _get_by_path_kw(pathlist):
""" Used by :meth:`get_by_path` to create the required kwargs for
Node.objects.get(). Might be a starting point for more sophisticated
queries including paths. Example::
ifi = Node.objects.get(**Node._get_by_path_kw(['uio', 'ifi']))
:param pathlist: A list of nod... |
def get_multiline_actions(a_string):
"""
Transforms the multiline command string provided into a list of single-line commands.
:param a_string:
:return: a list of action strings
"""
def _procline(l):
# remove spaces on the left
l = l.strip()
# remove comments
tr... |
def solve(n, mp, q, queries):
"""
Solve the problem here.
:return: The expected output.
"""
def set_transform(s):
return {mp[i] - 1 for i in s}
def stringify(tup):
return ','.join(map(str, tup))
answer = [-1 for _ in range(n-1)] + [0]
current = {i for i in range(n)}
... |
def validate_bool(val):
"""
Convert b to a boolean or raise a ValueError.
"""
if type(val) is str:
val = val.lower()
if val in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
return True
elif val in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
return False
else:... |
def exercise_1(inputs): # DO NOT CHANGE THIS LINE
"""
This functions receives the input in the parameter 'inputs'.
Change the code, so that the output is sqaure of the given input.
p, q, r = inputs
p => ['t101', 't102', 't103']
q => ['s101', 's102', 's103']
r => {
'l101':[... |
def build_person(first_name, last_name, age=None):
"""Return a dictionary of infotmation about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person |
def is_in_list(list_one, list_two):
"""Check if any element of list_one is in list_two."""
for element in list_one:
if element in list_two:
return True
return False |
def max_subseq(n, t):
"""
Return the maximum subsequence of length at most t that can be found in the given number n.
For example, for n = 20125 and t = 3, we have that the subsequences are
2
0
1
2
5
20
21
22
25
01
02
... |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
The code should run in O(n) time. Do not use Python's inbuilt functions to find min and max.
Args:
ints(list): list of integers containing one or more integers
"""
min_value = ints[0]
max_value = in... |
def invert(d):
"""
Take in dictionary d
Returns a new dictionary: d_inv
Values in it are a list
Flips value and keys
"""
d_Inv = {}
for i in d.keys():
temp = d[i]
# Need the if statement to assign, or add to a list!
if temp not in d_Inv:
d_... |
def all_unique(lst: list) -> bool:
"""Check if a given list has duplicate elements"""
return len(lst) == len(set(lst)) |
def fibonacci_comprehension(limit):
"""fibonacci sequence using a list comprehension."""
sequence = [0, 1]
[sequence.append(sequence[i] + sequence[i - 1]) for i in range(1, limit)]
return sequence[-1] |
def getnameinfo(sockaddr, flags):
"""Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending
on the settings of *flags*, the result can contain a fully-qualified domain name
or numeric address representation in *host*. Similarly, *port* can contain a
string port name o... |
def deformat_var_key(key: str) -> str:
"""
deformat ${key} to key
:param key: key
:type key: str
:return: deformat key
:rtype: str
"""
return key[2:-1] |
def cleana(tagged):
"""clean tags and new lines out of single attribute"""
if tagged:
untagged = (tagged.text) # strip tags
# strip newlines
stripped = (untagged
.replace('\n\n+', ' ')
.replace('\n', ' ')
.replace('\r... |
def selectArea(arr, x1, y1, x2, y2):
"""Selects a specified area from a 2D array and fills a 1D arr with the values"""
areaArr = []
for row in range(y1, y2):
for col in range(x1, x2):
areaArr.append(arr[row][col])
return areaArr |
def changeSecurityListToStr(securityList:list):
"""
This function will convert a list of string into a single string.
"""
securityListFormed = [i+',' for i in securityList]
return "".join(securityListFormed).strip(',') |
def fist_visible_seat(seats, pos: tuple, shift: tuple):
"""Return the first visible seat by continously applying the same shift.
>>> fist_visible_seat(["...L.#.#.#.#."], (0, 0), (0, 1))
'L'
>>> fist_visible_seat([".....#.#.#.#."], (0, 4), (0, 1))
'#'
"""
row, column = pos
rshift, cshift... |
def filterSplit(p, values):
"""
Function filters a list into two sub-lists, the first containing entries
satisfying the supplied predicate p, and the second of entries not satisfying p.
"""
satp = []
notp = []
for v in values:
if p(v):
satp.append(v)
else:
... |
def check_input(string, char_set):
"""checks if a string is 5 chars long and only contains chars from a given set"""
return len(string) == 5 and not (set(string) - char_set) |
def _product(a,scalar):
""" multiply iterable a by scalar """
return tuple([scalar*x for x in a]) |
def make_sepset_node_name(node_a_name, node_b_name):
"""
Make a standard sepset node name using the two neighboring nodes.
:param str node_a_name: The one node's name.
:param str node_b_name: The other node's name.
:return: The sepset's name
:rtype: str
"""
return "sepset__" + "__".join... |
def to_bool(val):
"""Converts true, yes, y, 1 to True, False otherwise."""
if val:
strg = str(val).lower()
if (strg == 'true' or strg == 'y'
or strg == 'yes' or strg == 'enabled'
or strg == '1'):
return True
else:
return False
else:... |
def read(path, mode='rt'):
"""Read a file and return its content."""
try:
with open(path, mode) as fp:
return fp.read()
except Exception as e:
return f'FILE ERROR: {e}, path {path!r}' |
def email_sent_ipn(path: str) -> tuple:
"""
**email_sent_ipn**
Delivered ipn for mailgun
:param path: organization_id
:return: OK, 200
"""
# NOTE: Delivered ipn will end up here
if path == "delivered":
pass
elif path == "clicks":
pass
elif path == "op... |
def code_event(event):
"""get the event code"""
if event == 'tracker': return 5
elif event == 'acc on': return 6
elif event == 'acc off': return 7
elif event == 'help me': return 1
elif event == 'speed': return 2
elif event == 'ac alarm': return 9
else: return None |
def username_to_oci_compatible_name(username):
"""
To generate a safe username this method can be used and we'll strip out characters that would typically appear in an email
which don't help with a username
Args:
* username : uncleansed username e.g. the user's email address
**Returns**
The cleansed u... |
def hass_to_lox(level):
"""Convert the given HASS light level (0-255) to Loxone (0.0-100.0)."""
return (level * 100.0) / 255.0 |
def ical_escape (victim):
""" iCal has weird escaping rules. Implement them.
iCal also has weird block formatting rules. Ugh.
"""
if not victim:
return "EMPTY STRING PROVIDED TO ICAL_ESCAPE"
# https://stackoverflow.com/questions/18935754/how-to-escape-special-characters-of-a-st... |
def get_slope_intercept(point1 , point2):
"""
:param point1: lower point of the line
:param point2: higher point of the line
:return: slope and intercept of this line
"""
slope = (point1[1] - point2[1]) / (point1[0] - point2[0]) # slope = ( y2-y1 ) / ( x2-x1 ) .
intercept = point1[1] - sl... |
def Shift(xs, shift):
"""Adds a constant to a sequence of values.
Args:
xs: sequence of values
shift: value to add
Returns:
sequence of numbers
"""
return [x+shift for x in xs] |
def filter_channels_by_server(channels, server):
"""Remove channels that are on the designated server"""
chans = []
for channel in channels:
sv, chan = channel.split(".", 1)
if sv == server:
chans.append(chan)
return chans |
def steering3(course, power):
"""
Computes how fast each motor in a pair should turn to achieve the
specified steering.
Compared to steering2, this alows pivoting.
Input:
course [-100, 100]:
* -100 means turn left as fast as possible (running left
... |
def _is_batch_all(batch, predicate):
"""
Implementation of is_symbolic_batch() and is_numeric_batch().
Returns True iff predicate() returns True for all components of
(possibly composite) batch.
Parameters
----------
batch : any numeric or symbolic batch.
This includes numpy.ndarray... |
def _strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
.. note:: copied from distutils.util
"""
... |
def _safe_decode(output_bytes: bytes) -> str:
"""
Decode a bytestring to Unicode with a safe fallback.
"""
try:
return output_bytes.decode(
encoding='utf-8',
errors='strict',
)
except UnicodeDecodeError:
return output_bytes.decode(
encoding... |
def Area_Perimeter(a,b,ch=1):
"""
a(int): Length of the rectangle
b(int): Breadth of the rectangle
ch(int): choice
ch==1>>Area
ch==2>>Perimeter
Returns area or perimeter of the rectangle.
"""
if ch==1:
return 'Area is '+str(a*... |
def check_if_string_in_file(file_name, string_to_search):
""" Check if any line in the file contains given string """
# Open the file in read only mode
with open(file_name, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
# For each line, check if l... |
def is_field_selected(model, field, spec):
"""Apply field_specs to tell if model.field is to be included
>>> specs = lambda s: parse_field_specs(s)
Basic direct usage
------------------
If explicitely selected::
>>> is_field_selected('bar', 'f1', specs('bar:f1'))
True
De... |
def box_volume_UPS(a=13, b=11, c=2):
"""Returns the volume of a box with edge lengths a, b and c.
Default values are a = 13 inches, b = 11 inches and c = 2 inches"""
return a * b * c |
def forcedir(path):
"""Ensure the path ends with a trailing forward slash
:param path: An FS path
>>> forcedir("foo/bar")
'foo/bar/'
>>> forcedir("foo/bar/")
'foo/bar/'
"""
if not path.endswith('/'):
return path + '/'
return path |
def fix_sign(x, N=360 * 60 * 10):
"""
Convert negative tenths of arcminutes *x* to positive by checking
bounds and taking the modulus N (360 degrees * 60 minutes per
degree * 10 tenths per 1).
"""
if x < 0:
assert x > -N
x += N
assert x < N
return x % N |
def get_steps_to_exit(data, strange=False):
"""
Determine the number of steps to exit the 'maze'
Starting at the first element, move the number of steps based on
the value of the current element, and either bump it by one, or
if 'strange' is True and the value is over three, decrease it by
one.... |
def evaluate(coeffs, x0):
"""evaluate polynomial represented by 'coeffs' at x = x0"""
p_x0 = 0
for c_k in reversed(coeffs):
p_x0 = p_x0*x0 + c_k
return p_x0 |
def tidy_participation_url(url: str) -> str:
"""
>>> tidy_participation_url(
... "https://test.connpass.com/event/123456/participation/")
'https://test.connpass.com/event/123456/participation/'
>>> tidy_participation_url(
... "https://test.connpass.com/event/123456/participation")
'ht... |
def make_key(x,y):
"""
function to combine two coordinates into a valid dict key
"""
return f'{x}, {y}' |
def rep_newlines_with_space(string: str) -> str:
"""Removes newlines and replaces them with spaces.
Also reduces double spaces to single spaces.
"""
return string.replace("\n", " ").replace(" ", " ") |
def get_max_len_word(_list):
"""Return max len word from list"""
return max(len(item) for item in _list if type(item) != int) |
def extract_words(all_words):
"""
Product title contains some preposition words.
The words after preposition word usually indicate
components, materials or intended usage. Therefore,
there is no need to find brand and product name in
the words after preposition. There is one exception:
the p... |
def scan_square(row, col, matrix):
""" Scan the current position for a square of odd sides.
Args:
row - integer for row position
col - column position
matrix - multi-dimensional list of 0's and 1's
Returns a tuple describing the biggest square's center coordinates
and the dimens... |
def normalize_cell(string, length):
"""Format string to a fixed length."""
return string + ((length - len(string)) * ' ') |
def scaling_constant(n0, n1, nr, p):
"""
Determine the scaling constant.
"""
h0 = 0.5 ** (n0 * p)
h1 = 0.5 ** (n1 * p)
hr = 0.5 ** (nr * p)
y = (h0 - hr) / (h1 - hr)
return y |
def log_error(error, log):
"""
- error: string
- log: None or list of string
RETURN: error string
"""
if log is not None:
log.append(error)
return error |
def _option_boolean(arg):
"""Copied from matplotlib plot_directive."""
if not arg or not arg.strip():
# no argument given, assume used as a flag
return True
elif arg.strip().lower() in ('no', '0', 'false'):
return False
elif arg.strip().lower() in ('yes', '1', 'true'):
re... |
def format_size(size):
"""
Convert size to XB, XKB, XMB, XGB
:param size: length value
:return: string value with size unit
"""
units = ['B', 'KB', 'MB', 'GB']
unit = ''
n = size
old_n = n
value = size
for i in units:
old_n = n
x, y = divmod(n, 1024)
i... |
def get_in_turn_repetition(pred, is_cn=False):
"""Get in-turn repetition."""
if len(pred) == 0:
return 1.0
if isinstance(pred[0], str):
pred = [tok.lower() for tok in pred]
if is_cn:
pred = "".join(pred)
tri_grams = set()
for i in range(len(pred) - 2):
tri... |
def std_value(x: float, m_x: float, s_x: float) -> float:
"""
This function computes standardized values of a sequence value
given its mean and standard deviation.
"""
return (x - m_x) / s_x |
def quadratic(x, a, b, c):
"""General quadratic function"""
return a*x**2 + b*x + c |
def finding_gitlab_forks(fork_user):
"""
fork_user: Takes a repository to user_count dictionary map
purpose: calculates how much gitlab forks are there among all the forks
"""
total_forks = 0
gitlab_forks = 0
gitlab_url = []
for fu in fork_user:
total_forks += 1
if 'h... |
def plot(ax, interval, valid, tmpf, lines, mydir, month):
""" Our plotting function """
if len(lines) > 10 or len(valid) < 2 or (valid[-1] - valid[0]) < interval:
return lines
if len(lines) == 10:
ax.text(0.5, 0.9, "ERROR: Limit of 10 lines reached",
transform=ax.transAxes)
... |
def get_antibody_type(antibody_type_string):
"""Generate mcf line for antibodyType"""
if antibody_type_string in ['Nanobody', 'Nanobody (VNAR)']:
return 'antibodyType: dcs:NanobodyAntibody'
if antibody_type_string == 'Bispecific':
return 'antibodyType: dcs:BispecificAntibody'
if antibody... |
def _profile_tag_from_conditions(conditions):
"""
Given a list of conditions, return the profile tag of the
device rule if there is one
"""
for c in conditions:
if c['kind'] == 'device':
return c['profile_tag']
return None |
def get_output(digit_list):
"""
>>> get_output([1,2,3])
'123'
"""
return ''.join([str(i) for i in digit_list]) |
def myadd(first, last):
"""Create column headings"""
if 'regression' in first:
output = first
else:
output = first + ' (' + last + ')'
return output |
def _num_extracted_rows_and_columns(
image_size: int,
patch_size: int,
stride: int,
num_scales: int,
scale_factor: int,
) -> int:
"""The number of rows or columns in a patch extraction grid."""
largest_patch_size = int(patch_size * (scale_factor**(num_scales - 1)))
residual = image_size - larg... |
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 build_uniform_beliefs(num_agents):
""" Build uniform belief state.
"""
return [i/(num_agents - 1) for i in range(num_agents)] |
def three_measurement_window_sum(list_int):
"""
This function calculates the sums of all three-measurement sliding windows in the list.
This is part of the answer to the second puzzle.
Parameters:
list_int (list): list of measurements(integers)
Returns:
new_list (list): list of sum... |
def center_of_points_list(points: list) -> tuple:
"""Calculates the center (average) of points in a list."""
# Extract all x coordinates from list of points (odd list positions)
coordinates_x = points[::2]
# Extract all y coordinates from list of points (even list positions)
coordinates_y = points... |
def build_first_number_with(digits_sum):
"""
Build the smallest number (f_value) with given digits sum.
:param digits_sum:
:return: list of digits in reverse order
for digits sum 20 returns: [9, 9, 2],
for digits_sum 45 returns : [9, 9, 9, 9, 9]
"""
n9, d = divmod(digits_sum, 9)
re... |
def parse_lod_value(lod_key: str) -> str:
"""Extract the LoD value from an LoD parameter key (eg. lod13).
For example 'lod13' -> '1.3'
"""
pos = lod_key.lower().find('lod')
if pos != 0:
raise ValueError(f"The key {lod_key} does not begin with 'lod'")
value = lod_key[3:]
if len(value... |
def get_upper(somedata):
"""
Handle Python 2/3 differences in argv encoding
"""
result = ""
try:
result = somedata.decode("utf-8").upper()
except:
result = somedata.upper()
return result |
def _1_add_profile_uuid(config):
"""Add the required values for a new default profile.
* PROFILE_UUID
The profile uuid will be used as a general purpose identifier for the profile, in
for example the RabbitMQ message queues and exchanges.
"""
for profile in config.get('profiles', {}).value... |
def get_chart_parameters(prefix='', rconn=None):
"""Return view, flip and rotate values of the control chart"""
if rconn is None:
return (100.0, False, 0.0)
try:
view = rconn.get(prefix+'view').decode('utf-8')
flip = rconn.get(prefix+'flip').decode('utf-8')
rot = rconn.get(pr... |
def get_model_config(model):
"""Returns hyper-parameters for given mode"""
if model == 'maml':
return 0.1, 0.5, 5
if model == 'fomaml':
return 0.1, 0.5, 100
return 0.1, 0.1, 100 |
def AsQuotedString(input_string):
"""Convert |input_string| into a quoted string."""
subs = [
('\n', '\\n'),
('\t', '\\t'),
("'", "\\'")
]
# Go through each substitution and replace any occurrences.
output_string = input_string
for before, after in subs:
output_string = output_string.... |
def _has_unclosed_parens(line):
"""
Assumes there's no more than one pair of parens (or just one "("), which is reasonable for
import lines.
"""
if '(' in line:
_, rest = line.split('(')
return ')' not in rest
return False |
def _type_name(value):
"""
:param value:
The value to get the type name of
:return:
A unicode string of the name of the value's type
"""
value_cls = value.__class__
value_module = value_cls.__module__
if value_module in set(['builtins', '__builtin__']):
return value... |
def chop_array(arr, window_size, hop_size):
"""chop_array([1,2,3], 2, 1) -> [[1,2], [2,3]]"""
return [arr[i - window_size:i] for i in range(window_size, len(arr) + 1, hop_size)] |
def std_action_map(sourceidx, action, labels):
"""Standard graphziv attributes used for visualizing actions.
Computes the attributes for a given source, action index and action labeling.
:param stateidx: The index of the source-state.
:type stateidx: int
:param action: The index of the action.
:... |
def euler_problem_80(bound=100, keep_digits=100):
"""
It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.
The square root of two is 1.41421356237309504880..., and t... |
def _solve_method_2(N, queries):
"""
This section right here uses some Pythonic optimizations, but they still
don't cut on speed. This at least is much faster I think, assuming each of
these operations is atomic.
"""
arr = [0] * N
largest = -1
for query in queries:
from operato... |
def writefile(filename, data, mode=None, encoding=None):
"""mode: None=datatype (default), 'b'=binary data, 't'=text data
"""
if mode is None:
mode = 't' if isinstance(data, str) else 'b'
if mode != 't' and mode != 'b':
raise ValueError('Unexpected mode {0!r}, expected \'b\' or \'t\''.fo... |
def sarray2iarray(S):
"""Convert an string array/list to iarray, replace non-int by"""
out=[]
for s in S:
try:
r=int(float(s))
except:
r=None
out.append(r)
return out |
def find_delta(a, b, c):
"""
Function that returns the delta of a quadratic equation.
"""
if a == 0:
raise ValueError("a is 0! [y = ax^2 + bx + c , a != 0]")
delta = b**2 - 4*a*c
return delta |
def format_buttons(buttons):
"""
In the typical Facebook response message, it sends back pressable
buttons. We don't really care that much about that for the
testing(for now). We just want to be sure that we're sending pictures/text
properly. Returns a list.
"""
if not buttons: return []
... |
def stuff(string,symbol,number):
""" Add number copies of symbol to string
Returns modified string.
"""
for i in range(number):
string += symbol
string += " "
return string |
def parse_task_full_content(full_content):
"""
Return a tuple (title, content) extracted from the content found in a file
edited through `todo edit` or `todo add [<title>] --edit`
"""
title, content = '', None
state = 'title'
lines = full_content.splitlines(keepends=True)
for i, line in enumerate(lines):
if s... |
def color_to_pixel(color):
"""Turns RGB color value to pixel value."""
red = color[0]
green = color[1]
blue = color[2]
alpha = 0
if len(color) == 4:
alpha = color[3]
return ((((red)) << 24) | # noqa: W504
(((green)) << 16) | # noqa: W504
(((blue)) << 8) | # noqa: W504
((alpha))) # noq... |
def bounding_box2D(pts):
"""
Rectangular bounding box for a list of 2D points.
Args:
pts (list): list of 2D points represented as 2-tuples or lists of length 2
Returns:
x, y, w, h (floats): coordinates of the top-left corner, width and
height of the bounding box
"""
... |
def Prime_Factorization(x):
""" Gives the list of all prime factors of the number. """
lst=[]
cycle=2
while cycle<=x:
if x%cycle==0:
x/=cycle
lst.append(cycle)
else:
cycle+=1
return lst |
def get_price(sellers,formula,total_we_profit=0):
"""
sellers is a list of lists where each list contains follwing item in order
1. Seller Name
2. Number of cores
3. Price of each core
If formula is 1 then curernt total profit should be subtracted from numberator
total_we_profit is the "curernt total profit" ... |
def sort_shares_by_status(shares):
"""Sorts shares by status and returns a dict key'd by status type.
:returns: tuple with the first part being the dictionary of shares
keyed by their status, the second part being the auth users share.
Example:
(
{'ACCEPTED': [...],
'PENDING'... |
def linear(a, b, c):
"""exec a * b + c"""
print('exec linear')
ret = a * b + c
print('linear: %s * %s + %s = %s' % (a, b, c, ret))
return ret |
def myfloat(value, prec=4):
""" round and return float """
if value is None:
return 0
return round(float(value), prec) |
def pcall(func, *args, **kwargs):
"""
Calls a passed function handling any exceptions.
Returns either (None, result) or (exc, None) tuple.
"""
try:
return None, func(*args, **kwargs)
except Exception as e:
return e, None |
def _check_native(tbl):
"""
Determine if Python's own native implementation
subsumes the supplied case folding table
"""
try:
for i in tbl:
stv = chr(i)
if stv.casefold() == stv:
return False
except AttributeError:
return False
return T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.