content stringlengths 7 1.05M |
|---|
# help.py
# Metadata
NAME = 'help'
ENABLE = True
PATTERN = '^!help\s*(?P<module_name>.*)$'
USAGE = '''Usage: !help [<module_name> | all]
Either list all the modules or provide the usage message for a particular
module.
'''
# Command
async def help(bot, message, module_name=None):
responses = []
if not module_name or module_name == 'all':
responses = sorted([m.NAME for m in bot.modules])
else:
for module in bot.modules:
if module.NAME == module_name:
responses = module.USAGE.splitlines()
# Suggest responses if none match
if not responses:
responses = sorted([m.NAME for m in bot.modules if module_name in m.NAME])
return [message.copy(body=r, notice=True) for r in responses]
# Register
def register(bot):
return (
('command', PATTERN, help),
)
# vim: set sts=4 sw=4 ts=8 expandtab ft=python:
|
k ,m= 0,0
while True:
try:
line = str(input())
except:
break
if line[0] == '+':
m +=1
elif line[0] == '-':
m -= 1
else:
k += m*len(line[line.index(':')+1::])
print(k)
|
dataset_type = 'SIXrayDataset'
data_root = 'datasets/sixray/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
albu_transforms = [
#dict(type='Equalize',mode='cv',by_channels=False)
#dict(type='Blur')
#dict(type='JpegCompression', quality_lower=10, quality_upper=11)
]
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
#dict(type='custom_MixUp', mixUp_prob=0.5),
dict(type='custom_CutMix', cutMix_prob=0.5, class_targets={1:2, 2:1}),
#dict(type='custom_bboxMixUp', mixUp_prob=0.5),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.0),
#dict(type='RandomFlip', flip_ratio=0.5),
#dict(type='Albu', transforms=albu_transforms),
#dict(type='custom_RandomCrop',crop_type='relative_range', crop_size=(0.75, 0.75)),
#dict(type='Rotate',level=10),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_train2017.json',
img_prefix=data_root + 'train2017/',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_test2017.json',
img_prefix=data_root + 'test2017/',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='bbox')
|
def solution(yourLeft, yourRight, friendsLeft, friendsRight):
'''
EXPLANATION
-------------------------------------------------------------------
Since all values are in question in this problem, I sort both
arrays, and then compare the resultant arrays.
-------------------------------------------------------------------
'''
a = sorted([yourLeft, yourRight])
b = sorted([friendsLeft, friendsRight])
return a == b
def oneline(yourLeft, yourRight, friendsLeft, friendsRight):
'''
EXPLANATION
-------------------------------------------------------------------
chris_l65 from the United States utilized the fact that sets are
displayed as sorted to turn the problem into a one line solution.
Their solution and mine vary under the hood of Python, but the end
result in this context is the same.
-------------------------------------------------------------------
'''
return {yourLeft, yourRight} == {friendsLeft, friendsRight}
|
# Filename:continue.py
while True:
s = input("Just input something:")
if s != "quit":
continue
break
|
"""
Board representation of No Dice Einstein.
"""
COLOR = {
"red": 'R',
"blue": 'B'
}
VALUE = {
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6'
}
MOVE = {
"U": "up",
"D": "down",
"L": "left",
"R": "right",
"X": "diagonal"
}
class Piece:
def __init__(self, row, col, color, value):
self.row = row # the piece's Y-coordinate on the board
self.col = col # the piece's X-coordinate on the board
self.color = color
self.value = value
def __str__(self):
return COLOR[self.color] + VALUE[self.value]
class Board:
def __init__(self, num_of_rows, num_of_cols):
self.NUM_OF_ROWS = num_of_rows
self.NUM_OF_COLS = num_of_cols
self.board = []
for _ in range(self.NUM_OF_ROWS):
newRow = [None] * self.NUM_OF_COLS
self.board.append(newRow)
def print_board(self):
print()
for r in range(self.NUM_OF_ROWS):
for c in range(self.NUM_OF_COLS):
print(self.board[r][c], end = " ")
print()
print()
def __str__(self):
s = ""
for r in range(self.NUM_OF_ROWS):
for c in range(self.NUM_OF_COLS):
if self.board[r][c]:
s = s + str(self.board[r][c]) + ' '
else:
s = s + "." + ' '
s = s + '\n'
return s
def addPiece(self, piece):
self.board[piece.row][piece.col] = piece
def movePiece(self, piece, row, col):
oldRow = piece.row
oldCol = piece.col
self.board[row][col] = self.board[piece.row][piece.col]
self.board[oldRow][oldCol] = None
piece.row = row
piece.col = col
def removePiece(self, piece):
self.board[piece.row][piece.col] = None
del piece
def get_piece(self, row, col):
return self.board[row][col]
def getRedPieces(self):
numberofpieces = 0
for r in range(self.NUM_OF_ROWS):
for c in range(self.NUM_OF_COLS):
if self.board[r][c]:
if self.board[r][c].color == "red":
numberofpieces += 1
return numberofpieces
def getBluePieces(self):
numberofpieces = 0
for r in range(self.NUM_OF_ROWS):
for c in range(self.NUM_OF_COLS):
if self.board[r][c]:
if self.board[r][c].color == "blue":
numberofpieces += 1
return numberofpieces
def getColorFromCoords(self, row, col):
if row>=self.NUM_OF_ROWS or row<0 or col>=self.NUM_OF_COLS or col<0:
return None # (checking boundaries!)
if self.board[row][col] != None:
return self.board[row][col].color
return None
|
'''
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
'''
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) <= 1:
return len(s)
start = 0
maxLen = 0
end = 0
for end in range(len(s)):
findIdx = self.instr(s, start, end)
if findIdx >= 0:
maxLen = max(maxLen, end - start)
start = findIdx + 1
if end > start:
maxLen = max(maxLen, end - start + 1)
return maxLen
def instr(self, s, start, end):
for i in range(start, end):
if s[i] == s[end]:
return i
else:
return -1
s = Solution()
print(s.lengthOfLongestSubstring("abcabcbb") == 3)
print(s.lengthOfLongestSubstring("bbbbb") == 1)
print(s.lengthOfLongestSubstring("pwwkew") == 3)
print(s.lengthOfLongestSubstring("") == 0)
print(s.lengthOfLongestSubstring("pwwkes") == 4)
|
# Python - 3.6.0
Test.assert_equals(fib(1), 0, 'fib(1) failed')
Test.assert_equals(fib(2), 1, 'fib(2) failed')
Test.assert_equals(fib(3), 1, 'fib(3) failed')
Test.assert_equals(fib(4), 2, 'fib(4) failed')
Test.assert_equals(fib(5), 3, 'fib(5) failed')
|
class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles.sort()
n = len(piles)
i, j = 0, n - 1
ans = 0
while i < j:
c = piles[j - 1]
j -= 2
i += 1
ans += c
return ans
|
# Motor control
DRIVE = 0
STEER = 1
# Body
WAIST = 2
HEAD_SWIVEL = 3
HEAD_TILT = 4
# Right arm
RIGHT_SHOULDER = 5
RIGHT_FLAP = 6
RIGHT_ELBOW = 7
RIGHT_WRIST = 8
RIGHT_TWIST = 9
RIGHT_GRIP = 10
# Left arm
LEFT_SHOULDER = 12
LEFT_FLAP = 13
LEFT_ELBOW = 14
LEFT_WRIST = 15
LEFT_TWIST = 16
LEFT_GRIP = 17
|
__author__ = 'katharine'
__version_info__ = (1, 1, 1)
__version__ = '.'.join(map(str, __version_info__))
|
#
# @lc app=leetcode.cn id=121 lang=python3
#
# [121] 买卖股票的最佳时机
#
# https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/
#
# algorithms
# Easy (54.27%)
# Likes: 1077
# Dislikes: 0
# Total Accepted: 241.4K
# Total Submissions: 442.5K
# Testcase Example: '[7,1,5,3,6,4]'
#
# 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
#
# 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
#
# 注意:你不能在买入股票前卖出股票。
#
#
#
# 示例 1:
#
# 输入: [7,1,5,3,6,4]
# 输出: 5
# 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
# 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
#
#
# 示例 2:
#
# 输入: [7,6,4,3,1]
# 输出: 0
# 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
#
#
#
# @lc code=start
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
dp0 = 0
dp1 = float('-inf')
for i in range(len(prices)):
dp0 = max(dp0,dp1+prices[i])
dp1 = max(dp1,-prices[i])
return dp0
# if len(prices) <= 1:
# return 0
# dp = [0]*len(prices)
# for i in range(1,len(prices)):
# for j in range(i):
# dp[i] = max(dp[i-1],prices[i]-prices[j],dp[i])
# return max(dp)
# @lc code=end
# def maxProfit(self, prices: List[int]) -> int:
# n = len(prices)
# if n<=1:
# return 0
# minval = prices[0]
# res = 0
# for i in range(1,n):
# minval = min(prices[i],minval)
# res = max(res,prices[i] - minval)
# return res
|
# Func20.py - Closure
def Calc():
def sum(i,j): return i+j
def sub(i,j): return i-j
def mul(i,j): return i*j
def div(i,j): return i/j
def ans(x,a,b):
if x =='덧셈': return sum(a,b)
elif x =='뺄셈': return sub(a,b)
elif x =='곱셈': return mul(a,b)
elif x =='나눗셈': return div(a,b)
return ans
계산 = Calc()
print(계산('덧셈',30,12))
print(계산('뺄셈',30,12))
print(계산('곱셈',30,12))
print(계산('나눗셈',30,12))
|
# This program will convert given temperatures to different measuring units
print("\nWelcome to the Temperature Conversion App")
temp_f = float(input("What is the temperature in Fahrenheit: "))
# Temperature Conversions
temp_c = (5/9) * (temp_f - 32)
temp_k = temp_c + 273.15
# Round Temperatures to 2 decimal places
temp_f = round(temp_f, 2)
temp_c = round(temp_c, 2)
temp_k = round(temp_k, 2)
# Display summary in a table
print("\nDegrees Fahrenheit:\t" + str(temp_f))
print("Degrees Celsius:\t" + str(temp_c))
print("Degrees Kelvin:\t\t" + str(temp_k))
|
#bilmemkacv2/OPP(object-oriented-programing)
class Account:
def init (self,isim,numara,bakiye):
self.isim = isim
self.numara = numara
self.bakiye = bakiye
def hesapBilgileri(self):
print('İsim: ',self.isim)
print('Numara: ',self.numara)
print('Bakiye: ',self.bakiye)
def paraÇek(self,miktar):
if (self.bakiye - miktar < 0):
print('Yetersiz Baliye')
else:
self.bakiye -= miktar
print('Yeni Bakiye: ',self.bakiye)
def paraYatir(self,miktar):
self.bakiye += miktar
print('Yeni Bakiye: ',self.bakiye)
account = Account('Engin Ege ES',123456,1000)
account.hesapBilgileri()
|
# Those are the field names of the cargo tables of leaguepedia
# Tournament
tournaments_fields = {
"Name",
"DateStart",
"Date",
"Region",
"League",
"Rulebook",
"TournamentLevel",
"IsQualifier",
"IsPlayoffs",
"IsOfficial",
"OverviewPage",
}
# Game
game_fields = {
"GameId",
"MatchId",
"Tournament",
"Team1",
"Team2",
"Winner",
"Gamelength_Number",
"DateTime_UTC",
"Team1Score",
"Team2Score",
"Team1Bans",
"Team2Bans",
"Team1Picks",
"Team2Picks",
"Team1Players",
"Team2Players",
"Team1Dragons",
"Team2Dragons",
"Team1Barons",
"Team2Barons",
"Team1Towers",
"Team2Towers",
"Team1RiftHeralds",
"Team2RiftHeralds",
"Team1Inhibitors",
"Team2Inhibitors",
"Patch",
"MatchHistory",
"VOD",
"Gamename",
"N_GameInMatch",
"OverviewPage",
}
# Game Player
game_players_fields = {
"ScoreboardPlayers.Name=gameName",
"ScoreboardPlayers.Role_Number=gameRoleNumber",
"ScoreboardPlayers.Champion",
"ScoreboardPlayers.Side",
"Players.Name=irlName",
"Players.Country",
"Players.Birthdate",
"Players.ID=currentGameName",
# "Players.Image",
# "Players.Team=currentTeam",
# "Players.Role=currentRole",
# "Players.SoloqueueIds",
}
# Ordered in the draft order for pro play as of June 2020
picks_bans_fields = [
"Team1Ban1",
"Team2Ban1",
"Team1Ban2",
"Team2Ban2",
"Team1Ban3",
"Team2Ban3",
"Team1Pick1",
"Team2Pick1",
"Team2Pick2",
"Team1Pick2",
"Team1Pick3",
"Team2Pick3",
"Team2Ban4",
"Team1Ban4",
"Team2Ban5",
"Team1Ban5",
"Team2Pick4",
"Team1Pick4",
"Team1Pick5",
"Team2Pick5",
]
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
# Compute all values of pairs
# 1000
# compute all nodes
# tree to graph
graph = collections.defaultdict(list)
leafs = set()
def dfs(node):
if node is not None:
if node.left is None and node.right is None:
leafs.add(node)
if node.left is not None:
graph[node].append(node.left)
graph[node.left].append(node)
dfs(node.left)
if node.right is not None:
graph[node].append(node.right)
graph[node.right].append(node)
dfs(node.right)
dfs(root)
# print([node.val for node in leafs])
self.cnt = 0
def bfs(node):
seen = {node}
frontier = [node]
k = distance
while frontier:
next_level = []
for u in frontier:
for v in graph[u]:
if v not in seen:
seen.add(v)
next_level.append(v)
self.cnt += v in leafs
frontier = next_level
if k == 1:
break
k -= 1
for node in leafs:
bfs(node)
return self.cnt // 2
|
class Game(dict):
def __init__(self, **kw):
dict.__init__(self, kw)
self.__dict__.update(kw)
# Assigned via game.xml
self.home_team= None
self.away_team = None
self.stadium = None
# Assigned via ????
self.innings = []
# Assigned Via game_events.xml
self.at_bats = []
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 15:17:43 2020
@author: runner
"""
def my_addition(a, b):
return a+b
print('10+2=12 ?',my_addition(10,2)) |
class UnionFind:
def __init__(self,n):
self.par=[-1]*n
self.siz=[1]*n
#根を求める
def root(self,x):
if self.par[x] == -1:
return x
else:
#経路圧縮
self.par[x]=self.root(self.par[x])
return self.par[x]
#グループ判定(根が一致するかどうか)
def issame(self,x,y):
return self.root(x) == self.root(y)
#xとyを併合する
def unite(self,x,y):
#根まで移動する
x=self.root(x)
y=self.root(y)
if x==y:
return False
#union by size(y側のサイズを小さく)
if self.siz[x] < self.siz[y]:
tmp=y
y=x
x=tmp
self.par[y]=x
self.siz[x] += self.siz[y]
return True
#xを含むグループのサイズ
def size(self,x):
return self.siz[self.root(x)]
if __name__ == '__main__':
uf=UnionFind(7)
uf.unite(1,2)
uf.unite(2,3)
uf.unite(5,6)
print(uf.issame(1,3))
print(uf.issame(2,5))
uf.unite(1,6)
print(uf.issame(2,5)) |
######################################################
# schema
schemaclipboard = None
SCHEMA_WRITE_PREFERENCE_DEFAULTS = [
{"key":"addchild","display":"Add child","default":True},
{"key":"remove","display":"Remove","default":True},
{"key":"childsopened","display":"Childs opened","default":False},
{"key":"editenabled","display":"Edit enabled","default":True},
{"key":"editkey","display":"Edit key","default":True},
{"key":"editvalue","display":"Edit value","default":True},
{"key":"radio","display":"Radio","default":False},
{"key":"slider","display":"Slider","default":False},
{"key":"check","display":"Check","default":False},
{"key":"showhelpashtml","display":"Show help as HTML","default":True}
]
class SchemaWritePreference:
def __init__(self):
for item in SCHEMA_WRITE_PREFERENCE_DEFAULTS:
self[item["key"]] = item["default"]
self.parent = None
self.changecallback = None
self.disabledlist = []
def setparent(self, parent):
self.parent = parent
return self
def setchangecallback(self, changecallback):
self.changecallback = changecallback
return self
def changed(self):
if not ( self.changecallback is None ):
self.changecallback()
def setdisabledlist(self, disabledlist):
self.disabledlist = disabledlist
return self
def form(self):
formdiv = Div().ac("noselect")
mdl = self.disabledlist
if not ( self.parent is None ):
if self.parent.parent is None:
mdl = mdl + ["editkey"]
for item in SCHEMA_WRITE_PREFERENCE_DEFAULTS:
if not ( item["key"] in mdl ):
formdiv.a(LabeledLinkedCheckBox(item["display"], self, item["key"], {
"patchclasses":["container/a/schemawritepreferenceformsubdiv"],
"changecallback": self.changed
}))
return formdiv
def toobj(self):
obj = {}
for item in SCHEMA_WRITE_PREFERENCE_DEFAULTS:
obj[item["key"]] = self[item["key"]]
return obj
DEFAULT_HELP = "No help available for this item."
DEFAULT_ENABLED = True
class SchemaItem(e):
def parentsettask(self):
pass
def setparent(self, parent):
self.parent = parent
self.parentsettask()
def getitem(self):
return self
def label(self):
return ""
def baseobj(self):
obj = {
"kind": self.kind,
"enabled": self.enabled,
"help": self.help,
"writepreference": self.writepreference.toobj()
}
return obj
def toobj(self):
return self.baseobj()
def topureobj(self):
pureobj = {}
return pureobj
def enablechangedtask():
pass
def enablecallback(self):
self.enabled = self.enablecheckbox.getchecked()
if not ( self.childparent is None ):
if self.childparent.writepreference.radio:
self.childparent.setradio(self)
self.childparent.enablechangedtask()
self.enablechangedtask()
def setenabled(self, enabled):
self.enabled = enabled
self.enablecheckbox.setchecked(self.enabled)
def helpboxclicked(self):
if self.helpopen:
self.helphook.x()
self.helpopen = False
else:
self.helpdiv = Div().ac("schemahelpdiv")
self.helpcontentdiv = Div().aac(["schemahelpcontentdiv","noselect"]).html(self.help)
self.helpeditdiv = Div().ac("schemahelpeditdiv")
self.helpedittextarea = LinkedTextarea(self, "help", {"patchclasses":["textarea/a/schemahelpedittextarea"],"text":self.help})
self.helpeditdiv.a(self.helpedittextarea)
if self.writepreference.showhelpashtml:
self.helpdiv.a(self.helpcontentdiv)
else:
self.helpdiv.a(self.helpeditdiv)
self.helphook.a(self.helpdiv)
self.helpopen = True
def copyboxclicked(self):
schemaclipboard.copy(self)
def settingsboxclicked(self):
if self.settingsopen:
self.settingshook.x()
self.settingsopen = False
else:
self.settingsdiv = Div().ac("schemasettingsdiv").a(self.writepreference.form())
self.settingshook.a(self.settingsdiv)
self.settingsopen = True
def removeboxclicked(self):
self.childparent.remove(self)
pass
def writepreferencechangedtask(self):
pass
def writepreferencechanged(self):
self.helpboxclicked()
self.helpboxclicked()
self.enablecheckbox.able(self.writepreference.editenabled)
self.setchildparent(self.childparent)
self.writepreferencechangedtask()
if not ( self.parent is None ):
self.parent.writepreferencechangedtask()
def setchildparent(self, childparent):
self.childparent = childparent
if ( not ( self.childparent is None ) ) and self.writepreference.remove:
self.schemacontainer.x().aa([self.enablebox, self.element, self.helpbox, self.copybox, self.settingsbox, self.removebox])
else:
self.schemacontainer.x().aa([self.enablebox, self.element, self.helpbox, self.copybox, self.settingsbox])
def elementdragstart(self, ev):
self.dragstartvect = getClientVect(ev)
def elementdrag(self, ev):
pass
def move(self, dir):
if self.childparent is None:
return
i = self.childparent.getitemindex(self)
newi = i + dir
self.childparent.movechildi(i, newi)
def elementdragend(self, ev):
self.dragendvect = getClientVect(ev)
diff = self.dragendvect.m(self.dragstartvect)
dir = int(diff.y / getglobalcssvarpxint("--schemabase"))
self.move(dir)
def __init__(self, args):
super().__init__("div")
self.parent = None
self.childparent = None
self.args = args
self.kind = "item"
self.enabled = args.get("enabled", DEFAULT_ENABLED)
self.help = args.get("help", DEFAULT_HELP)
self.writepreference = args.get("writepreference", SchemaWritePreference())
self.writepreference.setparent(self)
self.writepreference.setchangecallback(self.writepreferencechanged)
self.element = Div().ac("schemaitem")
self.schemacontainer = Div().ac("schemacontainer")
self.enablebox = Div().ac("schemaenablebox")
self.enablecheckbox = CheckBox(self.enabled).ac("schemaenablecheckbox").ae("change", self.enablecallback)
self.enablecheckbox.able(self.writepreference.editenabled)
self.enablebox.a(self.enablecheckbox)
self.helpbox = Div().aac(["schemahelpbox","noselect"]).ae("mousedown", self.helpboxclicked).html("?")
self.copybox = Div().aac(["schemacopybox","noselect"]).ae("mousedown", self.copyboxclicked).html("C")
self.settingsbox = Div().aac(["schemasettingsbox","noselect"]).ae("mousedown", self.settingsboxclicked).html("S")
self.removebox = Div().aac(["schemaremovebox","noselect"]).ae("mousedown", self.removeboxclicked).html("X")
self.afterelementhook = Div()
self.settingsopen = args.get("settingsopen", False)
self.helpopen = args.get("helpopen", False)
self.settingshook = Div()
self.helphook = Div()
self.schemacontainer.aa([self.enablebox, self.element, self.helpbox, self.copybox, self.settingsbox])
self.itemcontainer = Div()
self.itemcontainer.aa([self.schemacontainer, self.helphook, self.settingshook, self.afterelementhook])
self.a(self.itemcontainer)
self.dragelement = self.copybox
self.dragelement.sa("draggable", True)
self.dragelement.ae("dragstart", self.elementdragstart)
self.dragelement.ae("drag", self.elementdrag)
self.dragelement.ae("dragend", self.elementdragend)
self.dragelement.ae("dragover", lambda ev: ev.preventDefault())
class NamedSchemaItem(e):
def getitem(self):
return self.item
def label(self):
return self.key
def toobj(self):
return {
"kind": "nameditem",
"key": self.key,
"item": self.item.toobj()
}
def writepreferencechangedtask(self):
self.linkedtextinput.able(self.item.writepreference.editkey)
def keychanged(self):
if not ( self.keychangedcallback is None ):
self.keychangedcallback()
def setkeychangedcallback(self, keychangedcallback):
self.keychangedcallback = keychangedcallback
return self
def setkey(self, key):
self.key = key
self.linkedtextinput.setText(self.key)
return self
def __init__(self, args):
super().__init__("div")
self.kind = "nameditem"
#self.key = args.get("key", uid())
self.key = args.get("key", "")
self.item = args.get("item", SchemaItem(args))
self.keychangedcallback = None
self.item.setparent(self)
self.namedcontainer = Div().ac("namedschemaitem")
self.namediv = Div().ac("schemaitemname")
self.linkedtextinput = LinkedTextInput(self, "key", {
"textclass": "namedschemaitemrawtextinput",
"keyupcallback": self.keychanged
})
self.linkedtextinput.setText(self.key)
self.linkedtextinput.able(self.item.writepreference.editkey)
self.namediv.a(self.linkedtextinput)
self.namedcontainer.aa([self.namediv, self.item])
self.a(self.namedcontainer)
def copy(self, item):
self.item = schemafromobj(item.toobj())
self.item.parent = None
self.key = None
if not ( item.parent is None ):
self.key = item.parent.key
class SchemaScalar(SchemaItem):
def label(self):
return self.value
def toobj(self):
obj = self.baseobj()
obj["value"] = self.value
obj["minvalue"] = self.minvalue
obj["maxvalue"] = self.maxvalue
return obj
def topureobj(self):
obj = self.value
return obj
def writepreferencechangedtask(self):
self.build()
def enablechangedtask(self):
if self.writepreference.check:
if self.enabled:
self.value = "true"
else:
self.value = "false"
self.linkedtextinput.setText(self.value)
def build(self):
if self.writepreference.slider:
self.enablecheckbox.rc("schemacheckenablecheckbox")
self.linkedslider = LinkedSlider(self, "value", {
"containerclass": "schemalinkedslidercontainerclass",
"valuetextclass": "schemalinkedslidervaluetextclass",
"mintextclass": "schemalinkedslidermintextclass",
"sliderclass": "schemalinkedslidersliderclass",
"maxtextclass": "schemalinkedslidermaxtextclass"
})
self.element.x().aa([self.linkedslider])
else:
self.enablebox.arc(self.writepreference.check, "schemacheckenablecheckbox")
self.linkedtextinput = LinkedTextInput(self, "value", {"textclass":"schemascalarrawtextinput"})
self.linkedtextinput.able(self.writepreference.editvalue)
self.element.x().aa([self.linkedtextinput])
def __init__(self, args):
super().__init__(args)
self.kind = "scalar"
#self.value = args.get("value", randscalarvalue(2, 8))
self.value = args.get("value", "")
self.minvalue = args.get("minvalue", 1)
self.maxvalue = args.get("maxvalue", 100)
self.element.ac("schemascalar")
self.writepreference.setdisabledlist(["addchild","childsopened","radio"])
self.build()
class SchemaCollection(SchemaItem):
def removechildi(self, i):
newchilds = []
rchild = None
for j in range(0, len(self.childs)):
if ( j == i ):
rchild = self.childs[j]
else:
newchilds.append(self.childs[j])
self.childs = newchilds
self.openchilds()
self.openchilds()
return rchild
def insertchildi(self, i, child):
newchilds = []
for j in range(0, len(self.childs) + 1):
if ( j == i ):
newchilds.append(child)
if ( j < len(self.childs) ):
newchilds.append(self.childs[j])
self.childs = newchilds
self.openchilds()
self.openchilds()
def movechildi(self, i, newi):
if len(self.childs) <= 0:
return
if newi < 0:
newi = 0
if newi >= len(self.childs):
newi = len(self.childs) - 1
rchild = self.removechildi(i)
if not ( rchild is None ):
self.insertchildi(newi, rchild)
def getitemindex(self, item):
for i in range(0, len(self.childs)):
if self.childs[i].getitem() == item:
return i
return None
def parentsettask(self):
self.opendiv.arc(not self.parent is None, "schemadictchildleftmargin")
def enablechangedtask(self):
self.openchilds()
self.openchilds()
def buildchilds(self):
labellist = []
self.childshook.x()
for child in self.childs:
self.childshook.a(child)
if child.getitem().enabled:
labellist.append(child.label())
label = " , ".join(labellist)
self.openbutton.x().a(Div().ac("schemacollectionopenbuttonlabel").html(label))
def topureobj(self):
pureobj = {}
if self.writepreference.radio:
if self.kind == "dict":
pureobj = ["", {}]
for nameditem in self.childs:
key = nameditem.key
item = nameditem.item
if item.enabled or item.writepreference.check:
pureobj = [key, item.topureobj()]
break
elif self.kind == "list":
for item in self.childs:
if item.enabled or item.writepreference.check:
pureobj = item.topureobj()
break
else:
if self.kind == "dict":
for nameditem in self.childs:
key = nameditem.key
item = nameditem.item
if item.enabled or item.writepreference.check:
pureobj[key] = item.topureobj()
elif self.kind == "list":
pureobj = []
for item in self.childs:
if item.enabled or item.writepreference.check:
pureobj.append(item.topureobj())
return pureobj
def setradio(self, item):
for child in self.childs:
childitem = child.getitem()
childeq = ( childitem == item )
childitem.enabled = childeq
childitem.enablecheckbox.setchecked(childeq)
def remove(self, item):
newlist = []
for child in self.childs:
childeq = False
if child.kind == "nameditem":
childeq = ( child.item == item )
else:
childeq = ( child == item )
if not childeq:
newlist.append(child)
self.childs = newlist
self.openchilds()
self.openchilds()
def getschemakinds(self):
schemakinds = {
"create" : "Create new",
"scalar" : "Scalar",
"list" : "List",
"dict" : "Dict"
}
for nameditem in self.childs:
key = nameditem.key
if not ( key == None ):
if len(key) > 0:
schemakinds["#" + key] = key
return schemakinds
def updatecreatecombo(self):
if not ( self.createcombo is None ):
self.createcombo.setoptions(self.getschemakinds())
def getchildbykey(self, key):
if not ( self.kind == "dict" ):
return None
for nameditem in self.childs:
if nameditem.key == key:
return nameditem.item
return None
def createcallback(self, key):
self.updatecreatecombo()
sch = SchemaScalar({})
if key == "list":
sch = SchemaList({})
elif key == "dict":
sch = SchemaDict({})
if key[0] == "#":
truekey = key[1:]
titem = self.getchildbykey(truekey)
if titem == None:
print("error, no item with key", truekey)
else:
sch = schemafromobj(titem.toobj())
sch.setchildparent(self)
appendelement = sch
if self.kind == "dict":
appendelement = NamedSchemaItem({
"item": sch
}).setkeychangedcallback(self.updatecreatecombo)
self.childs.append(appendelement)
self.buildchilds()
self.updatecreatecombo()
def pastebuttonclicked(self):
try:
sch = schemafromobj(schemaclipboard.item.toobj())
except:
window.alert("No item on clipboard to paste!")
return self
sch.setchildparent(self)
appendelement = sch
if self.kind == "dict":
appendelement = NamedSchemaItem({
"item": sch
}).setkeychangedcallback(self.updatecreatecombo)
if not ( schemaclipboard.key is None ):
appendelement.setkey(schemaclipboard.key)
self.childs.append(appendelement)
self.buildchilds()
self.updatecreatecombo()
def openchilds(self):
if self.opened:
self.opened = False
self.createhook.x()
self.childshook.x()
self.openbutton.rc("schemacollectionopenbuttondone")
else:
self.opened = True
self.creatediv = Div().ac("schemaitem").ac("schemacreate")
self.createcombo = ComboBox({
"changecallback": self.createcallback,
"selectclass": "schemacreatecomboselect"
})
self.updatecreatecombo()
self.pastebutton = Button("Paste", self.pastebuttonclicked).ac("schemapastebutton")
self.creatediv.aa([self.createcombo, self.pastebutton])
if self.writepreference.addchild:
self.createhook.a(self.creatediv)
self.openbutton.ac("schemacollectionopenbuttondone")
self.buildchilds()
def writepreferencechangedtask(self):
self.openchilds()
self.openchilds()
def __init__(self, args):
super().__init__(args)
self.kind = "collection"
self.opened = False
self.childs = args.get("childs", [])
self.editmode = args.get("editmode", False)
self.childseditable = args.get("childseditable", True)
self.element.ac("schemacollection")
self.openbutton = Div().aac(["schemacollectionopenbutton","noselect"]).ae("mousedown", self.openchilds)
self.element.aa([self.openbutton])
self.createcombo = None
self.createhook = Div()
self.childshook = Div()
self.opendiv = Div().ac("schemacollectionopendiv")
self.opendiv.aa([self.createhook, self.childshook])
self.afterelementhook.a(self.opendiv)
self.openchilds()
if not self.writepreference.childsopened:
self.openchilds()
class SchemaList(SchemaCollection):
def getfirstselectedindex(self):
i = 0
for item in self.childs:
if item.enabled:
return i
i+=1
return None
def toobj(self):
listobj = []
for item in self.childs:
listobj.append(item.toobj())
obj = self.baseobj()
obj["items"] = listobj
return obj
def __init__(self, args):
super().__init__(args)
self.kind = "list"
self.element.ac("schemalist")
self.writepreference.setdisabledlist(["editvalue", "slider", "check"])
class SchemaDict(SchemaCollection):
def setchildatkey(self, key, item):
item.setchildparent(self)
nameditem = NamedSchemaItem({
"key": key,
"item": item
})
i = self.getitemindexbykey(key)
if i is None:
self.childs.append(nameditem)
else:
self.childs[i] = nameditem
self.openchilds()
self.openchilds()
def getfirstselectedindex(self):
i = 0
for item in self.childs:
if item.item.enabled:
return i
i+=1
return None
def getitemindexbykey(self, key):
i = 0
for item in self.childs:
if item.key == key:
return i
i+=1
return None
def toobj(self):
dictobj = []
for item in self.childs:
sch = {
"key": item.key,
"item": item.item.toobj()
}
dictobj.append(sch)
obj = self.baseobj()
obj["items"] = dictobj
return obj
def __init__(self, args):
super().__init__(args)
self.kind = "dict"
self.element.ac("schemadict")
self.writepreference.setdisabledlist(["editvalue", "slider", "check"])
def schemawritepreferencefromobj(obj):
swp = SchemaWritePreference()
for item in SCHEMA_WRITE_PREFERENCE_DEFAULTS:
swp[item["key"]] = getfromobj(obj, item["key"], item["default"])
return swp
def schemafromobj(obj):
kind = getfromobj(obj, "kind", "dict")
enabled = getfromobj(obj, "enabled", DEFAULT_ENABLED)
help = getfromobj(obj, "help", DEFAULT_HELP)
writepreference = schemawritepreferencefromobj(getfromobj(obj, "writepreference", {}))
returnobj = {}
if kind == "scalar":
returnobj = SchemaScalar({
"value": obj["value"],
"minvalue": obj["minvalue"],
"maxvalue": obj["maxvalue"],
"writepreference": writepreference
})
elif kind == "list":
items = obj["items"]
childs = []
for item in items:
sch = schemafromobj(item)
childs.append(sch)
returnobj = SchemaList({
"childs": childs,
"writepreference": writepreference
})
for child in returnobj.childs:
child.setchildparent(returnobj)
elif kind == "dict":
items = obj["items"]
childs = []
for itemobj in items:
key = itemobj["key"]
item = itemobj["item"]
sch = schemafromobj(item)
namedsch = NamedSchemaItem({
"key": key,
"item": sch,
"writepreference": writepreference
})
childs.append(namedsch)
returnobj = SchemaDict({
"childs": childs,
"writepreference": writepreference
})
for child in returnobj.childs:
child.item.setchildparent(returnobj)
child.setkeychangedcallback(returnobj.updatecreatecombo)
returnobj.setenabled(enabled)
returnobj.help = help
return returnobj
def getpathlistfromschema(sch, pathlist):
if len(pathlist)<=0:
return sch
key = pathlist[0]
pathlist = pathlist[1:]
if key == "#":
if sch.kind == "scalar":
return None
elif sch.kind == "list":
i = sch.getfirstselectedindex()
if i == None:
return None
return getpathlistfromschema(sch.childs[i], pathlist)
elif sch.kind == "dict":
i = sch.getfirstselectedindex()
if i == None:
return None
return getpathlistfromschema(sch.childs[i].item, pathlist)
else:
if sch.kind == "scalar":
return None
elif sch.kind == "list":
return None
elif sch.kind == "dict":
for child in sch.childs:
if child.key == key:
return getpathlistfromschema(child.item, pathlist)
return None
def getpathfromschema(sch, path):
pathlist = path.split("/")
return getpathlistfromschema(sch, pathlist)
def getscalarfromschema(sch, path):
found = getpathfromschema(sch, path)
if not ( found is None ):
if found.kind == "scalar":
return found.value
found = getpathfromschema(sch, path + "/#")
if not ( found is None ):
if found.kind == "scalar":
return found.value
return None
def schemafromucioptionsobj(obj):
ucioptions = SchemaDict({})
for opt in obj:
key = opt["key"]
kind = opt["kind"]
default = opt["default"]
min = opt["min"]
max = opt["max"]
options = opt["options"]
item = SchemaScalar({
"value": default
})
if kind == "spin":
item.minvalue = min
item.maxvalue = max
item.writepreference.slider = True
item.build()
elif kind == "check":
item.value = "false"
if default:
item.value = "true"
item.writepreference.check = True
item.setenabled(default)
item.build()
elif kind == "combo":
item = SchemaList({})
item.writepreference.radio = True
for comboopt in options:
comboitem = SchemaScalar({
"value": comboopt
})
comboitem.setenabled(comboopt == default)
comboitem.setchildparent(item)
item.childs.append(comboitem)
item.openchilds()
item.openchilds()
item.setchildparent(ucioptions)
nameditem = NamedSchemaItem({
"key": key,
"item": item
})
ucioptions.childs.append(nameditem)
return ucioptions
schemaclipboard = NamedSchemaItem({})
######################################################
|
# encoding: utf-8
class DummyResponse(object):
status_code = 250
class DummyBackend(object):
def __init__(self, **kw):
pass
def sendmail(self, **kw):
return DummyResponse()
|
class NetworkInfoEntry(object):
def __init__(self):
self.bytes = 0
self.packets = 0
self.error = 0
self.drop = 0
class NetworkLogEntry(object):
def __init__(self):
self.name = ""
self.rx = NetworkInfoEntry()
self.tx = NetworkInfoEntry()
class DomainLogEntry(object):
def __init__(self):
self.name = ""
self.cpu_seconds = 0
self.memory = 0
self.memory_percent = 0.0
self.max_memory = 0
self.max_memory_percent = 0.0
self.virtual_cpus = 0
self.networks = []
def __str__(self):
result = self.name
for network in self.networks:
result += ", " + network.name + " (RX:" + str(network.rx.bytes/1024/1024/1024) +"gb, TX:" + str(network.tx.bytes/1024/1024/1024) + "gb)"
return result
|
class Ball:
def __init__(self, x0, y0, r0):
self.x = x0
self.y = y0
self.r = r0
return
def distance(self, x0, y0):
return ((self.x-x0)**2. + (self.y-y0)**2.)**(0.5)
def distance_from_origin(self):
return self.distance(0,0)
def __str__(self):
out_str = "Radius = {}\n".format(self.r)
out_str += "Position = ({},{})".format(self.x, self.y)
return out_str
if __name__ == "__main__":
ball = Ball(3, 4, 3)
dist = ball.distance_from_origin()
print(ball)
|
#
# PySNMP MIB module CABH-CDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CABH-CDP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:26:22 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)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint")
clabProjCableHome, = mibBuilder.importSymbols("CLAB-DEF-MIB", "clabProjCableHome")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
NotificationType, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Counter64, MibIdentifier, Bits, ObjectIdentity, Integer32, Counter32, Unsigned32, IpAddress, ModuleIdentity, iso = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Counter64", "MibIdentifier", "Bits", "ObjectIdentity", "Integer32", "Counter32", "Unsigned32", "IpAddress", "ModuleIdentity", "iso")
DisplayString, PhysAddress, TruthValue, TextualConvention, RowStatus, DateAndTime, TimeStamp = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "PhysAddress", "TruthValue", "TextualConvention", "RowStatus", "DateAndTime", "TimeStamp")
cabhCdpMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4))
if mibBuilder.loadTexts: cabhCdpMib.setLastUpdated('200412160000Z')
if mibBuilder.loadTexts: cabhCdpMib.setOrganization('CableLabs Broadband Access Department')
cabhCdpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1))
cabhCdpBase = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1))
cabhCdpAddr = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2))
cabhCdpServer = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3))
cabhCdpSetToFactory = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 1), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpSetToFactory.setStatus('current')
cabhCdpLanTransCurCount = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpLanTransCurCount.setStatus('current')
cabhCdpLanTransThreshold = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65533))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpLanTransThreshold.setStatus('current')
cabhCdpLanTransAction = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("noAssignment", 2))).clone('normal')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpLanTransAction.setStatus('current')
cabhCdpWanDataIpAddrCount = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 63))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpWanDataIpAddrCount.setStatus('current')
cabhCdpLastSetToFactory = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 6), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpLastSetToFactory.setStatus('current')
cabhCdpTimeOffsetSelection = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("useDhcpOption2", 1), ("useSnmpSetOffset", 2))).clone('useDhcpOption2')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpTimeOffsetSelection.setStatus('current')
cabhCdpSnmpSetTimeOffset = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-43200, 46800))).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpSnmpSetTimeOffset.setStatus('current')
cabhCdpDaylightSavingTimeEnable = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpDaylightSavingTimeEnable.setStatus('current')
cabhCdpLanAddrTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1), )
if mibBuilder.loadTexts: cabhCdpLanAddrTable.setStatus('current')
cabhCdpLanAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1), ).setIndexNames((0, "CABH-CDP-MIB", "cabhCdpLanAddrIpType"), (0, "CABH-CDP-MIB", "cabhCdpLanAddrIp"))
if mibBuilder.loadTexts: cabhCdpLanAddrEntry.setStatus('current')
cabhCdpLanAddrIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1, 1), InetAddressType())
if mibBuilder.loadTexts: cabhCdpLanAddrIpType.setStatus('current')
cabhCdpLanAddrIp = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1, 2), InetAddress())
if mibBuilder.loadTexts: cabhCdpLanAddrIp.setStatus('current')
cabhCdpLanAddrClientID = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1, 3), PhysAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cabhCdpLanAddrClientID.setStatus('current')
cabhCdpLanAddrLeaseCreateTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1, 4), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpLanAddrLeaseCreateTime.setStatus('current')
cabhCdpLanAddrLeaseExpireTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1, 5), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpLanAddrLeaseExpireTime.setStatus('current')
cabhCdpLanAddrMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("mgmtReservationInactive", 1), ("mgmtReservationActive", 2), ("dynamicInactive", 3), ("dynamicActive", 4), ("psReservationInactive", 5), ("psReservationActive", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpLanAddrMethod.setStatus('current')
cabhCdpLanAddrHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpLanAddrHostName.setStatus('current')
cabhCdpLanAddrRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cabhCdpLanAddrRowStatus.setStatus('current')
cabhCdpWanDataAddrTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2), )
if mibBuilder.loadTexts: cabhCdpWanDataAddrTable.setStatus('current')
cabhCdpWanDataAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1), ).setIndexNames((0, "CABH-CDP-MIB", "cabhCdpWanDataAddrIndex"))
if mibBuilder.loadTexts: cabhCdpWanDataAddrEntry.setStatus('current')
cabhCdpWanDataAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: cabhCdpWanDataAddrIndex.setStatus('current')
cabhCdpWanDataAddrClientId = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 80))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cabhCdpWanDataAddrClientId.setStatus('current')
cabhCdpWanDataAddrIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1, 3), InetAddressType().clone('ipv4')).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpWanDataAddrIpType.setStatus('current')
cabhCdpWanDataAddrIp = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1, 4), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpWanDataAddrIp.setStatus('current')
cabhCdpWanDataAddrRenewalTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpWanDataAddrRenewalTime.setStatus('deprecated')
cabhCdpWanDataAddrRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1, 6), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cabhCdpWanDataAddrRowStatus.setStatus('current')
cabhCdpWanDataAddrLeaseCreateTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1, 7), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpWanDataAddrLeaseCreateTime.setStatus('current')
cabhCdpWanDataAddrLeaseExpireTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 2, 1, 8), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpWanDataAddrLeaseExpireTime.setStatus('current')
cabhCdpWanDnsServerTable = MibTable((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 3), )
if mibBuilder.loadTexts: cabhCdpWanDnsServerTable.setStatus('current')
cabhCdpWanDnsServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 3, 1), ).setIndexNames((0, "CABH-CDP-MIB", "cabhCdpWanDnsServerOrder"))
if mibBuilder.loadTexts: cabhCdpWanDnsServerEntry.setStatus('current')
cabhCdpWanDnsServerOrder = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary", 1), ("secondary", 2), ("tertiary", 3))))
if mibBuilder.loadTexts: cabhCdpWanDnsServerOrder.setStatus('current')
cabhCdpWanDnsServerIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 3, 1, 2), InetAddressType().clone('ipv4')).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpWanDnsServerIpType.setStatus('current')
cabhCdpWanDnsServerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 2, 3, 1, 3), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpWanDnsServerIp.setStatus('current')
cabhCdpLanPoolStartType = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 1), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpLanPoolStartType.setStatus('current')
cabhCdpLanPoolStart = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 2), InetAddress().clone(hexValue="c0a8000a")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpLanPoolStart.setStatus('current')
cabhCdpLanPoolEndType = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 3), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpLanPoolEndType.setStatus('current')
cabhCdpLanPoolEnd = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 4), InetAddress().clone(hexValue="c0a800fe")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpLanPoolEnd.setStatus('current')
cabhCdpServerNetworkNumberType = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 5), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerNetworkNumberType.setStatus('current')
cabhCdpServerNetworkNumber = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 6), InetAddress().clone(hexValue="c0a80000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerNetworkNumber.setStatus('current')
cabhCdpServerSubnetMaskType = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 7), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerSubnetMaskType.setStatus('current')
cabhCdpServerSubnetMask = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 8), InetAddress().clone(hexValue="ffffff00")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerSubnetMask.setStatus('current')
cabhCdpServerTimeOffset = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-86400, 86400))).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerTimeOffset.setStatus('current')
cabhCdpServerRouterType = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 10), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerRouterType.setStatus('current')
cabhCdpServerRouter = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 11), InetAddress().clone(hexValue="c0a80001")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerRouter.setStatus('current')
cabhCdpServerDnsAddressType = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 12), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerDnsAddressType.setStatus('current')
cabhCdpServerDnsAddress = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 13), InetAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerDnsAddress.setStatus('current')
cabhCdpServerSyslogAddressType = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 14), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerSyslogAddressType.setStatus('current')
cabhCdpServerSyslogAddress = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 15), InetAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerSyslogAddress.setStatus('current')
cabhCdpServerDomainName = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 16), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerDomainName.setStatus('current')
cabhCdpServerTTL = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255)).clone(64)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerTTL.setStatus('current')
cabhCdpServerInterfaceMTU = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(68, 4096), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerInterfaceMTU.setStatus('current')
cabhCdpServerVendorSpecific = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 19), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerVendorSpecific.setStatus('current')
cabhCdpServerLeaseTime = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 20), Unsigned32().clone(3600)).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerLeaseTime.setStatus('current')
cabhCdpServerDhcpAddressType = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 21), InetAddressType().clone('ipv4')).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpServerDhcpAddressType.setStatus('current')
cabhCdpServerDhcpAddress = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 22), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpServerDhcpAddress.setStatus('current')
cabhCdpServerControl = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("restoreConfig", 1), ("commitConfig", 2))).clone('restoreConfig')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerControl.setStatus('current')
cabhCdpServerCommitStatus = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("commitSucceeded", 1), ("commitNeeded", 2), ("commitFailed", 3))).clone('commitSucceeded')).setMaxAccess("readonly")
if mibBuilder.loadTexts: cabhCdpServerCommitStatus.setStatus('current')
cabhCdpServerUseCableDataNwDnsAddr = MibScalar((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 1, 3, 25), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cabhCdpServerUseCableDataNwDnsAddr.setStatus('current')
cabhCdpNotification = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 2))
cabhCdpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 2, 0))
cabhCdpConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 3))
cabhCdpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 3, 1))
cabhCdpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 3, 2))
cabhCdpBasicCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 3, 1, 3)).setObjects(("CABH-CDP-MIB", "cabhCdpGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cabhCdpBasicCompliance = cabhCdpBasicCompliance.setStatus('current')
cabhCdpGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4491, 2, 4, 4, 3, 2, 1)).setObjects(("CABH-CDP-MIB", "cabhCdpSetToFactory"), ("CABH-CDP-MIB", "cabhCdpLanTransCurCount"), ("CABH-CDP-MIB", "cabhCdpLanTransThreshold"), ("CABH-CDP-MIB", "cabhCdpLanTransAction"), ("CABH-CDP-MIB", "cabhCdpWanDataIpAddrCount"), ("CABH-CDP-MIB", "cabhCdpLastSetToFactory"), ("CABH-CDP-MIB", "cabhCdpTimeOffsetSelection"), ("CABH-CDP-MIB", "cabhCdpSnmpSetTimeOffset"), ("CABH-CDP-MIB", "cabhCdpDaylightSavingTimeEnable"), ("CABH-CDP-MIB", "cabhCdpLanAddrClientID"), ("CABH-CDP-MIB", "cabhCdpLanAddrLeaseCreateTime"), ("CABH-CDP-MIB", "cabhCdpLanAddrLeaseExpireTime"), ("CABH-CDP-MIB", "cabhCdpLanAddrMethod"), ("CABH-CDP-MIB", "cabhCdpLanAddrHostName"), ("CABH-CDP-MIB", "cabhCdpLanAddrRowStatus"), ("CABH-CDP-MIB", "cabhCdpWanDataAddrClientId"), ("CABH-CDP-MIB", "cabhCdpWanDataAddrIpType"), ("CABH-CDP-MIB", "cabhCdpWanDataAddrIp"), ("CABH-CDP-MIB", "cabhCdpWanDataAddrRowStatus"), ("CABH-CDP-MIB", "cabhCdpWanDataAddrLeaseCreateTime"), ("CABH-CDP-MIB", "cabhCdpWanDataAddrLeaseExpireTime"), ("CABH-CDP-MIB", "cabhCdpWanDnsServerIpType"), ("CABH-CDP-MIB", "cabhCdpWanDnsServerIp"), ("CABH-CDP-MIB", "cabhCdpLanPoolStartType"), ("CABH-CDP-MIB", "cabhCdpLanPoolStart"), ("CABH-CDP-MIB", "cabhCdpLanPoolEndType"), ("CABH-CDP-MIB", "cabhCdpLanPoolEnd"), ("CABH-CDP-MIB", "cabhCdpServerNetworkNumberType"), ("CABH-CDP-MIB", "cabhCdpServerNetworkNumber"), ("CABH-CDP-MIB", "cabhCdpServerSubnetMaskType"), ("CABH-CDP-MIB", "cabhCdpServerSubnetMask"), ("CABH-CDP-MIB", "cabhCdpServerTimeOffset"), ("CABH-CDP-MIB", "cabhCdpServerRouterType"), ("CABH-CDP-MIB", "cabhCdpServerRouter"), ("CABH-CDP-MIB", "cabhCdpServerDnsAddressType"), ("CABH-CDP-MIB", "cabhCdpServerDnsAddress"), ("CABH-CDP-MIB", "cabhCdpServerSyslogAddressType"), ("CABH-CDP-MIB", "cabhCdpServerSyslogAddress"), ("CABH-CDP-MIB", "cabhCdpServerDomainName"), ("CABH-CDP-MIB", "cabhCdpServerTTL"), ("CABH-CDP-MIB", "cabhCdpServerInterfaceMTU"), ("CABH-CDP-MIB", "cabhCdpServerVendorSpecific"), ("CABH-CDP-MIB", "cabhCdpServerLeaseTime"), ("CABH-CDP-MIB", "cabhCdpServerDhcpAddressType"), ("CABH-CDP-MIB", "cabhCdpServerDhcpAddress"), ("CABH-CDP-MIB", "cabhCdpServerControl"), ("CABH-CDP-MIB", "cabhCdpServerCommitStatus"), ("CABH-CDP-MIB", "cabhCdpServerUseCableDataNwDnsAddr"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cabhCdpGroup = cabhCdpGroup.setStatus('current')
mibBuilder.exportSymbols("CABH-CDP-MIB", cabhCdpSetToFactory=cabhCdpSetToFactory, cabhCdpLanPoolStartType=cabhCdpLanPoolStartType, cabhCdpWanDataAddrLeaseExpireTime=cabhCdpWanDataAddrLeaseExpireTime, cabhCdpWanDataAddrRowStatus=cabhCdpWanDataAddrRowStatus, cabhCdpLanAddrIp=cabhCdpLanAddrIp, cabhCdpWanDnsServerTable=cabhCdpWanDnsServerTable, cabhCdpServerSyslogAddress=cabhCdpServerSyslogAddress, cabhCdpServerLeaseTime=cabhCdpServerLeaseTime, cabhCdpGroups=cabhCdpGroups, cabhCdpServerDhcpAddress=cabhCdpServerDhcpAddress, PYSNMP_MODULE_ID=cabhCdpMib, cabhCdpServerUseCableDataNwDnsAddr=cabhCdpServerUseCableDataNwDnsAddr, cabhCdpLanAddrLeaseCreateTime=cabhCdpLanAddrLeaseCreateTime, cabhCdpWanDataAddrEntry=cabhCdpWanDataAddrEntry, cabhCdpLanTransCurCount=cabhCdpLanTransCurCount, cabhCdpBasicCompliance=cabhCdpBasicCompliance, cabhCdpLanAddrHostName=cabhCdpLanAddrHostName, cabhCdpServerTimeOffset=cabhCdpServerTimeOffset, cabhCdpWanDataIpAddrCount=cabhCdpWanDataIpAddrCount, cabhCdpServerSubnetMaskType=cabhCdpServerSubnetMaskType, cabhCdpServerDhcpAddressType=cabhCdpServerDhcpAddressType, cabhCdpCompliances=cabhCdpCompliances, cabhCdpGroup=cabhCdpGroup, cabhCdpServerNetworkNumber=cabhCdpServerNetworkNumber, cabhCdpBase=cabhCdpBase, cabhCdpLanAddrRowStatus=cabhCdpLanAddrRowStatus, cabhCdpServerRouter=cabhCdpServerRouter, cabhCdpLanPoolStart=cabhCdpLanPoolStart, cabhCdpServerDnsAddressType=cabhCdpServerDnsAddressType, cabhCdpWanDnsServerIp=cabhCdpWanDnsServerIp, cabhCdpLanPoolEnd=cabhCdpLanPoolEnd, cabhCdpServerNetworkNumberType=cabhCdpServerNetworkNumberType, cabhCdpConformance=cabhCdpConformance, cabhCdpDaylightSavingTimeEnable=cabhCdpDaylightSavingTimeEnable, cabhCdpWanDnsServerOrder=cabhCdpWanDnsServerOrder, cabhCdpLanAddrEntry=cabhCdpLanAddrEntry, cabhCdpServerInterfaceMTU=cabhCdpServerInterfaceMTU, cabhCdpServerCommitStatus=cabhCdpServerCommitStatus, cabhCdpLanAddrLeaseExpireTime=cabhCdpLanAddrLeaseExpireTime, cabhCdpSnmpSetTimeOffset=cabhCdpSnmpSetTimeOffset, cabhCdpServerDnsAddress=cabhCdpServerDnsAddress, cabhCdpServerRouterType=cabhCdpServerRouterType, cabhCdpWanDataAddrClientId=cabhCdpWanDataAddrClientId, cabhCdpWanDnsServerEntry=cabhCdpWanDnsServerEntry, cabhCdpLanPoolEndType=cabhCdpLanPoolEndType, cabhCdpServerControl=cabhCdpServerControl, cabhCdpLanTransAction=cabhCdpLanTransAction, cabhCdpServerSubnetMask=cabhCdpServerSubnetMask, cabhCdpNotifications=cabhCdpNotifications, cabhCdpLanAddrIpType=cabhCdpLanAddrIpType, cabhCdpServerSyslogAddressType=cabhCdpServerSyslogAddressType, cabhCdpLanAddrTable=cabhCdpLanAddrTable, cabhCdpWanDataAddrIndex=cabhCdpWanDataAddrIndex, cabhCdpTimeOffsetSelection=cabhCdpTimeOffsetSelection, cabhCdpMib=cabhCdpMib, cabhCdpObjects=cabhCdpObjects, cabhCdpLanAddrClientID=cabhCdpLanAddrClientID, cabhCdpLanTransThreshold=cabhCdpLanTransThreshold, cabhCdpWanDataAddrIpType=cabhCdpWanDataAddrIpType, cabhCdpWanDataAddrIp=cabhCdpWanDataAddrIp, cabhCdpWanDataAddrRenewalTime=cabhCdpWanDataAddrRenewalTime, cabhCdpAddr=cabhCdpAddr, cabhCdpWanDnsServerIpType=cabhCdpWanDnsServerIpType, cabhCdpServerDomainName=cabhCdpServerDomainName, cabhCdpWanDataAddrTable=cabhCdpWanDataAddrTable, cabhCdpServerTTL=cabhCdpServerTTL, cabhCdpLanAddrMethod=cabhCdpLanAddrMethod, cabhCdpLastSetToFactory=cabhCdpLastSetToFactory, cabhCdpServerVendorSpecific=cabhCdpServerVendorSpecific, cabhCdpNotification=cabhCdpNotification, cabhCdpServer=cabhCdpServer, cabhCdpWanDataAddrLeaseCreateTime=cabhCdpWanDataAddrLeaseCreateTime)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 核心思路
# 因为没有BST的性质,所以这里只能常规遍历
# 遍历时候返回:确定p/q的数量 & LCA的结点
# 自底向上遍历,当某个结点的左、右子树已经找齐了,则把LCA结点返回;如果左右子树数量,加上当前节点(如果是pq之一)
# 等于2,则说明当前节点就是LCA
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
_, node = visit(root, p, q)
return node
# return score, node(optional)
def visit(root, p, q):
if not root:
return 0, None
lscore, lnode = visit(root.left, p, q)
if lscore == 2:
return lscore, lnode
rscore, rnode = visit(root.right, p, q)
if rscore == 2:
return rscore, rnode
score = 1 if root == p or root == q else 0
score += lscore + rscore
return score, root
|
class Animal:
def __init__(self,name,legs):
self.name = name
self.legs = legs
class Bear(Animal):
def __init__(self,name,legs=4,hibernate='yes'):
self.name = name
self.legs = legs
self.hibernate = hibernate
yogi = Bear('Yogi')
print(yogi.name)
print(yogi.legs)
print(yogi.hibernate) |
'''
05.Mixed Phones
You will be given several phone entries, in the form of strings in format:
{firstElement} : {secondElement}
The first element is usually the person’s name, and the second one – his phone number.
The phone number consists ONLY of digits, while the person’s name can consist of any ASCII characters.
Sometimes the phone operator gets distracted by the Minesweeper she plays all day,
and gives you first the phone, and then the name. e.g. : 0888888888 :
Pesho. You must store them correctly, even in those cases.
When you receive the command “Over”, you are to print all names you’ve stored with their phones.
The names must be printed in alphabetical order.
'''
phone_dic = {}
while True:
person = list(input().split(' : '))
if person[0] == 'Over':
break
if person[1].isdigit():
phone_dic[person[0]] = person[1]
elif person[0].isdigit():
phone_dic[person[1]] = person[0]
for x, v in sorted(phone_dic.items()):
print(f'{x} -> {v}')
|
# _*_ coding: utf-8 _*_
# !/usr/bin/env python3
"""
Mictlantecuhtli: A Multi-Cloud Global Probe Mesh Creator.
@author: Collisio-Adolebitque
"""
class CommandParser:
def __init__(self, command_string=''):
self.command = command_string
def run(self):
return self.command
class Terraform:
def __init__(self):
pass
def init(self):
pass
def plan(self):
pass
def apply(self):
pass
def destroy(self):
pass
def refresh(self):
pass
def taint(self):
pass
def untaint(self):
pass
def validate(self):
pass
class AWS:
def __init__(self):
pass
class GCP:
def __init__(self):
pass
class Azure:
def __init__(self):
pass
class Alibaba:
def __init__(self):
pass
def main():
print('Bout ye')
if __name__ == '__main__':
main()
|
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
for i, n in enumerate(nums):
if target-n in d:
return [d[target-n], i + 1]
else:
d[n] = i + 1
|
year = int(input("Enter year: "))
if year % 400 == 0:
print('Entered year is a leap year.')
elif year % 100 != 0 and year % 4 == 0:
print('Entered year is a leap year.')
else:
print('Not a leap year.')
|
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class Type5Enum(object):
"""Implementation of the 'Type5' enum.
Specifies the type of managed Object in a HyperFlex protection source
like kServer.
Examples of a HyperFlex types include 'kServer'.
'kServer' indicates HyperFlex server entity.
Attributes:
KSERVER: TODO: type description here.
"""
KSERVER = 'kServer'
|
A= input('Digite a primeira nota:')
B= input('Digite a segunda nota:')
C= input('Digite a terceira nota:')
D= input('Digite a quarta nota:')
MA= (int(A)+int(B)+int(C)+int(D))/4
print ('A média aritmética é ',MA) |
def test():
class MyInt(int):
pass
def f(x):
"""
:type x: MyInt
"""
i = MyInt(2)
f(i)
|
# Description: Examples of a triple water pentagon. Zoom in on the selection. Edit by changing the residue number.
# Source: placeHolder
"""
cmd.do('fetch ${1:lw9}, async=0; ')
cmd.do('zoom resi ${2:313}; ')
cmd.do('preset.technical(selection="all", mode=1);')
"""
cmd.do('fetch lw9, async=0; ')
cmd.do('zoom resi 313; ')
cmd.do('preset.technical(selection="all", mode=1);')
|
"""
checklist:
- mock req
- mock resp
- two ravens:
- urls.py
- test js req
- view.py
- req_file.py
- test js resp
- test w/o TA2
- test w/ TA2
- add tests
"""
|
numb = int(input('Digite um número para saber se ele é primo: '))
cont = 0
lst = []
for p in range(1, numb + 1):
if numb % p == 0:
lst += [p]
cont += 1
if cont == 2:
print('É primo')
else:
print('Não é primo')
print('E seus divisóres são \n {}'.format(lst)) |
class Component(object):
"""Base class for components"""
NAME = "base_component"
def __init__(self):
self.host = None
self.properties = {}
def on_register(self, host):
self.host = host
def on_unregister(self):
self.host = None
def round_update(self):
pass
def minute_update(self):
pass
def hours_update(self):
pass
def days_update(self):
pass
def handle_message(self, message):
pass
|
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
ab = (a * b) // math.gcd(a, b)
ac = (a * c) // math.gcd(a, c)
bc = (b * c) // math.gcd(b, c)
abc = (ab * c) // math.gcd(ab, c)
lo, hi = 1, 2 * 10 ** 9
while lo < hi:
mid = (lo + hi) >> 1
count = mid // a + mid // b + mid // c - mid // ab - mid // ac - mid // bc + mid // abc;
if count < n:
lo = mid + 1
else:
hi = mid
return lo
|
# https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.ans = 0
def traverse(self, node, cur):
if not node.left and not node.right:
self.ans += int("".join(cur), 2)
return
if node.left:
cur.append(str(node.left.val))
self.traverse(node.left, cur)
cur.pop()
if node.right:
cur.append(str(node.right.val))
self.traverse(node.right, cur)
cur.pop()
def sumRootToLeaf(self, root):
if not root:
return 0
self.traverse(root, [str(root.val)])
return self.ans
|
class TimeInterval:
def __init__(self, earliest, latest):
self._earliest = earliest
self._latest = latest
@property
def earliest(self):
return self._earliest
@property
def latest(self):
return self._latest
|
'''
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
'''
# 2018-11-19
# 338. Counting Bits
# https://leetcode.com/problems/counting-bits/
# https://www.cnblogs.com/liujinhong/p/6115831.html
class Solution:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [0] * num
for i in range(num):
if i % 2 == 1:
# 奇数时增加1
res[i] = res[i>>1] + 1
else:
# 偶数时1的个数等于上一个奇数的1的个数
res[i] = res[i>>1]
return res
num = 5
test = Solution()
res = test.countBits(num)
print(res) |
#
# This file contains the Python code from Program 12.2 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm12_02.txt
#
class SetAsArray(Set):
def __init__(self, n):
super(SetAsArray, self).__init__(n)
self._array = Array(self._universeSize)
for item in xrange(0, self._universeSize):
self._array[item] = False
# ...
|
#!/usr/bin/env python3 # makes the terminal know this is in python
x = 9 #Set variables
y = 3
#Arithmetic Operators
print(x+y) # Addition
print(x-y) # Subtraction
print(x*y) # Multiplication
print(x/y) # Division
print(x%y) # Modulus (remainder)
print(x**y) # Exponentiation (to the power of)
x = 9.191823 # Make x into a complicated float to show the effect of floor division
print(x//y) # Floor Division (divide but get rid of the decimal will ALWAYS round down)
# how many whole times does y go into x
# Assignment Operators
x = 9 # set x back to 9. Single equal ASSIGNS the value. Double equals is boolean
x += 3 # take the previous value of x and add 3. So x is now 12
print(x)
x = 9 # set x back to 9.
x -= 3 # take the previous value of x and subtract 3. So x is now 6
print(x)
x = 9 # set x back to 9
x *= 3 # take the previous value of x and multiply by 3. x = 27
print(x)
x = 9 # set x back to 9
x /= 3 # take the previous value of x and divide 3. x = 3
print(x)
x = 9 # set x back to 9
x **= 3 # take the previous value of x and put it to the power of 3. x = 9^3
print(x)
# Comparison Operators - Booleans
x = 9
y = 3
print(x==y) # is x the same as y? In this case False
print(x!=y) # is x different than y? In this case True
print(x>y) # is x greater than y? In this case True
print(x<y) # is x less than y? In this case False
print(x>=y) # is x greater than or equal to y? In this case True
print(x<=y) # is x less than or equal to y? In this case False |
def convert(value, newType):
try:
return newType(value)
except ValueError:
return None
|
"""
The probability that a machine produces a defective product is 1/3.
What is the probability that the 1st defect is found during the 5th inspection?
"""
def geometric(n, p):
return p * (1 - p) ** (n - 1)
def sum_geometric(n, p):
total = 0
for i in range(1, n):
total += geometric(i, p)
return total
def main():
omega, space = map(int, input().split())
n = int(input())
p = omega / space
result = sum_geometric(6, p)
print("{:.3f}".format(result))
if __name__ == "__main__":
main()
|
casa = int(input('Qual o valor da casa a ser comprada? '))
salario = int(input('Qual seu salário? '))
anos = int(input('Em quantos anos você deseja pagar essa casa? '))
mes = anos*12
mínima = salario * 30 / 100
prestação = casa / mes
print('')
print('Para pagar uma casa de R${:.2f}, a prestação mínima é de R${:.2f} reais.'.format(casa,prestação))
print('')
if mínima < prestação:
print('EMPRESTIMO NEGADO')
elif mínima >= prestação:
print('EMPRESTIMO APROVADO')
|
class Node:
def __init__(self,value=None):
self.value = value
self.next = None
class CircularSinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
'''to iterate objects of this class with "in"-keyword'''
node = self.head
while node:
yield node.value
if node.next == self.head:
break
node = node.next
def insert(self,value,index=-1):
newNode = Node(value)
if self.head is None:
newNode.next = newNode
self.head = newNode
self.tail = newNode
elif index == 0:
newNode.next = self.head
self.head = newNode
self.tail.next = newNode
elif index == -1:
newNode.next = self.head
self.tail.next = newNode
self.tail = newNode
else:
i = -2
flag=True
temp = self.head
while i<index-3:
temp = temp.next
if temp is None:
print(f"could not insert node : length of list is {i+3} but index given was {index}")
flag =False
break
i+=1
if flag:
if temp.next == self.head:
self.tail = newNode
newNode.next= temp.next
temp.next = newNode
def traverse(self):
if self.head is None:
print("list is empty")
else:
temp = self.head
while temp:
print(temp.value)
temp = temp.next
if temp == self.head:
temp = None
def search(self,nodevalue):
if self.head is None:
print("not found, list is empty")
else:
temp = self.head
i=0
while temp:
if temp.value == nodevalue:
return f"value {nodevalue} found at index {i}"
i+=1
temp = temp.next
if temp==self.head:
return f"value {nodevalue} not found"
def pop(self,index=-1):
if self.head is None:
print("list is empty")
elif index == 0:
if self.head.next is self.head:
self.head = None
self.tail =None
else:
self.head=self.head.next
self.tail.next = self.head
elif index == -1:
temp = self.head
while temp.next.next!=self.head:
temp=temp.next
temp.next = self.head
self.tail = temp
else:
i = -2
flag=True
temp = self.head
while i<index-3:
temp = temp.next
if (temp is self.head) or (temp.next is self.head):
print(f"could not delete node : length of list is {i+3} but index given was {index}")
flag =False
break
i+=1
if flag:
if temp.next.next == self.head:
temp.next = self.head
self.tail=temp
else:
temp.next = temp.next.next
csll = CircularSinglyLinkedList()
csll.insert(1)
csll.insert(2)
csll.insert(3)
csll.insert(4)
csll.insert(5)
csll.insert(0,0)
csll.insert(7,6)
print([i for i in csll])
print(f"tail: {csll.tail.value}")
print(f"tail.next: {csll.tail.next.value}")
csll.traverse()
print(csll.search(4))
print(csll.search(79))
print(csll.search(7))
print(f"before pop(): {[i for i in csll]}")
csll.pop(3)
print(f"before pop(): {[i for i in csll]}")
|
class Solution:
ans = 0
def findPathNum(self, i, j, grid: List[List[int]], curLen, pLen)->None:
if(grid[i][j]==2):
if(pLen-1==curLen):
self.ans+=1
return
elif (grid[i][j]==-1):
return
curLen+=1
grid[i][j]=-1
if(i-1>=0):
self.findPathNum(i-1, j, grid, curLen, pLen)
if(j-1>=0):
self.findPathNum(i, j-1, grid, curLen, pLen)
if(i+1<len(grid)):
self.findPathNum(i+1, j, grid, curLen, pLen)
if(j+1<len(grid[0])):
self.findPathNum(i, j+1, grid, curLen, pLen)
grid[i][j]=0
def uniquePathsIII(self, grid: List[List[int]]) -> int:
pathLen = 0
start = (0, 0)
for i in range(len(grid)):
for j in range(len(grid[0])):
if(grid[i][j]!=-1):
pathLen+=1
if(grid[i][j]==1):
start = (i, j)
self.findPathNum(start[0], start[1], grid, 0, pathLen)
return self.ans |
class BoxDriveAPI():
host = None
key = None
secret = None
access_token = None
access_token_expiration = None
def __init__(self, host, key, secret):
# the function that is executed when
# an instance of the class is created
self.host = host
self.key = key
self.secret = secret
try:
self.access_token = self.get_access_token()
if self.access_token is None:
raise Exception("Request for access token failed.")
except Exception as e:
print(e)
else:
self.access_token_expiration = time.time() + 3500
def get_access_token(self):
# the function that is
# used to request the JWT
try:
# build the JWT and store
# in the variable `token_body`
# request an access token
request = requests.post(self.host, data=token_body)
# optional: raise exception for status code
request.raise_for_status()
except Exception as e:
print(e)
return None
else:
# assuming the response's structure is
# {"access_token": ""}
return request.json()['access_token']
class Decorators():
@staticmethod
def refreshToken(decorated):
# the function that is used to check
# the JWT and refresh if necessary
def wrapper(api, *args, **kwargs):
if time.time() > api.access_token_expiration:
api.get_access_token()
return decorated(api,*args,**kwargs)
return wrapper
@Decorators.refreshToken
def someRequest():
# make our API request
pass |
""" Quiz: Create an HTML List
Write some code, including a for loop, that iterates over a list of strings and creates a single string, html_str, which is an HTML list. For example, if the list is items = ['first string', 'second string'], printing html_str should output:
<ul>
<li>first string</li>
<li>second string</li>
</ul>
That is, the string's first line should be the opening tag <ul>. Following that is one line per element in the source list, surrounded by <li> and </li> tags. The final line of the string should be the closing tag </ul>.
"""
items = ["first string", "second string"]
html_str = "<ul>\n" # "\ n" is the character that marks the end of the line, it does
# the characters that are after it in html_str are on the next line
# write your code here
for item in items:
html_str += "<li>{}</li>\n".format(item)
html_str += "</ul>"
print(html_str)
|
title = 'LOJA SUPER BARATÃO'
ending = ' FIM DO PROGRAMA '
print('-' * 30)
print(f'{title:^30}')
print('-' * 30)
soma = cont = menor = controlador = 0
mais_barato = ''
while True:
produto = str(input('Nome do Produto: ').strip())
preço = float(input('Preço: R$').strip())
res = ' '
while res not in 'SN':
res = str(input('Quer continuar? [S/N] ')).upper().strip()[0]
print('-' * 30)
soma += preço
controlador += 1
if preço > 1000:
cont += 1
if controlador == 1 or preço < menor:
menor = preço
mais_barato = produto
if res == 'N':
break
print(f'{ending:-^40}')
print(f'O total da compra foi R${soma:.2f}')
print(f'Temos {cont} produtos custando mais de R$1000.00')
print(f'O produto mais barato foi {mais_barato} que custa R${menor}')
|
print(not None)
print(not False)
print(not True)
print(not 0)
print(not 1)
print(not -1)
print(not ())
print(not (1,))
print(not [])
print(not [1,])
print(not {})
print(not {1:1})
|
# A população de um pais
#Cont
cont = 0
# Pais A
pA = 80000
cA = 80000 * 3.0 / 100
tA = pA + cA
# Pais B
pB = 200000
cB = 200000 * 1.5 / 100
tB = pB + cB
while tA < tB:
tA += tA
tB += tB
cont += 1
print ("Serão necessarios %d anos, para que a cidade A alcance a B em numero de habitantes" %cont)
|
tot = 0
b = int(input())
for i in range(b):
a = list(map(float, input().split()))
if(a[0]==1001):
tot+=a[1]*1.5
elif(a[0]==1002):
tot+=a[1]*2.5
elif(a[0]==1003):
tot+=a[1]*3.5
elif(a[0]==1004):
tot+=a[1]*4.5
elif(a[0]==1005):
tot+=a[1]*5.5
print("%.2f" % (tot)) |
def division(a, b):
if a == b:
return 1
if a < b:
return 0
quotient = 1
temp_number = b
while temp_number + b <= a:
quotient += 1
temp_number += b
return quotient
print(division(1200, 3))
|
index = []
def createIndex():
for file in ["..\data\subgraph\hop1", "..\data\subgraph\hop2", "..\data\subgraph\hop3"]:
with open(file) as f:
edges = [edge.rstrip() for edge in f]
arr = []
for edge in edges:
arr2 = []
arr3 = []
x = edge.split(',')
y = x[1].split(' ')
arr2.append(int(x[0]))
for e in y:
z = e.split('-')
arr4 = [int(z[0]), int(z[1])]
arr3.append(arr4)
arr2.append(arr3)
arr.append(arr2)
index.append(arr)
return index
def get(hop, node):
for x in index[hop]:
if x[0] == node:
return x[1]
#
# subgraph = get(2, 114)
# print(subgraph)
|
def gaussJordan(A):
n = len(A)
x = [0]*n
print(f'A :\n{A}')
for i in range(n):
if A[i][i] == 0:
print('Ora iso mbagi 0 bos')
break
for j in range(i+1,n):
rasio = A[j][i]/A[i][i]
for k in range(n+1):
A[j][k] -= rasio*A[i][k]
print(f'A :\n{A}')
for i in range(n):
rasio = A[i][i]
for j in range(n+1):
A[i][j] /= rasio
print(f'A :\n{A}')
for i in range(n-1,0,-1):
for j in range(i-1,-1,-1):
rasio = A[j][i]
for k in range(n+1):
A[j][k] -= rasio*A[i][k]
print(f'A :\n{A}')
for i in range(n):
x[i] =A[i][n]
for i,j in enumerate(x):
print(f'x{i} : {j}')
return x
gaussJordan(A= [[2,3,-1,5],[4,4,-3,3],[-2,3,-1,1]])
|
def grade(key, submission):
if submission == 'b3_car3ful_0r_y0ur_l3ak_m1ght_l3ak':
return True, "You're now an elite hacker..."
else:
return False, "Keep digging..."
|
def ZG_rprod(X,Y):
if len(X.shape) < 2:
X = X[:,None]
n,m = X.shape
if Y.shape[0] != n or len(Y.shape) != 1:
print('rprod error')
return None
Y = Y[:,None]
Z = np.multiply(X,np.matmul(Y,np.ones((1,m))))
return Z
|
possibles = {
"A": "01000001",
"B": "01000010",
"C": "01000011",
"D": "01000100",
"E": "01000101",
"F": "01000110",
"G": "01000111",
"H": "01001000",
"I": "01001001",
"J": "01001010",
"K": "01001011",
"L": "01001100",
"M": "01001101",
"N": "01001110",
"O": "01001111",
"P": "01010000",
"Q": "01010001",
"R": "01010010",
"S": "01010011",
"T": "01010100",
"U": "01010101",
"V": "01010110",
"W": "01010111",
"X": "01011000",
"Y": "01011001",
"Z": "01011010",
"a": "01100001",
"b": "01100010",
"c": "01100011",
"d": "01100100",
"e": "01100101",
"f": "01100110",
"g": "01100111",
"h": "01101000",
"i": "01101001",
"j": "01101010",
"k": "01101011",
"l": "01101100",
"m": "01101101",
"n": "01101110",
"o": "01101111",
"p": "01110000",
"q": "01110001",
"r": "01110010",
"s": "01110011",
"t": "01110100",
"u": "01110101",
"v": "01110110",
"w": "01110111",
"x": "01111000",
"y": "01111001",
"z": "01111010",
" ": "00100000"
}
possibles_opposite = {
"01000001": "A",
"01000010": "B",
"01000011": "C",
"01000100": "D",
"01000101": "E",
"01000110": "F",
"01000111": "G",
"01001000": "H",
"01001001": "I",
"01001010": "J",
"01001011": "K",
"01001100": "L",
"01001101": "M",
"01001110": "N",
"01001111": "O",
"01010000": "P",
"01010001": "Q",
"01010010": "R",
"01010011": "S",
"01010100": "T",
"01010101": "U",
"01010110": "V",
"01010111": "W",
"01011000": "X",
"01011001": "Y",
"01011010": "Z",
"01100001": "a",
"01100010": "b",
"01100011": "c",
"01100100": "d",
"01100101": "e",
"01100110": "f",
"01100111": "g",
"01101000": "h",
"01101001": "i",
"01101010": "j",
"01101011": "k",
"01101100": "l",
"01101101": "m",
"01101110": "n",
"01101111": "o",
"01110000": "p",
"01110001": "q",
"01110010": "r",
"01110011": "s",
"01110100": "t",
"01110101": "u",
"01110110": "v",
"01110111": "w",
"01111000": "x",
"01111001": "y",
"01111010": "z",
"00100000": " "
}
while True:
starter = input("Enter B for converting text to Binary or T for binary to Text: ").upper()
converted = ""
queries = ""
if starter == "B":
queries = input(">_")
for q in queries:
converted += possibles[q] + " "
print(converted)
else:
print("Bye")
break
"""
elif starter == "T":
queries = input(">_")
for q in queries:
converted += possibles_opposite[q] + " "
print(converted)
""" |
# Emulating the badge module
#
# The badge module is a C module with Python bindings
# on the real badge, but for the emulator it's just a
# plain python module.
def nvs_get_u16(namespace, key, value):
return value
def eink_init():
"ok"
def safe_mode():
return False
|
#import In.entity
class Message(In.entity.Entity):
'''Message Entity class.
'''
room_id = None
def __init__(self, data = None, items = None, **args):
super().__init__(data, items, **args)
@IN.register('Message', type = 'Entitier')
class MessageEntitier(In.entity.EntityEntitier):
'''Base Message Entitier'''
# Message needs entity insert/update/delete hooks
invoke_entity_hook = True
# load all is very heavy
entity_load_all = False
@IN.register('Message', type = 'Model')
class MessageModel(In.entity.EntityModel):
'''Message Model'''
@IN.hook
def entity_model():
return {
'Message' : { # entity name
'table' : { # table
'name' : 'message',
'columns' : { # table columns / entity attributes
'id' : {},
'type' : {},
'created' : {},
'status' : {},
'nabar_id' : {},
'room_id' : {},
},
'keys' : {
'primary' : 'id',
},
},
},
}
@IN.register('Message', type = 'Themer')
class MessageThemer(In.entity.EntityThemer):
'''Message themer'''
def theme_attributes(self, obj, format, view_mode, args):
obj.attributes['data-id'] = obj.id # needed for js
super().theme_attributes(obj, format, view_mode, args)
def theme(self, obj, format, view_mode, args):
super().theme(obj, format, view_mode, args)
def theme_process_variables(self, obj, format, view_mode, args):
super().theme_process_variables(obj, format, view_mode, args)
nabar = IN.entitier.load('Nabar', obj.nabar_id)
args['nabar_name'] = nabar.name
args['nabar_id'] = nabar.id
args['nabar_picture'] = IN.nabar.nabar_profile_picture_themed(nabar)
args['created'] = In.core.util.format_datetime_friendly(obj.created)
|
x = [ 0, 2, 5, 10]
y = [ 0, 3, 5]
def carresgrosselistedistance(x, y):
xlist = list()
ylist = list()
grosse_liste = list()
print(len(x), len(y))
for i in range(len(x)):
try:
xlist.append(x[i + 1] - x[i])
except IndexError:
xlist.append(x[i])
for i in range(len(y)):
try:
ylist.append(y[i + 1] - y[i])
except IndexError:
ylist.append(y[i])
print(xlist, ylist)
grosse_liste += xlist + ylist
grosse_liste = xlist + list(set(ylist) - set(xlist))
print(grosse_liste)
"""
sol =0
for xgrosse in grosse_liste:
for ygrosse in grosse_liste:
if xgrosse == ygrosse:
sol +=1
return sol
"""
return len(grosse_liste)
def carreslistedescoordonnes(lstx,lsty):
coordx = list()
coordy = list()
for lentx in range(len(lstx)):
try:
coordx.append(lstx[lentx])
coordx.append(lstx[lentx+1])
except IndexError:
coordx.append(lstx[lentx])
#coordx.append(lstx[lentx])
for lenty in range(len(lsty)):
try:
coordy.append(lsty[lenty])
coordy.append(lsty[lenty+1])
except IndexError:
coordy.append(lsty[lenty])
#coordy.append(lsty[lenty])
return coordx, coordy
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 16:24:05 2020
@author: mberutti
"""
class Data:
""" Class for managing, storing, and broadcasting data
transmitted from the camera.
"""
def __init__(self, data_path):
self.data_path = data_path
self.results = None
self._purge_results()
def _load_results(self):
""" Load data from results folder into variable
"""
pass
def _purge_results(self):
""" Delete all from results folder
"""
pass
def _write_results(self, results):
""" Write to results folder
"""
pass
def pepare_broadcast(self):
""" Prepare data for transmission
"""
data = self._load_results()
data = self._format_for_trans(data)
return data
def fetch_data(self):
""" Fetch data from source (camera)
"""
data = None
self._write_results(data)
pass
class Broadcast:
""" Class for connecting to a peer and transmitting data.
"""
def __init__(self, peer):
self.peer = peer
self._connect()
def _connect(self):
""" Connect to peer
"""
if not self._verify_connection():
raise RuntimeError("Could not connect to peer.")
def _verify_connection(self):
""" Check if connected to peer
"""
connected = False
return connected
def broadcast_data(self, data):
""" Transmit data to peer
"""
if not self._verify_connection():
self._connect()
pass
def read_data(self):
""" Accept data from peer
"""
pass
|
def capitals_first(string):
words = string.split()
st1 = []
st2 = []
for word in words:
if word[0].isalpha():
if word[0].isupper():
st1.append(word)
else:
st2.append(word)
return " ".join(st1 + st2) |
# local usage only
dbconfig = {
'host' : '172.29.0.2',
'port' : 3306,
'db' : 'routing',
'user' : 'dev',
'password' : 'admin',
}
|
'''
Author : kazi_amit_hasan
Problem: Hello 2019,Problem A
Solution: Just check that first input is present in next input or not
'''
t= input()
h = input()
if t[0] in h or t[1] in h:
print("YES")
else:
print("NO")
|
#!/usr/bin/py
# Head ends here
def pairs(a,k):
# a is the list of numbers and k is the difference value
count = 0
compls = {}
for i in a:
if i in compls:
count += compls[i]
compls[i + k] = compls[i + k] + 1 if i+k in compls else 1
compls[i - k] = compls[i - k] + 1 if i-k in compls else 1
return count
# Tail starts here
if __name__ == '__main__':
a = input().strip()
a = list(map(int, a.split(' ')))
_a_size=a[0]
_k=a[1]
b = input().strip()
b = list(map(int, b.split(' ')))
print(pairs(b,_k))
|
def main():
for i in range (1001, 3339):
a = i
b = a + 3330
c = b + 3330
flag = False
flag2 = False
for eachNum in str(a):
if not (eachNum in str(b) or eachNum in str(c)):
for eachOtherNum in str(b):
if not eachOtherNum in str(c):
flag = True
if flag:
for eachNum in str(a):
if isPrime(int(eachNum)):
flag2 = True
if flag2:
if isPrime(a) and isPrime(b) and isPrime(c):
print(str(a) + str(b) + str(c))
return
def isPrime(n):
for i in range(2, int(n ** 0.5) + 1):
if n%i == 0:
return True
return False
if __name__ == '__main__':
main()
|
SUPPORT_PROTOCOL_VERSIONS = [3, 4]
SUPPORT_PROTOCOLS = ["MQIsdp" ,"MQTT"]
class TYPE():
R_0 = "\x00"
CONNECT = "\01"
CONNACK = "\x02"
PUBLISH = "\x03"
PUBACK = "\x04"
PUBREC = "\x05"
PUBREL = "\x06"
PUBCOMP = "\x07"
SUBSCRIBE = "\x08"
SUBACK = "\x09"
UNSUBSCRIBE = "\x0a"
UNSUBACK = "\x0b"
PINGREQ = "\x0c"
PINGRESP = "\x0d"
DISCONNECT = "\x0e"
R_15 = "\x0f"
@classmethod
def string(cls, num):
if num == cls.CONNECT:
return "CONNECT"
elif num == cls.CONNACK:
return "CONNACK"
elif num == cls.PUBLISH:
return "PUBLISH"
elif num == cls.PUBACK:
return "PUBACK"
elif num == cls.PUBREC:
return "PUBREC"
elif num == cls.PUBREL:
return "PUBREL"
elif num == cls.PUBCOMP:
return "PUBCOMP"
elif num == cls.SUBSCRIBE:
return "SUBSCRIBE"
elif num == cls.SUBACK:
return "SUBACK"
elif num == cls.UNSUBSCRIBE:
return "UNSUBSCRIBE"
elif num == cls.UNSUBACK:
return "UNSUBACK"
elif num == cls.PINGREQ:
return "PINGREQ"
elif num == cls.PINGRESP:
return "PINGRESP"
elif num == cls.DISCONNECT:
return "DISCONNECT"
else:
return "WARNNING: undefined type %s" % num
class ConnectReturn():
ACCEPTED = "\x00"
R_UNACCEPTABLE_PROTOCOL_VERSION = "\x01"
R_ID_REJECTED = "\02"
R_SERVER_UNAVAILABLE = "\x03"
R_BAD_NAME_PASS = "\04"
R_NOT_AUTHORIZED = "\x05"
@classmethod
def string(cls, num):
if num == cls.ACCEPTED:
return "CONNECTION ACCEPTED"
elif num == cls.R_UNACCEPTABLE_PROTOCOL_VERSION:
return "UNACCEPTABLE PROTOCOL VERSION"
elif num == cls.R_ID_REJECTED:
return "IDENTIFIER REJECTED"
elif num == cls.R_SERVER_UNAVAILABLE:
return "SERVER UNAVAILABLE"
elif num == cls.R_BAD_NAME_PASS:
return "BAD USER NAME OR PASSWORD"
elif num == cls.R_NOT_AUTHORIZED:
return "NOT AUTHORIZED"
else:
return "WARNNING: undefined code %s" % num
|
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
total = 0
for i in range(len(mat)):
total += mat[i][i] # elements from the primary diagonal
total += mat[i][len(mat)-1-i] # secondary diagonal
if len(mat) % 2 == 0:
return total
return total - mat[len(mat)//2][len(mat)//2]
|
"""Migration 001
Migration ID: 123
Revises:
Created at: 01/01/2001
"""
# Nomade migration identifiers
migration_name = 'Migration 001'
migration_date = '01/01/2001'
curr_migration = '123'
down_migration = ''
def upgrade():
"""Write your upgrade statements here."""
def downgrade():
"""Write your downgrade statements here."""
|
valorPorHora = float(input('Quanto voce ganha por hora: '))
horasTrabalhadas = float(input('Quantas horas voce trabalhou no mes: '))
salarioBruto = valorPorHora * horasTrabalhadas
impostoRenda = salarioBruto * 0.11
inss = salarioBruto * 0.08
sindicato = salarioBruto * 0.05
salarioLiquido = salarioBruto - impostoRenda - inss - sindicato
print('Salario Bruto:', salarioBruto)
print('Imposto de Renda:', impostoRenda)
print('INSS:', inss)
print('Sindicato:', sindicato)
print('Salario Liquido:', salarioLiquido)
|
def define_best_name(name1, name2):
if len(name1) > len(name2):
return name1
return name2
my_name = "Tom Thompsom"
your_name = "Lauretius Maximus"
the_best_name = define_best_name(my_name, your_name) |
def resolve():
'''
code here
Sを先頭 真ん中 お尻の三分割する
連結した場合を考えると以下の場合分け
先頭 お尻 真ん中×K (先頭₊お尻)×(K-1)
同じ文字が続いたらn//2個の文字変更が必要
以上で解けるた
'''
S = input()
K = int(input())
S_head = ''
head = S[0]
for s in S:
if s == head:
S_head += s
else:
break
S_tail = ''
tail = S[-1]
for s in S[::-1]:
if s == tail:
S_tail += s
else:
break
S_tail = S_tail[::-1]
S_body = S[len(S_head):-1 * len(S_tail)]
def double_counter(S):
cnt = 0
if len(S) >= 2:
prev = S[0]
for item in S[1:]:
if item == prev:
cnt += 1
prev = -1
else:
prev = item
return cnt
if len(S) >= 2 and len(S) != len(S_head):
res = len(S_head)//2\
+ len(S_tail)//2\
+ double_counter(S_body) * K\
+ double_counter(S_tail+S_head) * (K-1)
elif len(S) == 1:
res = K // 2
elif len(S) == len(S_head):
res = (K * len(S)) // 2
print(res)
if __name__ == "__main__":
resolve()
|
print("""\033[2;36m
__ __ ____ _ _
\ \/ / | _ \ _ __ ___ (_) __| |
\ /_____| | | | '__/ _ \| |/ _` |
/ \_____| |_| | | | (_) | | (_| |
/_/\_\ |____/|_| \___/|_|\__,_|v0.1®
""")
db = {}
print('Welcome!, I am X~Droid v0.1\nDesigned by Myth for data storage\n')
while True:
r = input( 'Shall we begin?\n(Y/N) >>> ')
if r == 'N':
print('Alright, Watch out for v0.2 with a new feature....Bye!')
break
elif r == 'Y':
print('\nGreat!')
print('So, what do you want to do?')
break
while True:
print('\nInput (S) to Save, (O) to Open already saved data, (L) to List all saved data')
print('or (Q) to Quit\n')
a = input('>>>')
if a == 'S':
n = input('Data name: ')
i = input('Data info: ')
db[n] = i
elif a == 'O':
n = input('Data name: ')
if not n in db:
print('No such Data name!')
else:
print('Your Data info: '+db[n]+'\n')
elif a == 'L':
print('Lists of Data names:')
print(db)
elif a == 'Q':
print('Thank you for using X~Droid, v0.2 will be out soon with a new feature, stay tuned...Bye!')
break
exit()
|
BATCH_SIZE = 512
D_MODEL = 512
P_DROP = 0.1
D_FF = 2048
HEADS = 8
LAYERS = 6
LR = 1e-3
EPOCHS = 40 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if head is None:
return head
#Find length and last node of list
length = 1
tail = head
while tail.next is not None:
tail = tail.next
length += 1
#Reduce rotations by using k mod length
k = k % length
#In case k is 0, return head
if k == 0:
return head
#Find the node prev to Kth node from end
curr = head
for _ in range(length - k - 1):
curr = curr.next
#New head with the node next to prev, here next to the current
#Store new head, assign curr.next to None and link last node's next to head
newHead = curr.next
curr.next = None
tail.next = head
return newHead |
# Python - 3.4.3
fib = {0: 0, 1: 1}
def fibonacci(n):
if not n in fib:
fib[n - 2] = fibonacci(n - 2)
fib[n - 1] = fibonacci(n - 1)
fib[n] = fib[n - 1] + fib[n - 2]
return fib[n]
|
"""
Contains custom exceptions
"""
class MissingSetting(Exception):
"""
When a setting is missing
"""
def __init__(self, setting_name):
self.setting_name = setting_name
super().__init__(
f"Could not find setting '{self.setting_name}' in 'PAGE_SHARER' settings."
)
|
# Try comparison operators in this quiz! This code calculates the
# population densities of Rio de Janeiro and San Francisco.
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
san_francisco_pop_density = sf_population/sf_area
rio_de_janeiro_pop_density = rio_population/rio_area
# Write code that prints True if San Francisco is denser than Rio,
# and False otherwise
print(san_francisco_pop_density > rio_de_janeiro_pop_density)
# The bool data type holds one of the values True or False, which are
# often encoded as 1 or 0, respectively.
# There are 6 comparison operators that are common to see in order to
# obtain a bool value:
# < : Less Than
# > : Greater Than
# <= : Less Than or Equal To
# >= : Greater Than or Equal To
# == : Equal to
# != : Not Equal to
# And there are 3 logical operators you need to be familiar with:
# and - Evaluates if all provided statements are True
# or - Evaluates if at least one of many statements is True
# not - Flips the Bool Value
|
"""
The submodule that handles form processing.
"""
def process(**kwargs):
"""
Processes the form arguments and returns a message to display to the user.
Keyword Arguments
-----------------
The keyword arguments are of the form:
{
'name': value
}
Where the name is the same key as in FORM_SPECIFICATION in app.py and the
value is provided by the user.
Returns
-------
str: The message to display to the user.
"""
return 'You submitted: {}'.format(kwargs) |
def create_matrix(rows):
result = []
for _ in range(rows):
row = [int(el) for el in input().split(", ")]
result.append(row)
return result
def get_biggest_sum_elements(matrix, r, c):
result = [matrix[r][c:c + 2], matrix[r + 1][c:c + 2]]
return result
def print_result(biggest_sum, biggest_sum_elements):
for el in biggest_sum_elements:
print(*list(map(str, el)), sep=" ")
print(biggest_sum)
rows, columns = list(map(int, input().split(", ")))
matrix = (create_matrix(rows))
sum_square = 0
biggest_sum_square = sum_square
for c in range(columns - 1):
for r in range(rows - 1):
sum_square = matrix[r][c] + matrix[r+1][c] + matrix[r+1][c+1] + matrix[r][c+1]
if sum_square > biggest_sum_square:
biggest_sum_square = sum_square
biggest_sum_elements = get_biggest_sum_elements(matrix, r, c)
print_result(biggest_sum_square, biggest_sum_elements) |
# Unindo dicionários e listas
'''Crie um program que leia NOME, SEXO e IDADE de VÁRIAS PESSOAS,
guardando os dados de cada pessoa em um DICIONÁRIO e todos os dicionários
em uma LISTA. No final, mostre:
A) Quantas pessoas foram cadastradas
B) A MÉDIA de idade do grupo
C) Uma lista com todas as MULHERES
D) Uma lista com todas as pessoas com IDADE acima da MÉDIA'''
dados = list()
pessoa = dict()
mulheres = list()
while True:
pessoa['nome'] = str(input('Nome: '))
while True:
pessoa['sexo'] = str(input('Sexo: [M/F] ')).upper()[0]
if pessoa['sexo'] in 'MF':
if pessoa['sexo'] == 'F':
mulheres.append((pessoa['nome']))
break
print('\033[31m''ERRO! Por favor, digite apenas M ou F''\033[m')
pessoa['idade'] = int(input('Idade: '))
dados.append(pessoa.copy())
pessoa.clear()
while True:
resp = str(input('Quer continuar? [S/N] ')).upper()[0]
if resp in 'SN':
break
print('\033[31m''ERRO! Por favor, digite apena M ou F''\033[m')
if resp == 'N':
break
print('\033[1:37m''-=''\033[m' * 30)
print(f'- O grupo tem {len(dados)} pessoas')
soma = 0
for i, p in enumerate(dados):
soma += dados[i]["idade"]
media = soma / len(dados)
print(f'- A média de idade é de {media:5.2f} anos')
print(f'- As mulheres cadastradas foram: ', end='')
for m in mulheres:
print(m, end=' ')
print('\n- Lista das pessoas que estão acima da média:')
for i, p in enumerate(dados):
if dados[i]["idade"] > media:
print(f'nome = {dados[i]["nome"]}; sexo = {dados[i]["sexo"]}; idade = {dados[i]["idade"]}')
print('<< ENCERRADO >>')
|
global v, foo
v = 1
v = 2
print(v)
def foo():
return 1
try:
def foo():
return 2
except RuntimeError:
print("RuntimeError1")
print(foo())
def __main__():
pass
|
# Problem: https://www.hackerrank.com/challenges/list-comprehensions/problem
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
|
class Pessoa:
tamanho_cpf = 11
p = Pessoa()
print(p.tamanho_cpf)
p.tamanho_cpf = 12
print(p.tamanho_cpf)
print(Pessoa.tamanho_cpf) |
__version__ = '1.8'
__name__ = 'Zhihu Favorite'
class Document:
def __init__(self, meta, content):
self.meta = meta
self.content = content
self.images = list()
def convert2(self, converter, file):
file.write(converter(self).tostring())
class DocBuilder:
def __init__(self, doc: Document):
self.doc = doc
class MarkdownBuilder(DocBuilder):
pass
class HtmlBuilder(DocBuilder):
pass
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def validateBST(min_val, max_val, root):
if not root:
return True
left = validateBST(min_val, root.val, root.left)
right = validateBST(root.val, max_val, root.right)
return min_val < root.val < max_val and left and right
return validateBST(-sys.maxsize, sys.maxsize, root)
|
class Player:
def __init__(self, name: str, sprint: int, dribble: int, passing: int, shooting: int):
self.__name = name
self.__sprint = sprint
self.__dribble = dribble
self.__passing = passing
self.__shooting = shooting
@property
def name(self):
return self.__name
def __str__(self):
return f"Player: {self.__name}\nSprint: {self.__sprint}\nDribble: {self.__dribble}\nPassing: {self.__passing}\nShooting: {self.__shooting}"
|
def designerPdfViewer(h, word):
word = list(word)
height = 0
width = len(word)
for x in word:
current = h[ord(x)-97]
if current > height:
height = current
return height * width |
pkgname = "lame"
pkgver = "3.100"
pkgrel = 0
build_style = "gnu_configure"
configure_args = ["--enable-nasm", "--enable-shared"]
hostmakedepends = ["nasm"]
makedepends = ["ncurses-devel"]
pkgdesc = "Fast, high quality MP3 encoder"
maintainer = "q66 <q66@chimera-linux.org>"
license = "LGPL-2.1-or-later"
url = "https://lame.sourceforge.io"
source = f"$(SOURCEFORGE_SITE)/{pkgname}/{pkgname}-{pkgver}.tar.gz"
sha256 = "ddfe36cab873794038ae2c1210557ad34857a4b6bdc515785d1da9e175b1da1e"
@subpackage("lame-devel")
def _devel(self):
return self.default_devel()
|
# anagram!
# remove each string that is an anagram of an earlier string, then return an ordered list of the remaining words
# example:
# input: ['code', 'doce', 'frame', 'edoc', 'framer']
# output: 'code', 'frame', 'framer'
# input = ['poke', 'ekop', 'kope', 'peok']
# output = ['poke']
# start with a brute force algorithm, then pare it down from there. Here's the text I was using as my main test case. Note that is has multiple items with anagrams, as well as a word that isn't an anagram but is similar to one of the anagrams
# text = ['code', 'doce', 'frame', 'edoc', 'framer', 'famer']
def anagram(text):
sorted_words = dict()
# reverses text list so that when it gets turned into a dictionary it will have the first instance of the anagram. Used list slice rather than the reverse method since reverse returns None.
for word in text[::-1]:
current = word #just another variable to keep the various instances of 'word' straight
# takes each word from the text list, essentially 'unanagrams' it, then appends it to the dict of sorted words. The letters are the thing being sorted, not the word order.
# removes duplicates from sorted words and returns it as a list
sorted_words.update({''.join(sorted(current)) : current})
return sorted(list(sorted_words.values()))
def anagram_oneliner(text):
return sorted(list({''.join(sorted(word)) : word for word in text[::-1]}.values()))
|
class MagicList :
def __init__(self):
self.data = [0]
def findMin(self):
M = self.data
smallest= min(M)
return(smallest)
def insert(self, E):
M = self.data
M.append(E)
l=len(M)
i= l-1
while (i//2 >= 1 and M[i//2] > M[i]):
M[i],M[i//2] = M[i//2],M[i]
i=i//2
return(M)
def deleteMin(self):
M = self.data
E1= min(M)
E2= M[len(M)-1]
i=0
while(E2<M[2*i] and E2<M[2*i+1]):
if M[2*i]< M[2*i+1]:
s=M[2*i]
else:
s=M[2*i+1]
b=E2
E2=s
s=b
def K_sum(L, K):
w = MagicList()
aseem = w.data
for i in L:
w.insert(i)
ans = 0
for i in range(1,K+1):
ans+=aseem[i]
return ans
if __name__ == "__main__" :
'''Here are a few test cases'''
'''insert and findMin'''
M = MagicList()
M.insert(4)
M.insert(3)
M.insert(5)
x = M.findMin()
if x == 3 :
print("testcase 1 : Passed")
else :
print("testcase 1 : Failed")
'''deleteMin and findMin'''
M.deleteMin()
x = M.findMin()
if x == 4 :
print("testcase 2 : Passed")
else :
print("testcase 2 : Failed")
'''k-sum'''
L = [2,5,8,3,6,1,0,9,4]
K = 4
x = K_sum(L,K)
if x == 6 :
print("testcase 3 : Passed")
else :
print("testcase 3 : Failed")
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
max_node = 1_000_000
nodes = {i: Node(i) for i in range(1, max_node + 1)}
initial_arrangement = [1, 5, 6, 7, 9, 4, 8, 2, 3, 10]
current = nodes[initial_arrangement[0]]
for i in range(1, len(initial_arrangement)):
prev = initial_arrangement[i - 1]
nodes[prev].next = nodes[initial_arrangement[i]]
for i in range(len(initial_arrangement) + 1, max_node + 1):
nodes[i - 1].next = nodes[i]
nodes[max_node].next = current
def take_n(start, n):
cur = start
for _ in range(n):
cur = cur.next
snippet_start = start.next
start.next = cur.next
cur.next = None
return snippet_start
def insert(insertion_point, nodes):
end = insertion_point.next
insertion_point.next = nodes
cur = nodes
while cur.next is not None:
cur = cur.next
cur.next = end
def decrement_label(l):
if l <= 1:
return max_node
else:
return l - 1
for i in range(10_000_000):
picked_up = take_n(current, 3)
picked_values = set(
[picked_up.value, picked_up.next.value, picked_up.next.next.value]
)
destination = decrement_label(current.value)
while destination in picked_values:
destination = decrement_label(destination)
insert(nodes[destination], picked_up)
current = current.next
print(nodes[1].next.value * nodes[1].next.next.value)
|
"""
Main test configuration
"""
def pytest_addoption(parser):
"""Add extra CLI options for integration testing"""
# TODO(RKM 2019-12-31) Update docs
parser.addoption("--run-integration", action="store_true")
parser.addoption("--docker-host", action="store")
parser.addoption(
"--integration-sim",
action="store",
default="bluesky",
choices=["bluesky", "machcoll"],
)
|
# Solution to Advent of Code 2020 day 5
# Read data
with open("input.txt") as inFile:
seats = inFile.read().split("\n")
# Part 1
seatIDs = []
for seat in seats:
row = int(seat[:7].replace("F", "0").replace("B", "1"), base=2)
column = int(seat[7:].replace("L", "0").replace("R", "1"), base=2)
seatIDs.append(row * 8 + column)
print("Max seat ID:", max(seatIDs))
# Part 2
missingSeats = set(range(1023)) - set(seatIDs)
for seat in missingSeats:
if not ((seat - 1) in missingSeats or (seat + 1) in missingSeats):
mySeat = seat
break
print("My seat ID:", mySeat)
|
def factorial(n):
if 0 < n < 13:
return n * factorial(n-1)
elif n == 0:
return 1
else:
raise ValueError
|
# Name or IP of the machine running vocabulary pet server
HOST = 'localhost'
# Port Name of vocabulary pet server
PORT = '8080'
# Please fill into the brakets the root directory of vocabulary pet
# Example: STATIC_PATH = '/home/user/vocabulary_pet/static'
STATIC_PATH = '/<vocabulary_pet_directory>/static'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.