content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Question Link : https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/572/week-4-december-22nd-december-28th/3581/
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
dp = [0] * n
if s[0] != '0':
dp[0] = 1
for i in range(1,n):
if s[i]!='0':
dp[i] += dp[i-1]
if s[i-1]=='1' or (s[i-1]=='2' and int(s[i])<7):
if i-2>0:
dp[i] += dp[i-2]
else:
dp[i]+=1
return dp[-1]
| class Solution(object):
def num_decodings(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
dp = [0] * n
if s[0] != '0':
dp[0] = 1
for i in range(1, n):
if s[i] != '0':
dp[i] += dp[i - 1]
if s[i - 1] == '1' or (s[i - 1] == '2' and int(s[i]) < 7):
if i - 2 > 0:
dp[i] += dp[i - 2]
else:
dp[i] += 1
return dp[-1] |
input = open('input', 'r').read().strip()
input = [list(map(int, r)) for r in input.splitlines()]
h, w = len(input), len(input[0])
def neighbours(x, y):
return [(p, q) for u in range(-1, 2) for v in range(-1, 2)
if 0 <= (p := x+u) < h and 0 <= (q := y+v) < w]
def step(m):
m = [[n+1 for n in r] for r in m]
flashs, bag = set(), {(x, y) for x, r in enumerate(m) for y, n in enumerate(r) if n > 9}
while bag:
flashs |= bag
expansion = set()
for x, y in bag:
for p, q in neighbours(x, y):
if (p, q) in flashs: continue
m[p][q] += 1
expansion.add((p, q))
bag = {(x, y) for x, y in expansion if m[x][y] > 9}
for (x, y) in flashs: m[x][y] = 0
return len(flashs), m
def p1(steps=100):
s, m = 0, input
for _ in range(steps):
f, m = step(m)
s += f
return s
def p2():
i, m = 0, input
while 1:
i += 1
f, m = step(m)
if f == h*w: return i
if (r1 := p1()) is not None: print(r1)
if (r2 := p2()) is not None: print(r2)
| input = open('input', 'r').read().strip()
input = [list(map(int, r)) for r in input.splitlines()]
(h, w) = (len(input), len(input[0]))
def neighbours(x, y):
return [(p, q) for u in range(-1, 2) for v in range(-1, 2) if 0 <= (p := (x + u)) < h and 0 <= (q := (y + v)) < w]
def step(m):
m = [[n + 1 for n in r] for r in m]
(flashs, bag) = (set(), {(x, y) for (x, r) in enumerate(m) for (y, n) in enumerate(r) if n > 9})
while bag:
flashs |= bag
expansion = set()
for (x, y) in bag:
for (p, q) in neighbours(x, y):
if (p, q) in flashs:
continue
m[p][q] += 1
expansion.add((p, q))
bag = {(x, y) for (x, y) in expansion if m[x][y] > 9}
for (x, y) in flashs:
m[x][y] = 0
return (len(flashs), m)
def p1(steps=100):
(s, m) = (0, input)
for _ in range(steps):
(f, m) = step(m)
s += f
return s
def p2():
(i, m) = (0, input)
while 1:
i += 1
(f, m) = step(m)
if f == h * w:
return i
if (r1 := p1()) is not None:
print(r1)
if (r2 := p2()) is not None:
print(r2) |
''' Automatically set `current_app` into context based on URL namespace. '''
def namespaced(request):
''' Set `current_app` to url namespace '''
request.current_app = request.resolver_match.namespace
return {}
| """ Automatically set `current_app` into context based on URL namespace. """
def namespaced(request):
""" Set `current_app` to url namespace """
request.current_app = request.resolver_match.namespace
return {} |
# *-* coding:utf-8 *-*
"""Module states Amapa"""
def start(st_reg_number):
"""Checks the number valiaty for the Alagoas state"""
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
if st_reg_number[0:2] != "03":
return False
aux = int(st_reg_number[0:len(st_reg_number) - 1])
if 3000000 < aux and aux < 3017001:
control1 = 5
control2 = 0
if 3017000 < aux and aux < 3019023:
control1 = 9
control2 = 1
if aux > 3019022:
control1 = 0
control2 = 0
sum_total = 0
peso = 9
for i in range(len(st_reg_number)-1):
sum_total = sum_total + int(st_reg_number[i]) * peso
peso = peso - 1
sum_total += control1
rest_division = sum_total % divisor
digit = divisor - rest_division
if digit == 10:
digit = 0
if digit == 11:
digit = control2
return digit == int(st_reg_number[len(st_reg_number)-1])
| """Module states Amapa"""
def start(st_reg_number):
"""Checks the number valiaty for the Alagoas state"""
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
if st_reg_number[0:2] != '03':
return False
aux = int(st_reg_number[0:len(st_reg_number) - 1])
if 3000000 < aux and aux < 3017001:
control1 = 5
control2 = 0
if 3017000 < aux and aux < 3019023:
control1 = 9
control2 = 1
if aux > 3019022:
control1 = 0
control2 = 0
sum_total = 0
peso = 9
for i in range(len(st_reg_number) - 1):
sum_total = sum_total + int(st_reg_number[i]) * peso
peso = peso - 1
sum_total += control1
rest_division = sum_total % divisor
digit = divisor - rest_division
if digit == 10:
digit = 0
if digit == 11:
digit = control2
return digit == int(st_reg_number[len(st_reg_number) - 1]) |
#!/usr/bin/env python
class AssembleError(Exception):
def __init__(self, line_no, reason):
message = '%d: %s' % (line_no, reason)
super(AssembleError, self).__init__(message)
| class Assembleerror(Exception):
def __init__(self, line_no, reason):
message = '%d: %s' % (line_no, reason)
super(AssembleError, self).__init__(message) |
#Boolean is a Data Type in Python which has 2 values - True and False
print (bool(0)) #Python will return False
print (bool(1)) #Python will return True
print (bool(1.5)) #Pyton will return True
print (bool(None)) #Python will return False
print (bool('')) #Python will return False | print(bool(0))
print(bool(1))
print(bool(1.5))
print(bool(None))
print(bool('')) |
n = int(input())
count = 0
for i in range(1, n + 1):
if i < 100:
count += 1
else:
s = str(i)
if int(s[1]) - int(s[0]) == int(s[2]) - int(s[1]):
count += 1
print(count)
| n = int(input())
count = 0
for i in range(1, n + 1):
if i < 100:
count += 1
else:
s = str(i)
if int(s[1]) - int(s[0]) == int(s[2]) - int(s[1]):
count += 1
print(count) |
l1 = list(range(10))
new_list = [x*x + 2*x + 1 for x in l1]
print(l1)
print(new_list)
| l1 = list(range(10))
new_list = [x * x + 2 * x + 1 for x in l1]
print(l1)
print(new_list) |
class Solution:
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n < 2:
return n
dp_ = [1] * n
for idx, num in enumerate(nums):
for i in range(idx-1, -1, -1):
if nums[i] < nums[idx]:
dp_[idx] = max(dp_[idx], dp_[i]+1)
return max(dp_)
| class Solution:
def length_of_lis(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n < 2:
return n
dp_ = [1] * n
for (idx, num) in enumerate(nums):
for i in range(idx - 1, -1, -1):
if nums[i] < nums[idx]:
dp_[idx] = max(dp_[idx], dp_[i] + 1)
return max(dp_) |
# md5 : 2cdb8e874f0950ea17a7135427b4f07d
# sha1 : 73b16f132eb0247ea124b6243ca4109f179e564c
# sha256 : 099b17422e1df0235e024ff5128a60571e72af451e1c59f4d61d3cf32c1539ed
ord_names = {
3: b'mciExecute',
4: b'CloseDriver',
5: b'DefDriverProc',
6: b'DriverCallback',
7: b'DrvGetModuleHandle',
8: b'GetDriverModuleHandle',
9: b'NotifyCallbackData',
10: b'OpenDriver',
11: b'PlaySound',
12: b'PlaySoundA',
13: b'PlaySoundW',
14: b'SendDriverMessage',
15: b'WOW32DriverCallback',
16: b'WOW32ResolveMultiMediaHandle',
17: b'WOWAppExit',
18: b'aux32Message',
19: b'auxGetDevCapsA',
20: b'auxGetDevCapsW',
21: b'auxGetNumDevs',
22: b'auxGetVolume',
23: b'auxOutMessage',
24: b'auxSetVolume',
25: b'joy32Message',
26: b'joyConfigChanged',
27: b'joyGetDevCapsA',
28: b'joyGetDevCapsW',
29: b'joyGetNumDevs',
30: b'joyGetPos',
31: b'joyGetPosEx',
32: b'joyGetThreshold',
33: b'joyReleaseCapture',
34: b'joySetCapture',
35: b'joySetThreshold',
36: b'mci32Message',
37: b'mciDriverNotify',
38: b'mciDriverYield',
39: b'mciFreeCommandResource',
40: b'mciGetCreatorTask',
41: b'mciGetDeviceIDA',
42: b'mciGetDeviceIDFromElementIDA',
43: b'mciGetDeviceIDFromElementIDW',
44: b'mciGetDeviceIDW',
45: b'mciGetDriverData',
46: b'mciGetErrorStringA',
47: b'mciGetErrorStringW',
48: b'mciGetYieldProc',
49: b'mciLoadCommandResource',
50: b'mciSendCommandA',
51: b'mciSendCommandW',
52: b'mciSendStringA',
53: b'mciSendStringW',
54: b'mciSetDriverData',
55: b'mciSetYieldProc',
56: b'mid32Message',
57: b'midiConnect',
58: b'midiDisconnect',
59: b'midiInAddBuffer',
60: b'midiInClose',
61: b'midiInGetDevCapsA',
62: b'midiInGetDevCapsW',
63: b'midiInGetErrorTextA',
64: b'midiInGetErrorTextW',
65: b'midiInGetID',
66: b'midiInGetNumDevs',
67: b'midiInMessage',
68: b'midiInOpen',
69: b'midiInPrepareHeader',
70: b'midiInReset',
71: b'midiInStart',
72: b'midiInStop',
73: b'midiInUnprepareHeader',
74: b'midiOutCacheDrumPatches',
75: b'midiOutCachePatches',
76: b'midiOutClose',
77: b'midiOutGetDevCapsA',
78: b'midiOutGetDevCapsW',
79: b'midiOutGetErrorTextA',
80: b'midiOutGetErrorTextW',
81: b'midiOutGetID',
82: b'midiOutGetNumDevs',
83: b'midiOutGetVolume',
84: b'midiOutLongMsg',
85: b'midiOutMessage',
86: b'midiOutOpen',
87: b'midiOutPrepareHeader',
88: b'midiOutReset',
89: b'midiOutSetVolume',
90: b'midiOutShortMsg',
91: b'midiOutUnprepareHeader',
92: b'midiStreamClose',
93: b'midiStreamOpen',
94: b'midiStreamOut',
95: b'midiStreamPause',
96: b'midiStreamPosition',
97: b'midiStreamProperty',
98: b'midiStreamRestart',
99: b'midiStreamStop',
100: b'mixerClose',
101: b'mixerGetControlDetailsA',
102: b'mixerGetControlDetailsW',
103: b'mixerGetDevCapsA',
104: b'mixerGetDevCapsW',
105: b'mixerGetID',
106: b'mixerGetLineControlsA',
107: b'mixerGetLineControlsW',
108: b'mixerGetLineInfoA',
109: b'mixerGetLineInfoW',
110: b'mixerGetNumDevs',
111: b'mixerMessage',
112: b'mixerOpen',
113: b'mixerSetControlDetails',
114: b'mmDrvInstall',
115: b'mmGetCurrentTask',
116: b'mmTaskBlock',
117: b'mmTaskCreate',
118: b'mmTaskSignal',
119: b'mmTaskYield',
120: b'mmioAdvance',
121: b'mmioAscend',
122: b'mmioClose',
123: b'mmioCreateChunk',
124: b'mmioDescend',
125: b'mmioFlush',
126: b'mmioGetInfo',
127: b'mmioInstallIOProcA',
128: b'mmioInstallIOProcW',
129: b'mmioOpenA',
130: b'mmioOpenW',
131: b'mmioRead',
132: b'mmioRenameA',
133: b'mmioRenameW',
134: b'mmioSeek',
135: b'mmioSendMessage',
136: b'mmioSetBuffer',
137: b'mmioSetInfo',
138: b'mmioStringToFOURCCA',
139: b'mmioStringToFOURCCW',
140: b'mmioWrite',
141: b'mmsystemGetVersion',
142: b'mod32Message',
143: b'mxd32Message',
144: b'sndPlaySoundA',
145: b'sndPlaySoundW',
146: b'tid32Message',
147: b'timeBeginPeriod',
148: b'timeEndPeriod',
149: b'timeGetDevCaps',
150: b'timeGetSystemTime',
151: b'timeGetTime',
152: b'timeKillEvent',
153: b'timeSetEvent',
154: b'waveInAddBuffer',
155: b'waveInClose',
156: b'waveInGetDevCapsA',
157: b'waveInGetDevCapsW',
158: b'waveInGetErrorTextA',
159: b'waveInGetErrorTextW',
160: b'waveInGetID',
161: b'waveInGetNumDevs',
162: b'waveInGetPosition',
163: b'waveInMessage',
164: b'waveInOpen',
165: b'waveInPrepareHeader',
166: b'waveInReset',
167: b'waveInStart',
168: b'waveInStop',
169: b'waveInUnprepareHeader',
170: b'waveOutBreakLoop',
171: b'waveOutClose',
172: b'waveOutGetDevCapsA',
173: b'waveOutGetDevCapsW',
174: b'waveOutGetErrorTextA',
175: b'waveOutGetErrorTextW',
176: b'waveOutGetID',
177: b'waveOutGetNumDevs',
178: b'waveOutGetPitch',
179: b'waveOutGetPlaybackRate',
180: b'waveOutGetPosition',
181: b'waveOutGetVolume',
182: b'waveOutMessage',
183: b'waveOutOpen',
184: b'waveOutPause',
185: b'waveOutPrepareHeader',
186: b'waveOutReset',
187: b'waveOutRestart',
188: b'waveOutSetPitch',
189: b'waveOutSetPlaybackRate',
190: b'waveOutSetVolume',
191: b'waveOutUnprepareHeader',
192: b'waveOutWrite',
193: b'wid32Message',
194: b'wod32Message',
} | ord_names = {3: b'mciExecute', 4: b'CloseDriver', 5: b'DefDriverProc', 6: b'DriverCallback', 7: b'DrvGetModuleHandle', 8: b'GetDriverModuleHandle', 9: b'NotifyCallbackData', 10: b'OpenDriver', 11: b'PlaySound', 12: b'PlaySoundA', 13: b'PlaySoundW', 14: b'SendDriverMessage', 15: b'WOW32DriverCallback', 16: b'WOW32ResolveMultiMediaHandle', 17: b'WOWAppExit', 18: b'aux32Message', 19: b'auxGetDevCapsA', 20: b'auxGetDevCapsW', 21: b'auxGetNumDevs', 22: b'auxGetVolume', 23: b'auxOutMessage', 24: b'auxSetVolume', 25: b'joy32Message', 26: b'joyConfigChanged', 27: b'joyGetDevCapsA', 28: b'joyGetDevCapsW', 29: b'joyGetNumDevs', 30: b'joyGetPos', 31: b'joyGetPosEx', 32: b'joyGetThreshold', 33: b'joyReleaseCapture', 34: b'joySetCapture', 35: b'joySetThreshold', 36: b'mci32Message', 37: b'mciDriverNotify', 38: b'mciDriverYield', 39: b'mciFreeCommandResource', 40: b'mciGetCreatorTask', 41: b'mciGetDeviceIDA', 42: b'mciGetDeviceIDFromElementIDA', 43: b'mciGetDeviceIDFromElementIDW', 44: b'mciGetDeviceIDW', 45: b'mciGetDriverData', 46: b'mciGetErrorStringA', 47: b'mciGetErrorStringW', 48: b'mciGetYieldProc', 49: b'mciLoadCommandResource', 50: b'mciSendCommandA', 51: b'mciSendCommandW', 52: b'mciSendStringA', 53: b'mciSendStringW', 54: b'mciSetDriverData', 55: b'mciSetYieldProc', 56: b'mid32Message', 57: b'midiConnect', 58: b'midiDisconnect', 59: b'midiInAddBuffer', 60: b'midiInClose', 61: b'midiInGetDevCapsA', 62: b'midiInGetDevCapsW', 63: b'midiInGetErrorTextA', 64: b'midiInGetErrorTextW', 65: b'midiInGetID', 66: b'midiInGetNumDevs', 67: b'midiInMessage', 68: b'midiInOpen', 69: b'midiInPrepareHeader', 70: b'midiInReset', 71: b'midiInStart', 72: b'midiInStop', 73: b'midiInUnprepareHeader', 74: b'midiOutCacheDrumPatches', 75: b'midiOutCachePatches', 76: b'midiOutClose', 77: b'midiOutGetDevCapsA', 78: b'midiOutGetDevCapsW', 79: b'midiOutGetErrorTextA', 80: b'midiOutGetErrorTextW', 81: b'midiOutGetID', 82: b'midiOutGetNumDevs', 83: b'midiOutGetVolume', 84: b'midiOutLongMsg', 85: b'midiOutMessage', 86: b'midiOutOpen', 87: b'midiOutPrepareHeader', 88: b'midiOutReset', 89: b'midiOutSetVolume', 90: b'midiOutShortMsg', 91: b'midiOutUnprepareHeader', 92: b'midiStreamClose', 93: b'midiStreamOpen', 94: b'midiStreamOut', 95: b'midiStreamPause', 96: b'midiStreamPosition', 97: b'midiStreamProperty', 98: b'midiStreamRestart', 99: b'midiStreamStop', 100: b'mixerClose', 101: b'mixerGetControlDetailsA', 102: b'mixerGetControlDetailsW', 103: b'mixerGetDevCapsA', 104: b'mixerGetDevCapsW', 105: b'mixerGetID', 106: b'mixerGetLineControlsA', 107: b'mixerGetLineControlsW', 108: b'mixerGetLineInfoA', 109: b'mixerGetLineInfoW', 110: b'mixerGetNumDevs', 111: b'mixerMessage', 112: b'mixerOpen', 113: b'mixerSetControlDetails', 114: b'mmDrvInstall', 115: b'mmGetCurrentTask', 116: b'mmTaskBlock', 117: b'mmTaskCreate', 118: b'mmTaskSignal', 119: b'mmTaskYield', 120: b'mmioAdvance', 121: b'mmioAscend', 122: b'mmioClose', 123: b'mmioCreateChunk', 124: b'mmioDescend', 125: b'mmioFlush', 126: b'mmioGetInfo', 127: b'mmioInstallIOProcA', 128: b'mmioInstallIOProcW', 129: b'mmioOpenA', 130: b'mmioOpenW', 131: b'mmioRead', 132: b'mmioRenameA', 133: b'mmioRenameW', 134: b'mmioSeek', 135: b'mmioSendMessage', 136: b'mmioSetBuffer', 137: b'mmioSetInfo', 138: b'mmioStringToFOURCCA', 139: b'mmioStringToFOURCCW', 140: b'mmioWrite', 141: b'mmsystemGetVersion', 142: b'mod32Message', 143: b'mxd32Message', 144: b'sndPlaySoundA', 145: b'sndPlaySoundW', 146: b'tid32Message', 147: b'timeBeginPeriod', 148: b'timeEndPeriod', 149: b'timeGetDevCaps', 150: b'timeGetSystemTime', 151: b'timeGetTime', 152: b'timeKillEvent', 153: b'timeSetEvent', 154: b'waveInAddBuffer', 155: b'waveInClose', 156: b'waveInGetDevCapsA', 157: b'waveInGetDevCapsW', 158: b'waveInGetErrorTextA', 159: b'waveInGetErrorTextW', 160: b'waveInGetID', 161: b'waveInGetNumDevs', 162: b'waveInGetPosition', 163: b'waveInMessage', 164: b'waveInOpen', 165: b'waveInPrepareHeader', 166: b'waveInReset', 167: b'waveInStart', 168: b'waveInStop', 169: b'waveInUnprepareHeader', 170: b'waveOutBreakLoop', 171: b'waveOutClose', 172: b'waveOutGetDevCapsA', 173: b'waveOutGetDevCapsW', 174: b'waveOutGetErrorTextA', 175: b'waveOutGetErrorTextW', 176: b'waveOutGetID', 177: b'waveOutGetNumDevs', 178: b'waveOutGetPitch', 179: b'waveOutGetPlaybackRate', 180: b'waveOutGetPosition', 181: b'waveOutGetVolume', 182: b'waveOutMessage', 183: b'waveOutOpen', 184: b'waveOutPause', 185: b'waveOutPrepareHeader', 186: b'waveOutReset', 187: b'waveOutRestart', 188: b'waveOutSetPitch', 189: b'waveOutSetPlaybackRate', 190: b'waveOutSetVolume', 191: b'waveOutUnprepareHeader', 192: b'waveOutWrite', 193: b'wid32Message', 194: b'wod32Message'} |
"""
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
"""
Method:
Defining a slow pointer and a fast pointer
Fast pointer is ahead of the slow pointer by n
When the fast pointer reaches the end, the slow pointer is at end-n-1
Delete the reference to the next node
Your runtime beats 38.08 % of python submissions
"""
# #Defining a slow pointer and a fast pointer
slow_ptr = head
fast_ptr = head
dummy = head
# #Fast pointer is ahead of the slow pointer by n
for _ in range(n):
if fast_ptr.next:
fast_ptr = fast_ptr.next
else:
return dummy.next
# #When the fast pointer reaches the end,
# #the slow pointer is at end-n-1
while fast_ptr and fast_ptr.next:
fast_ptr = fast_ptr.next
slow_ptr = slow_ptr.next
# #Delete the reference to the next node
slow_ptr.next = slow_ptr.next.next
return dummy | """
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
"""
class Solution(object):
def remove_nth_from_end(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
'\n Method:\n Defining a slow pointer and a fast pointer\n Fast pointer is ahead of the slow pointer by n\n When the fast pointer reaches the end, the slow pointer is at end-n-1\n Delete the reference to the next node\n\n Your runtime beats 38.08 % of python submissions\n '
slow_ptr = head
fast_ptr = head
dummy = head
for _ in range(n):
if fast_ptr.next:
fast_ptr = fast_ptr.next
else:
return dummy.next
while fast_ptr and fast_ptr.next:
fast_ptr = fast_ptr.next
slow_ptr = slow_ptr.next
slow_ptr.next = slow_ptr.next.next
return dummy |
dados = int(input())
pontos = input()
pontos = pontos.split(' ')
luisa = 0
antonio = 0
pessoa = 0
for vez in pontos:
pessoa += 1
if pessoa == 3:
pessoa = 1
if pessoa == 1:
luisa += int(vez)
elif pessoa == 2:
antonio += int(vez)
if int(vez) == 6 and pessoa == 1:
pessoa = 0
elif int(vez) == 6 and pessoa == 2:
pessoa = 1
elif pessoa == 2:
pessoa = 0
if luisa > antonio:
print('LUISA {}'.format(luisa))
elif antonio > luisa:
print('ANTONIO {}'.format(antonio))
else:
print('EMPATE {}'.format(antonio)) | dados = int(input())
pontos = input()
pontos = pontos.split(' ')
luisa = 0
antonio = 0
pessoa = 0
for vez in pontos:
pessoa += 1
if pessoa == 3:
pessoa = 1
if pessoa == 1:
luisa += int(vez)
elif pessoa == 2:
antonio += int(vez)
if int(vez) == 6 and pessoa == 1:
pessoa = 0
elif int(vez) == 6 and pessoa == 2:
pessoa = 1
elif pessoa == 2:
pessoa = 0
if luisa > antonio:
print('LUISA {}'.format(luisa))
elif antonio > luisa:
print('ANTONIO {}'.format(antonio))
else:
print('EMPATE {}'.format(antonio)) |
def getCountLetterString(input):
# get range
space_index = input.find(" ")
range = input[0:space_index]
hyphen_index = input.find("-")
start = range[0:hyphen_index]
end = range[hyphen_index + 1:]
# get letter
colon_index = input.find(":")
letter = input[space_index + 1:colon_index]
# get password string
password = input[colon_index + 1:]
# Debug
#print("Range: {} to {}; Letter: {}; Password: {}".format(start, end, letter, password))
return [int(start), int(end), letter, password]
lines = []
with open('./input') as f:
lines = f.read().splitlines()
valid_pass_count = 0
for input in lines:
count_letter_string = getCountLetterString(input)
start = count_letter_string[0]
end = count_letter_string[1]
letter = count_letter_string[2]
password = count_letter_string[3]
first_letter = password[start]
second_letter = password[end]
if first_letter is letter and second_letter is not letter:
valid_pass_count += 1
elif first_letter is not letter and second_letter is letter:
valid_pass_count += 1
print("There are {} valid passwords".format(valid_pass_count))
| def get_count_letter_string(input):
space_index = input.find(' ')
range = input[0:space_index]
hyphen_index = input.find('-')
start = range[0:hyphen_index]
end = range[hyphen_index + 1:]
colon_index = input.find(':')
letter = input[space_index + 1:colon_index]
password = input[colon_index + 1:]
return [int(start), int(end), letter, password]
lines = []
with open('./input') as f:
lines = f.read().splitlines()
valid_pass_count = 0
for input in lines:
count_letter_string = get_count_letter_string(input)
start = count_letter_string[0]
end = count_letter_string[1]
letter = count_letter_string[2]
password = count_letter_string[3]
first_letter = password[start]
second_letter = password[end]
if first_letter is letter and second_letter is not letter:
valid_pass_count += 1
elif first_letter is not letter and second_letter is letter:
valid_pass_count += 1
print('There are {} valid passwords'.format(valid_pass_count)) |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/own_data.py',
'../_base_/schedules/schedule_1x_own_data.py', '../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
load_from = 'https://download.openmmlab.com/mmdetection/v2.0/retinanet/retinanet_r50_fpn_1x_coco/retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth' | _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/own_data.py', '../_base_/schedules/schedule_1x_own_data.py', '../_base_/default_runtime.py']
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
load_from = 'https://download.openmmlab.com/mmdetection/v2.0/retinanet/retinanet_r50_fpn_1x_coco/retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth' |
# https://leetcode.com/problems/number-of-digit-one/
class Solution:
def countDigitOne(self, n: int) -> int:
result = threshold = 0
divisor = limit = 10
while n // limit > 0:
limit *= 10
while divisor <= limit:
div, mod = divmod(n, divisor)
result += div * (divisor // 10)
if mod > threshold:
result += min(mod - threshold, divisor // 10)
divisor, threshold = 10 * divisor, 10 * threshold + 9
return result
| class Solution:
def count_digit_one(self, n: int) -> int:
result = threshold = 0
divisor = limit = 10
while n // limit > 0:
limit *= 10
while divisor <= limit:
(div, mod) = divmod(n, divisor)
result += div * (divisor // 10)
if mod > threshold:
result += min(mod - threshold, divisor // 10)
(divisor, threshold) = (10 * divisor, 10 * threshold + 9)
return result |
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
bmi = weight/(height**2)
if bmi <= 18.5 :
print(f"you bmi is {bmi}, you are underweight")
elif bmi <=25 :
print(f"you bmi is {bmi}you have a normal weight")
elif bmi <= 30 :
print(f"you bmi is {bmi}you are slightly overweight")
elif bmi <= 35 :
print(f"you bmi is {bmi}you are obese")
else :
print(f"you bmi is {bmi}you are clinically obese")
| height = float(input('enter your height in m: '))
weight = float(input('enter your weight in kg: '))
bmi = weight / height ** 2
if bmi <= 18.5:
print(f'you bmi is {bmi}, you are underweight')
elif bmi <= 25:
print(f'you bmi is {bmi}you have a normal weight')
elif bmi <= 30:
print(f'you bmi is {bmi}you are slightly overweight')
elif bmi <= 35:
print(f'you bmi is {bmi}you are obese')
else:
print(f'you bmi is {bmi}you are clinically obese') |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 17 09:27:36 2016
@author: tih
"""
def Accounts(Type=None):
User_Pass = {
'NASA': ['', ''],
'GLEAM': ['', ''],
'FTP_WA': ['', ''],
'MSWEP': ['', ''],
'VITO': ['', '']}
Selected_Path = User_Pass[Type]
return(Selected_Path)
| """
Created on Thu Mar 17 09:27:36 2016
@author: tih
"""
def accounts(Type=None):
user__pass = {'NASA': ['', ''], 'GLEAM': ['', ''], 'FTP_WA': ['', ''], 'MSWEP': ['', ''], 'VITO': ['', '']}
selected__path = User_Pass[Type]
return Selected_Path |
script_create_table_tipos = lambda dados = {} : """
DROP TABLE IF EXISTS Tipos;
CREATE TABLE Tipos (
id int NOT NULL PRIMARY KEY,
nome text NOT NULL DEFAULT 'pokemon'
);
"""
script_insert_table_tipos = lambda dados = {} : """INSERT INTO Tipos (id, nome) VALUES (?, ?);"""
dados_padrao_tabela_tipos = lambda dados = {} : [(1,'pokemon')] | script_create_table_tipos = lambda dados={}: "\n DROP TABLE IF EXISTS Tipos;\n\n CREATE TABLE Tipos (\n id int NOT NULL PRIMARY KEY,\n nome text NOT NULL DEFAULT 'pokemon'\n );\n"
script_insert_table_tipos = lambda dados={}: 'INSERT INTO Tipos (id, nome) VALUES (?, ?);'
dados_padrao_tabela_tipos = lambda dados={}: [(1, 'pokemon')] |
n, k = map(int,input().split())
cnt = 0
prime = [True]*(n+1)
for i in range(2,n+1,1):
if prime[i] == False: continue
for j in range(i,n+1,i):
if prime[j] == True: prime[j] = False;cnt+=1
if cnt == k: print(j);break | (n, k) = map(int, input().split())
cnt = 0
prime = [True] * (n + 1)
for i in range(2, n + 1, 1):
if prime[i] == False:
continue
for j in range(i, n + 1, i):
if prime[j] == True:
prime[j] = False
cnt += 1
if cnt == k:
print(j)
break |
class TrackData():
def __init__(self):
self.trail_data = None # common dictionary, which is mutable
self.camera_id = None
self.trail_num = 0
self.file_name = None
self.feat_list = []
self.mean_feat = None
self.height = None
self.map_time_stamp = []
self.target_image_path = None
self.record_id = None
def set_record_id(self, record_id):
"""Set record id."""
self.record_id = record_id
def get_record_id(self):
"""Get record id."""
return self.record_id
def set_image_path(self, image_path):
"""Set image path."""
self.target_image_path = image_path
def get_image_path(self):
"""Get image path."""
return self.target_image_path
def get_map_time_stamp(self):
"""Get map time stamp."""
return list(set(self.map_time_stamp))
def add_map_time_stamp(self, map_time_stamp):
"""Add map time stamp."""
self.map_time_stamp.append(map_time_stamp)
def get_trail_stamp_list(self):
"""Get trail stamp list."""
return list(self.trail_data.keys())
def set_stamp_data(self, time_stamp, new_stamp_data):
"""Set stamp data."""
self.trail_data[time_stamp] = new_stamp_data
def get_stamp_data(self, time_stamp):
"""Get stamp data."""
try:
stamp_data = self.trail_data[time_stamp]
except KeyError:
stamp_data = None
return stamp_data
def set_height(self, height):
"""Set height."""
self.height = height
def get_height(self):
"""Get height."""
return self.height
def set_trail(self, trail_data):
"""Set trail data."""
self.trail_data = trail_data
def get_trail(self):
"""Get trail data."""
return self.trail_data
def set_camera_id(self, camera_id):
"""Set camera id."""
self.camera_id = camera_id
def get_camera_id(self):
"""Get camera id."""
return self.camera_id
def set_trail_num(self, trail_num):
"""Set trail num."""
self.trail_num = trail_num
def get_trail_num(self):
"""Get trail num."""
return self.trail_num
def set_file_name(self, file_name):
"""Set file_name."""
self.file_name = file_name
def get_file_name(self):
"""Get file_name."""
return self.file_name
def put_feat_list(self, feat):
"""Put feat list."""
self.feat_list.append(feat)
def get_feat_list(self):
"""Get feat list."""
return self.feat_list
def set_mean_feat(self, mean_feat):
"""Put mean_feat."""
self.mean_feat = mean_feat
def get_mean_feat(self):
"""Get mean_feat."""
return self.mean_feat
class FrameData():
"""To save info for each stamp of a track."""
def __init__(self):
self.bbox = None
self.head = None
self.feat = None
self.predict_flag = 0
self.world = None
self.flag = None
self.temp_world_dict = {}
self.camera_bbox = {}
def set_camera_bbox(self, camera, bbox):
"""Set camera bbox."""
self.camera_bbox[camera] = bbox
def get_camera_bbox(self, camera):
"""Get camera bbox."""
try:
bbox = self.camera_bbox[camera]
return bbox
except KeyError:
return None
def set_bbox(self, bbox):
"""Set bbox."""
self.bbox = bbox
def get_bbox(self):
"""Get bbox."""
return self.bbox
def set_head(self, head):
"""Set bbox."""
self.head = head
def get_head(self):
"""Get bbox."""
return self.head
def set_feat(self, feat):
self.feat = feat
def get_feat(self):
return self.feat
def set_flag(self, flag):
self.flag = flag
def get_flag(self):
return self.flag
def set_predict_flag(self, flag):
"""Set bbox."""
self.predict_flag = flag
def set_world(self, world):
"""Set world."""
self.world = world
def get_world(self):
"""Get world."""
return self.world
def put_temp_world_dict(self, record_id_a, record_id_b, world):
"""Get world temp."""
self.temp_world_dict[(record_id_a, record_id_b)] = world
def get_temp_world_dict(self):
"""Get world temp."""
return self.temp_world_dict
class FrameResultData(FrameData):
"""To save info for each stamp of global id."""
def __init__(self):
super(FrameResultData, self).__init__()
self.camera_bbox = {}
self.camera_head = {}
self.camera_feat = {}
self.footpoint = None
def set_camera_bbox(self, camera, bbox):
"""Set camera bbox."""
self.camera_bbox[camera] = bbox
def get_camera_bbox(self, camera):
"""Get camera bbox."""
try:
bbox = self.camera_bbox[camera]
return bbox
except KeyError:
return None
def set_camera_head(self, camera, head):
"""Set camera head."""
self.camera_head[camera] = head
def get_camera_head(self, camera):
"""Get camera head."""
try:
head = self.camera_head[camera]
return head
except KeyError:
return None
def set_footpoint(self, footpoint):
"""Set room_map."""
self.footpoint = footpoint
def get_footpoint(self):
"""Get room_map."""
return self.footpoint
def set_camera_feat(self, camera, feat):
self.camera_feat[camera] = feat
def get_camera_feat(self, camera):
try:
feat = self.camera_feat[camera]
return feat
except:
return None
| class Trackdata:
def __init__(self):
self.trail_data = None
self.camera_id = None
self.trail_num = 0
self.file_name = None
self.feat_list = []
self.mean_feat = None
self.height = None
self.map_time_stamp = []
self.target_image_path = None
self.record_id = None
def set_record_id(self, record_id):
"""Set record id."""
self.record_id = record_id
def get_record_id(self):
"""Get record id."""
return self.record_id
def set_image_path(self, image_path):
"""Set image path."""
self.target_image_path = image_path
def get_image_path(self):
"""Get image path."""
return self.target_image_path
def get_map_time_stamp(self):
"""Get map time stamp."""
return list(set(self.map_time_stamp))
def add_map_time_stamp(self, map_time_stamp):
"""Add map time stamp."""
self.map_time_stamp.append(map_time_stamp)
def get_trail_stamp_list(self):
"""Get trail stamp list."""
return list(self.trail_data.keys())
def set_stamp_data(self, time_stamp, new_stamp_data):
"""Set stamp data."""
self.trail_data[time_stamp] = new_stamp_data
def get_stamp_data(self, time_stamp):
"""Get stamp data."""
try:
stamp_data = self.trail_data[time_stamp]
except KeyError:
stamp_data = None
return stamp_data
def set_height(self, height):
"""Set height."""
self.height = height
def get_height(self):
"""Get height."""
return self.height
def set_trail(self, trail_data):
"""Set trail data."""
self.trail_data = trail_data
def get_trail(self):
"""Get trail data."""
return self.trail_data
def set_camera_id(self, camera_id):
"""Set camera id."""
self.camera_id = camera_id
def get_camera_id(self):
"""Get camera id."""
return self.camera_id
def set_trail_num(self, trail_num):
"""Set trail num."""
self.trail_num = trail_num
def get_trail_num(self):
"""Get trail num."""
return self.trail_num
def set_file_name(self, file_name):
"""Set file_name."""
self.file_name = file_name
def get_file_name(self):
"""Get file_name."""
return self.file_name
def put_feat_list(self, feat):
"""Put feat list."""
self.feat_list.append(feat)
def get_feat_list(self):
"""Get feat list."""
return self.feat_list
def set_mean_feat(self, mean_feat):
"""Put mean_feat."""
self.mean_feat = mean_feat
def get_mean_feat(self):
"""Get mean_feat."""
return self.mean_feat
class Framedata:
"""To save info for each stamp of a track."""
def __init__(self):
self.bbox = None
self.head = None
self.feat = None
self.predict_flag = 0
self.world = None
self.flag = None
self.temp_world_dict = {}
self.camera_bbox = {}
def set_camera_bbox(self, camera, bbox):
"""Set camera bbox."""
self.camera_bbox[camera] = bbox
def get_camera_bbox(self, camera):
"""Get camera bbox."""
try:
bbox = self.camera_bbox[camera]
return bbox
except KeyError:
return None
def set_bbox(self, bbox):
"""Set bbox."""
self.bbox = bbox
def get_bbox(self):
"""Get bbox."""
return self.bbox
def set_head(self, head):
"""Set bbox."""
self.head = head
def get_head(self):
"""Get bbox."""
return self.head
def set_feat(self, feat):
self.feat = feat
def get_feat(self):
return self.feat
def set_flag(self, flag):
self.flag = flag
def get_flag(self):
return self.flag
def set_predict_flag(self, flag):
"""Set bbox."""
self.predict_flag = flag
def set_world(self, world):
"""Set world."""
self.world = world
def get_world(self):
"""Get world."""
return self.world
def put_temp_world_dict(self, record_id_a, record_id_b, world):
"""Get world temp."""
self.temp_world_dict[record_id_a, record_id_b] = world
def get_temp_world_dict(self):
"""Get world temp."""
return self.temp_world_dict
class Frameresultdata(FrameData):
"""To save info for each stamp of global id."""
def __init__(self):
super(FrameResultData, self).__init__()
self.camera_bbox = {}
self.camera_head = {}
self.camera_feat = {}
self.footpoint = None
def set_camera_bbox(self, camera, bbox):
"""Set camera bbox."""
self.camera_bbox[camera] = bbox
def get_camera_bbox(self, camera):
"""Get camera bbox."""
try:
bbox = self.camera_bbox[camera]
return bbox
except KeyError:
return None
def set_camera_head(self, camera, head):
"""Set camera head."""
self.camera_head[camera] = head
def get_camera_head(self, camera):
"""Get camera head."""
try:
head = self.camera_head[camera]
return head
except KeyError:
return None
def set_footpoint(self, footpoint):
"""Set room_map."""
self.footpoint = footpoint
def get_footpoint(self):
"""Get room_map."""
return self.footpoint
def set_camera_feat(self, camera, feat):
self.camera_feat[camera] = feat
def get_camera_feat(self, camera):
try:
feat = self.camera_feat[camera]
return feat
except:
return None |
def sum_iter(numbers):
total = 0
for n in numbers:
total = total + n
return total
def sum_rec(numbers):
if len(numbers) == 0:
return 0
return numbers[0] + sum_rec(numbers[1:])
| def sum_iter(numbers):
total = 0
for n in numbers:
total = total + n
return total
def sum_rec(numbers):
if len(numbers) == 0:
return 0
return numbers[0] + sum_rec(numbers[1:]) |
with open('data.txt') as f:
data = f.readlines()
data = [int(i.rstrip()) for i in data]
incr = 0
for idx, val in enumerate(data):
if idx == 0:
print(data[0])
continue
if data[idx-1] < data[idx]:
incr += 1
print(f"{data[idx]} increase")
else:
print(f"{data[idx]}")
print(f"Loop Total {incr}")
asdf = sum([int(second > first) for first, second in zip(data, data[1:])])
print(f"Generator count = {asdf}")
| with open('data.txt') as f:
data = f.readlines()
data = [int(i.rstrip()) for i in data]
incr = 0
for (idx, val) in enumerate(data):
if idx == 0:
print(data[0])
continue
if data[idx - 1] < data[idx]:
incr += 1
print(f'{data[idx]} increase')
else:
print(f'{data[idx]}')
print(f'Loop Total {incr}')
asdf = sum([int(second > first) for (first, second) in zip(data, data[1:])])
print(f'Generator count = {asdf}') |
#!/usr/bin/python3
def this_fails():
x = 1/0
try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error: ', err) | def this_fails():
x = 1 / 0
try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error: ', err) |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def mergeTrees(self, t1, t2):
def recurse(a1, a2):
if a1 == None:
return a2
if a2 == None:
return a1
cur = TreeNode(a1.val + a2.val)
cur.left = recurse(a1.left, a2.left)
cur.right = recurse(a1.right, a2.right)
return cur
return recurse(t1, t2)
z = Solution()
a = TreeNode(1)
b = TreeNode(3)
c = TreeNode(2)
d = TreeNode(5)
a.left = b
a.right = c
b.left = d
e = TreeNode(2)
f = TreeNode(1)
g = TreeNode(3)
h = TreeNode(4)
i = TreeNode(7)
e.left = f
e.right = g
f.right = h
g.right = i
res = (z.mergeTrees(a, e))
print(res.val)
print(res.left.val)
print(res.right.val)
print(res.left.left.val)
print(res.left.right.val)
print(res.right.right.val)
| class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def merge_trees(self, t1, t2):
def recurse(a1, a2):
if a1 == None:
return a2
if a2 == None:
return a1
cur = tree_node(a1.val + a2.val)
cur.left = recurse(a1.left, a2.left)
cur.right = recurse(a1.right, a2.right)
return cur
return recurse(t1, t2)
z = solution()
a = tree_node(1)
b = tree_node(3)
c = tree_node(2)
d = tree_node(5)
a.left = b
a.right = c
b.left = d
e = tree_node(2)
f = tree_node(1)
g = tree_node(3)
h = tree_node(4)
i = tree_node(7)
e.left = f
e.right = g
f.right = h
g.right = i
res = z.mergeTrees(a, e)
print(res.val)
print(res.left.val)
print(res.right.val)
print(res.left.left.val)
print(res.left.right.val)
print(res.right.right.val) |
# -*- coding: utf-8 -*-
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = ('postgresql+psycopg2://'
'taxo:taxo@localhost:5432/taxonwiki')
ASSETS_DEBUG = False
ASSETS_CACHE = True
ASSETS_MANIFEST = 'json'
UGLIFYJS_EXTRA_ARGS = ['--compress', '--mangle']
COMPASS_CONFIG = {
'output_style': ':compressed'
}
SECRET_KEY = 'I am not safe please do not use me'
class ProductionConfig(Config):
SECRET_KEY = None
class DevelopmentConfig(Config):
DEBUG = True
ASSETS_CACHE = False
UGLIFYJS_EXTRA_ARGS = ['--compress']
COMPASS_CONFIG = {
'output_style': ':extended'
}
class TestingConfig(Config):
TESTING = True
| class Config(object):
debug = False
testing = False
database_uri = 'postgresql+psycopg2://taxo:taxo@localhost:5432/taxonwiki'
assets_debug = False
assets_cache = True
assets_manifest = 'json'
uglifyjs_extra_args = ['--compress', '--mangle']
compass_config = {'output_style': ':compressed'}
secret_key = 'I am not safe please do not use me'
class Productionconfig(Config):
secret_key = None
class Developmentconfig(Config):
debug = True
assets_cache = False
uglifyjs_extra_args = ['--compress']
compass_config = {'output_style': ':extended'}
class Testingconfig(Config):
testing = True |
buttons_dict = {1: [r"$|a|$", "abs"], 2: [r"$\sqrt{a}$", "sqrt"], 3: [r"$\log$", "log"],
4: [r"$\ln$", "ln"], 5: [r"$a^b$", "power"], 6: [r"$()$", "brackets"],
7: [r"%", "percent"], 8: [r"$=$", "equals"], 9: [r"$\lfloor{a}\rfloor$", "floor"],
10: [r"$f(x)$", "func"], 11: [r"$\cot$", "cot"], 12: [r"$\tan$", "tan"],
13: [r"$7$", "7"], 14: [r"$8$", "8"], 15: [r"$9$", "9"], 16: [r"$\div$", "div"],
17: [r"$\lceil{a}\rceil$", "ceil"], 18: [r"$\frac{d}{dx}$", "derivative"],
19: [r"$\sec$", "sec"], 20: [r"$\cos$", "cos"], 21: [r"$4$", "4"], 22: [r"$5$", "5"],
23: [r"$6$", "6"], 24: [r"$\times$", "times"], 25: [r"$x$", "x"],
26: [r"$\int$", "integral"], 27: [r"$\csc$", "csc"], 28: [r"$\sin$", "sin"],
29: [r"$1$", "1"], 30: [r"$2$", "2"], 31: [r"$3$", "3"], 32: [r"$-$", "minus"],
33: [r"$y$", "y"], 34: [r"$\int^a_b$", "def_integral"], 35: [r"$e$", "e"],
36: [r"$\pi$", "pi"], 37: [r"$\frac{a}{b}$", "fraction"], 38: [r"$0$", "0"],
39: [r"$.$", "decimal_point"], 40: [r"$+$", "plus"]}
# these are the buttons in LaTeX maths mode format | buttons_dict = {1: ['$|a|$', 'abs'], 2: ['$\\sqrt{a}$', 'sqrt'], 3: ['$\\log$', 'log'], 4: ['$\\ln$', 'ln'], 5: ['$a^b$', 'power'], 6: ['$()$', 'brackets'], 7: ['%', 'percent'], 8: ['$=$', 'equals'], 9: ['$\\lfloor{a}\\rfloor$', 'floor'], 10: ['$f(x)$', 'func'], 11: ['$\\cot$', 'cot'], 12: ['$\\tan$', 'tan'], 13: ['$7$', '7'], 14: ['$8$', '8'], 15: ['$9$', '9'], 16: ['$\\div$', 'div'], 17: ['$\\lceil{a}\\rceil$', 'ceil'], 18: ['$\\frac{d}{dx}$', 'derivative'], 19: ['$\\sec$', 'sec'], 20: ['$\\cos$', 'cos'], 21: ['$4$', '4'], 22: ['$5$', '5'], 23: ['$6$', '6'], 24: ['$\\times$', 'times'], 25: ['$x$', 'x'], 26: ['$\\int$', 'integral'], 27: ['$\\csc$', 'csc'], 28: ['$\\sin$', 'sin'], 29: ['$1$', '1'], 30: ['$2$', '2'], 31: ['$3$', '3'], 32: ['$-$', 'minus'], 33: ['$y$', 'y'], 34: ['$\\int^a_b$', 'def_integral'], 35: ['$e$', 'e'], 36: ['$\\pi$', 'pi'], 37: ['$\\frac{a}{b}$', 'fraction'], 38: ['$0$', '0'], 39: ['$.$', 'decimal_point'], 40: ['$+$', 'plus']} |
default_ingredient_list = ['lentils', 'kale', 'shallots', 'swiss cheese', 'anchovies', 'Quiche', 'cashew nut',
'Waffles', 'chicken liver', 'parsley', 'babaganoosh', 'Toast', 'bouillon', 'hamburger',
'hoisin sauce', 'chaurice sausage', 'fennel', 'curry', 'clams', 'spaghetti squash',
'haiku roll', 'ancho chili peppers', 'flax seed', 'remoulade', 'alfredo sauce', 'avacado',
'broccoli', 'moo shu wrappers', 'truffles', 'carne asada', 'Pancakes', 'tomato puree',
'steak', 'Guancamole', 'crab', 'bison', 'almond', 'snap peas', 'corn', 'basil', 'barley',
'grouper', 'romaine lettuce', 'tarragon', 'Spaghetti', 'edimame', 'Tater tots', 'jambalaya',
'amaretto', 'bean sauce', 'lobster', 'granola', 'sour cream', 'yogurt', 'cilantro',
'avocados', 'duck', 'dates', 'kumquats', 'spearmint', 'celery seeds', 'cider vinegar',
'sardines', 'bacon', 'jack cheese', 'haddock', 'shitakes', 'franks', 'pickles', 'ginger',
'ginger ale', 'french fries', 'Irish stew', 'breadfruit', 'dips', 'bass',
'potato chips', 'lemons', 'salmon', 'Wine', 'caviar', 'apple butter', 'bard', 'coconut oil',
'Cabbage', 'carrots', 'asparagus', 'kiwi', 'chocolate', 'unsweetened chocolate',
'tomato sauce', 'oatmeal', 'gumbo', 'panko bread crumbs', 'pancetta', 'Reuben',
'condensed milk', 'Pizza', 'curry paste', 'rosemary', 'ketchup', 'cornmeal', 'turkeys',
'rice', 'split peas', 'pink beans', 'maraschino cherries', 'dried leeks', 'bruschetta',
'molasses', 'spinach', 'cucumbers', 'cupcakes', 'mesclun greens', 'bagels', 'apples',
'Bruscetta', 'ice cream', 'asiago cheese', 'tomatoes', 'pistachios', 'eggs', 'vegemite',
'corn syrup', 'cake', 'hash browns', 'sazon', 'veal', 'habanero chilies', 'red chili powder',
'Tabasco sauce', 'fajita', 'portabella mushrooms', 'Goji berry', 'brazil nuts', 'parsnips',
'enchilada', 'Quesadilla', 'hummus', 'chimichangadates', 'sherry', 'bok choy', 'horseradish',
'rhubarb', 'quail', 'mint', 'Irish cream liqueur', 'Pepperoni', 'melons', 'pears',
'cocoa powder', 'bluefish', 'Mandarin oranges', 'cooking wine', 'tartar sauce', 'papayas',
'honey', 'shrimp', 'black olives', 'canola oil', 'cheddar cheese', 'alfalfa', 'cider',
'corn flour', 'feta cheese', 'fondu', 'onions', 'water', 'sauerkraut', 'cornstarch',
'bourbon', 'cabbage', 'brown rice', 'baguette', 'balsamic vinegar', 'ahi tuna ', 'mushrooms',
'pasta', 'chips', 'garlic', 'chicory', 'allspice', 'maple syrup', 'chickpeas', 'chard',
'hot dogs', 'baking soda', 'arugala', 'sausages', 'sweet peppers', 'five-spice powder',
'thyme', 'chili powder', 'Havarti cheese', 'artichokes', 'beef', 'fish ', 'tuna',
'eel sushi', 'sweet potatoes', 'donuts', 'sunflower seeds', 'coconuts', 'salsa', 'celery',
'prunes', 'crayfish', 'hamburger ', 'beer', 'jicama', 'rum', 'rice vinegar', 'bean threads',
'hazelnuts', 'kidney beans', 'halibut', 'grapes', 'chambord', 'adobo', 'chipotle peppers',
'capers', 'Ziti', 'cherries', 'hot sauce', 'eel', 'pico de gallo', 'green onions',
'sesame seeds', 'Zucchini', 'French toast', 'chai', 'focaccia', 'guavas', 'raspberries',
'huckleberries', 'zinfandel wine', 'croutons', 'mayonnaise', 'barbecue sauce', 'cumin',
'pea beans', 'tonic water', 'tortillas', 'squash', 'gorgonzola', 'squid', 'Graham crackers',
'brussels sprouts', 'coriander', 'summer squash', 'rose water', 'mustard seeds', 'borscht',
'gelatin', 'tofu', 'white beans', 'English muffins', 'jelly', 'cream cheese', 'snapper',
'mustard', 'broccoli raab', 'Romano cheese', 'buritto', 'paprika', 'acorn squash ',
'snow peas', 'cannellini beans', 'red snapper', 'ham', 'raisins', 'creme fraiche',
'watermelons', 'artificial sweetener', 'BBQ', 'Linguine', 'plantains', 'strawberries',
'monkfish', 'powdered sugar', 'Spinach', 'cheese', 'buckwheat', 'potatoes', 'goose', 'beets',
'lima beans', 'jelly beans', 'huenos rancheros', 'pumpkins', 'salt', 'blueberries',
'navy beans', 'graham crackers', 'custard', 'sushi', 'radishes', 'berries',
'red pepper flakes', 'ale', 'okra', 'soy sauce', 'tea', 'aioli', 'date sugar', 'pork',
'liver', 'cottage cheese', 'limes', 'orange peels', 'vinegar', 'olives', 'cactus', 'Kahlua',
'mackerel', 'apricots', 'green beans', 'Garlic', 'black-eyed peas', 'soybeans',
'andouille sausage', 'Marsala', 'jam', 'marshmallows', 'walnuts', 'geese', 'flour', 'coffee',
'heavy cream', 'red beans', 'lemon juice', 'poultry seasoning', 'Cappuccino Latte',
'red cabbage', 'blue cheese', 'chicken', 'Moose', 'Yogurt', 'baked beans', 'cream', 'figs',
'dill', 'swordfish', 'rice wine', 'peanuts', 'cayenne pepper', "pig's feet", 'fish sauce',
'barley sugar', 'acorn squash', 'rice paper', 'Lasagna', 'applesauce', 'cauliflower',
'kabobs', 'sea cucumbers', 'sugar', 'Ostrich', 'asian noodles ', 'zest', 'cinnamon',
'Venison', 'chowder', 'butter', 'almond butter', 'cream of tartar', 'dumpling', 'Milk',
'cantaloupes', 'apple pie spice', 'brown sugar', 'cod', 'lemon Peel', 'vermouth',
'provolone', 'Worcestershire sauce', 'beans', 'breadcrumbs', 'bay leaves', 'garlic powder',
'eggrolls', 'jerky', 'water chestnuts', 'scallops', 'Walnuts', 'almond paste', 'wasabi',
'cloves', 'marmalade', 'honeydew melons', 'brunoise', 'bread', 'white chocolate', 'chutney',
'chestnuts', 'Meatballs', 'baking powder', 'catfish', 'rabbits', 'olive oil', 'poppy seeds',
'margarine', 'pecans', 'nectarines', 'milk', 'eggplants', 'sweet chili sauce', 'bisque',
'venison', 'buttermilk', 'mascarpone', 'cereal', 'mozzarella', 'ricotta cheese',
'pumpkin seeds', 'half-and-half', 'Italian bread', 'dumplings', 'Noodles', 'pinto beans',
'jalapeno', 'plum tomatoes', 'curry powder', 'broth', 'Parmesan cheese', 'grapefruits',
'pepper', 'bacon grease', 'lettuce', 'crabs', 'plums', 'blackberries', 'pesto', 'cookies',
'succotash', 'soymilk', 'gouda', 'oranges', 'pine nuts', 'bean sprouts', 'artichoke',
'won ton skins', 'trout', 'pomegranates', 'French dip', 'cremini mushrooms', 'oregano',
'pheasants', 'corned beef', 'gnocchi', 'chili sauce', 'turtle', 'almond extract', 'antelope',
'lemon grass', 'Avocado roll', 'almonds', 'falafel', 'peanut butter', 'tomato paste',
'pineapples', 'wild rice', 'Milkshake', 'tomato juice', 'wine vinegar', 'alligator',
'albacore tuna', 'herring', 'mussels', 'lamb', 'cranberries', 'chives', 'onion powder',
'leeks', 'peaches', 'Lamb', 'fennel seeds', 'Indian food', 'Canadian bacon', 'prawns',
'coconut milk', 'peas', 'couscous', 'Apple juice', 'bananas', 'brandy', 'lobsters', 'sage',
'wine', 'prosciutto', 'chili peppers', 'kingfish', 'raw sugar', 'aquavit', 'Porter',
'curry leaves', 'black beans', 'vanilla', 'colby cheese', 'passion fruit', 'octopus',
'vanilla bean', 'grits', 'flounder', 'arugula', 'turnips', 'macaroni', 'anchovy paste']
| default_ingredient_list = ['lentils', 'kale', 'shallots', 'swiss cheese', 'anchovies', 'Quiche', 'cashew nut', 'Waffles', 'chicken liver', 'parsley', 'babaganoosh', 'Toast', 'bouillon', 'hamburger', 'hoisin sauce', 'chaurice sausage', 'fennel', 'curry', 'clams', 'spaghetti squash', 'haiku roll', 'ancho chili peppers', 'flax seed', 'remoulade', 'alfredo sauce', 'avacado', 'broccoli', 'moo shu wrappers', 'truffles', 'carne asada', 'Pancakes', 'tomato puree', 'steak', 'Guancamole', 'crab', 'bison', 'almond', 'snap peas', 'corn', 'basil', 'barley', 'grouper', 'romaine lettuce', 'tarragon', 'Spaghetti', 'edimame', 'Tater tots', 'jambalaya', 'amaretto', 'bean sauce', 'lobster', 'granola', 'sour cream', 'yogurt', 'cilantro', 'avocados', 'duck', 'dates', 'kumquats', 'spearmint', 'celery seeds', 'cider vinegar', 'sardines', 'bacon', 'jack cheese', 'haddock', 'shitakes', 'franks', 'pickles', 'ginger', 'ginger ale', 'french fries', 'Irish stew', 'breadfruit', 'dips', 'bass', 'potato chips', 'lemons', 'salmon', 'Wine', 'caviar', 'apple butter', 'bard', 'coconut oil', 'Cabbage', 'carrots', 'asparagus', 'kiwi', 'chocolate', 'unsweetened chocolate', 'tomato sauce', 'oatmeal', 'gumbo', 'panko bread crumbs', 'pancetta', 'Reuben', 'condensed milk', 'Pizza', 'curry paste', 'rosemary', 'ketchup', 'cornmeal', 'turkeys', 'rice', 'split peas', 'pink beans', 'maraschino cherries', 'dried leeks', 'bruschetta', 'molasses', 'spinach', 'cucumbers', 'cupcakes', 'mesclun greens', 'bagels', 'apples', 'Bruscetta', 'ice cream', 'asiago cheese', 'tomatoes', 'pistachios', 'eggs', 'vegemite', 'corn syrup', 'cake', 'hash browns', 'sazon', 'veal', 'habanero chilies', 'red chili powder', 'Tabasco sauce', 'fajita', 'portabella mushrooms', 'Goji berry', 'brazil nuts', 'parsnips', 'enchilada', 'Quesadilla', 'hummus', 'chimichangadates', 'sherry', 'bok choy', 'horseradish', 'rhubarb', 'quail', 'mint', 'Irish cream liqueur', 'Pepperoni', 'melons', 'pears', 'cocoa powder', 'bluefish', 'Mandarin oranges', 'cooking wine', 'tartar sauce', 'papayas', 'honey', 'shrimp', 'black olives', 'canola oil', 'cheddar cheese', 'alfalfa', 'cider', 'corn flour', 'feta cheese', 'fondu', 'onions', 'water', 'sauerkraut', 'cornstarch', 'bourbon', 'cabbage', 'brown rice', 'baguette', 'balsamic vinegar', 'ahi tuna ', 'mushrooms', 'pasta', 'chips', 'garlic', 'chicory', 'allspice', 'maple syrup', 'chickpeas', 'chard', 'hot dogs', 'baking soda', 'arugala', 'sausages', 'sweet peppers', 'five-spice powder', 'thyme', 'chili powder', 'Havarti cheese', 'artichokes', 'beef', 'fish ', 'tuna', 'eel sushi', 'sweet potatoes', 'donuts', 'sunflower seeds', 'coconuts', 'salsa', 'celery', 'prunes', 'crayfish', 'hamburger ', 'beer', 'jicama', 'rum', 'rice vinegar', 'bean threads', 'hazelnuts', 'kidney beans', 'halibut', 'grapes', 'chambord', 'adobo', 'chipotle peppers', 'capers', 'Ziti', 'cherries', 'hot sauce', 'eel', 'pico de gallo', 'green onions', 'sesame seeds', 'Zucchini', 'French toast', 'chai', 'focaccia', 'guavas', 'raspberries', 'huckleberries', 'zinfandel wine', 'croutons', 'mayonnaise', 'barbecue sauce', 'cumin', 'pea beans', 'tonic water', 'tortillas', 'squash', 'gorgonzola', 'squid', 'Graham crackers', 'brussels sprouts', 'coriander', 'summer squash', 'rose water', 'mustard seeds', 'borscht', 'gelatin', 'tofu', 'white beans', 'English muffins', 'jelly', 'cream cheese', 'snapper', 'mustard', 'broccoli raab', 'Romano cheese', 'buritto', 'paprika', 'acorn squash ', 'snow peas', 'cannellini beans', 'red snapper', 'ham', 'raisins', 'creme fraiche', 'watermelons', 'artificial sweetener', 'BBQ', 'Linguine', 'plantains', 'strawberries', 'monkfish', 'powdered sugar', 'Spinach', 'cheese', 'buckwheat', 'potatoes', 'goose', 'beets', 'lima beans', 'jelly beans', 'huenos rancheros', 'pumpkins', 'salt', 'blueberries', 'navy beans', 'graham crackers', 'custard', 'sushi', 'radishes', 'berries', 'red pepper flakes', 'ale', 'okra', 'soy sauce', 'tea', 'aioli', 'date sugar', 'pork', 'liver', 'cottage cheese', 'limes', 'orange peels', 'vinegar', 'olives', 'cactus', 'Kahlua', 'mackerel', 'apricots', 'green beans', 'Garlic', 'black-eyed peas', 'soybeans', 'andouille sausage', 'Marsala', 'jam', 'marshmallows', 'walnuts', 'geese', 'flour', 'coffee', 'heavy cream', 'red beans', 'lemon juice', 'poultry seasoning', 'Cappuccino Latte', 'red cabbage', 'blue cheese', 'chicken', 'Moose', 'Yogurt', 'baked beans', 'cream', 'figs', 'dill', 'swordfish', 'rice wine', 'peanuts', 'cayenne pepper', "pig's feet", 'fish sauce', 'barley sugar', 'acorn squash', 'rice paper', 'Lasagna', 'applesauce', 'cauliflower', 'kabobs', 'sea cucumbers', 'sugar', 'Ostrich', 'asian noodles ', 'zest', 'cinnamon', 'Venison', 'chowder', 'butter', 'almond butter', 'cream of tartar', 'dumpling', 'Milk', 'cantaloupes', 'apple pie spice', 'brown sugar', 'cod', 'lemon Peel', 'vermouth', 'provolone', 'Worcestershire sauce', 'beans', 'breadcrumbs', 'bay leaves', 'garlic powder', 'eggrolls', 'jerky', 'water chestnuts', 'scallops', 'Walnuts', 'almond paste', 'wasabi', 'cloves', 'marmalade', 'honeydew melons', 'brunoise', 'bread', 'white chocolate', 'chutney', 'chestnuts', 'Meatballs', 'baking powder', 'catfish', 'rabbits', 'olive oil', 'poppy seeds', 'margarine', 'pecans', 'nectarines', 'milk', 'eggplants', 'sweet chili sauce', 'bisque', 'venison', 'buttermilk', 'mascarpone', 'cereal', 'mozzarella', 'ricotta cheese', 'pumpkin seeds', 'half-and-half', 'Italian bread', 'dumplings', 'Noodles', 'pinto beans', 'jalapeno', 'plum tomatoes', 'curry powder', 'broth', 'Parmesan cheese', 'grapefruits', 'pepper', 'bacon grease', 'lettuce', 'crabs', 'plums', 'blackberries', 'pesto', 'cookies', 'succotash', 'soymilk', 'gouda', 'oranges', 'pine nuts', 'bean sprouts', 'artichoke', 'won ton skins', 'trout', 'pomegranates', 'French dip', 'cremini mushrooms', 'oregano', 'pheasants', 'corned beef', 'gnocchi', 'chili sauce', 'turtle', 'almond extract', 'antelope', 'lemon grass', 'Avocado roll', 'almonds', 'falafel', 'peanut butter', 'tomato paste', 'pineapples', 'wild rice', 'Milkshake', 'tomato juice', 'wine vinegar', 'alligator', 'albacore tuna', 'herring', 'mussels', 'lamb', 'cranberries', 'chives', 'onion powder', 'leeks', 'peaches', 'Lamb', 'fennel seeds', 'Indian food', 'Canadian bacon', 'prawns', 'coconut milk', 'peas', 'couscous', 'Apple juice', 'bananas', 'brandy', 'lobsters', 'sage', 'wine', 'prosciutto', 'chili peppers', 'kingfish', 'raw sugar', 'aquavit', 'Porter', 'curry leaves', 'black beans', 'vanilla', 'colby cheese', 'passion fruit', 'octopus', 'vanilla bean', 'grits', 'flounder', 'arugula', 'turnips', 'macaroni', 'anchovy paste'] |
"""type_traits.py
We need to assess if a string can be converted to int or float.
This module provides simple tests is_<type>.
"""
def is_float(val):
try:
return float(val) - val == 0
except:
return False
return False
def is_int(val):
try:
return int(val) - val == 0
except:
return False
return False
def is_zero(val):
return val == 0
| """type_traits.py
We need to assess if a string can be converted to int or float.
This module provides simple tests is_<type>.
"""
def is_float(val):
try:
return float(val) - val == 0
except:
return False
return False
def is_int(val):
try:
return int(val) - val == 0
except:
return False
return False
def is_zero(val):
return val == 0 |
# coding:utf-8
# example 04: double_linked_list.py
class Node(object):
def __init__(self, val=None):
self.val = val
self.prev = None
self.next = None
class DoubleLinkedList(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = Node()
self.tailnode = None
self.length = 0
def __len__(self):
return self.length
def iter_node(self):
if self.length == 0:
return
cur = self.root
for _ in range(self.length):
cur = cur.next
yield cur
def __iter__(self):
for node in self.iter_node():
yield node.val
def iter_node_reverse(self):
if self.length == 0:
return
cur = self.tailnode
for _ in range(self.length):
yield cur
cur = cur.prev
def empty(self):
return self.root.next is None
def append(self, val): # O(1)
if self.maxsize is not None and self.length == self.maxsize:
raise Exception("Full")
node = Node(val)
if self.length == 0:
node.prev = self.root
self.root.next = node
else:
node.prev = self.tailnode
self.tailnode.next = node
self.tailnode = node
self.length += 1
def appendleft(self, val): # O(1)
if self.maxsize is not None and self.length == self.maxsize:
raise Exception("Full")
node = Node(val)
if self.length == 0:
node.prev = self.root
self.root.next = node
self.tailnode = node
else:
node.prev = self.root
node.next = self.root.next
self.root.next.prev = node
self.root.next = node
self.length += 1
def pop(self): # O(1)
if self.length == 0:
raise Exception("pop form empty Double Linked List")
val = self.tailnode.val
tailnode = self.tailnode.prev
tailnode.next = None
del self.tailnode
self.length -= 1
self.tailnode = None if self.length == 0 else tailnode
return val
def popleft(self): # O(1)
if self.length == 0:
raise Exception("pop form empty Double Linked List")
headnode = self.root.next
val = headnode.val
self.root.next = headnode.next
if headnode is self.tailnode:
self.tailnode = None
else:
headnode.next.prev = self.root
del headnode
self.length -= 1
return val
def find(self, val): # O(n)
for idx, node in enumerate(self.iter_node()):
if node.val == val:
return idx
return -1
def insert(self, pos, val): # O(n)
if pos <= 0:
self.appendleft(val)
elif self.length - 1 < pos:
self.append(val)
else:
node = Node(val)
pre = self.root
for _ in range(pos):
pre = pre.next
node.prev = pre
node.next = pre.next
node.next.prev = node
pre.next = node
self.length += 1
def remove(self, node): # O(1), node is not value
if self.length == 0:
return
if self.length == 1:
self.root.next = None
self.tailnode = None
elif node is self.tailnode:
self.tailnode = node.prev
self.tailnode.next = None
else:
node.prev.next = node.next
node.next.prev = node.prev
self.length -= 1
return node
def clear(self):
for node in self.iter_node():
del node
self.root.next = None
self.tailnode = None
self.length = 0
# use pytest
dll = DoubleLinkedList()
class TestDoubleLinkedList(object):
def test_append(self):
dll.append(1)
dll.append(2)
dll.append(3)
assert [node.val for node in dll.iter_node()] == [1, 2, 3]
assert [node.val for node in dll.iter_node_reverse()] == [3, 2, 1]
def test_appendleft(self):
dll.appendleft(0)
assert list(dll) == [0, 1, 2, 3]
def test_len(self):
assert len(dll) == 4
def test_pop(self):
tail_val = dll.pop()
assert tail_val == 3
def test_popleft(self):
head_val = dll.popleft()
assert head_val == 0
def test_find(self):
assert dll.find(2) == 1
assert dll.find(4) == -1
def test_insert(self):
dll.insert(1, 5)
assert [node.val for node in dll.iter_node()] == [1, 5, 2]
def test_remove(self):
headnode = dll.root.next
node = dll.remove(headnode)
assert node.val == 1
assert [node.val for node in dll.iter_node()] == [5, 2]
def test_clear_and_empty(self):
dll.clear()
assert dll.empty() is True
| class Node(object):
def __init__(self, val=None):
self.val = val
self.prev = None
self.next = None
class Doublelinkedlist(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = node()
self.tailnode = None
self.length = 0
def __len__(self):
return self.length
def iter_node(self):
if self.length == 0:
return
cur = self.root
for _ in range(self.length):
cur = cur.next
yield cur
def __iter__(self):
for node in self.iter_node():
yield node.val
def iter_node_reverse(self):
if self.length == 0:
return
cur = self.tailnode
for _ in range(self.length):
yield cur
cur = cur.prev
def empty(self):
return self.root.next is None
def append(self, val):
if self.maxsize is not None and self.length == self.maxsize:
raise exception('Full')
node = node(val)
if self.length == 0:
node.prev = self.root
self.root.next = node
else:
node.prev = self.tailnode
self.tailnode.next = node
self.tailnode = node
self.length += 1
def appendleft(self, val):
if self.maxsize is not None and self.length == self.maxsize:
raise exception('Full')
node = node(val)
if self.length == 0:
node.prev = self.root
self.root.next = node
self.tailnode = node
else:
node.prev = self.root
node.next = self.root.next
self.root.next.prev = node
self.root.next = node
self.length += 1
def pop(self):
if self.length == 0:
raise exception('pop form empty Double Linked List')
val = self.tailnode.val
tailnode = self.tailnode.prev
tailnode.next = None
del self.tailnode
self.length -= 1
self.tailnode = None if self.length == 0 else tailnode
return val
def popleft(self):
if self.length == 0:
raise exception('pop form empty Double Linked List')
headnode = self.root.next
val = headnode.val
self.root.next = headnode.next
if headnode is self.tailnode:
self.tailnode = None
else:
headnode.next.prev = self.root
del headnode
self.length -= 1
return val
def find(self, val):
for (idx, node) in enumerate(self.iter_node()):
if node.val == val:
return idx
return -1
def insert(self, pos, val):
if pos <= 0:
self.appendleft(val)
elif self.length - 1 < pos:
self.append(val)
else:
node = node(val)
pre = self.root
for _ in range(pos):
pre = pre.next
node.prev = pre
node.next = pre.next
node.next.prev = node
pre.next = node
self.length += 1
def remove(self, node):
if self.length == 0:
return
if self.length == 1:
self.root.next = None
self.tailnode = None
elif node is self.tailnode:
self.tailnode = node.prev
self.tailnode.next = None
else:
node.prev.next = node.next
node.next.prev = node.prev
self.length -= 1
return node
def clear(self):
for node in self.iter_node():
del node
self.root.next = None
self.tailnode = None
self.length = 0
dll = double_linked_list()
class Testdoublelinkedlist(object):
def test_append(self):
dll.append(1)
dll.append(2)
dll.append(3)
assert [node.val for node in dll.iter_node()] == [1, 2, 3]
assert [node.val for node in dll.iter_node_reverse()] == [3, 2, 1]
def test_appendleft(self):
dll.appendleft(0)
assert list(dll) == [0, 1, 2, 3]
def test_len(self):
assert len(dll) == 4
def test_pop(self):
tail_val = dll.pop()
assert tail_val == 3
def test_popleft(self):
head_val = dll.popleft()
assert head_val == 0
def test_find(self):
assert dll.find(2) == 1
assert dll.find(4) == -1
def test_insert(self):
dll.insert(1, 5)
assert [node.val for node in dll.iter_node()] == [1, 5, 2]
def test_remove(self):
headnode = dll.root.next
node = dll.remove(headnode)
assert node.val == 1
assert [node.val for node in dll.iter_node()] == [5, 2]
def test_clear_and_empty(self):
dll.clear()
assert dll.empty() is True |
def trinomial(cfg,i,j,k) : #function t=trinomial(i,j,k)
#% Computes the trinomial of
#% the three input arguments
#
aux_1=cfg.factorial(i+j+k) #aux_1=factorial(i+j+k);
aux_2=cfg.factorial(i)*cfg.factorial(j)*cfg.factorial(k) #aux_2=factorial(i)*factorial(j)*factorial(k);
t = aux_1/aux_2 #t= aux_1/aux_2;
#
return t
| def trinomial(cfg, i, j, k):
aux_1 = cfg.factorial(i + j + k)
aux_2 = cfg.factorial(i) * cfg.factorial(j) * cfg.factorial(k)
t = aux_1 / aux_2
return t |
for x in range(65,70):
for y in range(65,x+1):
print(chr(x),end='')
print()
"""
# p[attern
A
BB
CCC
DDDD
EEEEE
""" | for x in range(65, 70):
for y in range(65, x + 1):
print(chr(x), end='')
print()
'\n# p[attern \n\nA\nBB\nCCC\nDDDD\nEEEEE\n\n' |
# -*- coding: utf-8 -*-
name = 'tbb'
version = '2017.0'
def commands():
appendenv('LD_LIBRARY_PATH', '{root}/lib/intel64/gcc4.7')
env.TBBROOT.set('{root}')
env.TBB_LIBRARIES.set('{root}/lib/intel64/gcc4.7')
env.TBB_INCLUDE_DIR.set('{root}/include')
| name = 'tbb'
version = '2017.0'
def commands():
appendenv('LD_LIBRARY_PATH', '{root}/lib/intel64/gcc4.7')
env.TBBROOT.set('{root}')
env.TBB_LIBRARIES.set('{root}/lib/intel64/gcc4.7')
env.TBB_INCLUDE_DIR.set('{root}/include') |
budget = float(input())
season = input()
if budget <= 100:
destination = 'Bulgaria'
money_spent = budget * 0.7
info = f'Hotel - {money_spent:.2f}'
if season == 'summer':
money_spent = budget * 0.3
info = f'Camp - {money_spent:.2f}'
elif budget <= 1000:
destination = 'Balkans'
money_spent = budget * 0.8
info = f'Hotel - {money_spent:.2f}'
if season == 'summer':
money_spent = budget * 0.4
info = f'Camp - {money_spent:.2f}'
else:
destination = 'Europe'
money_spent = budget * 0.9
info = f'Hotel - {money_spent:.2f}'
print('Somewhere in ' + destination)
print(info)
| budget = float(input())
season = input()
if budget <= 100:
destination = 'Bulgaria'
money_spent = budget * 0.7
info = f'Hotel - {money_spent:.2f}'
if season == 'summer':
money_spent = budget * 0.3
info = f'Camp - {money_spent:.2f}'
elif budget <= 1000:
destination = 'Balkans'
money_spent = budget * 0.8
info = f'Hotel - {money_spent:.2f}'
if season == 'summer':
money_spent = budget * 0.4
info = f'Camp - {money_spent:.2f}'
else:
destination = 'Europe'
money_spent = budget * 0.9
info = f'Hotel - {money_spent:.2f}'
print('Somewhere in ' + destination)
print(info) |
"""W3C Document Object Model implementation for Python.
The Python mapping of the Document Object Model is documented in <...>.
This package contains the following modules:
minidom -- A simple implementation of the Level 1 DOM with namespace
support added (based on the Level 2 specification).
"""
| """W3C Document Object Model implementation for Python.
The Python mapping of the Document Object Model is documented in <...>.
This package contains the following modules:
minidom -- A simple implementation of the Level 1 DOM with namespace
support added (based on the Level 2 specification).
""" |
FiboList , Flag = [0,1] , True
"""
This Function,
at first we create a array of -1's
to check fibonacci data's and store them in it.
Then each time we call the fibonacci function (Recursion).
Flag is for understanding that we need to create a new
arr or we call the function recursively.
"""
def fibonacci_1(n):
global Flag,FiboList
if Flag:
for i in range(n-1):
FiboList.append(-1)
Flag = False
if not Flag:
if FiboList[n] == -1:
FiboList[n] = fibonacci_1(n-1) + fibonacci_1(n-2)
return FiboList[n]
else:
return FiboList[n]
print(fibonacci_1(10))
| (fibo_list, flag) = ([0, 1], True)
"\nThis Function,\nat first we create a array of -1's \nto check fibonacci data's and store them in it.\nThen each time we call the fibonacci function (Recursion).\nFlag is for understanding that we need to create a new \narr or we call the function recursively.\n"
def fibonacci_1(n):
global Flag, FiboList
if Flag:
for i in range(n - 1):
FiboList.append(-1)
flag = False
if not Flag:
if FiboList[n] == -1:
FiboList[n] = fibonacci_1(n - 1) + fibonacci_1(n - 2)
return FiboList[n]
else:
return FiboList[n]
print(fibonacci_1(10)) |
def solution(movements):
horizontal, vertical = 0, 0
for move in movements:
direction, magnitude = move.split(' ')
if direction == "forward":
horizontal += int(magnitude)
elif direction == "down":
vertical += int(magnitude)
elif direction == "up":
vertical -= int(magnitude)
return horizontal * vertical
def solution2(movements):
horizontal, vertical, aim = 0, 0, 0
for move in movements:
direction, magnitude = move.split(' ')
magnitude = int(magnitude)
if direction == "forward":
horizontal += magnitude
vertical += (aim * magnitude)
elif direction == "down":
aim += int(magnitude)
elif direction == "up":
aim -= int(magnitude)
return horizontal * vertical
assert 150 == solution(["forward 5","down 5","forward 8","up 3","down 8","forward 2"])
assert 900 == solution2(["forward 5","down 5","forward 8","up 3","down 8","forward 2"])
def main():
with open('input.txt', 'r') as inp:
input_data = inp.readlines()
result1 = solution(input_data)
print(f"Part 1 answer: {result1}")
result2 = solution2(input_data)
print(f"Part 2 answer: {result2}")
main()
| def solution(movements):
(horizontal, vertical) = (0, 0)
for move in movements:
(direction, magnitude) = move.split(' ')
if direction == 'forward':
horizontal += int(magnitude)
elif direction == 'down':
vertical += int(magnitude)
elif direction == 'up':
vertical -= int(magnitude)
return horizontal * vertical
def solution2(movements):
(horizontal, vertical, aim) = (0, 0, 0)
for move in movements:
(direction, magnitude) = move.split(' ')
magnitude = int(magnitude)
if direction == 'forward':
horizontal += magnitude
vertical += aim * magnitude
elif direction == 'down':
aim += int(magnitude)
elif direction == 'up':
aim -= int(magnitude)
return horizontal * vertical
assert 150 == solution(['forward 5', 'down 5', 'forward 8', 'up 3', 'down 8', 'forward 2'])
assert 900 == solution2(['forward 5', 'down 5', 'forward 8', 'up 3', 'down 8', 'forward 2'])
def main():
with open('input.txt', 'r') as inp:
input_data = inp.readlines()
result1 = solution(input_data)
print(f'Part 1 answer: {result1}')
result2 = solution2(input_data)
print(f'Part 2 answer: {result2}')
main() |
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if k <= 0 or n < k:
return []
res_lst = []
def dfs(i, curr_lst):
if len(curr_lst) == k:
res_lst.append(curr_lst)
for value in range(i, n+1):
dfs(value+1, curr_lst+[value])
dfs(1, [])
return res_lst
# time complexity : O(n!)
# space complexity : O(k)
| class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if k <= 0 or n < k:
return []
res_lst = []
def dfs(i, curr_lst):
if len(curr_lst) == k:
res_lst.append(curr_lst)
for value in range(i, n + 1):
dfs(value + 1, curr_lst + [value])
dfs(1, [])
return res_lst |
# -*- coding: utf-8 -*-
__version__ = "0.2.4"
__title__ = "pygcgen"
__summary__ = "Automatic changelog generation"
__uri__ = "https://github.com/topic2k/pygcgen"
__author__ = "topic2k"
__email__ = "topic2k+pypi@gmail.com"
__license__ = "MIT"
__copyright__ = "2016-2018 %s" % __author__
| __version__ = '0.2.4'
__title__ = 'pygcgen'
__summary__ = 'Automatic changelog generation'
__uri__ = 'https://github.com/topic2k/pygcgen'
__author__ = 'topic2k'
__email__ = 'topic2k+pypi@gmail.com'
__license__ = 'MIT'
__copyright__ = '2016-2018 %s' % __author__ |
"""
Default status.html resource
"""
class StatusResource:
def on_get(self, req, resp):
pass | """
Default status.html resource
"""
class Statusresource:
def on_get(self, req, resp):
pass |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 13:02:55 2015
@author: magusverma
"""
def reached_limit(current, limit):
for i in range(len(current)):
if current[i] != limit[i]-1:
return False
return True
def increment(current, limit):
for i in range(len(current)-1,-1,-1):
if current[i] < limit[i]-1:
current[i]+=1
break
current[i] = 0
| """
Created on Fri Nov 13 13:02:55 2015
@author: magusverma
"""
def reached_limit(current, limit):
for i in range(len(current)):
if current[i] != limit[i] - 1:
return False
return True
def increment(current, limit):
for i in range(len(current) - 1, -1, -1):
if current[i] < limit[i] - 1:
current[i] += 1
break
current[i] = 0 |
class GraphEdgesMapping:
def __init__(self, first_dual_edges_mapping, second_dual_edges_mapping):
self._first = first_dual_edges_mapping
self._second = second_dual_edges_mapping
@property
def size(self):
return self._first.shape[0]
@property
def first(self):
return self._first
@property
def second(self):
return self._second
| class Graphedgesmapping:
def __init__(self, first_dual_edges_mapping, second_dual_edges_mapping):
self._first = first_dual_edges_mapping
self._second = second_dual_edges_mapping
@property
def size(self):
return self._first.shape[0]
@property
def first(self):
return self._first
@property
def second(self):
return self._second |
class Solution:
def binary_find_last(self, nums, target):
"""
this is find the last data
"""
low = 0
hight = len(nums)-1
first = True
while low <= hight:
mid = (hight-low)//2+low
if nums[mid] == target:
return mid
elif nums[mid] > target:
hight = mid-1
else:
low = mid+1
return -1
def searchRange(self, nums, target: int):
rul = self.binary_find_last(nums, target)
# left = 0
# right = len(nums)-1
# rul = [-1]*2
# while left <= right:
# mid = (right-left)//2+left
# if nums[mid] == target:
# rul[0] = mid
# elif nums[mid] > target:
# right = mid-1
# else:
# left = mid+1
# print(rul)
# rul = [-1]*2
# # find first data index
# left = 0
# right = len(nums)-1
# index = 0
# while left <= right:
# mid = (right-left)//2+left
# if target <= nums[mid]:
# right = mid-1
# index = mid
# else:
# left = mid+1
# # print(index)
# rul[0] = index
# if index == -1:
# return rul
# left = 0
# right = len(nums)-1
# index = 0
# target += 1
# while left <= right:
# mid = (right-left)//2+left
# if target <= nums[mid]:
# right = mid-1
# index = mid
# else:
# left = mid+1
# rul[1] = index
return rul
# def test_mid_find(nums, target):
# left = 0
# right = len(nums)-1
# index = -1
# while left <= right:
# mid = (right-left)//2+left
# if target <= nums[mid]:
# right = mid-1
# index = mid
# else:
# left = mid+1
# return index
# up method is wrong, for the fiorst data and unknow data for result 0
def binary_find(nums, target):
low = 0
hight = len(nums)-1
while low <= hight:
mid = (hight-low)//2+low
if nums[mid] == target:
return mid
elif nums[mid] > target:
hight = mid-1
else:
low = mid+1
return -1
if __name__ == "__main__":
nums = [5, 7, 7, 8, 8, 10]
target = 7
sol = Solution()
print(sol.searchRange(nums, target))
# print(test_mid_find(nums, target))
# print(binary_find(nums, target))
# it need complexity must be in the order of O(logn)
# so use midd find
| class Solution:
def binary_find_last(self, nums, target):
"""
this is find the last data
"""
low = 0
hight = len(nums) - 1
first = True
while low <= hight:
mid = (hight - low) // 2 + low
if nums[mid] == target:
return mid
elif nums[mid] > target:
hight = mid - 1
else:
low = mid + 1
return -1
def search_range(self, nums, target: int):
rul = self.binary_find_last(nums, target)
return rul
def binary_find(nums, target):
low = 0
hight = len(nums) - 1
while low <= hight:
mid = (hight - low) // 2 + low
if nums[mid] == target:
return mid
elif nums[mid] > target:
hight = mid - 1
else:
low = mid + 1
return -1
if __name__ == '__main__':
nums = [5, 7, 7, 8, 8, 10]
target = 7
sol = solution()
print(sol.searchRange(nums, target)) |
#!/usr/bin/env python3
data = open("in").read().split("\n\n")
data = list(map(lambda x: x.split("\n"), data))
for i in range(len(data)): # todo this is stupid
data[i] = list(filter(lambda x: x != '', data[i]))
tot = 0
tot2 = 0
for d in data:
a = set("".join(d))
tot += len(a)
tota = 0
for q in a:
if len(d) == len(list(filter(lambda x: x.count(q) > 0, d))):
tot2 += 1
print(tot)
print(tot2)
| data = open('in').read().split('\n\n')
data = list(map(lambda x: x.split('\n'), data))
for i in range(len(data)):
data[i] = list(filter(lambda x: x != '', data[i]))
tot = 0
tot2 = 0
for d in data:
a = set(''.join(d))
tot += len(a)
tota = 0
for q in a:
if len(d) == len(list(filter(lambda x: x.count(q) > 0, d))):
tot2 += 1
print(tot)
print(tot2) |
#operate with params
OP_PARAMS_PATH = "/data/params/"
def save_bool_param(param_name,param_value):
try:
real_param_value = 1 if param_value else 0
with open(OP_PARAMS_PATH+"/"+param_name, "w") as outfile:
outfile.write(f'{real_param_value}')
except IOError:
print("Failed to save "+param_name+" with value ",param_value)
def load_bool_param(param_name,param_def_value):
try:
with open(OP_PARAMS_PATH+"/"+param_name, 'r') as f:
for line in f:
value_saved = int(line)
#print("Reading Params ",param_name , "value", value_saved)
return True if value_saved == 1 else False
except IOError:
print("Initializing "+param_name+" with value ",param_def_value)
save_bool_param(param_name,param_def_value)
return param_def_value
def save_float_param(param_name,param_value):
try:
real_param_value = param_value * 1.0
with open(OP_PARAMS_PATH+"/"+param_name, "w") as outfile:
outfile.write(f'{real_param_value}')
except IOError:
print("Failed to save "+param_name+" with value ",real_param_value)
def load_float_param(param_name,param_def_value):
try:
with open(OP_PARAMS_PATH+"/"+param_name, 'r') as f:
for line in f:
value_saved = float(line)
#print("Reading Params ",param_name , "value", value_saved)
return value_saved * 1.0
except IOError:
print("Initializing "+param_name+" with value ",param_def_value*1.0)
save_float_param(param_name,param_def_value * 1.0)
return param_def_value * 1.0
| op_params_path = '/data/params/'
def save_bool_param(param_name, param_value):
try:
real_param_value = 1 if param_value else 0
with open(OP_PARAMS_PATH + '/' + param_name, 'w') as outfile:
outfile.write(f'{real_param_value}')
except IOError:
print('Failed to save ' + param_name + ' with value ', param_value)
def load_bool_param(param_name, param_def_value):
try:
with open(OP_PARAMS_PATH + '/' + param_name, 'r') as f:
for line in f:
value_saved = int(line)
return True if value_saved == 1 else False
except IOError:
print('Initializing ' + param_name + ' with value ', param_def_value)
save_bool_param(param_name, param_def_value)
return param_def_value
def save_float_param(param_name, param_value):
try:
real_param_value = param_value * 1.0
with open(OP_PARAMS_PATH + '/' + param_name, 'w') as outfile:
outfile.write(f'{real_param_value}')
except IOError:
print('Failed to save ' + param_name + ' with value ', real_param_value)
def load_float_param(param_name, param_def_value):
try:
with open(OP_PARAMS_PATH + '/' + param_name, 'r') as f:
for line in f:
value_saved = float(line)
return value_saved * 1.0
except IOError:
print('Initializing ' + param_name + ' with value ', param_def_value * 1.0)
save_float_param(param_name, param_def_value * 1.0)
return param_def_value * 1.0 |
# Hello! World!
print("Hello, World!")
# Learning Strings
my_string = "This is a string"
## Make string uppercase
my_string_upper = my_string.upper()
print(my_string_upper)
# Determine data type of string
print(type(my_string))
# Slicing strings [python is zero-based and starts at 0 and not 1]
print(my_string[0:4])
print(my_string[:1])
print(my_string[0:14])
| print('Hello, World!')
my_string = 'This is a string'
my_string_upper = my_string.upper()
print(my_string_upper)
print(type(my_string))
print(my_string[0:4])
print(my_string[:1])
print(my_string[0:14]) |
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
self.ret = []
self.counts = collections.Counter(candidates)
nums = [k for k in set(sorted(candidates))]
self.Backtrack(nums, target, [], 0)
return self.ret
def Backtrack(self, nums, target, combination, k):
if target == 0:
self.ret.append(combination)
return combination
for i in range(k, len(nums)):
if target - nums[i] < 0:
break
temp_sum = 0
temp_list = []
for j in range(self.counts[nums[i]]):
temp_sum += nums[i]
temp_list.append(nums[i])
if target - temp_sum < 0:
break
combination += temp_list
combination = self.Backtrack(nums, target - temp_sum, combination, i + 1)
combination = combination[:-len(temp_list)]
return combination
| class Solution:
def combination_sum2(self, candidates: List[int], target: int) -> List[List[int]]:
self.ret = []
self.counts = collections.Counter(candidates)
nums = [k for k in set(sorted(candidates))]
self.Backtrack(nums, target, [], 0)
return self.ret
def backtrack(self, nums, target, combination, k):
if target == 0:
self.ret.append(combination)
return combination
for i in range(k, len(nums)):
if target - nums[i] < 0:
break
temp_sum = 0
temp_list = []
for j in range(self.counts[nums[i]]):
temp_sum += nums[i]
temp_list.append(nums[i])
if target - temp_sum < 0:
break
combination += temp_list
combination = self.Backtrack(nums, target - temp_sum, combination, i + 1)
combination = combination[:-len(temp_list)]
return combination |
"""
Instructions:
1. Create a class named ReversedString that inherits from StringOperations class
2. Implement the function reverse
3. reverse function should be a one liner function that returns the reverse string to_be_reversed
4. Instantiate the class ReversedString
5. Print to show your function implementation result
"""
class StringOperations:
def reverse(self, *, to_be_reversed: str = None):
raise NotImplemented('This method need to be implemented')
class ReversedString(StringOperations):
def reverse(to_be_reversed):
print ("hello world"[::-1])
ob= ReversedString()
ob.reverse()
| """
Instructions:
1. Create a class named ReversedString that inherits from StringOperations class
2. Implement the function reverse
3. reverse function should be a one liner function that returns the reverse string to_be_reversed
4. Instantiate the class ReversedString
5. Print to show your function implementation result
"""
class Stringoperations:
def reverse(self, *, to_be_reversed: str=None):
raise not_implemented('This method need to be implemented')
class Reversedstring(StringOperations):
def reverse(to_be_reversed):
print('hello world'[::-1])
ob = reversed_string()
ob.reverse() |
# Function that detects cycle in a directed graph
def cycleCheck(vertices, adj):
visited = set()
ancestor = set()
for vertex in range(vertices):
if vertex not in visited:
if dfs(vertex, adj, visited, ancestor)==True:
return True
return False
# Recursive dfs function
def dfs(vertex, adj, visited, ancestor):
visited.add(vertex)
ancestor.add(vertex)
for neighbour in adj[vertex]:
if neighbour not in visited:
if dfs(neighbour, adj, visited, ancestor)==True:
return True
elif neighbour in ancestor:
return True
ancestor.remove(vertex)
return False
print('---------------------------------------------------------------------')
print('\tCheck if a cycle exists in a directed graph')
print('---------------------------------------------------------------------\n')
t = int(input("Enter the number of testcases: "))
for _ in range(t):
print('\n*************** Testcase', _+1, '***************\n')
vertices, edges = map(int, input("Enter number of vertices & edges: ").split())
# Create an adjacency list
adj = [[] for vertex in range(vertices)]
for edge in range(edges):
start, end = map(int, input("Enter edge: ").split())
adj[start].append(end)
if cycleCheck(vertices, adj) == True:
print('Cycle detected')
else:
print('No cycle detected') | def cycle_check(vertices, adj):
visited = set()
ancestor = set()
for vertex in range(vertices):
if vertex not in visited:
if dfs(vertex, adj, visited, ancestor) == True:
return True
return False
def dfs(vertex, adj, visited, ancestor):
visited.add(vertex)
ancestor.add(vertex)
for neighbour in adj[vertex]:
if neighbour not in visited:
if dfs(neighbour, adj, visited, ancestor) == True:
return True
elif neighbour in ancestor:
return True
ancestor.remove(vertex)
return False
print('---------------------------------------------------------------------')
print('\tCheck if a cycle exists in a directed graph')
print('---------------------------------------------------------------------\n')
t = int(input('Enter the number of testcases: '))
for _ in range(t):
print('\n*************** Testcase', _ + 1, '***************\n')
(vertices, edges) = map(int, input('Enter number of vertices & edges: ').split())
adj = [[] for vertex in range(vertices)]
for edge in range(edges):
(start, end) = map(int, input('Enter edge: ').split())
adj[start].append(end)
if cycle_check(vertices, adj) == True:
print('Cycle detected')
else:
print('No cycle detected') |
# DROP TABLES
USERS_TABLE = "users"
SONGS_TABLE = "songs"
ARTISTS_TABLE = "artists"
TIME_TABLE = "time"
SONGS_PLAY_TABLE = "songplays"
songplay_table_drop = f"DROP TABLE IF EXISTS {SONGS_PLAY_TABLE};"
user_table_drop = f"DROP TABLE IF EXISTS {USERS_TABLE};"
song_table_drop = f"DROP TABLE IF EXISTS {SONGS_TABLE};"
artist_table_drop = f"DROP TABLE IF EXISTS {ARTISTS_TABLE};"
time_table_drop = f"DROP TABLE IF EXISTS {TIME_TABLE};"
# CREATE TABLES
songplay_table_create = """
CREATE TABLE IF NOT EXISTS {} (
songplay_id SERIAL NOT NULL,
start_time bigint NOT NULL,
user_id int NOT NULL,
level text,
song_id text,
artist_id text,
session_id int,
location text,
user_agent text,
PRIMARY KEY(songplay_id),
FOREIGN KEY(user_id) REFERENCES {}(user_id),
FOREIGN KEY(song_id) REFERENCES {}(song_id),
FOREIGN KEY(artist_id) REFERENCES {}(artist_id),
FOREIGN KEY(start_time) REFERENCES {}(start_time)
);
""".format(
SONGS_PLAY_TABLE, USERS_TABLE, SONGS_TABLE, ARTISTS_TABLE, TIME_TABLE
)
user_table_create = """
CREATE TABLE IF NOT EXISTS {} (
user_id int NOT NULL,
first_name text,
last_name text,
gender text,
level text,
PRIMARY KEY(user_id)
);
""".format(
USERS_TABLE
)
song_table_create = """
CREATE TABLE IF NOT EXISTS {} (
song_id text NOT NULL,
title text,
artist_id text,
year int,
duration real,
PRIMARY KEY(song_id)
);
""".format(
SONGS_TABLE
)
artist_table_create = """
CREATE TABLE IF NOT EXISTS {} (
artist_id text NOT NULL,
name text,
location text,
latitude text,
longitude text,
PRIMARY KEY(artist_id)
);
""".format(
ARTISTS_TABLE
)
time_table_create = """
CREATE TABLE IF NOT EXISTS {} (
start_time bigint NOT NULL,
hour int,
day int,
week int,
month int,
year int,
weekday text,
PRIMARY KEY(start_time)
)
""".format(
TIME_TABLE
)
# INSERT RECORDS
songplay_table_insert = """
INSERT INTO {} (start_time, user_id, level, song_id, artist_id, session_id, location, user_agent)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT(songplay_id) DO NOTHING;
""".format(
SONGS_PLAY_TABLE
)
user_table_insert = """
INSERT INTO {} (user_id, first_name, last_name, gender, level)
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT(user_id) DO UPDATE SET level = excluded.level
""".format(
USERS_TABLE
)
song_table_insert = """
INSERT INTO {} (song_id, title, artist_id, year, duration)
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT(song_id) DO NOTHING;
""".format(
SONGS_TABLE
)
artist_table_insert = """
INSERT INTO {} (artist_id, name, location, latitude, longitude)
VALUES(%s, %s, %s, %s, %s)
ON CONFLICT(artist_id) DO NOTHING;
""".format(
ARTISTS_TABLE
)
time_table_insert = """
INSERT INTO {} (start_time, hour, day, week, month, year, weekday)
VALUES(%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT(start_time) DO NOTHING;
""".format(
TIME_TABLE
)
# FIND SONGS
song_select = """
SELECT songs.song_id, artists.artist_id
FROM songs JOIN artists ON songs.artist_id = artists.artist_id
WHERE songs.title = %s AND artists.name = %s AND songs.duration = %s;
"""
# QUERY LISTS
create_table_queries = [
user_table_create,
song_table_create,
artist_table_create,
time_table_create,
songplay_table_create,
]
drop_table_queries = [
user_table_drop,
song_table_drop,
artist_table_drop,
time_table_drop,
songplay_table_drop,
]
| users_table = 'users'
songs_table = 'songs'
artists_table = 'artists'
time_table = 'time'
songs_play_table = 'songplays'
songplay_table_drop = f'DROP TABLE IF EXISTS {SONGS_PLAY_TABLE};'
user_table_drop = f'DROP TABLE IF EXISTS {USERS_TABLE};'
song_table_drop = f'DROP TABLE IF EXISTS {SONGS_TABLE};'
artist_table_drop = f'DROP TABLE IF EXISTS {ARTISTS_TABLE};'
time_table_drop = f'DROP TABLE IF EXISTS {TIME_TABLE};'
songplay_table_create = '\nCREATE TABLE IF NOT EXISTS {} (\n songplay_id SERIAL NOT NULL,\n start_time bigint NOT NULL,\n user_id int NOT NULL,\n level text,\n song_id text,\n artist_id text,\n session_id int,\n location text,\n user_agent text,\n \n PRIMARY KEY(songplay_id),\n FOREIGN KEY(user_id) REFERENCES {}(user_id),\n FOREIGN KEY(song_id) REFERENCES {}(song_id),\n FOREIGN KEY(artist_id) REFERENCES {}(artist_id),\n FOREIGN KEY(start_time) REFERENCES {}(start_time)\n\n \n);\n'.format(SONGS_PLAY_TABLE, USERS_TABLE, SONGS_TABLE, ARTISTS_TABLE, TIME_TABLE)
user_table_create = '\nCREATE TABLE IF NOT EXISTS {} (\n user_id int NOT NULL,\n first_name text,\n last_name text,\n gender text,\n level text,\n\n PRIMARY KEY(user_id)\n);\n'.format(USERS_TABLE)
song_table_create = '\nCREATE TABLE IF NOT EXISTS {} (\n song_id text NOT NULL,\n title text,\n artist_id text,\n year int,\n duration real,\n\n PRIMARY KEY(song_id)\n);\n'.format(SONGS_TABLE)
artist_table_create = '\nCREATE TABLE IF NOT EXISTS {} (\n artist_id text NOT NULL,\n name text,\n location text,\n latitude text,\n longitude text,\n\n PRIMARY KEY(artist_id)\n);\n'.format(ARTISTS_TABLE)
time_table_create = '\nCREATE TABLE IF NOT EXISTS {} (\n start_time bigint NOT NULL,\n hour int,\n day int,\n week int,\n month int,\n year int,\n weekday text,\n\n PRIMARY KEY(start_time)\n)\n'.format(TIME_TABLE)
songplay_table_insert = '\nINSERT INTO {} (start_time, user_id, level, song_id, artist_id, session_id, location, user_agent) \nVALUES(%s, %s, %s, %s, %s, %s, %s, %s) \nON CONFLICT(songplay_id) DO NOTHING;\n'.format(SONGS_PLAY_TABLE)
user_table_insert = '\nINSERT INTO {} (user_id, first_name, last_name, gender, level) \nVALUES(%s, %s, %s, %s, %s)\nON CONFLICT(user_id) DO UPDATE SET level = excluded.level\n'.format(USERS_TABLE)
song_table_insert = '\nINSERT INTO {} (song_id, title, artist_id, year, duration) \nVALUES(%s, %s, %s, %s, %s)\nON CONFLICT(song_id) DO NOTHING;\n'.format(SONGS_TABLE)
artist_table_insert = '\nINSERT INTO {} (artist_id, name, location, latitude, longitude) \nVALUES(%s, %s, %s, %s, %s)\nON CONFLICT(artist_id) DO NOTHING;\n'.format(ARTISTS_TABLE)
time_table_insert = '\nINSERT INTO {} (start_time, hour, day, week, month, year, weekday) \nVALUES(%s, %s, %s, %s, %s, %s, %s)\nON CONFLICT(start_time) DO NOTHING;\n'.format(TIME_TABLE)
song_select = '\n\nSELECT songs.song_id, artists.artist_id \nFROM songs JOIN artists ON songs.artist_id = artists.artist_id\nWHERE songs.title = %s AND artists.name = %s AND songs.duration = %s;\n'
create_table_queries = [user_table_create, song_table_create, artist_table_create, time_table_create, songplay_table_create]
drop_table_queries = [user_table_drop, song_table_drop, artist_table_drop, time_table_drop, songplay_table_drop] |
class Config(object):
SECRET_KEY = "CantStopAddictedToTheShinDigChopTopHeSaysImGonnaWinBig"
HOST = "0a398d5f.ngrok.io"
SHOPIFY_CONFIG = {
'API_KEY': '<API KEY HERE>',
'API_SECRET': '<API SECRET HERE>',
'APP_HOME': 'http://' + HOST,
'CALLBACK_URL': 'http://' + HOST + '/install',
'REDIRECT_URI': 'http://' + HOST + '/connect',
'SCOPE': 'read_products, read_collection_listings'
}
| class Config(object):
secret_key = 'CantStopAddictedToTheShinDigChopTopHeSaysImGonnaWinBig'
host = '0a398d5f.ngrok.io'
shopify_config = {'API_KEY': '<API KEY HERE>', 'API_SECRET': '<API SECRET HERE>', 'APP_HOME': 'http://' + HOST, 'CALLBACK_URL': 'http://' + HOST + '/install', 'REDIRECT_URI': 'http://' + HOST + '/connect', 'SCOPE': 'read_products, read_collection_listings'} |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__version__ = "3.0.0"
__author__ = "Amir Zeldes"
__copyright__ = "Copyright 2015-2019, Amir Zeldes"
__license__ = "Apache 2.0 License"
| __version__ = '3.0.0'
__author__ = 'Amir Zeldes'
__copyright__ = 'Copyright 2015-2019, Amir Zeldes'
__license__ = 'Apache 2.0 License' |
DEV = {
"SERVER_NAME": "dev-api.materialsdatafacility.org",
"API_LOG_FILE": "deva.log",
"PROCESS_LOG_FILE": "devp.log",
"LOG_LEVEL": "DEBUG",
"FORM_URL": "https://connect.materialsdatafacility.org/",
"TRANSFER_DEADLINE": 3 * 60 * 60, # 3 hours, in seconds
"INGEST_URL": "https://dev-api.materialsdatafacility.org/ingest",
"INGEST_INDEX": "mdf-dev",
"INGEST_TEST_INDEX": "mdf-dev",
"LOCAL_EP": "ca7550ad-55a9-4762-b558-8f2b15049039",
# Disable backups
"BACKUP_EP": False,
# Petrel
# "BACKUP_EP": "e38ee745-6d04-11e5-ba46-22000b92c6ec",
# "BACKUP_PATH": "/MDF/mdf_connect/dev/data/",
# "BACKUP_HOST": "https://e38ee745-6d04-11e5-ba46-22000b92c6ec.e.globus.org",
# "BACKUP_FEEDSTOCK": "/MDF/mdf_connect/dev/feedstock/",
# NCSA
# "BACKUP_EP": "82f1b5c6-6e9b-11e5-ba47-22000b92c6ec",
"BACKUP_PATH": "/mdf_connect/dev/data/",
"BACKUP_HOST": "https://data.materialsdatafacility.org",
"BACKUP_FEEDSTOCK": "/mdf_connect/dev/feedstock/",
"DEFAULT_CLEANUP": True,
"FINAL_CLEANUP": True,
"DEFAULT_DOI_TEST": True,
"NUM_DOI_CHARS": 2, # Characters per section
"NUM_DOI_SECTIONS": 5,
"DEFAULT_PUBLISH_COLLECTION": 35,
"TEST_PUBLISH_COLLECTION": 35,
"DEFAULT_CITRINATION_PUBLIC": False,
"DEFAULT_MRR_TEST": True,
"SQS_QUEUE": "mdfc_dev1.fifo",
"SQS_GROUP_ID": "mdf_connect_dev",
"DYNAMO_STATUS_TABLE": "dev-status-alpha-2",
"DYNAMO_CURATION_TABLE": "dev-curation-alpha-1"
}
| dev = {'SERVER_NAME': 'dev-api.materialsdatafacility.org', 'API_LOG_FILE': 'deva.log', 'PROCESS_LOG_FILE': 'devp.log', 'LOG_LEVEL': 'DEBUG', 'FORM_URL': 'https://connect.materialsdatafacility.org/', 'TRANSFER_DEADLINE': 3 * 60 * 60, 'INGEST_URL': 'https://dev-api.materialsdatafacility.org/ingest', 'INGEST_INDEX': 'mdf-dev', 'INGEST_TEST_INDEX': 'mdf-dev', 'LOCAL_EP': 'ca7550ad-55a9-4762-b558-8f2b15049039', 'BACKUP_EP': False, 'BACKUP_PATH': '/mdf_connect/dev/data/', 'BACKUP_HOST': 'https://data.materialsdatafacility.org', 'BACKUP_FEEDSTOCK': '/mdf_connect/dev/feedstock/', 'DEFAULT_CLEANUP': True, 'FINAL_CLEANUP': True, 'DEFAULT_DOI_TEST': True, 'NUM_DOI_CHARS': 2, 'NUM_DOI_SECTIONS': 5, 'DEFAULT_PUBLISH_COLLECTION': 35, 'TEST_PUBLISH_COLLECTION': 35, 'DEFAULT_CITRINATION_PUBLIC': False, 'DEFAULT_MRR_TEST': True, 'SQS_QUEUE': 'mdfc_dev1.fifo', 'SQS_GROUP_ID': 'mdf_connect_dev', 'DYNAMO_STATUS_TABLE': 'dev-status-alpha-2', 'DYNAMO_CURATION_TABLE': 'dev-curation-alpha-1'} |
inputDoc = open("input.txt")
docLines = inputDoc.readlines()
inputDoc.close()
# PART 1
# Find two numbers that add up to 2020 and multiply them
correct1 = []
for line in docLines:
line = int(line.replace("\n", ""))
for lineTwo in docLines:
lineTwo = int(lineTwo.replace("\n", ""))
if line + lineTwo == 2020:
correct1 = [line, lineTwo]
break
if len(correct1) > 0:
break
print(correct1[0] * correct1[1]) # 514579
# PART 2
# Find 3 numbers that add to 2020
correct2 = []
for line in docLines:
line = int(line.replace("\n", ""))
for lineTwo in docLines:
lineTwo = int(lineTwo.replace("\n", ""))
for lineThree in docLines:
lineThree = int(lineThree.replace("\n", ""))
if line + lineTwo + lineThree == 2020:
correct2 = [line, lineTwo, lineThree]
break
if len(correct2) > 0:
break
if len(correct2) > 0:
break
print(correct2[0] * correct2[1] * correct2[2]) # 42275090
# print(next(map(lambda a: a[0] * a[1], [list(map(lambda a: int(a), filter(lambda a: [int(b) for b in docLines if int(a) + int(b) == 2020], docLines)))])))
| input_doc = open('input.txt')
doc_lines = inputDoc.readlines()
inputDoc.close()
correct1 = []
for line in docLines:
line = int(line.replace('\n', ''))
for line_two in docLines:
line_two = int(lineTwo.replace('\n', ''))
if line + lineTwo == 2020:
correct1 = [line, lineTwo]
break
if len(correct1) > 0:
break
print(correct1[0] * correct1[1])
correct2 = []
for line in docLines:
line = int(line.replace('\n', ''))
for line_two in docLines:
line_two = int(lineTwo.replace('\n', ''))
for line_three in docLines:
line_three = int(lineThree.replace('\n', ''))
if line + lineTwo + lineThree == 2020:
correct2 = [line, lineTwo, lineThree]
break
if len(correct2) > 0:
break
if len(correct2) > 0:
break
print(correct2[0] * correct2[1] * correct2[2]) |
"""Contains the class for a problem instance."""
class AgglutinatingRolls():
"""Define a class for a problem instance."""
def __init__(self, instance: dict):
"""Initialize an object."""
self.rolls_a = instance.get('rolls_a', [])
self.rolls_b = instance.get('rolls_a', [])
# costs = [agglutinate, new_roll, short_roll, unused_roll]
self.costs = instance.get('costs', [5, 8, 7, 7])
self.max_length = instance.get('max_length', 10000)
self.max_number_of_rolls = instance.get('max_number_of_rolls', 10)
| """Contains the class for a problem instance."""
class Agglutinatingrolls:
"""Define a class for a problem instance."""
def __init__(self, instance: dict):
"""Initialize an object."""
self.rolls_a = instance.get('rolls_a', [])
self.rolls_b = instance.get('rolls_a', [])
self.costs = instance.get('costs', [5, 8, 7, 7])
self.max_length = instance.get('max_length', 10000)
self.max_number_of_rolls = instance.get('max_number_of_rolls', 10) |
class InvalidApiKeyError(Exception):
def __init__(self):
self.message = "The API key you inserted isn't valid"
class InvalidCityNameError(Exception):
def __init__(self):
self.message = "Couldn't find any city with this name or code. Please check again."
| class Invalidapikeyerror(Exception):
def __init__(self):
self.message = "The API key you inserted isn't valid"
class Invalidcitynameerror(Exception):
def __init__(self):
self.message = "Couldn't find any city with this name or code. Please check again." |
#
# PySNMP MIB module GWPAGERMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GWPAGERMIB
# Produced by pysmi-0.3.4 at Wed May 1 13:20:45 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, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
MibIdentifier, TimeTicks, ObjectIdentity, IpAddress, iso, Integer32, enterprises, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, NotificationType, NotificationType, Gauge32, Bits, Counter32, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "TimeTicks", "ObjectIdentity", "IpAddress", "iso", "Integer32", "enterprises", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "NotificationType", "NotificationType", "Gauge32", "Bits", "Counter32", "ModuleIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
novell = MibIdentifier((1, 3, 6, 1, 4, 1, 23))
gateways = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2))
gwPAGER = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 43))
gwPAGERInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 43, 1))
gwPAGERTrapInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 23, 2, 43, 2))
gwPAGERGatewayName = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGERGatewayName.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERGatewayName.setDescription('The GroupWise PAGER Gateway name.')
gwPAGERUptime = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 2), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGERUptime.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERUptime.setDescription('Uptime of the GroupWise PAGER Gateway.')
gwPAGERGroupWiseLink = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGERGroupWiseLink.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERGroupWiseLink.setDescription('GroupWise PAGER Gateway Link: UP or DOWN')
gwPAGERFrgnLink = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGERFrgnLink.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERFrgnLink.setDescription('GroupWise PAGER Gateway Foreign Link: UP or DOWN')
gwPAGEROutBytes = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGEROutBytes.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGEROutBytes.setDescription('The number of message bytes sent to GroupWise PAGER.')
gwPAGERInBytes = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGERInBytes.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERInBytes.setDescription('The number of message bytes received from GroupWise PAGER.')
gwPAGEROutMsgs = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGEROutMsgs.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGEROutMsgs.setDescription('The number of messages sent to GroupWise PAGER.')
gwPAGERInMsgs = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGERInMsgs.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERInMsgs.setDescription('The number of messages received from PAGER.')
gwPAGEROutStatuses = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGEROutStatuses.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGEROutStatuses.setDescription('The number of statuses sent to PAGER.')
gwPAGERInStatuses = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGERInStatuses.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERInStatuses.setDescription('The number of statuses received from PAGER.')
gwPAGEROutErrors = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGEROutErrors.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGEROutErrors.setDescription('The number of failed transfers to PAGER.')
gwPAGERInErrors = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gwPAGERInErrors.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERInErrors.setDescription('The number of failed transfers from PAGER.')
gwPAGERTrapTime = MibScalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 2, 1), Integer32())
if mibBuilder.loadTexts: gwPAGERTrapTime.setStatus('mandatory')
if mibBuilder.loadTexts: gwPAGERTrapTime.setDescription('The time the trap occurred. Seconds since Jan 1, 1970 (GMT)')
gwPAGERStartTrap = NotificationType((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0,1)).setObjects(("GWPAGERMIB", "gwPAGERTrapTime"), ("GWPAGERMIB", "gwPAGERGatewayName"))
if mibBuilder.loadTexts: gwPAGERStartTrap.setDescription('GroupWise PAGER Gateway start.')
gwPAGERStopTrap = NotificationType((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0,2)).setObjects(("GWPAGERMIB", "gwPAGERTrapTime"), ("GWPAGERMIB", "gwPAGERGatewayName"))
if mibBuilder.loadTexts: gwPAGERStopTrap.setDescription('GroupWise PAGER Gateway stop.')
gwPAGERRestartTrap = NotificationType((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0,3)).setObjects(("GWPAGERMIB", "gwPAGERTrapTime"), ("GWPAGERMIB", "gwPAGERGatewayName"))
if mibBuilder.loadTexts: gwPAGERRestartTrap.setDescription('GroupWise PAGER Gateway restart.')
gwPAGERGroupWiseLinkTrap = NotificationType((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0,4)).setObjects(("GWPAGERMIB", "gwPAGERTrapTime"), ("GWPAGERMIB", "gwPAGERGatewayName"))
if mibBuilder.loadTexts: gwPAGERGroupWiseLinkTrap.setDescription('GroupWise Link lost by GroupWise PAGER Gateway')
gwPAGERFgnLinkTrap = NotificationType((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0,5)).setObjects(("GWPAGERMIB", "gwPAGERTrapTime"), ("GWPAGERMIB", "gwPAGERGatewayName"))
if mibBuilder.loadTexts: gwPAGERFgnLinkTrap.setDescription('PAGER Link lost by GroupWise PAGER Gateway')
mibBuilder.exportSymbols("GWPAGERMIB", gwPAGERTrapInfo=gwPAGERTrapInfo, gwPAGERRestartTrap=gwPAGERRestartTrap, gwPAGERInBytes=gwPAGERInBytes, gwPAGERInfo=gwPAGERInfo, gwPAGERGroupWiseLinkTrap=gwPAGERGroupWiseLinkTrap, novell=novell, gwPAGERInMsgs=gwPAGERInMsgs, gwPAGERTrapTime=gwPAGERTrapTime, gwPAGERInErrors=gwPAGERInErrors, gwPAGERFrgnLink=gwPAGERFrgnLink, gwPAGERUptime=gwPAGERUptime, gwPAGEROutBytes=gwPAGEROutBytes, gwPAGERStartTrap=gwPAGERStartTrap, gwPAGEROutErrors=gwPAGEROutErrors, gwPAGERGatewayName=gwPAGERGatewayName, gwPAGEROutMsgs=gwPAGEROutMsgs, gwPAGER=gwPAGER, gwPAGERGroupWiseLink=gwPAGERGroupWiseLink, gwPAGERStopTrap=gwPAGERStopTrap, gwPAGERFgnLinkTrap=gwPAGERFgnLinkTrap, gateways=gateways, gwPAGERInStatuses=gwPAGERInStatuses, gwPAGEROutStatuses=gwPAGEROutStatuses)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(mib_identifier, time_ticks, object_identity, ip_address, iso, integer32, enterprises, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, notification_type, notification_type, gauge32, bits, counter32, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'TimeTicks', 'ObjectIdentity', 'IpAddress', 'iso', 'Integer32', 'enterprises', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'NotificationType', 'NotificationType', 'Gauge32', 'Bits', 'Counter32', 'ModuleIdentity')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
novell = mib_identifier((1, 3, 6, 1, 4, 1, 23))
gateways = mib_identifier((1, 3, 6, 1, 4, 1, 23, 2))
gw_pager = mib_identifier((1, 3, 6, 1, 4, 1, 23, 2, 43))
gw_pager_info = mib_identifier((1, 3, 6, 1, 4, 1, 23, 2, 43, 1))
gw_pager_trap_info = mib_identifier((1, 3, 6, 1, 4, 1, 23, 2, 43, 2))
gw_pager_gateway_name = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGERGatewayName.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERGatewayName.setDescription('The GroupWise PAGER Gateway name.')
gw_pager_uptime = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 2), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGERUptime.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERUptime.setDescription('Uptime of the GroupWise PAGER Gateway.')
gw_pager_group_wise_link = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 5))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGERGroupWiseLink.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERGroupWiseLink.setDescription('GroupWise PAGER Gateway Link: UP or DOWN')
gw_pager_frgn_link = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 5))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGERFrgnLink.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERFrgnLink.setDescription('GroupWise PAGER Gateway Foreign Link: UP or DOWN')
gw_pager_out_bytes = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGEROutBytes.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGEROutBytes.setDescription('The number of message bytes sent to GroupWise PAGER.')
gw_pager_in_bytes = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGERInBytes.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERInBytes.setDescription('The number of message bytes received from GroupWise PAGER.')
gw_pager_out_msgs = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGEROutMsgs.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGEROutMsgs.setDescription('The number of messages sent to GroupWise PAGER.')
gw_pager_in_msgs = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGERInMsgs.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERInMsgs.setDescription('The number of messages received from PAGER.')
gw_pager_out_statuses = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 9), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGEROutStatuses.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGEROutStatuses.setDescription('The number of statuses sent to PAGER.')
gw_pager_in_statuses = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 10), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGERInStatuses.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERInStatuses.setDescription('The number of statuses received from PAGER.')
gw_pager_out_errors = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 11), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGEROutErrors.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGEROutErrors.setDescription('The number of failed transfers to PAGER.')
gw_pager_in_errors = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 1, 12), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gwPAGERInErrors.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERInErrors.setDescription('The number of failed transfers from PAGER.')
gw_pager_trap_time = mib_scalar((1, 3, 6, 1, 4, 1, 23, 2, 43, 2, 1), integer32())
if mibBuilder.loadTexts:
gwPAGERTrapTime.setStatus('mandatory')
if mibBuilder.loadTexts:
gwPAGERTrapTime.setDescription('The time the trap occurred. Seconds since Jan 1, 1970 (GMT)')
gw_pager_start_trap = notification_type((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0, 1)).setObjects(('GWPAGERMIB', 'gwPAGERTrapTime'), ('GWPAGERMIB', 'gwPAGERGatewayName'))
if mibBuilder.loadTexts:
gwPAGERStartTrap.setDescription('GroupWise PAGER Gateway start.')
gw_pager_stop_trap = notification_type((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0, 2)).setObjects(('GWPAGERMIB', 'gwPAGERTrapTime'), ('GWPAGERMIB', 'gwPAGERGatewayName'))
if mibBuilder.loadTexts:
gwPAGERStopTrap.setDescription('GroupWise PAGER Gateway stop.')
gw_pager_restart_trap = notification_type((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0, 3)).setObjects(('GWPAGERMIB', 'gwPAGERTrapTime'), ('GWPAGERMIB', 'gwPAGERGatewayName'))
if mibBuilder.loadTexts:
gwPAGERRestartTrap.setDescription('GroupWise PAGER Gateway restart.')
gw_pager_group_wise_link_trap = notification_type((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0, 4)).setObjects(('GWPAGERMIB', 'gwPAGERTrapTime'), ('GWPAGERMIB', 'gwPAGERGatewayName'))
if mibBuilder.loadTexts:
gwPAGERGroupWiseLinkTrap.setDescription('GroupWise Link lost by GroupWise PAGER Gateway')
gw_pager_fgn_link_trap = notification_type((1, 3, 6, 1, 4, 1, 23, 2, 43, 1) + (0, 5)).setObjects(('GWPAGERMIB', 'gwPAGERTrapTime'), ('GWPAGERMIB', 'gwPAGERGatewayName'))
if mibBuilder.loadTexts:
gwPAGERFgnLinkTrap.setDescription('PAGER Link lost by GroupWise PAGER Gateway')
mibBuilder.exportSymbols('GWPAGERMIB', gwPAGERTrapInfo=gwPAGERTrapInfo, gwPAGERRestartTrap=gwPAGERRestartTrap, gwPAGERInBytes=gwPAGERInBytes, gwPAGERInfo=gwPAGERInfo, gwPAGERGroupWiseLinkTrap=gwPAGERGroupWiseLinkTrap, novell=novell, gwPAGERInMsgs=gwPAGERInMsgs, gwPAGERTrapTime=gwPAGERTrapTime, gwPAGERInErrors=gwPAGERInErrors, gwPAGERFrgnLink=gwPAGERFrgnLink, gwPAGERUptime=gwPAGERUptime, gwPAGEROutBytes=gwPAGEROutBytes, gwPAGERStartTrap=gwPAGERStartTrap, gwPAGEROutErrors=gwPAGEROutErrors, gwPAGERGatewayName=gwPAGERGatewayName, gwPAGEROutMsgs=gwPAGEROutMsgs, gwPAGER=gwPAGER, gwPAGERGroupWiseLink=gwPAGERGroupWiseLink, gwPAGERStopTrap=gwPAGERStopTrap, gwPAGERFgnLinkTrap=gwPAGERFgnLinkTrap, gateways=gateways, gwPAGERInStatuses=gwPAGERInStatuses, gwPAGEROutStatuses=gwPAGEROutStatuses) |
a = input()
b = input()
c = input()
print(a[0] + b[1] + c[2])
| a = input()
b = input()
c = input()
print(a[0] + b[1] + c[2]) |
def evalRPN(tokens: List[str]) -> int:
stack = [] #make a stack to hold the numberes and result calculation
for char in tokens: #iterate through the tokens
if char not in "+*-/": #if token is not an operator then it is a number so we add to stack
stack.append(int(char))
else: #if it is an operator then we pop the last two values from the stack and the left + right
r,l = stack.pop(),stack.pop()
if char == "*":
stack.append(l*r)
elif char == "/":
stack.append(int(float(l)/r))
elif char == "+":
stack.append(l+r)
elif char == "-":
stack.append(l-r)
return stack [-1]
#explanation : https://www.youtube.com/watch?v=3wGTlsLnZE4&list=PLLOxZwkBK52Akgqf4oSWPOQO9ROWS_9rc&index=20
| def eval_rpn(tokens: List[str]) -> int:
stack = []
for char in tokens:
if char not in '+*-/':
stack.append(int(char))
else:
(r, l) = (stack.pop(), stack.pop())
if char == '*':
stack.append(l * r)
elif char == '/':
stack.append(int(float(l) / r))
elif char == '+':
stack.append(l + r)
elif char == '-':
stack.append(l - r)
return stack[-1] |
# Lv-677.PythonCore
name_que = input("Hello. \nWhat is your name? \n")
print ("Hello, ", name_que)
age_que = input("How old are you? \n")
print ("Your age is: ", age_que)
live_que = input(f"Where do u live {name_que}? \n")
print("You live in ", live_que) | name_que = input('Hello. \nWhat is your name? \n')
print('Hello, ', name_que)
age_que = input('How old are you? \n')
print('Your age is: ', age_que)
live_que = input(f'Where do u live {name_que}? \n')
print('You live in ', live_que) |
# Royals and suits
jack = 11
queen = 12
king = 13
ace = 14
spades = 's'
clubs = 'c'
hearts = 'h'
diamonds = 'd'
ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace]
suits = [spades, clubs, hearts, diamonds]
# Hands
straight_flush = 'Straight flush'
quads = 'Four of a kind'
full_house = 'Full house'
flush = 'Flush'
straight = 'Straight'
trips = 'Three of a kind'
two_pair = 'Two pair'
pair = 'Pair'
high_card = 'High card'
| jack = 11
queen = 12
king = 13
ace = 14
spades = 's'
clubs = 'c'
hearts = 'h'
diamonds = 'd'
ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace]
suits = [spades, clubs, hearts, diamonds]
straight_flush = 'Straight flush'
quads = 'Four of a kind'
full_house = 'Full house'
flush = 'Flush'
straight = 'Straight'
trips = 'Three of a kind'
two_pair = 'Two pair'
pair = 'Pair'
high_card = 'High card' |
s = ''
while True:
try:
s+= input()
except:
break
r = ['a', s.count('a')]
for i in range(98, 123):
n = s.count(chr(i))
if n > r[1]:
r[0] = chr(i)
r[1] = n
elif n == r[1]:
r[0] += chr(i)
print(r[0])
| s = ''
while True:
try:
s += input()
except:
break
r = ['a', s.count('a')]
for i in range(98, 123):
n = s.count(chr(i))
if n > r[1]:
r[0] = chr(i)
r[1] = n
elif n == r[1]:
r[0] += chr(i)
print(r[0]) |
def Run(filepath):
with open(filepath) as input:
measurements = list(map(int, input.read().split('\n')))
print('Day 1')
Part1(measurements)
Part2(measurements)
def Part1(measurements):
increases = 0
previousDepth = None
for depth in measurements:
#Increment if this isn't the first measurement and the depth has increased
if previousDepth != None and depth > previousDepth:
increases += 1
previousDepth = depth
print('Part 1: ' + str(increases))
#The result should be 1791
def Part2(measurements):
increases = 0
previousSum = None
#Run as long as there are complete sets of 3 measurements to add together
for index in range(len(measurements)-2):
measurement1 = measurements[index]
measurement2 = measurements[index+1]
measurement3 = measurements[index+2]
currentSum = measurement1 + measurement2 + measurement3
#Increment if this isn't the first set of measurements and the sum has increased
if previousSum != None and currentSum > previousSum:
increases += 1
previousSum = currentSum
print('Part 2: ' + str(increases))
#The result should be 1822 | def run(filepath):
with open(filepath) as input:
measurements = list(map(int, input.read().split('\n')))
print('Day 1')
part1(measurements)
part2(measurements)
def part1(measurements):
increases = 0
previous_depth = None
for depth in measurements:
if previousDepth != None and depth > previousDepth:
increases += 1
previous_depth = depth
print('Part 1: ' + str(increases))
def part2(measurements):
increases = 0
previous_sum = None
for index in range(len(measurements) - 2):
measurement1 = measurements[index]
measurement2 = measurements[index + 1]
measurement3 = measurements[index + 2]
current_sum = measurement1 + measurement2 + measurement3
if previousSum != None and currentSum > previousSum:
increases += 1
previous_sum = currentSum
print('Part 2: ' + str(increases)) |
"""
O(n^min(k, n-k))
"""
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
self.dfs(list(range(1, n + 1)), k, [], result)
return result
def dfs(self, arr, k, path, result):
if k < 0:
return
if k == 0:
result.append(path)
for i in range(len(arr)):
self.dfs(arr[i + 1 :], k - 1, path + [arr[i]], result)
| """
O(n^min(k, n-k))
"""
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
self.dfs(list(range(1, n + 1)), k, [], result)
return result
def dfs(self, arr, k, path, result):
if k < 0:
return
if k == 0:
result.append(path)
for i in range(len(arr)):
self.dfs(arr[i + 1:], k - 1, path + [arr[i]], result) |
my_email = 'twitterlehigh2@gmail.com'
my_password = 'kB5-LXX-T7w-TLG'
# my_email = 'twitterlehigh@gmail.com'
# my_password = 'Lehigh131016'
| my_email = 'twitterlehigh2@gmail.com'
my_password = 'kB5-LXX-T7w-TLG' |
'''
Given an integer, write a function that reverses
the bits (in binary) and returns the integer result.
Understand:
417 --> 267
167 --> 417
0 --> 0
Plan:
Use bin() to convert the binary into a string.
Use bracket indexing to reverse the order.
Use int() to convert it into a decimal number.
'''
def csReverseIntegerBits(n):
str_n = bin(n).replace("0b","")
rev_str_n = str_n[::-1]
int_n = int(rev_str_n, 2)
return int_n
#Author's Answer
def csReverseIntegerBits(n):
return int(bin(n)[:1:-1],2)
'''
Given a binary string (ASCII encoded), write a function
that returns the equivalent decoded text.
Every eight bits in the binary string represents one
character on the ASCII table.
Understand:
csBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda"
"" --> ""
Plan:
Split the string into a list of every 8 digits.
Convert each 8 digit into its ASCII character.
Join the string.
'''
def csBinaryToASCII(binary):
str_list = []
for i in range(0, len(binary), 8):
str_list.append(int(binary[i:i+8], 2))
chr_binary = []
for str_ in str_list:
chr_binary.append(chr(str_))
return "".join(chr_binary)
#Author's Answer
def csBinaryToASCII(binary):
return "".join( [ chr(int(binary[i: i+8], 2)) for i in range(0, len(binary), 8) ] )
'''
Given a number, write a function that converts
that number into a string that contains "raindrop sounds"
corresponding to certain potential factors. A factor
is a number that evenly divides into another number,
leaving no remainder. The simplest way to test if one
number is a factor of another is to use the modulo operator.
Here are the rules for csRaindrop. If the input number:
has 3 as a factor, add "Pling" to the result.
has 5 as a factor, add "Plang" to the result.
has 7 as a factor, add "Plong" to the result.
does not have any of 3, 5, or 7 as a factor, the result
should be the digits of the input number.
Understand:
28 --> "Plong"
30 --> "PlingPlang"
34 --> "34"
Plan:
Using if statements, check if the number has a factor
of 3, 5, or 7. If so, append an empty string with Pling,
Plang, or Plong. Else, return the number as the string.
'''
def csRaindrops(number):
result = ""
if number % 3 == 0:
result += "Pling"
if number % 5 == 0:
result += "Plang"
if number % 7 == 0:
result += "Plong"
if result == "":
result += str(number)
return result
#Author's Answer
def csRaindrops(number):
result = ''
result += "Pling" * (number % 3 == 0)
result += "Plang" * (number % 5 == 0)
result += "Plong" * (number % 7 == 0)
return result or str(number)
| """
Given an integer, write a function that reverses
the bits (in binary) and returns the integer result.
Understand:
417 --> 267
167 --> 417
0 --> 0
Plan:
Use bin() to convert the binary into a string.
Use bracket indexing to reverse the order.
Use int() to convert it into a decimal number.
"""
def cs_reverse_integer_bits(n):
str_n = bin(n).replace('0b', '')
rev_str_n = str_n[::-1]
int_n = int(rev_str_n, 2)
return int_n
def cs_reverse_integer_bits(n):
return int(bin(n)[:1:-1], 2)
'\nGiven a binary string (ASCII encoded), write a function \nthat returns the equivalent decoded text.\n\nEvery eight bits in the binary string represents one \ncharacter on the ASCII table.\n\nUnderstand:\ncsBinaryToASCII("011011000110000101101101011000100110010001100001") -> "lambda"\n"" --> ""\n\nPlan:\nSplit the string into a list of every 8 digits. \nConvert each 8 digit into its ASCII character. \nJoin the string.\n'
def cs_binary_to_ascii(binary):
str_list = []
for i in range(0, len(binary), 8):
str_list.append(int(binary[i:i + 8], 2))
chr_binary = []
for str_ in str_list:
chr_binary.append(chr(str_))
return ''.join(chr_binary)
def cs_binary_to_ascii(binary):
return ''.join([chr(int(binary[i:i + 8], 2)) for i in range(0, len(binary), 8)])
'\nGiven a number, write a function that converts \nthat number into a string that contains "raindrop sounds" \ncorresponding to certain potential factors. A factor \nis a number that evenly divides into another number, \nleaving no remainder. The simplest way to test if one \nnumber is a factor of another is to use the modulo operator.\n\nHere are the rules for csRaindrop. If the input number:\n\nhas 3 as a factor, add "Pling" to the result.\nhas 5 as a factor, add "Plang" to the result.\nhas 7 as a factor, add "Plong" to the result.\ndoes not have any of 3, 5, or 7 as a factor, the result \nshould be the digits of the input number.\n\nUnderstand:\n28 --> "Plong"\n30 --> "PlingPlang"\n34 --> "34"\n\nPlan:\nUsing if statements, check if the number has a factor \nof 3, 5, or 7. If so, append an empty string with Pling, \nPlang, or Plong. Else, return the number as the string.\n'
def cs_raindrops(number):
result = ''
if number % 3 == 0:
result += 'Pling'
if number % 5 == 0:
result += 'Plang'
if number % 7 == 0:
result += 'Plong'
if result == '':
result += str(number)
return result
def cs_raindrops(number):
result = ''
result += 'Pling' * (number % 3 == 0)
result += 'Plang' * (number % 5 == 0)
result += 'Plong' * (number % 7 == 0)
return result or str(number) |
class Solution:
def solve(self, board: List[List[str]]) -> None:
m, n = len(board), len(board and board[0])
def explore(i, j):
board[i][j] = "S"
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < m and 0 <= y < n and board[x][y] == "O":
explore(x, y)
for i in range(max(m, n)):
if i < m and board[i][0] == "O":
explore(i, 0)
if i < m and board[i][n - 1] == "O":
explore(i, n - 1)
if i < n and board[0][i] == "O":
explore(0, i)
if i < n and board[m - 1][i] == "O":
explore(m - 1, i)
for i in range(m):
for j in range(n):
if board[i][j] == "S":
board[i][j] = "O"
elif board[i][j] == "O":
board[i][j] = "X"
| class Solution:
def solve(self, board: List[List[str]]) -> None:
(m, n) = (len(board), len(board and board[0]))
def explore(i, j):
board[i][j] = 'S'
for (x, y) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < m and 0 <= y < n and (board[x][y] == 'O'):
explore(x, y)
for i in range(max(m, n)):
if i < m and board[i][0] == 'O':
explore(i, 0)
if i < m and board[i][n - 1] == 'O':
explore(i, n - 1)
if i < n and board[0][i] == 'O':
explore(0, i)
if i < n and board[m - 1][i] == 'O':
explore(m - 1, i)
for i in range(m):
for j in range(n):
if board[i][j] == 'S':
board[i][j] = 'O'
elif board[i][j] == 'O':
board[i][j] = 'X' |
# -*- coding: utf-8 -*-
"""
To-Do application
"""
def add(todos):
"""
Add a task
"""
pass
def delete(todos, index=None):
"""
Delete one or all tasks
"""
pass
def get_printable_todos(todos):
"""
Get formatted tasks
"""
pass
def toggle_done(todos, index):
"""
Toggle a task
"""
pass
def view(todos, index):
"""
Print tasks
"""
print('\nTo-Do list')
print('=' * 40)
def main():
"""
Main function
"""
print('Add New tasks...')
# TODO Add 3 tasks & print
print('\nThe Second one is toggled')
# TODO Toggle the second task & print
print('\nThe last one is removed')
# TODO Remove only the third task & print
print('\nAll the todos are cleaned.')
# TODO Remove all the tasks & print
if __name__ == '__main__':
main()
| """
To-Do application
"""
def add(todos):
"""
Add a task
"""
pass
def delete(todos, index=None):
"""
Delete one or all tasks
"""
pass
def get_printable_todos(todos):
"""
Get formatted tasks
"""
pass
def toggle_done(todos, index):
"""
Toggle a task
"""
pass
def view(todos, index):
"""
Print tasks
"""
print('\nTo-Do list')
print('=' * 40)
def main():
"""
Main function
"""
print('Add New tasks...')
print('\nThe Second one is toggled')
print('\nThe last one is removed')
print('\nAll the todos are cleaned.')
if __name__ == '__main__':
main() |
class SerVivo:
def __init__(self):
self._vivo = True
def is_vivo(self):
return self._vivo
def morir(self):
self._vivo= False
#Se pone _ porque es una clase abstracta y solo se puede usar en esta clase
#Se pone __ porque es una clase privada solo la usa cada clase
| class Servivo:
def __init__(self):
self._vivo = True
def is_vivo(self):
return self._vivo
def morir(self):
self._vivo = False |
#!/usr/bin/env python3
with open("main.go", encoding="utf-8") as file:
# FIXME
usage = "\n".join(file.read().split("\n")[13:-1])
with open("tools/_README.md", mode="r", encoding="utf-8") as file:
readme = file.read()
readme = readme.replace("<<<<USAGE>>>>", usage)
with open("README.md", mode="w", encoding="utf-8") as file:
file.write(readme)
| with open('main.go', encoding='utf-8') as file:
usage = '\n'.join(file.read().split('\n')[13:-1])
with open('tools/_README.md', mode='r', encoding='utf-8') as file:
readme = file.read()
readme = readme.replace('<<<<USAGE>>>>', usage)
with open('README.md', mode='w', encoding='utf-8') as file:
file.write(readme) |
def binary_search(the_list, target):
lower_bound = 0
upper_bound = len(the_list) - 1
while lower_bound <= upper_bound:
pivot = (lower_bound + upper_bound) // 2
pivot_value = the_list[pivot]
if pivot_value == target:
return pivot
if pivot_value > target:
upper_bound = pivot - 1
else:
lower_bound = pivot + 1
return -1
my_list = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 , 10]
print(binary_search(my_list, 10))
print(binary_search(my_list, 4))
print(binary_search(my_list, 33))
| def binary_search(the_list, target):
lower_bound = 0
upper_bound = len(the_list) - 1
while lower_bound <= upper_bound:
pivot = (lower_bound + upper_bound) // 2
pivot_value = the_list[pivot]
if pivot_value == target:
return pivot
if pivot_value > target:
upper_bound = pivot - 1
else:
lower_bound = pivot + 1
return -1
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(binary_search(my_list, 10))
print(binary_search(my_list, 4))
print(binary_search(my_list, 33)) |
"""
User ACL
========
"""
_schema = {
# Medlemsnummer
'id': {'type': 'integer',
'readonly': True
},
'acl': {'type': 'dict',
'readonly': False,
'schema': {'groups': {'type': 'list', 'default': [],'schema': {'type': 'objectid'}},
'roles': {'type': 'list', 'default': [],'schema': {'type': 'objectid'}},
},
}
}
definition = {
'item_title': 'users/acl',
'url': 'users/acl',
'datasource': {'source': 'users',
'default_sort': [('id', 1)],
},
'extra_response_fields': ['id'],
'resource_methods': ['GET'], #No post, only internal!!
'item_methods': ['GET'],
#'auth_field': 'id', #This will limit only users who has
'allowed_write_roles': ['superadmin'],
'allowed_item_write_roles': ['superadmin'],
'additional_lookup': {
'url': 'regex("[\d{1,6}]+")',
'field': 'id',
},
'schema': _schema,
}
| """
User ACL
========
"""
_schema = {'id': {'type': 'integer', 'readonly': True}, 'acl': {'type': 'dict', 'readonly': False, 'schema': {'groups': {'type': 'list', 'default': [], 'schema': {'type': 'objectid'}}, 'roles': {'type': 'list', 'default': [], 'schema': {'type': 'objectid'}}}}}
definition = {'item_title': 'users/acl', 'url': 'users/acl', 'datasource': {'source': 'users', 'default_sort': [('id', 1)]}, 'extra_response_fields': ['id'], 'resource_methods': ['GET'], 'item_methods': ['GET'], 'allowed_write_roles': ['superadmin'], 'allowed_item_write_roles': ['superadmin'], 'additional_lookup': {'url': 'regex("[\\d{1,6}]+")', 'field': 'id'}, 'schema': _schema} |
"""
The cost of stock on each day is given in an array A[] of size N.
Find all the days on which you buy and sell the stock
so that in between those days your profit is maximum.
"""
def sellandbuy(a, n):
result = []
start = 0
end = 1
while end < n:
if a[start] < a[end] and a[end] > a[end-1]:
end += 1
else:
if end-start > 1:
result.append([start, end-1])
start = end
end = end+1
else:
start = end
end = end+1
if end-start > 1 and a[end-1] > a[start]:
result.append([start, end-1])
start = end
end = end+1
return result
print(sellandbuy([11, 42, 49, 96, 23, 20, 49, 26,
26, 18, 73, 2, 53, 59, 34, 99, 25, 2], 18))
| """
The cost of stock on each day is given in an array A[] of size N.
Find all the days on which you buy and sell the stock
so that in between those days your profit is maximum.
"""
def sellandbuy(a, n):
result = []
start = 0
end = 1
while end < n:
if a[start] < a[end] and a[end] > a[end - 1]:
end += 1
elif end - start > 1:
result.append([start, end - 1])
start = end
end = end + 1
else:
start = end
end = end + 1
if end - start > 1 and a[end - 1] > a[start]:
result.append([start, end - 1])
start = end
end = end + 1
return result
print(sellandbuy([11, 42, 49, 96, 23, 20, 49, 26, 26, 18, 73, 2, 53, 59, 34, 99, 25, 2], 18)) |
def solution(n):
sum = 0
print(list(str(n)))
for i, j in enumerate(list(str(n))):
sum+=int(j)
return sum
print(solution(11)) | def solution(n):
sum = 0
print(list(str(n)))
for (i, j) in enumerate(list(str(n))):
sum += int(j)
return sum
print(solution(11)) |
"""
LeetCode Problem: 108. Convert Sorted Array to Binary Search Tree
Link: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(N)
Space Complexity: O(N)
"""
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
def helper(left, right):
if left > right:
return None
# always choose left middle node as a root
p = (left + right) // 2
# preorder traversal: node -> left -> right
root = TreeNode(nums[p])
root.left = helper(left, p - 1)
root.right = helper(p + 1, right)
return root
return helper(0, len(nums) - 1) | """
LeetCode Problem: 108. Convert Sorted Array to Binary Search Tree
Link: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(N)
Space Complexity: O(N)
"""
class Solution:
def sorted_array_to_bst(self, nums: List[int]) -> TreeNode:
def helper(left, right):
if left > right:
return None
p = (left + right) // 2
root = tree_node(nums[p])
root.left = helper(left, p - 1)
root.right = helper(p + 1, right)
return root
return helper(0, len(nums) - 1) |
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
x = [i == '1' for i in a[::-1]]
y = [i == '1' for i in b[::-1]]
r = []
carry = False
if len(x) > len(y):
y += [False] * (len(x) - len(y))
else:
x += [False] * (len(y) - len(x))
for d in range(len(x)):
s, carry = self.full_adder(x[d], y[d], carry)
r += [s]
if carry:
r += [True]
r.reverse()
return ''.join(['1' if i else '0' for i in r])
def half_adder(self, a, b):
return a ^ b, a & b
def full_adder(self, a, b, cin):
s1, c1 = self.half_adder(a, b)
s2, c2 = self.half_adder(s1, cin)
return s2, c1 | c2
| class Solution:
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
x = [i == '1' for i in a[::-1]]
y = [i == '1' for i in b[::-1]]
r = []
carry = False
if len(x) > len(y):
y += [False] * (len(x) - len(y))
else:
x += [False] * (len(y) - len(x))
for d in range(len(x)):
(s, carry) = self.full_adder(x[d], y[d], carry)
r += [s]
if carry:
r += [True]
r.reverse()
return ''.join(['1' if i else '0' for i in r])
def half_adder(self, a, b):
return (a ^ b, a & b)
def full_adder(self, a, b, cin):
(s1, c1) = self.half_adder(a, b)
(s2, c2) = self.half_adder(s1, cin)
return (s2, c1 | c2) |
#
# PySNMP MIB module HP-ICF-LINKTEST (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-LINKTEST
# Produced by pysmi-0.3.4 at Wed May 1 13:34:33 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, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint")
hpicfCommon, hpicfObjectModules = mibBuilder.importSymbols("HP-ICF-OID", "hpicfCommon", "hpicfObjectModules")
OwnerString, = mibBuilder.importSymbols("RMON-MIB", "OwnerString")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
Counter64, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, MibIdentifier, Gauge32, NotificationType, TimeTicks, Unsigned32, ModuleIdentity, ObjectIdentity, Bits, iso, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "MibIdentifier", "Gauge32", "NotificationType", "TimeTicks", "Unsigned32", "ModuleIdentity", "ObjectIdentity", "Bits", "iso", "Integer32")
TimeInterval, TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TimeInterval", "TextualConvention", "DisplayString", "RowStatus")
hpicfLinkTestMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7))
hpicfLinkTestMib.setRevisions(('2000-11-03 22:25', '1997-03-06 03:38', '1996-09-06 22:18',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hpicfLinkTestMib.setRevisionsDescriptions(('Updated division name.', "Added 'destroyWhenDone' capability.", 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: hpicfLinkTestMib.setLastUpdated('200011032225Z')
if mibBuilder.loadTexts: hpicfLinkTestMib.setOrganization('HP Networking')
if mibBuilder.loadTexts: hpicfLinkTestMib.setContactInfo('Hewlett Packard Company 8000 Foothills Blvd. Roseville, CA 95747')
if mibBuilder.loadTexts: hpicfLinkTestMib.setDescription('This MIB module describes objects for managing the link test features of devices in the HP Integrated Communication Facility product line.')
hpicfLinktest = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6))
hpicfLinkTestNextIndex = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpicfLinkTestNextIndex.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestNextIndex.setDescription("A currently unassigned value of hpicfLinkTestIndex. The value 0 indicates that no unassigned values are available. In order to cause a non-zero value of this object to be assigned for use as the hpicfLinkTestIndex of a future link test, it must be successfully modified by a set operation. When modified by a set operation, the new value must precisely match the value presently held by the object. If not, the management protocol set operation will fail. Immediately after the completion of a successful set operation, the agent must modify the value of this object. The algorithm for modifying the value is implementation-dependent, and may use a subset of values within the legal range. However, the agent must guarantee that the new value is not assigned to any in-use value of hpicfLinkTestIndex. A management station creates a new link test using this algorithm: - issue a management protocol retrieval operation to obtain the value of hpicfLinkTestNextIndex; if the retrieved value is zero, a new link test cannot be created at this time; - issue a management protocol set operation for hpicfLinkTestNextIndex, supplying the same value as obtained in the previous step; - if the set operation succeeds, use the supplied value as the hpicfLinkTestIndex of the new link test; if the set operation fails, go back to the first step and obtain a new value for hpicfLinkTestNextIndex; - issue a management protocol set operation to create an instance of the hpicfLinkTestStatus object setting its value to 'createAndGo' or 'createAndWait' (as specified in the description of the RowStatus textual convention). Note that the set of hpicfLinkTestNextIndex and the instance of hpicfLinkTestStatus may occur in the same set operation if desired.")
hpicfLinkTestTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2), )
if mibBuilder.loadTexts: hpicfLinkTestTable.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestTable.setDescription('A table of in-progress link tests.')
hpicfLinkTestEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1), ).setIndexNames((0, "HP-ICF-LINKTEST", "hpicfLinkTestIndex"))
if mibBuilder.loadTexts: hpicfLinkTestEntry.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestEntry.setDescription('A row in the table, containing information about a single link test.')
hpicfLinkTestIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: hpicfLinkTestIndex.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestIndex.setDescription('The value of this object uniquely identifies this link test.')
hpicfLinkTestType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("icmpEcho", 1), ("ieee8022Test", 2), ("ipxDiagnostic", 3)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpicfLinkTestType.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestType.setDescription('The type of test to run.')
hpicfLinkTestAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 3), OctetString().subtype(subtypeSpec=ConstraintsUnion(ValueSizeConstraint(4, 4), ValueSizeConstraint(6, 6), ValueSizeConstraint(10, 10), ))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpicfLinkTestAddress.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestAddress.setDescription("The destination address used for sending link test packets, formatted according to the value of the corresponding instance of hpicfLinkTestType. When hpicfLinkTestType is equal to 'icmpEcho', this object will be four octets long, and contain an IP address in network byte order. When hpicfLinkTestType is equal to 'ieee8022Test', this object will be six octets long, and contain an IEEE MAC address in canonical order. When hpicfLinkTestType is equal to 'ipxDiagnostic', this object will be ten octets long, and will contain the IPX network number in network byte order, followed by the IPX node number in network byte order.")
hpicfLinkTestIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 4), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpicfLinkTestIfIndex.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestIfIndex.setDescription('The local interface to send the link test packets on. The value of this object must correspond to an ifIndex value for an interface capable of supporting the requested link test. The value 0 is used to indicate that the agent should determine the interface using local routing information.')
hpicfLinkTestTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 5), TimeInterval().clone(100)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpicfLinkTestTimeout.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestTimeout.setDescription('The time interval over which a link test response must be received, or the test is counted as failed.')
hpicfLinkTestRepetitions = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpicfLinkTestRepetitions.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestRepetitions.setDescription('The total number of times that the agent should send link test packets to the destination host.')
hpicfLinkTestAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfLinkTestAttempts.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestAttempts.setDescription("The number of times we have sent link test packets to the destination during the current test. This object will start at zero when the corresponding instance of hpicfLinkTestStatus is set to 'active'. It will increment at the completion of each iteration of the test until either it reaches the value of hpicfLinkTestRepetitions, or the corresponding instance of hpicfLinkTestStatus is set to a value other than 'active'. Note that it is incremented at the completion of each iteration, not when the link test packet is sent, so that the number of failures can be calculated accurately.")
hpicfLinkTestSuccesses = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfLinkTestSuccesses.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestSuccesses.setDescription("The number of times that we have recieved a response to a link test packet during the current test. This object will start at zero when the corresponding instance of hpicfLinkTestStatus is set to 'active'. It will increment each time the agent recieves a response from the destination of this test. Note that the number of failed attempts is given by hpicfLinkTestAttempts - hpicfLinkTestSuccesses.")
hpicfLinkTestMinRespTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfLinkTestMinRespTime.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestMinRespTime.setDescription('The shortest time (in milliseconds) between request and response for all of the link tests that have been attempted as part of this test.')
hpicfLinkTestMaxRespTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfLinkTestMaxRespTime.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestMaxRespTime.setDescription('The longest time (in milliseconds) between request and response for all of the link tests that have been attempted as part of this test.')
hpicfLinkTestTotalRespTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpicfLinkTestTotalRespTime.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestTotalRespTime.setDescription('The sum of all of the response times (in milliseconds) for all of the link tests that have been attempted as part of this test. This value can be used in conjunction with hpicfLinkTestSuccesses to calculate the average response time.')
hpicfLinkTestOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 12), OwnerString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpicfLinkTestOwner.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestOwner.setDescription('The entity that configured this test and is therefore using the resources assigned to it.')
hpicfLinkTestStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 13), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpicfLinkTestStatus.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestStatus.setDescription('The status of this entry.')
hpicfLinkTestDeleteMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("keepWhenDone", 1), ("destroyWhenDone", 2))).clone('keepWhenDone')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpicfLinkTestDeleteMode.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestDeleteMode.setDescription("When the value of this object is 'keepWhenDone', the associated instance of the hpicfLinkTestStatus object will be changed to 'notInService' upon completion of the test. It will then be timed out by the agent after 5 minutes in the 'notInService' state. When the value of this object is 'destroyWhenDone', the associated instance of the hpicfLinkTestStatus object will be changed to 'destroy' upon completion of the test. This will remove the row from the table immediately after the test completes.")
hpicfLinkTestConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1))
hpicfLinkTestCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 1))
hpicfLinkTestGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 2))
hpicfLinkTestCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 1, 1)).setObjects(("HP-ICF-LINKTEST", "hpicfLinkTestGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfLinkTestCompliance = hpicfLinkTestCompliance.setStatus('deprecated')
if mibBuilder.loadTexts: hpicfLinkTestCompliance.setDescription('The compliance statement for ICF devices that provide a connectivity test facility.')
hpicfLinkTestCompliance2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 1, 2)).setObjects(("HP-ICF-LINKTEST", "hpicfLinkTestGroup2"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfLinkTestCompliance2 = hpicfLinkTestCompliance2.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestCompliance2.setDescription('The compliance statement for ICF devices that provide a connectivity test facility.')
hpicfLinkTestGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 2, 1)).setObjects(("HP-ICF-LINKTEST", "hpicfLinkTestNextIndex"), ("HP-ICF-LINKTEST", "hpicfLinkTestType"), ("HP-ICF-LINKTEST", "hpicfLinkTestAddress"), ("HP-ICF-LINKTEST", "hpicfLinkTestIfIndex"), ("HP-ICF-LINKTEST", "hpicfLinkTestTimeout"), ("HP-ICF-LINKTEST", "hpicfLinkTestRepetitions"), ("HP-ICF-LINKTEST", "hpicfLinkTestAttempts"), ("HP-ICF-LINKTEST", "hpicfLinkTestSuccesses"), ("HP-ICF-LINKTEST", "hpicfLinkTestMinRespTime"), ("HP-ICF-LINKTEST", "hpicfLinkTestMaxRespTime"), ("HP-ICF-LINKTEST", "hpicfLinkTestTotalRespTime"), ("HP-ICF-LINKTEST", "hpicfLinkTestOwner"), ("HP-ICF-LINKTEST", "hpicfLinkTestStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfLinkTestGroup = hpicfLinkTestGroup.setStatus('deprecated')
if mibBuilder.loadTexts: hpicfLinkTestGroup.setDescription('A collection of objects for initiating and monitoring network connectivity tests on ICF devices.')
hpicfLinkTestGroup2 = ObjectGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 2, 2)).setObjects(("HP-ICF-LINKTEST", "hpicfLinkTestNextIndex"), ("HP-ICF-LINKTEST", "hpicfLinkTestType"), ("HP-ICF-LINKTEST", "hpicfLinkTestAddress"), ("HP-ICF-LINKTEST", "hpicfLinkTestIfIndex"), ("HP-ICF-LINKTEST", "hpicfLinkTestTimeout"), ("HP-ICF-LINKTEST", "hpicfLinkTestRepetitions"), ("HP-ICF-LINKTEST", "hpicfLinkTestAttempts"), ("HP-ICF-LINKTEST", "hpicfLinkTestSuccesses"), ("HP-ICF-LINKTEST", "hpicfLinkTestMinRespTime"), ("HP-ICF-LINKTEST", "hpicfLinkTestMaxRespTime"), ("HP-ICF-LINKTEST", "hpicfLinkTestTotalRespTime"), ("HP-ICF-LINKTEST", "hpicfLinkTestOwner"), ("HP-ICF-LINKTEST", "hpicfLinkTestStatus"), ("HP-ICF-LINKTEST", "hpicfLinkTestDeleteMode"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfLinkTestGroup2 = hpicfLinkTestGroup2.setStatus('current')
if mibBuilder.loadTexts: hpicfLinkTestGroup2.setDescription('A collection of objects for initiating and monitoring network connectivity tests on ICF devices.')
mibBuilder.exportSymbols("HP-ICF-LINKTEST", hpicfLinktest=hpicfLinktest, hpicfLinkTestRepetitions=hpicfLinkTestRepetitions, hpicfLinkTestMinRespTime=hpicfLinkTestMinRespTime, hpicfLinkTestGroup=hpicfLinkTestGroup, hpicfLinkTestGroup2=hpicfLinkTestGroup2, hpicfLinkTestOwner=hpicfLinkTestOwner, hpicfLinkTestDeleteMode=hpicfLinkTestDeleteMode, hpicfLinkTestStatus=hpicfLinkTestStatus, hpicfLinkTestMaxRespTime=hpicfLinkTestMaxRespTime, hpicfLinkTestSuccesses=hpicfLinkTestSuccesses, hpicfLinkTestConformance=hpicfLinkTestConformance, hpicfLinkTestTotalRespTime=hpicfLinkTestTotalRespTime, hpicfLinkTestIfIndex=hpicfLinkTestIfIndex, hpicfLinkTestMib=hpicfLinkTestMib, hpicfLinkTestAttempts=hpicfLinkTestAttempts, hpicfLinkTestTimeout=hpicfLinkTestTimeout, hpicfLinkTestGroups=hpicfLinkTestGroups, hpicfLinkTestEntry=hpicfLinkTestEntry, hpicfLinkTestCompliance2=hpicfLinkTestCompliance2, hpicfLinkTestCompliances=hpicfLinkTestCompliances, hpicfLinkTestType=hpicfLinkTestType, hpicfLinkTestCompliance=hpicfLinkTestCompliance, hpicfLinkTestNextIndex=hpicfLinkTestNextIndex, PYSNMP_MODULE_ID=hpicfLinkTestMib, hpicfLinkTestTable=hpicfLinkTestTable, hpicfLinkTestAddress=hpicfLinkTestAddress, hpicfLinkTestIndex=hpicfLinkTestIndex)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, constraints_union, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueRangeConstraint')
(hpicf_common, hpicf_object_modules) = mibBuilder.importSymbols('HP-ICF-OID', 'hpicfCommon', 'hpicfObjectModules')
(owner_string,) = mibBuilder.importSymbols('RMON-MIB', 'OwnerString')
(notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup')
(counter64, ip_address, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, mib_identifier, gauge32, notification_type, time_ticks, unsigned32, module_identity, object_identity, bits, iso, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'IpAddress', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'MibIdentifier', 'Gauge32', 'NotificationType', 'TimeTicks', 'Unsigned32', 'ModuleIdentity', 'ObjectIdentity', 'Bits', 'iso', 'Integer32')
(time_interval, textual_convention, display_string, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'TimeInterval', 'TextualConvention', 'DisplayString', 'RowStatus')
hpicf_link_test_mib = module_identity((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7))
hpicfLinkTestMib.setRevisions(('2000-11-03 22:25', '1997-03-06 03:38', '1996-09-06 22:18'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
hpicfLinkTestMib.setRevisionsDescriptions(('Updated division name.', "Added 'destroyWhenDone' capability.", 'Initial version of this MIB module.'))
if mibBuilder.loadTexts:
hpicfLinkTestMib.setLastUpdated('200011032225Z')
if mibBuilder.loadTexts:
hpicfLinkTestMib.setOrganization('HP Networking')
if mibBuilder.loadTexts:
hpicfLinkTestMib.setContactInfo('Hewlett Packard Company 8000 Foothills Blvd. Roseville, CA 95747')
if mibBuilder.loadTexts:
hpicfLinkTestMib.setDescription('This MIB module describes objects for managing the link test features of devices in the HP Integrated Communication Facility product line.')
hpicf_linktest = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6))
hpicf_link_test_next_index = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpicfLinkTestNextIndex.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestNextIndex.setDescription("A currently unassigned value of hpicfLinkTestIndex. The value 0 indicates that no unassigned values are available. In order to cause a non-zero value of this object to be assigned for use as the hpicfLinkTestIndex of a future link test, it must be successfully modified by a set operation. When modified by a set operation, the new value must precisely match the value presently held by the object. If not, the management protocol set operation will fail. Immediately after the completion of a successful set operation, the agent must modify the value of this object. The algorithm for modifying the value is implementation-dependent, and may use a subset of values within the legal range. However, the agent must guarantee that the new value is not assigned to any in-use value of hpicfLinkTestIndex. A management station creates a new link test using this algorithm: - issue a management protocol retrieval operation to obtain the value of hpicfLinkTestNextIndex; if the retrieved value is zero, a new link test cannot be created at this time; - issue a management protocol set operation for hpicfLinkTestNextIndex, supplying the same value as obtained in the previous step; - if the set operation succeeds, use the supplied value as the hpicfLinkTestIndex of the new link test; if the set operation fails, go back to the first step and obtain a new value for hpicfLinkTestNextIndex; - issue a management protocol set operation to create an instance of the hpicfLinkTestStatus object setting its value to 'createAndGo' or 'createAndWait' (as specified in the description of the RowStatus textual convention). Note that the set of hpicfLinkTestNextIndex and the instance of hpicfLinkTestStatus may occur in the same set operation if desired.")
hpicf_link_test_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2))
if mibBuilder.loadTexts:
hpicfLinkTestTable.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestTable.setDescription('A table of in-progress link tests.')
hpicf_link_test_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1)).setIndexNames((0, 'HP-ICF-LINKTEST', 'hpicfLinkTestIndex'))
if mibBuilder.loadTexts:
hpicfLinkTestEntry.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestEntry.setDescription('A row in the table, containing information about a single link test.')
hpicf_link_test_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
hpicfLinkTestIndex.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestIndex.setDescription('The value of this object uniquely identifies this link test.')
hpicf_link_test_type = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('icmpEcho', 1), ('ieee8022Test', 2), ('ipxDiagnostic', 3)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpicfLinkTestType.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestType.setDescription('The type of test to run.')
hpicf_link_test_address = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 3), octet_string().subtype(subtypeSpec=constraints_union(value_size_constraint(4, 4), value_size_constraint(6, 6), value_size_constraint(10, 10)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpicfLinkTestAddress.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestAddress.setDescription("The destination address used for sending link test packets, formatted according to the value of the corresponding instance of hpicfLinkTestType. When hpicfLinkTestType is equal to 'icmpEcho', this object will be four octets long, and contain an IP address in network byte order. When hpicfLinkTestType is equal to 'ieee8022Test', this object will be six octets long, and contain an IEEE MAC address in canonical order. When hpicfLinkTestType is equal to 'ipxDiagnostic', this object will be ten octets long, and will contain the IPX network number in network byte order, followed by the IPX node number in network byte order.")
hpicf_link_test_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 4), integer32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpicfLinkTestIfIndex.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestIfIndex.setDescription('The local interface to send the link test packets on. The value of this object must correspond to an ifIndex value for an interface capable of supporting the requested link test. The value 0 is used to indicate that the agent should determine the interface using local routing information.')
hpicf_link_test_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 5), time_interval().clone(100)).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpicfLinkTestTimeout.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestTimeout.setDescription('The time interval over which a link test response must be received, or the test is counted as failed.')
hpicf_link_test_repetitions = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)).clone(1)).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpicfLinkTestRepetitions.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestRepetitions.setDescription('The total number of times that the agent should send link test packets to the destination host.')
hpicf_link_test_attempts = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfLinkTestAttempts.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestAttempts.setDescription("The number of times we have sent link test packets to the destination during the current test. This object will start at zero when the corresponding instance of hpicfLinkTestStatus is set to 'active'. It will increment at the completion of each iteration of the test until either it reaches the value of hpicfLinkTestRepetitions, or the corresponding instance of hpicfLinkTestStatus is set to a value other than 'active'. Note that it is incremented at the completion of each iteration, not when the link test packet is sent, so that the number of failures can be calculated accurately.")
hpicf_link_test_successes = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfLinkTestSuccesses.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestSuccesses.setDescription("The number of times that we have recieved a response to a link test packet during the current test. This object will start at zero when the corresponding instance of hpicfLinkTestStatus is set to 'active'. It will increment each time the agent recieves a response from the destination of this test. Note that the number of failed attempts is given by hpicfLinkTestAttempts - hpicfLinkTestSuccesses.")
hpicf_link_test_min_resp_time = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 9), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfLinkTestMinRespTime.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestMinRespTime.setDescription('The shortest time (in milliseconds) between request and response for all of the link tests that have been attempted as part of this test.')
hpicf_link_test_max_resp_time = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 10), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfLinkTestMaxRespTime.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestMaxRespTime.setDescription('The longest time (in milliseconds) between request and response for all of the link tests that have been attempted as part of this test.')
hpicf_link_test_total_resp_time = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 11), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hpicfLinkTestTotalRespTime.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestTotalRespTime.setDescription('The sum of all of the response times (in milliseconds) for all of the link tests that have been attempted as part of this test. This value can be used in conjunction with hpicfLinkTestSuccesses to calculate the average response time.')
hpicf_link_test_owner = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 12), owner_string()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpicfLinkTestOwner.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestOwner.setDescription('The entity that configured this test and is therefore using the resources assigned to it.')
hpicf_link_test_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 13), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpicfLinkTestStatus.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestStatus.setDescription('The status of this entry.')
hpicf_link_test_delete_mode = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 1, 6, 2, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('keepWhenDone', 1), ('destroyWhenDone', 2))).clone('keepWhenDone')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hpicfLinkTestDeleteMode.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestDeleteMode.setDescription("When the value of this object is 'keepWhenDone', the associated instance of the hpicfLinkTestStatus object will be changed to 'notInService' upon completion of the test. It will then be timed out by the agent after 5 minutes in the 'notInService' state. When the value of this object is 'destroyWhenDone', the associated instance of the hpicfLinkTestStatus object will be changed to 'destroy' upon completion of the test. This will remove the row from the table immediately after the test completes.")
hpicf_link_test_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1))
hpicf_link_test_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 1))
hpicf_link_test_groups = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 2))
hpicf_link_test_compliance = module_compliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 1, 1)).setObjects(('HP-ICF-LINKTEST', 'hpicfLinkTestGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicf_link_test_compliance = hpicfLinkTestCompliance.setStatus('deprecated')
if mibBuilder.loadTexts:
hpicfLinkTestCompliance.setDescription('The compliance statement for ICF devices that provide a connectivity test facility.')
hpicf_link_test_compliance2 = module_compliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 1, 2)).setObjects(('HP-ICF-LINKTEST', 'hpicfLinkTestGroup2'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicf_link_test_compliance2 = hpicfLinkTestCompliance2.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestCompliance2.setDescription('The compliance statement for ICF devices that provide a connectivity test facility.')
hpicf_link_test_group = object_group((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 2, 1)).setObjects(('HP-ICF-LINKTEST', 'hpicfLinkTestNextIndex'), ('HP-ICF-LINKTEST', 'hpicfLinkTestType'), ('HP-ICF-LINKTEST', 'hpicfLinkTestAddress'), ('HP-ICF-LINKTEST', 'hpicfLinkTestIfIndex'), ('HP-ICF-LINKTEST', 'hpicfLinkTestTimeout'), ('HP-ICF-LINKTEST', 'hpicfLinkTestRepetitions'), ('HP-ICF-LINKTEST', 'hpicfLinkTestAttempts'), ('HP-ICF-LINKTEST', 'hpicfLinkTestSuccesses'), ('HP-ICF-LINKTEST', 'hpicfLinkTestMinRespTime'), ('HP-ICF-LINKTEST', 'hpicfLinkTestMaxRespTime'), ('HP-ICF-LINKTEST', 'hpicfLinkTestTotalRespTime'), ('HP-ICF-LINKTEST', 'hpicfLinkTestOwner'), ('HP-ICF-LINKTEST', 'hpicfLinkTestStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicf_link_test_group = hpicfLinkTestGroup.setStatus('deprecated')
if mibBuilder.loadTexts:
hpicfLinkTestGroup.setDescription('A collection of objects for initiating and monitoring network connectivity tests on ICF devices.')
hpicf_link_test_group2 = object_group((1, 3, 6, 1, 4, 1, 11, 2, 14, 10, 2, 7, 1, 2, 2)).setObjects(('HP-ICF-LINKTEST', 'hpicfLinkTestNextIndex'), ('HP-ICF-LINKTEST', 'hpicfLinkTestType'), ('HP-ICF-LINKTEST', 'hpicfLinkTestAddress'), ('HP-ICF-LINKTEST', 'hpicfLinkTestIfIndex'), ('HP-ICF-LINKTEST', 'hpicfLinkTestTimeout'), ('HP-ICF-LINKTEST', 'hpicfLinkTestRepetitions'), ('HP-ICF-LINKTEST', 'hpicfLinkTestAttempts'), ('HP-ICF-LINKTEST', 'hpicfLinkTestSuccesses'), ('HP-ICF-LINKTEST', 'hpicfLinkTestMinRespTime'), ('HP-ICF-LINKTEST', 'hpicfLinkTestMaxRespTime'), ('HP-ICF-LINKTEST', 'hpicfLinkTestTotalRespTime'), ('HP-ICF-LINKTEST', 'hpicfLinkTestOwner'), ('HP-ICF-LINKTEST', 'hpicfLinkTestStatus'), ('HP-ICF-LINKTEST', 'hpicfLinkTestDeleteMode'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicf_link_test_group2 = hpicfLinkTestGroup2.setStatus('current')
if mibBuilder.loadTexts:
hpicfLinkTestGroup2.setDescription('A collection of objects for initiating and monitoring network connectivity tests on ICF devices.')
mibBuilder.exportSymbols('HP-ICF-LINKTEST', hpicfLinktest=hpicfLinktest, hpicfLinkTestRepetitions=hpicfLinkTestRepetitions, hpicfLinkTestMinRespTime=hpicfLinkTestMinRespTime, hpicfLinkTestGroup=hpicfLinkTestGroup, hpicfLinkTestGroup2=hpicfLinkTestGroup2, hpicfLinkTestOwner=hpicfLinkTestOwner, hpicfLinkTestDeleteMode=hpicfLinkTestDeleteMode, hpicfLinkTestStatus=hpicfLinkTestStatus, hpicfLinkTestMaxRespTime=hpicfLinkTestMaxRespTime, hpicfLinkTestSuccesses=hpicfLinkTestSuccesses, hpicfLinkTestConformance=hpicfLinkTestConformance, hpicfLinkTestTotalRespTime=hpicfLinkTestTotalRespTime, hpicfLinkTestIfIndex=hpicfLinkTestIfIndex, hpicfLinkTestMib=hpicfLinkTestMib, hpicfLinkTestAttempts=hpicfLinkTestAttempts, hpicfLinkTestTimeout=hpicfLinkTestTimeout, hpicfLinkTestGroups=hpicfLinkTestGroups, hpicfLinkTestEntry=hpicfLinkTestEntry, hpicfLinkTestCompliance2=hpicfLinkTestCompliance2, hpicfLinkTestCompliances=hpicfLinkTestCompliances, hpicfLinkTestType=hpicfLinkTestType, hpicfLinkTestCompliance=hpicfLinkTestCompliance, hpicfLinkTestNextIndex=hpicfLinkTestNextIndex, PYSNMP_MODULE_ID=hpicfLinkTestMib, hpicfLinkTestTable=hpicfLinkTestTable, hpicfLinkTestAddress=hpicfLinkTestAddress, hpicfLinkTestIndex=hpicfLinkTestIndex) |
"""Configs for VisDA17 experiments."""
def get_weighting_config_class_pareto(alpha, reverse, seed):
return {
'name': 'class_pareto',
'kwargs': {
'alpha': alpha,
'reverse': reverse,
'seed': seed
},
}
def get_dataset_config_visda17_pareto_target_imbalance(alpha, seed=None):
return {
'name': 'VisDA17',
'val_fraction': 0.15,
'mods': [],
'source': {
'index': 0,
'weighting': {
'name': 'class_uniform',
'kwargs': dict(),
},
'subsample': True,
},
'target': {
'index': 1,
'weighting': get_weighting_config_class_pareto(alpha, True, seed=seed),
'subsample': True,
},
}
def get_algorithm_config(algorithm, extra_hparams=None, extra_discriminator_hparams=None):
# Common configs of all algorithms
config = {
'name': algorithm,
'hparams': {
'da_network': {
'feature_extractor': {
'name': 'ResNet',
'hparams': {
'feature_dim': 256,
'pretrained': True,
'freeze_bn': False,
'resnet18': False,
'resnet_dropout': 0.0,
'fc_lr_factor': 1.0,
'fc_wd_factor': 1.0,
}
},
'classifier': {
'name': 'LogLossClassifier',
'hparams': {
'num_hidden': None,
'special_init': True,
}
},
},
'discriminator': {
'hparams': {
'num_hidden': 1024,
'depth': 3,
'spectral': False,
'history_size': 0,
}
},
'ema_momentum': None,
'fx_opt': {
'name': 'SGD',
'kwargs': {
'lr': 0.001,
'momentum': 0.9,
'weight_decay': 0.001,
'nesterov': True,
}
},
'fx_lr_decay_start': 0,
'fx_lr_decay_steps': 50000,
'fx_lr_decay_factor': 0.05,
'cls_opt': {
'name': 'SGD',
'kwargs': {
'lr': 0.01,
'momentum': 0.9,
'weight_decay': 0.001,
'nesterov': True,
}
},
'cls_weight': 1.0,
'cls_trg_weight': 0.0,
'alignment_weight': None,
'alignment_w_steps': 10000,
'disc_opt': {
'name': 'SGD',
'kwargs': {
'lr': 0.005,
'momentum': 0.9,
'weight_decay': 0.001,
'nesterov': True,
}
},
'disc_steps': 1,
'l2_weight': 0.0,
}
}
if extra_hparams is not None:
config['hparams'].update(extra_hparams)
if extra_discriminator_hparams is not None:
config['hparams']['discriminator']['hparams'].update(extra_discriminator_hparams)
return config
def register_experiments(registry):
# Algorithm configs format:
# nickname, algorithm_name, extra_hparams, extra_discriminator_hparams
algorithms = [
('source_only', 'ERM', None, None),
('dann_zero', 'DANN_NS', {'alignment_weight': 0.0}, None),
('dann', 'DANN_NS', {'alignment_weight': 0.1}, None),
]
iwdan_extra_hparams = {'alignment_weight': 0.1, 'iw_update_period': 4000, 'importance_weighting': {'ma': 0.5}}
algorithms.extend([
('iwdan', 'IWDAN', iwdan_extra_hparams, None),
('iwcdan', 'IWCDAN', iwdan_extra_hparams, None),
])
algorithms.append(
(f'sdann_4', 'SDANN', {'alignment_weight': 0.1}, {'beta': 4.0})
)
algorithms.extend([
('asa_abs', 'DANN_SUPP_ABS', {'alignment_weight': 0.1},
{'history_size': 1000}),
('asa_sq', 'DANN_SUPP_SQ', {'alignment_weight': 0.1},
{'history_size': 1000}),
])
for imbalance_alpha in [0.0, 1.0, 1.5, 2.0]:
for seed in range(1, 6):
dataset_config = get_dataset_config_visda17_pareto_target_imbalance(imbalance_alpha, seed=seed)
training_config = {
'seed': seed,
'num_steps': 50000,
'batch_size': 36,
'num_workers': 4,
'eval_period': 2500,
'log_period': 50,
'eval_bn_update': True,
'save_model': False,
'save_period': 1,
'disc_eval_period': 4,
}
for alg_nickname, algorithm_name, extra_hparams, extra_discriminator_hparams in algorithms:
algorithm_config = get_algorithm_config(algorithm_name, extra_hparams, extra_discriminator_hparams)
experiment_name = f'visda17/resnet50/seed_{seed}/s_alpha_{int(imbalance_alpha * 10):02d}/{alg_nickname}'
experiment_config = {
'dataset': dataset_config,
'algorithm': algorithm_config,
'training': training_config,
}
registry.register(experiment_name, experiment_config)
| """Configs for VisDA17 experiments."""
def get_weighting_config_class_pareto(alpha, reverse, seed):
return {'name': 'class_pareto', 'kwargs': {'alpha': alpha, 'reverse': reverse, 'seed': seed}}
def get_dataset_config_visda17_pareto_target_imbalance(alpha, seed=None):
return {'name': 'VisDA17', 'val_fraction': 0.15, 'mods': [], 'source': {'index': 0, 'weighting': {'name': 'class_uniform', 'kwargs': dict()}, 'subsample': True}, 'target': {'index': 1, 'weighting': get_weighting_config_class_pareto(alpha, True, seed=seed), 'subsample': True}}
def get_algorithm_config(algorithm, extra_hparams=None, extra_discriminator_hparams=None):
config = {'name': algorithm, 'hparams': {'da_network': {'feature_extractor': {'name': 'ResNet', 'hparams': {'feature_dim': 256, 'pretrained': True, 'freeze_bn': False, 'resnet18': False, 'resnet_dropout': 0.0, 'fc_lr_factor': 1.0, 'fc_wd_factor': 1.0}}, 'classifier': {'name': 'LogLossClassifier', 'hparams': {'num_hidden': None, 'special_init': True}}}, 'discriminator': {'hparams': {'num_hidden': 1024, 'depth': 3, 'spectral': False, 'history_size': 0}}, 'ema_momentum': None, 'fx_opt': {'name': 'SGD', 'kwargs': {'lr': 0.001, 'momentum': 0.9, 'weight_decay': 0.001, 'nesterov': True}}, 'fx_lr_decay_start': 0, 'fx_lr_decay_steps': 50000, 'fx_lr_decay_factor': 0.05, 'cls_opt': {'name': 'SGD', 'kwargs': {'lr': 0.01, 'momentum': 0.9, 'weight_decay': 0.001, 'nesterov': True}}, 'cls_weight': 1.0, 'cls_trg_weight': 0.0, 'alignment_weight': None, 'alignment_w_steps': 10000, 'disc_opt': {'name': 'SGD', 'kwargs': {'lr': 0.005, 'momentum': 0.9, 'weight_decay': 0.001, 'nesterov': True}}, 'disc_steps': 1, 'l2_weight': 0.0}}
if extra_hparams is not None:
config['hparams'].update(extra_hparams)
if extra_discriminator_hparams is not None:
config['hparams']['discriminator']['hparams'].update(extra_discriminator_hparams)
return config
def register_experiments(registry):
algorithms = [('source_only', 'ERM', None, None), ('dann_zero', 'DANN_NS', {'alignment_weight': 0.0}, None), ('dann', 'DANN_NS', {'alignment_weight': 0.1}, None)]
iwdan_extra_hparams = {'alignment_weight': 0.1, 'iw_update_period': 4000, 'importance_weighting': {'ma': 0.5}}
algorithms.extend([('iwdan', 'IWDAN', iwdan_extra_hparams, None), ('iwcdan', 'IWCDAN', iwdan_extra_hparams, None)])
algorithms.append((f'sdann_4', 'SDANN', {'alignment_weight': 0.1}, {'beta': 4.0}))
algorithms.extend([('asa_abs', 'DANN_SUPP_ABS', {'alignment_weight': 0.1}, {'history_size': 1000}), ('asa_sq', 'DANN_SUPP_SQ', {'alignment_weight': 0.1}, {'history_size': 1000})])
for imbalance_alpha in [0.0, 1.0, 1.5, 2.0]:
for seed in range(1, 6):
dataset_config = get_dataset_config_visda17_pareto_target_imbalance(imbalance_alpha, seed=seed)
training_config = {'seed': seed, 'num_steps': 50000, 'batch_size': 36, 'num_workers': 4, 'eval_period': 2500, 'log_period': 50, 'eval_bn_update': True, 'save_model': False, 'save_period': 1, 'disc_eval_period': 4}
for (alg_nickname, algorithm_name, extra_hparams, extra_discriminator_hparams) in algorithms:
algorithm_config = get_algorithm_config(algorithm_name, extra_hparams, extra_discriminator_hparams)
experiment_name = f'visda17/resnet50/seed_{seed}/s_alpha_{int(imbalance_alpha * 10):02d}/{alg_nickname}'
experiment_config = {'dataset': dataset_config, 'algorithm': algorithm_config, 'training': training_config}
registry.register(experiment_name, experiment_config) |
"""
This file contains the implementation of a mixin that contains a
method that solves the collision between a rectangular shape with
the ball.
Collision solve algorithm taken from:
https://github.com/noooway/love2d_arkanoid_tutorial/wiki/Resolving-Collisions
Author: Alejandro Mujica
Date: 15/07/2020
"""
class BallBounceMixin:
@staticmethod
def get_intersection(r1, r2):
"""
Compute, if exists, the intersection between two
rectangles.
"""
if (r1.x > r2.right or r1.right < r2.x
or r1.bottom < r2.y or r1.y > r2.bottom):
# There is no intersection
return None
# Compute x shift
if r1.centerx < r2.centerx:
x_shift = r1.right - r2.x
else:
x_shift = r1.x - r2.right
# Compute y shift
if r1.centery < r2.centery:
y_shift = r2.y - r1.bottom
else:
y_shift = r2.bottom - r1.y
return (x_shift, y_shift)
def rebound(self, ball):
br = ball.get_collision_rect()
sr = self.get_collision_rect()
r = self.get_intersection(br, sr)
if r is None:
return
shift_x, shift_y = r
min_shift = min(abs(shift_x), abs(shift_y))
if min_shift == abs(shift_x):
# Collision happened from left or right
ball.x += shift_x
ball.vx *= -1
else:
# Collision happend from top or bottom
ball.y += shift_y
ball.vy *= -1
| """
This file contains the implementation of a mixin that contains a
method that solves the collision between a rectangular shape with
the ball.
Collision solve algorithm taken from:
https://github.com/noooway/love2d_arkanoid_tutorial/wiki/Resolving-Collisions
Author: Alejandro Mujica
Date: 15/07/2020
"""
class Ballbouncemixin:
@staticmethod
def get_intersection(r1, r2):
"""
Compute, if exists, the intersection between two
rectangles.
"""
if r1.x > r2.right or r1.right < r2.x or r1.bottom < r2.y or (r1.y > r2.bottom):
return None
if r1.centerx < r2.centerx:
x_shift = r1.right - r2.x
else:
x_shift = r1.x - r2.right
if r1.centery < r2.centery:
y_shift = r2.y - r1.bottom
else:
y_shift = r2.bottom - r1.y
return (x_shift, y_shift)
def rebound(self, ball):
br = ball.get_collision_rect()
sr = self.get_collision_rect()
r = self.get_intersection(br, sr)
if r is None:
return
(shift_x, shift_y) = r
min_shift = min(abs(shift_x), abs(shift_y))
if min_shift == abs(shift_x):
ball.x += shift_x
ball.vx *= -1
else:
ball.y += shift_y
ball.vy *= -1 |
for x in range(16):
with open(f'..\\data\\cpu\\functions\\opcode_switch\\opcode_7xxx\\opcode_7xxx_{x}.mcfunction', 'w') as f:
f.write(f'scoreboard players operation Global V{hex(x)[2:].upper()} += Global PC_nibble_4\n')
f.write(f'execute if score Global V{hex(x)[2:].upper()} matches 256.. run scoreboard players remove Global V{hex(x)[2:].upper()} 256\n')
"""
for x in range(16):
with open('..\\data\\cpu\\functions\\opcode_switch\\opcode_7xxx.mcfunction', 'a') as f:
f.write(f'execute if score Global PC_nibble_2 matches {x} run function cpu:opcode_switch/opcode_7xxx/opcode_7xxx_{x}\n')
"""
| for x in range(16):
with open(f'..\\data\\cpu\\functions\\opcode_switch\\opcode_7xxx\\opcode_7xxx_{x}.mcfunction', 'w') as f:
f.write(f'scoreboard players operation Global V{hex(x)[2:].upper()} += Global PC_nibble_4\n')
f.write(f'execute if score Global V{hex(x)[2:].upper()} matches 256.. run scoreboard players remove Global V{hex(x)[2:].upper()} 256\n')
"\nfor x in range(16):\n with open('..\\data\\cpu\\functions\\opcode_switch\\opcode_7xxx.mcfunction', 'a') as f:\n f.write(f'execute if score Global PC_nibble_2 matches {x} run function cpu:opcode_switch/opcode_7xxx/opcode_7xxx_{x}\n')\n" |
class MoveGenerator:
"""
state=(BK,WK,WR)--> state=((x,y),(x,y,R),(x,y,K)) check for K and R for whose values most likely order you get is bk,w
where wk , wr and bk are positions for the pieces
"""
def __init__(self,state):
self.state=state #represennts initial state of the game p.s state is list not tuple
self.bk=state[0] #current black king position
if state[1][2]=='R':
self.wr=state[1][:-1]
elif state[1][2]=='K':
self.wk=state[1][:-1]
if state[2][2]=='K':
self.wk=state[2][:-1]
elif state[2][2]=='R':
self.wr=state[2][:-1]
self.adj_king=[(-1,1),(0,1),(1,1),(-1,0),(1,0),(-1,-1),(0,-1),(1,-1)]
self.wrScope=[] #possible moves for rook and king
self.wkScope=[]
self.bkScope=[]
for x,y in self.adj_king:
temp=(self.bk[0]+x,self.bk[1]+y)
if temp[0]<9 and temp[0]>0:
if temp[1]<9 and temp[1]>0:
self.bkScope.append(temp)
self.theend=False
#shall we make wrScope,wkScope and bkScope sets for efficiency ?? Let's see
#I think onlybkScope can be made a set ..wkscope and wrscope need to be iterable hmm..
def bkMovegen(self):
""" first priority is to capture an uprotected rook , else move to safe field,
no safe field the game ends"""
# FULL AWESOME
self.bkScope=[]
for x,y in self.adj_king:
temp=(self.bk[0]+x,self.bk[1]+y)
if temp[0]<9 and temp[0]>0:
if temp[1]<9 and temp[1]>0:
self.bkScope.append(temp) #this should do it :)
k= lambda x,y: (abs(x-5)*5)+(abs(y-5)*3)+((x+y)*0.1)
self.bkScope=[(x,y,k(x,y)) for x,y in self.bkScope]
self.bkScope.sort(key=lambda n: n[2])
self.bkScope=[(x,y) for x,y,z in self.bkScope] #already sorted do not need those values anymore
#first priority attack white rook if safe
""" we do not need this if self.wr in self.bkScope:
if self.wr not in self.wkScope:
return self.wr #kills the rook #do not update self.bk here cuz you are not gonna let it attack anyway"""
#make safe move
#assume game ends if bk can't move
self.theend=True
if self.wr in self.bkScope:
self.bkScope.remove(self.wr)
for t in self.bkScope:
if t not in self.wrScope:
if t not in self.wkScope:
self.bk=t
self.theend=False #game dosen't end and afterall
break
if self.theend==False:
return self.bk
else:
return 'call gameEnds'
#call gameends method
def whitePossibleMoves(self):
"""there's a catch wk and wr can't occupy each others positions unless the rook is under attack THE SUBTLE BUG, INTERDEPENDENCY
you don't need to do this check right yet , do it just before the white pieces move cuz it's affecting BK behavior
if self.wr in self.wkScope:
self.wkScope.remove(self.wr)
if self.wk in self.wrScope:
self.wrScope.remove(self.wk) """
for i in range(1,9):
if i!=self.wr[0]:
self.wrScope.append((i,self.wr[1]))
if i!=self.wr[1]:
self.wrScope.append((self.wr[0],i))
for x,y in self.adj_king:
temp=(self.wk[0]+x,self.wk[1]+y)
if temp[0]<9 and temp[0]>0:
if temp[1]<9 and temp[1]>0:
self.wkScope.append(temp)
#we need to trim rooks possible moves as it can't run through the other pieces
#first consider white king along horizontal aka y axis is same
trim=[z for z in self.wrScope if z[1]==self.wk[1]]
if trim!=[]: #which means white king is there horizontally
if self.wk[0]>self.wr[0]: #check if king is to the left or right of the rook
trim=[z for z in trim if z[0]>self.wk[0]] #remember we are removing !!!
elif self.wk[0]<self.wr[0]:
trim=[z for z in trim if z[0]<self.wk[0]] #this means king is to the left so whatever is left of the king exclude it
for tr in trim:
try:
self.wrScope.remove(tr)
except ValueError:
pass
#second consider white king along vertical axis i.e. x axis is same
trim=[z for z in self.wrScope if z[0]==self.wk[0]]
if trim!=[]: #which means white king is there vertically
if self.wk[1]>self.wr[1]: #check if king is above or below the rook
trim=[z for z in trim if z[1]>self.wk[1]]
elif self.wk[1]<self.wr[1]:
trim=[z for z in trim if z[1]<self.wk[1]]
for tr in trim:
try:
self.wrScope.remove(tr)
except ValueError:
pass
if self.bk[0]==self.wr[0] or self.bk[1]==self.wr[1]: #rook should be able to attack the black king
if self.bk not in self.wrScope:
self.wrScope.append(self.bk)
def gameEnds(self):
""" check for check/stale mate and other end game functionality later to be added :)"""
if self.bk in self.wkScope or self.bk in self.wrScope:
return'checkmate'
else:
return'stalemate'
#black king behavior successfuly debugged
def adjustWhitemove(self): #some preprocessing must call before the search
#similarly for black king horizontal
trim=[z for z in self.wrScope if z[1]==self.bk[1]]
if trim!=[]: #which means white king is there horizontally
if self.bk[0]>self.wr[0]: #check if king is to the left or right of the rook
trim=[z for z in trim if z[0]>self.bk[0]] #remember we are removing !!!
elif self.bk[0]<self.wr[0]:
trim=[z for z in trim if z[0]<self.bk[0]] #this means king is to the left so whatever is left of the king exclude it
for tr in trim:
try:
self.wrScope.remove(tr)
except ValueError:
pass
#similarly black king vertical
trim=[z for z in self.wrScope if z[0]==self.bk[0]]
if trim!=[]: #which means white king is there vertically
if self.bk[1]>self.wr[1]: #check if king is above or below the rook
trim=[z for z in trim if z[1]>self.bk[1]]
elif self.bk[1]<self.wr[1]:
trim=[z for z in trim if z[1]<self.bk[1]]
for tr in trim:
try:
self.wrScope.remove(tr)
except ValueError:
pass
if self.wr in self.wkScope:
self.wkScope.remove(self.wr)
if self.wk in self.wrScope:
self.wrScope.remove(self.wk)
#they can't run into each other
#either pices shouldn't be in the neighborhood of bk without backup
full_bkscope=[]
for x,y in self.adj_king:
temp=(self.bk[0]+x,self.bk[1]+y)
if temp[0]<9 and temp[0]>0:
if temp[1]<9 and temp[1]>0:
full_bkscope.append(temp)
to_remove=[r for r in self.wrScope if r in full_bkscope and r not in self.wkScope]
self.wrScope=[x for x in self.wrScope if x not in to_remove]
self.wkScope=[x for x in self.wkScope if x not in full_bkscope] #we can't lose our king backup or not
#except for first move wk,wr are aware of their safety before search, not first move cuz bkscope not available yet
#be careful to consider this in your search algorithm/heuristic
| class Movegenerator:
"""
state=(BK,WK,WR)--> state=((x,y),(x,y,R),(x,y,K)) check for K and R for whose values most likely order you get is bk,w
where wk , wr and bk are positions for the pieces
"""
def __init__(self, state):
self.state = state
self.bk = state[0]
if state[1][2] == 'R':
self.wr = state[1][:-1]
elif state[1][2] == 'K':
self.wk = state[1][:-1]
if state[2][2] == 'K':
self.wk = state[2][:-1]
elif state[2][2] == 'R':
self.wr = state[2][:-1]
self.adj_king = [(-1, 1), (0, 1), (1, 1), (-1, 0), (1, 0), (-1, -1), (0, -1), (1, -1)]
self.wrScope = []
self.wkScope = []
self.bkScope = []
for (x, y) in self.adj_king:
temp = (self.bk[0] + x, self.bk[1] + y)
if temp[0] < 9 and temp[0] > 0:
if temp[1] < 9 and temp[1] > 0:
self.bkScope.append(temp)
self.theend = False
def bk_movegen(self):
""" first priority is to capture an uprotected rook , else move to safe field,
no safe field the game ends"""
self.bkScope = []
for (x, y) in self.adj_king:
temp = (self.bk[0] + x, self.bk[1] + y)
if temp[0] < 9 and temp[0] > 0:
if temp[1] < 9 and temp[1] > 0:
self.bkScope.append(temp)
k = lambda x, y: abs(x - 5) * 5 + abs(y - 5) * 3 + (x + y) * 0.1
self.bkScope = [(x, y, k(x, y)) for (x, y) in self.bkScope]
self.bkScope.sort(key=lambda n: n[2])
self.bkScope = [(x, y) for (x, y, z) in self.bkScope]
'\twe do not need this if self.wr in self.bkScope: \n\t\t\tif self.wr not in self.wkScope:\n\t\t\t\treturn self.wr #kills the rook #do not update self.bk here cuz you are not gonna let it attack anyway'
self.theend = True
if self.wr in self.bkScope:
self.bkScope.remove(self.wr)
for t in self.bkScope:
if t not in self.wrScope:
if t not in self.wkScope:
self.bk = t
self.theend = False
break
if self.theend == False:
return self.bk
else:
return 'call gameEnds'
def white_possible_moves(self):
"""there's a catch wk and wr can't occupy each others positions unless the rook is under attack THE SUBTLE BUG, INTERDEPENDENCY
you don't need to do this check right yet , do it just before the white pieces move cuz it's affecting BK behavior
if self.wr in self.wkScope:
self.wkScope.remove(self.wr)
if self.wk in self.wrScope:
self.wrScope.remove(self.wk) """
for i in range(1, 9):
if i != self.wr[0]:
self.wrScope.append((i, self.wr[1]))
if i != self.wr[1]:
self.wrScope.append((self.wr[0], i))
for (x, y) in self.adj_king:
temp = (self.wk[0] + x, self.wk[1] + y)
if temp[0] < 9 and temp[0] > 0:
if temp[1] < 9 and temp[1] > 0:
self.wkScope.append(temp)
trim = [z for z in self.wrScope if z[1] == self.wk[1]]
if trim != []:
if self.wk[0] > self.wr[0]:
trim = [z for z in trim if z[0] > self.wk[0]]
elif self.wk[0] < self.wr[0]:
trim = [z for z in trim if z[0] < self.wk[0]]
for tr in trim:
try:
self.wrScope.remove(tr)
except ValueError:
pass
trim = [z for z in self.wrScope if z[0] == self.wk[0]]
if trim != []:
if self.wk[1] > self.wr[1]:
trim = [z for z in trim if z[1] > self.wk[1]]
elif self.wk[1] < self.wr[1]:
trim = [z for z in trim if z[1] < self.wk[1]]
for tr in trim:
try:
self.wrScope.remove(tr)
except ValueError:
pass
if self.bk[0] == self.wr[0] or self.bk[1] == self.wr[1]:
if self.bk not in self.wrScope:
self.wrScope.append(self.bk)
def game_ends(self):
""" check for check/stale mate and other end game functionality later to be added :)"""
if self.bk in self.wkScope or self.bk in self.wrScope:
return 'checkmate'
else:
return 'stalemate'
def adjust_whitemove(self):
trim = [z for z in self.wrScope if z[1] == self.bk[1]]
if trim != []:
if self.bk[0] > self.wr[0]:
trim = [z for z in trim if z[0] > self.bk[0]]
elif self.bk[0] < self.wr[0]:
trim = [z for z in trim if z[0] < self.bk[0]]
for tr in trim:
try:
self.wrScope.remove(tr)
except ValueError:
pass
trim = [z for z in self.wrScope if z[0] == self.bk[0]]
if trim != []:
if self.bk[1] > self.wr[1]:
trim = [z for z in trim if z[1] > self.bk[1]]
elif self.bk[1] < self.wr[1]:
trim = [z for z in trim if z[1] < self.bk[1]]
for tr in trim:
try:
self.wrScope.remove(tr)
except ValueError:
pass
if self.wr in self.wkScope:
self.wkScope.remove(self.wr)
if self.wk in self.wrScope:
self.wrScope.remove(self.wk)
full_bkscope = []
for (x, y) in self.adj_king:
temp = (self.bk[0] + x, self.bk[1] + y)
if temp[0] < 9 and temp[0] > 0:
if temp[1] < 9 and temp[1] > 0:
full_bkscope.append(temp)
to_remove = [r for r in self.wrScope if r in full_bkscope and r not in self.wkScope]
self.wrScope = [x for x in self.wrScope if x not in to_remove]
self.wkScope = [x for x in self.wkScope if x not in full_bkscope] |
travel_route = input().split('||')
amount_of_fuel = int(input())
amount_of_ammunition = int(input())
travelled_distance = 0
for x in travel_route:
current_command = x.split(' ')
command = current_command[0]
if command == 'Travel':
value = int(current_command[1])
if amount_of_fuel >= value:
travelled_distance += value
amount_of_fuel -= value
print(f'The spaceship travelled {value} light-years.')
else:
print("Mission failed.")
break
elif command == 'Enemy':
value = int(current_command[1])
if amount_of_ammunition >= value:
amount_of_ammunition -= value
print(f'An enemy with {value} armour is defeated.')
elif amount_of_ammunition < value:
if amount_of_fuel >= value * 2:
amount_of_fuel -= value * 2
print(f'An enemy with {value} armour is outmaneuvered.')
else:
print('Mission failed.')
break
elif command == 'Repair':
value = int(current_command[1])
amount_of_fuel += value
amount_of_ammunition += value * 2
print(f'Ammunitions added: {value*2}.')
print(f'Fuel added: {value}.')
elif command == 'Titan':
print('You have reached Titan, all passengers are safe.')
| travel_route = input().split('||')
amount_of_fuel = int(input())
amount_of_ammunition = int(input())
travelled_distance = 0
for x in travel_route:
current_command = x.split(' ')
command = current_command[0]
if command == 'Travel':
value = int(current_command[1])
if amount_of_fuel >= value:
travelled_distance += value
amount_of_fuel -= value
print(f'The spaceship travelled {value} light-years.')
else:
print('Mission failed.')
break
elif command == 'Enemy':
value = int(current_command[1])
if amount_of_ammunition >= value:
amount_of_ammunition -= value
print(f'An enemy with {value} armour is defeated.')
elif amount_of_ammunition < value:
if amount_of_fuel >= value * 2:
amount_of_fuel -= value * 2
print(f'An enemy with {value} armour is outmaneuvered.')
else:
print('Mission failed.')
break
elif command == 'Repair':
value = int(current_command[1])
amount_of_fuel += value
amount_of_ammunition += value * 2
print(f'Ammunitions added: {value * 2}.')
print(f'Fuel added: {value}.')
elif command == 'Titan':
print('You have reached Titan, all passengers are safe.') |
'''
Author : MiKueen
Level : Medium
Problem Statement : Subarray Sum Equals K
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Constraints:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
'''
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
# Time Complexity - O(n)
# Space Complexity - O(n)
curr_sum = res = 0
mapping = defaultdict(int)
for i in nums:
curr_sum += i
if (curr_sum - k) in mapping:
res += mapping[curr_sum - k]
mapping[curr_sum] += 1
res += mapping[k]
return res
| """
Author : MiKueen
Level : Medium
Problem Statement : Subarray Sum Equals K
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Constraints:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
"""
class Solution:
def subarray_sum(self, nums: List[int], k: int) -> int:
curr_sum = res = 0
mapping = defaultdict(int)
for i in nums:
curr_sum += i
if curr_sum - k in mapping:
res += mapping[curr_sum - k]
mapping[curr_sum] += 1
res += mapping[k]
return res |
class Node:
@property
def label(self):
return self.__label
@property
def left_child(self):
return self.__left_child
@left_child.setter
def left_child(self, n):
self.__left_child = n
self.__left_child.parent = self
@property
def right_sibling(self):
return self.__right_sibling
@right_sibling.setter
def right_sibling(self, n):
self.__right_sibling = n
self.__right_sibling.parent = self.parent
@property
def parent(self):
return self.__parent
@parent.setter
def parent(self, n):
self.__parent = n
def __init__(self, label):
self.__label = label
self.__left_child: Node = None
self.__right_sibling: Node = None
self.__parent: Node = None
def add_child(self, n):
if self.__left_child is None:
self.__left_child = n
| class Node:
@property
def label(self):
return self.__label
@property
def left_child(self):
return self.__left_child
@left_child.setter
def left_child(self, n):
self.__left_child = n
self.__left_child.parent = self
@property
def right_sibling(self):
return self.__right_sibling
@right_sibling.setter
def right_sibling(self, n):
self.__right_sibling = n
self.__right_sibling.parent = self.parent
@property
def parent(self):
return self.__parent
@parent.setter
def parent(self, n):
self.__parent = n
def __init__(self, label):
self.__label = label
self.__left_child: Node = None
self.__right_sibling: Node = None
self.__parent: Node = None
def add_child(self, n):
if self.__left_child is None:
self.__left_child = n |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
function
'''
def area(width, height=10):
'''
area
'''
print('width=%s, height=%s' % (width, height))
return width*height
print(area(10, 20))
print(area(height=10, width=20))
print(area(10))
def sum(a, b, *c):
'''
sum
'''
d = a+b
for i in c:
d = d+i
return d
print(sum(1, 2))
print(sum(1, 2, 3, 4, 5))
sum1 = lambda a, b: a+b
print(sum1(1, 2))
print(__name__)
| """
function
"""
def area(width, height=10):
"""
area
"""
print('width=%s, height=%s' % (width, height))
return width * height
print(area(10, 20))
print(area(height=10, width=20))
print(area(10))
def sum(a, b, *c):
"""
sum
"""
d = a + b
for i in c:
d = d + i
return d
print(sum(1, 2))
print(sum(1, 2, 3, 4, 5))
sum1 = lambda a, b: a + b
print(sum1(1, 2))
print(__name__) |
# DEFEAT
# https://www.codechef.com/UNCO2021/problems/DEFEAT
NMK = [int(i) for i in input().split()]
matrix = []
for column in range(NMK[1]):
matrix.append([0]* NMK[0])
enemyLoc = []
for enemy in range(NMK[2]):
enemyLoc.append([i for i in input().split()])
for enemy in range(NMK[2]):
for enemyRow in enemyLoc[enemy][0]:
for enemyCol in enemyLoc[enemy][1]:
matrix[int(enemyRow)-1][int(enemyCol)-1] += 1
def noOfenemies(rowNo, colNo, matrix):
rowEnemy = 0
for col in range(len(matrix)):
rowEnemy += matrix[rowNo][col]
colEnemy = 0
for row in range(len(matrix[0])):
colEnemy += matrix[row][colNo]
if matrix[rowNo][colNo] == 1 :
return(rowEnemy + colEnemy - 1)
else :
return(rowEnemy + colEnemy)
totalEnemy = []
for r in range(len(matrix)):
for c in range(len(matrix[0])):
totalEnemy.append(noOfenemies(r, c, matrix))
totalEnemy.sort()
print(totalEnemy[-1])
| nmk = [int(i) for i in input().split()]
matrix = []
for column in range(NMK[1]):
matrix.append([0] * NMK[0])
enemy_loc = []
for enemy in range(NMK[2]):
enemyLoc.append([i for i in input().split()])
for enemy in range(NMK[2]):
for enemy_row in enemyLoc[enemy][0]:
for enemy_col in enemyLoc[enemy][1]:
matrix[int(enemyRow) - 1][int(enemyCol) - 1] += 1
def no_ofenemies(rowNo, colNo, matrix):
row_enemy = 0
for col in range(len(matrix)):
row_enemy += matrix[rowNo][col]
col_enemy = 0
for row in range(len(matrix[0])):
col_enemy += matrix[row][colNo]
if matrix[rowNo][colNo] == 1:
return rowEnemy + colEnemy - 1
else:
return rowEnemy + colEnemy
total_enemy = []
for r in range(len(matrix)):
for c in range(len(matrix[0])):
totalEnemy.append(no_ofenemies(r, c, matrix))
totalEnemy.sort()
print(totalEnemy[-1]) |
class UvMap(object):
def __init__(self, coords=[], texture_file_name='', name=''):
self.coords = tuple(coords)
self.texture_file_name = texture_file_name
self.name = name
| class Uvmap(object):
def __init__(self, coords=[], texture_file_name='', name=''):
self.coords = tuple(coords)
self.texture_file_name = texture_file_name
self.name = name |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'cc_source_files': [
'animation.cc',
'animation.h',
'animation_curve.cc',
'animation_curve.h',
'animation_events.h',
'animation_id_provider.cc',
'animation_id_provider.h',
'animation_registrar.cc',
'animation_registrar.h',
'append_quads_data.h',
'bitmap_content_layer_updater.cc',
'bitmap_content_layer_updater.h',
'bitmap_skpicture_content_layer_updater.cc',
'bitmap_skpicture_content_layer_updater.h',
'caching_bitmap_content_layer_updater.cc',
'caching_bitmap_content_layer_updater.h',
'checkerboard_draw_quad.cc',
'checkerboard_draw_quad.h',
'completion_event.h',
'compositor_frame.cc',
'compositor_frame.h',
'compositor_frame_ack.cc',
'compositor_frame_ack.h',
'compositor_frame_metadata.cc',
'compositor_frame_metadata.h',
'content_layer.cc',
'content_layer.h',
'content_layer_client.h',
'content_layer_updater.cc',
'content_layer_updater.h',
'contents_scaling_layer.cc',
'contents_scaling_layer.h',
'context_provider.h',
'damage_tracker.cc',
'damage_tracker.h',
'debug_border_draw_quad.cc',
'debug_border_draw_quad.h',
'debug_colors.cc',
'debug_colors.h',
'debug_rect_history.cc',
'debug_rect_history.h',
'delay_based_time_source.cc',
'delay_based_time_source.h',
'delegated_frame_data.h',
'delegated_frame_data.cc',
'delegated_renderer_layer.cc',
'delegated_renderer_layer.h',
'delegated_renderer_layer_impl.cc',
'delegated_renderer_layer_impl.h',
'delegating_renderer.cc',
'delegating_renderer.h',
'devtools_instrumentation.h',
'direct_renderer.cc',
'direct_renderer.h',
'draw_properties.h',
'draw_quad.cc',
'draw_quad.h',
'fake_web_graphics_context_3d.cc',
'fake_web_graphics_context_3d.h',
'frame_rate_controller.cc',
'frame_rate_controller.h',
'frame_rate_counter.cc',
'frame_rate_counter.h',
'geometry_binding.cc',
'geometry_binding.h',
'gl_frame_data.h',
'gl_frame_data.cc',
'gl_renderer.cc',
'gl_renderer.h',
'gl_renderer_draw_cache.cc',
'gl_renderer_draw_cache.h',
'hash_pair.h',
'heads_up_display_layer.cc',
'heads_up_display_layer.h',
'heads_up_display_layer_impl.cc',
'heads_up_display_layer_impl.h',
'image_layer_updater.cc',
'image_layer_updater.h',
'image_layer.cc',
'image_layer.h',
'input_handler.h',
'io_surface_draw_quad.cc',
'io_surface_draw_quad.h',
'io_surface_layer.cc',
'io_surface_layer.h',
'io_surface_layer_impl.cc',
'io_surface_layer_impl.h',
'keyframed_animation_curve.cc',
'keyframed_animation_curve.h',
'layer.cc',
'layer.h',
'layer_animation_controller.cc',
'layer_animation_controller.h',
'layer_animation_event_observer.h',
'layer_animation_value_observer.h',
'layer_impl.cc',
'layer_impl.h',
'layer_iterator.cc',
'layer_iterator.h',
'layer_painter.h',
'layer_quad.cc',
'layer_quad.h',
'layer_sorter.cc',
'layer_sorter.h',
'layer_tiling_data.cc',
'layer_tiling_data.h',
'layer_tree_debug_state.cc',
'layer_tree_debug_state.h',
'layer_tree_host.cc',
'layer_tree_host.h',
'layer_tree_host_client.h',
'layer_tree_host_common.cc',
'layer_tree_host_common.h',
'layer_tree_host_impl.cc',
'layer_tree_host_impl.h',
'layer_tree_impl.cc',
'layer_tree_impl.h',
'layer_tree_settings.cc',
'layer_tree_settings.h',
'layer_updater.cc',
'layer_updater.h',
'managed_memory_policy.cc',
'managed_memory_policy.h',
'math_util.cc',
'math_util.h',
'memory_history.cc',
'memory_history.h',
'nine_patch_layer.cc',
'nine_patch_layer.h',
'nine_patch_layer_impl.cc',
'nine_patch_layer_impl.h',
'occlusion_tracker.cc',
'occlusion_tracker.h',
'output_surface.cc',
'output_surface.h',
'output_surface_client.h',
'overdraw_metrics.cc',
'overdraw_metrics.h',
'page_scale_animation.cc',
'page_scale_animation.h',
'paint_time_counter.cc',
'paint_time_counter.h',
'picture.cc',
'picture.h',
'picture_image_layer.cc',
'picture_image_layer.h',
'picture_image_layer_impl.cc',
'picture_image_layer_impl.h',
'picture_layer.cc',
'picture_layer.h',
'picture_layer_impl.cc',
'picture_layer_impl.h',
'picture_layer_tiling.cc',
'picture_layer_tiling.h',
'picture_layer_tiling_set.cc',
'picture_layer_tiling_set.h',
'picture_pile.cc',
'picture_pile.h',
'picture_pile_base.cc',
'picture_pile_base.h',
'picture_pile_impl.cc',
'picture_pile_impl.h',
'platform_color.h',
'prioritized_resource.cc',
'prioritized_resource.h',
'prioritized_resource_manager.cc',
'prioritized_resource_manager.h',
'priority_calculator.cc',
'priority_calculator.h',
'program_binding.cc',
'program_binding.h',
'proxy.cc',
'proxy.h',
'quad_culler.cc',
'quad_culler.h',
'quad_sink.h',
'raster_worker_pool.cc',
'raster_worker_pool.h',
'rate_limiter.cc',
'rate_limiter.h',
'region.cc',
'region.h',
'render_pass.cc',
'render_pass.h',
'render_pass_draw_quad.cc',
'render_pass_draw_quad.h',
'render_pass_sink.h',
'render_surface.cc',
'render_surface.h',
'render_surface_filters.cc',
'render_surface_filters.h',
'render_surface_impl.cc',
'render_surface_impl.h',
'renderer.cc',
'renderer.h',
'rendering_stats.cc',
'rendering_stats.h',
'resource.cc',
'resource.h',
'resource_pool.cc',
'resource_pool.h',
'resource_provider.cc',
'resource_provider.h',
'resource_update.cc',
'resource_update.h',
'resource_update_controller.cc',
'resource_update_controller.h',
'resource_update_queue.cc',
'resource_update_queue.h',
'ring_buffer.h',
'scheduler.cc',
'scheduler.h',
'scheduler_settings.cc',
'scheduler_settings.h',
'scheduler_state_machine.cc',
'scheduler_state_machine.h',
'scoped_ptr_algorithm.h',
'scoped_ptr_deque.h',
'scoped_ptr_hash_map.h',
'scoped_ptr_vector.h',
'scoped_resource.cc',
'scoped_resource.h',
'scrollbar_animation_controller.h',
'scrollbar_animation_controller_linear_fade.cc',
'scrollbar_animation_controller_linear_fade.h',
'scrollbar_geometry_fixed_thumb.cc',
'scrollbar_geometry_fixed_thumb.h',
'scrollbar_geometry_stub.cc',
'scrollbar_geometry_stub.h',
'scrollbar_layer.cc',
'scrollbar_layer.h',
'scrollbar_layer_impl.cc',
'scrollbar_layer_impl.h',
'scrollbar_layer_impl_base.h',
'shader.cc',
'shader.h',
'shared_quad_state.cc',
'shared_quad_state.h',
'single_thread_proxy.cc',
'single_thread_proxy.h',
'skpicture_content_layer_updater.cc',
'skpicture_content_layer_updater.h',
'software_output_device.h',
'software_renderer.cc',
'software_renderer.h',
'solid_color_draw_quad.cc',
'solid_color_draw_quad.h',
'solid_color_layer.cc',
'solid_color_layer.h',
'solid_color_layer_impl.cc',
'solid_color_layer_impl.h',
'stream_video_draw_quad.cc',
'stream_video_draw_quad.h',
'switches.cc',
'switches.h',
'texture_copier.cc',
'texture_copier.h',
'texture_draw_quad.cc',
'texture_draw_quad.h',
'texture_layer.cc',
'texture_layer.h',
'texture_layer_client.h',
'texture_layer_impl.cc',
'texture_layer_impl.h',
'texture_mailbox.cc',
'texture_mailbox.h',
'texture_uploader.cc',
'texture_uploader.h',
'thread.h',
'thread_impl.cc',
'thread_impl.h',
'thread_proxy.cc',
'thread_proxy.h',
'tile.cc',
'tile.h',
'tile_draw_quad.cc',
'tile_draw_quad.h',
'tile_manager.cc',
'tile_manager.h',
'tile_priority.cc',
'tile_priority.h',
'tiled_layer.cc',
'tiled_layer.h',
'tiled_layer_impl.cc',
'tiled_layer_impl.h',
'tiling_data.cc',
'tiling_data.h',
'time_source.h',
'timing_function.cc',
'timing_function.h',
'top_controls_manager.cc',
'top_controls_manager.h',
'top_controls_manager_client.h',
'transferable_resource.cc',
'transferable_resource.h',
'transform_operation.cc',
'transform_operation.h',
'transform_operations.cc',
'transform_operations.h',
'tree_synchronizer.cc',
'tree_synchronizer.h',
'util.h',
'video_frame_provider.h',
'video_frame_provider_client_impl.cc',
'video_frame_provider_client_impl.h',
'video_layer.cc',
'video_layer.h',
'video_layer_impl.cc',
'video_layer_impl.h',
'vsync_time_source.cc',
'vsync_time_source.h',
'worker_pool.cc',
'worker_pool.h',
'yuv_video_draw_quad.cc',
'yuv_video_draw_quad.h',
],
'conditions': [
['inside_chromium_build==1', {
'webkit_src_dir': '<(DEPTH)/third_party/WebKit',
}, {
'webkit_src_dir': '<(DEPTH)/../../..',
}],
],
},
'conditions': [
['inside_chromium_build==0', {
'defines': [
'INSIDE_WEBKIT_BUILD=1',
],
}],
],
'targets': [
{
'target_name': 'cc',
'type': '<(component)',
'dependencies': [
'<(DEPTH)/base/base.gyp:base',
'<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',
'<(DEPTH)/gpu/gpu.gyp:gpu',
'<(DEPTH)/skia/skia.gyp:skia',
'<(DEPTH)/media/media.gyp:media',
'<(DEPTH)/ui/gl/gl.gyp:gl',
'<(DEPTH)/ui/ui.gyp:ui',
'<(webkit_src_dir)/Source/WebKit/chromium/WebKit.gyp:webkit',
],
'defines': [
'CC_IMPLEMENTATION=1',
],
'sources': [
'<@(cc_source_files)',
],
# TODO(jschuh): crbug.com/167187 fix size_t to int truncations.
'msvs_disabled_warnings': [ 4267, ],
},
],
}
| {'variables': {'cc_source_files': ['animation.cc', 'animation.h', 'animation_curve.cc', 'animation_curve.h', 'animation_events.h', 'animation_id_provider.cc', 'animation_id_provider.h', 'animation_registrar.cc', 'animation_registrar.h', 'append_quads_data.h', 'bitmap_content_layer_updater.cc', 'bitmap_content_layer_updater.h', 'bitmap_skpicture_content_layer_updater.cc', 'bitmap_skpicture_content_layer_updater.h', 'caching_bitmap_content_layer_updater.cc', 'caching_bitmap_content_layer_updater.h', 'checkerboard_draw_quad.cc', 'checkerboard_draw_quad.h', 'completion_event.h', 'compositor_frame.cc', 'compositor_frame.h', 'compositor_frame_ack.cc', 'compositor_frame_ack.h', 'compositor_frame_metadata.cc', 'compositor_frame_metadata.h', 'content_layer.cc', 'content_layer.h', 'content_layer_client.h', 'content_layer_updater.cc', 'content_layer_updater.h', 'contents_scaling_layer.cc', 'contents_scaling_layer.h', 'context_provider.h', 'damage_tracker.cc', 'damage_tracker.h', 'debug_border_draw_quad.cc', 'debug_border_draw_quad.h', 'debug_colors.cc', 'debug_colors.h', 'debug_rect_history.cc', 'debug_rect_history.h', 'delay_based_time_source.cc', 'delay_based_time_source.h', 'delegated_frame_data.h', 'delegated_frame_data.cc', 'delegated_renderer_layer.cc', 'delegated_renderer_layer.h', 'delegated_renderer_layer_impl.cc', 'delegated_renderer_layer_impl.h', 'delegating_renderer.cc', 'delegating_renderer.h', 'devtools_instrumentation.h', 'direct_renderer.cc', 'direct_renderer.h', 'draw_properties.h', 'draw_quad.cc', 'draw_quad.h', 'fake_web_graphics_context_3d.cc', 'fake_web_graphics_context_3d.h', 'frame_rate_controller.cc', 'frame_rate_controller.h', 'frame_rate_counter.cc', 'frame_rate_counter.h', 'geometry_binding.cc', 'geometry_binding.h', 'gl_frame_data.h', 'gl_frame_data.cc', 'gl_renderer.cc', 'gl_renderer.h', 'gl_renderer_draw_cache.cc', 'gl_renderer_draw_cache.h', 'hash_pair.h', 'heads_up_display_layer.cc', 'heads_up_display_layer.h', 'heads_up_display_layer_impl.cc', 'heads_up_display_layer_impl.h', 'image_layer_updater.cc', 'image_layer_updater.h', 'image_layer.cc', 'image_layer.h', 'input_handler.h', 'io_surface_draw_quad.cc', 'io_surface_draw_quad.h', 'io_surface_layer.cc', 'io_surface_layer.h', 'io_surface_layer_impl.cc', 'io_surface_layer_impl.h', 'keyframed_animation_curve.cc', 'keyframed_animation_curve.h', 'layer.cc', 'layer.h', 'layer_animation_controller.cc', 'layer_animation_controller.h', 'layer_animation_event_observer.h', 'layer_animation_value_observer.h', 'layer_impl.cc', 'layer_impl.h', 'layer_iterator.cc', 'layer_iterator.h', 'layer_painter.h', 'layer_quad.cc', 'layer_quad.h', 'layer_sorter.cc', 'layer_sorter.h', 'layer_tiling_data.cc', 'layer_tiling_data.h', 'layer_tree_debug_state.cc', 'layer_tree_debug_state.h', 'layer_tree_host.cc', 'layer_tree_host.h', 'layer_tree_host_client.h', 'layer_tree_host_common.cc', 'layer_tree_host_common.h', 'layer_tree_host_impl.cc', 'layer_tree_host_impl.h', 'layer_tree_impl.cc', 'layer_tree_impl.h', 'layer_tree_settings.cc', 'layer_tree_settings.h', 'layer_updater.cc', 'layer_updater.h', 'managed_memory_policy.cc', 'managed_memory_policy.h', 'math_util.cc', 'math_util.h', 'memory_history.cc', 'memory_history.h', 'nine_patch_layer.cc', 'nine_patch_layer.h', 'nine_patch_layer_impl.cc', 'nine_patch_layer_impl.h', 'occlusion_tracker.cc', 'occlusion_tracker.h', 'output_surface.cc', 'output_surface.h', 'output_surface_client.h', 'overdraw_metrics.cc', 'overdraw_metrics.h', 'page_scale_animation.cc', 'page_scale_animation.h', 'paint_time_counter.cc', 'paint_time_counter.h', 'picture.cc', 'picture.h', 'picture_image_layer.cc', 'picture_image_layer.h', 'picture_image_layer_impl.cc', 'picture_image_layer_impl.h', 'picture_layer.cc', 'picture_layer.h', 'picture_layer_impl.cc', 'picture_layer_impl.h', 'picture_layer_tiling.cc', 'picture_layer_tiling.h', 'picture_layer_tiling_set.cc', 'picture_layer_tiling_set.h', 'picture_pile.cc', 'picture_pile.h', 'picture_pile_base.cc', 'picture_pile_base.h', 'picture_pile_impl.cc', 'picture_pile_impl.h', 'platform_color.h', 'prioritized_resource.cc', 'prioritized_resource.h', 'prioritized_resource_manager.cc', 'prioritized_resource_manager.h', 'priority_calculator.cc', 'priority_calculator.h', 'program_binding.cc', 'program_binding.h', 'proxy.cc', 'proxy.h', 'quad_culler.cc', 'quad_culler.h', 'quad_sink.h', 'raster_worker_pool.cc', 'raster_worker_pool.h', 'rate_limiter.cc', 'rate_limiter.h', 'region.cc', 'region.h', 'render_pass.cc', 'render_pass.h', 'render_pass_draw_quad.cc', 'render_pass_draw_quad.h', 'render_pass_sink.h', 'render_surface.cc', 'render_surface.h', 'render_surface_filters.cc', 'render_surface_filters.h', 'render_surface_impl.cc', 'render_surface_impl.h', 'renderer.cc', 'renderer.h', 'rendering_stats.cc', 'rendering_stats.h', 'resource.cc', 'resource.h', 'resource_pool.cc', 'resource_pool.h', 'resource_provider.cc', 'resource_provider.h', 'resource_update.cc', 'resource_update.h', 'resource_update_controller.cc', 'resource_update_controller.h', 'resource_update_queue.cc', 'resource_update_queue.h', 'ring_buffer.h', 'scheduler.cc', 'scheduler.h', 'scheduler_settings.cc', 'scheduler_settings.h', 'scheduler_state_machine.cc', 'scheduler_state_machine.h', 'scoped_ptr_algorithm.h', 'scoped_ptr_deque.h', 'scoped_ptr_hash_map.h', 'scoped_ptr_vector.h', 'scoped_resource.cc', 'scoped_resource.h', 'scrollbar_animation_controller.h', 'scrollbar_animation_controller_linear_fade.cc', 'scrollbar_animation_controller_linear_fade.h', 'scrollbar_geometry_fixed_thumb.cc', 'scrollbar_geometry_fixed_thumb.h', 'scrollbar_geometry_stub.cc', 'scrollbar_geometry_stub.h', 'scrollbar_layer.cc', 'scrollbar_layer.h', 'scrollbar_layer_impl.cc', 'scrollbar_layer_impl.h', 'scrollbar_layer_impl_base.h', 'shader.cc', 'shader.h', 'shared_quad_state.cc', 'shared_quad_state.h', 'single_thread_proxy.cc', 'single_thread_proxy.h', 'skpicture_content_layer_updater.cc', 'skpicture_content_layer_updater.h', 'software_output_device.h', 'software_renderer.cc', 'software_renderer.h', 'solid_color_draw_quad.cc', 'solid_color_draw_quad.h', 'solid_color_layer.cc', 'solid_color_layer.h', 'solid_color_layer_impl.cc', 'solid_color_layer_impl.h', 'stream_video_draw_quad.cc', 'stream_video_draw_quad.h', 'switches.cc', 'switches.h', 'texture_copier.cc', 'texture_copier.h', 'texture_draw_quad.cc', 'texture_draw_quad.h', 'texture_layer.cc', 'texture_layer.h', 'texture_layer_client.h', 'texture_layer_impl.cc', 'texture_layer_impl.h', 'texture_mailbox.cc', 'texture_mailbox.h', 'texture_uploader.cc', 'texture_uploader.h', 'thread.h', 'thread_impl.cc', 'thread_impl.h', 'thread_proxy.cc', 'thread_proxy.h', 'tile.cc', 'tile.h', 'tile_draw_quad.cc', 'tile_draw_quad.h', 'tile_manager.cc', 'tile_manager.h', 'tile_priority.cc', 'tile_priority.h', 'tiled_layer.cc', 'tiled_layer.h', 'tiled_layer_impl.cc', 'tiled_layer_impl.h', 'tiling_data.cc', 'tiling_data.h', 'time_source.h', 'timing_function.cc', 'timing_function.h', 'top_controls_manager.cc', 'top_controls_manager.h', 'top_controls_manager_client.h', 'transferable_resource.cc', 'transferable_resource.h', 'transform_operation.cc', 'transform_operation.h', 'transform_operations.cc', 'transform_operations.h', 'tree_synchronizer.cc', 'tree_synchronizer.h', 'util.h', 'video_frame_provider.h', 'video_frame_provider_client_impl.cc', 'video_frame_provider_client_impl.h', 'video_layer.cc', 'video_layer.h', 'video_layer_impl.cc', 'video_layer_impl.h', 'vsync_time_source.cc', 'vsync_time_source.h', 'worker_pool.cc', 'worker_pool.h', 'yuv_video_draw_quad.cc', 'yuv_video_draw_quad.h'], 'conditions': [['inside_chromium_build==1', {'webkit_src_dir': '<(DEPTH)/third_party/WebKit'}, {'webkit_src_dir': '<(DEPTH)/../../..'}]]}, 'conditions': [['inside_chromium_build==0', {'defines': ['INSIDE_WEBKIT_BUILD=1']}]], 'targets': [{'target_name': 'cc', 'type': '<(component)', 'dependencies': ['<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '<(DEPTH)/gpu/gpu.gyp:gpu', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/media/media.gyp:media', '<(DEPTH)/ui/gl/gl.gyp:gl', '<(DEPTH)/ui/ui.gyp:ui', '<(webkit_src_dir)/Source/WebKit/chromium/WebKit.gyp:webkit'], 'defines': ['CC_IMPLEMENTATION=1'], 'sources': ['<@(cc_source_files)'], 'msvs_disabled_warnings': [4267]}]} |
class FileLock:
def __init__(self, filename):
self.filename = filename
with open(self.filename, 'w') as f:
f.write('done')
def lock(self):
with open(self.filename, 'w') as f:
f.write('working')
def unlock(self):
with open(self.filename, 'w') as f:
f.write('done')
def is_locked(self):
return open(self.filename, 'r').read() == 'working'
| class Filelock:
def __init__(self, filename):
self.filename = filename
with open(self.filename, 'w') as f:
f.write('done')
def lock(self):
with open(self.filename, 'w') as f:
f.write('working')
def unlock(self):
with open(self.filename, 'w') as f:
f.write('done')
def is_locked(self):
return open(self.filename, 'r').read() == 'working' |
# Approach 1
def reverseList(A, start, end):
while start < end:
A[start], A[end] = A[end], A[start]
start += 1
end -= 1
# reverseList([1, 2, 3, 4, 5, 6], 0, 5) = [6 5 4 3 2 1]
# Approach 2
def reverseList(A, start, end):
if start >= end:
return
A[start], A[end] = A[end], A[start]
reverseList(A, start+1, end-1)
# reverseList([1, 2, 3, 4, 5, 6], 0, 5) = [6 5 4 3 2 1]
| def reverse_list(A, start, end):
while start < end:
(A[start], A[end]) = (A[end], A[start])
start += 1
end -= 1
def reverse_list(A, start, end):
if start >= end:
return
(A[start], A[end]) = (A[end], A[start])
reverse_list(A, start + 1, end - 1) |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 22 12:37:10 2020
@author: Arthur Donizeti Rodrigues Dias
"""
def arithmetic_arranger(problems, resultado = False):
lista =[]
listaNumero = []
listaOperador = []
listaSoma = []
listaFormatada = []
listaFormatada2 = []
listaFormatada3 = []
listaFormatada4 = []
for problem in problems:
lista.extend(problem.split())
for valor in lista:
if valor == '+' or valor == '-':
listaOperador.append(valor)
elif valor == '*' or valor == '/':
return("Error: Operator must be '+' or '-'.")
else:
listaNumero.append(valor)
try:
for numero in listaNumero:
int(numero)
if len(numero)>4:
return 'Error: Numbers cannot be more than four digits.'
except:
return('Error: Numbers must only contain digits.')
if len(problems)>5:
return("Error: Too many problems.")
else:
n =0
for operador in listaOperador:
if operador == '+':
teste = int(listaNumero[n]) + int(listaNumero[n+1])
listaSoma.append(teste)
n =n+2
elif operador == '-':
teste = int(listaNumero[n]) - int(listaNumero[n+1])
listaSoma.append(teste)
n =n+2
n = 0
m =1
o = 0
for conta in listaOperador:
if (len(listaNumero[m])==4):
teste1 = listaNumero[n].rjust(6)
teste2 = (listaOperador[o].ljust(2)+listaNumero[m]).rjust(6)
teste3 = '------'
teste4 = str(listaSoma[o]).rjust(6)
elif len(listaNumero[m])==3 :
if len(listaNumero[n])==4:
teste1 = listaNumero[n].rjust(6)
teste2 = (listaOperador[o].ljust(3)+listaNumero[m]).rjust(6)
teste3 = '------'
teste4 = str(listaSoma[o]).rjust(6)
else:
teste1 = listaNumero[n].rjust(5)
teste2 = (listaOperador[o].ljust(2)+listaNumero[m]).rjust(5)
teste3 = '-----'
teste4 = str(listaSoma[o]).rjust(5)
elif len(listaNumero[m])==2 :
if len(listaNumero[n])==4:
teste1 = listaNumero[n].rjust(6)
teste2 = (listaOperador[o].ljust(4)+listaNumero[m]).rjust(6)
teste3 = '------'
teste4 = str(listaSoma[o]).rjust(6)
elif len(listaNumero[n])==3:
teste1 = listaNumero[n].rjust(5)
teste2 = (listaOperador[o].ljust(3)+listaNumero[m]).rjust(5)
teste3 = '-----'
teste4 = str(listaSoma[o]).rjust(5)
else:
teste1 = listaNumero[n].rjust(4)
teste2 = (listaOperador[o].ljust(2)+listaNumero[m]).rjust(4)
teste3 = '----'
teste4 = str(listaSoma[o]).rjust(4)
elif len(listaNumero[m])==1 :
if len(listaNumero[n])==4:
teste1 = listaNumero[n].rjust(6)
teste2 = (listaOperador[o].ljust(5)+listaNumero[m]).rjust(6)
teste3 = '------'
teste4 = str(listaSoma[o]).rjust(6)
elif len(listaNumero[n])==3:
teste1 = listaNumero[n].rjust(5)
teste2 = (listaOperador[o].ljust(4)+listaNumero[m]).rjust(5)
teste3 = '-----'
teste4 = str(listaSoma[o]).rjust(5)
elif len(listaNumero[n])==2:
teste1 = listaNumero[n].rjust(4)
teste2 = (listaOperador[o].ljust(3)+listaNumero[m]).rjust(4)
teste3 = '----'
teste4 = str(listaSoma[o]).rjust(4)
else:
teste1 = listaNumero[n].rjust(3)
teste2 = (listaOperador[o].ljust(2)+listaNumero[m]).rjust(3)
teste3 = '---'
teste4 = str(listaSoma[o]).rjust(3)
listaFormatada.append(teste1)
listaFormatada2.append(teste2)
listaFormatada3.append(teste3)
listaFormatada4.append(teste4)
n = n+2
m = m+2
o = o+1
s=' '.join(listaFormatada)+'\n'+' '.join(listaFormatada2)+'\n'+' '.join(listaFormatada3)
soma = s+'\n'+' '.join(listaFormatada4)
if resultado == True:
return soma
else:
return s
| """
Created on Wed Jul 22 12:37:10 2020
@author: Arthur Donizeti Rodrigues Dias
"""
def arithmetic_arranger(problems, resultado=False):
lista = []
lista_numero = []
lista_operador = []
lista_soma = []
lista_formatada = []
lista_formatada2 = []
lista_formatada3 = []
lista_formatada4 = []
for problem in problems:
lista.extend(problem.split())
for valor in lista:
if valor == '+' or valor == '-':
listaOperador.append(valor)
elif valor == '*' or valor == '/':
return "Error: Operator must be '+' or '-'."
else:
listaNumero.append(valor)
try:
for numero in listaNumero:
int(numero)
if len(numero) > 4:
return 'Error: Numbers cannot be more than four digits.'
except:
return 'Error: Numbers must only contain digits.'
if len(problems) > 5:
return 'Error: Too many problems.'
else:
n = 0
for operador in listaOperador:
if operador == '+':
teste = int(listaNumero[n]) + int(listaNumero[n + 1])
listaSoma.append(teste)
n = n + 2
elif operador == '-':
teste = int(listaNumero[n]) - int(listaNumero[n + 1])
listaSoma.append(teste)
n = n + 2
n = 0
m = 1
o = 0
for conta in listaOperador:
if len(listaNumero[m]) == 4:
teste1 = listaNumero[n].rjust(6)
teste2 = (listaOperador[o].ljust(2) + listaNumero[m]).rjust(6)
teste3 = '------'
teste4 = str(listaSoma[o]).rjust(6)
elif len(listaNumero[m]) == 3:
if len(listaNumero[n]) == 4:
teste1 = listaNumero[n].rjust(6)
teste2 = (listaOperador[o].ljust(3) + listaNumero[m]).rjust(6)
teste3 = '------'
teste4 = str(listaSoma[o]).rjust(6)
else:
teste1 = listaNumero[n].rjust(5)
teste2 = (listaOperador[o].ljust(2) + listaNumero[m]).rjust(5)
teste3 = '-----'
teste4 = str(listaSoma[o]).rjust(5)
elif len(listaNumero[m]) == 2:
if len(listaNumero[n]) == 4:
teste1 = listaNumero[n].rjust(6)
teste2 = (listaOperador[o].ljust(4) + listaNumero[m]).rjust(6)
teste3 = '------'
teste4 = str(listaSoma[o]).rjust(6)
elif len(listaNumero[n]) == 3:
teste1 = listaNumero[n].rjust(5)
teste2 = (listaOperador[o].ljust(3) + listaNumero[m]).rjust(5)
teste3 = '-----'
teste4 = str(listaSoma[o]).rjust(5)
else:
teste1 = listaNumero[n].rjust(4)
teste2 = (listaOperador[o].ljust(2) + listaNumero[m]).rjust(4)
teste3 = '----'
teste4 = str(listaSoma[o]).rjust(4)
elif len(listaNumero[m]) == 1:
if len(listaNumero[n]) == 4:
teste1 = listaNumero[n].rjust(6)
teste2 = (listaOperador[o].ljust(5) + listaNumero[m]).rjust(6)
teste3 = '------'
teste4 = str(listaSoma[o]).rjust(6)
elif len(listaNumero[n]) == 3:
teste1 = listaNumero[n].rjust(5)
teste2 = (listaOperador[o].ljust(4) + listaNumero[m]).rjust(5)
teste3 = '-----'
teste4 = str(listaSoma[o]).rjust(5)
elif len(listaNumero[n]) == 2:
teste1 = listaNumero[n].rjust(4)
teste2 = (listaOperador[o].ljust(3) + listaNumero[m]).rjust(4)
teste3 = '----'
teste4 = str(listaSoma[o]).rjust(4)
else:
teste1 = listaNumero[n].rjust(3)
teste2 = (listaOperador[o].ljust(2) + listaNumero[m]).rjust(3)
teste3 = '---'
teste4 = str(listaSoma[o]).rjust(3)
listaFormatada.append(teste1)
listaFormatada2.append(teste2)
listaFormatada3.append(teste3)
listaFormatada4.append(teste4)
n = n + 2
m = m + 2
o = o + 1
s = ' '.join(listaFormatada) + '\n' + ' '.join(listaFormatada2) + '\n' + ' '.join(listaFormatada3)
soma = s + '\n' + ' '.join(listaFormatada4)
if resultado == True:
return soma
else:
return s |
#!/usr/bin/python3
# --- 001 > U5W2P1_Task1_w1
def solution(s):
return int(s)
if __name__ == "__main__":
print('----------start------------')
s = "12"
print(solution( s ))
print('------------end------------') | def solution(s):
return int(s)
if __name__ == '__main__':
print('----------start------------')
s = '12'
print(solution(s))
print('------------end------------') |
def sort(num) :
for i in range(len(num) - 1) :
for j in range(i, len(num)) :
if num[i] > num[j] :
temp = num[i]
num[i] = num[j]
num[j] = temp
num = [2, 6, 4, 8, 7]
sort(num)
print(num)
'''
Output :
[2, 4, 6, 7, 8]
''' | def sort(num):
for i in range(len(num) - 1):
for j in range(i, len(num)):
if num[i] > num[j]:
temp = num[i]
num[i] = num[j]
num[j] = temp
num = [2, 6, 4, 8, 7]
sort(num)
print(num)
'\nOutput :\n[2, 4, 6, 7, 8]\n' |
#! /usr/bin/env python3
def f(x):
def g(y):
# NEED THIS
nonlocal x
x = x - y
return x
return g
g0 = f(100)
ans0 = g0(42)
print(ans0)
g1 = f(200)
ans1 = g1(42)
print(ans1)
| def f(x):
def g(y):
nonlocal x
x = x - y
return x
return g
g0 = f(100)
ans0 = g0(42)
print(ans0)
g1 = f(200)
ans1 = g1(42)
print(ans1) |
"""
This file is part of pynadc
https://github.com/rmvanhees/pynadc
GOSAT-2 package
Copyright (c) 2019 SRON - Netherlands Institute for Space Research
All Rights Reserved
License: BSD-3-Clause
"""
__all__ = ['db']
| """
This file is part of pynadc
https://github.com/rmvanhees/pynadc
GOSAT-2 package
Copyright (c) 2019 SRON - Netherlands Institute for Space Research
All Rights Reserved
License: BSD-3-Clause
"""
__all__ = ['db'] |
# input
N = int(input())
S = []
for i in range(N):
S.append(input())
# process & output
length_T = 0
left = 0
right = N-1
while length_T < N:
if S[left] < S[right]:
print(S[left], end='')
left += 1
elif S[left] > S[right]:
print(S[right], end='')
right -= 1
else:
temp_l = left
temp_r = right
while temp_l < temp_r:
printed = False
temp_l += 1
temp_r -= 1
if S[temp_l] < S[temp_r]:
print(S[left], end='')
left += 1
printed = True
break
elif S[temp_l] > S[temp_r]:
print(S[right], end='')
right -= 1
printed = True
break
if (not printed) or left == right:
print(S[left], end='')
left += 1
length_T += 1
if length_T % 80 == 0:
print('\n', end='') | n = int(input())
s = []
for i in range(N):
S.append(input())
length_t = 0
left = 0
right = N - 1
while length_T < N:
if S[left] < S[right]:
print(S[left], end='')
left += 1
elif S[left] > S[right]:
print(S[right], end='')
right -= 1
else:
temp_l = left
temp_r = right
while temp_l < temp_r:
printed = False
temp_l += 1
temp_r -= 1
if S[temp_l] < S[temp_r]:
print(S[left], end='')
left += 1
printed = True
break
elif S[temp_l] > S[temp_r]:
print(S[right], end='')
right -= 1
printed = True
break
if not printed or left == right:
print(S[left], end='')
left += 1
length_t += 1
if length_T % 80 == 0:
print('\n', end='') |
template = """
{
"packagingVersion": "4.0",
"upgradesFrom": ["%%(upgrades-from)s"],
"downgradesTo": ["%%(downgrades-to)s"],
"minDcosReleaseVersion": "1.9",
"name": "%(package-name)s",
"version": "%%(package-version)s",
"maintainer": "%%(maintainer)s",
"description": "%(package-name)s on DC/OS",
"selected": false,
"framework": false,
"tags": ["%(package-name)s"],
"postInstallNotes": "DC/OS %(package-name)s is being installed!\\n\\n\\tDocumentation: %%(documentation-path)s\\n\\tIssues: %%(issues-path)s",
"postUninstallNotes": "DC/OS %(package-name)s is being uninstalled."
}
"""
| template = '\n{\n "packagingVersion": "4.0",\n "upgradesFrom": ["%%(upgrades-from)s"],\n "downgradesTo": ["%%(downgrades-to)s"],\n "minDcosReleaseVersion": "1.9",\n "name": "%(package-name)s",\n "version": "%%(package-version)s",\n "maintainer": "%%(maintainer)s",\n "description": "%(package-name)s on DC/OS",\n "selected": false,\n "framework": false,\n "tags": ["%(package-name)s"],\n "postInstallNotes": "DC/OS %(package-name)s is being installed!\\n\\n\\tDocumentation: %%(documentation-path)s\\n\\tIssues: %%(issues-path)s",\n "postUninstallNotes": "DC/OS %(package-name)s is being uninstalled."\n}\n' |
spin = input()
electric_charge = input()
if spin == '1' and electric_charge == '0':
print('Photon Boson')
else:
if electric_charge == '-1/3':
print('Strange Quark')
elif electric_charge == '2/3':
print('Charm Quark')
elif electric_charge == '-1':
print('Electron Lepton')
else:
print('Muon Lepton')
| spin = input()
electric_charge = input()
if spin == '1' and electric_charge == '0':
print('Photon Boson')
elif electric_charge == '-1/3':
print('Strange Quark')
elif electric_charge == '2/3':
print('Charm Quark')
elif electric_charge == '-1':
print('Electron Lepton')
else:
print('Muon Lepton') |
#! /usr/bin/python
@onRun
def run(args):
print("run")
return {"msg":"fsd"}
@onPause
def pause(args):
print("pause")
@onStart
def start(args):
print("start")
@onFinish
def finish(args):
print("finish") | @onRun
def run(args):
print('run')
return {'msg': 'fsd'}
@onPause
def pause(args):
print('pause')
@onStart
def start(args):
print('start')
@onFinish
def finish(args):
print('finish') |
"""
@file
@brief shortcuts to exams
"""
| """
@file
@brief shortcuts to exams
""" |
#encoding:utf-8
subreddit = 'tf2+tf2memes+tf2shitposterclub'
t_channel = '@r_TF2'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'tf2+tf2memes+tf2shitposterclub'
t_channel = '@r_TF2'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.