content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
_base_ = "./FlowNet512_1.5AugCosyAAEGray_Aggressive_Flat_Pbr_01_ape.py"
OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_Aggressive_Flat_lmPbr_SO/benchvise"
DATASETS = dict(TRAIN=("lm_pbr_benchvise_train",), TEST=("lm_real_benchvise_test",))
# bbnc7
# objects benchvise Avg(1)
# ad_2 10.77 10.77
# ad_5 48.01 48.01
# ad_10 92.92 92.92
# rete_2 43.55 43.55
# rete_5 99.32 99.32
# rete_10 100.00 100.00
# re_2 57.32 57.32
# re_5 99.32 99.32
# re_10 100.00 100.00
# te_2 82.25 82.25
# te_5 100.00 100.00
# te_10 100.00 100.00
# proj_2 74.88 74.88
# proj_5 99.22 99.22
# proj_10 100.00 100.00
# re 1.97 1.97
# te 0.01 0.01
| _base_ = './FlowNet512_1.5AugCosyAAEGray_Aggressive_Flat_Pbr_01_ape.py'
output_dir = 'output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_Aggressive_Flat_lmPbr_SO/benchvise'
datasets = dict(TRAIN=('lm_pbr_benchvise_train',), TEST=('lm_real_benchvise_test',)) |
class ChannelLengthException(Exception):
'''channel searched is more than 16 characters
use with the command line functions
'''
pass
class ChannelCharactersException(Exception):
'''
it should not contain characters that cannot be used in a channel
'''
pass
class ChannelQuotesException(Exception):
'''
it should remove any quotation marks
'''
pass
class ChannelEmptyException(Exception):
'''
it should not be an empty string
'''
pass
class ChannelTypeException(Exception):
'''
the channel type should be able to be made to a string
throw exception when it fails to be made a string
'''
class ChannelMissingException(Exception):
'''
the channel doesnt exist
'''
class ChannelAlreadyEnteredException(Exception):
'''for when a channel already exists in a data structure .
raise this exception
'''
| class Channellengthexception(Exception):
"""channel searched is more than 16 characters
use with the command line functions
"""
pass
class Channelcharactersexception(Exception):
"""
it should not contain characters that cannot be used in a channel
"""
pass
class Channelquotesexception(Exception):
"""
it should remove any quotation marks
"""
pass
class Channelemptyexception(Exception):
"""
it should not be an empty string
"""
pass
class Channeltypeexception(Exception):
"""
the channel type should be able to be made to a string
throw exception when it fails to be made a string
"""
class Channelmissingexception(Exception):
"""
the channel doesnt exist
"""
class Channelalreadyenteredexception(Exception):
"""for when a channel already exists in a data structure .
raise this exception
""" |
# Algorithm: Longest monotonic subsequence
# Overall Time Complexity: O(n^2).
# Space Complexity: O(n).
# Author: https://www.linkedin.com/in/kilar.
def monotonic_subsequence(arr):
Dict = {}
maximum = 0
for i in range(len(arr)):
Dict[i] = [arr[i]]
for j in range(i + 1, len(arr)):
if arr[j] >= Dict[i][-1]:
Dict[i].append(arr[j])
for m in Dict:
temp = maximum
maximum = max(maximum, len(Dict[m]))
if temp < maximum:
key = m
return Dict[key]
| def monotonic_subsequence(arr):
dict = {}
maximum = 0
for i in range(len(arr)):
Dict[i] = [arr[i]]
for j in range(i + 1, len(arr)):
if arr[j] >= Dict[i][-1]:
Dict[i].append(arr[j])
for m in Dict:
temp = maximum
maximum = max(maximum, len(Dict[m]))
if temp < maximum:
key = m
return Dict[key] |
class ArticleCandidate:
"""This is a helpclass to store the result of an article after it was extracted. Every implemented extractor
returns an ArticleCanditate as result.
"""
url = None
title = None
description = None
text = None
topimage = None
author = None
publish_date = None
extractor = None
language = None
| class Articlecandidate:
"""This is a helpclass to store the result of an article after it was extracted. Every implemented extractor
returns an ArticleCanditate as result.
"""
url = None
title = None
description = None
text = None
topimage = None
author = None
publish_date = None
extractor = None
language = None |
class Record:
def __init__(self, row_id):
self.row_id = row_id
class Table:
lookup_table = {}
@classmethod
def get_record(cls, row_id: int) -> Record:
"""
if row_id not in cls.lookup_table,
instantiate Record object on the fly.
"""
if row_id not in cls.lookup_table.keys():
# There must be more args.
cls.lookup_table[row_id] = Record(row_id)
return cls.lookup_table[row_id]
if __name__ == '__main__':
Table.get_record(1)
| class Record:
def __init__(self, row_id):
self.row_id = row_id
class Table:
lookup_table = {}
@classmethod
def get_record(cls, row_id: int) -> Record:
"""
if row_id not in cls.lookup_table,
instantiate Record object on the fly.
"""
if row_id not in cls.lookup_table.keys():
cls.lookup_table[row_id] = record(row_id)
return cls.lookup_table[row_id]
if __name__ == '__main__':
Table.get_record(1) |
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
red = 0
white = 0
blue = 0
for i in nums:
if i == 0:
red += 1
elif i == 1:
white += 1
else:
blue += 1
for i in range(len(nums)):
if red:
nums[i] = 0
red -= 1
elif white:
nums[i] = 1
white -= 1
else:
nums[i] = 2
| class Solution:
def sort_colors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
red = 0
white = 0
blue = 0
for i in nums:
if i == 0:
red += 1
elif i == 1:
white += 1
else:
blue += 1
for i in range(len(nums)):
if red:
nums[i] = 0
red -= 1
elif white:
nums[i] = 1
white -= 1
else:
nums[i] = 2 |
# p43.py
str1 = input().split()
str1.reverse()
def exp():
s = str1.pop()
if s[0] == '+':
return exp() + exp()
elif s[0] == '-':
return exp() - exp()
elif s[0] == '*':
return exp() * exp()
elif s[0] == '/':
return exp() / exp()
else:
return float(s)
print(int(exp()))
| str1 = input().split()
str1.reverse()
def exp():
s = str1.pop()
if s[0] == '+':
return exp() + exp()
elif s[0] == '-':
return exp() - exp()
elif s[0] == '*':
return exp() * exp()
elif s[0] == '/':
return exp() / exp()
else:
return float(s)
print(int(exp())) |
#!/usr/bin/env python3
# calculate path of lowest risk
# use Dijkstra algorithm
risk = []
with open('input', 'r') as data:
lines = data.readlines()
for line in lines:
risk.append([int(l) for l in line.strip()])
# prepare nodes
# we might get up with x <-> y again...
graph = []
for y in range(len(risk)):
graph.append([{"visited": False, "risk": 10000000} for x in range(len(risk[y]))])
def visit_neighbors(position, graph):
x = position[0]
y = position[1]
# if neighbor was not evaluated and path through current
# costs less, then update count
if x-1 >= 0:
if not graph[x-1][y]["visited"]:
if graph[x][y]["risk"] + risk[x-1][y] < graph[x-1][y]["risk"]:
graph[x-1][y]["risk"] = graph[x][y]["risk"] + risk[x-1][y]
if x+1 < len(graph[y]):
if not graph[x+1][y]["visited"]:
if graph[x][y]["risk"] + risk[x+1][y] < graph[x+1][y]["risk"]:
graph[x+1][y]["risk"] = graph[x][y]["risk"] + risk[x+1][y]
if y-1 >= 0:
if not graph[x][y-1]["visited"]:
if graph[x][y]["risk"] + risk[x][y-1] < graph[x][y-1]["risk"]:
graph[x][y-1]["risk"] = graph[x][y]["risk"] + risk[x][y-1]
if y+1 < len(graph):
if not graph[x][y+1]["visited"]:
if graph[x][y]["risk"] + risk[x][y+1] < graph[x][y+1]["risk"]:
graph[x][y+1]["risk"] = graph[x][y]["risk"] + risk[x][y+1]
return graph
def get_lowest_unvisited(graph):
lowest = None
for y in range(len(graph)):
for x in range(len(graph[y])):
if not graph[x][y]["visited"]:
if lowest == None or graph[x][y]["risk"] < graph[lowest[0]][lowest[1]]["risk"]:
lowest = [x, y]
return lowest
# enter the starting node
position = [0,0]
graph[0][0]["visited"] = True
# special: start node is not counted
graph[0][0]["risk"] = 0
end = [len(graph)-1, len(graph[0])-1]
print(str(end))
while position != end:
graph = visit_neighbors(position, graph)
graph[position[0]][position[1]]["visited"] = True
position = get_lowest_unvisited(graph)
#for y in range(len(graph)):
# for x in range(len(graph[y])):
# risk = graph[y][x]["risk"]
# print(f'{risk:02d}', end=" ")
# print("")
#print(str(position))
print(graph[end[0]][end[1]]["risk"])
| risk = []
with open('input', 'r') as data:
lines = data.readlines()
for line in lines:
risk.append([int(l) for l in line.strip()])
graph = []
for y in range(len(risk)):
graph.append([{'visited': False, 'risk': 10000000} for x in range(len(risk[y]))])
def visit_neighbors(position, graph):
x = position[0]
y = position[1]
if x - 1 >= 0:
if not graph[x - 1][y]['visited']:
if graph[x][y]['risk'] + risk[x - 1][y] < graph[x - 1][y]['risk']:
graph[x - 1][y]['risk'] = graph[x][y]['risk'] + risk[x - 1][y]
if x + 1 < len(graph[y]):
if not graph[x + 1][y]['visited']:
if graph[x][y]['risk'] + risk[x + 1][y] < graph[x + 1][y]['risk']:
graph[x + 1][y]['risk'] = graph[x][y]['risk'] + risk[x + 1][y]
if y - 1 >= 0:
if not graph[x][y - 1]['visited']:
if graph[x][y]['risk'] + risk[x][y - 1] < graph[x][y - 1]['risk']:
graph[x][y - 1]['risk'] = graph[x][y]['risk'] + risk[x][y - 1]
if y + 1 < len(graph):
if not graph[x][y + 1]['visited']:
if graph[x][y]['risk'] + risk[x][y + 1] < graph[x][y + 1]['risk']:
graph[x][y + 1]['risk'] = graph[x][y]['risk'] + risk[x][y + 1]
return graph
def get_lowest_unvisited(graph):
lowest = None
for y in range(len(graph)):
for x in range(len(graph[y])):
if not graph[x][y]['visited']:
if lowest == None or graph[x][y]['risk'] < graph[lowest[0]][lowest[1]]['risk']:
lowest = [x, y]
return lowest
position = [0, 0]
graph[0][0]['visited'] = True
graph[0][0]['risk'] = 0
end = [len(graph) - 1, len(graph[0]) - 1]
print(str(end))
while position != end:
graph = visit_neighbors(position, graph)
graph[position[0]][position[1]]['visited'] = True
position = get_lowest_unvisited(graph)
print(graph[end[0]][end[1]]['risk']) |
stack = []
stack.append("Moby Dick")
stack.append("The Great Gatsby")
stack.append("Hamlet")
stack.pop()
stack.append("The Iliad")
stack.append("Pride and Prejudice")
stack.pop()
stack.append("To Kill a Mockingbird")
stack.append("Gulliver's Travels")
stack.append("Don Quixote")
stack.pop()
stack.pop()
stack.pop()
stack.pop()
print(stack) # ['Moby Dick', 'The Great Gatsby'] | stack = []
stack.append('Moby Dick')
stack.append('The Great Gatsby')
stack.append('Hamlet')
stack.pop()
stack.append('The Iliad')
stack.append('Pride and Prejudice')
stack.pop()
stack.append('To Kill a Mockingbird')
stack.append("Gulliver's Travels")
stack.append('Don Quixote')
stack.pop()
stack.pop()
stack.pop()
stack.pop()
print(stack) |
MOCK_PLAYER = {
"_id": 1234,
"uuid": "2ad3kfei9ikmd",
"displayname": "TestPlayer123",
"knownAliases": ["1234", "test", "TestPlayer123"],
"firstLogin": 123456,
"lastLogin": 150996,
"achievementsOneTime": ["MVP", "MVP2", "BedwarsMVP"],
"achievementPoints": 300,
"achievements": {"bedwars_level": 5, "general_challenger": 7, "bedwars_wins": 18},
"networkExp": 3400,
"challenges": {"all_time": {"DUELS_challenge": 1, "BEDWARS_challenge": 6}},
"mostRecentGameType": "BEDWARS",
"socialMedia": {"links": {"DISCORD": "test#1234"}},
"karma": 8888,
"mcVersionRp": "1.8.9",
"petStats": {},
"currentGadget": "Dummy thingy",
}
| mock_player = {'_id': 1234, 'uuid': '2ad3kfei9ikmd', 'displayname': 'TestPlayer123', 'knownAliases': ['1234', 'test', 'TestPlayer123'], 'firstLogin': 123456, 'lastLogin': 150996, 'achievementsOneTime': ['MVP', 'MVP2', 'BedwarsMVP'], 'achievementPoints': 300, 'achievements': {'bedwars_level': 5, 'general_challenger': 7, 'bedwars_wins': 18}, 'networkExp': 3400, 'challenges': {'all_time': {'DUELS_challenge': 1, 'BEDWARS_challenge': 6}}, 'mostRecentGameType': 'BEDWARS', 'socialMedia': {'links': {'DISCORD': 'test#1234'}}, 'karma': 8888, 'mcVersionRp': '1.8.9', 'petStats': {}, 'currentGadget': 'Dummy thingy'} |
# -*- coding: utf-8 -*
INN_TEST_WEIGHTS_10 = (2, 4, 10, 3, 5, 9, 4, 6, 8, 0)
INN_TEST_WEIGHTS_12_0 = (7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0, 0)
INN_TEST_WEIGHTS_12_1 = (3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0)
def test_inn_org(inn):
""" returns True if inn of the organisation pass the check
"""
if len(inn) != 10:
return False
res = 0
for i, char in enumerate(inn):
res += int(char) * INN_TEST_WEIGHTS_10[i]
res = res % 11 % 10
return res == int(inn[-1])
def test_inn_person(inn):
""" returns True if inn of the person pass the check
"""
if len(inn) != 12:
return False
res1 = 0
for i, char in enumerate(inn):
res1 += int(char) * INN_TEST_WEIGHTS_12_0[i]
res1 = res1 % 11 % 10
res2 = 0
for i, char in enumerate(inn):
res2 += int(char) * INN_TEST_WEIGHTS_12_1[i]
res2 = res2 % 11 % 10
return (res1 == int(inn[-2])) and (res2 == int(inn[-1]))
def test_inn(inn):
""" returns True if inn pass the check
"""
if len(inn) == 10:
return test_inn_org(inn)
elif len(inn) == 12:
return test_inn_person(inn)
return False
BANK_ACC_TEST_WEIGHTS = ((7, 1, 3) * 8)[:-1]
def test_bank_number(anumber):
if not isinstance(anumber, str) and not anumber.isdigit():
return False
if len(anumber) != 23:
return False
res = 0
for i, char in enumerate(anumber):
res += int(char) * BANK_ACC_TEST_WEIGHTS[i]
return (res % 10) == 0
def test_bank_corr_account_number(account, bik):
return len(account) == 20 and len(bik) == 7 and \
test_bank_number('0' + bik[4:6] + account)
def test_bank_account_number(account, bik):
return len(account) == 20 and len(bik) == 7 and \
test_bank_number(bik[-3:] + account)
| inn_test_weights_10 = (2, 4, 10, 3, 5, 9, 4, 6, 8, 0)
inn_test_weights_12_0 = (7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0, 0)
inn_test_weights_12_1 = (3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0)
def test_inn_org(inn):
""" returns True if inn of the organisation pass the check
"""
if len(inn) != 10:
return False
res = 0
for (i, char) in enumerate(inn):
res += int(char) * INN_TEST_WEIGHTS_10[i]
res = res % 11 % 10
return res == int(inn[-1])
def test_inn_person(inn):
""" returns True if inn of the person pass the check
"""
if len(inn) != 12:
return False
res1 = 0
for (i, char) in enumerate(inn):
res1 += int(char) * INN_TEST_WEIGHTS_12_0[i]
res1 = res1 % 11 % 10
res2 = 0
for (i, char) in enumerate(inn):
res2 += int(char) * INN_TEST_WEIGHTS_12_1[i]
res2 = res2 % 11 % 10
return res1 == int(inn[-2]) and res2 == int(inn[-1])
def test_inn(inn):
""" returns True if inn pass the check
"""
if len(inn) == 10:
return test_inn_org(inn)
elif len(inn) == 12:
return test_inn_person(inn)
return False
bank_acc_test_weights = ((7, 1, 3) * 8)[:-1]
def test_bank_number(anumber):
if not isinstance(anumber, str) and (not anumber.isdigit()):
return False
if len(anumber) != 23:
return False
res = 0
for (i, char) in enumerate(anumber):
res += int(char) * BANK_ACC_TEST_WEIGHTS[i]
return res % 10 == 0
def test_bank_corr_account_number(account, bik):
return len(account) == 20 and len(bik) == 7 and test_bank_number('0' + bik[4:6] + account)
def test_bank_account_number(account, bik):
return len(account) == 20 and len(bik) == 7 and test_bank_number(bik[-3:] + account) |
class Solution:
def XXX(self, root: TreeNode) -> int:
self.maxleftlength = 0
self.maxrightlength = 0
return self.dp(root)
def dp(self,root):
if(root is None):
return 0
self.maxleftlength = self.dp(root.left)
self.maxrightlength = self.dp(root.right)
return max(self.maxleftlength,self.maxrightlength)+1
| class Solution:
def xxx(self, root: TreeNode) -> int:
self.maxleftlength = 0
self.maxrightlength = 0
return self.dp(root)
def dp(self, root):
if root is None:
return 0
self.maxleftlength = self.dp(root.left)
self.maxrightlength = self.dp(root.right)
return max(self.maxleftlength, self.maxrightlength) + 1 |
{'application':{'type':'Application',
'name':'GuiPyBlog',
'backgrounds': [
{'type':'Background',
'name':'bgTextRouter',
'title':'TextRouter 0.60',
'size':(650, 426),
'statusBar':1,
'icon':'tr.ico',
'style':['resizeable'],
'menubar': {'type':'MenuBar',
'menus': [
{'type':'Menu',
'name':'menuFile',
'label':'&File',
'items': [
{'type':'MenuItem',
'name':'menuFileLoad',
'label':'&Open',
},
{'type':'MenuItem',
'name':'menuFileLoadFrom',
'label':'Op&en...',
},
{'type':'MenuItem',
'name':'menuFileSave',
'label':'&Save',
},
{'type':'MenuItem',
'name':'menuFileSaveAs',
'label':'Save &As...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuFileLoadConfig',
'label':'&Load Config...',
},
{'type':'MenuItem',
'name':'menuFileSaveConfig',
'label':'S&ave Config',
},
{'type':'MenuItem',
'name':'menuFileSaveConfigAs',
'label':'Sa&ve Config As...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuFilePreferences',
'label':'&Preferences...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuFileExit',
'label':'E&xit\tCtrl+Q',
'command':'exit',
},
]
},
{'type':'Menu',
'name':'Edit',
'label':'&Edit',
'items': [
{'type':'MenuItem',
'name':'menuEditUndo',
'label':'&Undo\tCtrl+Z',
},
{'type':'MenuItem',
'name':'menuEditRedo',
'label':'&Redo\tCtrl+Y',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuEditCut',
'label':'Cu&t\tCtrl+X',
},
{'type':'MenuItem',
'name':'menuEditCopy',
'label':'&Copy\tCtrl+C',
},
{'type':'MenuItem',
'name':'menuEditPaste',
'label':'&Paste\tCtrl+V',
},
{ 'type':'MenuItem', 'name':'editSep2', 'label':'-' },
{ 'type':'MenuItem',
'name':'menuEditFind',
'label':'&Find...\tCtrl+F',
'command':'doEditFind'},
{ 'type':'MenuItem',
'name':'menuEditFindNext',
'label':'&Find Next\tF3',
'command':'doEditFindNext'},
{'type':'MenuItem',
'name':'editSep3',
'label':'-',
},
{'type':'MenuItem',
'name':'menuEditRemoveNewlines',
'label':'Remove &Newlines',
},
{'type':'MenuItem',
'name':'menuEditWrapText',
'label':'&Wrap Text',
},
{'type':'MenuItem',
'name':'editSep4',
'label':'-',
},
{'type':'MenuItem',
'name':'menuEditClear',
'label':'Cle&ar\tDel',
},
{'type':'MenuItem',
'name':'menuEditSelectAll',
'label':'Select A&ll\tCtrl+A',
},
]
},
{'type':'Menu',
'name':'HTML',
'label':'F&ormat',
'items': [
{'type':'MenuItem',
'name':'menuHtmlBold',
'label':'&Bold\tCtrl+B',
'command':'menuHtmlMake',
},
{'type':'MenuItem',
'name':'menuHtmlItalic',
'label':'&Italic\tCtrl+I',
'command':'menuHtmlMake',
},
{'type':'MenuItem',
'name':'menuHtmlCenter',
'label':'&Center',
},
{'type':'MenuItem',
'name':'menuHtmlCode',
'label':'C&ode',
'command':'menuHtmlMake',
},
{'type':'MenuItem',
'name':'menuHtmlBlockquote',
'label':'Block"e',
'command':'menuHtmlMake',
},
{'type':'MenuItem',
'name':'htmlSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuHtmlAddLink',
'label':'&Add Link...\tCtrl+L',
'command':'menuHtmlAddLink',
},
{'type':'MenuItem',
'name':'htmlSep2',
'label':'-',
},
{'type':'MenuItem',
'name':'menuHtmlStripHTML',
'label':'&Strip HTML\tCtrl+G',
},
{'type':'MenuItem',
'name':'htmlSep2',
'label':'-',
},
{'type':'MenuItem',
'name':'menuHtmlPreferences',
'label':'Preferences...',
},
]
},
{'type':'Menu',
'name':'menuRouteTo',
'label':'&Route Text To...',
'items': [
{'type':'MenuItem',
'name':'menuRouteToBlogger',
'label':'&Blogger\tCtrl+W',
},
{'type':'MenuItem',
'name':'menuRouteToManila',
'label':'&Manila\tCtrl+E',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuRouteToEmailPredefined',
'label':'&Predefined Email...\tCtrl+R',
},
{'type':'MenuItem',
'name':'menuRouteToEmail',
'label':'&New Email...\tCtrl+T',
},
# {'type':'MenuItem',
# 'name':'editSep1',
# 'label':'-',
# },
# {'type':'MenuItem',
# 'name':'menuRouteToRSS',
# 'label':'RSS File...\tAlt-R',
# },
]
},
{'type':'Menu',
'name':'menuManila',
'label':'&Manila',
'items': [
{'type':'MenuItem',
'name':'menuManilaLogin',
'label':'&Login',
},
{'type':'MenuItem',
'name':'menuManilaFlipHomepage',
'label':'&Flip Homepage...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaAddToHP',
'label':'&Add To Homepage',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaGetHP',
'label':'&Get Current Homepage',
},
{'type':'MenuItem',
'name':'menuManilaSetAsHP',
'label':'&Set As Homepage',
},
{'type':'MenuItem',
'name':'menuManilaSetHPFromOPML',
'label':'Set &Homepage From OPML',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaGetStoryList',
'label':'Get Story Lis&t',
},
{'type':'MenuItem',
'name':'menuManilaDownloadStory',
'label':'&Download Story...',
},
{'type':'MenuItem',
'name':'menuManilaUploadStory',
'label':'&Upload Story...',
},
{'type':'MenuItem',
'name':'menuManilaPostNewStory',
'label':'Post As &New Story',
},
{'type':'MenuItem',
'name':'menuManilaSetStoryAsHP',
'label':'S&et Story As Homepage',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaUploadPicture',
'label':'Upload &Image...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaJumpTo',
'label':'&Jump To URL...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaChooseActiveAccount',
'label':'Choose Active Account...',
},
{'type':'MenuItem',
'name':'menuManilaNewAccount',
'label':'New Account...',
},
{'type':'MenuItem',
'name':'menuManilaEditAccount',
'label':'Edit Account...',
},
{'type':'MenuItem',
'name':'menuManilaRemoveAccount',
'label':'Remove Account...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaPreferences',
'label':'&Preferences...',
},
]
},
{'type':'Menu',
'name':'menuBlogger',
'label':'&Blogger',
'items': [
{'type':'MenuItem',
'name':'menuBloggerLogin',
'label':'&Login',
},
{'type':'MenuItem',
'name':'menuBloggerChooseBlog',
'label':'&Choose Blog...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerFetchPosts',
'label':'&Fetch Previous Posts',
},
{'type':'MenuItem',
'name':'menuBloggerInsertPrevPost',
'label':'&Insert Previous Post...',
},
{'type':'MenuItem',
'name':'menuBloggerGetPost',
'label':'Ge&t Post By ID...',
},
{'type':'MenuItem',
'name':'menuBloggerUpdatePost',
'label':'&Update Post',
},
{'type':'MenuItem',
'name':'menuBloggerDeletePost',
'label':'&Delete Post...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerGetTemplate',
'label':'&Get Template...',
},
{'type':'MenuItem',
'name':'menuBloggerSetTemplate',
'label':'&Set Template...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerJumpTo',
'label':'&Jump To Blog...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerChooseActiveAccount',
'label':'Choose Active Account...',
},
{'type':'MenuItem',
'name':'menuBloggerNewAccount',
'label':'New Account...',
},
{'type':'MenuItem',
'name':'menuBloggerEditAccount',
'label':'Edit Account...',
},
{'type':'MenuItem',
'name':'menuBloggerRemoveAccount',
'label':'Remove Account...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerPreferences',
'label':'&Preferences...',
},
]
},
{'type':'Menu',
'name':'menuEmail',
'label':'Emai&l',
'items': [
{'type':'MenuItem',
'name':'menuEmailNewEmailRcpt',
'label':'New Email Recipient',
},
{'type':'MenuItem',
'name':'menuEmailRemoveEmailRcpt',
'label':'Remove Recipient',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuEmailPreferences',
'label':'&Preferences...',
},
# {'type':'MenuItem',
# 'name':'editSep1',
# 'label':'-',
# },
# {'type':'MenuItem',
# 'name':'menuSettingsRSS',
# 'label':'RSS Files...',
# },
]
},
{'type':'Menu',
'name':'menuUtilities',
'label':'&Utilities',
'items': [
{'type':'MenuItem',
'name':'menuUtilitiesExternalEditor',
'label':'&External Editor',
},
{'type':'MenuItem',
'name':'menuUtilitiesTextScroller',
'label':'&Text Auto-Scroller',
},
{'type':'MenuItem',
'name':'menuUtilitiesApplyFilter',
'label':'&Apply Filter',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuUtilitiesNewFilter',
'label':'&New Filter',
},
{'type':'MenuItem',
'name':'menuUtilitiesRemoveFilter',
'label':'&Remove Filter',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuUtilitiesNewShortcut',
'label':'New &Shortcut',
},
{'type':'MenuItem',
'name':'menuUtilitiesRemoveShortcut',
'label':'Remove S&hortcut',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
# {'type':'MenuItem',
# 'name':'menuUtilitiesLoadShortcuts',
# 'label':'&Load Shortcuts...',
# },
# {'type':'MenuItem',
# 'name':'menuUtilitiesSaveShortcuts',
# 'label':'Sa&ve Shortcuts...',
# },
# {'type':'MenuItem',
# 'name':'editSep1',
# 'label':'-',
# },
{'type':'MenuItem',
'name':'menuUtilitiesPreferences',
'label':'&Preferences...',
},
]
},
{'type':'Menu',
'name':'menuHelp',
'label':'&Help',
'items': [
{'type':'MenuItem',
'name':'menuHelpHelp',
'label':'&Help (loads browser)',
},
{'type':'MenuItem',
'name':'menuHelpReadme',
'label':'&README (loads browser)',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuHelpAbout',
'label':'&About TextRouter...',
},
]
},
]
},
'components': [
{'type':'StaticText',
'name':'lblSubject',
'position':(0, 0),
'size':(80, -1),
'text':'Title/Subject:',
},
{'type':'TextField',
'name':'area2',
'position':(100, 0),
'size':(530, 22),
},
{'type':'TextArea',
'name':'area1',
'position':(0, 40),
'size':(640, 300),
},
{'type':'Button',
'name':'buttonClearIt',
'position':(1, 303),
'size':(120, -1),
'label':'Clear It',
},
{'type':'Button',
'name':'buttonClipIt',
'position':(1, 327),
'size':(120, -1),
'label':'Get Clipboard Text',
},
{'type':'RadioGroup',
'name':'nextInputActionMode',
'position':(131, 303),
#'size':(240, -1),
'label':'Input Action:',
'layout':'horizontal',
'items':['inserts', 'appends', 'replaces'],
'stringSelection':'inserts',
'toolTip':'Controls how the next text input action (from file, clipboard, remote server) works.'
},
{'type':'RadioGroup',
'name':'nextOutputActionMode',
'position':(380, 303),
#'size':(160, -1),
'label':'Output Action Works On:',
'layout':'horizontal',
'items':['all', 'selection'],
'stringSelection':'all',
'toolTip':'Controls how the next text output action (to file, blogger, manila, email) works.'
},
] # end components
} # end background
] # end backgrounds
} }
| {'application': {'type': 'Application', 'name': 'GuiPyBlog', 'backgrounds': [{'type': 'Background', 'name': 'bgTextRouter', 'title': 'TextRouter 0.60', 'size': (650, 426), 'statusBar': 1, 'icon': 'tr.ico', 'style': ['resizeable'], 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu', 'name': 'menuFile', 'label': '&File', 'items': [{'type': 'MenuItem', 'name': 'menuFileLoad', 'label': '&Open'}, {'type': 'MenuItem', 'name': 'menuFileLoadFrom', 'label': 'Op&en...'}, {'type': 'MenuItem', 'name': 'menuFileSave', 'label': '&Save'}, {'type': 'MenuItem', 'name': 'menuFileSaveAs', 'label': 'Save &As...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuFileLoadConfig', 'label': '&Load Config...'}, {'type': 'MenuItem', 'name': 'menuFileSaveConfig', 'label': 'S&ave Config'}, {'type': 'MenuItem', 'name': 'menuFileSaveConfigAs', 'label': 'Sa&ve Config As...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuFilePreferences', 'label': '&Preferences...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuFileExit', 'label': 'E&xit\tCtrl+Q', 'command': 'exit'}]}, {'type': 'Menu', 'name': 'Edit', 'label': '&Edit', 'items': [{'type': 'MenuItem', 'name': 'menuEditUndo', 'label': '&Undo\tCtrl+Z'}, {'type': 'MenuItem', 'name': 'menuEditRedo', 'label': '&Redo\tCtrl+Y'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditCut', 'label': 'Cu&t\tCtrl+X'}, {'type': 'MenuItem', 'name': 'menuEditCopy', 'label': '&Copy\tCtrl+C'}, {'type': 'MenuItem', 'name': 'menuEditPaste', 'label': '&Paste\tCtrl+V'}, {'type': 'MenuItem', 'name': 'editSep2', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditFind', 'label': '&Find...\tCtrl+F', 'command': 'doEditFind'}, {'type': 'MenuItem', 'name': 'menuEditFindNext', 'label': '&Find Next\tF3', 'command': 'doEditFindNext'}, {'type': 'MenuItem', 'name': 'editSep3', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditRemoveNewlines', 'label': 'Remove &Newlines'}, {'type': 'MenuItem', 'name': 'menuEditWrapText', 'label': '&Wrap Text'}, {'type': 'MenuItem', 'name': 'editSep4', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditClear', 'label': 'Cle&ar\tDel'}, {'type': 'MenuItem', 'name': 'menuEditSelectAll', 'label': 'Select A&ll\tCtrl+A'}]}, {'type': 'Menu', 'name': 'HTML', 'label': 'F&ormat', 'items': [{'type': 'MenuItem', 'name': 'menuHtmlBold', 'label': '&Bold\tCtrl+B', 'command': 'menuHtmlMake'}, {'type': 'MenuItem', 'name': 'menuHtmlItalic', 'label': '&Italic\tCtrl+I', 'command': 'menuHtmlMake'}, {'type': 'MenuItem', 'name': 'menuHtmlCenter', 'label': '&Center'}, {'type': 'MenuItem', 'name': 'menuHtmlCode', 'label': 'C&ode', 'command': 'menuHtmlMake'}, {'type': 'MenuItem', 'name': 'menuHtmlBlockquote', 'label': 'Block"e', 'command': 'menuHtmlMake'}, {'type': 'MenuItem', 'name': 'htmlSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuHtmlAddLink', 'label': '&Add Link...\tCtrl+L', 'command': 'menuHtmlAddLink'}, {'type': 'MenuItem', 'name': 'htmlSep2', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuHtmlStripHTML', 'label': '&Strip HTML\tCtrl+G'}, {'type': 'MenuItem', 'name': 'htmlSep2', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuHtmlPreferences', 'label': 'Preferences...'}]}, {'type': 'Menu', 'name': 'menuRouteTo', 'label': '&Route Text To...', 'items': [{'type': 'MenuItem', 'name': 'menuRouteToBlogger', 'label': '&Blogger\tCtrl+W'}, {'type': 'MenuItem', 'name': 'menuRouteToManila', 'label': '&Manila\tCtrl+E'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuRouteToEmailPredefined', 'label': '&Predefined Email...\tCtrl+R'}, {'type': 'MenuItem', 'name': 'menuRouteToEmail', 'label': '&New Email...\tCtrl+T'}]}, {'type': 'Menu', 'name': 'menuManila', 'label': '&Manila', 'items': [{'type': 'MenuItem', 'name': 'menuManilaLogin', 'label': '&Login'}, {'type': 'MenuItem', 'name': 'menuManilaFlipHomepage', 'label': '&Flip Homepage...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuManilaAddToHP', 'label': '&Add To Homepage'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuManilaGetHP', 'label': '&Get Current Homepage'}, {'type': 'MenuItem', 'name': 'menuManilaSetAsHP', 'label': '&Set As Homepage'}, {'type': 'MenuItem', 'name': 'menuManilaSetHPFromOPML', 'label': 'Set &Homepage From OPML'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuManilaGetStoryList', 'label': 'Get Story Lis&t'}, {'type': 'MenuItem', 'name': 'menuManilaDownloadStory', 'label': '&Download Story...'}, {'type': 'MenuItem', 'name': 'menuManilaUploadStory', 'label': '&Upload Story...'}, {'type': 'MenuItem', 'name': 'menuManilaPostNewStory', 'label': 'Post As &New Story'}, {'type': 'MenuItem', 'name': 'menuManilaSetStoryAsHP', 'label': 'S&et Story As Homepage'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuManilaUploadPicture', 'label': 'Upload &Image...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuManilaJumpTo', 'label': '&Jump To URL...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuManilaChooseActiveAccount', 'label': 'Choose Active Account...'}, {'type': 'MenuItem', 'name': 'menuManilaNewAccount', 'label': 'New Account...'}, {'type': 'MenuItem', 'name': 'menuManilaEditAccount', 'label': 'Edit Account...'}, {'type': 'MenuItem', 'name': 'menuManilaRemoveAccount', 'label': 'Remove Account...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuManilaPreferences', 'label': '&Preferences...'}]}, {'type': 'Menu', 'name': 'menuBlogger', 'label': '&Blogger', 'items': [{'type': 'MenuItem', 'name': 'menuBloggerLogin', 'label': '&Login'}, {'type': 'MenuItem', 'name': 'menuBloggerChooseBlog', 'label': '&Choose Blog...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuBloggerFetchPosts', 'label': '&Fetch Previous Posts'}, {'type': 'MenuItem', 'name': 'menuBloggerInsertPrevPost', 'label': '&Insert Previous Post...'}, {'type': 'MenuItem', 'name': 'menuBloggerGetPost', 'label': 'Ge&t Post By ID...'}, {'type': 'MenuItem', 'name': 'menuBloggerUpdatePost', 'label': '&Update Post'}, {'type': 'MenuItem', 'name': 'menuBloggerDeletePost', 'label': '&Delete Post...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuBloggerGetTemplate', 'label': '&Get Template...'}, {'type': 'MenuItem', 'name': 'menuBloggerSetTemplate', 'label': '&Set Template...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuBloggerJumpTo', 'label': '&Jump To Blog...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuBloggerChooseActiveAccount', 'label': 'Choose Active Account...'}, {'type': 'MenuItem', 'name': 'menuBloggerNewAccount', 'label': 'New Account...'}, {'type': 'MenuItem', 'name': 'menuBloggerEditAccount', 'label': 'Edit Account...'}, {'type': 'MenuItem', 'name': 'menuBloggerRemoveAccount', 'label': 'Remove Account...'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuBloggerPreferences', 'label': '&Preferences...'}]}, {'type': 'Menu', 'name': 'menuEmail', 'label': 'Emai&l', 'items': [{'type': 'MenuItem', 'name': 'menuEmailNewEmailRcpt', 'label': 'New Email Recipient'}, {'type': 'MenuItem', 'name': 'menuEmailRemoveEmailRcpt', 'label': 'Remove Recipient'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEmailPreferences', 'label': '&Preferences...'}]}, {'type': 'Menu', 'name': 'menuUtilities', 'label': '&Utilities', 'items': [{'type': 'MenuItem', 'name': 'menuUtilitiesExternalEditor', 'label': '&External Editor'}, {'type': 'MenuItem', 'name': 'menuUtilitiesTextScroller', 'label': '&Text Auto-Scroller'}, {'type': 'MenuItem', 'name': 'menuUtilitiesApplyFilter', 'label': '&Apply Filter'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuUtilitiesNewFilter', 'label': '&New Filter'}, {'type': 'MenuItem', 'name': 'menuUtilitiesRemoveFilter', 'label': '&Remove Filter'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuUtilitiesNewShortcut', 'label': 'New &Shortcut'}, {'type': 'MenuItem', 'name': 'menuUtilitiesRemoveShortcut', 'label': 'Remove S&hortcut'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuUtilitiesPreferences', 'label': '&Preferences...'}]}, {'type': 'Menu', 'name': 'menuHelp', 'label': '&Help', 'items': [{'type': 'MenuItem', 'name': 'menuHelpHelp', 'label': '&Help (loads browser)'}, {'type': 'MenuItem', 'name': 'menuHelpReadme', 'label': '&README (loads browser)'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuHelpAbout', 'label': '&About TextRouter...'}]}]}, 'components': [{'type': 'StaticText', 'name': 'lblSubject', 'position': (0, 0), 'size': (80, -1), 'text': 'Title/Subject:'}, {'type': 'TextField', 'name': 'area2', 'position': (100, 0), 'size': (530, 22)}, {'type': 'TextArea', 'name': 'area1', 'position': (0, 40), 'size': (640, 300)}, {'type': 'Button', 'name': 'buttonClearIt', 'position': (1, 303), 'size': (120, -1), 'label': 'Clear It'}, {'type': 'Button', 'name': 'buttonClipIt', 'position': (1, 327), 'size': (120, -1), 'label': 'Get Clipboard Text'}, {'type': 'RadioGroup', 'name': 'nextInputActionMode', 'position': (131, 303), 'label': 'Input Action:', 'layout': 'horizontal', 'items': ['inserts', 'appends', 'replaces'], 'stringSelection': 'inserts', 'toolTip': 'Controls how the next text input action (from file, clipboard, remote server) works.'}, {'type': 'RadioGroup', 'name': 'nextOutputActionMode', 'position': (380, 303), 'label': 'Output Action Works On:', 'layout': 'horizontal', 'items': ['all', 'selection'], 'stringSelection': 'all', 'toolTip': 'Controls how the next text output action (to file, blogger, manila, email) works.'}]}]}} |
"""
Given a string of numbers and operators, return all possible results from computing
all the different possible ways to group numbers and operators. The valid operators
are +, - and *.
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Time complexity of this algorithm is Catalan number.
"""
def way_to_compute(input):
ans = []
for i in range(len(input)):
c = input[i]
if c in '-*+':
left = way_to_compute(input[:i])
right = way_to_compute(input[i+1:])
if c == "-":
ans.append( left - right )
elif c == "+":
ans.append( left + right )
elif c == "*":
ans.append( left * right )
if not ans:
ans.append(int(input))
return ans
print(way_to_compute("2*3-4*5"))
| """
Given a string of numbers and operators, return all possible results from computing
all the different possible ways to group numbers and operators. The valid operators
are +, - and *.
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Time complexity of this algorithm is Catalan number.
"""
def way_to_compute(input):
ans = []
for i in range(len(input)):
c = input[i]
if c in '-*+':
left = way_to_compute(input[:i])
right = way_to_compute(input[i + 1:])
if c == '-':
ans.append(left - right)
elif c == '+':
ans.append(left + right)
elif c == '*':
ans.append(left * right)
if not ans:
ans.append(int(input))
return ans
print(way_to_compute('2*3-4*5')) |
WARNING_HEADER = '[\033[1m\033[93mWARNING\033[0m]'
def warning_message(message_text):
print('{header} {text}'.format(header=WARNING_HEADER, text=message_text))
| warning_header = '[\x1b[1m\x1b[93mWARNING\x1b[0m]'
def warning_message(message_text):
print('{header} {text}'.format(header=WARNING_HEADER, text=message_text)) |
class WebsocketError(Exception):
pass
class NoTokenError(WebsocketError):
pass
| class Websocketerror(Exception):
pass
class Notokenerror(WebsocketError):
pass |
a,b=0,1
while b<10:
print(b)
a,b=b,a+b
| (a, b) = (0, 1)
while b < 10:
print(b)
(a, b) = (b, a + b) |
# while loops
"""
a = 1
b = 10
while a < b:
print(a) #will go on forever
"""
# Docstringed loop above. Uncomment to see an infinite loop
# then kill it or wait for Python to reach an error
a = 1
b = 10
while a < b:
print(a)
a = a +1 # Now it will stop
# Bonus: calculate the iterations before this stops
while True:
# Asks you things forever
answer = input('Are you happy?')
# Unless you are forced into optimism
if answer == 'yes':
break
| """
a = 1
b = 10
while a < b:
print(a) #will go on forever
"""
a = 1
b = 10
while a < b:
print(a)
a = a + 1
while True:
answer = input('Are you happy?')
if answer == 'yes':
break |
def thank_you(donation):
if donation >= 1000:
print("Thank you for your donation! You have achieved platinum donation status!")
elif donation >= 500:
print("Thank you for your donation! You have achieved gold donation status!")
elif donation >= 100:
print("Thank you for your donation! You have achieved silver donation status!")
else:
print("Thank you for your donation! You have achieved bronze donation status!")
thank_you(500)
def grade_converter(gpa):
grade = "F"
if gpa >= 4.0:
grade = "A"
elif gpa >= 3.0:
grade = "B"
elif gpa >= 2.0:
grade = "C"
elif gpa >= 1.0:
grade = "D"
return grade
print(grade_converter(2.0)) | def thank_you(donation):
if donation >= 1000:
print('Thank you for your donation! You have achieved platinum donation status!')
elif donation >= 500:
print('Thank you for your donation! You have achieved gold donation status!')
elif donation >= 100:
print('Thank you for your donation! You have achieved silver donation status!')
else:
print('Thank you for your donation! You have achieved bronze donation status!')
thank_you(500)
def grade_converter(gpa):
grade = 'F'
if gpa >= 4.0:
grade = 'A'
elif gpa >= 3.0:
grade = 'B'
elif gpa >= 2.0:
grade = 'C'
elif gpa >= 1.0:
grade = 'D'
return grade
print(grade_converter(2.0)) |
'''
This file holds all the constants that are required for programming the LIS3DH
including register addresses and their values
'''
'''
The LIS3DH I2C address
'''
LIS3DH_I2C_ADDR = 0x18
'''
The LIS3DH Register Map
'''
#0x00 - 0x06 - reserved
STATUS_REG_AUX = 0x07
OUT_ADC1_L = 0x08
OUT_ADC1_H = 0x09
OUT_ADC2_L = 0x0A
OUT_ADC2_H = 0x0B
OUT_ADC3_L = 0x0C
OUT_ADC3_H = 0x0D
INT_COUNTER_REG = 0x0E
WHO_AM_I = 0x0F
# 0x10 0x1E - reserved
TEMP_CFG_REG = 0x1F
CTRL_REG1 = 0x20
CTRL_REG2 = 0x21
CTRL_REG3 = 0x22
CTRL_REG4 = 0x23
CTRL_REG5 = 0x24
CTRL_REG6 = 0x25
REFERENCE = 0x26
STATUS_REG2 = 0x27
OUT_X_L = 0x28
OUT_X_H = 0x29
OUT_Y_L = 0x2A
OUT_Y_H = 0x2B
OUT_Z_L = 0x2C
OUT_Z_H = 0x2D
FIFO_CTRL_REG = 0x2E
FIFO_SRC_REG = 0x2F
INT1_CFG = 0x30
INT1_SOURCE = 0x31
INT1_THS = 0x32
INT1_DURATION = 0x33
#0x34 - 0x37 - reserved
CLICK_CFG = 0x38
CLICK_SRC = 0x39
CLICK_THS = 0x3A
TIME_LIMIT = 0x3B
TIME_LATENCY = 0x3C
TIME_WINDOW = 0x3D
'''
Values to select range of the accelerometer
'''
RANGE_2G = 0b00
RANGE_4G = 0b01
RANGE_8G = 0b10
RANGE_16G = 0b11
'''
Values to select data refresh rate of the accelerometer
'''
RATE_400HZ = 0b0111
RATE_200HZ = 0b0110
RATE_100HZ = 0b0101
RATE_50HZ = 0b0100
RATE_25HZ = 0b0011
RATE_10HZ = 0b0010
RATE_1HZ = 0b0001
RATE_POWERDOWN = 0
RATE_LOWPOWER_1K6HZ = 0b1000
RATE_LOWPOWER_5KHZ = 0b1001
'''
The WHO_AM_I reply
'''
WHO_AM_I_ID = 0x33
| """
This file holds all the constants that are required for programming the LIS3DH
including register addresses and their values
"""
'\nThe LIS3DH I2C address\n'
lis3_dh_i2_c_addr = 24
'\nThe LIS3DH Register Map\n'
status_reg_aux = 7
out_adc1_l = 8
out_adc1_h = 9
out_adc2_l = 10
out_adc2_h = 11
out_adc3_l = 12
out_adc3_h = 13
int_counter_reg = 14
who_am_i = 15
temp_cfg_reg = 31
ctrl_reg1 = 32
ctrl_reg2 = 33
ctrl_reg3 = 34
ctrl_reg4 = 35
ctrl_reg5 = 36
ctrl_reg6 = 37
reference = 38
status_reg2 = 39
out_x_l = 40
out_x_h = 41
out_y_l = 42
out_y_h = 43
out_z_l = 44
out_z_h = 45
fifo_ctrl_reg = 46
fifo_src_reg = 47
int1_cfg = 48
int1_source = 49
int1_ths = 50
int1_duration = 51
click_cfg = 56
click_src = 57
click_ths = 58
time_limit = 59
time_latency = 60
time_window = 61
'\nValues to select range of the accelerometer\n'
range_2_g = 0
range_4_g = 1
range_8_g = 2
range_16_g = 3
'\nValues to select data refresh rate of the accelerometer\n'
rate_400_hz = 7
rate_200_hz = 6
rate_100_hz = 5
rate_50_hz = 4
rate_25_hz = 3
rate_10_hz = 2
rate_1_hz = 1
rate_powerdown = 0
rate_lowpower_1_k6_hz = 8
rate_lowpower_5_khz = 9
'\nThe WHO_AM_I reply\n'
who_am_i_id = 51 |
def moveDictionary():
electro_shock = {"Name" : "Electro Shock", \
"Kind" : "atk",\
"Pwr" : 25, \
"Acc" : 95, \
"Crit" : 80, \
"Txt" : "releases one thousand volts of static"}
#special
heal = {"Name" : "Heal", \
"Kind" : "heal",\
"Pwr" : 28, \
"Acc" : 36, \
"Crit" : 5, \
"Txt" : "attempts to put itself back together"}
robot_punch = {"Name" : "Robot Punch", \
"Kind" : "atk",\
"Pwr" : 40, \
"Acc" : 70, \
"Crit" : 20, \
"Txt" : "reels back and slugs hard"}
robot_slap = {"Name" : "Robot Slap", \
"Kind" : "atk",\
"Pwr" : 32, \
"Acc" : 90, \
"Crit" : 20, \
"Txt" : "slaps a hoe"}
robot_headbutt = {"Name" : "Robot Headbutt", \
"Kind" : "atk",\
"Pwr" : 45, \
"Acc" : 20, \
"Crit" : 80, \
"Txt" : "attempts a powerful attack"}
#special
moveDic = {"electro_shock" : electro_shock,\
"heal" : heal, \
"robot_punch" : robot_punch,\
"robot_slap" : robot_slap,\
"robot_headbutt" : robot_headbutt}
return moveDic
##dictionary = moveDictionary() #module testing
##print(type(dictionary)) #module print test
| def move_dictionary():
electro_shock = {'Name': 'Electro Shock', 'Kind': 'atk', 'Pwr': 25, 'Acc': 95, 'Crit': 80, 'Txt': 'releases one thousand volts of static'}
heal = {'Name': 'Heal', 'Kind': 'heal', 'Pwr': 28, 'Acc': 36, 'Crit': 5, 'Txt': 'attempts to put itself back together'}
robot_punch = {'Name': 'Robot Punch', 'Kind': 'atk', 'Pwr': 40, 'Acc': 70, 'Crit': 20, 'Txt': 'reels back and slugs hard'}
robot_slap = {'Name': 'Robot Slap', 'Kind': 'atk', 'Pwr': 32, 'Acc': 90, 'Crit': 20, 'Txt': 'slaps a hoe'}
robot_headbutt = {'Name': 'Robot Headbutt', 'Kind': 'atk', 'Pwr': 45, 'Acc': 20, 'Crit': 80, 'Txt': 'attempts a powerful attack'}
move_dic = {'electro_shock': electro_shock, 'heal': heal, 'robot_punch': robot_punch, 'robot_slap': robot_slap, 'robot_headbutt': robot_headbutt}
return moveDic |
"""
limis management - messages
Messages used for logging and exception handling.
"""
COMMAND_CREATE_PROJECT_RUN_COMPLETED = 'Completed creating limis project: "{}".'
COMMAND_CREATE_PROJECT_RUN_ERROR = 'Error creating project in directory: "{}".\nError Message: {}'
COMMAND_CREATE_PROJECT_RUN_STARTED = 'Creating limis project: "{}".'
COMMAND_CREATE_SERVICE_RUN_COMPLETED = 'Completed creating limis service: "{}".'
COMMAND_CREATE_SERVICE_RUN_ERROR = 'Error creating service in directory: "{}".\nError Message: {}'
COMMAND_CREATE_SERVICE_RUN_STARTED = 'Creating limis service: "{}".'
COMMAND_LINE_INTERFACE_COMMAND_REQUIRED = 'Error: Command required, none specified.\n\nValid commands:'
COMMAND_LINE_INTERFACE_HELP_COMMAND = '{} - {}'
COMMAND_LINE_INTERFACE_RUN_INVALID_ARGUMENTS = 'Error: Invalid arguments.\n\nValid arguments:'
COMMAND_LINE_INTERFACE_RUN_UNKNOWN_COMMAND = 'Error: "{}" is not a valid command.'
COMMAND_SERVER_INVALID_PORT = 'Error: "{}" is not a valid port.'
COMMAND_SERVER_INVALID_ROOT_SERVICES = 'Error: Root services not properly defined.'
COMMAND_INVALID_ARGUMENT = 'Error: invalid argument.'
COMMAND_UNKNOWN_ARGUMENT = 'Error: "{}" is not a valid argument.'
COMMAND_VERSION = 'limis - {}'
| """
limis management - messages
Messages used for logging and exception handling.
"""
command_create_project_run_completed = 'Completed creating limis project: "{}".'
command_create_project_run_error = 'Error creating project in directory: "{}".\nError Message: {}'
command_create_project_run_started = 'Creating limis project: "{}".'
command_create_service_run_completed = 'Completed creating limis service: "{}".'
command_create_service_run_error = 'Error creating service in directory: "{}".\nError Message: {}'
command_create_service_run_started = 'Creating limis service: "{}".'
command_line_interface_command_required = 'Error: Command required, none specified.\n\nValid commands:'
command_line_interface_help_command = '{} - {}'
command_line_interface_run_invalid_arguments = 'Error: Invalid arguments.\n\nValid arguments:'
command_line_interface_run_unknown_command = 'Error: "{}" is not a valid command.'
command_server_invalid_port = 'Error: "{}" is not a valid port.'
command_server_invalid_root_services = 'Error: Root services not properly defined.'
command_invalid_argument = 'Error: invalid argument.'
command_unknown_argument = 'Error: "{}" is not a valid argument.'
command_version = 'limis - {}' |
class Solution:
def rob(self, nums):
robbed, notRobbed = 0, 0
for i in nums:
robbed, notRobbed = notRobbed + i, max(robbed, notRobbed)
return max(robbed, notRobbed)
| class Solution:
def rob(self, nums):
(robbed, not_robbed) = (0, 0)
for i in nums:
(robbed, not_robbed) = (notRobbed + i, max(robbed, notRobbed))
return max(robbed, notRobbed) |
# Common package prefixes, in the order we want to check for them
_PREFIXES = (".com.", ".org.", ".net.", ".io.")
# By default bazel computes the name of test classes based on the
# standard Maven directory structure, which we may not always use,
# so try to compute the correct package name.
def get_package_name():
pkg = native.package_name().replace("/", ".")
for prefix in _PREFIXES:
idx = pkg.find(prefix)
if idx != -1:
return pkg[idx + 1:] + "."
return ""
# Converts a file name into what is hopefully a valid class name.
def get_class_name(src):
# Strip the suffix from the source
idx = src.rindex(".")
name = src[:idx].replace("/", ".")
for prefix in _PREFIXES:
idx = name.find(prefix)
if idx != -1:
return name[idx + 1:]
pkg = get_package_name()
if pkg:
return pkg + name
return name
| _prefixes = ('.com.', '.org.', '.net.', '.io.')
def get_package_name():
pkg = native.package_name().replace('/', '.')
for prefix in _PREFIXES:
idx = pkg.find(prefix)
if idx != -1:
return pkg[idx + 1:] + '.'
return ''
def get_class_name(src):
idx = src.rindex('.')
name = src[:idx].replace('/', '.')
for prefix in _PREFIXES:
idx = name.find(prefix)
if idx != -1:
return name[idx + 1:]
pkg = get_package_name()
if pkg:
return pkg + name
return name |
numbers = [int(i) for i in input().split(" ")]
opposite_numbers = []
for current_num in numbers:
if current_num >= 0:
opposite_numbers.append(-current_num)
elif current_num < 0:
opposite_numbers.append(abs(current_num))
print(opposite_numbers) | numbers = [int(i) for i in input().split(' ')]
opposite_numbers = []
for current_num in numbers:
if current_num >= 0:
opposite_numbers.append(-current_num)
elif current_num < 0:
opposite_numbers.append(abs(current_num))
print(opposite_numbers) |
def finder(data, x):
if x == 0:
return data[x]
v1 = data[x]
v2 = finder(data, x-1)
if v1 > v2:
return v1
else:
return v2
print(finder([0, -247, 341, 1001, 741, 22])) | def finder(data, x):
if x == 0:
return data[x]
v1 = data[x]
v2 = finder(data, x - 1)
if v1 > v2:
return v1
else:
return v2
print(finder([0, -247, 341, 1001, 741, 22])) |
def extractStrictlybromanceCom(item):
'''
Parser for 'strictlybromance.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('grave robbers\' chronicles', 'grave robbers\' chronicles', 'translated'),
('haunted houses\' chronicles', 'haunted houses\' chronicles', 'translated'),
('the trial game of life', 'the trial game of life', 'translated'),
('the invasion day', 'The Invasion Day', 'translated'),
('saving unpermitted', 'saving unpermitted', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | def extract_strictlybromance_com(item):
"""
Parser for 'strictlybromance.com'
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [("grave robbers' chronicles", "grave robbers' chronicles", 'translated'), ("haunted houses' chronicles", "haunted houses' chronicles", 'translated'), ('the trial game of life', 'the trial game of life', 'translated'), ('the invasion day', 'The Invasion Day', 'translated'), ('saving unpermitted', 'saving unpermitted', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if tagname in item['tags']:
return build_release_message_with_type(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
class Solution:
def largestTimeFromDigits(self, nums: List[int]) -> str:
res=[]
def per(depth):
if depth==len(nums)-1:
res.append(nums[:])
for i in range(depth,len(nums)):
nums[i],nums[depth]=nums[depth],nums[i]
per(depth+1)
nums[i],nums[depth]=nums[depth],nums[i]
per(0)
re=""
for i in res:
if i[0]*10 +i[1]<24 and i[2]*10+i[3]<60:
re=max(re,str(i[0])+str(i[1])+':'+str(i[2])+str(i[3]))
return re
| class Solution:
def largest_time_from_digits(self, nums: List[int]) -> str:
res = []
def per(depth):
if depth == len(nums) - 1:
res.append(nums[:])
for i in range(depth, len(nums)):
(nums[i], nums[depth]) = (nums[depth], nums[i])
per(depth + 1)
(nums[i], nums[depth]) = (nums[depth], nums[i])
per(0)
re = ''
for i in res:
if i[0] * 10 + i[1] < 24 and i[2] * 10 + i[3] < 60:
re = max(re, str(i[0]) + str(i[1]) + ':' + str(i[2]) + str(i[3]))
return re |
def fbx_references_elements(root, scene_data):
"""
Have no idea what references are in FBX currently... Just writing empty element.
"""
docs = elem_empty(root, b"References")
| def fbx_references_elements(root, scene_data):
"""
Have no idea what references are in FBX currently... Just writing empty element.
"""
docs = elem_empty(root, b'References') |
EPS = 1.0e-16
PI = 3.141592653589793
| eps = 1e-16
pi = 3.141592653589793 |
#all binary
allSensors = ['D021', 'D022', 'D023', 'D024',
'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032', 'M001',
'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010',
'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019',
'M020']
doorSensors = ['D021', 'D022', 'D023', 'D024',
'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032']
motionSensors = ['M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010',
'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019',
'M020']
doorFalse = "CLOSE"
doorTrue = "OPEN"
motionFalse = "OFF"
motionTrue = "ON"
allActivities = ['Bathing', 'Bed_Toilet_Transition', 'Eating', 'Enter_Home', 'Housekeeping', 'Leave_Home',
'Meal_Preparation', 'Other_Activity', 'Personal_Hygiene', 'Relax', 'Sleeping_Not_in_Bed',
'Sleeping_in_Bed', 'Take_Medicine', 'Work']
sensColToOrd = { val : i for i, val in enumerate(allSensors)}
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
timeMidn = "TimeFromMid"
class rawLabels:
time = "Time"
sensor = "Sensor"
signal = "Signal"
activity = "Activity"
correctOrder = [time, sensor, signal, activity]
rl = rawLabels
features = [rl.time, rl.signal] + allSensors + allActivities
conditionals = [timeMidn] + week
conditionalSize = len(conditionals)
colOrdConditional = {day : i+1 for i, day in enumerate(week)}
colOrdConditional[timeMidn] = 0
allBinaryColumns = [rl.signal] + allSensors + allActivities + week
correctOrder = features + conditionals
class start_stop:
def __init__(self, start, length):
self.start = start
self.stop = start + length
class pivots:
time = start_stop(0,1)
signal = start_stop(time.stop, 1)
sensors = start_stop(signal.stop, len(allSensors))
activities = start_stop(sensors.stop, len(allActivities))
features = start_stop(0, activities.stop)
timeLabels = start_stop(activities.stop, len(conditionals))
weekdays = start_stop(timeLabels.start, 1)
colOrder = [rl.time, rl.signal] + allSensors + allActivities + conditionals
ordinalColDict = {i:c for i, c in enumerate(colOrder)}
colOrdinalDict = {c:i for i, c in enumerate(colOrder)}
class home_names:
allHomes = "All Real Home"
synthetic = "Fake Home"
home1 = "H1"
home2 = "H2"
home3 = "H3" | all_sensors = ['D021', 'D022', 'D023', 'D024', 'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032', 'M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010', 'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019', 'M020']
door_sensors = ['D021', 'D022', 'D023', 'D024', 'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032']
motion_sensors = ['M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010', 'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019', 'M020']
door_false = 'CLOSE'
door_true = 'OPEN'
motion_false = 'OFF'
motion_true = 'ON'
all_activities = ['Bathing', 'Bed_Toilet_Transition', 'Eating', 'Enter_Home', 'Housekeeping', 'Leave_Home', 'Meal_Preparation', 'Other_Activity', 'Personal_Hygiene', 'Relax', 'Sleeping_Not_in_Bed', 'Sleeping_in_Bed', 'Take_Medicine', 'Work']
sens_col_to_ord = {val: i for (i, val) in enumerate(allSensors)}
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
time_midn = 'TimeFromMid'
class Rawlabels:
time = 'Time'
sensor = 'Sensor'
signal = 'Signal'
activity = 'Activity'
correct_order = [time, sensor, signal, activity]
rl = rawLabels
features = [rl.time, rl.signal] + allSensors + allActivities
conditionals = [timeMidn] + week
conditional_size = len(conditionals)
col_ord_conditional = {day: i + 1 for (i, day) in enumerate(week)}
colOrdConditional[timeMidn] = 0
all_binary_columns = [rl.signal] + allSensors + allActivities + week
correct_order = features + conditionals
class Start_Stop:
def __init__(self, start, length):
self.start = start
self.stop = start + length
class Pivots:
time = start_stop(0, 1)
signal = start_stop(time.stop, 1)
sensors = start_stop(signal.stop, len(allSensors))
activities = start_stop(sensors.stop, len(allActivities))
features = start_stop(0, activities.stop)
time_labels = start_stop(activities.stop, len(conditionals))
weekdays = start_stop(timeLabels.start, 1)
col_order = [rl.time, rl.signal] + allSensors + allActivities + conditionals
ordinal_col_dict = {i: c for (i, c) in enumerate(colOrder)}
col_ordinal_dict = {c: i for (i, c) in enumerate(colOrder)}
class Home_Names:
all_homes = 'All Real Home'
synthetic = 'Fake Home'
home1 = 'H1'
home2 = 'H2'
home3 = 'H3' |
f = [1, 1, 2, 6, 4]
for _ in range(int(input())):
n = int(input())
if n <= 4:
print(f[n])
else:
print(0)
| f = [1, 1, 2, 6, 4]
for _ in range(int(input())):
n = int(input())
if n <= 4:
print(f[n])
else:
print(0) |
# 6. Zigzag Conversion
# Runtime: 103 ms, faster than 20.89% of Python3 online submissions for Zigzag Conversion.
# Memory Usage: 14.7 MB, less than 13.84% of Python3 online submissions for Zigzag Conversion.
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [[] for _ in range(numRows)]
# In the first and last rows, the interval between two adjacent elements is the larget.
largest_interval = (numRows * 2) - 2
for r in range(numRows):
i = r
# In other rows, The sum of the intervals of every three elements is equal to the larget interval.
curr_interval = largest_interval - 2 * r
if curr_interval == 0:
curr_interval = largest_interval
while i < len(s):
rows[r].append(s[i])
i += curr_interval
if curr_interval != largest_interval:
curr_interval = largest_interval - curr_interval
ans = []
for row in rows:
ans.extend(row)
return "".join(ans) | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [[] for _ in range(numRows)]
largest_interval = numRows * 2 - 2
for r in range(numRows):
i = r
curr_interval = largest_interval - 2 * r
if curr_interval == 0:
curr_interval = largest_interval
while i < len(s):
rows[r].append(s[i])
i += curr_interval
if curr_interval != largest_interval:
curr_interval = largest_interval - curr_interval
ans = []
for row in rows:
ans.extend(row)
return ''.join(ans) |
#
# PySNMP MIB module AGENTX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGENTX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:15:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
Counter64, mib_2, NotificationType, Bits, iso, Unsigned32, MibIdentifier, TimeTicks, ObjectIdentity, Integer32, ModuleIdentity, Gauge32, IpAddress, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "mib-2", "NotificationType", "Bits", "iso", "Unsigned32", "MibIdentifier", "TimeTicks", "ObjectIdentity", "Integer32", "ModuleIdentity", "Gauge32", "IpAddress", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TimeStamp, DisplayString, TextualConvention, TDomain, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "DisplayString", "TextualConvention", "TDomain", "TruthValue")
agentxMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 74))
agentxMIB.setRevisions(('2000-01-10 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: agentxMIB.setRevisionsDescriptions(('Initial version published as RFC 2742.',))
if mibBuilder.loadTexts: agentxMIB.setLastUpdated('200001100000Z')
if mibBuilder.loadTexts: agentxMIB.setOrganization('AgentX Working Group')
if mibBuilder.loadTexts: agentxMIB.setContactInfo('WG-email: agentx@dorothy.bmc.com Subscribe: agentx-request@dorothy.bmc.com WG-email Archive: ftp://ftp.peer.com/pub/agentx/archives FTP repository: ftp://ftp.peer.com/pub/agentx http://www.ietf.org/html.charters/agentx-charter.html Chair: Bob Natale ACE*COMM Corporation Email: bnatale@acecomm.com WG editor: Mark Ellison Ellison Software Consulting, Inc. Email: ellison@world.std.com Co-author: Lauren Heintz Cisco Systems, EMail: lheintz@cisco.com Co-author: Smitha Gudur Independent Consultant Email: sgudur@hotmail.com ')
if mibBuilder.loadTexts: agentxMIB.setDescription('This is the MIB module for the SNMP Agent Extensibility Protocol (AgentX). This MIB module will be implemented by the master agent. ')
class AgentxTAddress(TextualConvention, OctetString):
description = 'Denotes a transport service address. This is identical to the TAddress textual convention (SNMPv2-SMI) except that zero-length values are permitted. '
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255)
agentxObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1))
agentxGeneral = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 1))
agentxConnection = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 2))
agentxSession = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 3))
agentxRegistration = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 4))
agentxDefaultTimeout = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(5)).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxDefaultTimeout.setStatus('current')
if mibBuilder.loadTexts: agentxDefaultTimeout.setDescription('The default length of time, in seconds, that the master agent should allow to elapse after dispatching a message to a session before it regards the subagent as not responding. This is a system-wide value that may override the timeout value associated with a particular session (agentxSessionTimeout) or a particular registered MIB region (agentxRegTimeout). If the associated value of agentxSessionTimeout and agentxRegTimeout are zero, or impractical in accordance with implementation-specific procedure of the master agent, the value represented by this object will be the effective timeout value for the master agent to await a response to a dispatch from a given subagent. ')
agentxMasterAgentXVer = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxMasterAgentXVer.setStatus('current')
if mibBuilder.loadTexts: agentxMasterAgentXVer.setDescription('The AgentX protocol version supported by this master agent. The current protocol version is 1. Note that the master agent must also allow interaction with earlier version subagents. ')
agentxConnTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 2, 1), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxConnTableLastChange.setStatus('current')
if mibBuilder.loadTexts: agentxConnTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxConnectionTable. ')
agentxConnectionTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 2, 2), )
if mibBuilder.loadTexts: agentxConnectionTable.setStatus('current')
if mibBuilder.loadTexts: agentxConnectionTable.setDescription('The agentxConnectionTable tracks all current AgentX transport connections. There may be zero, one, or more AgentX sessions carried on a given AgentX connection. ')
agentxConnectionEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex"))
if mibBuilder.loadTexts: agentxConnectionEntry.setStatus('current')
if mibBuilder.loadTexts: agentxConnectionEntry.setDescription('An agentxConnectionEntry contains information describing a single AgentX transport connection. A connection may be used to support zero or more AgentX sessions. An entry is created when a new transport connection is established, and is destroyed when the transport connection is terminated. ')
agentxConnIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: agentxConnIndex.setStatus('current')
if mibBuilder.loadTexts: agentxConnIndex.setDescription('agentxConnIndex contains the value that uniquely identifies an open transport connection used by this master agent to provide AgentX service. Values of this index should not be re-used. The value assigned to a given transport connection is constant for the lifetime of that connection. ')
agentxConnOpenTime = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 2), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxConnOpenTime.setStatus('current')
if mibBuilder.loadTexts: agentxConnOpenTime.setDescription('The value of sysUpTime when this connection was established and, therefore, its value when this entry was added to the table. ')
agentxConnTransportDomain = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 3), TDomain()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxConnTransportDomain.setStatus('current')
if mibBuilder.loadTexts: agentxConnTransportDomain.setDescription('The transport protocol in use for this connection to the subagent. ')
agentxConnTransportAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 4), AgentxTAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxConnTransportAddress.setStatus('current')
if mibBuilder.loadTexts: agentxConnTransportAddress.setDescription('The transport address of the remote (subagent) end of this connection to the master agent. This object may be zero-length for unix-domain sockets (and possibly other types of transport addresses) since the subagent need not bind a filename to its local socket. ')
agentxSessionTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 3, 1), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionTableLastChange.setStatus('current')
if mibBuilder.loadTexts: agentxSessionTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxSessionTable. ')
agentxSessionTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 3, 2), )
if mibBuilder.loadTexts: agentxSessionTable.setStatus('current')
if mibBuilder.loadTexts: agentxSessionTable.setDescription('A table of AgentX subagent sessions currently in effect. ')
agentxSessionEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex"), (0, "AGENTX-MIB", "agentxSessionIndex"))
if mibBuilder.loadTexts: agentxSessionEntry.setStatus('current')
if mibBuilder.loadTexts: agentxSessionEntry.setDescription('Information about a single open session between the AgentX master agent and a subagent is contained in this entry. An entry is created when a new session is successfully established and is destroyed either when the subagent transport connection has terminated or when the subagent session is closed. ')
agentxSessionIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295)))
if mibBuilder.loadTexts: agentxSessionIndex.setStatus('current')
if mibBuilder.loadTexts: agentxSessionIndex.setDescription("A unique index for the subagent session. It is the same as h.sessionID defined in the agentx header. Note that if a subagent's session with the master agent is closed for any reason its index should not be re-used. A value of zero(0) is specifically allowed in order to be compatible with the definition of h.sessionId. ")
agentxSessionObjectID = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionObjectID.setStatus('current')
if mibBuilder.loadTexts: agentxSessionObjectID.setDescription("This is taken from the o.id field of the agentx-Open-PDU. This attribute will report a value of '0.0' for subagents not supporting the notion of an AgentX session object identifier. ")
agentxSessionDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionDescr.setStatus('current')
if mibBuilder.loadTexts: agentxSessionDescr.setDescription('A textual description of the session. This is analogous to sysDescr defined in the SNMPv2-MIB in RFC 1907 [19] and is taken from the o.descr field of the agentx-Open-PDU. This attribute will report a zero-length string value for subagents not supporting the notion of a session description. ')
agentxSessionAdminStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentxSessionAdminStatus.setStatus('current')
if mibBuilder.loadTexts: agentxSessionAdminStatus.setDescription("The administrative (desired) status of the session. Setting the value to 'down(2)' closes the subagent session (with c.reason set to 'reasonByManager'). ")
agentxSessionOpenTime = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 5), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionOpenTime.setStatus('current')
if mibBuilder.loadTexts: agentxSessionOpenTime.setDescription('The value of sysUpTime when this session was opened and, therefore, its value when this entry was added to the table. ')
agentxSessionAgentXVer = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionAgentXVer.setStatus('current')
if mibBuilder.loadTexts: agentxSessionAgentXVer.setDescription('The version of the AgentX protocol supported by the session. This must be less than or equal to the value of agentxMasterAgentXVer. ')
agentxSessionTimeout = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionTimeout.setStatus('current')
if mibBuilder.loadTexts: agentxSessionTimeout.setDescription("The length of time, in seconds, that a master agent should allow to elapse after dispatching a message to this session before it regards the subagent as not responding. This value is taken from the o.timeout field of the agentx-Open-PDU. This is a session-specific value that may be overridden by values associated with the specific registered MIB regions (see agentxRegTimeout). A value of zero(0) indicates that the master agent's default timeout value should be used (see agentxDefaultTimeout). ")
agentxRegistrationTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 4, 1), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegistrationTableLastChange.setStatus('current')
if mibBuilder.loadTexts: agentxRegistrationTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxRegistrationTable. ')
agentxRegistrationTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 4, 2), )
if mibBuilder.loadTexts: agentxRegistrationTable.setStatus('current')
if mibBuilder.loadTexts: agentxRegistrationTable.setDescription('A table of registered regions. ')
agentxRegistrationEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex"), (0, "AGENTX-MIB", "agentxSessionIndex"), (0, "AGENTX-MIB", "agentxRegIndex"))
if mibBuilder.loadTexts: agentxRegistrationEntry.setStatus('current')
if mibBuilder.loadTexts: agentxRegistrationEntry.setDescription('Contains information for a single registered region. An entry is created when a session successfully registers a region and is destroyed for any of three reasons: this region is unregistered by the session, the session is closed, or the subagent connection is closed. ')
agentxRegIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: agentxRegIndex.setStatus('current')
if mibBuilder.loadTexts: agentxRegIndex.setDescription('agentxRegIndex uniquely identifies a registration entry. This value is constant for the lifetime of an entry. ')
agentxRegContext = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 2), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegContext.setStatus('current')
if mibBuilder.loadTexts: agentxRegContext.setDescription('The context in which the session supports the objects in this region. A zero-length context indicates the default context. ')
agentxRegStart = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 3), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegStart.setStatus('current')
if mibBuilder.loadTexts: agentxRegStart.setDescription('The starting OBJECT IDENTIFIER of this registration entry. The session identified by agentxSessionIndex implements objects starting at this value (inclusive). Note that this value could identify an object type, an object instance, or a partial object instance. ')
agentxRegRangeSubId = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegRangeSubId.setStatus('current')
if mibBuilder.loadTexts: agentxRegRangeSubId.setDescription("agentxRegRangeSubId is used to specify the range. This is taken from r.region_subid in the registration PDU. If the value of this object is zero, no range is specified. If it is non-zero, it identifies the `nth' sub-identifier in r.region for which this entry's agentxRegUpperBound value is substituted in the OID for purposes of defining the region's upper bound. ")
agentxRegUpperBound = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegUpperBound.setStatus('current')
if mibBuilder.loadTexts: agentxRegUpperBound.setDescription('agentxRegUpperBound represents the upper-bound sub-identifier in a registration. This is taken from the r.upper_bound in the registration PDU. If agentxRegRangeSubid (r.region_subid) is zero, this value is also zero and is not used to define an upper bound for this registration. ')
agentxRegPriority = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegPriority.setStatus('current')
if mibBuilder.loadTexts: agentxRegPriority.setDescription('The registration priority. Lower values have higher priority. This value is taken from r.priority in the register PDU. Sessions should use the value of 127 for r.priority if a default value is desired. ')
agentxRegTimeout = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegTimeout.setStatus('current')
if mibBuilder.loadTexts: agentxRegTimeout.setDescription('The timeout value, in seconds, for responses to requests associated with this registered MIB region. A value of zero(0) indicates the default value (indicated by by agentxSessionTimeout or agentxDefaultTimeout) is to be used. This value is taken from the r.timeout field of the agentx-Register-PDU. ')
agentxRegInstance = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 8), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegInstance.setStatus('current')
if mibBuilder.loadTexts: agentxRegInstance.setDescription("The value of agentxRegInstance is `true' for registrations for which the INSTANCE_REGISTRATION was set, and is `false' for all other registrations. ")
agentxConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2))
agentxMIBGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2, 1))
agentxMIBCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2, 2))
agentxMIBCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 74, 2, 2, 1)).setObjects(("AGENTX-MIB", "agentxMIBGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
agentxMIBCompliance = agentxMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: agentxMIBCompliance.setDescription('The compliance statement for SNMP entities that implement the AgentX protocol. Note that a compliant agent can implement all objects in this MIB module as read-only. ')
agentxMIBGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 74, 2, 1, 1)).setObjects(("AGENTX-MIB", "agentxDefaultTimeout"), ("AGENTX-MIB", "agentxMasterAgentXVer"), ("AGENTX-MIB", "agentxConnTableLastChange"), ("AGENTX-MIB", "agentxConnOpenTime"), ("AGENTX-MIB", "agentxConnTransportDomain"), ("AGENTX-MIB", "agentxConnTransportAddress"), ("AGENTX-MIB", "agentxSessionTableLastChange"), ("AGENTX-MIB", "agentxSessionTimeout"), ("AGENTX-MIB", "agentxSessionObjectID"), ("AGENTX-MIB", "agentxSessionDescr"), ("AGENTX-MIB", "agentxSessionAdminStatus"), ("AGENTX-MIB", "agentxSessionOpenTime"), ("AGENTX-MIB", "agentxSessionAgentXVer"), ("AGENTX-MIB", "agentxRegistrationTableLastChange"), ("AGENTX-MIB", "agentxRegContext"), ("AGENTX-MIB", "agentxRegStart"), ("AGENTX-MIB", "agentxRegRangeSubId"), ("AGENTX-MIB", "agentxRegUpperBound"), ("AGENTX-MIB", "agentxRegPriority"), ("AGENTX-MIB", "agentxRegTimeout"), ("AGENTX-MIB", "agentxRegInstance"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
agentxMIBGroup = agentxMIBGroup.setStatus('current')
if mibBuilder.loadTexts: agentxMIBGroup.setDescription('All accessible objects in the AgentX MIB. ')
mibBuilder.exportSymbols("AGENTX-MIB", agentxConnTransportAddress=agentxConnTransportAddress, agentxRegistrationTable=agentxRegistrationTable, agentxMIBGroups=agentxMIBGroups, agentxSession=agentxSession, agentxDefaultTimeout=agentxDefaultTimeout, agentxConformance=agentxConformance, agentxGeneral=agentxGeneral, PYSNMP_MODULE_ID=agentxMIB, agentxConnTransportDomain=agentxConnTransportDomain, agentxSessionTableLastChange=agentxSessionTableLastChange, AgentxTAddress=AgentxTAddress, agentxRegInstance=agentxRegInstance, agentxMIBCompliances=agentxMIBCompliances, agentxRegistration=agentxRegistration, agentxConnIndex=agentxConnIndex, agentxConnOpenTime=agentxConnOpenTime, agentxRegIndex=agentxRegIndex, agentxMIB=agentxMIB, agentxSessionIndex=agentxSessionIndex, agentxRegistrationTableLastChange=agentxRegistrationTableLastChange, agentxSessionEntry=agentxSessionEntry, agentxRegRangeSubId=agentxRegRangeSubId, agentxConnTableLastChange=agentxConnTableLastChange, agentxSessionAgentXVer=agentxSessionAgentXVer, agentxSessionOpenTime=agentxSessionOpenTime, agentxRegTimeout=agentxRegTimeout, agentxMIBGroup=agentxMIBGroup, agentxSessionTable=agentxSessionTable, agentxSessionObjectID=agentxSessionObjectID, agentxRegStart=agentxRegStart, agentxSessionTimeout=agentxSessionTimeout, agentxConnectionTable=agentxConnectionTable, agentxConnectionEntry=agentxConnectionEntry, agentxRegPriority=agentxRegPriority, agentxMIBCompliance=agentxMIBCompliance, agentxRegistrationEntry=agentxRegistrationEntry, agentxRegUpperBound=agentxRegUpperBound, agentxConnection=agentxConnection, agentxObjects=agentxObjects, agentxSessionAdminStatus=agentxSessionAdminStatus, agentxMasterAgentXVer=agentxMasterAgentXVer, agentxRegContext=agentxRegContext, agentxSessionDescr=agentxSessionDescr)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup')
(counter64, mib_2, notification_type, bits, iso, unsigned32, mib_identifier, time_ticks, object_identity, integer32, module_identity, gauge32, ip_address, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'mib-2', 'NotificationType', 'Bits', 'iso', 'Unsigned32', 'MibIdentifier', 'TimeTicks', 'ObjectIdentity', 'Integer32', 'ModuleIdentity', 'Gauge32', 'IpAddress', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn')
(time_stamp, display_string, textual_convention, t_domain, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'TimeStamp', 'DisplayString', 'TextualConvention', 'TDomain', 'TruthValue')
agentx_mib = module_identity((1, 3, 6, 1, 2, 1, 74))
agentxMIB.setRevisions(('2000-01-10 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
agentxMIB.setRevisionsDescriptions(('Initial version published as RFC 2742.',))
if mibBuilder.loadTexts:
agentxMIB.setLastUpdated('200001100000Z')
if mibBuilder.loadTexts:
agentxMIB.setOrganization('AgentX Working Group')
if mibBuilder.loadTexts:
agentxMIB.setContactInfo('WG-email: agentx@dorothy.bmc.com Subscribe: agentx-request@dorothy.bmc.com WG-email Archive: ftp://ftp.peer.com/pub/agentx/archives FTP repository: ftp://ftp.peer.com/pub/agentx http://www.ietf.org/html.charters/agentx-charter.html Chair: Bob Natale ACE*COMM Corporation Email: bnatale@acecomm.com WG editor: Mark Ellison Ellison Software Consulting, Inc. Email: ellison@world.std.com Co-author: Lauren Heintz Cisco Systems, EMail: lheintz@cisco.com Co-author: Smitha Gudur Independent Consultant Email: sgudur@hotmail.com ')
if mibBuilder.loadTexts:
agentxMIB.setDescription('This is the MIB module for the SNMP Agent Extensibility Protocol (AgentX). This MIB module will be implemented by the master agent. ')
class Agentxtaddress(TextualConvention, OctetString):
description = 'Denotes a transport service address. This is identical to the TAddress textual convention (SNMPv2-SMI) except that zero-length values are permitted. '
status = 'current'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 255)
agentx_objects = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1))
agentx_general = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1, 1))
agentx_connection = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1, 2))
agentx_session = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1, 3))
agentx_registration = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1, 4))
agentx_default_timeout = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 255)).clone(5)).setUnits('seconds').setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxDefaultTimeout.setStatus('current')
if mibBuilder.loadTexts:
agentxDefaultTimeout.setDescription('The default length of time, in seconds, that the master agent should allow to elapse after dispatching a message to a session before it regards the subagent as not responding. This is a system-wide value that may override the timeout value associated with a particular session (agentxSessionTimeout) or a particular registered MIB region (agentxRegTimeout). If the associated value of agentxSessionTimeout and agentxRegTimeout are zero, or impractical in accordance with implementation-specific procedure of the master agent, the value represented by this object will be the effective timeout value for the master agent to await a response to a dispatch from a given subagent. ')
agentx_master_agent_x_ver = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxMasterAgentXVer.setStatus('current')
if mibBuilder.loadTexts:
agentxMasterAgentXVer.setDescription('The AgentX protocol version supported by this master agent. The current protocol version is 1. Note that the master agent must also allow interaction with earlier version subagents. ')
agentx_conn_table_last_change = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 2, 1), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxConnTableLastChange.setStatus('current')
if mibBuilder.loadTexts:
agentxConnTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxConnectionTable. ')
agentx_connection_table = mib_table((1, 3, 6, 1, 2, 1, 74, 1, 2, 2))
if mibBuilder.loadTexts:
agentxConnectionTable.setStatus('current')
if mibBuilder.loadTexts:
agentxConnectionTable.setDescription('The agentxConnectionTable tracks all current AgentX transport connections. There may be zero, one, or more AgentX sessions carried on a given AgentX connection. ')
agentx_connection_entry = mib_table_row((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1)).setIndexNames((0, 'AGENTX-MIB', 'agentxConnIndex'))
if mibBuilder.loadTexts:
agentxConnectionEntry.setStatus('current')
if mibBuilder.loadTexts:
agentxConnectionEntry.setDescription('An agentxConnectionEntry contains information describing a single AgentX transport connection. A connection may be used to support zero or more AgentX sessions. An entry is created when a new transport connection is established, and is destroyed when the transport connection is terminated. ')
agentx_conn_index = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 4294967295)))
if mibBuilder.loadTexts:
agentxConnIndex.setStatus('current')
if mibBuilder.loadTexts:
agentxConnIndex.setDescription('agentxConnIndex contains the value that uniquely identifies an open transport connection used by this master agent to provide AgentX service. Values of this index should not be re-used. The value assigned to a given transport connection is constant for the lifetime of that connection. ')
agentx_conn_open_time = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 2), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxConnOpenTime.setStatus('current')
if mibBuilder.loadTexts:
agentxConnOpenTime.setDescription('The value of sysUpTime when this connection was established and, therefore, its value when this entry was added to the table. ')
agentx_conn_transport_domain = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 3), t_domain()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxConnTransportDomain.setStatus('current')
if mibBuilder.loadTexts:
agentxConnTransportDomain.setDescription('The transport protocol in use for this connection to the subagent. ')
agentx_conn_transport_address = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 4), agentx_t_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxConnTransportAddress.setStatus('current')
if mibBuilder.loadTexts:
agentxConnTransportAddress.setDescription('The transport address of the remote (subagent) end of this connection to the master agent. This object may be zero-length for unix-domain sockets (and possibly other types of transport addresses) since the subagent need not bind a filename to its local socket. ')
agentx_session_table_last_change = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 3, 1), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionTableLastChange.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxSessionTable. ')
agentx_session_table = mib_table((1, 3, 6, 1, 2, 1, 74, 1, 3, 2))
if mibBuilder.loadTexts:
agentxSessionTable.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionTable.setDescription('A table of AgentX subagent sessions currently in effect. ')
agentx_session_entry = mib_table_row((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1)).setIndexNames((0, 'AGENTX-MIB', 'agentxConnIndex'), (0, 'AGENTX-MIB', 'agentxSessionIndex'))
if mibBuilder.loadTexts:
agentxSessionEntry.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionEntry.setDescription('Information about a single open session between the AgentX master agent and a subagent is contained in this entry. An entry is created when a new session is successfully established and is destroyed either when the subagent transport connection has terminated or when the subagent session is closed. ')
agentx_session_index = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 4294967295)))
if mibBuilder.loadTexts:
agentxSessionIndex.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionIndex.setDescription("A unique index for the subagent session. It is the same as h.sessionID defined in the agentx header. Note that if a subagent's session with the master agent is closed for any reason its index should not be re-used. A value of zero(0) is specifically allowed in order to be compatible with the definition of h.sessionId. ")
agentx_session_object_id = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 2), object_identifier()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionObjectID.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionObjectID.setDescription("This is taken from the o.id field of the agentx-Open-PDU. This attribute will report a value of '0.0' for subagents not supporting the notion of an AgentX session object identifier. ")
agentx_session_descr = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 3), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionDescr.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionDescr.setDescription('A textual description of the session. This is analogous to sysDescr defined in the SNMPv2-MIB in RFC 1907 [19] and is taken from the o.descr field of the agentx-Open-PDU. This attribute will report a zero-length string value for subagents not supporting the notion of a session description. ')
agentx_session_admin_status = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('up', 1), ('down', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentxSessionAdminStatus.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionAdminStatus.setDescription("The administrative (desired) status of the session. Setting the value to 'down(2)' closes the subagent session (with c.reason set to 'reasonByManager'). ")
agentx_session_open_time = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 5), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionOpenTime.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionOpenTime.setDescription('The value of sysUpTime when this session was opened and, therefore, its value when this entry was added to the table. ')
agentx_session_agent_x_ver = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionAgentXVer.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionAgentXVer.setDescription('The version of the AgentX protocol supported by the session. This must be less than or equal to the value of agentxMasterAgentXVer. ')
agentx_session_timeout = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setUnits('seconds').setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionTimeout.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionTimeout.setDescription("The length of time, in seconds, that a master agent should allow to elapse after dispatching a message to this session before it regards the subagent as not responding. This value is taken from the o.timeout field of the agentx-Open-PDU. This is a session-specific value that may be overridden by values associated with the specific registered MIB regions (see agentxRegTimeout). A value of zero(0) indicates that the master agent's default timeout value should be used (see agentxDefaultTimeout). ")
agentx_registration_table_last_change = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 4, 1), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegistrationTableLastChange.setStatus('current')
if mibBuilder.loadTexts:
agentxRegistrationTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxRegistrationTable. ')
agentx_registration_table = mib_table((1, 3, 6, 1, 2, 1, 74, 1, 4, 2))
if mibBuilder.loadTexts:
agentxRegistrationTable.setStatus('current')
if mibBuilder.loadTexts:
agentxRegistrationTable.setDescription('A table of registered regions. ')
agentx_registration_entry = mib_table_row((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1)).setIndexNames((0, 'AGENTX-MIB', 'agentxConnIndex'), (0, 'AGENTX-MIB', 'agentxSessionIndex'), (0, 'AGENTX-MIB', 'agentxRegIndex'))
if mibBuilder.loadTexts:
agentxRegistrationEntry.setStatus('current')
if mibBuilder.loadTexts:
agentxRegistrationEntry.setDescription('Contains information for a single registered region. An entry is created when a session successfully registers a region and is destroyed for any of three reasons: this region is unregistered by the session, the session is closed, or the subagent connection is closed. ')
agentx_reg_index = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 4294967295)))
if mibBuilder.loadTexts:
agentxRegIndex.setStatus('current')
if mibBuilder.loadTexts:
agentxRegIndex.setDescription('agentxRegIndex uniquely identifies a registration entry. This value is constant for the lifetime of an entry. ')
agentx_reg_context = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 2), octet_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegContext.setStatus('current')
if mibBuilder.loadTexts:
agentxRegContext.setDescription('The context in which the session supports the objects in this region. A zero-length context indicates the default context. ')
agentx_reg_start = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 3), object_identifier()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegStart.setStatus('current')
if mibBuilder.loadTexts:
agentxRegStart.setDescription('The starting OBJECT IDENTIFIER of this registration entry. The session identified by agentxSessionIndex implements objects starting at this value (inclusive). Note that this value could identify an object type, an object instance, or a partial object instance. ')
agentx_reg_range_sub_id = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 4), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegRangeSubId.setStatus('current')
if mibBuilder.loadTexts:
agentxRegRangeSubId.setDescription("agentxRegRangeSubId is used to specify the range. This is taken from r.region_subid in the registration PDU. If the value of this object is zero, no range is specified. If it is non-zero, it identifies the `nth' sub-identifier in r.region for which this entry's agentxRegUpperBound value is substituted in the OID for purposes of defining the region's upper bound. ")
agentx_reg_upper_bound = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 5), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegUpperBound.setStatus('current')
if mibBuilder.loadTexts:
agentxRegUpperBound.setDescription('agentxRegUpperBound represents the upper-bound sub-identifier in a registration. This is taken from the r.upper_bound in the registration PDU. If agentxRegRangeSubid (r.region_subid) is zero, this value is also zero and is not used to define an upper bound for this registration. ')
agentx_reg_priority = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 6), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegPriority.setStatus('current')
if mibBuilder.loadTexts:
agentxRegPriority.setDescription('The registration priority. Lower values have higher priority. This value is taken from r.priority in the register PDU. Sessions should use the value of 127 for r.priority if a default value is desired. ')
agentx_reg_timeout = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setUnits('seconds').setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegTimeout.setStatus('current')
if mibBuilder.loadTexts:
agentxRegTimeout.setDescription('The timeout value, in seconds, for responses to requests associated with this registered MIB region. A value of zero(0) indicates the default value (indicated by by agentxSessionTimeout or agentxDefaultTimeout) is to be used. This value is taken from the r.timeout field of the agentx-Register-PDU. ')
agentx_reg_instance = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 8), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegInstance.setStatus('current')
if mibBuilder.loadTexts:
agentxRegInstance.setDescription("The value of agentxRegInstance is `true' for registrations for which the INSTANCE_REGISTRATION was set, and is `false' for all other registrations. ")
agentx_conformance = mib_identifier((1, 3, 6, 1, 2, 1, 74, 2))
agentx_mib_groups = mib_identifier((1, 3, 6, 1, 2, 1, 74, 2, 1))
agentx_mib_compliances = mib_identifier((1, 3, 6, 1, 2, 1, 74, 2, 2))
agentx_mib_compliance = module_compliance((1, 3, 6, 1, 2, 1, 74, 2, 2, 1)).setObjects(('AGENTX-MIB', 'agentxMIBGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
agentx_mib_compliance = agentxMIBCompliance.setStatus('current')
if mibBuilder.loadTexts:
agentxMIBCompliance.setDescription('The compliance statement for SNMP entities that implement the AgentX protocol. Note that a compliant agent can implement all objects in this MIB module as read-only. ')
agentx_mib_group = object_group((1, 3, 6, 1, 2, 1, 74, 2, 1, 1)).setObjects(('AGENTX-MIB', 'agentxDefaultTimeout'), ('AGENTX-MIB', 'agentxMasterAgentXVer'), ('AGENTX-MIB', 'agentxConnTableLastChange'), ('AGENTX-MIB', 'agentxConnOpenTime'), ('AGENTX-MIB', 'agentxConnTransportDomain'), ('AGENTX-MIB', 'agentxConnTransportAddress'), ('AGENTX-MIB', 'agentxSessionTableLastChange'), ('AGENTX-MIB', 'agentxSessionTimeout'), ('AGENTX-MIB', 'agentxSessionObjectID'), ('AGENTX-MIB', 'agentxSessionDescr'), ('AGENTX-MIB', 'agentxSessionAdminStatus'), ('AGENTX-MIB', 'agentxSessionOpenTime'), ('AGENTX-MIB', 'agentxSessionAgentXVer'), ('AGENTX-MIB', 'agentxRegistrationTableLastChange'), ('AGENTX-MIB', 'agentxRegContext'), ('AGENTX-MIB', 'agentxRegStart'), ('AGENTX-MIB', 'agentxRegRangeSubId'), ('AGENTX-MIB', 'agentxRegUpperBound'), ('AGENTX-MIB', 'agentxRegPriority'), ('AGENTX-MIB', 'agentxRegTimeout'), ('AGENTX-MIB', 'agentxRegInstance'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
agentx_mib_group = agentxMIBGroup.setStatus('current')
if mibBuilder.loadTexts:
agentxMIBGroup.setDescription('All accessible objects in the AgentX MIB. ')
mibBuilder.exportSymbols('AGENTX-MIB', agentxConnTransportAddress=agentxConnTransportAddress, agentxRegistrationTable=agentxRegistrationTable, agentxMIBGroups=agentxMIBGroups, agentxSession=agentxSession, agentxDefaultTimeout=agentxDefaultTimeout, agentxConformance=agentxConformance, agentxGeneral=agentxGeneral, PYSNMP_MODULE_ID=agentxMIB, agentxConnTransportDomain=agentxConnTransportDomain, agentxSessionTableLastChange=agentxSessionTableLastChange, AgentxTAddress=AgentxTAddress, agentxRegInstance=agentxRegInstance, agentxMIBCompliances=agentxMIBCompliances, agentxRegistration=agentxRegistration, agentxConnIndex=agentxConnIndex, agentxConnOpenTime=agentxConnOpenTime, agentxRegIndex=agentxRegIndex, agentxMIB=agentxMIB, agentxSessionIndex=agentxSessionIndex, agentxRegistrationTableLastChange=agentxRegistrationTableLastChange, agentxSessionEntry=agentxSessionEntry, agentxRegRangeSubId=agentxRegRangeSubId, agentxConnTableLastChange=agentxConnTableLastChange, agentxSessionAgentXVer=agentxSessionAgentXVer, agentxSessionOpenTime=agentxSessionOpenTime, agentxRegTimeout=agentxRegTimeout, agentxMIBGroup=agentxMIBGroup, agentxSessionTable=agentxSessionTable, agentxSessionObjectID=agentxSessionObjectID, agentxRegStart=agentxRegStart, agentxSessionTimeout=agentxSessionTimeout, agentxConnectionTable=agentxConnectionTable, agentxConnectionEntry=agentxConnectionEntry, agentxRegPriority=agentxRegPriority, agentxMIBCompliance=agentxMIBCompliance, agentxRegistrationEntry=agentxRegistrationEntry, agentxRegUpperBound=agentxRegUpperBound, agentxConnection=agentxConnection, agentxObjects=agentxObjects, agentxSessionAdminStatus=agentxSessionAdminStatus, agentxMasterAgentXVer=agentxMasterAgentXVer, agentxRegContext=agentxRegContext, agentxSessionDescr=agentxSessionDescr) |
class Layer:
def __init(self):
self.input=None
self.output=None
def forward(self,input):
#to return the output layer
pass
def backward(self,output_gradient,learning_rate):
#change para and return input derivative
pass
| class Layer:
def __init(self):
self.input = None
self.output = None
def forward(self, input):
pass
def backward(self, output_gradient, learning_rate):
pass |
class Capture:
def capture(self):
pass
| class Capture:
def capture(self):
pass |
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(input())
values = [str(f(x)) for x in range(0, n+1)]
print(",".join(values)) | def f(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return f(n - 1) + f(n - 2)
n = int(input())
values = [str(f(x)) for x in range(0, n + 1)]
print(','.join(values)) |
#TODO Create Functions for PMTA
## TORISPHERICAL TOP HEAD 2:1 - Min thickness allowed and PMTA
class TorisphericalCalcs:
def __init__(self):
self.L_top_head = None
self.r_top_head = None
self.ratio_L_r_top = None
self.M_factor_top_head = None
self.t_min_top_head = None
self.t_nom_top_head_plate =None
self.t_top_head_nom_after_conf = None
self.top_head_pmta = None
self.L_bottom_head = None
self.r_bottom_head = None
self.ratio_L_r_bottom = None
self.M_factor_bottom_head = None
self.t_min_bottom_head = None
self.t_nom_bottom_head_plate = None
self.t_bottom_head_nom_after_conf = None
self.bottom_head_pmta = None
def tor_top_min_thick_allowed(self,Rcor, P, Shot_top_head, E, conf_loss, C):
self.L_top_head = 0.904 * (2 * Rcor)
self.r_top_head = 0.173 * (2 * Rcor)
self.ratio_L_r_top = self.L_top_head/self.r_top_head
self.M_factor_top_head = (1/4) * (3 + (self.ratio_L_r_top)**(1/2))
self.t_min_top_head = (P * self.L_top_head * self.M_factor_top_head) / ((2 * Shot_top_head * E) - 0.2 * P)
self.t_nom_top_head_plate = self.t_min_top_head + conf_loss + C
self.t_top_head_nom_after_conf = self.t_min_top_head + C
print(f"\n\nTorispherical Top Head Min thickness allowed: \n\nTop Head radius (L) is {self.L_top_head} mm \nTop Head Toroidal radius (r) is {self.r_top_head} mm \nTop Head M factor (M) is {self.M_factor_top_head}")
print(f"Top Head minimun thickness due circuferencial stress is {self.t_min_top_head} mm.")
print(f"Top Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_top_head_plate} mm. Ps.: Choose equal or higher comercial plate")
print(f"Top Head Nominal Thicknes after conformation is {self.t_top_head_nom_after_conf} mm")
return self.L_top_head, self.r_top_head, self.ratio_L_r_top , self.M_factor_top_head, self.t_nom_top_head_plate, self.t_top_head_nom_after_conf, self.t_min_top_head
def tor_top_head_pmta (self,Rcor, Shot_top_head, E):
self.L_top_head = 0.904 * (2 * Rcor)
self.r_top_head = 0.173 * (2 * Rcor)
self.ratio_L_r_top = self.L_top_head/self.r_top_head
self.M_factor_top_head = (1/4) * (3 + (self.ratio_L_r_top)**(1/2))
self.top_head_pmta = (2*self.t_min_top_head*Shot_top_head*E)/(self.L_top_head*self.M_factor_top_head + 0.2*self.t_min_top_head)
print(f"Top Head MAWP is: {self.top_head_pmta} kPa")
return self.top_head_pmta
def tor_top_head_stress_calc(self, P, E):
self.top_head_stress = P * (self.L_top_head * self.M_factor_top_head + 0.2 * self.t_min_top_head) / (2 * self.t_min_top_head * E)
print(f"Top head stress is {self.top_head_stress} kPa")
return self.top_head_stress
## TORISPHERICAL BOTTOM HEAD 2:1 - Min thickness allowed and PMTA
def tor_bottom_min_thick_allowed(self,Rcor,Pwater_col, P, Shot_bottom_head, E, conf_loss, C ):
self.L_bottom_head = 0.904 * (2 * Rcor)
self.r_bottom_head = 0.173 * (2 * Rcor)
self.ratio_L_r_bottom = self.L_bottom_head/self.r_bottom_head
self.M_factor_bottom_head = (1/4) * (3 + (self.ratio_L_r_bottom)**(1/2))
self.t_min_bottom_head = ((P+Pwater_col) * self.L_bottom_head * self.M_factor_bottom_head) / ((2 * Shot_bottom_head * E) - 0.2 * P)
self.t_nom_bottom_head_plate = self.t_min_bottom_head + conf_loss + C
self.t_bottom_head_nom_after_conf = self.t_min_bottom_head + C
print(f"\n\nTorispherical Bottom Head Min thickness allowed: \n\nBottom Head radius (L) is {self.L_bottom_head} mm \nBottom Head Toroidal radius (r) is {self.r_bottom_head} mm \nBottom Head M factor (M) is {self.M_factor_bottom_head}")
print(f"Bottom Head minimun thickness due circuferencial stress is {self.t_min_bottom_head} mm.")
print(f"Bottom Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_bottom_head_plate} mm. Ps.: Choose equal or higher comercial plate")
print(f"Bottom Head Nominal Thicknes after conformation is {self.t_bottom_head_nom_after_conf} mm")
return self.L_bottom_head, self.r_bottom_head, self.ratio_L_r_bottom, self.M_factor_bottom_head, self.t_min_bottom_head, self.t_nom_bottom_head_plate, self.t_bottom_head_nom_after_conf
def tor_bottom_head_pmta (self,Rcor, E, Shot_bottom_head):
self.L_bottom_head = 0.904 * (2 * Rcor)
self.r_bottom_head = 0.173 * (2 * Rcor)
self.ratio_L_r_bottom = self.L_bottom_head/self.r_bottom_head
self.M_factor_bottom_head = (1/4) * (3 + (self.ratio_L_r_bottom)**(1/2))
self.bottom_head_pmta = (2*self.t_min_bottom_head*Shot_bottom_head*E)/(self.L_bottom_head*self.M_factor_bottom_head + 0.2*self.t_min_bottom_head)
print(f"Bottom Head MAWP is: {self.bottom_head_pmta} kPa")
return self.bottom_head_pmta
def tor_bottom_head_stress_calc(self,Pwater_col, P, E):
self.bottom_head_stress = (P+Pwater_col) * (self.L_bottom_head * self.M_factor_bottom_head + 0.2 * self.t_min_bottom_head) / (2 * self.t_min_bottom_head * E)
print(f"Bottom head stress is {self.bottom_head_stress} kPa")
return self.bottom_head_stress | class Torisphericalcalcs:
def __init__(self):
self.L_top_head = None
self.r_top_head = None
self.ratio_L_r_top = None
self.M_factor_top_head = None
self.t_min_top_head = None
self.t_nom_top_head_plate = None
self.t_top_head_nom_after_conf = None
self.top_head_pmta = None
self.L_bottom_head = None
self.r_bottom_head = None
self.ratio_L_r_bottom = None
self.M_factor_bottom_head = None
self.t_min_bottom_head = None
self.t_nom_bottom_head_plate = None
self.t_bottom_head_nom_after_conf = None
self.bottom_head_pmta = None
def tor_top_min_thick_allowed(self, Rcor, P, Shot_top_head, E, conf_loss, C):
self.L_top_head = 0.904 * (2 * Rcor)
self.r_top_head = 0.173 * (2 * Rcor)
self.ratio_L_r_top = self.L_top_head / self.r_top_head
self.M_factor_top_head = 1 / 4 * (3 + self.ratio_L_r_top ** (1 / 2))
self.t_min_top_head = P * self.L_top_head * self.M_factor_top_head / (2 * Shot_top_head * E - 0.2 * P)
self.t_nom_top_head_plate = self.t_min_top_head + conf_loss + C
self.t_top_head_nom_after_conf = self.t_min_top_head + C
print(f'\n\nTorispherical Top Head Min thickness allowed: \n\nTop Head radius (L) is {self.L_top_head} mm \nTop Head Toroidal radius (r) is {self.r_top_head} mm \nTop Head M factor (M) is {self.M_factor_top_head}')
print(f'Top Head minimun thickness due circuferencial stress is {self.t_min_top_head} mm.')
print(f'Top Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_top_head_plate} mm. Ps.: Choose equal or higher comercial plate')
print(f'Top Head Nominal Thicknes after conformation is {self.t_top_head_nom_after_conf} mm')
return (self.L_top_head, self.r_top_head, self.ratio_L_r_top, self.M_factor_top_head, self.t_nom_top_head_plate, self.t_top_head_nom_after_conf, self.t_min_top_head)
def tor_top_head_pmta(self, Rcor, Shot_top_head, E):
self.L_top_head = 0.904 * (2 * Rcor)
self.r_top_head = 0.173 * (2 * Rcor)
self.ratio_L_r_top = self.L_top_head / self.r_top_head
self.M_factor_top_head = 1 / 4 * (3 + self.ratio_L_r_top ** (1 / 2))
self.top_head_pmta = 2 * self.t_min_top_head * Shot_top_head * E / (self.L_top_head * self.M_factor_top_head + 0.2 * self.t_min_top_head)
print(f'Top Head MAWP is: {self.top_head_pmta} kPa')
return self.top_head_pmta
def tor_top_head_stress_calc(self, P, E):
self.top_head_stress = P * (self.L_top_head * self.M_factor_top_head + 0.2 * self.t_min_top_head) / (2 * self.t_min_top_head * E)
print(f'Top head stress is {self.top_head_stress} kPa')
return self.top_head_stress
def tor_bottom_min_thick_allowed(self, Rcor, Pwater_col, P, Shot_bottom_head, E, conf_loss, C):
self.L_bottom_head = 0.904 * (2 * Rcor)
self.r_bottom_head = 0.173 * (2 * Rcor)
self.ratio_L_r_bottom = self.L_bottom_head / self.r_bottom_head
self.M_factor_bottom_head = 1 / 4 * (3 + self.ratio_L_r_bottom ** (1 / 2))
self.t_min_bottom_head = (P + Pwater_col) * self.L_bottom_head * self.M_factor_bottom_head / (2 * Shot_bottom_head * E - 0.2 * P)
self.t_nom_bottom_head_plate = self.t_min_bottom_head + conf_loss + C
self.t_bottom_head_nom_after_conf = self.t_min_bottom_head + C
print(f'\n\nTorispherical Bottom Head Min thickness allowed: \n\nBottom Head radius (L) is {self.L_bottom_head} mm \nBottom Head Toroidal radius (r) is {self.r_bottom_head} mm \nBottom Head M factor (M) is {self.M_factor_bottom_head}')
print(f'Bottom Head minimun thickness due circuferencial stress is {self.t_min_bottom_head} mm.')
print(f'Bottom Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_bottom_head_plate} mm. Ps.: Choose equal or higher comercial plate')
print(f'Bottom Head Nominal Thicknes after conformation is {self.t_bottom_head_nom_after_conf} mm')
return (self.L_bottom_head, self.r_bottom_head, self.ratio_L_r_bottom, self.M_factor_bottom_head, self.t_min_bottom_head, self.t_nom_bottom_head_plate, self.t_bottom_head_nom_after_conf)
def tor_bottom_head_pmta(self, Rcor, E, Shot_bottom_head):
self.L_bottom_head = 0.904 * (2 * Rcor)
self.r_bottom_head = 0.173 * (2 * Rcor)
self.ratio_L_r_bottom = self.L_bottom_head / self.r_bottom_head
self.M_factor_bottom_head = 1 / 4 * (3 + self.ratio_L_r_bottom ** (1 / 2))
self.bottom_head_pmta = 2 * self.t_min_bottom_head * Shot_bottom_head * E / (self.L_bottom_head * self.M_factor_bottom_head + 0.2 * self.t_min_bottom_head)
print(f'Bottom Head MAWP is: {self.bottom_head_pmta} kPa')
return self.bottom_head_pmta
def tor_bottom_head_stress_calc(self, Pwater_col, P, E):
self.bottom_head_stress = (P + Pwater_col) * (self.L_bottom_head * self.M_factor_bottom_head + 0.2 * self.t_min_bottom_head) / (2 * self.t_min_bottom_head * E)
print(f'Bottom head stress is {self.bottom_head_stress} kPa')
return self.bottom_head_stress |
'''
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
'''
class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
last_bit = n & 1
n >>= 1
while n > 0:
tmp = n & 1
if tmp == last_bit:
return False
last_bit = tmp
n >>= 1
return True
| """
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
"""
class Solution(object):
def has_alternating_bits(self, n):
"""
:type n: int
:rtype: bool
"""
last_bit = n & 1
n >>= 1
while n > 0:
tmp = n & 1
if tmp == last_bit:
return False
last_bit = tmp
n >>= 1
return True |
# Collaborators (including web sites where you got help: (enter none if you didn't need help)
# claryse adams
def avg_temp(user_list):
total = 0
for x in range(1, len(user_list)):
total += user_list[x]
average = total/(len(user_list)-1)
average = round(average, 2)
return average
if __name__ == '__main__':
with open("temps.txt") as file_object:
contents = file_object.readlines()
int()
list_length = len(contents)
for i in range(1, list_length):
contents[i] = contents[i].rstrip()
contents[i] = int(contents[i])
print(contents)
print(avg_temp(contents)) | def avg_temp(user_list):
total = 0
for x in range(1, len(user_list)):
total += user_list[x]
average = total / (len(user_list) - 1)
average = round(average, 2)
return average
if __name__ == '__main__':
with open('temps.txt') as file_object:
contents = file_object.readlines()
int()
list_length = len(contents)
for i in range(1, list_length):
contents[i] = contents[i].rstrip()
contents[i] = int(contents[i])
print(contents)
print(avg_temp(contents)) |
def fry():
print('The eggs have been fried')
| def fry():
print('The eggs have been fried') |
class Data:
def __init__(self, dia, mes, ano):
self.dia = dia
self.mes = mes
self.ano = ano
print(self)
@classmethod
def de_string(cls, data_string):
dia, mes, ano = map(int, data_string.split("-"))
data = cls(dia, mes, ano)
return data
@staticmethod
def is_date_valid(data_string):
dia, mes, ano = map(int, data_string.split("-"))
return dia <= 31 and mes <= 12 and ano <= 2030
data = Data(10, 10, 10)
data1 = data.de_string("10-10-2020")
print(data1)
vdd = data1.is_date_valid("10-10-2020")
print(vdd)
| class Data:
def __init__(self, dia, mes, ano):
self.dia = dia
self.mes = mes
self.ano = ano
print(self)
@classmethod
def de_string(cls, data_string):
(dia, mes, ano) = map(int, data_string.split('-'))
data = cls(dia, mes, ano)
return data
@staticmethod
def is_date_valid(data_string):
(dia, mes, ano) = map(int, data_string.split('-'))
return dia <= 31 and mes <= 12 and (ano <= 2030)
data = data(10, 10, 10)
data1 = data.de_string('10-10-2020')
print(data1)
vdd = data1.is_date_valid('10-10-2020')
print(vdd) |
"""
Created by adam on 5/20/18
"""
__author__ = 'adam'
class IModifierList(object):
"""
Interface for classes which act on a list of strings by modifying
the input strings and returning a list of modified strings.
Used for tasks like lemmatizing etc
"""
def __init__(self):
pass
def run(self, wordbag, **kwargs):
"""
Processes list of strings
:param wordbag: List of strings to run
:param kwargs:
:return: List of strings, modified
"""
raise NotImplementedError
class IModifier(object):
"""
Interface for classes which modify the input string and return the
modified string.
Used for tasks like stemming lemmatizing etc
"""
def __init__(self):
pass
def run(self, text, **kwargs):
raise NotImplementedError
def _check_is_single_word(self, text):
"""
Some implmentations of IModifier allow for sentences. Others
want just one word at a time. This is called by the latter
and checks to make sure that it has the correct input
:param text: String to screen for multiple words
"""
assert (type(text) is str)
assert (text.count(" ") is 0)
if __name__ == '__main__':
pass
| """
Created by adam on 5/20/18
"""
__author__ = 'adam'
class Imodifierlist(object):
"""
Interface for classes which act on a list of strings by modifying
the input strings and returning a list of modified strings.
Used for tasks like lemmatizing etc
"""
def __init__(self):
pass
def run(self, wordbag, **kwargs):
"""
Processes list of strings
:param wordbag: List of strings to run
:param kwargs:
:return: List of strings, modified
"""
raise NotImplementedError
class Imodifier(object):
"""
Interface for classes which modify the input string and return the
modified string.
Used for tasks like stemming lemmatizing etc
"""
def __init__(self):
pass
def run(self, text, **kwargs):
raise NotImplementedError
def _check_is_single_word(self, text):
"""
Some implmentations of IModifier allow for sentences. Others
want just one word at a time. This is called by the latter
and checks to make sure that it has the correct input
:param text: String to screen for multiple words
"""
assert type(text) is str
assert text.count(' ') is 0
if __name__ == '__main__':
pass |
class DummyContext:
context = {}
dummy_context = DummyContext()
| class Dummycontext:
context = {}
dummy_context = dummy_context() |
class NameScope(object,INameScopeDictionary,INameScope,IDictionary[str,object],ICollection[KeyValuePair[str,object]],IEnumerable[KeyValuePair[str,object]],IEnumerable):
"""
Implements base WPF support for the System.Windows.Markup.INameScope methods that store or retrieve name-object mappings into a particular XAML namescope. Adds attached property support to make it simpler to get or set XAML namescope names dynamically at the element level..
NameScope()
"""
def Add(self,*__args):
"""
Add(self: NameScope,key: str,value: object)
Adds an item to the collection.
key: The string key,which is the name of the XAML namescope mapping to add.
value: The object value,which is the object reference of the XAML namescope mapping
to add.
Add(self: NameScope,item: KeyValuePair[str,object])
"""
pass
def Clear(self):
"""
Clear(self: NameScope)
Removes all items from the collection.
"""
pass
def Contains(self,item):
""" Contains(self: NameScope,item: KeyValuePair[str,object]) -> bool """
pass
def ContainsKey(self,key):
"""
ContainsKey(self: NameScope,key: str) -> bool
Returns whether a provided name already exists in this System.Windows.NameScope.
key: The string key to find.
Returns: true if the specified key identifies a name for an existing mapping in this
System.Windows.NameScope. false if the specified key does not exist in the
current System.Windows.NameScope.
"""
pass
def CopyTo(self,array,arrayIndex):
""" CopyTo(self: NameScope,array: Array[KeyValuePair[str,object]],arrayIndex: int) """
pass
def FindName(self,name):
"""
FindName(self: NameScope,name: str) -> object
Returns the corresponding object in the XAML namescope maintained by this
System.Windows.NameScope,based on a provided name string.
name: Name portion of an existing mapping to retrieve the object portion for.
Returns: The requested object that is mapped with name. Can return null if name was
provided as null or empty string,or if no matching object was found.
"""
pass
@staticmethod
def GetNameScope(dependencyObject):
"""
GetNameScope(dependencyObject: DependencyObject) -> INameScope
Provides the attached property get accessor for the
System.Windows.NameScope.NameScope attached property.
dependencyObject: The object to get the XAML namescope from.
Returns: A XAML namescope,as an System.Windows.Markup.INameScope instance.
"""
pass
def RegisterName(self,name,scopedElement):
"""
RegisterName(self: NameScope,name: str,scopedElement: object)
Registers a new name-object pair into the current XAML namescope.
name: The name to use for mapping the given object.
scopedElement: The object to be mapped to the provided name.
"""
pass
def Remove(self,*__args):
"""
Remove(self: NameScope,key: str) -> bool
Removes a mapping for a specified name from the collection.
key: The string key,which is the name of the XAML namescope mapping to remove.
Returns: true if item was successfully removed from the collection,otherwise false.
Also returns false if the item was not found in the collection.
Remove(self: NameScope,item: KeyValuePair[str,object]) -> bool
"""
pass
@staticmethod
def SetNameScope(dependencyObject,value):
"""
SetNameScope(dependencyObject: DependencyObject,value: INameScope)
Provides the attached property set accessor for the
System.Windows.NameScope.NameScope attached property.
dependencyObject: Object to change XAML namescope for.
value: The new XAML namescope,using an interface cast.
"""
pass
def TryGetValue(self,key,value):
"""
TryGetValue(self: NameScope,key: str) -> (bool,object)
Gets the value associated with the specified key.
key: The key of the value to get.
Returns: true if the System.Windows.NameScope contains a mapping for the name provided
as key. Otherwise,false.
"""
pass
def UnregisterName(self,name):
"""
UnregisterName(self: NameScope,name: str)
Removes a name-object mapping from the XAML namescope.
name: The name of the mapping to remove.
"""
pass
def __add__(self,*args):
""" x.__add__(y) <==> x+yx.__add__(y) <==> x+y """
pass
def __contains__(self,*args):
""" __contains__(self: IDictionary[str,object],key: str) -> bool """
pass
def __getitem__(self,*args):
""" x.__getitem__(y) <==> x[y] """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __iter__(self,*args):
""" __iter__(self: IEnumerable) -> object """
pass
def __len__(self,*args):
""" x.__len__() <==> len(x) """
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __setitem__(self,*args):
""" x.__setitem__(i,y) <==> x[i]= """
pass
Count=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Returns the number of items in the collection of mapped names in this System.Windows.NameScope.
Get: Count(self: NameScope) -> int
"""
IsReadOnly=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the collection is read-only.
Get: IsReadOnly(self: NameScope) -> bool
"""
Keys=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a collection of the keys in the System.Windows.NameScope dictionary.
Get: Keys(self: NameScope) -> ICollection[str]
"""
Values=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a collection of the values in the System.Windows.NameScope dictionary.
Get: Values(self: NameScope) -> ICollection[object]
"""
NameScopeProperty=None
| class Namescope(object, INameScopeDictionary, INameScope, IDictionary[str, object], ICollection[KeyValuePair[str, object]], IEnumerable[KeyValuePair[str, object]], IEnumerable):
"""
Implements base WPF support for the System.Windows.Markup.INameScope methods that store or retrieve name-object mappings into a particular XAML namescope. Adds attached property support to make it simpler to get or set XAML namescope names dynamically at the element level..
NameScope()
"""
def add(self, *__args):
"""
Add(self: NameScope,key: str,value: object)
Adds an item to the collection.
key: The string key,which is the name of the XAML namescope mapping to add.
value: The object value,which is the object reference of the XAML namescope mapping
to add.
Add(self: NameScope,item: KeyValuePair[str,object])
"""
pass
def clear(self):
"""
Clear(self: NameScope)
Removes all items from the collection.
"""
pass
def contains(self, item):
""" Contains(self: NameScope,item: KeyValuePair[str,object]) -> bool """
pass
def contains_key(self, key):
"""
ContainsKey(self: NameScope,key: str) -> bool
Returns whether a provided name already exists in this System.Windows.NameScope.
key: The string key to find.
Returns: true if the specified key identifies a name for an existing mapping in this
System.Windows.NameScope. false if the specified key does not exist in the
current System.Windows.NameScope.
"""
pass
def copy_to(self, array, arrayIndex):
""" CopyTo(self: NameScope,array: Array[KeyValuePair[str,object]],arrayIndex: int) """
pass
def find_name(self, name):
"""
FindName(self: NameScope,name: str) -> object
Returns the corresponding object in the XAML namescope maintained by this
System.Windows.NameScope,based on a provided name string.
name: Name portion of an existing mapping to retrieve the object portion for.
Returns: The requested object that is mapped with name. Can return null if name was
provided as null or empty string,or if no matching object was found.
"""
pass
@staticmethod
def get_name_scope(dependencyObject):
"""
GetNameScope(dependencyObject: DependencyObject) -> INameScope
Provides the attached property get accessor for the
System.Windows.NameScope.NameScope attached property.
dependencyObject: The object to get the XAML namescope from.
Returns: A XAML namescope,as an System.Windows.Markup.INameScope instance.
"""
pass
def register_name(self, name, scopedElement):
"""
RegisterName(self: NameScope,name: str,scopedElement: object)
Registers a new name-object pair into the current XAML namescope.
name: The name to use for mapping the given object.
scopedElement: The object to be mapped to the provided name.
"""
pass
def remove(self, *__args):
"""
Remove(self: NameScope,key: str) -> bool
Removes a mapping for a specified name from the collection.
key: The string key,which is the name of the XAML namescope mapping to remove.
Returns: true if item was successfully removed from the collection,otherwise false.
Also returns false if the item was not found in the collection.
Remove(self: NameScope,item: KeyValuePair[str,object]) -> bool
"""
pass
@staticmethod
def set_name_scope(dependencyObject, value):
"""
SetNameScope(dependencyObject: DependencyObject,value: INameScope)
Provides the attached property set accessor for the
System.Windows.NameScope.NameScope attached property.
dependencyObject: Object to change XAML namescope for.
value: The new XAML namescope,using an interface cast.
"""
pass
def try_get_value(self, key, value):
"""
TryGetValue(self: NameScope,key: str) -> (bool,object)
Gets the value associated with the specified key.
key: The key of the value to get.
Returns: true if the System.Windows.NameScope contains a mapping for the name provided
as key. Otherwise,false.
"""
pass
def unregister_name(self, name):
"""
UnregisterName(self: NameScope,name: str)
Removes a name-object mapping from the XAML namescope.
name: The name of the mapping to remove.
"""
pass
def __add__(self, *args):
""" x.__add__(y) <==> x+yx.__add__(y) <==> x+y """
pass
def __contains__(self, *args):
""" __contains__(self: IDictionary[str,object],key: str) -> bool """
pass
def __getitem__(self, *args):
""" x.__getitem__(y) <==> x[y] """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __iter__(self, *args):
""" __iter__(self: IEnumerable) -> object """
pass
def __len__(self, *args):
""" x.__len__() <==> len(x) """
pass
def __repr__(self, *args):
""" __repr__(self: object) -> str """
pass
def __setitem__(self, *args):
""" x.__setitem__(i,y) <==> x[i]= """
pass
count = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Returns the number of items in the collection of mapped names in this System.Windows.NameScope.\n\n\n\nGet: Count(self: NameScope) -> int\n\n\n\n'
is_read_only = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets a value indicating whether the collection is read-only.\n\n\n\nGet: IsReadOnly(self: NameScope) -> bool\n\n\n\n'
keys = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets a collection of the keys in the System.Windows.NameScope dictionary.\n\n\n\nGet: Keys(self: NameScope) -> ICollection[str]\n\n\n\n'
values = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets a collection of the values in the System.Windows.NameScope dictionary.\n\n\n\nGet: Values(self: NameScope) -> ICollection[object]\n\n\n\n'
name_scope_property = None |
# Copyright 2020 BBC Research & Development
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
experiment_name = "exp1_bn" # experiment name
experiment_path = "experiment/path" # experiment base path
output_path = experiment_path + experiment_name
# Model parameters
core_model = "bn_model" # [bn_model, in_model, bn_sn_model, in_sn_model, ibn_model]
d_scales = 1 # number of multi discriminator scales
# Data parameters
data_path = "data/path" # data path for train and test
input_shape = (256, 256) # input shape
input_color_mode = 'rgb' # input colour space (same as data path content)
output_color_mode = 'lab' # output colour space
interpolation = 'nearest' # interpolation for reshaping operations
chunk_size = 10000 # reading chunk size
samples_rate = 1. # percentage of output samples within data path
shuffle = True # shuffle during training
seed = 42 # seed for shuffle operation
# Training parameters
epochs = 200 # training epochs
batch_size = 16 # batch size for train and validation. batch_size = 1 for test
l1_lambda = 100 # l1 weight into global loss function
lr_d = 0.0002 # learning rate for discriminator
lr_g = 0.0002 # learning rate for generator
beta = 0.5 # learning beta
display_step = 10 # step size for updating tensorboard log file
plots_per_epoch = 20 # prediction logs per epoch
weights_per_epoch = 20 # weight checkpoints per epoch
multi_gpu = False # enable multi gpu model
gpus = 2 # number of available gpus
workers = 10 # number of worker threads
max_queue_size = 10 # queue size for worker threads
use_multiprocessing = False # use multiprocessing
| experiment_name = 'exp1_bn'
experiment_path = 'experiment/path'
output_path = experiment_path + experiment_name
core_model = 'bn_model'
d_scales = 1
data_path = 'data/path'
input_shape = (256, 256)
input_color_mode = 'rgb'
output_color_mode = 'lab'
interpolation = 'nearest'
chunk_size = 10000
samples_rate = 1.0
shuffle = True
seed = 42
epochs = 200
batch_size = 16
l1_lambda = 100
lr_d = 0.0002
lr_g = 0.0002
beta = 0.5
display_step = 10
plots_per_epoch = 20
weights_per_epoch = 20
multi_gpu = False
gpus = 2
workers = 10
max_queue_size = 10
use_multiprocessing = False |
# -*- coding: utf-8 -*-
__author__ = 'Wael Ben Zid El Guebsi'
__email__ = 'benzid.wael@hotmail.fr'
__version__ = '0.0.0' | __author__ = 'Wael Ben Zid El Guebsi'
__email__ = 'benzid.wael@hotmail.fr'
__version__ = '0.0.0' |
# coding: utf-8
n = int(input())
li = [int(i) for i in input().split()]
print(sum(li)/n)
| n = int(input())
li = [int(i) for i in input().split()]
print(sum(li) / n) |
class Question:
def __init__(self, text, answer):
self.text = text
self.answer = answer
new_q = Question("lkajsdkf", "False")
| class Question:
def __init__(self, text, answer):
self.text = text
self.answer = answer
new_q = question('lkajsdkf', 'False') |
#!/usr/bin/env python3
"""Mtools version."""
__version__ = '1.6.4-dev'
| """Mtools version."""
__version__ = '1.6.4-dev' |
def buildMaskSplit(noiseGShape,
noiseGTexture,
categoryVectorDim,
attribKeysOrder,
attribShift,
keySplits=None,
mixedNoise=False):
r"""
Build a 8bits mask that split a full input latent vector into two
intermediate latent vectors: one for the shape network and one for the
texture network.
"""
# latent vector split
# Reminder, a latent vector is organized as follow
# [z1,......, z_N, c_1, ....., c_C]
# N : size of the noise part
# C : size of the conditional part (ACGAN)
# Here we will split the vector in
# [y1, ..., y_N1, z1,......, z_N2, c_1, ....., c_C]
N1 = noiseGShape
N2 = noiseGTexture
if not mixedNoise:
maskShape = [1 for x in range(N1)] + [0 for x in range(N2)]
maskTexture = [0 for x in range(N1)] + [1 for x in range(N2)]
else:
maskShape = [1 for x in range(N1 + N2)]
maskTexture = [1 for x in range(N1 + N2)]
# Now the conditional part
# Some conditions apply to the shape, other to the texture, and sometimes
# to both
if attribKeysOrder is not None:
C = categoryVectorDim
if keySplits is not None:
maskShape = maskShape + [0 for x in range(C)]
maskTexture = maskTexture + [0 for x in range(C)]
for key in keySplits["GShape"]:
index = attribKeysOrder[key]["order"]
shift = N1 + N2 + attribShift[index]
for i in range(shift, shift + len(attribKeysOrder[key]["values"])):
maskShape[i] = 1
for key in keySplits["GTexture"]:
index = attribKeysOrder[key]["order"]
shift = N1 + N2 + attribShift[index]
for i in range(shift, shift + len(attribKeysOrder[key]["values"])):
maskTexture[i] = 1
else:
maskShape = maskShape + [1 for x in range(C)]
maskTexture = maskTexture + [1 for x in range(C)]
return maskShape, maskTexture
| def build_mask_split(noiseGShape, noiseGTexture, categoryVectorDim, attribKeysOrder, attribShift, keySplits=None, mixedNoise=False):
"""
Build a 8bits mask that split a full input latent vector into two
intermediate latent vectors: one for the shape network and one for the
texture network.
"""
n1 = noiseGShape
n2 = noiseGTexture
if not mixedNoise:
mask_shape = [1 for x in range(N1)] + [0 for x in range(N2)]
mask_texture = [0 for x in range(N1)] + [1 for x in range(N2)]
else:
mask_shape = [1 for x in range(N1 + N2)]
mask_texture = [1 for x in range(N1 + N2)]
if attribKeysOrder is not None:
c = categoryVectorDim
if keySplits is not None:
mask_shape = maskShape + [0 for x in range(C)]
mask_texture = maskTexture + [0 for x in range(C)]
for key in keySplits['GShape']:
index = attribKeysOrder[key]['order']
shift = N1 + N2 + attribShift[index]
for i in range(shift, shift + len(attribKeysOrder[key]['values'])):
maskShape[i] = 1
for key in keySplits['GTexture']:
index = attribKeysOrder[key]['order']
shift = N1 + N2 + attribShift[index]
for i in range(shift, shift + len(attribKeysOrder[key]['values'])):
maskTexture[i] = 1
else:
mask_shape = maskShape + [1 for x in range(C)]
mask_texture = maskTexture + [1 for x in range(C)]
return (maskShape, maskTexture) |
def find_three_values_that_sum(lines, sum=2020):
for idx1, line1 in enumerate(lines):
for idx2, line2 in enumerate(lines[idx1:]):
for idx3, line3 in enumerate(lines[idx1+idx2:]):
num1 = int(line1)
num2 = int(line2)
num3 = int(line3)
if (num1 + num2 + num3 == sum):
print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}, ({idx3}): {num3}')
return num1, num2, num3
def find_two_values_that_sum(lines, sum=2020):
for idx1, line1 in enumerate(lines):
for idx2, line2 in enumerate(lines[idx1:]):
num1 = int(line1)
num2 = int(line2)
if (num1 + num2 == sum):
print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}')
return num1, num2
def main():
filename = 'input-p1.txt'
with open(filename, 'r') as f:
lines = f.readlines()
print(f'Read in file: {filename} Number of lines: {len(lines)}')
num1, num2 = find_two_values_that_sum(lines, sum=2020)
print(f'Multiply two values together: {num1 * num2}')
num1, num2, num3 = find_three_values_that_sum(lines, sum=2020)
print(f'Multiply three values together: {num1 * num2 * num3}')
if __name__ == '__main__':
main()
| def find_three_values_that_sum(lines, sum=2020):
for (idx1, line1) in enumerate(lines):
for (idx2, line2) in enumerate(lines[idx1:]):
for (idx3, line3) in enumerate(lines[idx1 + idx2:]):
num1 = int(line1)
num2 = int(line2)
num3 = int(line3)
if num1 + num2 + num3 == sum:
print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}, ({idx3}): {num3}')
return (num1, num2, num3)
def find_two_values_that_sum(lines, sum=2020):
for (idx1, line1) in enumerate(lines):
for (idx2, line2) in enumerate(lines[idx1:]):
num1 = int(line1)
num2 = int(line2)
if num1 + num2 == sum:
print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}')
return (num1, num2)
def main():
filename = 'input-p1.txt'
with open(filename, 'r') as f:
lines = f.readlines()
print(f'Read in file: {filename} Number of lines: {len(lines)}')
(num1, num2) = find_two_values_that_sum(lines, sum=2020)
print(f'Multiply two values together: {num1 * num2}')
(num1, num2, num3) = find_three_values_that_sum(lines, sum=2020)
print(f'Multiply three values together: {num1 * num2 * num3}')
if __name__ == '__main__':
main() |
class Constants(object):
"""
Constant declarations.
"""
API_URL = 'https://i.instagram.com/api/v1/'
VERSION = '9.2.0'
IG_SIG_KEY = '012a54f51c49aa8c5c322416ab1410909add32c966bbaa0fe3dc58ac43fd7ede'
EXPERIMENTS = 'ig_android_ad_holdout_16m5_universe,ig_android_progressive_jpeg,ig_creation_growth_holdout,ig_android_oppo_app_badging,ig_android_ad_remove_username_from_caption_universe,ig_android_enable_share_to_whatsapp,ig_android_direct_drawing_in_quick_cam_universe,ig_android_ad_always_send_ad_attribution_id_universe,ig_android_universe_video_production,ig_android_direct_plus_button,ig_android_ads_heatmap_overlay_universe,ig_android_http_stack_experiment_2016,ig_android_infinite_scrolling,ig_fbns_blocked,ig_android_post_auto_retry_v7_21,ig_fbns_push,ig_android_video_playback_bandwidth_threshold,ig_android_direct_link_preview,ig_android_direct_typing_indicator,ig_android_preview_capture,ig_android_feed_pill,ig_android_profile_link_iab,ig_android_story_caption,ig_android_network_cancellation,ig_android_histogram_reporter,ig_android_anrwatchdog,ig_android_search_client_matching,ig_android_follow_request_text_buttons,ig_android_feed_zoom,ig_android_drafts_universe,ig_android_disable_comment,ig_android_user_detail_endpoint,ig_android_os_version_blocking,ig_android_blocked_list,ig_android_event_creation,ig_android_high_res_upload_2,ig_android_2fac,ig_android_mark_reel_seen_on_Swipe_forward,ig_android_comment_redesign,ig_android_ad_sponsored_label_universe,ig_android_mentions_dismiss_rule,ig_android_disable_chroma_subsampling,ig_android_share_spinner,ig_android_video_reuse_surface,ig_explore_v3_android_universe,ig_android_media_favorites,ig_android_nux_holdout,ig_android_insta_video_universe,ig_android_search_null_state,ig_android_universe_reel_video_production,liger_instagram_android_univ,ig_android_direct_emoji_picker,ig_feed_holdout_universe,ig_android_direct_send_auto_retry_universe,ig_android_samsung_app_badging,ig_android_disk_usage,ig_android_business_promotion,ig_android_direct_swipe_to_inbox,ig_android_feed_reshare_button_nux,ig_android_react_native_boost_post,ig_android_boomerang_feed_attribution,ig_fbns_shared,ig_fbns_dump_ids,ig_android_react_native_universe,ig_show_promote_button_in_feed,ig_android_ad_metadata_behavior_universe,ig_android_video_loopcount_int,ig_android_inline_gallery_backoff_hours_universe,ig_android_rendering_controls,ig_android_profile_photo_as_media,ig_android_async_stack_image_cache,ig_video_max_duration_qe_preuniverse,ig_video_copyright_whitelist,ig_android_render_stories_with_content_override,ig_android_ad_intent_to_highlight_universe,ig_android_swipe_navigation_x_angle_universe,ig_android_disable_comment_public_test,ig_android_profile,ig_android_direct_blue_tab,ig_android_enable_share_to_messenger,ig_android_fetch_reel_tray_on_resume_universe,ig_android_promote_again,ig_feed_event_landing_page_channel,ig_ranking_following,ig_android_pending_request_search_bar,ig_android_feed_ufi_redesign,ig_android_pending_edits_dialog_universe,ig_android_business_conversion_flow_universe,ig_android_show_your_story_when_empty_universe,ig_android_ad_drop_cookie_early,ig_android_app_start_config,ig_android_fix_ise_two_phase,ig_android_ppage_toggle_universe,ig_android_pbia_normal_weight_universe,ig_android_profanity_filter,ig_ios_su_activity_feed,ig_android_search,ig_android_boomerang_entry,ig_android_mute_story,ig_android_inline_gallery_universe,ig_android_ad_remove_one_tap_indicator_universe,ig_android_view_count_decouple_likes_universe,ig_android_contact_button_redesign_v2,ig_android_periodic_analytics_upload_v2,ig_android_send_direct_typing_indicator,ig_android_ad_holdout_16h2m1_universe,ig_android_react_native_comment_moderation_settings,ig_video_use_sve_universe,ig_android_inline_gallery_no_backoff_on_launch_universe,ig_android_immersive_viewer,ig_android_discover_people_icon,ig_android_profile_follow_back_button,is_android_feed_seen_state,ig_android_dense_feed_unit_cards,ig_android_drafts_video_universe,ig_android_exoplayer,ig_android_add_to_last_post,ig_android_ad_remove_cta_chevron_universe,ig_android_ad_comment_cta_universe,ig_android_ad_chevron_universe,ig_android_ad_comment_cta_universe,ig_android_search_event_icon,ig_android_channels_home,ig_android_feed,ig_android_dv2_realtime_private_share,ig_android_non_square_first,ig_android_video_interleaved_v2,ig_android_video_cache_policy,ig_android_react_native_universe_kill_switch,ig_android_video_captions_universe,ig_android_follow_search_bar,ig_android_last_edits,ig_android_two_step_capture_flow,ig_android_video_download_logging,ig_android_share_link_to_whatsapp,ig_android_facebook_twitter_profile_photos,ig_android_swipeable_filters_blacklist,ig_android_ad_pbia_profile_tap_universe,ig_android_use_software_layer_for_kc_drawing_universe,ig_android_react_native_ota,ig_android_direct_mutually_exclusive_experiment_universe,ig_android_following_follower_social_context'
LOGIN_EXPERIMENTS = 'ig_android_reg_login_btn_active_state,ig_android_ci_opt_in_at_reg,ig_android_one_click_in_old_flow,ig_android_merge_fb_and_ci_friends_page,ig_android_non_fb_sso,ig_android_mandatory_full_name,ig_android_reg_enable_login_password_btn,ig_android_reg_phone_email_active_state,ig_android_analytics_data_loss,ig_fbns_blocked,ig_android_contact_point_triage,ig_android_reg_next_btn_active_state,ig_android_prefill_phone_number,ig_android_show_fb_social_context_in_nux,ig_android_one_tap_login_upsell,ig_fbns_push,ig_android_phoneid_sync_interval'
SIG_KEY_VERSION = '4'
ANDROID_VERSION = 18
ANDROID_RELEASE = '4.3'
| class Constants(object):
"""
Constant declarations.
"""
api_url = 'https://i.instagram.com/api/v1/'
version = '9.2.0'
ig_sig_key = '012a54f51c49aa8c5c322416ab1410909add32c966bbaa0fe3dc58ac43fd7ede'
experiments = 'ig_android_ad_holdout_16m5_universe,ig_android_progressive_jpeg,ig_creation_growth_holdout,ig_android_oppo_app_badging,ig_android_ad_remove_username_from_caption_universe,ig_android_enable_share_to_whatsapp,ig_android_direct_drawing_in_quick_cam_universe,ig_android_ad_always_send_ad_attribution_id_universe,ig_android_universe_video_production,ig_android_direct_plus_button,ig_android_ads_heatmap_overlay_universe,ig_android_http_stack_experiment_2016,ig_android_infinite_scrolling,ig_fbns_blocked,ig_android_post_auto_retry_v7_21,ig_fbns_push,ig_android_video_playback_bandwidth_threshold,ig_android_direct_link_preview,ig_android_direct_typing_indicator,ig_android_preview_capture,ig_android_feed_pill,ig_android_profile_link_iab,ig_android_story_caption,ig_android_network_cancellation,ig_android_histogram_reporter,ig_android_anrwatchdog,ig_android_search_client_matching,ig_android_follow_request_text_buttons,ig_android_feed_zoom,ig_android_drafts_universe,ig_android_disable_comment,ig_android_user_detail_endpoint,ig_android_os_version_blocking,ig_android_blocked_list,ig_android_event_creation,ig_android_high_res_upload_2,ig_android_2fac,ig_android_mark_reel_seen_on_Swipe_forward,ig_android_comment_redesign,ig_android_ad_sponsored_label_universe,ig_android_mentions_dismiss_rule,ig_android_disable_chroma_subsampling,ig_android_share_spinner,ig_android_video_reuse_surface,ig_explore_v3_android_universe,ig_android_media_favorites,ig_android_nux_holdout,ig_android_insta_video_universe,ig_android_search_null_state,ig_android_universe_reel_video_production,liger_instagram_android_univ,ig_android_direct_emoji_picker,ig_feed_holdout_universe,ig_android_direct_send_auto_retry_universe,ig_android_samsung_app_badging,ig_android_disk_usage,ig_android_business_promotion,ig_android_direct_swipe_to_inbox,ig_android_feed_reshare_button_nux,ig_android_react_native_boost_post,ig_android_boomerang_feed_attribution,ig_fbns_shared,ig_fbns_dump_ids,ig_android_react_native_universe,ig_show_promote_button_in_feed,ig_android_ad_metadata_behavior_universe,ig_android_video_loopcount_int,ig_android_inline_gallery_backoff_hours_universe,ig_android_rendering_controls,ig_android_profile_photo_as_media,ig_android_async_stack_image_cache,ig_video_max_duration_qe_preuniverse,ig_video_copyright_whitelist,ig_android_render_stories_with_content_override,ig_android_ad_intent_to_highlight_universe,ig_android_swipe_navigation_x_angle_universe,ig_android_disable_comment_public_test,ig_android_profile,ig_android_direct_blue_tab,ig_android_enable_share_to_messenger,ig_android_fetch_reel_tray_on_resume_universe,ig_android_promote_again,ig_feed_event_landing_page_channel,ig_ranking_following,ig_android_pending_request_search_bar,ig_android_feed_ufi_redesign,ig_android_pending_edits_dialog_universe,ig_android_business_conversion_flow_universe,ig_android_show_your_story_when_empty_universe,ig_android_ad_drop_cookie_early,ig_android_app_start_config,ig_android_fix_ise_two_phase,ig_android_ppage_toggle_universe,ig_android_pbia_normal_weight_universe,ig_android_profanity_filter,ig_ios_su_activity_feed,ig_android_search,ig_android_boomerang_entry,ig_android_mute_story,ig_android_inline_gallery_universe,ig_android_ad_remove_one_tap_indicator_universe,ig_android_view_count_decouple_likes_universe,ig_android_contact_button_redesign_v2,ig_android_periodic_analytics_upload_v2,ig_android_send_direct_typing_indicator,ig_android_ad_holdout_16h2m1_universe,ig_android_react_native_comment_moderation_settings,ig_video_use_sve_universe,ig_android_inline_gallery_no_backoff_on_launch_universe,ig_android_immersive_viewer,ig_android_discover_people_icon,ig_android_profile_follow_back_button,is_android_feed_seen_state,ig_android_dense_feed_unit_cards,ig_android_drafts_video_universe,ig_android_exoplayer,ig_android_add_to_last_post,ig_android_ad_remove_cta_chevron_universe,ig_android_ad_comment_cta_universe,ig_android_ad_chevron_universe,ig_android_ad_comment_cta_universe,ig_android_search_event_icon,ig_android_channels_home,ig_android_feed,ig_android_dv2_realtime_private_share,ig_android_non_square_first,ig_android_video_interleaved_v2,ig_android_video_cache_policy,ig_android_react_native_universe_kill_switch,ig_android_video_captions_universe,ig_android_follow_search_bar,ig_android_last_edits,ig_android_two_step_capture_flow,ig_android_video_download_logging,ig_android_share_link_to_whatsapp,ig_android_facebook_twitter_profile_photos,ig_android_swipeable_filters_blacklist,ig_android_ad_pbia_profile_tap_universe,ig_android_use_software_layer_for_kc_drawing_universe,ig_android_react_native_ota,ig_android_direct_mutually_exclusive_experiment_universe,ig_android_following_follower_social_context'
login_experiments = 'ig_android_reg_login_btn_active_state,ig_android_ci_opt_in_at_reg,ig_android_one_click_in_old_flow,ig_android_merge_fb_and_ci_friends_page,ig_android_non_fb_sso,ig_android_mandatory_full_name,ig_android_reg_enable_login_password_btn,ig_android_reg_phone_email_active_state,ig_android_analytics_data_loss,ig_fbns_blocked,ig_android_contact_point_triage,ig_android_reg_next_btn_active_state,ig_android_prefill_phone_number,ig_android_show_fb_social_context_in_nux,ig_android_one_tap_login_upsell,ig_fbns_push,ig_android_phoneid_sync_interval'
sig_key_version = '4'
android_version = 18
android_release = '4.3' |
"Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k"
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if not nums or len(nums) == 1:
return False
pairs = dict()
for idx, num in enumerate(nums):
if num in pairs:
if abs(pairs[num] - idx) <= k:
return True
pairs[num] = idx
return False
| """Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k"""
class Solution:
def contains_nearby_duplicate(self, nums: List[int], k: int) -> bool:
if not nums or len(nums) == 1:
return False
pairs = dict()
for (idx, num) in enumerate(nums):
if num in pairs:
if abs(pairs[num] - idx) <= k:
return True
pairs[num] = idx
return False |
class Solution:
def generate(self, numRows: int):
result = []
if not numRows:
return result
for i in range(1, numRows + 1):
temp = [1] * i
lo = 1
hi = i - 2
while lo <= hi:
temp[lo] = temp[hi] = result[i - 2][lo] + result[i - 2][lo - 1]
lo += 1
hi -= 1
result.append(temp)
return result | class Solution:
def generate(self, numRows: int):
result = []
if not numRows:
return result
for i in range(1, numRows + 1):
temp = [1] * i
lo = 1
hi = i - 2
while lo <= hi:
temp[lo] = temp[hi] = result[i - 2][lo] + result[i - 2][lo - 1]
lo += 1
hi -= 1
result.append(temp)
return result |
"""
This problem was asked by Microsoft.
Given an array of numbers, find the length of the longest increasing subsequence in the array.
The subsequence does not necessarily have to be contiguous.
For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],
the longest increasing subsequence has length 6: it is 0, 2, 6, 9, 11, 15.
"""
memo_dict = None
def helper(arr, seq=[], recur_depth = 0):
if len(arr) == 0:
memo_dict[seq[recur_depth]] = seq[recur_depth:]
return seq
longest_seq = []
for i in range(len(arr)):
if arr[i] > seq[-1]:
res = helper(arr[i+1:], seq+[arr[i]], recur_depth+1)
if len(res) >= len(longest_seq):
longest_seq = res
memo_dict[seq[recur_depth]] = longest_seq[recur_depth:]
return longest_seq
def long_subsequence(arr):
longest = []
global memo_dict
memo_dict = {}
for i in range(len(arr)):
if arr[i] in memo_dict:
res = memo_dict[arr[i]]
else:
res = helper(arr[i+1:], [arr[i]])
# print("->>>> res: {}".format(res))
if len(res) > len(longest):
longest = res
return len(longest)
if __name__ == '__main__':
print(long_subsequence([0, 4, 6, 2, 3, 5, 9])) # 5
print(long_subsequence([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])) # 6
print(long_subsequence([11])) # 1
print(long_subsequence([])) # 0 | """
This problem was asked by Microsoft.
Given an array of numbers, find the length of the longest increasing subsequence in the array.
The subsequence does not necessarily have to be contiguous.
For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],
the longest increasing subsequence has length 6: it is 0, 2, 6, 9, 11, 15.
"""
memo_dict = None
def helper(arr, seq=[], recur_depth=0):
if len(arr) == 0:
memo_dict[seq[recur_depth]] = seq[recur_depth:]
return seq
longest_seq = []
for i in range(len(arr)):
if arr[i] > seq[-1]:
res = helper(arr[i + 1:], seq + [arr[i]], recur_depth + 1)
if len(res) >= len(longest_seq):
longest_seq = res
memo_dict[seq[recur_depth]] = longest_seq[recur_depth:]
return longest_seq
def long_subsequence(arr):
longest = []
global memo_dict
memo_dict = {}
for i in range(len(arr)):
if arr[i] in memo_dict:
res = memo_dict[arr[i]]
else:
res = helper(arr[i + 1:], [arr[i]])
if len(res) > len(longest):
longest = res
return len(longest)
if __name__ == '__main__':
print(long_subsequence([0, 4, 6, 2, 3, 5, 9]))
print(long_subsequence([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]))
print(long_subsequence([11]))
print(long_subsequence([])) |
class Empty(Exception):
pass
class LinkedQueue:
"""FIFO queue implkementation using a singly linked list for storage"""
class _Node:
"""Lightweight, nonpublic claass for storing a singly linked node."""
__slots__ = (
"_element",
"_next",
) # streamline memory usage as we expect to have many instances of a node class
def __init__(self, element, next): # Initialize node fields
self._element = element # reference to user's element
self._next = next # reference to next node
def __init__(self) -> None:
self._head = None
self._tail = None
self._size = 0
def __len__(self):
"""Return the number of elements in the queue"""
return self._size
def is_empty(self):
"""Return True if the queue is empty"""
return self._size == 0
def first(self):
"""Return but do not remove the element at the front of the queue"""
if self.is_empty():
raise Empty("Queue is Empty")
return self._head._element
def dequeue(self):
"""Remove and reutrn the first element of the queue
Raise Empty exception if the queue is empty"""
if self.is_empty():
raise Empty("Queue is Empty")
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty(): # special case as queue is empty
self._tail = None # removed head had been the tail
return answer
def enqueue(self, e):
"""Add an element to the back of the queue"""
newest = self._Node(e, None)
if self.is_empty():
self._head = newest
else:
self._tail._next = newest
self._tail = newest
self._size += 1
| class Empty(Exception):
pass
class Linkedqueue:
"""FIFO queue implkementation using a singly linked list for storage"""
class _Node:
"""Lightweight, nonpublic claass for storing a singly linked node."""
__slots__ = ('_element', '_next')
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self) -> None:
self._head = None
self._tail = None
self._size = 0
def __len__(self):
"""Return the number of elements in the queue"""
return self._size
def is_empty(self):
"""Return True if the queue is empty"""
return self._size == 0
def first(self):
"""Return but do not remove the element at the front of the queue"""
if self.is_empty():
raise empty('Queue is Empty')
return self._head._element
def dequeue(self):
"""Remove and reutrn the first element of the queue
Raise Empty exception if the queue is empty"""
if self.is_empty():
raise empty('Queue is Empty')
answer = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty():
self._tail = None
return answer
def enqueue(self, e):
"""Add an element to the back of the queue"""
newest = self._Node(e, None)
if self.is_empty():
self._head = newest
else:
self._tail._next = newest
self._tail = newest
self._size += 1 |
# 1921. Eliminate Maximum Number of Monsters
# You are playing a video game where you are defending your city from a group of n monsters.
# You are given a 0-indexed integer array dist of size n, where dist[i] is the initial
# distance in meters of the ith monster from the city.
# The monsters walk toward the city at a constant speed. The speed of each monster is
# given to you in an integer array speed of size n, where speed[i] is the speed of the
# ith monster in meters per minute.
# The monsters start moving at minute 0. You have a weapon that you can choose to use
# at the start of every minute, including minute 0. You cannot use the weapon in the
# middle of a minute. The weapon can eliminate any monster that is still alive.
# You lose when any monster reaches your city. If a monster reaches the city exactly
# at the start of a minute, it counts as a loss, and the game ends before you can use
# your weapon in that minute.
# Return the maximum number of monsters that you can eliminate before you lose, or n
# if you can eliminate all the monsters before they reach the city.
# Example 1:
# Input: dist = [1,3,4], speed = [1,1,1]
# Output: 3
# Explanation:
# At the start of minute 0, the distances of the monsters are [1,3,4], you eliminate the first monster.
# At the start of minute 1, the distances of the monsters are [X,2,3], you don't do anything.
# At the start of minute 2, the distances of the monsters are [X,1,2], you eliminate the second monster.
# At the start of minute 3, the distances of the monsters are [X,X,1], you eliminate the third monster.
# All 3 monsters can be eliminated.
# Example 2:
# Input: dist = [1,1,2,3], speed = [1,1,1,1]
# Output: 1
# Explanation:
# At the start of minute 0, the distances of the monsters are [1,1,2,3], you eliminate the first monster.
# At the start of minute 1, the distances of the monsters are [X,0,1,2], so you lose.
# You can only eliminate 1 monster.
# Example 3:
# Input: dist = [3,2,4], speed = [5,3,2]
# Output: 1
# Explanation:
# At the start of minute 0, the distances of the monsters are [3,2,4], you eliminate the first monster.
# At the start of minute 1, the distances of the monsters are [X,0,2], so you lose.
# You can only eliminate 1 monster.
# Constraints:
# n == dist.length == speed.length
# 1 <= n <= 105
# 1 <= dist[i], speed[i] <= 105
# Solution
# Sort the monsters by arrival times
# If the moster arrives earlier than we can shoot, then we lost
class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
if not dist or not speed or len(dist) == 0 or len(speed) == 0 or len(dist) != len(speed):
return 0
l = len(speed)
orders = []
for i in range(l):
orders.append([dist[i], speed[i]])
orders.sort(key=lambda x: math.ceil(x[0] / x[1]))
for i in range(l):
if orders[i][0] <= i * orders[i][1]:
# arrive earlier than we can shoot
return i
return l
| class Solution:
def eliminate_maximum(self, dist: List[int], speed: List[int]) -> int:
if not dist or not speed or len(dist) == 0 or (len(speed) == 0) or (len(dist) != len(speed)):
return 0
l = len(speed)
orders = []
for i in range(l):
orders.append([dist[i], speed[i]])
orders.sort(key=lambda x: math.ceil(x[0] / x[1]))
for i in range(l):
if orders[i][0] <= i * orders[i][1]:
return i
return l |
__author__ = 'Chetan'
class Wizard():
def __init__(self, src, rootdir):
self.choices = []
self.rootdir = rootdir
self.src = src
def preferences(self, command):
self.choices.append(command)
def execute(self):
for choice in self.choices:
if list(choice.values())[0]:
print("Copying binaries --", self.src, " to ", self.rootdir)
else:
print("No Operation")
def rollback(self):
print("Deleting the unwanted..", self.rootdir)
if __name__ == '__main__':
## Client code
wizard = Wizard('python3.5.gzip', '/usr/bin/')
## Steps for installation. ## Users chooses to install Python only
wizard.preferences({'python':True})
wizard.preferences({'java':False})
wizard.execute()
| __author__ = 'Chetan'
class Wizard:
def __init__(self, src, rootdir):
self.choices = []
self.rootdir = rootdir
self.src = src
def preferences(self, command):
self.choices.append(command)
def execute(self):
for choice in self.choices:
if list(choice.values())[0]:
print('Copying binaries --', self.src, ' to ', self.rootdir)
else:
print('No Operation')
def rollback(self):
print('Deleting the unwanted..', self.rootdir)
if __name__ == '__main__':
wizard = wizard('python3.5.gzip', '/usr/bin/')
wizard.preferences({'python': True})
wizard.preferences({'java': False})
wizard.execute() |
#######################################################
#
# ManageRacacatPinController.py
# Python implementation of the Class ManageRacacatPinController
# Generated by Enterprise Architect
# Created on: 15-Apr-2020 4:57:23 PM
# Original author: Giu Platania
#
#######################################################
class ManageRacacatPinController:
# default constructor def __init__(self):
pass | class Manageracacatpincontroller:
pass |
N = int(input())
ans = 0
if N < 10 ** 3:
print(0)
elif 10 ** 3 <= N < 10 ** 6:
print(N - 10 ** 3 + 1)
elif 10 ** 6 <= N < 10 ** 9:
print(10 ** 6 - 10 ** 3 + (N - 10 ** 6 + 1)*2)
elif 10 ** 9 <= N < 10 ** 12:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (N - 10 ** 9 + 1)*3)
elif 10 ** 12 <= N < 10 ** 15:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (10 ** 12 - 10 ** 9)*3 + (N - 10 ** 12 + 1)*4)
else:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (10 ** 12 - 10 ** 9)*3 + (10 ** 15 - 10 ** 12)*4 + 5) | n = int(input())
ans = 0
if N < 10 ** 3:
print(0)
elif 10 ** 3 <= N < 10 ** 6:
print(N - 10 ** 3 + 1)
elif 10 ** 6 <= N < 10 ** 9:
print(10 ** 6 - 10 ** 3 + (N - 10 ** 6 + 1) * 2)
elif 10 ** 9 <= N < 10 ** 12:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6) * 2 + (N - 10 ** 9 + 1) * 3)
elif 10 ** 12 <= N < 10 ** 15:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6) * 2 + (10 ** 12 - 10 ** 9) * 3 + (N - 10 ** 12 + 1) * 4)
else:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6) * 2 + (10 ** 12 - 10 ** 9) * 3 + (10 ** 15 - 10 ** 12) * 4 + 5) |
valor = 12
def teste_git(testes):
result = testes ** 33
return result
print(teste_git(valor))
| valor = 12
def teste_git(testes):
result = testes ** 33
return result
print(teste_git(valor)) |
def show_first(word):
print(word[0])
show_first("abc")
| def show_first(word):
print(word[0])
show_first('abc') |
def new_multiplayer(bot, message):
"""
/new_multiplayer command handler
"""
chat_id = message.chat.id
bot.send_message(chat_id=chat_id, text="Not implemented yet") | def new_multiplayer(bot, message):
"""
/new_multiplayer command handler
"""
chat_id = message.chat.id
bot.send_message(chat_id=chat_id, text='Not implemented yet') |
def count_positives_sum_negatives(arr):
if not arr:
return []
positive_array_count = 0
negative_array_count = 0
neither_array = 0
for i in arr:
if i > 0:
positive_array_count = positive_array_count + 1
elif i == 0:
neither_array = neither_array + i
else:
negative_array_count = negative_array_count + i
return [positive_array_count, negative_array_count] | def count_positives_sum_negatives(arr):
if not arr:
return []
positive_array_count = 0
negative_array_count = 0
neither_array = 0
for i in arr:
if i > 0:
positive_array_count = positive_array_count + 1
elif i == 0:
neither_array = neither_array + i
else:
negative_array_count = negative_array_count + i
return [positive_array_count, negative_array_count] |
input_shape = 56, 56, 3
num_class = 80
total_epoches = 50
batch_size = 64
train_num = 11650
val_num = 1254
iterations_per_epoch = train_num // batch_size + 1
test_iterations = val_num // batch_size + 1
weight_decay = 1e-3
label_smoothing = 0.1
'''
numeric characteristics
'''
mean = [154.64720717, 163.98750114, 175.11027269]
std = [88.22176357, 82.46385599, 78.50590683]
# eigval = [18793.85624672, 1592.25590705, 360.43236465]
eigval = [137.09068621, 39.90308142, 18.98505635]
eigvec = [[-0.61372719, -0.62390345, 0.48382169],
[-0.59095847, -0.0433538, -0.80553618],
[-0.52355231, 0.78029798, 0.34209362]]
| input_shape = (56, 56, 3)
num_class = 80
total_epoches = 50
batch_size = 64
train_num = 11650
val_num = 1254
iterations_per_epoch = train_num // batch_size + 1
test_iterations = val_num // batch_size + 1
weight_decay = 0.001
label_smoothing = 0.1
'\nnumeric characteristics\n'
mean = [154.64720717, 163.98750114, 175.11027269]
std = [88.22176357, 82.46385599, 78.50590683]
eigval = [137.09068621, 39.90308142, 18.98505635]
eigvec = [[-0.61372719, -0.62390345, 0.48382169], [-0.59095847, -0.0433538, -0.80553618], [-0.52355231, 0.78029798, 0.34209362]] |
def sort3(a, b, c):
i = []
i.append(a), i.append(b), i.append(c)
i = sorted(i)
return i
a, b, c = input(), input(), input()
print(*sort3(a, b, c))
| def sort3(a, b, c):
i = []
(i.append(a), i.append(b), i.append(c))
i = sorted(i)
return i
(a, b, c) = (input(), input(), input())
print(*sort3(a, b, c)) |
'''
occurrences_dict
loop values:
occurrences_dict[value] += 1
'''
# numbers_string = '-2.5 4 3 -2.5 -5.54 4 3 3 -2.5 3'
# numbers_string = '2 4 4 5 5 2 3 3 4 4 3 3 4 3 5 3 2 5 4 3'
numbers_string = input()
occurrence_counts = {}
# No such thing as tuple comprehension, this is generator
numbers = [float(x) for x in numbers_string.split(' ')]
for number in numbers:
# Not the best solution
# if number in occurrence_counts:
# occurrence_counts[number] += 1
# else:
# occurrence_counts[number] = 1
if number not in occurrence_counts:
occurrence_counts[number] = 0
occurrence_counts[number] += 1
for number, count in occurrence_counts.items():
print(f'{number:.1f} - {count} times')
| """
occurrences_dict
loop values:
occurrences_dict[value] += 1
"""
numbers_string = input()
occurrence_counts = {}
numbers = [float(x) for x in numbers_string.split(' ')]
for number in numbers:
if number not in occurrence_counts:
occurrence_counts[number] = 0
occurrence_counts[number] += 1
for (number, count) in occurrence_counts.items():
print(f'{number:.1f} - {count} times') |
count = 0
total = 0
while True:
Enter = input('Enter a number:\n')
try:
if Enter == "Done":
break
else:
inp = int(Enter)
total = total + inp
count = count + 1
average = total / count
except:
print('Invalid input')
print('Total:', total, 'Count:', count, 'Average:', average)
| count = 0
total = 0
while True:
enter = input('Enter a number:\n')
try:
if Enter == 'Done':
break
else:
inp = int(Enter)
total = total + inp
count = count + 1
average = total / count
except:
print('Invalid input')
print('Total:', total, 'Count:', count, 'Average:', average) |
#
# PySNMP MIB module BEGEMOT-IP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-IP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:03 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")
ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion")
begemot, = mibBuilder.importSymbols("BEGEMOT-MIB", "begemot")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Gauge32, ModuleIdentity, Counter64, Integer32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, MibIdentifier, ObjectIdentity, Unsigned32, Counter32, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "ModuleIdentity", "Counter64", "Integer32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "MibIdentifier", "ObjectIdentity", "Unsigned32", "Counter32", "NotificationType", "TimeTicks")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
begemotIp = ModuleIdentity((1, 3, 6, 1, 4, 1, 12325, 1, 3))
if mibBuilder.loadTexts: begemotIp.setLastUpdated('200602130000Z')
if mibBuilder.loadTexts: begemotIp.setOrganization('German Aerospace Center')
if mibBuilder.loadTexts: begemotIp.setContactInfo(' Hartmut Brandt Postal: German Aerospace Center Oberpfaffenhofen 82234 Wessling Germany Fax: +49 8153 28 2843 E-mail: harti@freebsd.org')
if mibBuilder.loadTexts: begemotIp.setDescription('The MIB for IP stuff that is not in the official IP MIBs.')
begemotIpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 3, 1))
mibBuilder.exportSymbols("BEGEMOT-IP-MIB", begemotIp=begemotIp, PYSNMP_MODULE_ID=begemotIp, begemotIpObjects=begemotIpObjects)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion')
(begemot,) = mibBuilder.importSymbols('BEGEMOT-MIB', 'begemot')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(iso, gauge32, module_identity, counter64, integer32, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, mib_identifier, object_identity, unsigned32, counter32, notification_type, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Gauge32', 'ModuleIdentity', 'Counter64', 'Integer32', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'MibIdentifier', 'ObjectIdentity', 'Unsigned32', 'Counter32', 'NotificationType', 'TimeTicks')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
begemot_ip = module_identity((1, 3, 6, 1, 4, 1, 12325, 1, 3))
if mibBuilder.loadTexts:
begemotIp.setLastUpdated('200602130000Z')
if mibBuilder.loadTexts:
begemotIp.setOrganization('German Aerospace Center')
if mibBuilder.loadTexts:
begemotIp.setContactInfo(' Hartmut Brandt Postal: German Aerospace Center Oberpfaffenhofen 82234 Wessling Germany Fax: +49 8153 28 2843 E-mail: harti@freebsd.org')
if mibBuilder.loadTexts:
begemotIp.setDescription('The MIB for IP stuff that is not in the official IP MIBs.')
begemot_ip_objects = mib_identifier((1, 3, 6, 1, 4, 1, 12325, 1, 3, 1))
mibBuilder.exportSymbols('BEGEMOT-IP-MIB', begemotIp=begemotIp, PYSNMP_MODULE_ID=begemotIp, begemotIpObjects=begemotIpObjects) |
SECRET_KEY = 'fake-key-here'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'data_ingest',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
ROOT_URLCONF = 'data_ingest.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'test_data_ingest',
'USER': 'postgres',
'PASSWORD': 'test_data_password',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Rest Framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated', )
}
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
| secret_key = 'fake-key-here'
installed_apps = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'data_ingest']
middleware = ['django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware']
root_urlconf = 'data_ingest.urls'
templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'context_processors': ['django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages']}}]
databases = {'default': {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_data_ingest', 'USER': 'postgres', 'PASSWORD': 'test_data_password', 'HOST': 'localhost', 'PORT': '5432'}}
rest_framework = {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',)}
language_code = 'en-us'
time_zone = 'UTC'
use_i18_n = True
use_l10_n = True
use_tz = True |
# RUN: test-parser.sh %s
# RUN: test-output.sh %s
x = 1 # PARSER-LABEL:x = 1i
y = 2 # PARSER-NEXT:y = 2i
print("Start") # PARSER-NEXT:print("Start")
# OUTPUT-LABEL: Start
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if (y == 3i):
print("A") # PARSER-NEXT: print("A")
else: # PARSER-NEXT:else:
print("C") # PARSER-NEXT: print("C")
print("D") # PARSER-NEXT:print("D")
# OUTPUT-NEXT: D
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if (y == 3i):
print("A") # PARSER-NEXT: print("A")
else: # PARSER-NEXT: else:
print("B") # PARSER-NEXT: print("B")
else: # PARSER-NEXT:else:
print("C") # PARSER-NEXT: print("C")
print("D") # PARSER-NEXT:print("D")
# OUTPUT-NEXT: B
# OUTPUT-NEXT: D
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if (y == 3i):
print("A") # PARSER-NEXT: print("A")
else: # PARSER-NEXT: else:
print("B") # PARSER-NEXT: print("B")
print("D") # PARSER-NEXT:print("D")
# OUTPUT-NEXT: B
# OUTPUT-NEXT: D
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if (y == 3i):
print("A") # PARSER-NEXT: print("A")
else: # PARSER-NEXT: else:
print("X") # PARSER-NEXT: print("X")
if y == 2: # PARSER-NEXT: if (y == 2i):
print("B") # PARSER-NEXT: print("B")
else: # PARSER-NEXT: else:
print("E") # PARSER-NEXT: print("E")
else: # PARSER-NEXT:else:
print("C") # PARSER-NEXT: print("C")
print("D") # PARSER-NEXT:print("D")
# OUTPUT-NEXT: X
# OUTPUT-NEXT: B
# OUTPUT-NEXT: D
| x = 1
y = 2
print('Start')
if x == 1:
if y == 3:
print('A')
else:
print('C')
print('D')
if x == 1:
if y == 3:
print('A')
else:
print('B')
else:
print('C')
print('D')
if x == 1:
if y == 3:
print('A')
else:
print('B')
print('D')
if x == 1:
if y == 3:
print('A')
else:
print('X')
if y == 2:
print('B')
else:
print('E')
else:
print('C')
print('D') |
class CameraNotConnected(Exception):
pass
class WiredControlAlreadyEstablished(Exception):
pass
| class Cameranotconnected(Exception):
pass
class Wiredcontrolalreadyestablished(Exception):
pass |
"""
Project Euler: Problem #002
"""
def solve(lim = 4 * 1000 * 1000):
"""
Naive solution with a function.
:param lim: Max number to sum up to.
:returns: The sum of the even Fibo-numbers.
"""
a, b = 0, 1
sum = 0
while b < lim:
if not b % 2:
sum += b
a, b = b, a + b # <-- tuple assignment to avoid tmp var
return sum
def solve_alt(lim):
"""
Alternative solution using a generator.
**Note**: Must sum over the generator at the end.
:param lim: Max number to sum up to.
:returns: The sum of the odd Fibo-numbers.
"""
def numGen(lim):
a, b = 0, 1
while b < lim:
if not b % 2:
yield b # <-- generator
a, b = b, a + b # <-- tuple assignment to avoid tmp var
return sum(numGen(lim))
if __name__ == '__main__':
print("Check: {}".format(eu002(100))) | """
Project Euler: Problem #002
"""
def solve(lim=4 * 1000 * 1000):
"""
Naive solution with a function.
:param lim: Max number to sum up to.
:returns: The sum of the even Fibo-numbers.
"""
(a, b) = (0, 1)
sum = 0
while b < lim:
if not b % 2:
sum += b
(a, b) = (b, a + b)
return sum
def solve_alt(lim):
"""
Alternative solution using a generator.
**Note**: Must sum over the generator at the end.
:param lim: Max number to sum up to.
:returns: The sum of the odd Fibo-numbers.
"""
def num_gen(lim):
(a, b) = (0, 1)
while b < lim:
if not b % 2:
yield b
(a, b) = (b, a + b)
return sum(num_gen(lim))
if __name__ == '__main__':
print('Check: {}'.format(eu002(100))) |
# https://codeforces.com/problemset/problem/116/A
n = int(input())
stops = [list(map(int, input().split())) for _ in range(n)]
p, peak_p = 0, 0
for stop in stops:
p -= stop[0]
p += stop[1]
peak_p = max(p, peak_p)
print(peak_p) | n = int(input())
stops = [list(map(int, input().split())) for _ in range(n)]
(p, peak_p) = (0, 0)
for stop in stops:
p -= stop[0]
p += stop[1]
peak_p = max(p, peak_p)
print(peak_p) |
def int_to_char(word):
arr = list(word)
num_str = ""
while True:
if not arr[0].isdigit():
break
num_str += arr[0]
arr.pop(0)
num = int(num_str)
arr.insert(0, chr(num))
return "".join(arr)
def switch_letters(word):
list_chars = list(word)
list_chars[1], list_chars[-1] = list_chars[-1], list_chars[1]
return "".join(list_chars)
def decrypt_word(word):
word = int_to_char(word)
word = switch_letters(word)
return word
words = input().split()
words = [decrypt_word(word) for word in words]
print(" ".join(words))
| def int_to_char(word):
arr = list(word)
num_str = ''
while True:
if not arr[0].isdigit():
break
num_str += arr[0]
arr.pop(0)
num = int(num_str)
arr.insert(0, chr(num))
return ''.join(arr)
def switch_letters(word):
list_chars = list(word)
(list_chars[1], list_chars[-1]) = (list_chars[-1], list_chars[1])
return ''.join(list_chars)
def decrypt_word(word):
word = int_to_char(word)
word = switch_letters(word)
return word
words = input().split()
words = [decrypt_word(word) for word in words]
print(' '.join(words)) |
PROJECT_ID = 'dmp-y-tests'
DATASET_NAME = 'test_gpl'
BUCKET_NAME = 'bucket_gpl'
LOCAL_DIR_PATH = '/tmp/gpl_directory'
| project_id = 'dmp-y-tests'
dataset_name = 'test_gpl'
bucket_name = 'bucket_gpl'
local_dir_path = '/tmp/gpl_directory' |
def commonDiv(num, den, divs = None) :
if not divs : divs = divisors(den)
for i in divs[1:] :
if not num % i : return True
return False
def validNums(den, minNum, maxNum) :
divs = divisors(den)
return [i for i in range(minNum,maxNum+1) if not commonDiv(i, den, divs)]
def countBetween(lowNum, lowDen, highNum, highDen, maxDen) :
total = 0
for i in range(2,maxDen+1) :
minNum = i*lowNum/lowDen+1
maxNum = (i*highNum-1)/highDen
nums = validNums(i, minNum, maxNum)
total += len(nums)
#print "%d -> %d to %d (%s) %d" % (i, minNum, maxNum, ','.join([str(i) for i in nums]), total)
return total
countBetween(1, 3, 1, 2, 12000)
| def common_div(num, den, divs=None):
if not divs:
divs = divisors(den)
for i in divs[1:]:
if not num % i:
return True
return False
def valid_nums(den, minNum, maxNum):
divs = divisors(den)
return [i for i in range(minNum, maxNum + 1) if not common_div(i, den, divs)]
def count_between(lowNum, lowDen, highNum, highDen, maxDen):
total = 0
for i in range(2, maxDen + 1):
min_num = i * lowNum / lowDen + 1
max_num = (i * highNum - 1) / highDen
nums = valid_nums(i, minNum, maxNum)
total += len(nums)
return total
count_between(1, 3, 1, 2, 12000) |
# Exception Handling function
def exception_handling(number1, number2, operator):
# Only digit exception
try:
int(number1)
except:
return "Error: Numbers must only contain digits."
try:
int(number2)
except:
return "Error: Numbers must only contain digits."
# More than 4 digit no. exception
try:
if len(number1) > 4 or len(number2) > 4:
raise BaseException
except:
return "Error: Numbers cannot be more than four digits."
# Operator must be + | - exception.
try:
if operator != '+' and operator != '-':
raise BaseException
except:
return "Error: Operator must be '+' or '-'."
return ""
def arithmetic_arranger(problems, displayMode=False):
start = True
side_space = " "
line1 = line2 = line3 = line4 = ""
# Too many Problem exception
try:
if len(problems) > 5:
raise BaseException
except:
return "Error: Too many problems."
for prob in problems:
# Splitting the Problem into separate strings
separated_problem = prob.split()
# storing number 1
number1 = separated_problem[0]
# Storing the operator sign
operator = separated_problem[1]
# storing number 2
number2 = separated_problem[2]
exp = exception_handling(number1, number2, operator)
if exp != "":
return exp
no1 = int(number1)
no2 = int(number2)
# space contains the max no. os spaces required.
space = max(len(number1), len(number2))
# For first arithmetic arragement
if start == True:
line1 += number1.rjust(space + 2)
line2 += operator + ' ' + number2.rjust(space)
line3 += '-' * (space + 2)
if displayMode == True:
if operator == '+':
line4 += str(no1 + no2).rjust(space + 2)
else:
line4 += str(no1 - no2).rjust(space + 2)
start = False
# Other than first arithmetic arragement
else:
line1 += number1.rjust(space + 6)
line2 += operator.rjust(5) + ' ' + number2.rjust(space)
line3 += side_space + '-' * (space + 2)
if displayMode == True:
if operator == '+':
line4 += side_space + str(no1 + no2).rjust(space + 2)
else:
line4 += side_space + str(no1 - no2).rjust(space + 2)
# displayMode is Ture then append line4
if displayMode == True:
return line1 + '\n' + line2 + '\n' + line3 + '\n' + line4
return line1 + '\n' + line2 + '\n' + line3
| def exception_handling(number1, number2, operator):
try:
int(number1)
except:
return 'Error: Numbers must only contain digits.'
try:
int(number2)
except:
return 'Error: Numbers must only contain digits.'
try:
if len(number1) > 4 or len(number2) > 4:
raise BaseException
except:
return 'Error: Numbers cannot be more than four digits.'
try:
if operator != '+' and operator != '-':
raise BaseException
except:
return "Error: Operator must be '+' or '-'."
return ''
def arithmetic_arranger(problems, displayMode=False):
start = True
side_space = ' '
line1 = line2 = line3 = line4 = ''
try:
if len(problems) > 5:
raise BaseException
except:
return 'Error: Too many problems.'
for prob in problems:
separated_problem = prob.split()
number1 = separated_problem[0]
operator = separated_problem[1]
number2 = separated_problem[2]
exp = exception_handling(number1, number2, operator)
if exp != '':
return exp
no1 = int(number1)
no2 = int(number2)
space = max(len(number1), len(number2))
if start == True:
line1 += number1.rjust(space + 2)
line2 += operator + ' ' + number2.rjust(space)
line3 += '-' * (space + 2)
if displayMode == True:
if operator == '+':
line4 += str(no1 + no2).rjust(space + 2)
else:
line4 += str(no1 - no2).rjust(space + 2)
start = False
else:
line1 += number1.rjust(space + 6)
line2 += operator.rjust(5) + ' ' + number2.rjust(space)
line3 += side_space + '-' * (space + 2)
if displayMode == True:
if operator == '+':
line4 += side_space + str(no1 + no2).rjust(space + 2)
else:
line4 += side_space + str(no1 - no2).rjust(space + 2)
if displayMode == True:
return line1 + '\n' + line2 + '\n' + line3 + '\n' + line4
return line1 + '\n' + line2 + '\n' + line3 |
TWITTER_TAGS = [
"agdq2021",
"gamesdonequick.com",
"agdq",
"sgdq",
"gamesdonequick",
"awesome games done quick",
"games done quick",
"summer games done quick",
"gdq",
]
TWITCH_CHANNEL = "gamesdonequick"
TWITCH_HOST = "irc.twitch.tv"
TWITCH_PORT = 6667
# Update this value to change the current event:
EVENT_SHORTHAND = "AGDQ2021"
# The following should stay pretty stable between events
DONATION_URL = (
"https://gamesdonequick.com/tracker/event/{}".format(EVENT_SHORTHAND)
)
SCHEDULE_URL = "https://gamesdonequick.com/schedule"
DONATION_INDEX_URL = (
"https://gamesdonequick.com/tracker/donations/{}".format(EVENT_SHORTHAND)
)
DONATION_DETAIL_URL = "https://gamesdonequick.com/tracker/donation"
DONOR_URL = "https://gamesdonequick.com/tracker/donor"
| twitter_tags = ['agdq2021', 'gamesdonequick.com', 'agdq', 'sgdq', 'gamesdonequick', 'awesome games done quick', 'games done quick', 'summer games done quick', 'gdq']
twitch_channel = 'gamesdonequick'
twitch_host = 'irc.twitch.tv'
twitch_port = 6667
event_shorthand = 'AGDQ2021'
donation_url = 'https://gamesdonequick.com/tracker/event/{}'.format(EVENT_SHORTHAND)
schedule_url = 'https://gamesdonequick.com/schedule'
donation_index_url = 'https://gamesdonequick.com/tracker/donations/{}'.format(EVENT_SHORTHAND)
donation_detail_url = 'https://gamesdonequick.com/tracker/donation'
donor_url = 'https://gamesdonequick.com/tracker/donor' |
'''
Problem : Find out duplicate number between 1 to N numbers.
- Find array sum
- Subtract sum of First (n-1) natural numbers from it to find the result.
Author : Alok Tripathi
'''
# Method to find duplicate in array
def findDuplicate(arr, n):
return sum(arr) - (((n - 1) * n) // 2) #it will return int not float
# Driver method
if __name__ == "__main__":
arr = [1, 2, 3, 3, 4]
n = len(arr)
print(findDuplicate(arr, n))
| """
Problem : Find out duplicate number between 1 to N numbers.
- Find array sum
- Subtract sum of First (n-1) natural numbers from it to find the result.
Author : Alok Tripathi
"""
def find_duplicate(arr, n):
return sum(arr) - (n - 1) * n // 2
if __name__ == '__main__':
arr = [1, 2, 3, 3, 4]
n = len(arr)
print(find_duplicate(arr, n)) |
def get_score(player_deck):
score_sum=0
for i in player_deck:
try:
score_sum+=int(i[1])
except:
if i[1] in ['K', 'Q', 'J']:
score_sum+=10
if i[1]=='Ace':
if (score_sum+11)<=21:
score_sum+=11
else:
score_sum+=1
return score_sum | def get_score(player_deck):
score_sum = 0
for i in player_deck:
try:
score_sum += int(i[1])
except:
if i[1] in ['K', 'Q', 'J']:
score_sum += 10
if i[1] == 'Ace':
if score_sum + 11 <= 21:
score_sum += 11
else:
score_sum += 1
return score_sum |
def ok(msg):
"""OK message
:msg: TODO
:returns: TODO
"""
return {"message": str(msg)}
def err(msg):
"""Error message
:msg: TODO
:returns: TODO
"""
return {"error": str(msg)}
| def ok(msg):
"""OK message
:msg: TODO
:returns: TODO
"""
return {'message': str(msg)}
def err(msg):
"""Error message
:msg: TODO
:returns: TODO
"""
return {'error': str(msg)} |
#MenuTitle: Count Layer and Edit Note
# -*- coding: utf-8 -*-
# Edit by Tanukizamurai
__doc__="""
Count glyphs layers and add value to glyphs note.
"""
font = Glyphs.font
selectedLayers = font.selectedLayers
for thisLayer in selectedLayers:
thisGlyph = thisLayer.parent
layerCount = len(thisLayer.parent.layers) #count layer
glyphName = thisLayer.parent.name
glyphNote = thisGlyph.note
if glyphNote is None:
glyphNote = ''
splitNote = glyphNote.split()
splitNote.insert(0, 'layercount:' + str(layerCount) + ' ') #insert at head of note
finalNote = ' '.join(splitNote)
thisGlyph.note = finalNote #update note
print('add_note glyph:' + glyphName + ' ' + finalNote)
| __doc__ = '\nCount glyphs layers and add value to glyphs note.\n'
font = Glyphs.font
selected_layers = font.selectedLayers
for this_layer in selectedLayers:
this_glyph = thisLayer.parent
layer_count = len(thisLayer.parent.layers)
glyph_name = thisLayer.parent.name
glyph_note = thisGlyph.note
if glyphNote is None:
glyph_note = ''
split_note = glyphNote.split()
splitNote.insert(0, 'layercount:' + str(layerCount) + ' ')
final_note = ' '.join(splitNote)
thisGlyph.note = finalNote
print('add_note glyph:' + glyphName + ' ' + finalNote) |
class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
files = path.split('/')
stack = list()
for f in files:
if len(f) == 0 or f == '.':
continue
elif f == '..':
if len(stack):
stack.pop()
else:
continue
else:
stack.append(f)
return '/'+'/'.join(stack) | class Solution:
def simplify_path(self, path):
"""
:type path: str
:rtype: str
"""
files = path.split('/')
stack = list()
for f in files:
if len(f) == 0 or f == '.':
continue
elif f == '..':
if len(stack):
stack.pop()
else:
continue
else:
stack.append(f)
return '/' + '/'.join(stack) |
# coding: utf-8
n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
if i < n-1 and a[i+1]<a[i]:
break
if i==n-1:
ans = 0
else:
ans = n-1-i
a = a[i+1:]+a[:i+1]
for i in range(n-1):
if a[i] > a[i+1]:
print(-1)
break
else:
print(ans)
| n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
if i < n - 1 and a[i + 1] < a[i]:
break
if i == n - 1:
ans = 0
else:
ans = n - 1 - i
a = a[i + 1:] + a[:i + 1]
for i in range(n - 1):
if a[i] > a[i + 1]:
print(-1)
break
else:
print(ans) |
# Scrapy settings for dirbot project
SPIDER_MODULES = ['dirbot.spiders']
NEWSPIDER_MODULE = 'dirbot.spiders'
DEFAULT_ITEM_CLASS = 'dirbot.items.Website'
ITEM_PIPELINES = {
'dirbot.pipelines.RequiredFieldsPipeline': 1,
'dirbot.pipelines.FilterWordsPipeline': 2,
'dirbot.pipelines.DbPipeline': 3,
}
# Database settings
DB_API_NAME = 'MySQLdb'
DB_ARGS = {
'host': 'localhost',
'db': 'dirbot',
'user': 'root',
'passwd': '123',
'charset': 'utf8',
'use_unicode': True,
}
| spider_modules = ['dirbot.spiders']
newspider_module = 'dirbot.spiders'
default_item_class = 'dirbot.items.Website'
item_pipelines = {'dirbot.pipelines.RequiredFieldsPipeline': 1, 'dirbot.pipelines.FilterWordsPipeline': 2, 'dirbot.pipelines.DbPipeline': 3}
db_api_name = 'MySQLdb'
db_args = {'host': 'localhost', 'db': 'dirbot', 'user': 'root', 'passwd': '123', 'charset': 'utf8', 'use_unicode': True} |
class Solution:
def getHeight(self, root):
if root is None:
return 0
lh = self.getHeight(root.left) + 1
rh = self.getHeight(root.right) + 1
return max(lh, rh)
def isBalanced(self, root):
if root is None:
return True
leftHeight = self.getHeight(root.left)
rightHeight = self.getHeight(root.right)
return abs(leftHeight - rightHeight) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
'''
Given a sorted array with unique ints, write algo to
create binary search tree with min height
[1,2,3,4,5,6,7], len 7, middle 3
4
2 6
1 3 5 7
[1,2], len 1, middle 0
1
2
[1,2,3], len 2, middle 1
1
2 3
[1,2,3,4], len 3, middle 1
1
2 3
4
'''
# print(arrToBst([]))
# print(arrToBst([1]))
# print(arrToBst([1, 2]))
# print(arrToBst([1, 2, 3]))
# print(arrToBst([1, 2, 3, 4]))
# print(arrToBst([1, 2, 3, 4, 5]))
print("******* In order 1 *******")
# postOrder(root, [])
# preOrder(root, [])
# inOrder(root, [])
| class Solution:
def get_height(self, root):
if root is None:
return 0
lh = self.getHeight(root.left) + 1
rh = self.getHeight(root.right) + 1
return max(lh, rh)
def is_balanced(self, root):
if root is None:
return True
left_height = self.getHeight(root.left)
right_height = self.getHeight(root.right)
return abs(leftHeight - rightHeight) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
'\nGiven a sorted array with unique ints, write algo to\ncreate binary search tree with min height\n\n[1,2,3,4,5,6,7], len 7, middle 3\n 4\n 2 6\n 1 3 5 7\n\n[1,2], len 1, middle 0\n 1\n 2\n\n[1,2,3], len 2, middle 1\n 1\n 2 3\n\n[1,2,3,4], len 3, middle 1\n 1\n 2 3\n 4\n'
print('******* In order 1 *******') |
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
# Dynamic programming, keep track of multiples of ugly 2s, 3s, and 5s
# Quick return
if n <= 0:
return 0
# Create dp array
dp = [1] * n
# Indices to keep track of last 2, 3, 5 multiple of ugly number
idx_2 = idx_3 = idx_5 = 0
# Now loop
for i in range(1, n):
dp[i] = min(dp[idx_2] * 2, dp[idx_3] * 3, dp[idx_5] * 5)
if dp[i] == dp[idx_2] * 2:
idx_2 += 1
if dp[i] == dp[idx_3] * 3:
idx_3 += 1
if dp[i] == dp[idx_5] * 5:
idx_5 += 1
# Return last element in table
return dp[-1] | class Solution(object):
def nth_ugly_number(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 0:
return 0
dp = [1] * n
idx_2 = idx_3 = idx_5 = 0
for i in range(1, n):
dp[i] = min(dp[idx_2] * 2, dp[idx_3] * 3, dp[idx_5] * 5)
if dp[i] == dp[idx_2] * 2:
idx_2 += 1
if dp[i] == dp[idx_3] * 3:
idx_3 += 1
if dp[i] == dp[idx_5] * 5:
idx_5 += 1
return dp[-1] |
# %%
#######################################
def merge_arrays(*lsts: list):
"""Merges all arrays into one flat list.
Examples:
>>> lst_abc = ['a','b','c']\n
>>> lst_123 = [1,2,3]\n
>>> lst_names = ['John','Alice','Bob']\n
>>> merge_arrays(lst_abc,lst_123,lst_names)\n
['a', 'b', 'c', 1, 2, 3, 'John', 'Alice', 'Bob']
"""
merged_list = []
[merged_list.extend(e) for e in lsts]
return merged_list
| def merge_arrays(*lsts: list):
"""Merges all arrays into one flat list.
Examples:
>>> lst_abc = ['a','b','c']
>>> lst_123 = [1,2,3]
>>> lst_names = ['John','Alice','Bob']
>>> merge_arrays(lst_abc,lst_123,lst_names)
['a', 'b', 'c', 1, 2, 3, 'John', 'Alice', 'Bob']
"""
merged_list = []
[merged_list.extend(e) for e in lsts]
return merged_list |
def get_products_of_all_ints_except_at_index(int_list):
if len(int_list) < 2:
raise IndexError('Getting the product of numbers at other '
'indices requires at least 2 numbers')
# We make a list with the length of the input list to
# hold our products
products_of_all_ints_except_at_index = [None] * len(int_list)
# For each integer, we find the product of all the integers
# before it, storing the total product so far each time
product_so_far = 1
for i in range(len(int_list)):
products_of_all_ints_except_at_index[i] = product_so_far
product_so_far *= int_list[i]
# For each integer, we find the product of all the integers
# after it. since each index in products already has the
# product of all the integers before it, now we're storing
# the total product of all other integers
product_so_far = 1
for i in range(len(int_list) - 1, -1, -1):
products_of_all_ints_except_at_index[i] *= product_so_far
product_so_far *= int_list[i]
return products_of_all_ints_except_at_index
| def get_products_of_all_ints_except_at_index(int_list):
if len(int_list) < 2:
raise index_error('Getting the product of numbers at other indices requires at least 2 numbers')
products_of_all_ints_except_at_index = [None] * len(int_list)
product_so_far = 1
for i in range(len(int_list)):
products_of_all_ints_except_at_index[i] = product_so_far
product_so_far *= int_list[i]
product_so_far = 1
for i in range(len(int_list) - 1, -1, -1):
products_of_all_ints_except_at_index[i] *= product_so_far
product_so_far *= int_list[i]
return products_of_all_ints_except_at_index |
count = 0 # A global count variable
def remember():
global count
count += 1 # Count this invocation
print(str(count))
remember()
remember()
remember()
remember()
remember()
| count = 0
def remember():
global count
count += 1
print(str(count))
remember()
remember()
remember()
remember()
remember() |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 17:54:07 2019
@author: SaiLikhithK
"""
def merge_and_count(b,c):
res_arr, inv_count = [], 0
while len(b) > 0 or len(c) > 0:
if len(b) > 0 and len(c) > 0:
if b[0] < c[0]:
res_arr.append(b[0])
b = b[1:]
else:
res_arr.append(c[0])
c = c[1:]
inv_count += len(b)
elif len(b) > 0:
res_arr.append(b[0])
b = b[1:]
elif len(c) > 0:
res_arr.append(c[0])
c = c[1:]
return res_arr, inv_count
def sort_and_count(a):
arr_len = len(a)
if arr_len <= 1:
return a, 0
b,x = sort_and_count(a[:(int)(arr_len/2)])
c,y = sort_and_count(a[(int)(arr_len/2):])
d,z = merge_and_count(b,c)
return d, x+y+z
#Test Cases
t1 = [1,3,5,2,4,6]
print ("Testing using", t1)
print ("Expecting:", 3)
print ("Returned:", sort_and_count(t1)[1])
t2 = [1,5,3,2,4]
print ("\nTesting using", t2)
print ("Expecting:", 4)
print ("Returned:", sort_and_count(t2)[1])
t3 = [5,4,3,2,1]
print ("\nTesting using", t3)
print ("Expecting:", 10)
print ("Returned:", sort_and_count(t3)[1])
t4 = [1,6,3,2,4,5]
print ("\nTesting using", t4)
print ("Expecting:", 5)
print ("Returned:", sort_and_count(t4)[1])
t5 = [1,2,3,4,5,6]
print ("\nTesting using", t5)
print ("Expecting:", 0)
print ("Returned:", sort_and_count(t5)[1])
print ("\n\nFinal run against IntergerArray.txt")
with open('IntegerArray.txt', 'r') as f:
print (sort_and_count([int(l) for l in f])[1]) | """
Created on Sat Nov 16 17:54:07 2019
@author: SaiLikhithK
"""
def merge_and_count(b, c):
(res_arr, inv_count) = ([], 0)
while len(b) > 0 or len(c) > 0:
if len(b) > 0 and len(c) > 0:
if b[0] < c[0]:
res_arr.append(b[0])
b = b[1:]
else:
res_arr.append(c[0])
c = c[1:]
inv_count += len(b)
elif len(b) > 0:
res_arr.append(b[0])
b = b[1:]
elif len(c) > 0:
res_arr.append(c[0])
c = c[1:]
return (res_arr, inv_count)
def sort_and_count(a):
arr_len = len(a)
if arr_len <= 1:
return (a, 0)
(b, x) = sort_and_count(a[:int(arr_len / 2)])
(c, y) = sort_and_count(a[int(arr_len / 2):])
(d, z) = merge_and_count(b, c)
return (d, x + y + z)
t1 = [1, 3, 5, 2, 4, 6]
print('Testing using', t1)
print('Expecting:', 3)
print('Returned:', sort_and_count(t1)[1])
t2 = [1, 5, 3, 2, 4]
print('\nTesting using', t2)
print('Expecting:', 4)
print('Returned:', sort_and_count(t2)[1])
t3 = [5, 4, 3, 2, 1]
print('\nTesting using', t3)
print('Expecting:', 10)
print('Returned:', sort_and_count(t3)[1])
t4 = [1, 6, 3, 2, 4, 5]
print('\nTesting using', t4)
print('Expecting:', 5)
print('Returned:', sort_and_count(t4)[1])
t5 = [1, 2, 3, 4, 5, 6]
print('\nTesting using', t5)
print('Expecting:', 0)
print('Returned:', sort_and_count(t5)[1])
print('\n\nFinal run against IntergerArray.txt')
with open('IntegerArray.txt', 'r') as f:
print(sort_and_count([int(l) for l in f])[1]) |
class IncapBlocked(ValueError):
"""
Base exception for exceptions in this module.
:param response: The response which was being processed when this error was raised.
:type response: requests.Response
:param *args: Additional arguments to pass to :class:`ValueError`.
"""
def __init__(self, response, *args):
self.response = response
super(IncapBlocked, self).__init__(*args)
class MaxRetriesExceeded(IncapBlocked):
"""
Raised when the number attempts to bypass incapsula has exceeded the amount specified.
:param response: The response which was being processed when this error was raised.
:type response: requests.Response
:param *args: Additional arguments to pass to :class:`ValueError`.
"""
pass
class RecaptchaBlocked(IncapBlocked):
"""
Raised when re-captcha is encountered.
:param response: The response which contains the re-captcha.
:type response: requests.Response
:param *args: Additional arguments to pass to :class:`ValueError`.
"""
pass
| class Incapblocked(ValueError):
"""
Base exception for exceptions in this module.
:param response: The response which was being processed when this error was raised.
:type response: requests.Response
:param *args: Additional arguments to pass to :class:`ValueError`.
"""
def __init__(self, response, *args):
self.response = response
super(IncapBlocked, self).__init__(*args)
class Maxretriesexceeded(IncapBlocked):
"""
Raised when the number attempts to bypass incapsula has exceeded the amount specified.
:param response: The response which was being processed when this error was raised.
:type response: requests.Response
:param *args: Additional arguments to pass to :class:`ValueError`.
"""
pass
class Recaptchablocked(IncapBlocked):
"""
Raised when re-captcha is encountered.
:param response: The response which contains the re-captcha.
:type response: requests.Response
:param *args: Additional arguments to pass to :class:`ValueError`.
"""
pass |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: median.py
@time: 2019/6/15 14:18
@desc:
'''
class Solution:
"""
@param A: An integer array.
@param B: An integer array.
@return: a double whose format is *.5 or *.0
"""
def findMedianSortedArrays(self, A, B):
m, n = len(A), len(B)
if m == 0 and n == 0:
return 0.0
total = m + n
if total % 2 == 1:
return self.kth_largest(A, B, total // 2 + 1) * 1.0
else:
# a = self.kth_largest(A, B, total // 2)
# b = self.kth_largest(A, B, total // 2 + 1)
a, b = self.kth_largest_two(A, B, total // 2)
return (a + b) / 2.0
def kth_largest(self, A, B, kth):
m, n = len(A), len(B)
if m == 0:
return B[kth-1]
if n == 0:
return A[kth-1]
if kth == 1:
return min(A[0], B[0])
mid = kth // 2
a, b = float("inf"), float("inf")
if m >= mid:
a = A[mid - 1]
if n >= mid:
b = B[mid - 1]
if a < b:
return self.kth_largest(A[mid:], B, kth - mid)
else:
return self.kth_largest(A, B[mid:], kth - mid)
def kth_largest_two(self, A, B, kth):
m, n = len(A), len(B)
if m == 0:
return B[kth-1], B[kth]
if n == 0:
return A[kth-1], A[kth]
if kth == 1:
if A[0] <= B[0]:
a = A[0]
b = min(A[1], B[0]) if m >= 2 else B[0]
else:
a = B[0]
b = min(A[0], B[1]) if n >= 2 else A[0]
return a, b
mid = kth // 2
a, b = float("inf"), float("inf")
if m >= mid:
a = A[mid - 1]
if n >= mid:
b = B[mid - 1]
if a < b:
return self.kth_largest_two(A[mid:], B, kth - mid)
else:
return self.kth_largest_two(A, B[mid:], kth - mid)
if __name__ == '__main__':
a = [1,2,3]
b = [4,5,6,7,8,9,10,11,12,13,14,15,16]
res = Solution()
c = res.findMedianSortedArrays(a, b)
print(c) | """
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: median.py
@time: 2019/6/15 14:18
@desc:
"""
class Solution:
"""
@param A: An integer array.
@param B: An integer array.
@return: a double whose format is *.5 or *.0
"""
def find_median_sorted_arrays(self, A, B):
(m, n) = (len(A), len(B))
if m == 0 and n == 0:
return 0.0
total = m + n
if total % 2 == 1:
return self.kth_largest(A, B, total // 2 + 1) * 1.0
else:
(a, b) = self.kth_largest_two(A, B, total // 2)
return (a + b) / 2.0
def kth_largest(self, A, B, kth):
(m, n) = (len(A), len(B))
if m == 0:
return B[kth - 1]
if n == 0:
return A[kth - 1]
if kth == 1:
return min(A[0], B[0])
mid = kth // 2
(a, b) = (float('inf'), float('inf'))
if m >= mid:
a = A[mid - 1]
if n >= mid:
b = B[mid - 1]
if a < b:
return self.kth_largest(A[mid:], B, kth - mid)
else:
return self.kth_largest(A, B[mid:], kth - mid)
def kth_largest_two(self, A, B, kth):
(m, n) = (len(A), len(B))
if m == 0:
return (B[kth - 1], B[kth])
if n == 0:
return (A[kth - 1], A[kth])
if kth == 1:
if A[0] <= B[0]:
a = A[0]
b = min(A[1], B[0]) if m >= 2 else B[0]
else:
a = B[0]
b = min(A[0], B[1]) if n >= 2 else A[0]
return (a, b)
mid = kth // 2
(a, b) = (float('inf'), float('inf'))
if m >= mid:
a = A[mid - 1]
if n >= mid:
b = B[mid - 1]
if a < b:
return self.kth_largest_two(A[mid:], B, kth - mid)
else:
return self.kth_largest_two(A, B[mid:], kth - mid)
if __name__ == '__main__':
a = [1, 2, 3]
b = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
res = solution()
c = res.findMedianSortedArrays(a, b)
print(c) |
def find_rc(rc):
rc = rc[:: -1]
replacements = {"A": "T",
"T": "A",
"G": "C",
"C": "G"}
rc = "".join([replacements.get(c, c) for c in rc])
return rc
print(find_rc('ATTA'))
| def find_rc(rc):
rc = rc[::-1]
replacements = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
rc = ''.join([replacements.get(c, c) for c in rc])
return rc
print(find_rc('ATTA')) |
"""Configuration settings for baseball team manager program."""
# The starting players list of lists
players = [
['Joe', 'P', 10, 2, 0.2],
['Tom', 'SS', 11, 4, 0.364],
['Ben', '3B', 0, 0, 0.0],
]
# valid baseball team positions
valid_positions = ('C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF', 'P') | """Configuration settings for baseball team manager program."""
players = [['Joe', 'P', 10, 2, 0.2], ['Tom', 'SS', 11, 4, 0.364], ['Ben', '3B', 0, 0, 0.0]]
valid_positions = ('C', '1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF', 'P') |
first_name = input("Please enter your first name: ")
print(f"Your first name is: {first_name}")
print("a regular string: " + first_name)
print('a regular string' + first_name)
# string literal with the r prefix
print(r'a regular string')
| first_name = input('Please enter your first name: ')
print(f'Your first name is: {first_name}')
print('a regular string: ' + first_name)
print('a regular string' + first_name)
print('a regular string') |
"""
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
"""
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
return self.search_1(A, target)
def search_1(self, A, target):
start = 0
end = len(A) - 1
while start + 1 < end:
mid = (start + end) / 2
if target == A[mid]:
return mid
if A[start] < A[mid]: # First half sorted
if A[start] <= target < A[mid]: # In first half
end = mid
else: # In second half
start = mid
else: # Second half sorted
if A[mid] < target <= A[end]: # In second half
start = mid
else:
end = mid
if A[start] == target:
return start
if A[end] == target:
return end
return -1
# Switching to NC way, use start+1 < end instead
def search_rec(self, A, target):
return self.search_helper(A, target, 0, len(A) - 1)
def search_helper(self, A, target, start, end):
if start > end:
return -1
mid = (start + end) / 2
if A[mid] == target:
return mid
elif A[mid] > A[end]: # First half sorted
if A[start] <= target and target < A[mid]:
return self.search_helper(A, target, start, mid - 1)
else:
return self.search_helper(A, target, mid + 1, end)
else: # Second half sorted
if A[mid] < target and target <= A[end]:
return self.search_helper(A, target, mid + 1, end)
else:
return self.search_helper(A, target, start, mid - 1)
| """
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
"""
class Solution:
def search(self, A, target):
return self.search_1(A, target)
def search_1(self, A, target):
start = 0
end = len(A) - 1
while start + 1 < end:
mid = (start + end) / 2
if target == A[mid]:
return mid
if A[start] < A[mid]:
if A[start] <= target < A[mid]:
end = mid
else:
start = mid
elif A[mid] < target <= A[end]:
start = mid
else:
end = mid
if A[start] == target:
return start
if A[end] == target:
return end
return -1
def search_rec(self, A, target):
return self.search_helper(A, target, 0, len(A) - 1)
def search_helper(self, A, target, start, end):
if start > end:
return -1
mid = (start + end) / 2
if A[mid] == target:
return mid
elif A[mid] > A[end]:
if A[start] <= target and target < A[mid]:
return self.search_helper(A, target, start, mid - 1)
else:
return self.search_helper(A, target, mid + 1, end)
elif A[mid] < target and target <= A[end]:
return self.search_helper(A, target, mid + 1, end)
else:
return self.search_helper(A, target, start, mid - 1) |
# A variable lets you save some information to use later
# You can save numbers!
my_var = 1
print(my_var)
# Or strings!
my_var = "MARIO"
print(my_var)
# Or anything else you need! | my_var = 1
print(my_var)
my_var = 'MARIO'
print(my_var) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.