content
stringlengths 7
1.05M
|
---|
def consolidate(sets):
setlist = [s for s in sets if s]
for i, s1 in enumerate(setlist):
if s1:
for s2 in setlist[i+1:]:
intersection = s1.intersection(s2)
if intersection:
s2.update(s1)
s1.clear()
s1 = s2
return [s for s in setlist if s]
|
class InterpreterException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class SymbolNotFound(InterpreterException):
pass
class UnexpectedCharacter(InterpreterException):
pass
class ParserSyntaxError(InterpreterException):
pass
class DuplicateSymbol(InterpreterException):
pass
class InterpreterRuntimeError(InterpreterException):
pass
class InvalidParamCount(InterpreterRuntimeError):
pass |
#! /usr/bin/env python
#
# parameters/standard.py
#
# Nick Barnes, Ravenbrook Limited, 2010-02-15
# Avi Persin, Revision 2016-01-06
"""Parameters controlling the standard GISTEMP algorithm.
Various parameters controlling each phase of the algorithm are
collected and documented here. They appear here in approximately the
order in which they are used in the algorithm.
Parameters controlling cccgistemp extensions to the standard GISTEMP
algorithm, or obsolete features of GISTEMP, are in other parameter
files.
"""
station_drop_minimum_months = 20
"""A station record must have at least one month of the year with at
least this many valid data values, otherwise it is dropped immediately
prior to the peri-urban adjustment step."""
rural_designator = "global_light <= 10"
"""Describes the test used to determine whether a station is rural or
not, in terms of the station metadata fields. Relevant fields are:
'global_light' (global satellite nighttime radiance value); 'popcls'
(GHCN population class flag; the value 'R' stands for rural);
'us_light' (class derived from satellite nighttime radiance covering
the US and some neighbouring stations), 'berkeley' (a field of unknown
provenance which seems to be related to the Berkeley Earth Surface
Temperature project).
The value of this parameter may be a comma separated sequence. Each
member in that sequence can either be a metadata field name, or a
numeric comparison on a metadata field name (e.g. "global_light <= 10",
the default). If a field name appears on its own, the meaning is
field-dependent.
The fields are consulted in the order specified until one is found
that is not blank, and that obeys the condition (the only field which
is likely to be blank is 'us_light': this sequential feature is
required to emulate a previous version of GISTEMP).
Previous versions of GISTEMP can be "emulated" as follows:
"popcls" GISTEMP 1999 to 2001
"us_light, popcls" GISTEMP 2001 to 2010
"global_light <= 10" GISTEMP 2010 onwards
"global_light <= 0" GISTEMP 2011 passing 2 as second arg to do_comb_step2.sh
"berkeley <= 0" GISTEMP 2011 passing 3 as second arg to do_comb_step2.sh
"""
urban_adjustment_min_years = 20
"""When trying to calculate an urban station adjustment, at least this
many years have to have sufficient rural stations (if there are
not enough qualifying years, we may try again at a larger radius)."""
urban_adjustment_proportion_good = 2.0 / 3.0
"""When trying to calculate an urban station adjustment, at least this
proportion of the years to which the fit applies have to have
sufficient rural stations (if there are insufficient stations, we may
try again at a larger radius)."""
urban_adjustment_min_rural_stations = 3
"""When trying to calculate an urban station adjustment, a year
without at least this number of valid readings from rural stations is
not used to calculate the fit."""
urban_adjustment_min_leg = 5
"""When finding a two-part adjustment, only consider knee years which
have at least this many data points (note: not years) on each side."""
urban_adjustment_short_leg = 7
"""When a two-part adjustment has been identified, if either leg is
shorter than this number of years, a one-part adjustment is applied
instead."""
urban_adjustment_steep_leg = 0.1
"""When a two-part adjustment has been identified, if the gradient of
either leg is steeper than this (in absolute degrees Celsius per
year), or if the difference between the leg gradients is greater than
this, a one-part adjustment is applied instead."""
urban_adjustment_leg_difference = 0.05
"""When a two-part adjustment has been identified, if the difference
in gradient between the two legs is greater than this (in absolute
degrees Celsius per year), it is counted separately for statistical
purposes."""
urban_adjustment_reverse_gradient = 0.02
"""When a two-part adjustment has been identified, if the two
gradients have opposite sign, and both gradients are steeper than this
(in absolute degrees Celsius per year), a one-part adjustment is
applied instead."""
urban_adjustment_full_radius = 1000.0
"""Range in kilometres within which a rural station will be considered
for adjusting an urban station record. Half of this radius will be
attempted first."""
rural_station_min_overlap = 20
"""When combining rural station annual anomaly records to calculate
urban adjustment parameters, do not combine a candidate rural record
if it has fewer than this number years of overlap."""
gridding_min_overlap = 20
"""When combining station records to give a grid record, do not
combine a candidate station record if it has fewer than this number of
years of overlap with the combined grid record."""
gridding_radius = 1200.0
"""The radius in kilometres used to find and weight station records to
give a grid record."""
gridding_reference_period = (1951, 1980)
"""When gridding, temperature series are turned into anomaly series by
subtracting monthly means computed over a reference period. This is
the first and last years of that reference period."""
sea_surface_cutoff_temp = -1.77
"""When incorporating monthly sea-surface datasets, treat any
temperature colder than this as missing data."""
subbox_min_valid = 240
"""When combining the sub-boxes into boxes, do not use any sub-box
record, either land or ocean, which has fewer than this number of
valid data."""
subbox_land_range = 100
"""If a subbox has both land data and ocean data, but the distance
from the subbox centre to the nearest station used in its record is
less than this, the land data is used in preference to the ocean data
when calculating the box series. Note: the distance used is actually a
great-circle chord length."""
subbox_reference_period = (1961, 1990)
"""When combining subbox records into box records, temperature series
are turned into anomaly series by subtracting monthly means computed
over a reference period. This is the first and last years of that
reference period."""
box_min_overlap = 20
"""When combining subbox records to make box records, do not combine a
calendar month from a candidate subbox record if it has fewer than
this number of years of overlap with the same calendar month in the
combined box record. Also used when combining boxes into zones."""
box_reference_period = (1951, 1980)
"""When combining box records into zone records, temperature series
are turned into anomaly series by subtracting monthly means computed
over a reference period. This is the first and last years of that
reference period."""
zone_annual_min_months = 6
"""When computing zone annual means, require at least this many valid
month data."""
|
#Copyright (c) 2009-11, Walter Bender, Tony Forster
# This procedure is invoked when the user-definable block on the
# "extras" palette is selected.
# Usage: Import this code into a Python (user-definable) block; when
# this code is run, the current mouse status will be pushed to the
# FILO heap. If a mouse button event occurs, a y, x, and 1 are pushed
# to the heap. If no button is pressed, 0 is pushed to the heap.
# To use these data, pop the heap in a compare block to determine if a
# button has been pushed. If a 1 was popped from the heap, pop the x
# and y coordinates.
def myblock(tw, x): # ignore second argument
''' Push mouse event to stack '''
if tw.mouse_flag == 1:
# push y first so x will be popped first
tw.lc.heap.append((tw.canvas.height / 2) - tw.mouse_y)
tw.lc.heap.append(tw.mouse_x - (tw.canvas.width / 2))
tw.lc.heap.append(1) # mouse event
tw.mouse_flag = 0
else:
tw.lc.heap.append(0) # no mouse event
|
#Constants
POSITION_MAP = {
# Remaining: F, IR, Util
0 : '0' # IR?
, 1 : 'Center'
, 2 : 'Left Wing'
, 3 : 'Right Wing'
, 4 : 'Defense'
, 5 : 'Goalie'
, 6 : '6' # Forward ?
, 7 : '7' # Goalie, F (Goalie Bench?)
, 8 : '8' # Goalie, F
, 'Center': 1
, 'Left Wing' : 2
, 'Right Wing' : 3
, 'Defense' : 4
, 'Goalie' : 5
}
STATS_IDENTIFIER = {
'00': 'Total',
'01': 'Last 7',
'02': 'Last 15',
'03': 'Last 30',
'10': 'Projected',
'20': '20'
}
PRO_TEAM_MAP = {
1: 'Boston Bruins'
, 2: 'Buffalo Sabres'
, 3: 'Calgary Flames'
, 4: 'Chicago Blackhawks'
, 5: 'Detroit Red Wings'
, 6: 'Edmonton Oilers'
, 7: 'Carolina Hurricanes'
, 8: 'Los Angeles Kings'
, 9: 'Dallas Stars'
, 10: 'Montréal Canadiens'
, 11: 'New Jersey Devils'
, 12: 'New York Islanders'
, 13: 'New York Rangers'
, 14: 'Ottawa Senators'
, 15: 'Philadelphia Flyers'
, 16: 'Pittsburgh Penguins'
, 17: 'Colorado Avalanche'
, 18: 'San Jose Sharks'
, 19: 'St. Louis Blues'
, 20: 'Tampa Bay Lightning'
, 21: 'Toronto Maple Leafs'
, 22: 'Vancouver Canucks'
, 23: 'Washington Capitals'
, 24: 'Arizona Coyotes'
, 25: 'Anaheim Ducks'
, 26: 'Florida Panthers'
, 27: 'Nashville Predators'
, 28: 'Winnipeg Jets'
, 29: 'Columbus Blue Jackets'
, 30: 'Minnesota Wild'
, 37: 'Vegas Golden Knights'
, 124292: 'Seattle Krakens'
}
STATS_MAP = {
'0': 'GS',
'1': 'W',
'2': 'L',
'3': 'SA',
'4': 'GA',
'5': '5',
'6': 'SV',
'7': 'SO',
'8': 'MIN ?',
'9': 'OTL',
'10': 'GAA',
'11': 'SV%',
'12': '12',
'13': 'G',
'14': 'A',
'15': '+/-',
'16': '16',
'17': 'PIM',
'18': 'PPG',
'19': '19',
'20': 'SHG',
'21': 'SHA',
'22': 'GWG',
'23': 'FOW',
'24': 'FOL',
'25': '25',
'26': 'TTOI ?',
'27': 'ATOI',
'28': 'HAT',
'29': 'SOG',
'30': '30',
'31': 'HIT',
'32': 'BLK',
'33': 'DEF',
'34': 'GP',
'35': '35',
'36': '36',
'37': '37',
'38': 'PPP',
'39': 'SHP',
'40': '40',
'41': '41',
'42': '42',
'43': '43',
'44': '44',
'45': '45',
'99': '99'
}
ACTIVITY_MAP = {
178: 'FA ADDED',
180: 'WAIVER ADDED',
179: 'DROPPED',
181: 'DROPPED',
239: 'DROPPED',
244: 'TRADED',
'FA': 178,
'WAIVER': 180,
'TRADED': 244
}
|
can_juggle = True
# The code below has problems. See if
# you can fix them!
#if can_juggle print("I can juggle!")
#else
print("I can't juggle.")
|
# decompiled-by-hand & optimized
# definitely not gonna refactor this one
# 0.18s on pypy3
ip_reg = 4
reg = [0, 0, 0, 0, 0, 0]
i = 0
seen = set()
lst = []
while True:
i += 1
break_true = False
while True:
if break_true:
if i == 1:
print("1)", reg[1])
if reg[1] in seen:
if len(lst) == 25000:
p2 = max(seen, key=lambda x: lst.index(x))
print("2)", p2)
exit()
seen.add(reg[1])
lst.append(reg[1])
break
reg[2] = reg[1] | 65536 # 6
reg[1] = 8725355 # 7
while True:
reg[5] = reg[2] & 255 # 8
reg[1] += reg[5] # 9
reg[1] &= 16777215 # 10
reg[1] *= 65899 # 11
reg[1] &= 16777215 # 12
reg[2] = reg[2] // 256
if reg[2] == 0:
break_true = True
break
break_true = False
|
"""Write a program that allow user enter a file name (path) then content, allow user to save it"""
filename = input("Please input filename")
f= open(filename,"w+")
content = input("Please input content")
f.write(content) |
class DxlNmapOptions:
"""
Constants that are used to execute Nmap tool
+-------------+---------+----------------------------------------------------------+
| Option | Command | Description |
+=============+=========+==========================================================+
| Aggressive | -A | Aggressive Scan |
| Scan | | |
+-------------+---------+----------------------------------------------------------+
| Operating | -O | Operating system in the current host |
| System | | |
+-------------+---------+----------------------------------------------------------+
| Aggressive | -O - A | Both options |
| Scan | | |
| + | | |
| Operating | | |
| System | | |
+-------------+---------+----------------------------------------------------------+
"""
AGGRESSIVE_SCAN = "-A"
OPERATING_SYSTEM = "-O"
AGGRESSIVE_SCAN_OP_SYSTEM = "-O -A"
|
# See
# The configuration file should be a valid Python source file with a python extension (e.g. gunicorn.conf.py).
# https://docs.gunicorn.org/en/stable/configure.html
bind='127.0.0.1:8962'
timeout=75
daemon=True
user='user'
accesslog='/var/local/log/user/blockchain_backup.gunicorn.access.log'
errorlog='/var/local/log/user/blockchain_backup.gunicorn.error.log'
log_level='debug'
capture_output=True
max_requests=3
workers=1
|
size = 5
m = (2 * size)-2
for i in range(0, size):
for j in range(0, m):
print(end=" ")
m = m - 1
for j in range(0, i + 1):
if(m%2!=0):
print("*", end=" ")
print("") |
__version__ = '2.0.0'
__description__ = 'Sample for calculations with data from the ctrlX Data Layer'
__author__ = 'Fantastic Python Developers'
__licence__ = 'MIT License'
__copyright__ = 'Copyright (c) 2021 Bosch Rexroth AG' |
__all__ = (
'readonly_admin',
'singleton'
)
|
def somar(x, y):
if x and y >= 0:
x = x + y
return(x)
def subtrair(x, y):
if x and y >= 0:
x = x - y
return(x)
def multiplicar(x, y):
if x and y >= 0:
x = x * y
return(x)
def dividirInteiro(x, y):
if x and y >= 0:
x = x / y
return(x)
def dividir(x, y):
if x and y >= 0:
x = x // y
return(x)
def porcentagem(x, y):
if x and y >= 0:
x = x * y
x = x / 100
return(x)
def exponencial(x, y):
if x and y >= 0:
x = x ** y
return(x)
def raizQuadrada(x):
if x >= 0:
x = x ** 0.5
return(x)
controller = 0
fim = 0
while controller != 2:
if controller == 1 or controller == 0:
e = int(input('Digite um número para escolher: \n'
' 1 para soma \n'
' 2 para subtração \n'
' 3 para multiplicação \n'
' 4 para divisão inteira \n'
' 5 para divisão real \n '
'6 para porcentagem \n'
' 7 para exponencial \n'
' 8 para raiz quadrada: '))
if e == 1:
if controller == 0:
h = int(input('Digite um valor: '))
t = int(input('Digite um valor para somar: '))
c = somar(h, t)
fim = c
print('Resultado: ', fim)
elif controller == 1:
t = int(input('Digite um valor para somar: '))
c = somar(fim, t)
fim = c
print('Resultado: ', fim)
elif e == 2:
if controller == 0:
h = int(input('Digite um valor: '))
t = int(input('Digite um valor para subtrair: '))
c = subtrair(h, t)
fim = c
print('Resultado: ', fim)
elif controller == 1:
t = int(input('Digite um valor para subtrair: '))
c = subtrair(fim, t)
fim = c
print('Resultado: ', fim)
elif e == 3:
if controller == 0:
h = int(input('Digite o primeiro valor: '))
t = int(input('Digite o segundo valor: '))
c = multiplicar(h, t)
fim = c
print('Resultado: ', fim)
elif controller == 1:
t = int(input('Digite um valor para multiplicar: '))
c = multiplicar(fim, t)
fim = c
print('Resultado: ', fim)
elif e == 4:
if controller == 0:
h = int(input('Digite o valor a ser dividido: '))
t = int(input('Digite o valor divisor: '))
c = dividirInteiro(h, t)
fim = c
print('Resultado: ', fim)
elif controller == 1:
t = int(input('Digite um valor para divisor: '))
c = dividirInteiro(fim, t)
fim = c
print('Resultado: ', fim)
elif e == 5:
if controller == 0:
h = int(input('Digite o valor a ser dividido: '))
t = int(input('Digite o valor divisor: '))
c = dividir(h, t)
fim = c
print('Resultado: ', fim)
elif controller == 1:
t = int(input('Digite um valor para divisor: '))
c = dividir(fim, t)
fim = c
print('Resultado: ', fim)
elif e == 6:
if controller == 0:
h = int(input('Digite o valor: '))
t = int(input('Digite a porcentagem: '))
c = porcentagem(h, t)
fim = c
print('Resultado final: ', fim,'%')
break;
elif controller == 1:
t = int(input('Digite o valor para descobrir porcentagem: '))
c = porcentagem(fim, t)
fim = c
print('Resultado final: ', fim,'%')
break;
elif e == 7:
if controller == 0:
h = int(input('Digite o valor: '))
t = int(input('Elevado a: '))
c = exponencial(h, t)
fim = c
print('Resultado: ', fim)
elif controller == 1:
t = int(input('Elevado a: '))
c = exponencial(fim, t)
fim = c
print('Resultado: ', fim)
elif e == 8:
if controller == 0:
t = int(input('Número para descobrir raiz quadrada: '))
c = raizQuadrada(t)
fim = c
print('Resultado: ', fim)
elif controller == 1:
c = raizQuadrada(fim)
fim = c
print('Resultado: ', fim)
controller = int(input('Deseja continuar? \n'
'Se sim digite 1, se não digite 2: '))
if controller == 2:
print('Valor Final: ',fim)
break;
|
integer = [
['lld', 'long long', 9223372036854775807, -9223372036854775808],
['ld', 'long', 9223372036854775807, -9223372036854775808],
['lu', 'unsigned long', 18446744073709551615, 0],
['d', 'signed', 2147483647, -2147483648],
['u', 'unsigned', 4294967295, 0],
['hd', 'short', 32767, -32768],
['hu', 'unsigned short', 65535, 0],
['c', 'char', 127, -128],
['c', 'unsigned char', 255, 0],
['d', '_Bool', 1, 0],
]
real = [
['f', 'float', 3.40282e+38, -3.40282e+38],
['f', 'double', 1.79769e+308, -1.79769e+308],
['Lf', 'long double', 1.79769e+308, -1.79769e+308]
]
# todo: fix path
path = ''
directory = 'env'
filename1 = f'{directory}/code1.c'
filename2 = f'{directory}/code2.c'
logfile1 = f'{directory}/log1.txt'
logfile2 = f'{directory}/log2.txt'
eo_out = f'{directory}/eo_out.txt'
c_out = f'{directory}/c_out.txt'
c_bin = f'{directory}/a.out'
launcher = '../../bin/launcher.py'
full_log = None
resultDir = '../../../result'
|
#!/usr/bin/env python
#
# Create filter taps to use for interpolation filter in
# clock recovery algorithm. These taps are copied from
# GNU Radio at gnuradio/filter/interpolator_taps.h.
#
# This file includes them in natural order and I want
# them stored in reversed order such that they can be
# used directly.
#
filters = [
[ 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 ],
[ -1.54700e-04, 8.53777e-04, -2.76968e-03, 7.89295e-03, 9.98534e-01, -5.41054e-03, 1.24642e-03, -1.98993e-04 ],
[ -3.09412e-04, 1.70888e-03, -5.55134e-03, 1.58840e-02, 9.96891e-01, -1.07209e-02, 2.47942e-03, -3.96391e-04 ],
[ -4.64053e-04, 2.56486e-03, -8.34364e-03, 2.39714e-02, 9.95074e-01, -1.59305e-02, 3.69852e-03, -5.92100e-04 ],
[ -6.18544e-04, 3.42130e-03, -1.11453e-02, 3.21531e-02, 9.93082e-01, -2.10389e-02, 4.90322e-03, -7.86031e-04 ],
[ -7.72802e-04, 4.27773e-03, -1.39548e-02, 4.04274e-02, 9.90917e-01, -2.60456e-02, 6.09305e-03, -9.78093e-04 ],
[ -9.26747e-04, 5.13372e-03, -1.67710e-02, 4.87921e-02, 9.88580e-01, -3.09503e-02, 7.26755e-03, -1.16820e-03 ],
[ -1.08030e-03, 5.98883e-03, -1.95925e-02, 5.72454e-02, 9.86071e-01, -3.57525e-02, 8.42626e-03, -1.35627e-03 ],
[ -1.23337e-03, 6.84261e-03, -2.24178e-02, 6.57852e-02, 9.83392e-01, -4.04519e-02, 9.56876e-03, -1.54221e-03 ],
[ -1.38589e-03, 7.69462e-03, -2.52457e-02, 7.44095e-02, 9.80543e-01, -4.50483e-02, 1.06946e-02, -1.72594e-03 ],
[ -1.53777e-03, 8.54441e-03, -2.80746e-02, 8.31162e-02, 9.77526e-01, -4.95412e-02, 1.18034e-02, -1.90738e-03 ],
[ -1.68894e-03, 9.39154e-03, -3.09033e-02, 9.19033e-02, 9.74342e-01, -5.39305e-02, 1.28947e-02, -2.08645e-03 ],
[ -1.83931e-03, 1.02356e-02, -3.37303e-02, 1.00769e-01, 9.70992e-01, -5.82159e-02, 1.39681e-02, -2.26307e-03 ],
[ -1.98880e-03, 1.10760e-02, -3.65541e-02, 1.09710e-01, 9.67477e-01, -6.23972e-02, 1.50233e-02, -2.43718e-03 ],
[ -2.13733e-03, 1.19125e-02, -3.93735e-02, 1.18725e-01, 9.63798e-01, -6.64743e-02, 1.60599e-02, -2.60868e-03 ],
[ -2.28483e-03, 1.27445e-02, -4.21869e-02, 1.27812e-01, 9.59958e-01, -7.04471e-02, 1.70776e-02, -2.77751e-03 ],
[ -2.43121e-03, 1.35716e-02, -4.49929e-02, 1.36968e-01, 9.55956e-01, -7.43154e-02, 1.80759e-02, -2.94361e-03 ],
[ -2.57640e-03, 1.43934e-02, -4.77900e-02, 1.46192e-01, 9.51795e-01, -7.80792e-02, 1.90545e-02, -3.10689e-03 ],
[ -2.72032e-03, 1.52095e-02, -5.05770e-02, 1.55480e-01, 9.47477e-01, -8.17385e-02, 2.00132e-02, -3.26730e-03 ],
[ -2.86289e-03, 1.60193e-02, -5.33522e-02, 1.64831e-01, 9.43001e-01, -8.52933e-02, 2.09516e-02, -3.42477e-03 ],
[ -3.00403e-03, 1.68225e-02, -5.61142e-02, 1.74242e-01, 9.38371e-01, -8.87435e-02, 2.18695e-02, -3.57923e-03 ],
[ -3.14367e-03, 1.76185e-02, -5.88617e-02, 1.83711e-01, 9.33586e-01, -9.20893e-02, 2.27664e-02, -3.73062e-03 ],
[ -3.28174e-03, 1.84071e-02, -6.15931e-02, 1.93236e-01, 9.28650e-01, -9.53307e-02, 2.36423e-02, -3.87888e-03 ],
[ -3.41815e-03, 1.91877e-02, -6.43069e-02, 2.02814e-01, 9.23564e-01, -9.84679e-02, 2.44967e-02, -4.02397e-03 ],
[ -3.55283e-03, 1.99599e-02, -6.70018e-02, 2.12443e-01, 9.18329e-01, -1.01501e-01, 2.53295e-02, -4.16581e-03 ],
[ -3.68570e-03, 2.07233e-02, -6.96762e-02, 2.22120e-01, 9.12947e-01, -1.04430e-01, 2.61404e-02, -4.30435e-03 ],
[ -3.81671e-03, 2.14774e-02, -7.23286e-02, 2.31843e-01, 9.07420e-01, -1.07256e-01, 2.69293e-02, -4.43955e-03 ],
[ -3.94576e-03, 2.22218e-02, -7.49577e-02, 2.41609e-01, 9.01749e-01, -1.09978e-01, 2.76957e-02, -4.57135e-03 ],
[ -4.07279e-03, 2.29562e-02, -7.75620e-02, 2.51417e-01, 8.95936e-01, -1.12597e-01, 2.84397e-02, -4.69970e-03 ],
[ -4.19774e-03, 2.36801e-02, -8.01399e-02, 2.61263e-01, 8.89984e-01, -1.15113e-01, 2.91609e-02, -4.82456e-03 ],
[ -4.32052e-03, 2.43930e-02, -8.26900e-02, 2.71144e-01, 8.83893e-01, -1.17526e-01, 2.98593e-02, -4.94589e-03 ],
[ -4.44107e-03, 2.50946e-02, -8.52109e-02, 2.81060e-01, 8.77666e-01, -1.19837e-01, 3.05345e-02, -5.06363e-03 ],
[ -4.55932e-03, 2.57844e-02, -8.77011e-02, 2.91006e-01, 8.71305e-01, -1.22047e-01, 3.11866e-02, -5.17776e-03 ],
[ -4.67520e-03, 2.64621e-02, -9.01591e-02, 3.00980e-01, 8.64812e-01, -1.24154e-01, 3.18153e-02, -5.28823e-03 ],
[ -4.78866e-03, 2.71272e-02, -9.25834e-02, 3.10980e-01, 8.58189e-01, -1.26161e-01, 3.24205e-02, -5.39500e-03 ],
[ -4.89961e-03, 2.77794e-02, -9.49727e-02, 3.21004e-01, 8.51437e-01, -1.28068e-01, 3.30021e-02, -5.49804e-03 ],
[ -5.00800e-03, 2.84182e-02, -9.73254e-02, 3.31048e-01, 8.44559e-01, -1.29874e-01, 3.35600e-02, -5.59731e-03 ],
[ -5.11376e-03, 2.90433e-02, -9.96402e-02, 3.41109e-01, 8.37557e-01, -1.31581e-01, 3.40940e-02, -5.69280e-03 ],
[ -5.21683e-03, 2.96543e-02, -1.01915e-01, 3.51186e-01, 8.30432e-01, -1.33189e-01, 3.46042e-02, -5.78446e-03 ],
[ -5.31716e-03, 3.02507e-02, -1.04150e-01, 3.61276e-01, 8.23188e-01, -1.34699e-01, 3.50903e-02, -5.87227e-03 ],
[ -5.41467e-03, 3.08323e-02, -1.06342e-01, 3.71376e-01, 8.15826e-01, -1.36111e-01, 3.55525e-02, -5.95620e-03 ],
[ -5.50931e-03, 3.13987e-02, -1.08490e-01, 3.81484e-01, 8.08348e-01, -1.37426e-01, 3.59905e-02, -6.03624e-03 ],
[ -5.60103e-03, 3.19495e-02, -1.10593e-01, 3.91596e-01, 8.00757e-01, -1.38644e-01, 3.64044e-02, -6.11236e-03 ],
[ -5.68976e-03, 3.24843e-02, -1.12650e-01, 4.01710e-01, 7.93055e-01, -1.39767e-01, 3.67941e-02, -6.18454e-03 ],
[ -5.77544e-03, 3.30027e-02, -1.14659e-01, 4.11823e-01, 7.85244e-01, -1.40794e-01, 3.71596e-02, -6.25277e-03 ],
[ -5.85804e-03, 3.35046e-02, -1.16618e-01, 4.21934e-01, 7.77327e-01, -1.41727e-01, 3.75010e-02, -6.31703e-03 ],
[ -5.93749e-03, 3.39894e-02, -1.18526e-01, 4.32038e-01, 7.69305e-01, -1.42566e-01, 3.78182e-02, -6.37730e-03 ],
[ -6.01374e-03, 3.44568e-02, -1.20382e-01, 4.42134e-01, 7.61181e-01, -1.43313e-01, 3.81111e-02, -6.43358e-03 ],
[ -6.08674e-03, 3.49066e-02, -1.22185e-01, 4.52218e-01, 7.52958e-01, -1.43968e-01, 3.83800e-02, -6.48585e-03 ],
[ -6.15644e-03, 3.53384e-02, -1.23933e-01, 4.62289e-01, 7.44637e-01, -1.44531e-01, 3.86247e-02, -6.53412e-03 ],
[ -6.22280e-03, 3.57519e-02, -1.25624e-01, 4.72342e-01, 7.36222e-01, -1.45004e-01, 3.88454e-02, -6.57836e-03 ],
[ -6.28577e-03, 3.61468e-02, -1.27258e-01, 4.82377e-01, 7.27714e-01, -1.45387e-01, 3.90420e-02, -6.61859e-03 ],
[ -6.34530e-03, 3.65227e-02, -1.28832e-01, 4.92389e-01, 7.19116e-01, -1.45682e-01, 3.92147e-02, -6.65479e-03 ],
[ -6.40135e-03, 3.68795e-02, -1.30347e-01, 5.02377e-01, 7.10431e-01, -1.45889e-01, 3.93636e-02, -6.68698e-03 ],
[ -6.45388e-03, 3.72167e-02, -1.31800e-01, 5.12337e-01, 7.01661e-01, -1.46009e-01, 3.94886e-02, -6.71514e-03 ],
[ -6.50285e-03, 3.75341e-02, -1.33190e-01, 5.22267e-01, 6.92808e-01, -1.46043e-01, 3.95900e-02, -6.73929e-03 ],
[ -6.54823e-03, 3.78315e-02, -1.34515e-01, 5.32164e-01, 6.83875e-01, -1.45993e-01, 3.96678e-02, -6.75943e-03 ],
[ -6.58996e-03, 3.81085e-02, -1.35775e-01, 5.42025e-01, 6.74865e-01, -1.45859e-01, 3.97222e-02, -6.77557e-03 ],
[ -6.62802e-03, 3.83650e-02, -1.36969e-01, 5.51849e-01, 6.65779e-01, -1.45641e-01, 3.97532e-02, -6.78771e-03 ],
[ -6.66238e-03, 3.86006e-02, -1.38094e-01, 5.61631e-01, 6.56621e-01, -1.45343e-01, 3.97610e-02, -6.79588e-03 ],
[ -6.69300e-03, 3.88151e-02, -1.39150e-01, 5.71370e-01, 6.47394e-01, -1.44963e-01, 3.97458e-02, -6.80007e-03 ],
[ -6.71985e-03, 3.90083e-02, -1.40136e-01, 5.81063e-01, 6.38099e-01, -1.44503e-01, 3.97077e-02, -6.80032e-03 ],
[ -6.74291e-03, 3.91800e-02, -1.41050e-01, 5.90706e-01, 6.28739e-01, -1.43965e-01, 3.96469e-02, -6.79662e-03 ],
[ -6.76214e-03, 3.93299e-02, -1.41891e-01, 6.00298e-01, 6.19318e-01, -1.43350e-01, 3.95635e-02, -6.78902e-03 ],
[ -6.77751e-03, 3.94578e-02, -1.42658e-01, 6.09836e-01, 6.09836e-01, -1.42658e-01, 3.94578e-02, -6.77751e-03 ],
[ -6.78902e-03, 3.95635e-02, -1.43350e-01, 6.19318e-01, 6.00298e-01, -1.41891e-01, 3.93299e-02, -6.76214e-03 ],
[ -6.79662e-03, 3.96469e-02, -1.43965e-01, 6.28739e-01, 5.90706e-01, -1.41050e-01, 3.91800e-02, -6.74291e-03 ],
[ -6.80032e-03, 3.97077e-02, -1.44503e-01, 6.38099e-01, 5.81063e-01, -1.40136e-01, 3.90083e-02, -6.71985e-03 ],
[ -6.80007e-03, 3.97458e-02, -1.44963e-01, 6.47394e-01, 5.71370e-01, -1.39150e-01, 3.88151e-02, -6.69300e-03 ],
[ -6.79588e-03, 3.97610e-02, -1.45343e-01, 6.56621e-01, 5.61631e-01, -1.38094e-01, 3.86006e-02, -6.66238e-03 ],
[ -6.78771e-03, 3.97532e-02, -1.45641e-01, 6.65779e-01, 5.51849e-01, -1.36969e-01, 3.83650e-02, -6.62802e-03 ],
[ -6.77557e-03, 3.97222e-02, -1.45859e-01, 6.74865e-01, 5.42025e-01, -1.35775e-01, 3.81085e-02, -6.58996e-03 ],
[ -6.75943e-03, 3.96678e-02, -1.45993e-01, 6.83875e-01, 5.32164e-01, -1.34515e-01, 3.78315e-02, -6.54823e-03 ],
[ -6.73929e-03, 3.95900e-02, -1.46043e-01, 6.92808e-01, 5.22267e-01, -1.33190e-01, 3.75341e-02, -6.50285e-03 ],
[ -6.71514e-03, 3.94886e-02, -1.46009e-01, 7.01661e-01, 5.12337e-01, -1.31800e-01, 3.72167e-02, -6.45388e-03 ],
[ -6.68698e-03, 3.93636e-02, -1.45889e-01, 7.10431e-01, 5.02377e-01, -1.30347e-01, 3.68795e-02, -6.40135e-03 ],
[ -6.65479e-03, 3.92147e-02, -1.45682e-01, 7.19116e-01, 4.92389e-01, -1.28832e-01, 3.65227e-02, -6.34530e-03 ],
[ -6.61859e-03, 3.90420e-02, -1.45387e-01, 7.27714e-01, 4.82377e-01, -1.27258e-01, 3.61468e-02, -6.28577e-03 ],
[ -6.57836e-03, 3.88454e-02, -1.45004e-01, 7.36222e-01, 4.72342e-01, -1.25624e-01, 3.57519e-02, -6.22280e-03 ],
[ -6.53412e-03, 3.86247e-02, -1.44531e-01, 7.44637e-01, 4.62289e-01, -1.23933e-01, 3.53384e-02, -6.15644e-03 ],
[ -6.48585e-03, 3.83800e-02, -1.43968e-01, 7.52958e-01, 4.52218e-01, -1.22185e-01, 3.49066e-02, -6.08674e-03 ],
[ -6.43358e-03, 3.81111e-02, -1.43313e-01, 7.61181e-01, 4.42134e-01, -1.20382e-01, 3.44568e-02, -6.01374e-03 ],
[ -6.37730e-03, 3.78182e-02, -1.42566e-01, 7.69305e-01, 4.32038e-01, -1.18526e-01, 3.39894e-02, -5.93749e-03 ],
[ -6.31703e-03, 3.75010e-02, -1.41727e-01, 7.77327e-01, 4.21934e-01, -1.16618e-01, 3.35046e-02, -5.85804e-03 ],
[ -6.25277e-03, 3.71596e-02, -1.40794e-01, 7.85244e-01, 4.11823e-01, -1.14659e-01, 3.30027e-02, -5.77544e-03 ],
[ -6.18454e-03, 3.67941e-02, -1.39767e-01, 7.93055e-01, 4.01710e-01, -1.12650e-01, 3.24843e-02, -5.68976e-03 ],
[ -6.11236e-03, 3.64044e-02, -1.38644e-01, 8.00757e-01, 3.91596e-01, -1.10593e-01, 3.19495e-02, -5.60103e-03 ],
[ -6.03624e-03, 3.59905e-02, -1.37426e-01, 8.08348e-01, 3.81484e-01, -1.08490e-01, 3.13987e-02, -5.50931e-03 ],
[ -5.95620e-03, 3.55525e-02, -1.36111e-01, 8.15826e-01, 3.71376e-01, -1.06342e-01, 3.08323e-02, -5.41467e-03 ],
[ -5.87227e-03, 3.50903e-02, -1.34699e-01, 8.23188e-01, 3.61276e-01, -1.04150e-01, 3.02507e-02, -5.31716e-03 ],
[ -5.78446e-03, 3.46042e-02, -1.33189e-01, 8.30432e-01, 3.51186e-01, -1.01915e-01, 2.96543e-02, -5.21683e-03 ],
[ -5.69280e-03, 3.40940e-02, -1.31581e-01, 8.37557e-01, 3.41109e-01, -9.96402e-02, 2.90433e-02, -5.11376e-03 ],
[ -5.59731e-03, 3.35600e-02, -1.29874e-01, 8.44559e-01, 3.31048e-01, -9.73254e-02, 2.84182e-02, -5.00800e-03 ],
[ -5.49804e-03, 3.30021e-02, -1.28068e-01, 8.51437e-01, 3.21004e-01, -9.49727e-02, 2.77794e-02, -4.89961e-03 ],
[ -5.39500e-03, 3.24205e-02, -1.26161e-01, 8.58189e-01, 3.10980e-01, -9.25834e-02, 2.71272e-02, -4.78866e-03 ],
[ -5.28823e-03, 3.18153e-02, -1.24154e-01, 8.64812e-01, 3.00980e-01, -9.01591e-02, 2.64621e-02, -4.67520e-03 ],
[ -5.17776e-03, 3.11866e-02, -1.22047e-01, 8.71305e-01, 2.91006e-01, -8.77011e-02, 2.57844e-02, -4.55932e-03 ],
[ -5.06363e-03, 3.05345e-02, -1.19837e-01, 8.77666e-01, 2.81060e-01, -8.52109e-02, 2.50946e-02, -4.44107e-03 ],
[ -4.94589e-03, 2.98593e-02, -1.17526e-01, 8.83893e-01, 2.71144e-01, -8.26900e-02, 2.43930e-02, -4.32052e-03 ],
[ -4.82456e-03, 2.91609e-02, -1.15113e-01, 8.89984e-01, 2.61263e-01, -8.01399e-02, 2.36801e-02, -4.19774e-03 ],
[ -4.69970e-03, 2.84397e-02, -1.12597e-01, 8.95936e-01, 2.51417e-01, -7.75620e-02, 2.29562e-02, -4.07279e-03 ],
[ -4.57135e-03, 2.76957e-02, -1.09978e-01, 9.01749e-01, 2.41609e-01, -7.49577e-02, 2.22218e-02, -3.94576e-03 ],
[ -4.43955e-03, 2.69293e-02, -1.07256e-01, 9.07420e-01, 2.31843e-01, -7.23286e-02, 2.14774e-02, -3.81671e-03 ],
[ -4.30435e-03, 2.61404e-02, -1.04430e-01, 9.12947e-01, 2.22120e-01, -6.96762e-02, 2.07233e-02, -3.68570e-03 ],
[ -4.16581e-03, 2.53295e-02, -1.01501e-01, 9.18329e-01, 2.12443e-01, -6.70018e-02, 1.99599e-02, -3.55283e-03 ],
[ -4.02397e-03, 2.44967e-02, -9.84679e-02, 9.23564e-01, 2.02814e-01, -6.43069e-02, 1.91877e-02, -3.41815e-03 ],
[ -3.87888e-03, 2.36423e-02, -9.53307e-02, 9.28650e-01, 1.93236e-01, -6.15931e-02, 1.84071e-02, -3.28174e-03 ],
[ -3.73062e-03, 2.27664e-02, -9.20893e-02, 9.33586e-01, 1.83711e-01, -5.88617e-02, 1.76185e-02, -3.14367e-03 ],
[ -3.57923e-03, 2.18695e-02, -8.87435e-02, 9.38371e-01, 1.74242e-01, -5.61142e-02, 1.68225e-02, -3.00403e-03 ],
[ -3.42477e-03, 2.09516e-02, -8.52933e-02, 9.43001e-01, 1.64831e-01, -5.33522e-02, 1.60193e-02, -2.86289e-03 ],
[ -3.26730e-03, 2.00132e-02, -8.17385e-02, 9.47477e-01, 1.55480e-01, -5.05770e-02, 1.52095e-02, -2.72032e-03 ],
[ -3.10689e-03, 1.90545e-02, -7.80792e-02, 9.51795e-01, 1.46192e-01, -4.77900e-02, 1.43934e-02, -2.57640e-03 ],
[ -2.94361e-03, 1.80759e-02, -7.43154e-02, 9.55956e-01, 1.36968e-01, -4.49929e-02, 1.35716e-02, -2.43121e-03 ],
[ -2.77751e-03, 1.70776e-02, -7.04471e-02, 9.59958e-01, 1.27812e-01, -4.21869e-02, 1.27445e-02, -2.28483e-03 ],
[ -2.60868e-03, 1.60599e-02, -6.64743e-02, 9.63798e-01, 1.18725e-01, -3.93735e-02, 1.19125e-02, -2.13733e-03 ],
[ -2.43718e-03, 1.50233e-02, -6.23972e-02, 9.67477e-01, 1.09710e-01, -3.65541e-02, 1.10760e-02, -1.98880e-03 ],
[ -2.26307e-03, 1.39681e-02, -5.82159e-02, 9.70992e-01, 1.00769e-01, -3.37303e-02, 1.02356e-02, -1.83931e-03 ],
[ -2.08645e-03, 1.28947e-02, -5.39305e-02, 9.74342e-01, 9.19033e-02, -3.09033e-02, 9.39154e-03, -1.68894e-03 ],
[ -1.90738e-03, 1.18034e-02, -4.95412e-02, 9.77526e-01, 8.31162e-02, -2.80746e-02, 8.54441e-03, -1.53777e-03 ],
[ -1.72594e-03, 1.06946e-02, -4.50483e-02, 9.80543e-01, 7.44095e-02, -2.52457e-02, 7.69462e-03, -1.38589e-03 ],
[ -1.54221e-03, 9.56876e-03, -4.04519e-02, 9.83392e-01, 6.57852e-02, -2.24178e-02, 6.84261e-03, -1.23337e-03 ],
[ -1.35627e-03, 8.42626e-03, -3.57525e-02, 9.86071e-01, 5.72454e-02, -1.95925e-02, 5.98883e-03, -1.08030e-03 ],
[ -1.16820e-03, 7.26755e-03, -3.09503e-02, 9.88580e-01, 4.87921e-02, -1.67710e-02, 5.13372e-03, -9.26747e-04 ],
[ -9.78093e-04, 6.09305e-03, -2.60456e-02, 9.90917e-01, 4.04274e-02, -1.39548e-02, 4.27773e-03, -7.72802e-04 ],
[ -7.86031e-04, 4.90322e-03, -2.10389e-02, 9.93082e-01, 3.21531e-02, -1.11453e-02, 3.42130e-03, -6.18544e-04 ],
[ -5.92100e-04, 3.69852e-03, -1.59305e-02, 9.95074e-01, 2.39714e-02, -8.34364e-03, 2.56486e-03, -4.64053e-04 ],
[ -3.96391e-04, 2.47942e-03, -1.07209e-02, 9.96891e-01, 1.58840e-02, -5.55134e-03, 1.70888e-03, -3.09412e-04 ],
[ -1.98993e-04, 1.24642e-03, -5.41054e-03, 9.98534e-01, 7.89295e-03, -2.76968e-03, 8.53777e-04, -1.54700e-04 ],
[ 0.00000e+00, 0.00000e+00, 0.00000e+00, 1.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00, 0.00000e+00 ]
]
print("static const int NUM_TAPS = 8;")
print("static const int NUM_STEPS = 128;")
print("static const mmseTaps[NUM_STEPS+1][NUM_TAPS] = {")
for taps in filters:
body = ", ".join("%.5e" % t for t in reversed(taps))
print("{ " + body + " },")
print("};")
|
class Node:
def __init__(self, val: int):
self.val = val
self.prev = None
self.next = None
class DoublyLinkedList:
def takeinput(self) -> Node:
inputlist = [int(x) for x in input().split()]
head = None
temp = None
for curr in inputlist:
if curr == -1:
break
Newnode = Node(curr)
if head is None:
head = Newnode
temp = head
else:
temp.next = Newnode
Newnode.prev = temp
temp = temp.next
return head
def printLL(self, head: Node) -> None:
temp = head
while temp is not None:
print(temp.val, end='->')
temp = temp.next
print("None")
def getLength(self, head: Node) -> int:
count = 0
temp = head
while temp is not None:
count += 1
temp = temp.next
return temp
def getMiddle(self, head: Node) -> int:
slow = head
fast = head
while fast and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow.val
def reverseLL(self, head: Node) -> Node:
pass |
class Combo():
def combine(self,n, k):
A = list(range(1,n + 1))
res = self.comb(A, k)
return res
def comb(self, A, n):
if n == 0:
return [[]]
l = []
for i in range(0, len(A)):
m = A[i]
remLst = A[i + 1:]
for p in self.comb(remLst, n - 1):
l.append([m] + p)
return l
def combinations(n, list, combos=[]):
# initialize combos during the first pass through
if combos is None:
combos = []
if len(list) == n:
# when list has been dwindeled down to size n
# check to see if the combo has already been found
# if not, add it to our list
if combos.count(list) == 0:
combos.append(list)
combos.sort()
return combos
else:
# for each item in our list, make a recursive
# call to find all possible combos of it and
# the remaining items
for i in range(len(list)):
refined_list = list[:i] + list[i+1:]
combos = combinations(n, refined_list, combos)
return combos
a = Combo()
A = 4
B = 2
# print(a.combine(A,B))
print(a.comb([1,2,3,4], 2))
print(a.comb([1,2,3,4,5], 2))
|
f = open('./day4.py')
for chunk in iter(lambda :f.read(10),''):
print(chunk)
|
class WebsiteBaseError(Exception):
pass
class TreeTraversal(WebsiteBaseError):
def __init__(self, tree, request, segment, req=None):
super().__init__()
self.tree, self.request, self.segment, self.req = tree, request, segment, req
def __str__(self) -> str:
return f"{self.tree} > {self.request}[{self.segment}] {'' if self.req is None else self.req}"
class BufferRead(WebsiteBaseError):
def __init__(self, buffer):
super().__init__()
self.buffer = buffer
def __str__(self) -> str:
return f"{self.buffer}"
|
linelist = [line for line in open('Day 02.input').readlines()]
hor = 0
dep = 0
for line in linelist:
mov, amount = line.split(' ')
if mov == 'forward':
hor += int(amount)
else:
dep += int(amount) * (-1 if mov == 'up' else 1)
print(hor * dep)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple color picker program."""
BANNER = """ .::::::::::::::::::::::::::::::::::::::::::::::::.
.. .... ..
.. ...... ... ..
|S .F.Cards.. F.G ia
nt sS.F.Gi||BASE BAL LB
AS EBALLBASEBA||S .F. Gi
an tsS.F.Giants S. F.
Gi ||BASEBALLBA SE BA
LL BASEBA||N.Y.Yankees.F .Gia nt
sS .F.Gi||BASEBALLBASEBALLBASEB A|
|S .F.MetsS.F.GiantsS.F.Gi||BASE BA
LL BA SEBALLBASEBA||S.T.L.Cards.Reds S.
F. Gi||B ASEBALLBASEBALLBASEBA||S.F.GiantsS.F .G
ia nt sS.F.Gi||BASEBALLBASEBALLBASEBA||S.F .G
ia ntsT.B.Rayss.F.Gi||BASEBALL BA
S EBALLBASEBA|'`''''''''''' S
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
____ ____ ____ _ ____ ____ ____
| __ )| __ ) / ___| / \ | _ \| _ \/ ___|
| _ \| _ \ _____| | / _ \ | |_) | | | \___ \
| |_) | |_) |_____| |___ / ___ \| _ <| |_| |___) |
|____/|____/ \____/_/ \_|_| \_|____/|____/
"""
|
def convert_sample_to_shot_wow(sample, with_knowledge=True):
prefix = "Dialogue:\n"
assert len(sample["dialogue"]) == len(sample["meta"])
for turn, meta in zip(sample["dialogue"],sample["meta"]):
prefix += f"User: {turn[0]}" +"\n"
if with_knowledge:
if len(meta)>0:
prefix += f"KB: {meta[0]}" +"\n"
else:
prefix += f"KB: None" +"\n"
if turn[1] == "":
prefix += f"Assistant:"
return prefix
else:
prefix += f"Assistant: {turn[1]}" +"\n"
return prefix
def convert_sample_to_shot_wow_interact(sample, with_knowledge=True):
prefix = "Dialogue:\n"
assert len(sample["dialogue"]) == len(sample["KB_wiki"])
for turn, meta in zip(sample["dialogue"],sample["KB_wiki"]):
prefix += f"User: {turn[0]}" +"\n"
if with_knowledge:
if len(meta)>0:
prefix += f"KB: {meta[0]}" +"\n"
else:
prefix += f"KB: None" +"\n"
if turn[1] == "":
prefix += f"Assistant:"
return prefix
else:
prefix += f"Assistant: {turn[1]}" +"\n"
return prefix
|
# Test cases that are expected to fail, e.g. unimplemented features or bug-fixes.
# Remove from list when fixed.
xfail = {
"namespace_keywords", # 70
"googletypes_struct", # 9
"googletypes_value", # 9
"import_capitalized_package",
"example", # This is the example in the readme. Not a test.
}
services = {
"googletypes_response",
"googletypes_response_embedded",
"service",
"service_separate_packages",
"import_service_input_message",
"googletypes_service_returns_empty",
"googletypes_service_returns_googletype",
"example_service",
"empty_service",
}
# Indicate json sample messages to skip when testing that json (de)serialization
# is symmetrical becuase some cases legitimately are not symmetrical.
# Each key references the name of the test scenario and the values in the tuple
# Are the names of the json files.
non_symmetrical_json = {"empty_repeated": ("empty_repeated",)}
|
class Settings:
BOT_KEY = ""
HOST_NAME = "127.0.0.1"
USER_NAME = "root"
USER_PASS = "Andrey171200"
SQL_NAME = "moneysaver"
|
{
"targets": [
{
"target_name": "binding",
"sources": [
"native\\winhttpBindings.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"libraries": [
"WinHTTP.lib",
"-DelayLoad:node.exe"
],
"msbuild_settings": {
"ClCompile": {
"RuntimeLibrary": "MultiThreaded"
}
}
}
]
}
|
def open_file():
while True:
file_name = input("Enter input file: ")
try:
measles = open(file_name, "r")
break
except:
print("File unable to open. Invalid name or file doesn't exist!")
continue # name it re-prompts for a write name
return measles
def process_file(measles):
while True:
year = input("Enter year: ")
if len(year) == 4: # this ensures that the year has four characters
break
else:
print("Invalid year. Year MUST be four digits")
continue
while True: # this loop assigns the income level
print("Income levels;\n Input 1 for WB_LI\n Input 2 for WB_LMI\n Input 3 for WB_UMI\n Input 4 for WB_HI")
income = input("Enter income level(1,2,3,4): ")
if income == "1":
income = "WB_LI"
break
elif income == "2":
income = "WB_LMI"
break
elif income == "3":
income = "WB_UMI"
break
elif income == "4":
income = "WB_HI"
break
else:
print("Invalid income level!") # an invalid input re-prompts till the right one is made
continue
count = 0
percentages = []
countries = []
for line in measles:
if (line[88:92] == year) and (line[51:56] == income or line[51:57] == income): # Ensures the criteria is met
count += 1
percentages.append(int(line[59:61])) # adds percentages to the list percentages
country = line[0:51]
country = str(country)
country = country.strip()
countries.append(country) # adds percentages to the list of countries
continue
country_percentage = dict(zip(countries, percentages)) # Creates a dictionary with country as the key and percentage as values
if count > 0:
percent_sum = sum(percentages)
percent_avg = percent_sum / count # average of percentages
max_percentage = max(percentages)
min_percentage = min(percentages)
# gets countries for maximum percentages to this list
max_country = [country for country, percentage in country_percentage.items() if percentage == max_percentage]
# gets countries for minimum percentages to this list
min_country = [country for country, percentage in country_percentage.items() if percentage == min_percentage]
print(f"Nunber of countries in the record: {count}")
print(f"Average percentage for {year} with {income} is {percent_avg:.1f}%")
print(f"Country(ies) have maximum percentage in {year} with {income} of {max_percentage}%")
for i in max_country: # print contries with maximum percentages
print(" >", i)
print(f"Country(ies) have minimum percentage in {year} with {income} of {min_percentage}%")
for i in min_country: # print contries with minimum percentages
print(" >", i)
else: # if there is no item in the list, it prints this
print(f"The year {year} does not exist in the record...")
def main():
measles = open_file()
process_file(measles)
measles.close()
main()
|
def get_obj1():
obj = \
{
"sha": "d25341478381063d1c76e81b3a52e0592a7c997f",
"commit": {
"author": {
"name": "Stephen Dolan",
"email": "mu@netsoc.tcd.ie",
"date": "2013-06-22T16:30:59Z"
},
"committer": {
"name": "Stephen Dolan",
"email": "mu@netsoc.tcd.ie",
"date": "2013-06-22T16:30:59Z"
},
"message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",
"tree": {
"sha": "6ab697a8dfb5a96e124666bf6d6213822599fb40",
"url": "https://api.github.com/repos/stedolan/jq/git/trees/6ab697a8dfb5a96e124666bf6d6213822599fb40"
},
"url": "https://api.github.com/repos/stedolan/jq/git/commits/d25341478381063d1c76e81b3a52e0592a7c997f",
"comment_count": 0
},
"url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f",
"html_url": "https://github.com/stedolan/jq/commit/d25341478381063d1c76e81b3a52e0592a7c997f",
"comments_url": "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f/comments",
"author": {
"login": "stedolan",
"id": 79765,
"avatar_url": "https://avatars.githubusercontent.com/u/79765?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/stedolan",
"html_url": "https://github.com/stedolan",
"followers_url": "https://api.github.com/users/stedolan/followers",
"following_url": "https://api.github.com/users/stedolan/following{/other_user}",
"gists_url": "https://api.github.com/users/stedolan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/stedolan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/stedolan/subscriptions",
"organizations_url": "https://api.github.com/users/stedolan/orgs",
"repos_url": "https://api.github.com/users/stedolan/repos",
"events_url": "https://api.github.com/users/stedolan/events{/privacy}",
"received_events_url": "https://api.github.com/users/stedolan/received_events",
"type": "User",
"site_admin": False
},
"committer": {
"login": "stedolan",
"id": 79765,
"avatar_url": "https://avatars.githubusercontent.com/u/79765?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/stedolan",
"html_url": "https://github.com/stedolan",
"followers_url": "https://api.github.com/users/stedolan/followers",
"following_url": "https://api.github.com/users/stedolan/following{/other_user}",
"gists_url": "https://api.github.com/users/stedolan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/stedolan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/stedolan/subscriptions",
"organizations_url": "https://api.github.com/users/stedolan/orgs",
"repos_url": "https://api.github.com/users/stedolan/repos",
"events_url": "https://api.github.com/users/stedolan/events{/privacy}",
"received_events_url": "https://api.github.com/users/stedolan/received_events",
"type": "User",
"site_admin": False
},
"parents": [
{
"sha": "54b9c9bdb225af5d886466d72f47eafc51acb4f7",
"url": "https://api.github.com/repos/stedolan/jq/commits/54b9c9bdb225af5d886466d72f47eafc51acb4f7",
"html_url": "https://github.com/stedolan/jq/commit/54b9c9bdb225af5d886466d72f47eafc51acb4f7"
},
{
"sha": "8b1b503609c161fea4b003a7179b3fbb2dd4345a",
"url": "https://api.github.com/repos/stedolan/jq/commits/8b1b503609c161fea4b003a7179b3fbb2dd4345a",
"html_url": "https://github.com/stedolan/jq/commit/8b1b503609c161fea4b003a7179b3fbb2dd4345a"
}
]
}
return obj |
description = 'system setup'
group = 'lowlevel'
sysconfig = dict(
cache = 'localhost',
instrument = 'ErWIN',
experiment = 'Exp',
datasinks = ['conssink', 'dmnsink'],
notifiers = [],
)
modules = ['nicos.commands.standard']
devices = dict(
ErWIN = device('nicos.devices.instrument.Instrument',
description = 'ErWIN instrument',
instrument = 'ErWIN',
responsible = 'Michael Heere <michael.heere@kit.edu>',
website = 'https://mlz-garching.de/erwin',
operators = [
'Karlsruhe Institute of Technology (KIT)',
],
),
Sample = device('nicos.devices.sample.Sample',
description = 'sample object',
),
Exp = device('nicos_mlz.devices.experiment.Experiment',
description = 'experiment object',
dataroot = 'data',
sample = 'Sample',
reporttemplate = '',
sendmail = False,
serviceexp = 'p0',
mailsender = 'erwin@frm2.tum.de',
mailserver = 'mailhost.frm2.tum.de',
elog = True,
managerights = dict(
enableDirMode = 0o775,
enableFileMode = 0o644,
disableDirMode = 0o550,
disableFileMode = 0o440,
owner = 'erwin',
group = 'erwin'
),
),
filesink = device('nicos.devices.datasinks.AsciiScanfileSink'),
conssink = device('nicos.devices.datasinks.ConsoleScanSink'),
dmnsink = device('nicos.devices.datasinks.DaemonSink'),
Space = device('nicos.devices.generic.FreeSpace',
description = 'The amount of free space for storing data',
warnlimits = (5., None),
path = None,
minfree = 5,
),
LogSpace = device('nicos.devices.generic.FreeSpace',
description = 'Space on log drive',
path = 'log',
warnlimits = (.5, None),
minfree = 0.5,
lowlevel = True,
),
)
|
valor = input("Digite algo: ")
print("É do tipo", type(valor))
print("Valor numérico:", valor.isnumeric())
print("Valor Alfa:", valor.isalpha())
print("Valor Alfanumérico:", valor.isalnum())
print("Valor ASCII:", valor.isascii())
print("Valor Decimal", valor.isdecimal())
print("Valor Printavel", valor.isprintable()) |
# -*- coding: utf-8 -*-
"""
1265. Print Immutable Linked List in Reverse
You are given an immutable linked list, print out all values of each node in reverse with the help of the following
interface:
ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
You need to use the following functions to access the linked list (you can't access the ImmutableListNode directly):
ImmutableListNode.printValue(): Print value of the current node.
ImmutableListNode.getNext(): Return the next node.
The input is only given to initialize the linked list internally.
You must solve this problem without modifying the linked list.
In other words, you must operate the linked list using only the mentioned APIs.
Constraints:
The length of the linked list is between [1, 1000].
The value of each node in the linked list is between [-1000, 1000].
Follow up:
Could you solve this problem in:
Constant space complexity?
Linear time complexity and less than linear space complexity?
"""
"""
This is the ImmutableListNode's API interface.
You should not implement it, or speculate about its implementation.
"""
class ImmutableListNode:
def printValue(self) -> None: # print the value of this node.
pass
def getNext(self) -> 'ImmutableListNode': # return the next node.
pass
class Solution:
def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None:
if head is None:
return
self.printLinkedListInReverse(head.getNext())
head.printValue()
|
num1 = input()
num2 = input()
num3 = input()
print(int(num1) + int(num2) + int(num3))
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
linked_list = ''
while temp:
linked_list += str(temp.data) + " -> "
temp = temp.next
print(linked_list)
# lists start at 0
def insert_node(self, val, pos):
target = Node(val)
# specific case for replacing head
if pos == 0:
target.next = self.head
self.head = target
return
def get_prev(position):
temp = self.head
count = 1
while count < position:
temp = temp.next
count += 1
return temp
# Getting previous node
prev = get_prev(pos)
if prev.next:
# Temp variable for upcoming node
next_node = prev.next
# Set previous next to our target node
prev.next = target
# Set next node of target node from temp variable
target.next = next_node
def delete_node(self, key):
temp = self.head
if temp is None:
return
if temp.data == key:
self.head = temp.next
temp = None
return
while temp.next.data != key:
temp = temp.next
# Getting target node
target_node = temp.next
# Set previous node's next to target's next
temp.next = target_node.next
# Remove target node's pointer
target_node.next = None
# Nodes: 4 -> 5 -> 7 -> 2
link = LinkedList()
link.head = Node(4)
first_node = Node(5)
second_node = Node(7)
third_node = Node(2)
link.head.next = first_node
first_node.next = second_node
second_node.next = third_node
link.print_list()
# Nodes: 4 -> 5 -> 7 -> 2
# Insert 3 at index 2
# Nodes: 4 -> 5 -> 3 -> 7 -> 2
link.insert_node(3, 2)
link.print_list()
# Nodes: 4 -> 5 -> 3 -> 7 -> 2
# Delete 3
# Nodes: 4 -> 5 -> 7 -> 2
link.delete_node(3)
link.print_list()
|
def bubblesort(L):
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L)-1):
if L[i]>L[i+1]:
L[i], L[i+1] = L[i+1], L[i]
keepgoing = True
|
# Hydro settings
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en-us'
APPLICATION_NAME = 'HYDRO'
SECRET_KEY = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&022shmi1jcgihb*'
# SESSION_TIMEOUT is used in validate_session_active decorator to see if the
# session is active.
SECOND = 1
MINUTE = SECOND * 60
SECONDS_IN_DAY = SECOND*86400
MYSQL_CACHE_DB = 'cache'
MYSQL_STATS_DB = 'stats'
MYSQL_CACHE_TABLE = 'hydro_cache_table'
CACHE_IN_MEMORY_KEY_EXPIRE = 600
CACHE_DB_KEY_EXPIRE = 86400
USE_STATS_DB = False
DATABASES = {
'stats': {
'ENGINE': 'django.db.backends.mysql',
'NAME': MYSQL_STATS_DB,
'USER': 'root',
'PASSWORD': 'xxxx',
'HOST': '127.0.0.1',
'OPTIONS': {
"init_command": "SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;",
"compress": True
},
},
'cache': {
'ENGINE': 'django.db.backends.mysql',
'NAME': MYSQL_CACHE_DB,
'USER': 'root',
'PASSWORD': 'xxxx',
'HOST': '127.0.0.1',
'OPTIONS': {
"init_command": "SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;",
"compress": True
},
},
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cache',
'USER': 'root',
'PASSWORD': 'xxxx',
'HOST': '127.0.0.1',
'OPTIONS': {
"init_command": "SET storage_engine=INNODB; SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;",
"compress": True
}
},
}
|
def load_external_repo():
native.local_repository(
name = "ext_repo",
path = "test/external_repo/repo",
)
|
'''
Created on May 26, 2012
@author: Charlie
'''
class MainModule01(object):
def __init__(self):
pass |
#
# PySNMP MIB module GENERIC-3COM-VLAN-MIB-1-0-7 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENERIC-3COM-VLAN-MIB-1-0-7
# Produced by pysmi-0.3.4 at Wed May 1 11:09:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
NotificationType, Counter32, Integer32, ObjectIdentity, Counter64, IpAddress, MibIdentifier, iso, ModuleIdentity, Unsigned32, Gauge32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Counter32", "Integer32", "ObjectIdentity", "Counter64", "IpAddress", "MibIdentifier", "iso", "ModuleIdentity", "Unsigned32", "Gauge32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "enterprises")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
class RowStatus(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))
namedValues = NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6))
a3Com = MibIdentifier((1, 3, 6, 1, 4, 1, 43))
generic = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10))
genExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1))
genVirtual = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14))
a3ComVlanGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1))
a3ComVlanProtocolsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2))
a3ComVirtualGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 3))
a3ComEncapsulationGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4))
class A3ComVlanType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
namedValues = NamedValues(("vlanLayer2", 1), ("vlanUnspecifiedProtocols", 2), ("vlanIPProtocol", 3), ("vlanIPXProtocol", 4), ("vlanAppleTalkProtocol", 5), ("vlanXNSProtocol", 6), ("vlanISOProtocol", 7), ("vlanDECNetProtocol", 8), ("vlanNetBIOSProtocol", 9), ("vlanSNAProtocol", 10), ("vlanVINESProtocol", 11), ("vlanX25Protocol", 12), ("vlanIGMPProtocol", 13), ("vlanSessionLayer", 14), ("vlanNetBeui", 15), ("vlanLayeredProtocols", 16), ("vlanIPXIIProtocol", 17), ("vlanIPX8022Protocol", 18), ("vlanIPX8023Protocol", 19), ("vlanIPX8022SNAPProtocol", 20))
class A3ComVlanLayer3Type(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
namedValues = NamedValues(("vlanIPProtocol", 1), ("vlanIPXProtocol", 2), ("vlanAppleTalkProtocol", 3), ("vlanXNSProtocol", 4), ("vlanSNAProtocol", 5), ("vlanDECNetProtocol", 6), ("vlanNetBIOSProtocol", 7), ("vlanVINESProtocol", 8), ("vlanX25Protocol", 9), ("vlanIPXIIProtocol", 10), ("vlanIPX8022Protocol", 11), ("vlanIPX8023Protocol", 12), ("vlanIPX8022SNAPProtocol", 13))
class A3ComVlanModeType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("vlanUseDefault", 1), ("vlanOpen", 2), ("vlanClosed", 3))
a3ComVlanGlobalMappingTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1), )
if mibBuilder.loadTexts: a3ComVlanGlobalMappingTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanGlobalMappingTable.setDescription('This table lists VLAN interfaces that are globally identified. A single entry exists in this list for each VLAN interface in the system that is bound to a global identifier.')
a3ComVlanGlobalMappingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanGlobalMappingIdentifier"))
if mibBuilder.loadTexts: a3ComVlanGlobalMappingEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanGlobalMappingEntry.setDescription('An individual VLAN interface global mapping entry. Entries in this table are created by setting the a3ComVlanIfGlobalIdentifier object in the a3ComVlanIfTable to a non-zero value.')
a3ComVlanGlobalMappingIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: a3ComVlanGlobalMappingIdentifier.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanGlobalMappingIdentifier.setDescription('An index into the a3ComVlanGlobalMappingTable and an administratively assigned global VLAN identifier. The value of this object globally identifies the VLAN interface. For VLAN interfaces, on different network devices, which are part of the same globally identified VLAN, the value of this object will be the same.')
a3ComVlanGlobalMappingIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComVlanGlobalMappingIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanGlobalMappingIfIndex.setDescription('The value of a3ComVlanIfIndex for the VLAN interface in the a3ComVlanIfTable, which is bound to the global identifier specified by this entry.')
a3ComVlanIfTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2), )
if mibBuilder.loadTexts: a3ComVlanIfTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfTable.setDescription('This table lists VLAN interfaces that exist within a device. A single entry exists in this list for each VLAN interface in the system. A VLAN interface may be created, destroyed and/or mapped to a globally identified vlan.')
a3ComVlanIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanIfIndex"))
if mibBuilder.loadTexts: a3ComVlanIfEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfEntry.setDescription('An individual VLAN interface entry. When an NMS wishes to create a new entry in this table, it must obtain a non-zero index from the a3ComNextAvailableVirtIfIndex object. Row creation in this table will fail if the chosen index value does not match the current value returned from the a3ComNextAvailableVirtIfIndex object.')
a3ComVlanIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 1), Integer32())
if mibBuilder.loadTexts: a3ComVlanIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfIndex.setDescription("The index value of this row and the vlan's ifIndex in the ifTable. The NMS obtains the index value for this row by reading the a3ComNextAvailableVirtIfIndex object.")
a3ComVlanIfDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfDescr.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfDescr.setDescription('This is a description of the VLAN interface.')
a3ComVlanIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 3), A3ComVlanType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfType.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfType.setDescription('The VLAN interface type.')
a3ComVlanIfGlobalIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfGlobalIdentifier.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfGlobalIdentifier.setDescription('An administratively assigned global VLAN identifier. For VLAN interfaces, on different network devices, which are part of the same globally identified VLAN, the value of this object will be the same. The binding between a global identifier and a VLAN interface can be created or removed. To create a binding an NMS must write a non-zero value to this object. To delete a binding, the NMS must write a zero to this object.')
a3ComVlanIfInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 5), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComVlanIfInfo.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfInfo.setDescription('A TLV encoded information string for the VLAN interface. The information contained within this string corresponds to VLAN information not contained within this table, but contained elsewhere within this MIB module. The purpose of this string is to provide an NMS with a quick read mechanism of all related VLAN interface information. The encoding rules are defined according to: tag = 2 bytes length = 2 bytes value = n bytes The following tags are defined: TAG OBJECT DESCRIPTION 1 a3ComIpVlanIpNetAddress IP Network Address of IP VLAN 2 a3ComIpVlanIpNetMask IP Network Mask of IP VLAN')
a3ComVlanIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 6), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfStatus.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfStatus.setDescription('The status column for this VLAN interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the creation request. Setting this object to createAndWait(5) causes a row in in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptible to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). When the state of the row transitions to active(1), the agent creates the corresponding row in the ifTable.. Setting this object to destroy(6) will remove the corresponding VLAN interface, remove the entry in this table, and the corresponding entries in the a3ComVlanGlobalMappingTable and the ifTable. In order for a set of this object to destroy(6) to succeed, all dependencies on this row must have been removed. These will include any stacking dependencies in the ifStackTable and any protocol specific tables dependencies.')
a3ComVlanIfModeType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 1, 2, 1, 7), A3ComVlanModeType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanIfModeType.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanIfModeType.setDescription(' The VLAN mode type for this interface. This object can be set to: usedefault(1) open(2) closed(3) UseDefault Vlans: uses the bridge Vlan Mode value. The bridge Vlan Mode Value can be set to : Open, Closed or Mixed. Open VLANs: have no requirements about relationship between the bridge port that a frame was received upon and the bridge port(s) that it is transmitted on. All open VLANs within the bridge will share the same address table. Closed VLANs: require that the bridge port that a frame is received on is the same VLAN interface as the bridge port(s) that a frame is transmitted on. Each closed VLAN within the bridge will have its own address table.')
a3ComIpVlanTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1), )
if mibBuilder.loadTexts: a3ComIpVlanTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanTable.setDescription('A list of IP VLAN interface information entries. Entries in this table are related to entries in the a3ComVlanIfTable by using the same index.')
a3ComIpVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanIfIndex"))
if mibBuilder.loadTexts: a3ComIpVlanEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanEntry.setDescription('A a3ComIpVlanEntry contains layer 3 information about a particular IP VLAN interface. Note entries in this table cannot be deleted until the entries in the ifStackTable that produce overlap are removed.')
a3ComIpVlanIpNetAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 1), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComIpVlanIpNetAddress.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanIpNetAddress.setDescription('The IP network number for the IP VLAN interface defined in the a3ComVlanIfTable identified with the same index. The IpNetAdress and the IpNetMask must be set and the the row creation process completed by a NMS before overlapping rows in the ifStackTable can be created. Sets to the ifStackTable that produce overlapping IP IP VLAN interfaces will fail if this object is not set.')
a3ComIpVlanIpNetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComIpVlanIpNetMask.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanIpNetMask.setDescription('The IP network mask corresponding to the IP Network address defined by a3ComIpVlanIpNetAddress. The IpNetAdress and the IpNetMask must be set and the row creation process completed by a NMS before overlapping rows in the ifStackTable can be created. Sets to the ifStackTable that produce overlapping IP VLAN interfaces will fail if this object is not set.')
a3ComIpVlanStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 1, 1, 3), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComIpVlanStatus.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComIpVlanStatus.setDescription('The status column for this IP VLAN entry. This object can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the row creation request. Setting this object to createAndWait(5) causes a row in in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptible to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). When the status changes to active(1), the agent applies the IP parmeters to the IP VLAN interface identified by the corresponding value of the a3ComIpVlanIndex object. Setting this object to destroy(6) will remove the IP parmeters from the IP VLAN interface and remove the entry from this table. Setting this object to destroy(6) will remove the layer 3 information from the IP VLAN interface and will remove the row from this table. Note that this action cannot be performed if there are ifStackTable entries that result in overlapping IP VLAN interfaces. Note that these dependencies must be removed first.')
a3ComVlanProtocolTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2), )
if mibBuilder.loadTexts: a3ComVlanProtocolTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolTable.setDescription('This table lists the configured protocols per Vlan. A single entry exists in this list for each protocol configured on a VLAN interface. The a3ComVlanIfType object in a3ComVlanIfTable has to be set to vlanLayeredProtocols in order to use this table.')
a3ComVlanProtocolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanProtocolIfIndex"), (0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanProtocolIndex"))
if mibBuilder.loadTexts: a3ComVlanProtocolEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolEntry.setDescription('A a3ComVlanProtocolEntry contains a single VLAN to protocol entry.')
a3ComVlanProtocolIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 1), Integer32())
if mibBuilder.loadTexts: a3ComVlanProtocolIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolIfIndex.setDescription("The first indice of this row and the vlan's ifIndex in the ifTable. The value of this object is the same as the corresponding a3ComVlanIfIndex in the a3ComVlanTable.")
a3ComVlanProtocolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 2), A3ComVlanLayer3Type())
if mibBuilder.loadTexts: a3ComVlanProtocolIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolIndex.setDescription('The second indice of this row, which identifies one of possible many protocols associated with the VLAN interface identified by this entries first indice. The values are based on the layer 3 protocols specified in A3ComVlanType')
a3ComVlanProtocolStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 2, 2, 1, 3), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanProtocolStatus.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanProtocolStatus.setDescription('The status column for this VLAN interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notInService(2) notReady(3). Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row and the values are acceptible to the agent, the agent will change the status to active(1). If any of the necessary objects are not available, the agent will reject the creation request. Setting this object to createAndWait(5) causes a row in this table to be created. The agent sets the status to notInService(2) if all of the information is present in the row and the values are acceptable to the agent; otherwise, the agent sets the status to notReady(3). Setting this object to active(1) is only valid when the current status is active(1) or notInService(2). Row creation to this table is only possible when a corresponding VLAN entry has been created in the a3ComVlanTable with an a3ComVlanType set to vlanLayeredProtocols(16). Setting this object to destroy(6) will remove the corresponding VLAN interface to protocol mapping.')
class A3ComVlanEncapsType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("vlanEncaps3ComProprietaryVLT", 1), ("vlanEncaps8021q", 2), ("vlanEncapsPre8021qONcore", 3))
a3ComVlanEncapsIfTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1), )
if mibBuilder.loadTexts: a3ComVlanEncapsIfTable.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfTable.setDescription('This table lists VLAN encapsulation interfaces that exist within a device. A single entry exists in this list for each VLAN encapsulation interface in the system. A VLAN encapsulation interface may be created or destroyed.')
a3ComVlanEncapsIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1), ).setIndexNames((0, "GENERIC-3COM-VLAN-MIB-1-0-7", "a3ComVlanEncapsIfIndex"))
if mibBuilder.loadTexts: a3ComVlanEncapsIfEntry.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfEntry.setDescription('An individual VLAN encapsulation interface entry. When an NMS wishes to create a new entry in this table, it must obtain a non-zero index from the a3ComNextAvailableVirtIfIndex object. Row creation in this table will fail if the chosen index value does not match the current value returned from the a3ComNextAvailableVirtIfIndex object.')
a3ComVlanEncapsIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 1), Integer32())
if mibBuilder.loadTexts: a3ComVlanEncapsIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfIndex.setDescription("The index value of this row and the encapsulation interface's ifIndex in the ifTable. The NMS obtains the index value used for creating a row in this table by reading the a3ComNextAvailableVirtIfIndex object.")
a3ComVlanEncapsIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 2), A3ComVlanEncapsType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanEncapsIfType.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfType.setDescription('The encapsulation algorithm used when encapsulating packets transmitted, or de-encapsulating packets received through this interface.')
a3ComVlanEncapsIfTag = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanEncapsIfTag.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfTag.setDescription('The tag used when encapsulating packets transmitted, or de-encapsulating packets received through this interface.')
a3ComVlanEncapsIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 4, 1, 1, 4), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: a3ComVlanEncapsIfStatus.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComVlanEncapsIfStatus.setDescription('The row status for this VLAN encapsulation interface. This OBJECT can be set to: active(1) createAndGo(4) createAndWait(5) destroy(6) The following values may be read: active(1) notReady(3). In order for a row to become active, the NMS must set a3ComVlanEncapsIfTagType and a3ComVlanEncapsIfTag to some valid and consistent values. Setting this object to createAndGo(4) causes the agent to attempt to create and commit the row based on the contents of the objects in the row. If all necessary information is present in the row, the agent will create the row and change the status to active(1). If any of the necessary objects are not available, or specify an invalid configuration, the row will not be created and the agent will return an appropriate error. Setting this object to createAndWait(5) causes a row in in this table to be created. If all necessary objects in the row have been assigned values and specify a valid configuration, the status of the row will be set to notInService(2); otherwise, the status will be set to notReady(3). This object may only be set to createAndGo(4) or createAndWait(5) if it does not exist. Setting this object to active(1) when the status is notInService(2) causes the agent to commit the row. Setting this object to active(1) when its value is already active(1) is a no-op. Setting this object to destroy(6) will remove the corresponding VLAN encapsulation interface, remote the entry in this table, and remove the corresponding entry in the ifTable. In order for a set of this object to destroy(6) to succeed, all dependencies on this row must have been removed. These will include any references to this interface in the ifStackTable.')
a3ComNextAvailableVirtIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 1, 14, 3, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: a3ComNextAvailableVirtIfIndex.setStatus('mandatory')
if mibBuilder.loadTexts: a3ComNextAvailableVirtIfIndex.setDescription("The value of the next available virtual ifIndex. This object is used by an NMS to select an index value for row-creation in tables indexed by ifIndex. The current value of this object is changed to a new value when the current value is written to an agent's table, that is indexed by ifIndex. Row creation using the current value of this object, allocates a virtual ifIndex. Note the following: 1. A newly created row does not have to be active(1) for the agent to allocate the virtual ifIndex. 2. Race conditions between multiple NMS's end when a row is created. Rows are deemed created when a setRequest is successfully committed (i.e. the errorStats is noError(0)). 3. An agent that exhausts its supply of virual ifIndex values returns zero as the value of this object. This can be used by an NMS as an indication to deleted unused rows and reboot the device.")
mibBuilder.exportSymbols("GENERIC-3COM-VLAN-MIB-1-0-7", a3ComVlanEncapsIfStatus=a3ComVlanEncapsIfStatus, a3ComEncapsulationGroup=a3ComEncapsulationGroup, A3ComVlanLayer3Type=A3ComVlanLayer3Type, a3ComVlanIfTable=a3ComVlanIfTable, generic=generic, a3ComIpVlanTable=a3ComIpVlanTable, a3ComVlanIfModeType=a3ComVlanIfModeType, a3ComVlanProtocolTable=a3ComVlanProtocolTable, a3ComVirtualGroup=a3ComVirtualGroup, A3ComVlanType=A3ComVlanType, a3ComIpVlanIpNetMask=a3ComIpVlanIpNetMask, a3ComVlanGlobalMappingTable=a3ComVlanGlobalMappingTable, a3ComVlanEncapsIfIndex=a3ComVlanEncapsIfIndex, a3ComIpVlanIpNetAddress=a3ComIpVlanIpNetAddress, a3ComVlanProtocolIndex=a3ComVlanProtocolIndex, a3ComVlanGlobalMappingEntry=a3ComVlanGlobalMappingEntry, a3ComVlanEncapsIfTag=a3ComVlanEncapsIfTag, a3ComVlanIfIndex=a3ComVlanIfIndex, a3ComNextAvailableVirtIfIndex=a3ComNextAvailableVirtIfIndex, a3ComVlanIfDescr=a3ComVlanIfDescr, a3ComVlanIfStatus=a3ComVlanIfStatus, a3ComVlanGlobalMappingIfIndex=a3ComVlanGlobalMappingIfIndex, a3ComVlanEncapsIfEntry=a3ComVlanEncapsIfEntry, a3ComVlanEncapsIfTable=a3ComVlanEncapsIfTable, a3ComVlanIfGlobalIdentifier=a3ComVlanIfGlobalIdentifier, a3ComVlanIfInfo=a3ComVlanIfInfo, a3ComVlanProtocolIfIndex=a3ComVlanProtocolIfIndex, genVirtual=genVirtual, RowStatus=RowStatus, a3ComIpVlanEntry=a3ComIpVlanEntry, a3ComVlanIfEntry=a3ComVlanIfEntry, a3ComVlanProtocolEntry=a3ComVlanProtocolEntry, A3ComVlanModeType=A3ComVlanModeType, a3ComIpVlanStatus=a3ComIpVlanStatus, a3Com=a3Com, a3ComVlanGroup=a3ComVlanGroup, a3ComVlanEncapsIfType=a3ComVlanEncapsIfType, a3ComVlanProtocolStatus=a3ComVlanProtocolStatus, a3ComVlanIfType=a3ComVlanIfType, a3ComVlanProtocolsGroup=a3ComVlanProtocolsGroup, A3ComVlanEncapsType=A3ComVlanEncapsType, a3ComVlanGlobalMappingIdentifier=a3ComVlanGlobalMappingIdentifier, genExperimental=genExperimental)
|
"""
User configuration file for the client.
"""
SERVER_ADDRESS = "127.0.0.1"
SERVER_PORT = 50000
|
# PROBLEM
#
# Assume s is a string of lower case characters.
#
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your
# program should print:
#
# 'Longest substring in alphabetical order is: beggh'
#
# In case of ties, print the first substring. For example, if s = 'abcbcd',
# then your program should print:
#
# 'Longest substring in alphabetical order is: abc'
# For test purposes
s = 'azcbobobegghakl'
# SOLUTION
if len(s) > 1:
substring = s[0]
length = 1
# Store initial solution
bestsubstring = substring
bestlength = length
for num in range(len(s)-1): # Last letter is checked by 2nd-last letter
if s[num] <= s[num+1]:
substring = substring + s[num+1]
length += 1
if length > bestlength:
bestsubstring = substring
bestlength = length
else: # Reset substring and length
substring = s[num+1]
length = 1
else:
bestsubstring = s
print ('Longest substring in alphabetical order is: ' + bestsubstring)
|
mandatory = \
{
'article' : ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'],
'book' : ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'],
'booklet' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'conference' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'],
'inbook' : ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'],
'incollection' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'],
'inproceedings' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'year'],
'manual' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'mastersthesis' : ['ENTRYTYPE', 'ID', 'author', 'title', 'school', 'year'],
'misc' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'phdthesis' : ['ENTRYTYPE', 'ID', 'author', 'title', 'school', 'year'],
'proceedings' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'techreport' : ['ENTRYTYPE', 'ID', 'author', 'title', 'institution', 'year'],
'unpublished' : ['ENTRYTYPE', 'ID', 'author', 'title', 'note']
} |
class ParkingLot:
def __init__(self, username, latitude, longitude, totalSpace, costHour):
self.username = username
self.latitude = latitude
self.longitude = longitude
self.totalSpace = totalSpace
self.availableSpace = totalSpace
self.costHour = costHour
def getSpace(self):
return self.availableSpace
def setBook(self):
self.availableSpace -= 1
class signUp:
def __init__(self, username, password):
self.username = username
self.password = password
# def getDetails():
|
class AnalyticalModelStick(AnalyticalModel,IDisposable):
"""
An element that represents a stick in the structural analytical model.
Could be one of beam,brace or column type.
"""
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def GetAlignmentMethod(self,selector):
"""
GetAlignmentMethod(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> AnalyticalAlignmentMethod
Gets the alignment method for a given selector.
selector: End of the analytical model.
Returns: The alignment method at a given end.
"""
pass
def getBoundingBox(self,*args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def GetLocalCoordinateSystem(self,*__args):
"""
GetLocalCoordinateSystem(self: AnalyticalModelStick,point: XYZ) -> Transform
Gets the local coordinate system (LCS) reflects analytical model orientation at
the specified point.
point: The point on the analytical model stick element.
Returns: Transformation matrix.
x - longitudinal axis,y - transversal,section -
horizontal,strong axis,z - transversal,section - vertical,weak axis,origin
- base point of LCS.
GetLocalCoordinateSystem(self: AnalyticalModelStick,parameter: float) -> Transform
Gets the local coordinate system (LCS) reflects analytical model orientation at
the specified parameter value along a curve.
parameter: The parameter value along a curve that should be in the range [0,1],where 0
represents start and 1 represents end of the element.
Returns: Transformation matrix.
x - longitudinal axis,y - transversal,section -
horizontal,strong axis,z - transversal,section - vertical,weak axis,origin
- base point of LCS.
"""
pass
def GetMemberForces(self):
"""
GetMemberForces(self: AnalyticalModelStick) -> IList[MemberForces]
Gets the member forces associated with this element.
Returns: Returns a collection of Member Forces associated with this element. Empty
collection will be returned if element doesn't have any Member Forces.
To
find out with which end member forces are associated use
Autodesk::Revit::DB::Structure::MemberForces::Position
property to obtain a
position of Member Forces on element.
"""
pass
def GetProjectionPlaneY(self,selector):
"""
GetProjectionPlaneY(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> ElementId
Retrieves analytical model projection information for Y direction.
selector: End of the analytical model.
Returns: Plane on to which analytical model is projected,or invalidElementId if
not
projected to a Plane.
"""
pass
def GetProjectionPlaneZ(self,selector):
"""
GetProjectionPlaneZ(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> ElementId
Retrieves analytical model projection information for Z direction.
selector: End of the analytical model.
Returns: Plane on to which analytical model is projected,or invalidElementId if
not
projected to a Plane.
"""
pass
def GetProjectionY(self,selector):
"""
GetProjectionY(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> StickElementProjectionY
Retrieves analytical model projection information for Y direction.
selector: End of the analytical model.
Returns: Indicates if the projection is a preset value,or refers to a Plane.
"""
pass
def GetProjectionZ(self,selector):
"""
GetProjectionZ(self: AnalyticalModelStick,selector: AnalyticalElementSelector) -> StickElementProjectionZ
Retrieves analytical model projection information for Z direction.
selector: End of the analytical model.
Returns: Indicates if the projection is a preset value,or refers to a Plane.
"""
pass
def GetReleases(self,start,fx,fy,fz,mx,my,mz):
"""
GetReleases(self: AnalyticalModelStick,start: bool) -> (bool,bool,bool,bool,bool,bool)
Gets the releases of element.
start: The position on analytical model stick element. True for start,false for end.
"""
pass
def GetReleaseType(self,start):
"""
GetReleaseType(self: AnalyticalModelStick,start: bool) -> ReleaseType
Gets the release type.
start: The position on analytical model stick element. True for start,false for end.
Returns: The type of release.
"""
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: Element,disposing: bool) """
pass
def RemoveAllMemberForces(self):
"""
RemoveAllMemberForces(self: AnalyticalModelStick) -> bool
Removes all member forces associated with element.
Returns: True if any member forces were removed,false otherwise.
"""
pass
def RemoveMemberForces(self,start):
"""
RemoveMemberForces(self: AnalyticalModelStick,start: bool) -> bool
Removes member forces defined for given position.
start: Member Forces position on analytical model stick element. True for start,false
for end.
Returns: True if member forces for provided position were removed,false otherwise.
"""
pass
def SetAlignmentMethod(self,selector,method):
"""
SetAlignmentMethod(self: AnalyticalModelStick,selector: AnalyticalElementSelector,method: AnalyticalAlignmentMethod)
Sets the alignment method for a given selector.
selector: End of the analytical model.
method: The alignment method at a given end.
"""
pass
def setElementType(self,*args):
""" setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """
pass
def SetMemberForces(self,*__args):
"""
SetMemberForces(self: AnalyticalModelStick,start: bool,force: XYZ,moment: XYZ)
Adds Member Forces to element.
start: Member Forces position on analytical model stick element. True for start,false
for end.
force: The translational forces at specified position of the element.
The x value
of XYZ object represents force along x-axis of the analytical model coordinate
system,y along y-axis,z along z-axis respectively.
moment: The rotational forces at specified position of the element.
The x value of
XYZ object represents moment about x-axis of the analytical model coordinate
system,y about y-axis,z about z-axis respectively.
SetMemberForces(self: AnalyticalModelStick,memberForces: MemberForces)
Sets Member Forces to element.
memberForces: End to which member forces will be added is defined by setting
Autodesk::Revit::DB::Structure::MemberForces::Position
property in provided
Member Forces object.
"""
pass
def SetProjection(self,selector,*__args):
"""
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,planeIdY: ElementId,projectionZ: StickElementProjectionZ)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
planeIdY: Plane on to which analytical model may be projected in Y direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
projectionZ: Preset value for Analytical Model Stick projection Z.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,projectionY: StickElementProjectionY,projectionZ: StickElementProjectionZ)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
projectionY: Preset value for Analytical Model Stick projection Y.
projectionZ: Preset value for Analytical Model Stick projection Z.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,planeIdY: ElementId,planeIdZ: ElementId)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
planeIdY: Plane on to which analytical model may be projected in Y direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
planeIdZ: Plane on to which analytical model may be projected in Z direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
SetProjection(self: AnalyticalModelStick,selector: AnalyticalElementSelector,projectionY: StickElementProjectionY,planeIdZ: ElementId)
Sets the analytical model projection to a preset value.
selector: End of the analytical model.
projectionY: Preset value for Analytical Model Stick projection Y.
planeIdZ: Plane on to which analytical model may be projected in Z direction.
Plane
identifies a Level,a Grid,or a Ref Plane.
"""
pass
def SetReleases(self,start,fx,fy,fz,mx,my,mz):
"""
SetReleases(self: AnalyticalModelStick,start: bool,fx: bool,fy: bool,fz: bool,mx: bool,my: bool,mz: bool)
Sets the releases of element.
start: The position on analytical model stick element. True for start,false for end.
"""
pass
def SetReleaseType(self,start,releaseType):
"""
SetReleaseType(self: AnalyticalModelStick,start: bool,releaseType: ReleaseType)
Sets the release type.
start: The position on analytical model stick element. True for start,false for end.
releaseType: The type of release.
"""
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
|
""""
Crie uma Fazenda de Bichinhos instanciando vários objetos bichinho e mantendo o controle deles através de uma lista.
Imite o funcionamento do programa básico, mas ao invés de exigis que o usuário tome conta de um único bichinho,
exija que ele tome conta da fazenda inteira. Cada opção do menu deveria permitir que o usuário executasse
uma ação para todos os bichinhos (alimentar todos os bichinhos, brincar com todos os bichinhos, ou ouvir a todos os
bichinhos). Para tornar o programa mais interessante, dê para cada bichinho um nivel inicial aleatório de fome e tédio.
"""
# todo: terminar
|
lst1=list()
lst1.append('K')
lst1.append('A')
lst2=['U', 'S', 'H', 'I', 'K']
print(lst1+lst2)
print(lst2[0] +lst2[1]+lst1[1])
for i in lst1+lst2:
print(i)
|
class Photo(object):
def __init__(self, photo_id: int, orientation: str, number_of_tags: int, tags: set):
self.id = photo_id
self.orientation = orientation
self.number_of_tags = number_of_tags
self.tags = tags
self.is_vertical = orientation == 'V'
self.is_horizontal = orientation == 'H'
def __str__(self):
return str(self.id)
|
# addition will takes place after multiplication and addition
num1 = 1 + 4 * 3 / 2;
# same as 5 * 3 /2
num2 = (1 + 4) * 3 / 2;
# same as 1+12/2
num3 = 1 + (4 * 3) / 2;
print("python follow precedence rules");
# this should produce 7.5
print(num1);
print(num2);
print(num3); |
class Fruit:
def __init__(self,name,parents):
self.name = name
self.parents = parents
self.children = []
self.family = []
self.siblings = []
self.node = None ## Link to node object in graph
def find_children(self,basket): # basket is a list of Fruit objects
for fruit in basket:
if fruit.name is not self.name:
if self.name in [parent.name for parent in fruit.parents]:
self.children.append(fruit)
self.family = self.parents + self.children
def find_siblings(self,basket):
for fruit in basket:
if fruit.name is not self.name:
if set(fruit.parents).is_disjoint(set(self.parents)):
continue
else:
self.siblings.append(fruit)
|
file = open("text.txt", "r")
file2 = open("text2.txt", "w")
for data in file:
file2.write(data)
file.close()
file2.close()
|
animals = ['cat', 'dog', 'pig']
for animal in animals :
print (animal + 'would make a great pet.')
print ('All of those animals would makea great pet')
|
"""Exceptions of the library"""
class PyConnectError(Exception):
"""Base class for all exceptions in py_connect."""
class InvalidPowerCombination(PyConnectError):
"""Connection of different power pins."""
class MaxConnectionsError(PyConnectError):
"""Interface has exceeded it's max connections limit."""
class InvalidGpioError(PyConnectError):
"""Invalid connection of two gpio pins."""
class AlreadyConnectedError(PyConnectError):
"""One or more pins of the interface are already connected."""
class TwoMasterError(PyConnectError):
"""Error when connecting two master interfaces."""
class TwoSlaveError(PyConnectError):
"""Error when connecting two slave interfaces."""
class ChipEnabledFullError(PyConnectError):
"""All chip enable pins are in use."""
class NotImplementedDriverError(PyConnectError):
"""This peripheral doesn't have an implemented driver."""
class UnicludedDeviceError(PyConnectError):
"""Device hasn't been included in connections specification."""
class EmptyListError(PyConnectError):
"""Empty list given for an attribute."""
|
#! /bin/bash/python3
'''Ejemplo de un script que puede ser importado como módulo.'''
titulo = "Espacio muestral"
datos = (76, 81, 75, 77, 80, 75, 76, 79, 75)
def promedio(encabezado, muestra):
'''Despliega el contenido de encabezado,así como el cálculo del promedio de muestra, ingresado en una lista o tupla.'''
print("El promedio de %s con %d elementos es %f." % (encabezado, len(muestra), sum(muestra) / len(muestra)))
promedio(titulo, datos) |
genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
num_files = 100
with open(f'INPUT_FULL', 'w') as f:
for genre in genres:
for i in range(num_files):
for j in range(6):
f.write(f'/datasets/duet/genres/{genre}.{i:05d}.{j}.wav /datasets/duet/genres/{genre}.{i:05d}.{j}.wav\n') |
# Copyright 2020 University of Adelaide
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def check_inst(inst, mask, match):
return inst & mask == match
def cycles_push(inst):
if check_inst(inst, 0b1111111000000000, 0b1011010000000000):
return 1 + bin(inst & 0x00ff).count('1')
return -1
def cycles_pop(inst):
# Format 14: push/pop registers
if check_inst(inst, 0b1111111000000000, 0b1011110000000000):
return 1 + bin(inst & 0x00ff).count('1')
return -1
def cycles_pop_pc(inst):
# Format 14: push/pop registers
if check_inst(inst, 0b1111111100000000, 0b1011110100000000):
return 4 + bin(inst & 0x00ff).count('1')
return -1
def cycles_add(inst):
# Format 2: add/subtract
if check_inst(inst, 0b1111101000000000, 0b0001100000000000):
return 1
return -1
def cycles_add_pc(inst):
return -1
def cycles_rot(inst):
# Format 4
if check_inst(inst, 0b1111111111000000, 0b0100000111000000):
return 1
return -1
def cycles_ldr(inst):
# Format 7
# Format 9
if check_inst(inst, 0b1111101000000000, 0b0101100000000000) or \
check_inst(inst, 0b1110100000000000, 0b0110100000000000):
return 2
return -1
def cycles_str(inst):
# Format 7
# Format 9
if check_inst(inst, 0b1111101000000000, 0b0101000000000000) or \
check_inst(inst, 0b1110100000000000, 0b0110000000000000):
return 2
return -1
def cycles_mov(inst):
# Format 1: move shifted register
# Format 3: move/compare/add/subtract immediate
# Format 5: Hi register operations/branch exchange
if check_inst(inst, 0b1111111111000000, 0b0000000000000000) or \
check_inst(inst, 0b1111100000000000, 0b0010000000000000) or \
check_inst(inst, 0b1111111100000000, 0b0100011000000000):
return 1
return -1
def cycles_mov_pc(inst):
# Format 5: dest = pc
if check_inst(inst, 0b1111111101000111, 0b0100011001000111):
return 3
return -1
__cycle_counts = [
[ cycles_mov, cycles_mov_pc ],
[ cycles_add, cycles_add_pc ],
[ cycles_ldr ],
[ cycles_str ],
[ cycles_rot ],
[ cycles_pop, cycles_pop_pc ],
[ cycles_push ]
]
def get_cycle_counts():
return __cycle_counts |
d = {'key1': 1, 'key2': 2, 'key3': 3}
for k in d:
print(k)
# key1
# key2
# key3
for k in d.keys():
print(k)
# key1
# key2
# key3
keys = d.keys()
print(keys)
print(type(keys))
# dict_keys(['key1', 'key2', 'key3'])
# <class 'dict_keys'>
k_list = list(d.keys())
print(k_list)
print(type(k_list))
# ['key1', 'key2', 'key3']
# <class 'list'>
for v in d.values():
print(v)
# 1
# 2
# 3
values = d.values()
print(values)
print(type(values))
# dict_values([1, 2, 3])
# <class 'dict_values'>
v_list = list(d.values())
print(v_list)
print(type(v_list))
# [1, 2, 3]
# <class 'list'>
for k, v in d.items():
print(k, v)
# key1 1
# key2 2
# key3 3
for t in d.items():
print(t)
print(type(t))
print(t[0])
print(t[1])
print('---')
# ('key1', 1)
# <class 'tuple'>
# key1
# 1
# ---
# ('key2', 2)
# <class 'tuple'>
# key2
# 2
# ---
# ('key3', 3)
# <class 'tuple'>
# key3
# 3
# ---
items = d.items()
print(items)
print(type(items))
# dict_items([('key1', 1), ('key2', 2), ('key3', 3)])
# <class 'dict_items'>
i_list = list(d.items())
print(i_list)
print(type(i_list))
# [('key1', 1), ('key2', 2), ('key3', 3)]
# <class 'list'>
print(i_list[0])
print(type(i_list[0]))
# ('key1', 1)
# <class 'tuple'>
|
# Testing out some stuff with async and await
async def hello(name):
print ("hello" + name)
return "hello" + name
# We can use the await statement in coroutines to call
# coroutines as normal functions; i.e. what it implies is that
# if we runt return await func(*args) in a courtoune
# is like running return func2(*args) in a normal def function
async def await_hello(func, *args):
return await func(*args)
def run(coro, *args):
try:
# We need to create the coroutine object before we start using it.
#
g = coro(*args)
# In order to run the coroutine from a normal function, we need to
# send it a value, in this case None.
g.send(None)
# However, the coroutine will run til it returns a StopIteration
# which we need to catch, and then catch the value of that
# exception, so as to find out what it has produced
except StopIteration as e:
return e.value
print(run(await_hello, hello, "wut")) |
number = int(input())
raiz = number/2
for i in range(1,20):
raiz = ((raiz ** 2) + number) / (2 * raiz)
print(raiz) |
class Item:
def __init__(self,weight,value) -> None:
self.weight=weight
self.value=value
self.ratio=value/weight
def knapsackMethod(items,capacity):
items.sort(key=lambda x: x.ratio,reverse=True)
usedCapacity=0
totalValue=0
for i in items:
if usedCapacity+i.weight<=capacity:
usedCapacity+=i.weight
totalValue+=i.value
else:
unusedWeight=capacity-usedCapacity
value=i.ratio*unusedWeight
usedCapacity+=unusedWeight
totalValue+=value
if usedCapacity==capacity:
break
print("Total value obtained: "+str(totalValue))
item1=Item(20,100)
item2=Item(30,120)
item3=Item(10,60)
cList=[item1,item2,item3]
knapsackMethod(cList,50) |
class Node:
"""
A node class used in A* Pathfinding.
parent: it is parent of current node
position: it is current position of node in the maze.
g: cost from start to current Node
h: heuristic based estimated cost for current Node to end Node
f: total cost of present node i.e. : f = g + h
"""
def __init__(self , parent=None , poistion=None):
self.parent = parent
self.position = poistion
self.g = 0
self.f = 0
self.h = 0
def __eq__(self , other):
return self.position == other.position
class FindPath():
def __init__(self , maze , cost , start , end):
self.maze = maze
self.cost = cost
self.start = start
self.end = end
self.move = [ [-1, 0] , # go up
[ 0,-1] , # go left
[ 1, 0] , # go down
[ 0, 1] , # go right
[-1,-1] , # go left-up
[-1, 1] , # go left down
[ 1,-1] , # go right down
[ 1, 1] ] # go right up
def return_path(self,curr_node,cost_matrix):
path = []
no_rows , no_columns = np.shape(cost_matrix)
# here we create the initialized result maze with -1 in every position
res = [[-1 for i in range(no_columns)] for j in range(no_rows)]
#we will iterate over all parents of node and store in path
curr = curr_node
while curr is not None:
path.append(curr.position)
curr = curr.parent
path = path[::-1]
initial_value = 0
# we will insert the path in matrix
for i in range(len(path)):
res[path[i][0]][path[i][1]] = initial_value
initial_value += 1
return res
def search(self):
"""
Returns a list of tuples as a path from the given start to the given end in the given maze
"""
# we will create start node and end node
# we will initialize g, h and f value zero
start_node = Node(None, tuple(self.start))
start_node.g = 0
start_node.h = 0
start_node.f = 0
end_node = Node(None, tuple(self.end))
end_node.g = 0
end_node.h = 0
end_node.f = 0
# we need to initialize both queue and visited list
# we will find the lowest cost node to expand next
queue = []
# we will store all visited node
visited_list = []
# Add the start node
queue.append(start_node)
# calculate the maximiuim number of steps we can move in the matrix
counter = 0
max_steps = (len(self.maze) // 2) ** 10
# Get number of rows and columns
no_rows, no_columns = np.shape(self.maze)
# Loop until you find the end
while len(queue) > 0:
# Every time any node is visited increase the counter
counter += 1
# Get the current node
current_node = queue[0]
current_index = 0
for index, item in enumerate(queue):
if item.f < current_node.f:
current_node = item
current_index = index
# if we hit this point return the path such as it may be no solution or
# computation cost is too high
if counter > max_steps:
print ("Destination cannot be reached")
return self.return_path(current_node , self.maze)
# Pop current node out off
queue.pop(current_index)
# mark it visited
visited_list.append(current_node)
# check if goal is reached or not
if current_node == end_node:
return self.return_path(current_node , self.maze)
# Generate coordinate from all adjacent coordinates
coordinates = []
for move in self.move:
# Get node position
current_node_position = (current_node.position[0] + move[0] , current_node.position[1] + move[1])
# check if all the moves are in maze limit
if (current_node_position[0] > (no_rows - 1) or current_node_position[0] < 0 or current_node_position[1] > (no_columns -1) or current_node_position[1] < 0):
continue
# Make sure walkable terrain
if self.maze[current_node_position[0]][current_node_position[1]] != 0:
continue
# Create new node
new_node = Node(current_node , current_node_position)
# Append
coordinates.append(new_node)
# Loop through children
for child in coordinates:
# Child is on the visited list (search entire visited list)
if len([visited_child for visited_child in visited_list if visited_child == child]) > 0:
continue
# calculate f, g, and h values
child.g = current_node.g + self.cost
# calculated Heuristic costs, this is using eucledian distance
child.h = (((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2))
child.f = child.g + child.h
# Child if already in queue and g cost is already lower
if len([i for i in queue if child == i and child.g > i.g]) > 0:
continue
queue.append(child)
class Preprocess:
def __init__(self , maze , n , m):
self.maze = maze
self.n = n
self.m = m
def check(self , value):
data=''
for i in range(len(value)):
if(value[i] == '[' or value[i] == ']'):
continue
else:
data+=value[i]
return data
def process_text(self):
c=0
matrix = self.maze
matrix = matrix.split(',')
data = []
for i in range(self.n):
l = []
for j in range(self.m):
l.append(int(self.check(matrix[c])))
c += 1
data.append(l)
return data
if __name__ == '__main__':
no_rows = int(input("Enter number of rows: "))
no_cols = int(input("Enter number of columns: "))
matrix = Preprocess(str(input("Enter Matrix: ")) , no_rows , no_cols).process_text()
start_x = int(input("Enter x coordinate of starting node: "))
start_y = int(input("Enter y coordinate of starting node: "))
end_x = int(input("Enter x coordinate of ending node: "))
end_y = int(input("Enter y coordinate of ending node: "))
cost = int(input("Enter cost: "))
start = [start_x , start_y]
end = [end_x , end_y]
path = FindPath(matrix , cost , start , end).search()
if(path != None):
print("Path found: ")
for i in range(len(path)):
for j in range(len(path[i])):
if(path[i][j] == -1):
print(0 , end=" ")
else:
print(path[i][j] , end=" ")
print()
else:
print("No Path found")
#input:
# Enter number of rows: 5
# Enter number of columns: 6
# Enter Matrix: [[0, 1, 0, 0, 0, 0],
# [0, 1, 0, 0, 0, 0],
# [0, 1, 0, 1, 0, 0],
# [0, 1, 0, 0, 1, 0],
# [0, 0, 0, 0, 1, 0]]
# Enter x coordinate of starting node: 0
# Enter y coordinate of starting node: 0
# Enter x coordinate of ending node: 4
# Enter y coordinate of ending node: 5
# Enter cost: 1
#Path found:
# 0 0 0 0 0 0
# 1 0 0 0 0 0
# 2 0 0 0 7 0
# 3 0 0 6 0 8
# 0 4 5 0 0 9
|
#LeetCode problem 54: Spiral Matrix
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if(len(matrix)==0 or len(matrix[0])==0):
return []
res=[]
rb=0
re=len(matrix)
cb=0
ce=len(matrix[0])
while(re>rb and ce>cb):
for j in range(cb,ce):
res.append(matrix[rb][j])
for k in range(rb+1,re-1):
res.append(matrix[k][ce-1])
if(re!=rb+1):
for l in range(ce-1,cb-1,-1):
res.append(matrix[re-1][l])
if(cb!=ce-1):
for m in range(re-2,rb,-1):
res.append(matrix[m][cb])
rb+=1
ce-=1
cb+=1
re-=1
return(res) |
"""
Non-orthogonal Reflection
by Ira Greenberg.
Based on the equation (R = 2N(N * L) - L) where R is the reflection vector, N
is the normal, and L is the incident vector.
"""
# Position of left hand side of floor.
base1 = None
# Position of right hand side of floor.
base2 = None
# A list of subpoints along the floor path.
coords = []
# Variables related to moving ball.
position = None
velocity = None
r = 6
speed = 3.5
def setup():
size(640, 360)
fill(128)
base1 = PVector(0, height - 150)
base2 = PVector(width, height)
createGround()
# Start ellipse at middle top of screen.
position = PVector(width / 2, 0)
# Calculate initial random velocity.
velocity = PVector.random2D()
velocity.mult(speed)
def draw():
# Draw background.
fill(0, 12)
noStroke()
rect(0, 0, width, height)
# Draw base.
fill(200)
quad(base1.x, base1.y, base2.x, base2.y, base2.x, height, 0, height)
# Calculate base top normal.
baseDelta = PVector.sub(base2, base1)
baseDelta.normalize()
normal = PVector(-baseDelta.y, baseDelta.x)
# Draw ellipse.
noStroke()
fill(255)
ellipse(position.x, position.y, r * 2, r * 2)
# Move elipse.
position.add(velocity)
# Normalized incidence vector.
incidence = PVector.mult(velocity, -1)
incidence.normalize()
# Detect and handle collision.
for coord in coords:
# Check distance between ellipse and base top coordinates.
if PVector.dist(position, coord) < r:
# Calculate dot product of incident vector and base top normal.
dot = incidence.dot(normal)
# Calculate reflection vector.
# Assign reflection vector to direction vector.
velocity.set(2 * normal.x * dot - incidence.x,
2 * normal.y * dot - incidence.y, 0)
velocity.mult(speed)
# Draw base top normal at collision point.
stroke(255, 128, 0)
line(position.x, position.y,
position.x - normal.x * 100, position.y - normal.y * 100)
# Detect boundary collision.
# Right.
if position.x > width - r:
position.x = width - r
velocity.x *= -1
# Left.
if position.x < r:
position.x = r
velocity.x *= -1
# Top.
if position.y < r:
position.y = r
velocity.y *= -1
# Randomize base top.
base1.y = random(height - 100, height)
base2.y = random(height - 100, height)
createGround()
# Calculate variables for the ground.
def createGround():
# Calculate length of base top.
baseLength = PVector.dist(base1, base2)
# Fill base top coordinate array.
coords = [PVector(base1.x + ((base2.x - base1.x) / baseLength) * i,
base1.y + ((base2.y - base1.y) / baseLength) * i)
for i in range(ceil(baseLength))]
|
def isPower(n):
'''
Determine if the given number is a power of some non-negative integer.
'''
if n == 1:
return True
sqrt = math.sqrt(n)
for a in range(int(sqrt)+1):
for b in range(2, int(sqrt)+1):
if a ** b == n:
return True
return False |
# Add your own choices here!
fruit = ["apples", "oranges", "pears", "grapes", "blueberries"]
lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"]
situations = {"fruit":fruit, "lunch":lunch}
|
__author__ = 'Brian Nguyen'
def greeting(msg):
print("We would like to say: " + msg) |
"""
This module contains the general settings used across modules.
"""
FPS = 60
WINDOW_WIDTH = 1100
WINDOW_HEIGHT = 600
TIME_MULTIPLIER = 1.0
|
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
k = 1
max_len, i = 0, 0
for j in range(len(nums)):
if nums[j] == 0:
k -= 1
if k < 0:
if nums[i] == 0:
k += 1
i += 1
max_len = max(max_len, j - i)
return max_len
|
ROOT_WK_API_URL = "https://api.wanikani.com/v2/"
RESOURCES_WITHOUT_IDS = ["user", "collection", "report"]
SUBJECT_ENDPOINT = "subjects"
SINGLE_SUBJECT_ENPOINT = r"subjects/\d+"
ASSIGNMENT_ENDPOINT = "assignments"
REVIEW_STATS_ENDPOINT = "review_statistics"
STUDY_MATERIALS_ENDPOINT = "study_materials"
REVIEWS_ENDPOINT = "reviews"
LEVEL_PROGRESSIONS_ENDPOINT = "level_progressions"
RESETS_ENDPOINT = "resets"
SUMMARY_ENDPOINT = "summary"
USER_ENDPOINT = "user"
|
"""
Script testing 14.4.2 control from OWASP ASVS 4.0:
'Verify that all API responses contain a Content-Disposition: attachment;
filename="api.json" header (or other appropriate filename for the content
type).'
The script will raise an alert if 'Content-Disposition' header is present but not follow the format - Content-Disposition: attachment; filename=
"""
def scan(ps, msg, src):
#find "Content-Disposition" header
header = str(msg.getResponseHeader().getHeader("Content-Disposition"))
#alert parameters
alertRisk= 1
alertConfidence = 2
alertTitle = "14.4.2 Verify that all API responses contain a Content-Disposition."
alertDescription = "Verify that all API responses contain a Content-Disposition: attachment; filename='api.json'header (or other appropriate filename for the content type)."
url = msg.getRequestHeader().getURI().toString()
alertParam = ""
alertAttack = ""
alertInfo = "https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload"
alertSolution = "Use the format 'Content-Disposition: attachment; filename=' for API responses"
alertEvidence = ""
cweID = 116
wascID = 0
# if "attachment; filename=" is not in "Content-Disposition" header, raise alert
if ("attachment; filename=" not in header.lower()):
ps.raiseAlert(alertRisk, alertConfidence, alertTitle, alertDescription,
url, alertParam, alertAttack, alertInfo, alertSolution, alertEvidence, cweID, wascID, msg);
|
MAX_N = 10000 + 1
isprime = [True] * (MAX_N)
isprime[0] = False
isprime[1] = False
for i in range(2, MAX_N):
if not isprime[i]:
continue
for j in range(i+i, MAX_N, i):
isprime[j] = False
T = int(input())
for _ in range(T):
n = int(input())
for i in range(n//2, 1, -1):
if isprime[i] and isprime[n-i]:
print('%d %d' % (i, n-i))
break
|
#
# PySNMP MIB module DOCS-LOADBALANCING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-LOADBALANCING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:53:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint")
clabProjDocsis, = mibBuilder.importSymbols("CLAB-DEF-MIB", "clabProjDocsis")
docsIfCmtsCmStatusIndex, docsIfCmtsCmStatusEntry = mibBuilder.importSymbols("DOCS-IF-MIB", "docsIfCmtsCmStatusIndex", "docsIfCmtsCmStatusEntry")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
ModuleIdentity, Gauge32, Counter32, IpAddress, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, TimeTicks, Counter64, Unsigned32, zeroDotZero, Integer32, iso, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Gauge32", "Counter32", "IpAddress", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "TimeTicks", "Counter64", "Unsigned32", "zeroDotZero", "Integer32", "iso", "ObjectIdentity")
TimeStamp, TruthValue, TextualConvention, DisplayString, RowStatus, RowPointer, MacAddress = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "TruthValue", "TextualConvention", "DisplayString", "RowStatus", "RowPointer", "MacAddress")
docsLoadBalanceMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2))
docsLoadBalanceMib.setRevisions(('2004-03-10 17:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: docsLoadBalanceMib.setRevisionsDescriptions(('Initial version of this mib module.',))
if mibBuilder.loadTexts: docsLoadBalanceMib.setLastUpdated('200403101700Z')
if mibBuilder.loadTexts: docsLoadBalanceMib.setOrganization('Cable Television Laboratories, Inc')
if mibBuilder.loadTexts: docsLoadBalanceMib.setContactInfo(' Postal: Cable Television Laboratories, Inc. 400 Centennial Parkway Louisville, Colorado 80027-1266 U.S.A. Phone: +1 303-661-9100 Fax: +1 303-661-9199 E-mail: mibs@cablelabs.com')
if mibBuilder.loadTexts: docsLoadBalanceMib.setDescription('This is the MIB Module for the load balancing. Load balancing is manageable on a per-CM basis. Each CM is assigned: a) to a set of channels (a Load Balancing Group) among which it can be moved by the CMTS b) a policy which governs if and when the CM can be moved c) a priority value which can be used by the CMTS in order to select CMs to move.')
class ChannelChgInitTechMap(TextualConvention, Bits):
description = "This textual convention enumerates the Initialization techniques for Dynamic Channel Change (DCC). The techniques are represented by the 5 most significant bits (MSB). Bits 0 through 4 map to initialization techniques 0 through 4. Each bit position represents the internal associated technique as described below: reinitializeMac(0) : Reinitialize the MAC broadcastInitRanging(1): Perform Broadcast initial ranging on new channel before normal operation unicastInitRanging(2) : Perform unicast ranging on new channel before normal operation initRanging(3) : Perform either broadcast or unicast ranging on new channel before normal operation direct(4) : Use the new channel(s) directly without re-initializing or ranging Multiple bits selection in 1's means the CMTS selects the best suitable technique among the selected in a proprietary manner. An empty value or a value with all bits in '0' means no channel changes allowed"
status = 'current'
namedValues = NamedValues(("reinitializeMac", 0), ("broadcastInitRanging", 1), ("unicastInitRanging", 2), ("initRanging", 3), ("direct", 4))
docsLoadBalNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 0))
docsLoadBalMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1))
docsLoadBalSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 1))
docsLoadBalChgOverObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2))
docsLoadBalGrpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3))
docsLoadBalPolicyObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4))
docsLoadBalChgOverGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 1))
docsLoadBalEnable = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 1, 1), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalEnable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalEnable.setDescription('Setting this object to true(1) enables internal autonomous load balancing operation on this CMTS. Setting it to false(2) disables the autonomous load balancing operations. However moving a cable modem via docsLoadBalChgOverTable is allowed even when this object is set to false(2).')
docsLoadBalChgOverMacAddress = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 1, 1), MacAddress().clone(hexValue="000000000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalChgOverMacAddress.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverMacAddress.setDescription('The mac address of the cable modem that the CMTS instructs to move to a new downstream frequency and/or upstream channel.')
docsLoadBalChgOverDownFrequency = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1000000000))).setUnits('hertz').setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalChgOverDownFrequency.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverDownFrequency.setDescription('The new downstream frequency to which the cable modem is instructed to move. The value 0 indicates that the CMTS does not create a TLV for the downstream frequency in the DCC-REQ message. This object has no meaning when executing UCC operations.')
docsLoadBalChgOverUpChannelId = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalChgOverUpChannelId.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverUpChannelId.setDescription('The new upstream channel ID to which the cable modem is instructed to move. The value -1 indicates that the CMTS does not create a TLV for the upstream channel ID in the channel change request.')
docsLoadBalChgOverInitTech = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 1, 4), ChannelChgInitTechMap()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalChgOverInitTech.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverInitTech.setDescription("The initialization technique that the cable modem is instructed to use when performing change over operation. By default this object is initialized with all the defined bits having a value of '1'.")
docsLoadBalChgOverCmd = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("any", 1), ("dcc", 2), ("ucc", 3))).clone('any')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalChgOverCmd.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverCmd.setDescription('The change over command that the CMTS is instructed use when performing change over operation. The any(1) value indicates that the CMTS is to use its own algorithm to determine the appropriate command.')
docsLoadBalChgOverCommit = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 1, 6), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalChgOverCommit.setReference('Data-Over-Cable Service Interface Specifications: Radio Frequency Interface Specification SP-RFIv2.0-I04-030730, Sections C.4.1, 11.4.5.1.')
if mibBuilder.loadTexts: docsLoadBalChgOverCommit.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverCommit.setDescription("The command to execute the DCC/UCC operation when set to true(1). The following are reasons for rejecting an SNMP SET to this object: - The MAC address in docsLoadBalChgOverMacAddr is not an existing MAC address in docsIfCmtsMacToCmEntry. - docsLoadBalChgOverCmd is ucc(3) and docsLoadBalChgOverUpChannelId is '-1', - docsLoadBalChgOverUpChannelId is '-1' and docsLoadBalChgOverDownFrequency is '0'. - DCC/UCC operation is currently being executed for the cable modem, on which the new command is committed, specifically if the value of docsLoadBalChgOverStatusValue is one of: messageSent(1), modemDeparting(4), waitToSendMessage(6). - An UCC operation is committed for a non-existing upstream channel ID or the corresponding ifOperStatus is down(2). - A DCC operation is committed for an invalid or non-existing downstream frequency, or the corresponding ifOperStatus is down(2). In those cases, the SET is rejected with an error code 'commitFailed'. After processing the SNMP SET the information in docsLoadBalChgOverGroup is updated in a corresponding entry in docsLoadBalChgOverStatusEntry. Reading this object always returns false(2).")
docsLoadBalChgOverLastCommit = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 1, 7), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChgOverLastCommit.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverLastCommit.setDescription('The value of sysUpTime when docsLoadBalChgOverCommit was last set to true. Zero if never set.')
docsLoadBalChgOverStatusTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2), )
if mibBuilder.loadTexts: docsLoadBalChgOverStatusTable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusTable.setDescription('A table of CMTS operation entries to reports the status of cable modems instructed to move to a new downstream and/or upstream channel. Using the docsLoadBalChgOverGroup objects. An entry in this table is created or updated for the entry with docsIfCmtsCmStatusIndex that correspond to the cable modem MAC address of the Load Balancing operation. docsLoadBalChgOverCommit to true(1).')
docsLoadBalChgOverStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2, 1), ).setIndexNames((0, "DOCS-IF-MIB", "docsIfCmtsCmStatusIndex"))
if mibBuilder.loadTexts: docsLoadBalChgOverStatusEntry.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusEntry.setDescription('A CMTS operation entry to instruct a cable modem to move to a new downstream frequency and/or upstream channel. An operator can use this to initiate an operation in CMTS to instruct the selected cable modem to move to a new downstream frequency and/or upstream channel.')
docsLoadBalChgOverStatusMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2, 1, 1), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChgOverStatusMacAddr.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusMacAddr.setDescription('The mac address set in docsLoadBalChgOverMacAddress.')
docsLoadBalChgOverStatusDownFreq = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1000000000))).setUnits('hertz').setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChgOverStatusDownFreq.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusDownFreq.setDescription('The Downstream frequency set in docsLoadBalChgOverDownFrequency.')
docsLoadBalChgOverStatusUpChnId = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 255)).clone(-1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChgOverStatusUpChnId.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusUpChnId.setDescription('The upstream channel ID set in docsLoadBalChgOverUpChannelId.')
docsLoadBalChgOverStatusInitTech = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2, 1, 4), ChannelChgInitTechMap()).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChgOverStatusInitTech.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusInitTech.setDescription('The initialization technique set in docsLoadBalChgOverInitTech.')
docsLoadBalChgOverStatusCmd = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("any", 1), ("dcc", 2), ("ucc", 3))).clone('any')).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChgOverStatusCmd.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusCmd.setDescription('The load balancing command set in docsLoadBalChgOverCmd.')
docsLoadBalChgOverStatusValue = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("messageSent", 1), ("noOpNeeded", 2), ("modemDeparting", 3), ("waitToSendMessage", 4), ("cmOperationRejected", 5), ("cmtsOperationRejected", 6), ("timeOutT13", 7), ("timeOutT15", 8), ("rejectinit", 9), ("success", 10))).clone('waitToSendMessage')).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChgOverStatusValue.setReference('Data-Over-Cable Service Interface Specifications: Radio Frequency Interface Specification SP-RFIv2.0-I04-030730, Sections C.4.1, 11.4.5.1.')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusValue.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusValue.setDescription("The status of the specified DCC/UCC operation. The enumerations are: messageSent(1): The CMTS has sent change over request message to the cable modem. noOpNeed(2): A operation was requested in which neither the DS Frequency nor the Upstream Channel ID was changed. An active value in this entry's row status indicates that no CMTS operation is required. modemDeparting(3): The cable modem has responded with a change over response of either a DCC-RSP with a confirmation code of depart(180) or a UCC-RSP. waitToSendMessage(4): The specified operation is active and CMTS is waiting to send the channel change message with channel info to the cable modem. cmOperationRejected(5): Channel Change (such as DCC or UCC) operation was rejected by the cable modem. cmtsOperationRejected(6) Channel Change (such as DCC or UCC) operation was rejected by the Cable modem Termination System. timeOutT13(7): Failure due to no DCC-RSP with confirmation code depart(180) received prior to expiration of the T13 timer. timeOutT15(8): T15 timer timed out prior to the arrival of a bandwidth request, RNG-REQ message, or DCC-RSP message with confirmation code of arrive(181) from the cable modem. rejectInit(9): DCC operation rejected due to unsupported initialization tech requested. success(10): CMTS received an indication that the CM successfully completed the change over operation. e.g., If an initialization technique of re-initialize the MAC is used, success in indicated by the receipt of a DCC-RSP message with a confirmation code of depart(180). In all other cases, success is indicated by: (1) the CMTS received a DCC-RSP message with confirmation code of arrive(181) or (2) the CMTS internally confirms the presence of the CM on the new channel.")
docsLoadBalChgOverStatusUpdate = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 2, 2, 1, 7), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChgOverStatusUpdate.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChgOverStatusUpdate.setDescription('The value of sysUpTime when docsLoadBalChgOverStatusValue was last updated.')
docsLoadBalGrpTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1), )
if mibBuilder.loadTexts: docsLoadBalGrpTable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpTable.setDescription('This table contains the attributes of the load balancing groups present in this CMTS.')
docsLoadBalGrpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1), ).setIndexNames((0, "DOCS-LOADBALANCING-MIB", "docsLoadBalGrpId"))
if mibBuilder.loadTexts: docsLoadBalGrpEntry.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpEntry.setDescription('A set of attributes of load balancing group in the CMTS. It is index by a docsLoadBalGrpId which is unique within a CMTS. Entries in this table persist after CMTS initialization.')
docsLoadBalGrpId = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: docsLoadBalGrpId.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpId.setDescription('A unique index assigned to the load balancing group by the CMTS.')
docsLoadBalGrpIsRestricted = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1, 2), TruthValue().clone('false')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalGrpIsRestricted.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpIsRestricted.setDescription('A value true(1)Indicates type of load balancing group. A Restricted Load Balancing Group is associated to a specific provisioned set of cable modems. Restricted Load Balancing Group is used to accommodate a topology specific or provisioning specific restriction. Example such as a group that are reserved for business customers). Setting this object to true(1) means it is a Restricted Load Balancing type and setting it to false(2) means it is a General Load Balancing group type. This object should not be changed while its group ID is referenced by an active entry in docsLoadBalRestrictCmEntry.')
docsLoadBalGrpInitTech = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1, 3), ChannelChgInitTechMap()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalGrpInitTech.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpInitTech.setDescription("The initialization techniques that the CMTS can use when load balancing cable modems in the load balancing group. By default this object is initialized with all the defined bits having a value of '1'.")
docsLoadBalGrpDefaultPolicy = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalGrpDefaultPolicy.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpDefaultPolicy.setDescription('Each Load Balancing Group has a default Load Balancing Policy. A policy is described by a set of conditions (rules) that govern the load balancing process for a cable modem. The CMTS assigns this Policy ID value to a cable modem associated with the group ID when the cable modem does not signal a Policy ID during registration. The Policy ID value is intended to be a numeric reference to a row entry in docsLoadBalPolicyEntry. However, It is not required to have an existing or active entry in docsLoadBalPolicyEntry when setting the value of docsLoadBalGrpDefaultPolicy, in which case it indicates no policy is associated with the load Balancing Group. The Policy ID of value 0 is reserved to indicate no policy is associated with the load balancing group.')
docsLoadBalGrpEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1, 5), TruthValue().clone('true')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalGrpEnable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpEnable.setDescription('Setting this object to true(1) enables internal autonomous load balancing on this group. Setting it to false(2) disables the load balancing operation on this group.')
docsLoadBalGrpChgOverSuccess = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalGrpChgOverSuccess.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpChgOverSuccess.setDescription('The number of successful load balancing change over operations initiated within this load balancing group.')
docsLoadBalGrpChgOverFails = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalGrpChgOverFails.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpChgOverFails.setDescription('The number of failed load balancing change over operations initiated within this load balancing group.')
docsLoadBalGrpStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalGrpStatus.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalGrpStatus.setDescription("Indicates the status of the row in this table. Setting this object to 'destroy' or 'notInService' for a group ID entry already referenced by docsLoadBalChannelEntry, docsLoadBalChnPairsEntry or docsLoadBalRestrictCmEntry returns an error code inconsistentValue.")
docsLoadBalChannelTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 2), )
if mibBuilder.loadTexts: docsLoadBalChannelTable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChannelTable.setDescription('Lists all upstream and downstream channels associated with load balancing groups.')
docsLoadBalChannelEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 2, 1), ).setIndexNames((0, "DOCS-LOADBALANCING-MIB", "docsLoadBalGrpId"), (0, "DOCS-LOADBALANCING-MIB", "docsLoadBalChannelIfIndex"))
if mibBuilder.loadTexts: docsLoadBalChannelEntry.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChannelEntry.setDescription('Lists a specific upstream or downstream, within a load Balancing group. An entry in this table exists for each ifEntry with an ifType of docsCableDownstream(128) and docsCableUpstream(129) associated with the Load Balancing Group. Entries in this table persist after CMTS initialization.')
docsLoadBalChannelIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 2, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: docsLoadBalChannelIfIndex.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChannelIfIndex.setDescription('The ifIndex of either the downstream or upstream.')
docsLoadBalChannelStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 2, 1, 2), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalChannelStatus.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChannelStatus.setDescription("Indicates the status of the rows in this table. Creating entries in this table requires an existing value for docsLoadBalGrpId in docsLoadBalGrpEntry and an existing value of docsLoadBalChannelIfIndex in ifEntry, otherwise is rejected with error 'noCreation'. Setting this object to 'destroy' or 'notInService for a a row entry that is being referenced by docsLoadBalChnPairsEntry is rejected with error code inconsistentValue.")
docsLoadBalChnPairsTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 3), )
if mibBuilder.loadTexts: docsLoadBalChnPairsTable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChnPairsTable.setDescription('This table contains pairs of upstream channels within a Load Balancing Group. Entries in this table are used to override the initialization techniques defined for the associated Load Balancing Group.')
docsLoadBalChnPairsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 3, 1), ).setIndexNames((0, "DOCS-LOADBALANCING-MIB", "docsLoadBalGrpId"), (0, "DOCS-LOADBALANCING-MIB", "docsLoadBalChnPairsIfIndexDepart"), (0, "DOCS-LOADBALANCING-MIB", "docsLoadBalChnPairsIfIndexArrive"))
if mibBuilder.loadTexts: docsLoadBalChnPairsEntry.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChnPairsEntry.setDescription('An entry in this table describes a channel pair for which an initialization technique override is needed. On a CMTS which supports logical upstream channels (ifType is equal to docsCableUpstreamChannel(205)), the entries in this table correspond to pairs of ifType 205. On a CMTS which only supports physical upstream channels (ifType is equal to docsCableUpstream(129)), the entries in this table correspond to pairs of ifType 129. Entries in this table persist after CMTS initialization.')
docsLoadBalChnPairsIfIndexDepart = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 3, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: docsLoadBalChnPairsIfIndexDepart.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChnPairsIfIndexDepart.setDescription('This index indicates the ifIndex of the upstream channel from which a cable modem would depart in a load balancing channel change operation.')
docsLoadBalChnPairsIfIndexArrive = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 3, 1, 2), InterfaceIndex())
if mibBuilder.loadTexts: docsLoadBalChnPairsIfIndexArrive.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChnPairsIfIndexArrive.setDescription('This index indicates the ifIndex of the upstream channel on which a cable modem would arrive in a load balancing channel change operation.')
docsLoadBalChnPairsOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("operational", 1), ("notOperational", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: docsLoadBalChnPairsOperStatus.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChnPairsOperStatus.setDescription('Operational status of the channel pair. The value operational(1) indicates that ifOperStatus of both channels is up(1). The value notOperational(2) means that ifOperStatus of one or both is not up(1).')
docsLoadBalChnPairsInitTech = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 3, 1, 4), ChannelChgInitTechMap()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalChnPairsInitTech.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChnPairsInitTech.setDescription("Specifies initialization technique for load balancing for the Depart/Arrive pair. By default this object's value is the initialization technique configured for the Load Balancing Group indicated by docsLoadBalGrpId.")
docsLoadBalChnPairsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 3, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalChnPairsRowStatus.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalChnPairsRowStatus.setDescription("The object for conceptual rows creation. An attempt to create a row with values for docsLoadBalChnPairsIfIndexDepart or docsLoadBalChnPairsIfIndexArrive which are not a part of the Load Balancing Group (or for a 2.0 CMTS are not logical channels (ifType 205)) are rejected with a 'noCreation' error status reported. There is no restriction on settings columns in this table when the value of docsLoadBalChnPairsRowStatus is active(1).")
docsLoadBalRestrictCmTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 4), )
if mibBuilder.loadTexts: docsLoadBalRestrictCmTable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalRestrictCmTable.setDescription('Lists all cable modems in each Restricted Load Balancing Groups.')
docsLoadBalRestrictCmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 4, 1), ).setIndexNames((0, "DOCS-LOADBALANCING-MIB", "docsLoadBalGrpId"), (0, "DOCS-LOADBALANCING-MIB", "docsLoadBalRestrictCmIndex"))
if mibBuilder.loadTexts: docsLoadBalRestrictCmEntry.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalRestrictCmEntry.setDescription('An entry of modem within a restricted load balancing group type. An entry represents a cable modem that is associated with the Restricted Load Balancing Group ID of a Restricted Load Balancing Group. Entries in this table persist after CMTS initialization.')
docsLoadBalRestrictCmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 4, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: docsLoadBalRestrictCmIndex.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalRestrictCmIndex.setDescription('The index that uniquely identifies an entry which represents restricted cable modem(s) within each Restricted Load Balancing Group.')
docsLoadBalRestrictCmMACAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 4, 1, 2), MacAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalRestrictCmMACAddr.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalRestrictCmMACAddr.setDescription('Mac Address of the cable modem within the restricted load balancing group.')
docsLoadBalRestrictCmMacAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 4, 1, 3), OctetString().subtype(subtypeSpec=ConstraintsUnion(ValueSizeConstraint(0, 0), ValueSizeConstraint(6, 6), )).clone(hexValue="")).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalRestrictCmMacAddrMask.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalRestrictCmMacAddrMask.setDescription('A bit mask acting as a wild card to associate a set of modem MAC addresses to the same Group ID. Cable modem look up is performed first with entries containing this value not null, if several entries match, the largest consecutive bit match from MSB to LSB is used. Empty value is equivalent to the bit mask all in ones.')
docsLoadBalRestrictCmStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 3, 4, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalRestrictCmStatus.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalRestrictCmStatus.setDescription("Indicates the status of the rows in this table. The attempt to create an entry associated to a group ID with docsLoadBalGrpIsRestricted equal to false(2) returns an error 'noCreation'. There is no restriction on settings columns in this table any time.")
docsLoadBalPolicyTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 1), )
if mibBuilder.loadTexts: docsLoadBalPolicyTable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalPolicyTable.setDescription('This table describes the set of Load Balancing policies. Rows in this table might be referenced by rows in docsLoadBalGrpEntry.')
docsLoadBalPolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 1, 1), ).setIndexNames((0, "DOCS-LOADBALANCING-MIB", "docsLoadBalPolicyId"), (0, "DOCS-LOADBALANCING-MIB", "docsLoadBalPolicyRuleId"))
if mibBuilder.loadTexts: docsLoadBalPolicyEntry.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalPolicyEntry.setDescription('Entries containing rules for policies. When a load balancing policy is defined by multiple rules, all the rules apply. Load balancing rules can be created to allow for specific vendor-defined load balancing actions. However there is a basic rule that the CMTS is required to support by configuring a pointer in docsLoadBalPolicyRulePtr to the table docsLoadBalBasicRuleTable. Vendor specific rules may be added by pointing the object docsLoadBalPolicyRulePtr to proprietary mib structures. Entries in this table persist after CMTS initialization.')
docsLoadBalPolicyId = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: docsLoadBalPolicyId.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalPolicyId.setDescription('An index identifying the Load Balancing Policy.')
docsLoadBalPolicyRuleId = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 1, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: docsLoadBalPolicyRuleId.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalPolicyRuleId.setDescription('An index for the rules entries associated within a policy.')
docsLoadBalPolicyRulePtr = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 1, 1, 3), RowPointer().clone((0, 0))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalPolicyRulePtr.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalPolicyRulePtr.setDescription('A pointer to an entry in a rule table. E.g., docsLoadBalBasicRuleEnable in docsLoadBalBasicRuleEntry. A value pointing to zeroDotZero, an inactive Row or a non-existing entry is treated as no rule defined for this policy entry.')
docsLoadBalPolicyRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalPolicyRowStatus.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalPolicyRowStatus.setDescription("The status of this conceptual row. There is no restriction on settings columns in this table when the value of docsLoadBalPolicyRowStatus is active(1). Setting this object to 'destroy' or 'notInService' for a row entry that is being referenced by docsLoadBalGrpDefaultPolicy in docsLoadBalGrpEntry returns an error code inconsistentValue.")
docsLoadBalBasicRuleTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 2), )
if mibBuilder.loadTexts: docsLoadBalBasicRuleTable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicRuleTable.setDescription('DOCSIS defined basic ruleset for load Balancing Policy. This table enables of disable load balancing for the groups pointing to this ruleset in the policy group.')
docsLoadBalBasicRuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 2, 1), ).setIndexNames((0, "DOCS-LOADBALANCING-MIB", "docsLoadBalBasicRuleId"))
if mibBuilder.loadTexts: docsLoadBalBasicRuleEntry.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicRuleEntry.setDescription('An entry of DOCSIS defined basic ruleset. The object docsLoadBalBasicRuleEnable is used for instantiating an entry in this table via a RowPointer. Entries in this table persist after CMTS initialization.')
docsLoadBalBasicRuleId = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: docsLoadBalBasicRuleId.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicRuleId.setDescription('The unique index for this row.')
docsLoadBalBasicRuleEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ("disabledPeriod", 3)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalBasicRuleEnable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicRuleEnable.setDescription('When using this ruleset, load balancing is enabled or disabled by the values enabled(1) and disabled(2) respectively. Additionally, a Load Balancing disabling period is defined in docsLoadBalBasicRuleDisStart and docsLoadBalBasicRuleDisPeriod if this object value is set to disabledPeriod(3).')
docsLoadBalBasicRuleDisStart = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 2, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 86400))).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalBasicRuleDisStart.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicRuleDisStart.setDescription('if object docsLoadBalBasicRuleEnable is disablePeriod(3) Load Balancing is disabled starting at this object value time (seconds from 12 AM). Otherwise, this object has no meaning.')
docsLoadBalBasicRuleDisPeriod = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 2, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 86400))).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalBasicRuleDisPeriod.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicRuleDisPeriod.setDescription('If object docsLoadBalBasicRuleEnable is disablePeriod(3) Load Balancing is disabled for the period of time defined between docsLoadBalBasicRuleDisStart and docsLoadBalBasicRuleDisStart plus the period of time of docsLoadBalBasicRuleDisPeriod. Otherwise, this object value has no meaning.')
docsLoadBalBasicRuleRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 4, 2, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: docsLoadBalBasicRuleRowStatus.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicRuleRowStatus.setDescription("This object is to create or delete rows in this table. There is no restriction for changing this row status or object's values in this table at any time.")
docsLoadBalCmtsCmStatusTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 1, 4), )
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusTable.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusTable.setDescription('The list contains the load balancing attributes associated with the cable modem. ')
docsLoadBalCmtsCmStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 1, 4, 1), )
docsIfCmtsCmStatusEntry.registerAugmentions(("DOCS-LOADBALANCING-MIB", "docsLoadBalCmtsCmStatusEntry"))
docsLoadBalCmtsCmStatusEntry.setIndexNames(*docsIfCmtsCmStatusEntry.getIndexNames())
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusEntry.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusEntry.setDescription('Additional objects for docsIfCmtsCmStatusTable entry that relate to load balancing ')
docsLoadBalCmtsCmStatusGroupId = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 1, 4, 1, 1), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusGroupId.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusGroupId.setDescription('The Group ID associated with this cable modem.')
docsLoadBalCmtsCmStatusPolicyId = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 1, 4, 1, 2), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusPolicyId.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusPolicyId.setDescription('The Policy ID associated with this cable modem.')
docsLoadBalCmtsCmStatusPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 1, 1, 4, 1, 3), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusPriority.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusPriority.setDescription('The Priority associated with this cable modem.')
docsLoadBalConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2))
docsLoadBalCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2, 1))
docsLoadBalGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2, 2))
docsLoadBalBasicCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2, 1, 1)).setObjects(("DOCS-LOADBALANCING-MIB", "docsLoadBalSystemGroup"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalParametersGroup"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalPoliciesGroup"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalBasicRuleGroup"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalCmtsCmStatusGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
docsLoadBalBasicCompliance = docsLoadBalBasicCompliance.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicCompliance.setDescription('The compliance statement for DOCSIS load balancing systems.')
docsLoadBalSystemGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2, 2, 1)).setObjects(("DOCS-LOADBALANCING-MIB", "docsLoadBalEnable"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverMacAddress"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverDownFrequency"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverUpChannelId"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverInitTech"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverCmd"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverCommit"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverLastCommit"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverStatusMacAddr"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverStatusDownFreq"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverStatusUpChnId"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverStatusInitTech"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverStatusCmd"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverStatusValue"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChgOverStatusUpdate"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
docsLoadBalSystemGroup = docsLoadBalSystemGroup.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalSystemGroup.setDescription('A collection of objects providing system-wide parameters for load balancing.')
docsLoadBalParametersGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2, 2, 2)).setObjects(("DOCS-LOADBALANCING-MIB", "docsLoadBalGrpIsRestricted"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalGrpInitTech"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalGrpDefaultPolicy"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalGrpEnable"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalGrpChgOverSuccess"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalGrpChgOverFails"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalGrpStatus"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChannelStatus"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChnPairsOperStatus"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChnPairsInitTech"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalChnPairsRowStatus"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalRestrictCmMACAddr"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalRestrictCmMacAddrMask"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalRestrictCmStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
docsLoadBalParametersGroup = docsLoadBalParametersGroup.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalParametersGroup.setDescription('A collection of objects containing the load balancing parameters.')
docsLoadBalPoliciesGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2, 2, 3)).setObjects(("DOCS-LOADBALANCING-MIB", "docsLoadBalPolicyRulePtr"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalPolicyRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
docsLoadBalPoliciesGroup = docsLoadBalPoliciesGroup.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalPoliciesGroup.setDescription('A collection of objects providing policies.')
docsLoadBalBasicRuleGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2, 2, 4)).setObjects(("DOCS-LOADBALANCING-MIB", "docsLoadBalBasicRuleEnable"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalBasicRuleDisStart"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalBasicRuleDisPeriod"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalBasicRuleRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
docsLoadBalBasicRuleGroup = docsLoadBalBasicRuleGroup.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalBasicRuleGroup.setDescription('DOCSIS defined basic Ruleset for load balancing policies.')
docsLoadBalCmtsCmStatusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4491, 2, 1, 2, 2, 2, 5)).setObjects(("DOCS-LOADBALANCING-MIB", "docsLoadBalCmtsCmStatusGroupId"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalCmtsCmStatusPolicyId"), ("DOCS-LOADBALANCING-MIB", "docsLoadBalCmtsCmStatusPriority"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
docsLoadBalCmtsCmStatusGroup = docsLoadBalCmtsCmStatusGroup.setStatus('current')
if mibBuilder.loadTexts: docsLoadBalCmtsCmStatusGroup.setDescription('Cable mode status extension objects.')
mibBuilder.exportSymbols("DOCS-LOADBALANCING-MIB", docsLoadBalChgOverStatusEntry=docsLoadBalChgOverStatusEntry, docsLoadBalCmtsCmStatusTable=docsLoadBalCmtsCmStatusTable, docsLoadBalCmtsCmStatusEntry=docsLoadBalCmtsCmStatusEntry, docsLoadBalBasicRuleDisStart=docsLoadBalBasicRuleDisStart, docsLoadBalBasicCompliance=docsLoadBalBasicCompliance, docsLoadBalChnPairsIfIndexDepart=docsLoadBalChnPairsIfIndexDepart, docsLoadBalChgOverStatusValue=docsLoadBalChgOverStatusValue, docsLoadBalMibObjects=docsLoadBalMibObjects, docsLoadBalEnable=docsLoadBalEnable, docsLoadBalGrpChgOverFails=docsLoadBalGrpChgOverFails, docsLoadBalCmtsCmStatusPriority=docsLoadBalCmtsCmStatusPriority, docsLoadBalBasicRuleDisPeriod=docsLoadBalBasicRuleDisPeriod, docsLoadBalChgOverStatusMacAddr=docsLoadBalChgOverStatusMacAddr, docsLoadBalGrpDefaultPolicy=docsLoadBalGrpDefaultPolicy, docsLoadBalGrpInitTech=docsLoadBalGrpInitTech, docsLoadBalRestrictCmStatus=docsLoadBalRestrictCmStatus, docsLoadBalChgOverGroup=docsLoadBalChgOverGroup, docsLoadBalChnPairsIfIndexArrive=docsLoadBalChnPairsIfIndexArrive, docsLoadBalChgOverLastCommit=docsLoadBalChgOverLastCommit, docsLoadBalPolicyEntry=docsLoadBalPolicyEntry, docsLoadBalChgOverStatusUpdate=docsLoadBalChgOverStatusUpdate, docsLoadBalChannelEntry=docsLoadBalChannelEntry, docsLoadBalChnPairsEntry=docsLoadBalChnPairsEntry, docsLoadBalGrpIsRestricted=docsLoadBalGrpIsRestricted, docsLoadBalSystem=docsLoadBalSystem, docsLoadBalChnPairsInitTech=docsLoadBalChnPairsInitTech, docsLoadBalBasicRuleGroup=docsLoadBalBasicRuleGroup, docsLoadBalChgOverStatusUpChnId=docsLoadBalChgOverStatusUpChnId, docsLoadBalParametersGroup=docsLoadBalParametersGroup, docsLoadBalBasicRuleEntry=docsLoadBalBasicRuleEntry, docsLoadBalRestrictCmMacAddrMask=docsLoadBalRestrictCmMacAddrMask, docsLoadBalPolicyRulePtr=docsLoadBalPolicyRulePtr, docsLoadBalGrpStatus=docsLoadBalGrpStatus, docsLoadBalSystemGroup=docsLoadBalSystemGroup, docsLoadBalGrpChgOverSuccess=docsLoadBalGrpChgOverSuccess, docsLoadBalPolicyObjects=docsLoadBalPolicyObjects, docsLoadBalGroups=docsLoadBalGroups, docsLoadBalanceMib=docsLoadBalanceMib, docsLoadBalChgOverInitTech=docsLoadBalChgOverInitTech, docsLoadBalChgOverStatusDownFreq=docsLoadBalChgOverStatusDownFreq, docsLoadBalGrpObjects=docsLoadBalGrpObjects, docsLoadBalChnPairsTable=docsLoadBalChnPairsTable, docsLoadBalCompliances=docsLoadBalCompliances, docsLoadBalCmtsCmStatusPolicyId=docsLoadBalCmtsCmStatusPolicyId, docsLoadBalGrpEnable=docsLoadBalGrpEnable, docsLoadBalBasicRuleRowStatus=docsLoadBalBasicRuleRowStatus, docsLoadBalChgOverStatusInitTech=docsLoadBalChgOverStatusInitTech, docsLoadBalGrpTable=docsLoadBalGrpTable, docsLoadBalChgOverCmd=docsLoadBalChgOverCmd, docsLoadBalGrpEntry=docsLoadBalGrpEntry, docsLoadBalRestrictCmIndex=docsLoadBalRestrictCmIndex, docsLoadBalChannelTable=docsLoadBalChannelTable, docsLoadBalChgOverObjects=docsLoadBalChgOverObjects, docsLoadBalPolicyTable=docsLoadBalPolicyTable, docsLoadBalBasicRuleTable=docsLoadBalBasicRuleTable, docsLoadBalGrpId=docsLoadBalGrpId, docsLoadBalChgOverDownFrequency=docsLoadBalChgOverDownFrequency, docsLoadBalChgOverUpChannelId=docsLoadBalChgOverUpChannelId, docsLoadBalChgOverCommit=docsLoadBalChgOverCommit, docsLoadBalPolicyRowStatus=docsLoadBalPolicyRowStatus, docsLoadBalRestrictCmMACAddr=docsLoadBalRestrictCmMACAddr, docsLoadBalPolicyId=docsLoadBalPolicyId, docsLoadBalRestrictCmTable=docsLoadBalRestrictCmTable, PYSNMP_MODULE_ID=docsLoadBalanceMib, docsLoadBalNotifications=docsLoadBalNotifications, docsLoadBalBasicRuleEnable=docsLoadBalBasicRuleEnable, docsLoadBalPolicyRuleId=docsLoadBalPolicyRuleId, docsLoadBalChnPairsOperStatus=docsLoadBalChnPairsOperStatus, docsLoadBalChgOverMacAddress=docsLoadBalChgOverMacAddress, docsLoadBalRestrictCmEntry=docsLoadBalRestrictCmEntry, docsLoadBalBasicRuleId=docsLoadBalBasicRuleId, docsLoadBalChannelIfIndex=docsLoadBalChannelIfIndex, docsLoadBalCmtsCmStatusGroup=docsLoadBalCmtsCmStatusGroup, docsLoadBalConformance=docsLoadBalConformance, docsLoadBalCmtsCmStatusGroupId=docsLoadBalCmtsCmStatusGroupId, docsLoadBalChannelStatus=docsLoadBalChannelStatus, docsLoadBalChnPairsRowStatus=docsLoadBalChnPairsRowStatus, docsLoadBalChgOverStatusTable=docsLoadBalChgOverStatusTable, ChannelChgInitTechMap=ChannelChgInitTechMap, docsLoadBalChgOverStatusCmd=docsLoadBalChgOverStatusCmd, docsLoadBalPoliciesGroup=docsLoadBalPoliciesGroup)
|
"""
Linear State Space Element Class
"""
class Element(object):
"""
State space member
"""
def __init__(self):
self.sys_id = str() # A string with the name of the element
self.sys = None # The actual object
self.ss = None # The state space object
self.settings = dict()
def initialise(self, data, sys_id):
self.sys_id = sys_id
settings = data.linear.settings[sys_id] # Load settings, the settings should be stored in data.linear.settings
# data.linear.settings should be created in the class above containing the entire set up
# Get the actual class object (like lingebm) from a dictionary in the same way that it is done for the solvers
# in sharpy
# sys = sys_from_string(sys_id)
# To use the decorator idea we would first need to instantiate the class. Need to see how this is done with NL
# SHARPy
def assemble(self):
pass |
"""Constants."""
# A ``None``-ish constant for use where ``None`` may be a valid value.
NOT_SET = type('NOT_SET', (), {
'__bool__': (lambda self: False),
'__str__': (lambda self: 'NOT_SET'),
'__repr__': (lambda self: 'NOT_SET'),
'__copy__': (lambda self: self),
})()
# An alias for NOT_SET that may be more semantically-correct in some
# contexts.
NO_DEFAULT = NOT_SET
|
class Solution:
def minCut(self, s: str) -> int:
dp=self.isPal(s)
return self.bfs(s,dp)
def isPal(self,s):
dp=[[False for i in s] for i in s]
for i in range(len(s)):
dp[i][i]=True
if i+1<len(s):
dp[i][i+1]=True if s[i]==s[i+1] else False
for i in range(len(s)):
for j in range(1,min(i+1,len(s)-i)):
# if j==1:
# dp[i][i+j]=True if s[i]==s[i+j] else False
# dp[i-j][i] = True if s[i] == s[i - j] else False
# else:
if i-j>-1 and i+j<len(s):
dp[i-j][i+j]= True if s[i-j]==s[i+j] and dp[i-j+1][i+j-1] else False
if i-j>-1 and i+j+1<len(s):
dp[i-j][i+j+1]=True if s[i-j]==s[i+1+j] and dp[i-j+1][i+j] else False
return dp
def bfs(self,s,dp):
q=list()
depth=1
for i in range(len(dp[0])):
if dp[0][i]:
if i==len(s)-1:
return 0
q.append(i+1)
while q:
size=len(q)
for i in range(size):
c=q[0]
q.pop(0)
for index in range(len(dp[c])):
if dp[c][index]:
if index==len(s)-1:
return depth
q.append(index+1)
depth+=1
return depth
if __name__ == '__main__':
sol=Solution()
# s='aammbbc'
# s='bb'
s="fifgbeajcacehiicccfecbfhhgfiiecdcjjffbghdidbhbdbfbfjccgbbdcjheccfbhafehieabbdfeigbiaggchaeghaijfbjhi"
print(sol.minCut(s)) |
def main(j, args, params, tags, tasklet):
params.merge(args)
doc = params.doc
tags = params.tags
out = ""
cmdstr = params.macrostr.split(":", 1)[1].replace("}}", "").strip()
md5 = j.base.byteprocessor.hashMd5(cmdstr)
j.system.fs.createDir(j.system.fs.joinPaths(j.core.portal.active.filesroot, "dot"))
path = j.system.fs.joinPaths(j.core.portal.active.filesroot, "dot", md5)
if not j.system.fs.exists(path + ".png"):
j.system.fs.writeFile(path + ".dot", cmdstr)
cmd = "dot -Tpng %s.dot -o %s.png" % (path, path)
# for i in range(5):
rescode, result = j.system.process.execute(cmd)
# if result.find("warning")==011:
if result.find("warning") != -1:
out = result
out += '\n'
out += "##DOT FILE WAS##:\n"
out += cmdstr
out += "##END OF DOT FILE##\n"
out = "{{code:\n%s\n}}" % out
params.result = out
return params
out = "!/files/dot/%s.png!" % md5
params.result = (out, doc)
return params
def match(j, args, params, tags, tasklet):
return True
|
"""
TakeDown v0.0.1
===============
author: Zesheng Xing
email: zsxing@ucdavis.edu
This Python project is to help people search on some client hosting contents that potential violate the their copyright.
"""
VERSION = "0.1.0"
DESCRIPTION = "A python script that allows users to search potential copyright violated information on GitHub and " \
"send emails taking down those."
CONTRIBUTORS_INFO = "The project is developed by Zesheng Xing and supervised by Joël Porquet-Lupine at UC Davis, 2020."
USAGE = \
"""
Usage: takedown.py command [args...]
where commands include:
find search repositories
python takedown.py find [search_query] [GitHub_token] [-options]
with following args:
[search_query]: required. The text used to search.
[Github_token]: required. The Github token used to raise the rate limit and enable broader search.
[-t target]: optional. The target of the search query. It could be “repo”, “code”. It is “code” by default.
Concatenate them by “+”, eg. “-t code+repo”.
[-i input]: optional. The file path of previous output of takedown find. By providing this path, the output
this time will be compared against the previous one.
[-o output]: optional. The output file path. The result will be printed to the console by default.
[-f format]: optional. The output format. It could be “yaml” or “json”. It is “yaml” by default
or using a configuration file:
python takedown.py find -c <path_to_config_file>
config file args:
required args:
[search_query]: required. The text used to search.
[Github_token]: required. The Github token used to raise the rate limit and enable broader search.
optional args:
[target]: optional. The target of the search query. It could be “repo”, “code”. It is “code” by default.
Concatenate them by “+”, eg. “-t code+repo”.
[input]: optional. The file path of previous output of takedown find. By providing this path,
the output this time will be compared against the previous one.
[output]: optional. The output file path. The result will be printed to the console by default.
[format]: optional. The output format. It could be “yaml” or “json”. It is “yaml” by default
send send emails based on records
python takedown send [domain] [port] [inputs] [-options]
with following args:
[domain]: required. The domain address to connect
[port]: required. port of domain to connect
[inputs]: required. Input files to send email
[-u username]: optional. username of the account. or ask
[-p password]: optional. password of the account. or ask
[-s secure method]: optional. It could be “TLS” or “SSL”, depending on the domain and port connected.
Confirm before using this option.
[-t tags]: optional. Only the records that matches the tag will be sent with an email
[-o output]: optional. The output file path. The result will be printed to the console by default.
[-f format]: optional. The output format. It could be “yaml” or “json”. It is “yaml” by default
[-en email name]: optional. name used to send email. Otherwise username will be used
[-es email subject]: optional. subject of the email. Otherwise default email subject is used
[-ep email preface]: optional. preface of the email. Otherwise default email preface is used
[-ee email ending]: optional. preface of the email. Otherwise default email preface is used
or using a configuration file:
python takedown.py send -c <path_to_config_file>
config file args:
required parameters:
[domain]: required. Domain used to connect smtp service
[port]: required. Port of domain to connect smtp service
[inputs]: required. Records based to send emails
optional parameters:
[username]: optional. username of the account. or ask
[password]: optional. password of the account. or ask
[secure method]: optional. It could be “TLS” or “SSL”, depending on the domain and port connected.
Confirm before using this option.
[tags]: optional. Only the records that matches the tag will be sent with an email
[output]: optional. The output file path. The result will be printed to the console by default.
[format]: optional. The output format. It could be “yaml” or “json”. It is “yaml” by default
[emai_name]: optional. name used to send email. Otherwise username will be used
[email_subject]: optional. subject of the email. Otherwise default email subject is used
[email_preface]: optional. preface of the email. Otherwise default email preface is used
[email_ending]: optional. preface of the email. Otherwise default email preface is used
help show instructions and list of options
"""
|
"""
Exceptions module
"""
class CuckooHashMapFullException(Exception):
"""
Exception raised when filter is full.
"""
pass
|
print('Interrogando um suspeito: ')
pg1 = str(input("Telefonou para a vítma?(S/N)\n").upper().strip())
pg2 = str(input('Esteve no local do crime?(S/N)\n').upper().strip())
pg3 = str(input('Mora perto da vítma?(S/N)\n').upper().strip())
pg4 = str(input('Devia para a vítma?(S/N)\n').upper().strip())
pg5 = str(input('Já trabalhou com a vítma?(S/N\n').upper().strip())
lst = [pg1, pg2, pg3, pg4, pg5].count('S')
if 3 > lst >= 2 :
print('Suspeita')
elif lst == 3 or lst == 4:
print('Cúmplice')
elif lst == 5:
print('Assassino')
else:
print('Inocente')
|
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
for i in range(0, len(haystack) - len(needle) + 1):
print(haystack[i : i + len(needle)], needle)
if haystack[i : i + len(needle)] == needle:
return i
return -1 |
"""
499. Word Count (Map Reduce)
https://www.lintcode.com/problem/word-count-map-reduce/description
"""
class WordCount:
# @param {str} line a text, for example "Bye Bye see you next"
def mapper(self, _, line):
# Write your code here
# Please use 'yield key, value'
word_lists = line.split(" ")
for word in word_lists:
yield word, 1
# @param key is from mapper
# @param values is a set of value with the same key
def reducer(self, key, values):
# Write your code here
# Please use 'yield key, value'
yield key, sum(values)
|
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
# This method changes the existing tree instead of returning a new one
if t1 and t2:
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
else:
return t1 or t2
|
n = int(input())
m = int(input())
r = m
for i in range(n):
a, b = map(int, input().split())
m += a
m -= b
if m < 0:
print(0)
exit()
r = max(r, m)
print(r)
|
name = " alberT"
one = name.rsplit()
print("one:", one)
two = name.index('al', 0)
print("two:", two)
three = name.index('T', -1)
print("three:", three)
four = name.replace('l', 'p')
print("four:", four)
five = name.split('l')
print("five:", five)
six = name.upper()
print("six:", six)
seven = name.lower()
print("seven:", seven)
eight = name[1]
print("eight:", eight )
nine = name[:3]
print("nine:", nine)
ten = name[-2:]
print("ten:", ten)
eleven = name.index("e")
print("eleven:", eleven)
twelve = name[:-1]
print("twelve:", twelve) |
n = int(input())
s = [[0] * 10 for _ in range(n + 1)]
s[1] = [0] + [1] * 9
mod = 1000 ** 3
for i in range(2, n + 1):
for j in range(0, 9 + 1):
if j >= 1:
s[i][j] += s[i - 1][j - 1]
if j <= 8:
s[i][j] += s[i - 1][j + 1]
print(sum(s[n]) % mod) |
class RpnCalcError(Exception):
"""Calculator Generic Exception"""
pass
class StackDepletedError(RpnCalcError):
""" Stack is out of items """
pass
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Definition of all Rainman2 exceptions
"""
__author__ = 'Ari Saha (arisaha@icloud.com), Mingyang Liu(liux3941@umn.edu)'
__date__ = 'Wednesday, February 14th 2018, 11:38:08 am'
class FileOpenError(IOError):
"""
Exception raised when a file couldn't be opened.
"""
pass
class AgentNotSupported(Exception):
"""
Exception raised when agent is not valid for requested algorithm
"""
pass
class AgentMethodNotImplemented(NotImplementedError):
"""
Exception raised when trying to access a private method of an agent
that is not implemented yet.
"""
pass
class AlgorithmNotImplemented(NotImplementedError):
"""
Exception raised when trying to access algorithm that is not
implemented yet.
"""
pass
class AlgorithmMethodNotImplemented(NotImplementedError):
"""
Exception raised when trying to access a private method of an algorithm
that is not implemented yet.
"""
pass
class ClientNotImplemented(NotImplementedError):
"""
Exception raised when trying to access client that is not
implemented yet.
"""
pass
class ClientMethodNotImplemented(NotImplementedError):
"""
Exception raised when trying to access a private method of a client
that is not implemented yet.
"""
pass
class EnvironmentNotImplemented(NotImplementedError):
"""
Exception raised when trying to access Environment that is not
implemented yet.
"""
pass
class EnvironmentMethodNotImplemented(NotImplementedError):
"""
Exception raised when trying to access a private method of an environment
that is not implemented yet.
"""
pass
class ExternalServerError(Exception):
"""
Exception raised when external server is not accessible
"""
pass
|
# Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
print('-' * 100)
print('{: ^100}'.format('EXERCÍCIO 014 - CONVERSOR DE TEMPERATURAS'))
print('-' * 100)
c = float(input('Informe a temperatura em ºC: '))
f = ((9 * c) / 5) + 32
print(f'A temperatura de {c:.2f}ºC corresponde a {f:.2f}ºF.')
print('-' * 100)
input('Pressione ENTER para sair...')
|
__title__ = "FisherExactTest"
__version__ = "1.0.1"
__author__ = "Ae-Mc"
__author_email__ = "ae_mc@mail.ru"
__description__ = "Two tailed Fisher's exact test wrote in pure Python"
__url__ = "https://github.com/Ae-Mc/Fisher"
__classifiers__ = [
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Utilities"
]
|
# Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
# Example:
# Given nums = [-2, 0, 3, -5, 2, -1]
# sumRange(0, 2) -> 1
# sumRange(2, 5) -> -1
# sumRange(0, 5) -> -3
class NumArray:
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.array = [0]
for num in nums:
self.array.append(self.array[-1] + num)
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.array[j+1] - self.array[i]
# Time: O(n)
# Space: O(n)
# Difficulty: easy |
# -*- coding: utf-8 -*-
class Solution:
def sortSentence(self, s: str) -> str:
tokens = s.split()
result = [None] * len(tokens)
for token in tokens:
word, index = token[:-1], int(token[-1])
result[index - 1] = word
return ' '.join(result)
if __name__ == '__main__':
solution = Solution()
assert 'This is a sentence' == solution.sortSentence('is2 sentence4 This1 a3')
assert 'Me Myself and I' == solution.sortSentence('Myself2 Me1 I4 and3')
|
#!/usr/bin/python3
##python3 闭包 与 nonlocal
#如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,
#那么内部函数就被认为是闭包(closure)
def A_():
var = 0
def clo_B():
var_b = 1 # 闭包的局部变量
var = 100
print(var) # 引用外部的var , 但是不会改变var 的值
return clo_B
#clo_B是一个闭包
#nonlocal 关键字
def A_():
var = 0
def clo_B():
nonlocal var # nonlocal关键字 指定var 不是闭包的局部变量
var = var + 1 # 若 不使用nonlocal 关键字 , 则此行代码会出现错误
|
"""Specifies the supported Bazel versions."""
CURRENT_BAZEL_VERSION = "5.0.0"
OTHER_BAZEL_VERSIONS = [
"6.0.0-pre.20220223.1",
]
SUPPORTED_BAZEL_VERSIONS = [
CURRENT_BAZEL_VERSION,
] + OTHER_BAZEL_VERSIONS
|
def _compile(words):
if not len(words):
return None, ''
num = None
if words[0].isdigit():
num = int(words[0])
words = words[1:]
return num, ' '.join(words)
def _split_out_colons(terms):
newterms = []
for term in terms:
if ':' in term:
subterms = term.split(':')
for sub in subterms:
newterms.append(sub)
newterms.append(':')
newterms = newterms[:-1]
else:
newterms.append(term)
return [term for term in newterms if len(term)]
# parse user command text
def user_command(text):
terms = text.strip().split()
terms = _split_out_colons(terms)
cmd = {}
if len(terms) == 0:
return cmd
cmd['verb'] = terms[0]
mode = 'directobject'
flags = ['with', 'by', 'from', 'for', 'to', ':']
words = []
for term in terms[1:]:
if mode == ':':
words.append(term)
elif term in flags:
num, cmd[mode] = _compile(words)
if not len(cmd[mode]):
cmd.pop(mode)
if num:
cmd[mode+'_num'] = num
words = []
mode = term
else:
words.append(term)
if len(words):
num, cmd[mode] = _compile(words)
if num:
cmd[mode+'_num'] = num
return cmd |
class BankAccount:
def __init__(self, checking = None, savings = None):
self._checking = checking
self._savings = savings
def get_checking(self):
return self._checking
def set_checking(self, new_checking):
self._checking = new_checking
def get_savings(self):
return self._savings
def set_savings(self, new_savings):
self._savings = new_savings
my_account = BankAccount()
my_account.set_checking(523.48)
print(my_account.get_checking())
my_account.set_savings(386.15)
print(my_account.get_savings()) |
"""
LeetCode Problem: 344. Reverse String
Link: https://leetcode.com/problems/reverse-string/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(n)
Space Complexity: O(1)
"""
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
low = 0
high = len(s) - 1
while low < high:
s[low], s[high] = s[high], s[low]
low += 1
high -= 1 |
# 670. 最大交换
#
# 20200905
# huao
class Solution:
def maximumSwap(self, num: int) -> int:
return int(self.maximumSwapStr(str(num)))
def maximumSwapStr(self, num: str) -> str:
s = list(num)
if len(s) == 1:
return num
maxNum = '0'
maxLoc = 0
for i in range(len(s))[::-1]:
c = s[i]
if maxNum < c:
maxNum = c
maxLoc = i
if s[0] == maxNum:
return maxNum + self.maximumSwapStr(num[1:])
s[maxLoc] = s[0]
s[0] = str(maxNum)
ss = ""
for i in s:
ss += i
return ss
print(Solution().maximumSwap(100))
print(Solution().maximumSwap(2736))
print(Solution().maximumSwap(9973))
print(Solution().maximumSwap(98638))
|
# abba
# foo bar bar foo
text1 = list(input())
text2 = input().split()
# text1 = set(text1)
print(text1)
print(text2)
for i in range(len(text1)):
if text1[i] == "a":
text1[i] = 1
else:
text1[i] = 0
for i in range(len(text2)):
if text2[i] == "foo":
text2[i] = 1
else:
text2[i] = 0
print(text1)
print(text2)
if (text1 == text2):
print(True)
else:
print(False)
|
#!/usr/bin/env python3
'''
The MIT License (MIT)
Copyright (c) 2014 Mark Haines
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
def asdata(obj, asdata):
if isinstance(obj, Data):
return obj.asdata(asdata)
elif isinstance(obj, str):
return obj
elif hasattr(obj, '_asdict'):
return asdata(obj._asdict(), asdata)
elif isinstance(obj, dict):
return dict((k, asdata(v, asdata)) for (k, v) in obj.items())
else:
try:
return list(asdata(child, asdata) for child in obj)
except:
return obj
class Data:
def asdata(self, asdata = asdata):
return dict((k, asdata(v, asdata)) for (k, v) in self.__dict__.items())
def __repr__(self):
return self.asdata().__repr__()
|
class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
n = len(A)
g = local = 0
for i in range(1, n):
if A[i] < A[i-1]:
local += 1
if A[i] < i:
diff = i - A[i]
g += diff * (diff+1) // 2
return g == local
|
xval = 0
xvalue1 = 1
xvalue2 = 2
print(xvalue1 + xvalue2)
|
class Order():
def __init__(self, exchCode, sym_, _sym, orderType, price, side, qty, stopPrice=''):
self.odid = None
self.status = None
self.tempOdid = None
self.sym_ = sym_
self._sym = _sym
self.symbol = sym_ + _sym
self.exchCode = exchCode.upper()
self.orderType = orderType
self.price = price
self.fair = -1.0
self.side = side.upper()
self.sign = '+' if self.side == 'BUY' else '-' # for logging only
# self.order_type_id = None # Only for Coinigy
# self.price_type_id = None # Only for Coinigy
self.qty = qty
self.stop_price = stopPrice
self.orderExposure = -1.0
# timestamp
self.createTs = -1.0
self.activeTs = -1.0
self.cxlTs = -1.0
self.cxledTs = -1.0
self.filledTs = -1.0
# for pricing
self.eq = -1.0
# for order handling
self.nbFillQ = 0
self.nbMissingAck = 0
self.nbExtRej = 0
self.nbNone = 0
self.nbFalseActive = 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.