content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def getting_input():
"""
Gets input from user and implements it into an 2 dim array
"""
print('Enter a table:')
return [list(map(int, list(input()))) for _ in range(9)]
| def getting_input():
"""
Gets input from user and implements it into an 2 dim array
"""
print('Enter a table:')
return [list(map(int, list(input()))) for _ in range(9)] |
class Type():
NONE = 0x0
NOCOLOR = 0x1
JAIL = 0x2
BHYVE = 0x4
EXIT = 0x8
CONNECTION_CLOSED = 0x10
| class Type:
none = 0
nocolor = 1
jail = 2
bhyve = 4
exit = 8
connection_closed = 16 |
# -*- coding:utf-8 -*-
# !/usr/bin/env python3
"""
"""
class AsyncIteratorWrapper:
def __init__(self, obj):
self._it = iter(obj)
def __aiter__(self):
return self
async def __anext__(self):
try:
value = next(self._it)
except StopIteration:
raise StopAsyncIteration
return value
| """
"""
class Asynciteratorwrapper:
def __init__(self, obj):
self._it = iter(obj)
def __aiter__(self):
return self
async def __anext__(self):
try:
value = next(self._it)
except StopIteration:
raise StopAsyncIteration
return value |
"""
This module implement a filter interface.
"""
class ImagineFilterInterface(object):
"""
Filter interface
"""
def apply(self, resource):
"""
Apply filter to resource
:param resource: Image
:return: Image
"""
raise NotImplementedError()
| """
This module implement a filter interface.
"""
class Imaginefilterinterface(object):
"""
Filter interface
"""
def apply(self, resource):
"""
Apply filter to resource
:param resource: Image
:return: Image
"""
raise not_implemented_error() |
### naive apporach
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zeroNum = 0
i = 0
while nums:
if nums[i] == 0:
nums.pop(i)
zeroNum += 1
i -= 1
i += 1
if i >= len(nums) - 1:
break
for i in range(zeroNum):
nums.append(0)
### smarter approach
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[zero] = nums[zero], nums[i]
zero += 1
### "cheat" approach
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums.sort(key=bool, reverse=True)
| class Solution:
def move_zeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero_num = 0
i = 0
while nums:
if nums[i] == 0:
nums.pop(i)
zero_num += 1
i -= 1
i += 1
if i >= len(nums) - 1:
break
for i in range(zeroNum):
nums.append(0)
class Solution:
def move_zeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero = 0
for i in range(len(nums)):
if nums[i] != 0:
(nums[i], nums[zero]) = (nums[zero], nums[i])
zero += 1
class Solution:
def move_zeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums.sort(key=bool, reverse=True) |
print("==== PROGRAM HITUNG TOTAL HARGA PESANAN ====".center(50))
print("="*38)
print("*Menu*".center(37))
print("="*38)
print("1. Susu".rjust(8), "Rp.7.000".rjust(27))
print("2. Teh".rjust(7), "Rp.5.000".rjust(28))
print("3. Kopi".rjust(8), " Rp.5.000".rjust(27))
print("="*38, "\n")
banyak_jenis = int(input("banyak jenis: "))
kode_potong = []
banyak_potong = []
jenis_potong = []
harga = []
total = []
i = 0
while i < banyak_jenis:
print("jenis ke", i+1)
kode_potong.append(input("kode Pesanan [S/T/K]: "))
banyak_potong.append(int(input("banyak Pesanan: \n")))
if kode_potong[i] == "S" or kode_potong[i] == "s":
jenis_potong.append("Susu")
harga.append("7000")
total.append(banyak_potong[i]*int("7000"))
elif kode_potong[i] == "T" or kode_potong[i] == "t":
jenis_potong.append("Teh")
harga.append("5000")
total.append(banyak_potong[i]*int("5000"))
elif kode_potong[i] == "K" or kode_potong[i] == "k":
jenis_potong.append("Kopi")
harga.append("5000")
total.append(banyak_potong[i] * int("5000"))
else:
jenis_potong.append("Kode salah")
harga.append("0")
total.append(banyak_potong[i]*int("0"))
i = i+1
print("="*61)
print("*CAFE BALE-BALE*".center(61))
print("="*61)
print("No".rjust(4), "Jenis".rjust(10), "Harga".rjust(15), "Banyak".rjust(15), "Jumlah".rjust(10))
print("".rjust(4), "Potong".rjust(11), "satuan".rjust(15), "Beli".rjust(13), "Harga".rjust(11))
print("-"*61)
jumlah_bayar = 0
a = 0
while a < banyak_jenis:
jumlah_bayar = jumlah_bayar + total[0]
print(" %i %s %s %i Rp.%i\n" % (a+1, jenis_potong[a],
harga[a], banyak_potong[a], total[a]))
a = a + 1
print("Total jumlah Rp.".rjust(52), jumlah_bayar)
print("-"*61)
jumlah = jumlah_bayar
if jumlah >= 35000:
diskon = jumlah_bayar / 10
total_bayar = jumlah_bayar - diskon
print("Diskon 10% Rp.".rjust(50), diskon)
print("kamu hanya perlu membayar Rp.".rjust(49), total_bayar)
elif jumlah >= 35000 or jumlah_bayar >= 15000:
diskon = jumlah_bayar / 5
total_bayar = jumlah_bayar - diskon
print("Diskon 5% Rp.".rjust(50), diskon)
print("kamu hanya perlu membayar Rp.".rjust(49), total_bayar)
elif jumlah < 15000:
diskon = 0
total = jumlah_bayar
print("Diskon Rp.0".rjust(47))
print("Total bayar Rp.".rjust(51), total)
print("="*61)
| print('==== PROGRAM HITUNG TOTAL HARGA PESANAN ===='.center(50))
print('=' * 38)
print('*Menu*'.center(37))
print('=' * 38)
print('1. Susu'.rjust(8), 'Rp.7.000'.rjust(27))
print('2. Teh'.rjust(7), 'Rp.5.000'.rjust(28))
print('3. Kopi'.rjust(8), ' Rp.5.000'.rjust(27))
print('=' * 38, '\n')
banyak_jenis = int(input('banyak jenis: '))
kode_potong = []
banyak_potong = []
jenis_potong = []
harga = []
total = []
i = 0
while i < banyak_jenis:
print('jenis ke', i + 1)
kode_potong.append(input('kode Pesanan [S/T/K]: '))
banyak_potong.append(int(input('banyak Pesanan: \n')))
if kode_potong[i] == 'S' or kode_potong[i] == 's':
jenis_potong.append('Susu')
harga.append('7000')
total.append(banyak_potong[i] * int('7000'))
elif kode_potong[i] == 'T' or kode_potong[i] == 't':
jenis_potong.append('Teh')
harga.append('5000')
total.append(banyak_potong[i] * int('5000'))
elif kode_potong[i] == 'K' or kode_potong[i] == 'k':
jenis_potong.append('Kopi')
harga.append('5000')
total.append(banyak_potong[i] * int('5000'))
else:
jenis_potong.append('Kode salah')
harga.append('0')
total.append(banyak_potong[i] * int('0'))
i = i + 1
print('=' * 61)
print('*CAFE BALE-BALE*'.center(61))
print('=' * 61)
print('No'.rjust(4), 'Jenis'.rjust(10), 'Harga'.rjust(15), 'Banyak'.rjust(15), 'Jumlah'.rjust(10))
print(''.rjust(4), 'Potong'.rjust(11), 'satuan'.rjust(15), 'Beli'.rjust(13), 'Harga'.rjust(11))
print('-' * 61)
jumlah_bayar = 0
a = 0
while a < banyak_jenis:
jumlah_bayar = jumlah_bayar + total[0]
print(' %i %s %s %i Rp.%i\n' % (a + 1, jenis_potong[a], harga[a], banyak_potong[a], total[a]))
a = a + 1
print('Total jumlah Rp.'.rjust(52), jumlah_bayar)
print('-' * 61)
jumlah = jumlah_bayar
if jumlah >= 35000:
diskon = jumlah_bayar / 10
total_bayar = jumlah_bayar - diskon
print('Diskon 10% Rp.'.rjust(50), diskon)
print('kamu hanya perlu membayar Rp.'.rjust(49), total_bayar)
elif jumlah >= 35000 or jumlah_bayar >= 15000:
diskon = jumlah_bayar / 5
total_bayar = jumlah_bayar - diskon
print('Diskon 5% Rp.'.rjust(50), diskon)
print('kamu hanya perlu membayar Rp.'.rjust(49), total_bayar)
elif jumlah < 15000:
diskon = 0
total = jumlah_bayar
print('Diskon Rp.0'.rjust(47))
print('Total bayar Rp.'.rjust(51), total)
print('=' * 61) |
first_num = int(input())
second_num = int(input())
third_num = int(input())
for i in range (1, first_num + 1):
for j in range (1, second_num + 1):
for k in range (1, third_num + 1):
if i % 2 == 0 and j > 1 and k % 2 == 0:
for prime in range(2, j):
if (j % prime) == 0:
break
else:
print(f'{i} {j} {k}')
| first_num = int(input())
second_num = int(input())
third_num = int(input())
for i in range(1, first_num + 1):
for j in range(1, second_num + 1):
for k in range(1, third_num + 1):
if i % 2 == 0 and j > 1 and (k % 2 == 0):
for prime in range(2, j):
if j % prime == 0:
break
else:
print(f'{i} {j} {k}') |
a = int(input("Enter number a: "))
b = int(input("Enter number b: "))
i = a % b
j = b % a
print(i * j + 1)
| a = int(input('Enter number a: '))
b = int(input('Enter number b: '))
i = a % b
j = b % a
print(i * j + 1) |
class UserMessageError(Exception):
def __init__(self, response_code, user_msg=None, server_msg=None):
self.user_msg = user_msg or ""
self.server_msg = server_msg or self.user_msg
self.response_code = response_code
super().__init__()
class ClientError(UserMessageError):
def __init__(self, response_code=400, user_msg=None, **kwargs):
if not user_msg:
user_msg = "Invalid request"
super().__init__(response_code, user_msg=user_msg, **kwargs)
class ServerError(UserMessageError):
def __init__(self, response_code=500, user_msg=None, server_msg=None):
user_msg = f"An error occurred while processing the request{f': {user_msg}' if user_msg else ''}"
server_msg = f"Server-side error while processing request: {server_msg or user_msg}"
super().__init__(response_code, user_msg=user_msg, server_msg=server_msg)
class NotFoundError(UserMessageError):
def __init__(self, user_msg=None, **kwargs):
if not user_msg:
user_msg = "Requested resource not found"
super().__init__(404, user_msg=user_msg, **kwargs)
class NotAuthorized(ClientError):
def __init__(self, user_msg=None, **kwargs):
if not user_msg:
user_msg = "You are not authorized to access the requested resource."
super().__init__(response_code=401, user_msg=user_msg, **kwargs)
class InvalidEnum(ValueError):
pass
| class Usermessageerror(Exception):
def __init__(self, response_code, user_msg=None, server_msg=None):
self.user_msg = user_msg or ''
self.server_msg = server_msg or self.user_msg
self.response_code = response_code
super().__init__()
class Clienterror(UserMessageError):
def __init__(self, response_code=400, user_msg=None, **kwargs):
if not user_msg:
user_msg = 'Invalid request'
super().__init__(response_code, user_msg=user_msg, **kwargs)
class Servererror(UserMessageError):
def __init__(self, response_code=500, user_msg=None, server_msg=None):
user_msg = f"An error occurred while processing the request{(f': {user_msg}' if user_msg else '')}"
server_msg = f'Server-side error while processing request: {server_msg or user_msg}'
super().__init__(response_code, user_msg=user_msg, server_msg=server_msg)
class Notfounderror(UserMessageError):
def __init__(self, user_msg=None, **kwargs):
if not user_msg:
user_msg = 'Requested resource not found'
super().__init__(404, user_msg=user_msg, **kwargs)
class Notauthorized(ClientError):
def __init__(self, user_msg=None, **kwargs):
if not user_msg:
user_msg = 'You are not authorized to access the requested resource.'
super().__init__(response_code=401, user_msg=user_msg, **kwargs)
class Invalidenum(ValueError):
pass |
# https://projecteuler.net/problem=5
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
print(gcd(1,6))
result = 1
for i in range(2, 21):
g = gcd(result, i)
result = result * (i/g)
print(i, g, result)
print(result)
| def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(1, 6))
result = 1
for i in range(2, 21):
g = gcd(result, i)
result = result * (i / g)
print(i, g, result)
print(result) |
#Calculadora basica que haga suma,resta,multiplicacion y division
def main() :
n = input('Ingresa los numeroes entre espacios: \n')
print("\t")
print("Estos son los numeros ingresados: ")
respuesta = input("\n Desea continuar? Y/N: ")
if respuesta == "Y":
print("Funciono")
print(n)
| def main():
n = input('Ingresa los numeroes entre espacios: \n')
print('\t')
print('Estos son los numeros ingresados: ')
respuesta = input('\n Desea continuar? Y/N: ')
if respuesta == 'Y':
print('Funciono')
print(n) |
class TimeoutException(Exception):
"""Class to add a timeout attribute to an exception. If an exception is
raised specifically due to a rate-limits being exceeded, this class can
be used to add a timeout, indicated how long a task or application should
wait until retrying.
Attributes:
exception (Exception): Base exception raised by any class.
timeout (int): Number of seconds the task should wait until retrying.
"""
def __init__(self, exception, timeout):
self.exception = exception
self.timeout = timeout
def __str__(self):
return str(self.exception)
| class Timeoutexception(Exception):
"""Class to add a timeout attribute to an exception. If an exception is
raised specifically due to a rate-limits being exceeded, this class can
be used to add a timeout, indicated how long a task or application should
wait until retrying.
Attributes:
exception (Exception): Base exception raised by any class.
timeout (int): Number of seconds the task should wait until retrying.
"""
def __init__(self, exception, timeout):
self.exception = exception
self.timeout = timeout
def __str__(self):
return str(self.exception) |
def insertion_sort(lst):
for passes in range(1, len(lst)): # n-1 passes
current_val = lst[passes]
pos = passes
while pos > 0 and lst[pos-1] > current_val:
lst[pos] = lst[pos-1]
pos = pos-1
lst[pos] = current_val
return lst
arr = [2, 4, 42, 6, 22, 7]
print(insertion_sort(arr))
| def insertion_sort(lst):
for passes in range(1, len(lst)):
current_val = lst[passes]
pos = passes
while pos > 0 and lst[pos - 1] > current_val:
lst[pos] = lst[pos - 1]
pos = pos - 1
lst[pos] = current_val
return lst
arr = [2, 4, 42, 6, 22, 7]
print(insertion_sort(arr)) |
class Util:
def __init__(self, node):
self._node = node
def createmultisig(self, nrequired, keys, address_type="legacy"): # 01
return self._node._rpc.call("createmultisig", nrequired, keys, address_type)
def deriveaddresses(self, descriptor, range=None): # 02
return self._node._rpc.call("deriveaddresses", descriptor, range)
def estimatesmartfee(self, conf_target, estimate_mode="CONSERVATIVE"): # 03
return self._node._rpc.call("estimatesmartfee", conf_target, estimate_mode)
def getdescriptorinfo(self, descriptor): # 04
return self._node._rpc.call("getdescriptorinfo", descriptor)
def signmessagewithprivkey(self, privkey, message): # 05
return self._node._rpc.call("signmessagewithprivkey", privkey, message)
def validateaddress(self, address): # 06
return self._node._rpc.call("validateaddress", address)
def verifymessage(self, address, signature, message): # 07
return self._node._rpc.call("verifymessage", address, signature, message)
| class Util:
def __init__(self, node):
self._node = node
def createmultisig(self, nrequired, keys, address_type='legacy'):
return self._node._rpc.call('createmultisig', nrequired, keys, address_type)
def deriveaddresses(self, descriptor, range=None):
return self._node._rpc.call('deriveaddresses', descriptor, range)
def estimatesmartfee(self, conf_target, estimate_mode='CONSERVATIVE'):
return self._node._rpc.call('estimatesmartfee', conf_target, estimate_mode)
def getdescriptorinfo(self, descriptor):
return self._node._rpc.call('getdescriptorinfo', descriptor)
def signmessagewithprivkey(self, privkey, message):
return self._node._rpc.call('signmessagewithprivkey', privkey, message)
def validateaddress(self, address):
return self._node._rpc.call('validateaddress', address)
def verifymessage(self, address, signature, message):
return self._node._rpc.call('verifymessage', address, signature, message) |
# For singly Linked List
# class MySinglyLinkedList:
# def __init__(self):
# self.head = None
# self.size = 0
# # If the index is invalid, return -1
# def get(self, index: int) -> int:
# if index >= self.size or index < 0:
# return -1
# if self.head is None:
# return -1
# curr = self.head
# for i in range(index):
# curr = curr.next
# return curr.val
# def addAtHead(self, val: int) -> None:
# node = Node(val, self.head)
# self.head = node
# self.size += 1
# def addAtTail(self, val: int) -> None:
# curr = self.head
# if curr is None:
# self.addAtHead(val)
# else:
# while curr.next is not None:
# curr = curr.next
# curr.next = Node(val)
# self.size += 1
# def addAtIndex(self, index: int, val: int) -> None:
# if index > self.size:
# return -1
# if index == 0:
# self.addAtHead(val)
# else:
# curr = self.head
# prev = curr
# for i in range(index):
# prev = curr
# curr = curr.next
# prev.next = Node(val, curr)
# self.size += 1
# # Delete the indexth node in the linked list, if the index is valid.
# def deleteAtIndex(self, index: int) -> None:
# if index >= self.size:
# return -1
# curr = self.head
# if index == 0:
# self.head = self.head.next
# else:
# prev = curr
# for i in range(index):
# prev = curr
# curr = curr.next
# if curr.next is None:
# prev.next = None
# else:
# prev.next = curr.next
# self.size -= 1
'''
["MyLinkedList","addAtIndex","addAtIndex","addAtIndex","get"]
[[],[0,10],[0,20],[1,30],[0]]
["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","deleteAtIndex","deleteAtIndex","get"]
[[],[1],[3],[1,2],[1],[1],[0],[0],[1]]
["MyLinkedList","addAtHead","get","addAtTail","get","addAtIndex","addAtIndex","get","deleteAtIndex","get"]
[[],[1],[0],[3],[1],[1,2],[4,4],[1],[1],[1]]
["MyLinkedList","addAtHead","deleteAtIndex"]
[[],[1],[0]]
["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"]
[[],[1],[3],[1,2],[1],[0],[0]]
'''
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
class Node:
def __init__(self, val = 0, anext = None, prev = None):
self.val = val
self.next = anext
self.prev = prev
class MyLinkedList:
def __init__(self):
self.head = None
self.size = 0
def get(self, index):
if self.size and 0 <= index < self.size:
curr = self.head
while index > 0:
curr = curr.next
index -= 1
return curr.val
else:
return -1
def addAtHead(self, val):
node = Node(val, self.head, None)
self.head = node
self.size += 1
def addAtTail(self, val):
if not self.size:
self.addAtHead(val)
return
curr = self.head
while curr.next:
curr = curr.next
node = Node(val, None, curr)
curr.next = node
self.size += 1
def deleteAtIndex(self, index):
if index == 0:
self.head = self.head.next
self.size -= 1
return
if index < self.size and index > 0:
curr = self.head
while index > 0:
prev = curr
curr = curr.next
index -= 1
anext = None
if curr is not None:
anext = curr.next
prev.next = anext
self.size -= 1
def addAtIndex(self, index, val):
if index > self.size or index < 0:
return self.head
if not self.size or index == 0:
self.addAtHead(val)
return
if index == self.size:
self.addAtTail(val)
return
curr = self.head
while index > 0:
prev = curr
curr = curr.next
index -= 1
anext = curr
node = Node(val, anext, prev)
anext.prev = node
if prev:
prev.next = node
self.size += 1 | """
["MyLinkedList","addAtIndex","addAtIndex","addAtIndex","get"]
[[],[0,10],[0,20],[1,30],[0]]
["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","deleteAtIndex","deleteAtIndex","get"]
[[],[1],[3],[1,2],[1],[1],[0],[0],[1]]
["MyLinkedList","addAtHead","get","addAtTail","get","addAtIndex","addAtIndex","get","deleteAtIndex","get"]
[[],[1],[0],[3],[1],[1,2],[4,4],[1],[1],[1]]
["MyLinkedList","addAtHead","deleteAtIndex"]
[[],[1],[0]]
["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"]
[[],[1],[3],[1,2],[1],[0],[0]]
"""
class Node:
def __init__(self, val=0, anext=None, prev=None):
self.val = val
self.next = anext
self.prev = prev
class Mylinkedlist:
def __init__(self):
self.head = None
self.size = 0
def get(self, index):
if self.size and 0 <= index < self.size:
curr = self.head
while index > 0:
curr = curr.next
index -= 1
return curr.val
else:
return -1
def add_at_head(self, val):
node = node(val, self.head, None)
self.head = node
self.size += 1
def add_at_tail(self, val):
if not self.size:
self.addAtHead(val)
return
curr = self.head
while curr.next:
curr = curr.next
node = node(val, None, curr)
curr.next = node
self.size += 1
def delete_at_index(self, index):
if index == 0:
self.head = self.head.next
self.size -= 1
return
if index < self.size and index > 0:
curr = self.head
while index > 0:
prev = curr
curr = curr.next
index -= 1
anext = None
if curr is not None:
anext = curr.next
prev.next = anext
self.size -= 1
def add_at_index(self, index, val):
if index > self.size or index < 0:
return self.head
if not self.size or index == 0:
self.addAtHead(val)
return
if index == self.size:
self.addAtTail(val)
return
curr = self.head
while index > 0:
prev = curr
curr = curr.next
index -= 1
anext = curr
node = node(val, anext, prev)
anext.prev = node
if prev:
prev.next = node
self.size += 1 |
widget = WidgetDefault()
widget.width = 101
widget.height = 101
widget.border = "None"
widget.background = "None"
commonDefaults["BarGraphWidget"] = widget
def generateBarGraphWidget(file, screen, bar, parentName):
name = bar.getName()
file.write(" %s = leBarGraphWidget_New();" % (name))
generateBaseWidget(file, screen, bar)
writeSetBoolean(file, name, "Stacked", bar.getStacked(), False)
writeSetBoolean(file, name, "FillGraphArea", bar.getFillGraphArea(), True)
writeSetInt(file, name, "TickLength", bar.getTickLength(), 5)
if bar.getMinValue() != 0:
file.write(" %s->fn->setMinValue(%s, BAR_GRAPH_AXIS_0, %d);" % (name, name, bar.getMinValue()))
if bar.getMaxValue() != 100:
file.write(" %s->fn->setMaxValue(%s, BAR_GRAPH_AXIS_0, %d);" % (name, name, bar.getMaxValue()))
if bar.getTickInterval() != 10:
file.write(" %s->fn->setValueAxisTicksInterval(%s, BAR_GRAPH_AXIS_0, %d);" % (name, name, bar.getTickInterval()))
if bar.getSubtickInterval() != 5:
file.write(" %s->fn->setValueAxisSubticksInterval(%s, BAR_GRAPH_AXIS_0, %d);" % (name, name, bar.getSubtickInterval()))
if bar.getValueAxisTicksVisible() == False:
file.write(" %s->fn->setValueAxisTicksVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);" % (name, name))
if bar.getValueGridlinesVisible() == False:
file.write(" %s->fn->setGridLinesVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);" % (name, name))
position = bar.getValueAxisTicksPosition().toString()
if position != "Center":
if position == "Inside":
position = "BAR_GRAPH_TICK_IN"
elif position == "Outside":
position = "BAR_GRAPH_TICK_OUT"
else:
position = "BAR_GRAPH_TICK_CENTER"
file.write(" %s->fn->setValueAxisTicksPosition(%s, BAR_GRAPH_AXIS_0, %s);" % (name, name, position))
if bar.getValueAxisLabelsVisible() == False:
file.write(" %s->fn->setValueAxisLabelsVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);" % (name, name))
if bar.getValueAxisSubticksVisible() == False:
file.write(" %s->fn->setValueAxisSubticksVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);" % (name, name))
position = bar.getValueAxisSubticksPosition().toString()
if position != "Center":
if position == "Inside":
position = "BAR_GRAPH_TICK_IN"
elif position == "Outside":
position = "BAR_GRAPH_TICK_OUT"
else:
position = "BAR_GRAPH_TICK_CENTER"
file.write(" %s->fn->setValueAxisSubticksPosition(%s, BAR_GRAPH_AXIS_0, %s);" % (name, name, position))
writeSetFontAssetName(file, name, "TicksLabelFont", bar.getLabelFontName())
writeSetBoolean(file, name, "CategoryAxisTicksVisible", bar.getCategoryAxisTicksVisible(), True)
writeSetBoolean(file, name, "CategoryAxisLabelsVisible", bar.getCategoryAxisLabelsVisible(), True)
position = bar.getCategoryAxisTicksPosition().toString()
if position != "Center":
if position == "Inside":
position = "BAR_GRAPH_TICK_IN"
elif position == "Outside":
position = "BAR_GRAPH_TICK_OUT"
else:
position = "BAR_GRAPH_TICK_CENTER"
file.write(" %s->fn->setCategoryAxisTicksPosition(%s, %s);" % (name, name, position))
categoryList = bar.getCategories()
for i in range(0, len(categoryList)):
file.write(" %s->fn->addCategory(%s, NULL);" % (name, name))
stringName = craftStringAssetName(categoryList[i].string)
if stringName != "NULL":
file.write(" %s->fn->setCategoryString(%s, %d, (leString*)%s);" % (name, name, i, stringName))
seriesList = bar.getDataSeries()
if len(seriesList) > 0:
for idx, series in enumerate(seriesList):
file.write(" %s->fn->addSeries(%s, NULL);" % (name, name))
if testStringValidity(series.scheme):
file.write(" %s->fn->setSeriesScheme(%s, %d, &%s);" % (name, name, idx, series.scheme))
for dataVal in series.data:
file.write(" %s->fn->addDataToSeries(%s, %d, %d, NULL);" % (name, name, idx, dataVal))
file.write(" %s->fn->addChild(%s, (leWidget*)%s);" % (parentName, parentName, name))
file.writeNewLine()
def generateBarGraphAction(text, variables, owner, event, action):
name = action.targetName
#print(action.argumentData)
if action.actionID == "SetTickLength":
val = getActionArgumentValue(action, "Length")
writeActionFunc(text, action, "setTickLength", [val])
elif action.actionID == "SetFillGraphArea":
val = getActionArgumentValue(action, "Fill")
writeActionFunc(text, action, "setFillGraphArea", [val])
elif action.actionID == "SetStacked":
val = getActionArgumentValue(action, "Stacked")
writeActionFunc(text, action, "setStacked", [val])
elif action.actionID == "SetMax":
val = getActionArgumentValue(action, "Value")
writeActionFunc(text, action, "setMaxValue", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "SetMin":
val = getActionArgumentValue(action, "Value")
writeActionFunc(text, action, "setMinValue", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "SetTickInterval":
val = getActionArgumentValue(action, "Interval")
writeActionFunc(text, action, "setValueAxisTicksInterval", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "SetSubtickInterval":
val = getActionArgumentValue(action, "Interval")
writeActionFunc(text, action, "setValueAxisSubticksInterval", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "ShowValueAxisLabels":
val = getActionArgumentValue(action, "Show")
writeActionFunc(text, action, "setValueAxisLabelsVisible", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "ShowValueAxisTicks":
val = getActionArgumentValue(action, "Show")
writeActionFunc(text, action, "setValueAxisTicksVisible", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "ShowValueAxisSubticks":
val = getActionArgumentValue(action, "Show")
writeActionFunc(text, action, "setValueAxisSubticksVisible", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "ShowValueAxisGrid":
val = getActionArgumentValue(action, "Show")
writeActionFunc(text, action, "setGridLinesVisible", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "SetValueAxisTickPosition":
val = getActionArgumentValue(action, "Position")
if val == "Center":
val = "BAR_GRAPH_TICK_CENTER"
elif val == "Inside":
val = "BAR_GRAPH_TICK_IN"
elif val == "Outside":
val = "BAR_GRAPH_TICK_OUT"
writeActionFunc(text, action, "setValueAxisTicksPosition", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "SetValueAxisSubtickPosition":
val = getActionArgumentValue(action, "Position")
if val == "Center":
val = "BAR_GRAPH_TICK_CENTER"
elif val == "Inside":
val = "BAR_GRAPH_TICK_IN"
elif val == "Outside":
val = "BAR_GRAPH_TICK_OUT"
writeActionFunc(text, action, "setValueAxisSubticksPosition", ["BAR_GRAPH_AXIS_0", val])
elif action.actionID == "ShowCategoryAxisLabels":
val = getActionArgumentValue(action, "Show")
writeActionFunc(text, action, "setCategoryAxisLabelsVisible", [val])
elif action.actionID == "ShowCategoryAxisTicks":
val = getActionArgumentValue(action, "Show")
writeActionFunc(text, action, "setCategoryAxisTicksVisible", [val])
elif action.actionID == "SetCategoryAxisTickPosition":
val = getActionArgumentValue(action, "Position")
if val == "Center":
val = "BAR_GRAPH_TICK_CENTER"
elif val == "Inside":
val = "BAR_GRAPH_TICK_IN"
elif val == "Outside":
val = "BAR_GRAPH_TICK_OUT"
writeActionFunc(text, action, "setCategoryAxisTicksPosition", [val])
elif action.actionID == "SetLabelFont":
val = getActionArgumentValue(action, "FontAsset")
writeActionFunc(text, action, "setTicksLabelFont", [val])
elif action.actionID == "AddCategory":
val = getActionArgumentValue(action, "StringAsset")
variables["categoryIdx"] = "uint32_t"
writeActionFunc(text, action, "addCategory", ["&categoryIdx"])
writeActionFunc(text, action, "setCategoryString", ["categoryIdx", val])
elif action.actionID == "AddSeries":
val = getActionArgumentValue(action, "Scheme")
variables["seriesIdx"] = "uint32_t"
writeActionFunc(text, action, "addSeries", ["&seriesIdx"])
writeActionFunc(text, action, "setSeriesScheme", ["seriesIdx", val])
elif action.actionID == "AddData":
seriesIdx = getActionArgumentValue(action, "SeriesIndex")
val = getActionArgumentValue(action, "Value")
writeActionFunc(text, action, "addDataToSeries", [seriesIdx, val, "NULL"])
elif action.actionID == "SetData":
catIdx = getActionArgumentValue(action, "CategoryIndex")
seriesIdx = getActionArgumentValue(action, "SeriesIndex")
val = getActionArgumentValue(action, "Value")
variables["categoryIdx"] = "uint32_t"
variables["seriesIdx"] = "uint32_t"
writeActionFunc(text, action, "setDataInSeries", [seriesIdx, catIdx, val])
elif action.actionID == "DeleteData":
writeActionFunc(text, action, "clearData", [])
else:
generateWidgetAction(text, variables, owner, event, action) | widget = widget_default()
widget.width = 101
widget.height = 101
widget.border = 'None'
widget.background = 'None'
commonDefaults['BarGraphWidget'] = widget
def generate_bar_graph_widget(file, screen, bar, parentName):
name = bar.getName()
file.write(' %s = leBarGraphWidget_New();' % name)
generate_base_widget(file, screen, bar)
write_set_boolean(file, name, 'Stacked', bar.getStacked(), False)
write_set_boolean(file, name, 'FillGraphArea', bar.getFillGraphArea(), True)
write_set_int(file, name, 'TickLength', bar.getTickLength(), 5)
if bar.getMinValue() != 0:
file.write(' %s->fn->setMinValue(%s, BAR_GRAPH_AXIS_0, %d);' % (name, name, bar.getMinValue()))
if bar.getMaxValue() != 100:
file.write(' %s->fn->setMaxValue(%s, BAR_GRAPH_AXIS_0, %d);' % (name, name, bar.getMaxValue()))
if bar.getTickInterval() != 10:
file.write(' %s->fn->setValueAxisTicksInterval(%s, BAR_GRAPH_AXIS_0, %d);' % (name, name, bar.getTickInterval()))
if bar.getSubtickInterval() != 5:
file.write(' %s->fn->setValueAxisSubticksInterval(%s, BAR_GRAPH_AXIS_0, %d);' % (name, name, bar.getSubtickInterval()))
if bar.getValueAxisTicksVisible() == False:
file.write(' %s->fn->setValueAxisTicksVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);' % (name, name))
if bar.getValueGridlinesVisible() == False:
file.write(' %s->fn->setGridLinesVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);' % (name, name))
position = bar.getValueAxisTicksPosition().toString()
if position != 'Center':
if position == 'Inside':
position = 'BAR_GRAPH_TICK_IN'
elif position == 'Outside':
position = 'BAR_GRAPH_TICK_OUT'
else:
position = 'BAR_GRAPH_TICK_CENTER'
file.write(' %s->fn->setValueAxisTicksPosition(%s, BAR_GRAPH_AXIS_0, %s);' % (name, name, position))
if bar.getValueAxisLabelsVisible() == False:
file.write(' %s->fn->setValueAxisLabelsVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);' % (name, name))
if bar.getValueAxisSubticksVisible() == False:
file.write(' %s->fn->setValueAxisSubticksVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);' % (name, name))
position = bar.getValueAxisSubticksPosition().toString()
if position != 'Center':
if position == 'Inside':
position = 'BAR_GRAPH_TICK_IN'
elif position == 'Outside':
position = 'BAR_GRAPH_TICK_OUT'
else:
position = 'BAR_GRAPH_TICK_CENTER'
file.write(' %s->fn->setValueAxisSubticksPosition(%s, BAR_GRAPH_AXIS_0, %s);' % (name, name, position))
write_set_font_asset_name(file, name, 'TicksLabelFont', bar.getLabelFontName())
write_set_boolean(file, name, 'CategoryAxisTicksVisible', bar.getCategoryAxisTicksVisible(), True)
write_set_boolean(file, name, 'CategoryAxisLabelsVisible', bar.getCategoryAxisLabelsVisible(), True)
position = bar.getCategoryAxisTicksPosition().toString()
if position != 'Center':
if position == 'Inside':
position = 'BAR_GRAPH_TICK_IN'
elif position == 'Outside':
position = 'BAR_GRAPH_TICK_OUT'
else:
position = 'BAR_GRAPH_TICK_CENTER'
file.write(' %s->fn->setCategoryAxisTicksPosition(%s, %s);' % (name, name, position))
category_list = bar.getCategories()
for i in range(0, len(categoryList)):
file.write(' %s->fn->addCategory(%s, NULL);' % (name, name))
string_name = craft_string_asset_name(categoryList[i].string)
if stringName != 'NULL':
file.write(' %s->fn->setCategoryString(%s, %d, (leString*)%s);' % (name, name, i, stringName))
series_list = bar.getDataSeries()
if len(seriesList) > 0:
for (idx, series) in enumerate(seriesList):
file.write(' %s->fn->addSeries(%s, NULL);' % (name, name))
if test_string_validity(series.scheme):
file.write(' %s->fn->setSeriesScheme(%s, %d, &%s);' % (name, name, idx, series.scheme))
for data_val in series.data:
file.write(' %s->fn->addDataToSeries(%s, %d, %d, NULL);' % (name, name, idx, dataVal))
file.write(' %s->fn->addChild(%s, (leWidget*)%s);' % (parentName, parentName, name))
file.writeNewLine()
def generate_bar_graph_action(text, variables, owner, event, action):
name = action.targetName
if action.actionID == 'SetTickLength':
val = get_action_argument_value(action, 'Length')
write_action_func(text, action, 'setTickLength', [val])
elif action.actionID == 'SetFillGraphArea':
val = get_action_argument_value(action, 'Fill')
write_action_func(text, action, 'setFillGraphArea', [val])
elif action.actionID == 'SetStacked':
val = get_action_argument_value(action, 'Stacked')
write_action_func(text, action, 'setStacked', [val])
elif action.actionID == 'SetMax':
val = get_action_argument_value(action, 'Value')
write_action_func(text, action, 'setMaxValue', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'SetMin':
val = get_action_argument_value(action, 'Value')
write_action_func(text, action, 'setMinValue', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'SetTickInterval':
val = get_action_argument_value(action, 'Interval')
write_action_func(text, action, 'setValueAxisTicksInterval', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'SetSubtickInterval':
val = get_action_argument_value(action, 'Interval')
write_action_func(text, action, 'setValueAxisSubticksInterval', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'ShowValueAxisLabels':
val = get_action_argument_value(action, 'Show')
write_action_func(text, action, 'setValueAxisLabelsVisible', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'ShowValueAxisTicks':
val = get_action_argument_value(action, 'Show')
write_action_func(text, action, 'setValueAxisTicksVisible', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'ShowValueAxisSubticks':
val = get_action_argument_value(action, 'Show')
write_action_func(text, action, 'setValueAxisSubticksVisible', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'ShowValueAxisGrid':
val = get_action_argument_value(action, 'Show')
write_action_func(text, action, 'setGridLinesVisible', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'SetValueAxisTickPosition':
val = get_action_argument_value(action, 'Position')
if val == 'Center':
val = 'BAR_GRAPH_TICK_CENTER'
elif val == 'Inside':
val = 'BAR_GRAPH_TICK_IN'
elif val == 'Outside':
val = 'BAR_GRAPH_TICK_OUT'
write_action_func(text, action, 'setValueAxisTicksPosition', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'SetValueAxisSubtickPosition':
val = get_action_argument_value(action, 'Position')
if val == 'Center':
val = 'BAR_GRAPH_TICK_CENTER'
elif val == 'Inside':
val = 'BAR_GRAPH_TICK_IN'
elif val == 'Outside':
val = 'BAR_GRAPH_TICK_OUT'
write_action_func(text, action, 'setValueAxisSubticksPosition', ['BAR_GRAPH_AXIS_0', val])
elif action.actionID == 'ShowCategoryAxisLabels':
val = get_action_argument_value(action, 'Show')
write_action_func(text, action, 'setCategoryAxisLabelsVisible', [val])
elif action.actionID == 'ShowCategoryAxisTicks':
val = get_action_argument_value(action, 'Show')
write_action_func(text, action, 'setCategoryAxisTicksVisible', [val])
elif action.actionID == 'SetCategoryAxisTickPosition':
val = get_action_argument_value(action, 'Position')
if val == 'Center':
val = 'BAR_GRAPH_TICK_CENTER'
elif val == 'Inside':
val = 'BAR_GRAPH_TICK_IN'
elif val == 'Outside':
val = 'BAR_GRAPH_TICK_OUT'
write_action_func(text, action, 'setCategoryAxisTicksPosition', [val])
elif action.actionID == 'SetLabelFont':
val = get_action_argument_value(action, 'FontAsset')
write_action_func(text, action, 'setTicksLabelFont', [val])
elif action.actionID == 'AddCategory':
val = get_action_argument_value(action, 'StringAsset')
variables['categoryIdx'] = 'uint32_t'
write_action_func(text, action, 'addCategory', ['&categoryIdx'])
write_action_func(text, action, 'setCategoryString', ['categoryIdx', val])
elif action.actionID == 'AddSeries':
val = get_action_argument_value(action, 'Scheme')
variables['seriesIdx'] = 'uint32_t'
write_action_func(text, action, 'addSeries', ['&seriesIdx'])
write_action_func(text, action, 'setSeriesScheme', ['seriesIdx', val])
elif action.actionID == 'AddData':
series_idx = get_action_argument_value(action, 'SeriesIndex')
val = get_action_argument_value(action, 'Value')
write_action_func(text, action, 'addDataToSeries', [seriesIdx, val, 'NULL'])
elif action.actionID == 'SetData':
cat_idx = get_action_argument_value(action, 'CategoryIndex')
series_idx = get_action_argument_value(action, 'SeriesIndex')
val = get_action_argument_value(action, 'Value')
variables['categoryIdx'] = 'uint32_t'
variables['seriesIdx'] = 'uint32_t'
write_action_func(text, action, 'setDataInSeries', [seriesIdx, catIdx, val])
elif action.actionID == 'DeleteData':
write_action_func(text, action, 'clearData', [])
else:
generate_widget_action(text, variables, owner, event, action) |
# -*- coding: utf-8 -*-
"""
bandwidth
This file was automatically generated by APIMATIC v3.0 (
https://www.apimatic.io ).
"""
class PriorityEnum(object):
"""Implementation of the 'Priority' enum.
The message's priority, currently for toll-free or short code SMS only.
Messages with a priority value of `"high"` are given preference over your
other traffic.
Attributes:
DEFAULT: TODO: type description here.
HIGH: TODO: type description here.
"""
DEFAULT = 'default'
HIGH = 'high'
| """
bandwidth
This file was automatically generated by APIMATIC v3.0 (
https://www.apimatic.io ).
"""
class Priorityenum(object):
"""Implementation of the 'Priority' enum.
The message's priority, currently for toll-free or short code SMS only.
Messages with a priority value of `"high"` are given preference over your
other traffic.
Attributes:
DEFAULT: TODO: type description here.
HIGH: TODO: type description here.
"""
default = 'default'
high = 'high' |
#!/usr/bin/python35
fp = open('hello.txt')
print(fp.__next__())
print(next(fp))
fp.close()
| fp = open('hello.txt')
print(fp.__next__())
print(next(fp))
fp.close() |
GLOBAL_TRANSITIONS = "global_transitions"
TRANSITIONS = "transitions"
RESPONSE = "response"
PROCESSING = "processing"
GRAPH = "graph"
MISC = "misc"
| global_transitions = 'global_transitions'
transitions = 'transitions'
response = 'response'
processing = 'processing'
graph = 'graph'
misc = 'misc' |
#################################################################################
# #
# Copyright 2018/08/16 Zachary Priddy (me@zpriddy.com) https://zpriddy.com #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
#################################################################################
class WTFRequest(object):
def __init__(self, request_name, pid=None, **kwargs):
self._request_name = request_name
self._pid = pid
self._kwargs = kwargs
self.set_kwargs()
def set_kwargs(self):
for name, value in self._kwargs.iteritems():
setattr(self, name, value)
@property
def request_name(self):
return self._request_name
@property
def pid(self):
return self._pid
@property
def kwargs(self):
return self._kwargs
class WTFAction(WTFRequest):
def __init__(self, action_name, pid=None, **kwargs):
super(WTFAction, self).__init__(action_name, pid, **kwargs)
| class Wtfrequest(object):
def __init__(self, request_name, pid=None, **kwargs):
self._request_name = request_name
self._pid = pid
self._kwargs = kwargs
self.set_kwargs()
def set_kwargs(self):
for (name, value) in self._kwargs.iteritems():
setattr(self, name, value)
@property
def request_name(self):
return self._request_name
@property
def pid(self):
return self._pid
@property
def kwargs(self):
return self._kwargs
class Wtfaction(WTFRequest):
def __init__(self, action_name, pid=None, **kwargs):
super(WTFAction, self).__init__(action_name, pid, **kwargs) |
def merge_the_tools(string, k):
lens = len(string)
for i in range(0, lens, k):
lists = [j for j in string[i:i+k]]
print(''.join(sorted(set(lists), key=lists.index)))
s = input()
n = int(input())
merge_the_tools(s, n) | def merge_the_tools(string, k):
lens = len(string)
for i in range(0, lens, k):
lists = [j for j in string[i:i + k]]
print(''.join(sorted(set(lists), key=lists.index)))
s = input()
n = int(input())
merge_the_tools(s, n) |
def f(x, y):
"""
Args:
x (int): foo
Args:
y (int): bar
Examples:
first line
second line
third line
""" | def f(x, y):
"""
Args:
x (int): foo
Args:
y (int): bar
Examples:
first line
second line
third line
""" |
# Stepper mode select
STEPPER_m0 = 17
STEPPER_m1 = 27
STEPPER_m2 = 22
# First wheel GPIO Pin
WHEEL1_step = 21
WHEEL1_dir = 20
# Second wheel GPIO Pin
WHEEL2_step = 11
WHEEL2_dir = 10
# Third wheel GPIO Pin
WHEEL3_step = 7
WHEEL3_dir = 8
# Fourth wheel GPIO Pin
WHEEL4_step = 24
WHEEL4_dir = 23
CW = 1 # Clockwise rotation
CCW = 0 # Counter-clockwise rotation
STEPS_PER_REVOLUTION = 800 # Steps per Revolution (360/1.8) * 4. Multiply by 4 because quarter step.
STEPPER_DELAY = 0.0005
| stepper_m0 = 17
stepper_m1 = 27
stepper_m2 = 22
wheel1_step = 21
wheel1_dir = 20
wheel2_step = 11
wheel2_dir = 10
wheel3_step = 7
wheel3_dir = 8
wheel4_step = 24
wheel4_dir = 23
cw = 1
ccw = 0
steps_per_revolution = 800
stepper_delay = 0.0005 |
def compute(a, b):
return a + b
def Test1():
a = -1
b = 1
assert compute(a, b) == -1
def testabc():
a = 0
b = -1
assert compute(a, b) == 0
def Test3():
a = 1
b = 10
assert compute(a, b) == 10
def Test4():
a = -1
b = -1
assert compute(a, b) == 1
| def compute(a, b):
return a + b
def test1():
a = -1
b = 1
assert compute(a, b) == -1
def testabc():
a = 0
b = -1
assert compute(a, b) == 0
def test3():
a = 1
b = 10
assert compute(a, b) == 10
def test4():
a = -1
b = -1
assert compute(a, b) == 1 |
URL_PROJECT_VIEW="http://tasks.hotosm.org/project/{project}"
URL_PROJECT_EDIT="http://tasks.hotosm.org/project/{project}/edit"
URL_PROJECT_TASKS="http://tasks.hotosm.org/project/{project}/tasks.json"
URL_CHANGESET_VIEW="http://www.openstreetmap.org/changeset/{changeset}"
URL_CHANGESET_API ="https://api.openstreetmap.org/api/0.6/changeset/{changeset}"
URL_USER_VIEW="https://www.openstreetmap.org/user/{user}"
TASK_STATE_READY = 0
TASK_STATE_INVALIDATED = 1
TASK_STATE_DONE = 2
TASK_STATE_VALIDATED = 3
TASK_STATE_REMOVED = -1
| url_project_view = 'http://tasks.hotosm.org/project/{project}'
url_project_edit = 'http://tasks.hotosm.org/project/{project}/edit'
url_project_tasks = 'http://tasks.hotosm.org/project/{project}/tasks.json'
url_changeset_view = 'http://www.openstreetmap.org/changeset/{changeset}'
url_changeset_api = 'https://api.openstreetmap.org/api/0.6/changeset/{changeset}'
url_user_view = 'https://www.openstreetmap.org/user/{user}'
task_state_ready = 0
task_state_invalidated = 1
task_state_done = 2
task_state_validated = 3
task_state_removed = -1 |
def contains_cycle(first_node):
nodes_visited = set()
if not first_node or not first_node.next:
return False
current_node = first_node.next
while current_node.next:
if current_node.value in nodes_visited:
return True
else:
nodes_visited.add(current_node.value)
current_node = current_node.next
return False
| def contains_cycle(first_node):
nodes_visited = set()
if not first_node or not first_node.next:
return False
current_node = first_node.next
while current_node.next:
if current_node.value in nodes_visited:
return True
else:
nodes_visited.add(current_node.value)
current_node = current_node.next
return False |
pessoas = {'nome': 'Gustavo', 'sexo ': 'M', 'idade' : 22}
print(pessoas)
print(pessoas['idade'])## 22
print(f' O {pessoas["nome"]} tem {pessoas["idade"]} anos.')## O Gustavo tem 22 anos.
print(pessoas.keys())## dict_keys(['nome', 'sexo ', 'idade'])
print(pessoas.values())##dict_values(['Gustavo', 'M', 22])
print(pessoas.items())##dict_items([('nome', 'Gustavo'), ('sexo ', 'M'), ('idade', 22)])
for k in pessoas.keys():
print(k)## nome sexo idade
for k, v in pessoas.items():
print(f'{k} = {v}') ## nome = Gustavo // sexo = M // idade=22
pessoas['peso ']= 98.5 ## apaga sexo]
for k, v in pessoas.items():
print(f'{k} = {v}') ## nome = Gustavo // sexo = M // idade=22// peso = 98.5
| pessoas = {'nome': 'Gustavo', 'sexo ': 'M', 'idade': 22}
print(pessoas)
print(pessoas['idade'])
print(f" O {pessoas['nome']} tem {pessoas['idade']} anos.")
print(pessoas.keys())
print(pessoas.values())
print(pessoas.items())
for k in pessoas.keys():
print(k)
for (k, v) in pessoas.items():
print(f'{k} = {v}')
pessoas['peso '] = 98.5
for (k, v) in pessoas.items():
print(f'{k} = {v}') |
CONF_Main = {
"environment": "lux_gym:lux-v0",
"setup": "rl",
"model_name": "actor_critic_sep_residual_six_actions",
"n_points": 40, # check tfrecords reading transformation merge_rl
}
CONF_Scrape = {
"lux_version": "3.1.0",
"scrape_type": "single",
"parallel_calls": 8,
"is_for_rl": True,
"is_pg_rl": True,
"team_name": None, # "Toad Brigade",
"only_wins": False,
"only_top_teams": False,
}
CONF_Collect = {
"is_for_imitator": False,
"is_for_rl": True,
"is_pg_rl": True,
"only_wins": False,
}
CONF_Evaluate = {
"eval_compare_agent": "compare_agent_sub13",
}
CONF_Imitate = {
"batch_size": 300,
"self_imitation": False,
"with_evaluation": True,
}
CONF_RL = {
"rl_type": "continuous_ac_mc",
# "lambda": 0.8,
"debug": False,
"default_lr": 1e-5,
"batch_size": 300,
# "iterations_number": 1000,
# "save_interval": 100,
"entropy_c": 1e-5,
"entropy_c_decay": 0.3,
}
| conf__main = {'environment': 'lux_gym:lux-v0', 'setup': 'rl', 'model_name': 'actor_critic_sep_residual_six_actions', 'n_points': 40}
conf__scrape = {'lux_version': '3.1.0', 'scrape_type': 'single', 'parallel_calls': 8, 'is_for_rl': True, 'is_pg_rl': True, 'team_name': None, 'only_wins': False, 'only_top_teams': False}
conf__collect = {'is_for_imitator': False, 'is_for_rl': True, 'is_pg_rl': True, 'only_wins': False}
conf__evaluate = {'eval_compare_agent': 'compare_agent_sub13'}
conf__imitate = {'batch_size': 300, 'self_imitation': False, 'with_evaluation': True}
conf_rl = {'rl_type': 'continuous_ac_mc', 'debug': False, 'default_lr': 1e-05, 'batch_size': 300, 'entropy_c': 1e-05, 'entropy_c_decay': 0.3} |
# Transmission registers
TXB0CTRL = 0x30
TXB1CTRL = 0x40
TXB2CTRL = 0x50
TXRTSCTRL = 0x0D
TXB0SIDH = 0x31
TXB1SIDH = 0x41
TXB2SIDH = 0x51
TXB0SIDL = 0x32
TXB1SIDL = 0x42
TXB2SIDL = 0x52
TXB0EID8 = 0x33
TXB1EID8 = 0x43
TXB0EID8 = 0x53
TXB0EID0 = 0x34
TXB1EID0 = 0x44
TXB2EID0 = 0x54
TXB0DLC = 0x35
TXB1DLC = 0x45
TXB2DLC = 0x55
TXB0D = 0x36
TXB1D = 0x46
TXB2D = 0x56
# receive registers
RXB0CTRL = 0x60
RXB1CTRL = 0x70
BFPCTRL = 0x0C
RXB0SIDH = 0x61
RXB1SIDH = 0x71
RXB0SIDL = 0x62
RXB1SIDL = 0x72
RXB0EID8 = 0x63
RXB1EID8 = 0x73
RXB0EID0 = 0x64
RXB1EID0 = 0x74
RXB0DLC = 0x65
RXB1DLC = 0x75
RXB0D0 = 0x66
RXB0D1 = 0x67
RXB0D2 = 0x68
RXB0D3 = 0x69
RXB0D4 = 0x6A
RXB0D5 = 0x6B
RXB0D6 = 0x6C
RXB0D7 = 0x6D
RXB1D = 0x76
# Filter Registers
RXF0SIDH = 0x00
RXF1SIDH = 0x04
RXF2SIDH = 0x08
RXF3SIDH = 0x10
RXF4SIDH = 0x14
RXF5SIDH = 0x18
RXF0SIDL = 0x01
RXF1SIDL = 0x05
RXF2SIDL = 0x09
RXF3SIDL = 0x11
RXF4SIDL = 0x15
RXF5SIDL = 0x19
RXF0EID8 = 0x02
RXF1EID8 = 0x06
RXF2EID8 = 0x0A
RXF3EID8 = 0x12
RXF4EID8 = 0x16
RXF5EID8 = 0x1A
RXF0EID0 = 0x03
RXF1EID0 = 0x07
RXF2EID0 = 0x0B
RXF3EID0 = 0x13
RXF4EID0 = 0x17
RXF5EID0 = 0x1B
#Mask Registers
RXM0SIDH = 0x20
RXM1SIDH = 0x24
RXM0SIDL = 0x21
RXM1SIDL = 0x25
RXM0EID8 = 0x22
RXM1EID8 = 0x26
RXM0EID0 = 0x23
RXM1EID0 = 0x27
# Configuration Registers
CNF1 = 0x2A
CNF2 = 0x29
CNF3 = 0x28
TEC = 0x1C
REC = 0x1D
EFLG = 0x2D
CANINTE = 0x2B
CANINTF = 0x2C
CANCTRL = 0x0F
CANSTAT = 0x0E
| txb0_ctrl = 48
txb1_ctrl = 64
txb2_ctrl = 80
txrtsctrl = 13
txb0_sidh = 49
txb1_sidh = 65
txb2_sidh = 81
txb0_sidl = 50
txb1_sidl = 66
txb2_sidl = 82
txb0_eid8 = 51
txb1_eid8 = 67
txb0_eid8 = 83
txb0_eid0 = 52
txb1_eid0 = 68
txb2_eid0 = 84
txb0_dlc = 53
txb1_dlc = 69
txb2_dlc = 85
txb0_d = 54
txb1_d = 70
txb2_d = 86
rxb0_ctrl = 96
rxb1_ctrl = 112
bfpctrl = 12
rxb0_sidh = 97
rxb1_sidh = 113
rxb0_sidl = 98
rxb1_sidl = 114
rxb0_eid8 = 99
rxb1_eid8 = 115
rxb0_eid0 = 100
rxb1_eid0 = 116
rxb0_dlc = 101
rxb1_dlc = 117
rxb0_d0 = 102
rxb0_d1 = 103
rxb0_d2 = 104
rxb0_d3 = 105
rxb0_d4 = 106
rxb0_d5 = 107
rxb0_d6 = 108
rxb0_d7 = 109
rxb1_d = 118
rxf0_sidh = 0
rxf1_sidh = 4
rxf2_sidh = 8
rxf3_sidh = 16
rxf4_sidh = 20
rxf5_sidh = 24
rxf0_sidl = 1
rxf1_sidl = 5
rxf2_sidl = 9
rxf3_sidl = 17
rxf4_sidl = 21
rxf5_sidl = 25
rxf0_eid8 = 2
rxf1_eid8 = 6
rxf2_eid8 = 10
rxf3_eid8 = 18
rxf4_eid8 = 22
rxf5_eid8 = 26
rxf0_eid0 = 3
rxf1_eid0 = 7
rxf2_eid0 = 11
rxf3_eid0 = 19
rxf4_eid0 = 23
rxf5_eid0 = 27
rxm0_sidh = 32
rxm1_sidh = 36
rxm0_sidl = 33
rxm1_sidl = 37
rxm0_eid8 = 34
rxm1_eid8 = 38
rxm0_eid0 = 35
rxm1_eid0 = 39
cnf1 = 42
cnf2 = 41
cnf3 = 40
tec = 28
rec = 29
eflg = 45
caninte = 43
canintf = 44
canctrl = 15
canstat = 14 |
class Solution:
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
first = second = float('inf')
for n in nums:
if n <= first:
first = n
elif n <= second:
second = n
else:
return True
return False
def test_increasing_triplet():
s = Solution()
assert s.increasingTriplet([1, 2, 3, 4, 5]) is True
assert s.increasingTriplet([5, 4, 3, 2, 1]) is False
assert s.increasingTriplet([5, 1, 5, 5, 2, 5, 4]) is True
assert s.increasingTriplet([2, 4, -2, -3]) is False
| class Solution:
def increasing_triplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
first = second = float('inf')
for n in nums:
if n <= first:
first = n
elif n <= second:
second = n
else:
return True
return False
def test_increasing_triplet():
s = solution()
assert s.increasingTriplet([1, 2, 3, 4, 5]) is True
assert s.increasingTriplet([5, 4, 3, 2, 1]) is False
assert s.increasingTriplet([5, 1, 5, 5, 2, 5, 4]) is True
assert s.increasingTriplet([2, 4, -2, -3]) is False |
# Heroku PostgreSQL credentials, rename this file to config.py
HOST = "placeholder"
DB = "placeholder"
USER = "placeholder"
PASSWORD = "placeholder"
PORT = "5432"
| host = 'placeholder'
db = 'placeholder'
user = 'placeholder'
password = 'placeholder'
port = '5432' |
# Every neuron has a unique connection to the previous neuron.
inputs = [3.1 , 2.5 , 5.4]
# Every input is going to have a unique weight
weights = [4.5 , 7.6 , 2.4]
# Every neuron is going to have a unique bias
bias = 3
# Now let's check the output from the neuron
output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias
# Now let's print the output
print(output)
| inputs = [3.1, 2.5, 5.4]
weights = [4.5, 7.6, 2.4]
bias = 3
output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias
print(output) |
class RebarCouplerError(Enum, IComparable, IFormattable, IConvertible):
"""
Error states for the Rebar Coupler
enum RebarCouplerError,values: BarSegementsAreNotParallel (6),BarSegmentsAreNotOnSameLine (7),BarSegmentSmallerThanEngagement (13),BarsNotTouching (3),CurvesOtherThanLine (12),DifferentLayout (2),InconsistentShape (8),IncorrectEndTreatmentCoupler (5),IncorrectEndTreatmentHook (4),IncorrectInputData (1),InvalidDiameter (9),ValidationSuccessfuly (0),VaryingDistanceBetweenDistributionsBars (14)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
BarSegementsAreNotParallel = None
BarSegmentsAreNotOnSameLine = None
BarSegmentSmallerThanEngagement = None
BarsNotTouching = None
CurvesOtherThanLine = None
DifferentLayout = None
InconsistentShape = None
IncorrectEndTreatmentCoupler = None
IncorrectEndTreatmentHook = None
IncorrectInputData = None
InvalidDiameter = None
ValidationSuccessfuly = None
value__ = None
VaryingDistanceBetweenDistributionsBars = None
| class Rebarcouplererror(Enum, IComparable, IFormattable, IConvertible):
"""
Error states for the Rebar Coupler
enum RebarCouplerError,values: BarSegementsAreNotParallel (6),BarSegmentsAreNotOnSameLine (7),BarSegmentSmallerThanEngagement (13),BarsNotTouching (3),CurvesOtherThanLine (12),DifferentLayout (2),InconsistentShape (8),IncorrectEndTreatmentCoupler (5),IncorrectEndTreatmentHook (4),IncorrectInputData (1),InvalidDiameter (9),ValidationSuccessfuly (0),VaryingDistanceBetweenDistributionsBars (14)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
bar_segements_are_not_parallel = None
bar_segments_are_not_on_same_line = None
bar_segment_smaller_than_engagement = None
bars_not_touching = None
curves_other_than_line = None
different_layout = None
inconsistent_shape = None
incorrect_end_treatment_coupler = None
incorrect_end_treatment_hook = None
incorrect_input_data = None
invalid_diameter = None
validation_successfuly = None
value__ = None
varying_distance_between_distributions_bars = None |
def generate_odd_nums(start, end):
for num in range(start, end+1):
if num % 2 !=0:
print(num, end=" ")
generate_odd_nums(start = 0, end = 15)
| def generate_odd_nums(start, end):
for num in range(start, end + 1):
if num % 2 != 0:
print(num, end=' ')
generate_odd_nums(start=0, end=15) |
__author__ = 'KKishore'
PAD_WORD = '#=KISHORE=#'
HEADERS = ['class', 'sms']
FEATURE_COL = 'sms'
LABEL_COL = 'class'
WEIGHT_COLUNM_NAME = 'weight'
TARGET_LABELS = ['spam', 'ham']
TARGET_SIZE = len(TARGET_LABELS)
HEADER_DEFAULTS = [['NA'], ['NA']]
MAX_DOCUMENT_LENGTH = 100
| __author__ = 'KKishore'
pad_word = '#=KISHORE=#'
headers = ['class', 'sms']
feature_col = 'sms'
label_col = 'class'
weight_colunm_name = 'weight'
target_labels = ['spam', 'ham']
target_size = len(TARGET_LABELS)
header_defaults = [['NA'], ['NA']]
max_document_length = 100 |
class PracticeCenter:
def __init__(self, practice_center_id, name, email=None, web_site=None, phone_number=None,
climates=None, recommendations=None, average_note=None):
self.id = practice_center_id
self.name = name
self.email = email
self.web_site = web_site
self.phone_number = phone_number
self.climates = [] if climates is None else climates
self.recommendations = [] if recommendations is None else recommendations
self.average_note = 0 if average_note is None else average_note
def __eq__(self, other):
if isinstance(other, PracticeCenter):
return self.id == other.id
return False
| class Practicecenter:
def __init__(self, practice_center_id, name, email=None, web_site=None, phone_number=None, climates=None, recommendations=None, average_note=None):
self.id = practice_center_id
self.name = name
self.email = email
self.web_site = web_site
self.phone_number = phone_number
self.climates = [] if climates is None else climates
self.recommendations = [] if recommendations is None else recommendations
self.average_note = 0 if average_note is None else average_note
def __eq__(self, other):
if isinstance(other, PracticeCenter):
return self.id == other.id
return False |
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return "Rectangle(width=" + str(self.width) + ", height="+ str(self.height) + ")"
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
return self.width * self.height
def get_perimeter(self):
return 2 * (self.width + self.height)
def get_diagonal(self):
return (self.width ** 2 + self.height ** 2) ** 0.5
def get_picture(self):
if(self.width > 50 or self.height > 50):
return "Too big for picture."
string = ""
for i in range(self.height):
for j in range(self.width):
string += '*'
string += '\n'
return string
def get_amount_inside(self, another_shape):
return self.get_area() // another_shape.get_area()
class Square(Rectangle):
def __init__(self, length):
self.length = length
def __str__(self):
return "Square(side=" + str(self.length) + ")"
def set_side(self, length):
self.length = length
def set_width(self, length):
self.length = length
def set_height(self, length):
self.length = length
def get_area(self):
return self.length ** 2
def get_perimeter(self):
return 4 * self.length
def get_diagonal(self):
return (2 * self.length ** 2) ** 0.5
def get_picture(self):
if(self.length > 50):
return "Too big for picture."
string = ""
for i in range(self.length):
for j in range(self.length):
string += '*'
string += '\n'
return string
| class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return 'Rectangle(width=' + str(self.width) + ', height=' + str(self.height) + ')'
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
return self.width * self.height
def get_perimeter(self):
return 2 * (self.width + self.height)
def get_diagonal(self):
return (self.width ** 2 + self.height ** 2) ** 0.5
def get_picture(self):
if self.width > 50 or self.height > 50:
return 'Too big for picture.'
string = ''
for i in range(self.height):
for j in range(self.width):
string += '*'
string += '\n'
return string
def get_amount_inside(self, another_shape):
return self.get_area() // another_shape.get_area()
class Square(Rectangle):
def __init__(self, length):
self.length = length
def __str__(self):
return 'Square(side=' + str(self.length) + ')'
def set_side(self, length):
self.length = length
def set_width(self, length):
self.length = length
def set_height(self, length):
self.length = length
def get_area(self):
return self.length ** 2
def get_perimeter(self):
return 4 * self.length
def get_diagonal(self):
return (2 * self.length ** 2) ** 0.5
def get_picture(self):
if self.length > 50:
return 'Too big for picture.'
string = ''
for i in range(self.length):
for j in range(self.length):
string += '*'
string += '\n'
return string |
class Test:
def foo(a):
if a == 'foo':
return 'foo'
return 'bar'
| class Test:
def foo(a):
if a == 'foo':
return 'foo'
return 'bar' |
#-------------------------------------------------------------------
# Copyright (c) 2021, Scott D. Peckham
#
# Oct. 2021. Added to bypass old tf_utils.py for version, etc.
#
#-------------------------------------------------------------------
# Notes: Update these whenever a new version is released
#-------------------------------------------------------------------
#
# name()
# version_number()
# build_date()
# version_string()
#
#-------------------------------------------------------------------
def name():
return 'Stochastic Conflict Model'
# name()
#-------------------------------------------------------------------
def version_number():
return 0.8
# version_number()
#-------------------------------------------------------------------
def build_date():
return '2021-10-13'
# build_date()
#-------------------------------------------------------------------
def version_string():
num_str = str( version_number() )
date_str = ' (' + build_date() + ')'
ver_string = name() + ' Version ' + num_str + date_str
return ver_string
# version_string()
#-------------------------------------------------------------------
| def name():
return 'Stochastic Conflict Model'
def version_number():
return 0.8
def build_date():
return '2021-10-13'
def version_string():
num_str = str(version_number())
date_str = ' (' + build_date() + ')'
ver_string = name() + ' Version ' + num_str + date_str
return ver_string |
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit = temp_profit = 0
incresing = [tomorrow-today for today, tomorrow in zip(prices[:-1],prices[1:])]
# print(incresing)
for price in incresing:
temp_profit += price
if temp_profit < 0:
temp_profit = 0
else:
max_profit = max(max_profit, temp_profit)
return max_profit | class Solution:
def max_profit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit = temp_profit = 0
incresing = [tomorrow - today for (today, tomorrow) in zip(prices[:-1], prices[1:])]
for price in incresing:
temp_profit += price
if temp_profit < 0:
temp_profit = 0
else:
max_profit = max(max_profit, temp_profit)
return max_profit |
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
#or
full_name = "{} {}".format(first_name,last_name)
#print(full_name)
message = f"Hello, {full_name.title()}!"
print(message) | first_name = 'ada'
last_name = 'lovelace'
full_name = f'{first_name} {last_name}'
full_name = '{} {}'.format(first_name, last_name)
message = f'Hello, {full_name.title()}!'
print(message) |
'''
the permission will be set in the database
and only the managers will have permission to
cancel an order already completed
'''
class User():
def __init__(self, userid, username, permission):
self.userid=userid
self.username=username
self.permission=permission
def getUserNumber(self):
return self.userid
def getUserName(self):
return self.username
def getUserPermission(self):
return self.permission
def __str__(self):
return self.username | """
the permission will be set in the database
and only the managers will have permission to
cancel an order already completed
"""
class User:
def __init__(self, userid, username, permission):
self.userid = userid
self.username = username
self.permission = permission
def get_user_number(self):
return self.userid
def get_user_name(self):
return self.username
def get_user_permission(self):
return self.permission
def __str__(self):
return self.username |
class Solution:
def recurse(self, A, stack) :
if A == "" :
self.ans.append(stack)
temp_str = ""
n = len(A)
for i, ch in enumerate(A) :
temp_str += ch
if self.isPalindrome(temp_str) :
self.recurse(A[i+1:], stack+[temp_str])
def isPalindrome(self, string) :
if string == string[::-1] :
return True
return False
# @param A : string
# @return a list of list of strings
def partition(self, A):
n = len(A)
if n <= 1 :
return [A]
self.ans = []
self.recurse(A, [])
self.ans.sort()
return self.ans
| class Solution:
def recurse(self, A, stack):
if A == '':
self.ans.append(stack)
temp_str = ''
n = len(A)
for (i, ch) in enumerate(A):
temp_str += ch
if self.isPalindrome(temp_str):
self.recurse(A[i + 1:], stack + [temp_str])
def is_palindrome(self, string):
if string == string[::-1]:
return True
return False
def partition(self, A):
n = len(A)
if n <= 1:
return [A]
self.ans = []
self.recurse(A, [])
self.ans.sort()
return self.ans |
class DataParser:
input_pub_sub_subscription = ""
output_pub_sub_subscription = ""
stocks: list = []
brokers: list = []
def __init__(self, html):
self.html = html
def parse_table_content(self, html):
"""
:param html: a table of stock or broker
:return:
"""
pass
def parse_stocks(self, content):
"""
for each stock return buys sells and net
:param content:
:return:
"""
pass
def parse_brokers(self, content):
"""
for each broker return buys sells and net
:param content:
:return:
"""
pass
def save_stocks(self, stocks):
"""
save all stock data to data-service main database
:param stocks:
:return:
"""
pass
def save_brokers(self, brokers):
"""
save all brokers data to data-service main database
:param brokers:
:return:
"""
pass
def get_single_stock(self, symbol):
"""
parse data for just one stock symbol
:param stocks:
:return:
"""
pass
def send_to_pubsub_topic(self, stocks):
"""
get single stock from the list of stocks then send that stock through pubsub
:param stocks:
:return:
"""
pass
| class Dataparser:
input_pub_sub_subscription = ''
output_pub_sub_subscription = ''
stocks: list = []
brokers: list = []
def __init__(self, html):
self.html = html
def parse_table_content(self, html):
"""
:param html: a table of stock or broker
:return:
"""
pass
def parse_stocks(self, content):
"""
for each stock return buys sells and net
:param content:
:return:
"""
pass
def parse_brokers(self, content):
"""
for each broker return buys sells and net
:param content:
:return:
"""
pass
def save_stocks(self, stocks):
"""
save all stock data to data-service main database
:param stocks:
:return:
"""
pass
def save_brokers(self, brokers):
"""
save all brokers data to data-service main database
:param brokers:
:return:
"""
pass
def get_single_stock(self, symbol):
"""
parse data for just one stock symbol
:param stocks:
:return:
"""
pass
def send_to_pubsub_topic(self, stocks):
"""
get single stock from the list of stocks then send that stock through pubsub
:param stocks:
:return:
"""
pass |
# name: TColors
# Version: 1
# Created by: Grigory Sazanov
# GitHub: https://github.com/SazanovGrigory
class TerminalColors:
# Description: Class that can be used to color terminal output
# Example: print('GitHub: '+f"{BColors.TerminalColors.UNDERLINE}https://github.com/SazanovGrigory{BColors.TerminalColors.ENDC}")
HEADER ='\033[95m'
OKBLUE ='\033[94m'
OKCYAN ='\033[96m'
OKGREEN ='\033[92m'
WARNING ='\033[93m'
FAIL ='\033[91m'
ENDC ='\033[0m'
BOLD ='\033[1m'
UNDERLINE ='\033[4m'
def main():
print('Name: '+f"{TerminalColors.HEADER}TColors{TerminalColors.ENDC}")
print('Version: '+f"{TerminalColors.WARNING}1{TerminalColors.ENDC}")
print('Created by: '+f"{TerminalColors.BOLD}Grigory Sazanov{TerminalColors.ENDC}")
print('GitHub: '+f"{TerminalColors.UNDERLINE}https://github.com/SazanovGrigory{TerminalColors.ENDC}")
print(f"{TerminalColors.OKGREEN}Description: This is just a class that can be used to color terminal output{TerminalColors.ENDC}")
print("Example: print(\"GitHub: \"+f\"{TColors.TerminalColors.UNDERLINE}Some text here{TColors.TerminalColors.ENDC}\")")
print('Colors:')
print(' '+f"{TerminalColors.HEADER}HEADER{TerminalColors.ENDC}")
print(' '+f"{TerminalColors.OKBLUE}OKBLUE{TerminalColors.ENDC}")
print(' '+f"{TerminalColors.OKCYAN}OKCYAN{TerminalColors.ENDC}")
print(' '+f"{TerminalColors.OKGREEN}OKGREEN{TerminalColors.ENDC}")
print(' '+f"{TerminalColors.WARNING}WARNING{TerminalColors.ENDC}")
print(' '+f"{TerminalColors.FAIL}FAIL{TerminalColors.ENDC}")
print(' '+f"{TerminalColors.BOLD}BOLD{TerminalColors.ENDC}")
print(' '+f"{TerminalColors.UNDERLINE}UNDERLINE{TerminalColors.ENDC}")
if __name__ == '__main__':
main() | class Terminalcolors:
header = '\x1b[95m'
okblue = '\x1b[94m'
okcyan = '\x1b[96m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
def main():
print('Name: ' + f'{TerminalColors.HEADER}TColors{TerminalColors.ENDC}')
print('Version: ' + f'{TerminalColors.WARNING}1{TerminalColors.ENDC}')
print('Created by: ' + f'{TerminalColors.BOLD}Grigory Sazanov{TerminalColors.ENDC}')
print('GitHub: ' + f'{TerminalColors.UNDERLINE}https://github.com/SazanovGrigory{TerminalColors.ENDC}')
print(f'{TerminalColors.OKGREEN}Description: This is just a class that can be used to color terminal output{TerminalColors.ENDC}')
print('Example: print("GitHub: "+f"{TColors.TerminalColors.UNDERLINE}Some text here{TColors.TerminalColors.ENDC}")')
print('Colors:')
print(' ' + f'{TerminalColors.HEADER}HEADER{TerminalColors.ENDC}')
print(' ' + f'{TerminalColors.OKBLUE}OKBLUE{TerminalColors.ENDC}')
print(' ' + f'{TerminalColors.OKCYAN}OKCYAN{TerminalColors.ENDC}')
print(' ' + f'{TerminalColors.OKGREEN}OKGREEN{TerminalColors.ENDC}')
print(' ' + f'{TerminalColors.WARNING}WARNING{TerminalColors.ENDC}')
print(' ' + f'{TerminalColors.FAIL}FAIL{TerminalColors.ENDC}')
print(' ' + f'{TerminalColors.BOLD}BOLD{TerminalColors.ENDC}')
print(' ' + f'{TerminalColors.UNDERLINE}UNDERLINE{TerminalColors.ENDC}')
if __name__ == '__main__':
main() |
"""
#David Hickox
#Mar 20 17
#Typing Program
#this will tell each of the 7 dwarfs if they can type fast enough or not
#variables
# STUDENTS = names of the dwarfs
# num = WPM
"""
STUDENTS = ["Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"]
print("Welcome to the Typing program")
#starts the loop
for i in enumerate(STUDENTS):
#asks for input
num = float(input("How many words per minute can "+i[1]+" type? "))
#checks to see what wpm someone types at
if num >= 150:
print(i[1].upper(), "PUT DOWN THE COFFEE!!!")
elif num >= 25:
print(i[1], "you can type fast enough to pass Keyboarding")
else:
print(i[1]+", sorry you need to type faster!")
input("Press Enter to exit")
| """
#David Hickox
#Mar 20 17
#Typing Program
#this will tell each of the 7 dwarfs if they can type fast enough or not
#variables
# STUDENTS = names of the dwarfs
# num = WPM
"""
students = ['Bashful', 'Doc', 'Dopey', 'Happy', 'Sleepy', 'Sneezy', 'Grumpy']
print('Welcome to the Typing program')
for i in enumerate(STUDENTS):
num = float(input('How many words per minute can ' + i[1] + ' type? '))
if num >= 150:
print(i[1].upper(), 'PUT DOWN THE COFFEE!!!')
elif num >= 25:
print(i[1], 'you can type fast enough to pass Keyboarding')
else:
print(i[1] + ', sorry you need to type faster!')
input('Press Enter to exit') |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def solve(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if not t1 and not t2:
return None
node = TreeNode(0)
if t1:
node.val += t1.val
if t2:
node.val += t2.val
l = self.solve(t1.left if t1 else None, t2.left if t2 else None)
r = self.solve(t1.right if t1 else None, t2.right if t2 else None)
node.left = l
node.right = r
return node
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
return self.solve(t1, t2)
| class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def solve(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if not t1 and (not t2):
return None
node = tree_node(0)
if t1:
node.val += t1.val
if t2:
node.val += t2.val
l = self.solve(t1.left if t1 else None, t2.left if t2 else None)
r = self.solve(t1.right if t1 else None, t2.right if t2 else None)
node.left = l
node.right = r
return node
def merge_trees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
return self.solve(t1, t2) |
"""Question: https://leetcode.com/problems/validate-binary-search-tree/
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def is_valid_bst_recu(root, low, high):
if root is None:
return True
return (low < root.val < high
and is_valid_bst_recu(root.left, low, root.val)
and is_valid_bst_recu(root.right, root.val, high))
return is_valid_bst_recu(root, float('-inf'), float('inf'))
| """Question: https://leetcode.com/problems/validate-binary-search-tree/
"""
class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_valid_bst(self, root: TreeNode) -> bool:
def is_valid_bst_recu(root, low, high):
if root is None:
return True
return low < root.val < high and is_valid_bst_recu(root.left, low, root.val) and is_valid_bst_recu(root.right, root.val, high)
return is_valid_bst_recu(root, float('-inf'), float('inf')) |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 14:15:21 2019
@author: hu
"""
| """
Created on Wed Jul 17 14:15:21 2019
@author: hu
""" |
def foo():
global bar
def bar():
pass
| def foo():
global bar
def bar():
pass |
#!/usr/bin/env python
"""
idea: break up the address into 3 sections: 0xAABBCC.
Treat each section like it is a layer in the page tables.
AA is the base of one table. From that, offset BB is the base of the "PTE".
Then CC is the offset into the "page" and contains a 24-bit word that we can
copy.
"""
WORD_WIDTH = 24
DEPTH = 4
bit = 0xdeadbe
bit = bit & ((1 << WORD_WIDTH) - 1)
def gen(depth, prefix, max):
width = DEPTH - depth
indent = " "*(width)
assert(max < (1<<DEPTH))
pretty_bin = "{:0{width}b}"
prefix_fmt = "prefix_" + pretty_bin
next_1 = (prefix << 1) | 1
prefix_1 = prefix_fmt.format(next_1, width=width+1)
next_0 = (prefix << 1) | 0
prefix_0 = prefix_fmt.format(next_0, width=width+1)
if depth == 0 and prefix <= max:
real_label = "_BB_" + pretty_bin.format(prefix, width=width)
print("{0}jmp {1}, {1}".format(indent, real_label))
elif (prefix << depth) > max:
print("{}EXIT".format(indent))
else:
print("{}seek PC_base + width".format(indent))
print("{}jmp {}, {}".format(indent, prefix_1, prefix_0))
print("{}prefix_{:0{width}b}:".format(indent, next_1, width=width+1))
gen(depth - 1, next_1, max)
print("{}prefix_{:0{width}b}:".format(indent, next_0, width=width+1))
gen(depth - 1, next_0, max)
gen(DEPTH, 0, 3)
| """
idea: break up the address into 3 sections: 0xAABBCC.
Treat each section like it is a layer in the page tables.
AA is the base of one table. From that, offset BB is the base of the "PTE".
Then CC is the offset into the "page" and contains a 24-bit word that we can
copy.
"""
word_width = 24
depth = 4
bit = 14593470
bit = bit & (1 << WORD_WIDTH) - 1
def gen(depth, prefix, max):
width = DEPTH - depth
indent = ' ' * width
assert max < 1 << DEPTH
pretty_bin = '{:0{width}b}'
prefix_fmt = 'prefix_' + pretty_bin
next_1 = prefix << 1 | 1
prefix_1 = prefix_fmt.format(next_1, width=width + 1)
next_0 = prefix << 1 | 0
prefix_0 = prefix_fmt.format(next_0, width=width + 1)
if depth == 0 and prefix <= max:
real_label = '_BB_' + pretty_bin.format(prefix, width=width)
print('{0}jmp {1}, {1}'.format(indent, real_label))
elif prefix << depth > max:
print('{}EXIT'.format(indent))
else:
print('{}seek PC_base + width'.format(indent))
print('{}jmp {}, {}'.format(indent, prefix_1, prefix_0))
print('{}prefix_{:0{width}b}:'.format(indent, next_1, width=width + 1))
gen(depth - 1, next_1, max)
print('{}prefix_{:0{width}b}:'.format(indent, next_0, width=width + 1))
gen(depth - 1, next_0, max)
gen(DEPTH, 0, 3) |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
INSTANCE_TAIL_LOGS_RESPONSE = """-------------------------------------
/var/log/awslogs.log
-------------------------------------
{'skipped_events_count': 0, 'first_event': {'timestamp': 1522962583519, 'start_position': 559799L, 'end_position': 560017L}, 'fallback_events_count': 0, 'last_event': {'timestamp': 1522962583519, 'start_position': 559799L, 'end_position': 560017L}, 'source_id': '77b026040b93055eb448bdc0b59e446f', 'num_of_events': 1, 'batch_size_in_bytes': 243}
-------------------------------------
/var/log/httpd/error_log
-------------------------------------
[Thu Apr 05 19:54:23.624780 2018] [mpm_prefork:warn] [pid 3470] AH00167: long lost child came home! (pid 3088)
-------------------------------------
/var/log/httpd/access_log
-------------------------------------
172.31.69.153 (94.208.192.103) - - [05/Apr/2018:20:57:55 +0000] "HEAD /pma/ HTTP/1.1" 404 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
-------------------------------------
/var/log/eb-activity.log
-------------------------------------
+ chown -R webapp:webapp /var/app/ondeck
[2018-04-05T19:54:21.630Z] INFO [3555] - [Application update app-180406_044630@3/AppDeployStage0/AppDeployPreHook/02_setup_envvars.sh] : Starting activity...
-------------------------------------
/tmp/sample-app.log
-------------------------------------
2018-04-05 20:52:51 Received message: \\xe2\\x96\\x88\\xe2
-------------------------------------
/var/log/eb-commandprocessor.log
-------------------------------------
[2018-04-05T19:45:05.526Z] INFO [2853] : Running 2 of 2 actions: AppDeployPostHook..."""
REQUEST_ENVIRONMENT_INFO_RESPONSE = {
"EnvironmentInfo": [
{
"InfoType": "tail",
"Ec2InstanceId": "i-024a31a441247971d",
"SampleTimestamp": "2018-04-06T01:05:43.875Z",
"Message": "https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com"
},
{
"InfoType": "tail",
"Ec2InstanceId": "i-0dce0f6c5e2d5fa48",
"SampleTimestamp": "2018-04-06T01:05:43.993Z",
"Message": "https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com"
},
{
"InfoType": "tail",
"Ec2InstanceId": "i-090689581e5afcfc6",
"SampleTimestamp": "2018-04-06T01:05:43.721Z",
"Message": "https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com"
},
{
"InfoType": "tail",
"Ec2InstanceId": "i-053efe7c102d0a540",
"SampleTimestamp": "2018-04-06T01:05:43.900Z",
"Message": "https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com"
}
]
}
| instance_tail_logs_response = '-------------------------------------\n/var/log/awslogs.log\n-------------------------------------\n{\'skipped_events_count\': 0, \'first_event\': {\'timestamp\': 1522962583519, \'start_position\': 559799L, \'end_position\': 560017L}, \'fallback_events_count\': 0, \'last_event\': {\'timestamp\': 1522962583519, \'start_position\': 559799L, \'end_position\': 560017L}, \'source_id\': \'77b026040b93055eb448bdc0b59e446f\', \'num_of_events\': 1, \'batch_size_in_bytes\': 243}\n\n\n\n-------------------------------------\n/var/log/httpd/error_log\n-------------------------------------\n[Thu Apr 05 19:54:23.624780 2018] [mpm_prefork:warn] [pid 3470] AH00167: long lost child came home! (pid 3088)\n\n\n\n-------------------------------------\n/var/log/httpd/access_log\n-------------------------------------\n172.31.69.153 (94.208.192.103) - - [05/Apr/2018:20:57:55 +0000] "HEAD /pma/ HTTP/1.1" 404 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"\n\n\n\n-------------------------------------\n/var/log/eb-activity.log\n-------------------------------------\n + chown -R webapp:webapp /var/app/ondeck\n[2018-04-05T19:54:21.630Z] INFO [3555] - [Application update app-180406_044630@3/AppDeployStage0/AppDeployPreHook/02_setup_envvars.sh] : Starting activity...\n\n\n-------------------------------------\n/tmp/sample-app.log\n-------------------------------------\n2018-04-05 20:52:51 Received message: \\xe2\\x96\\x88\\xe2\n\n\n\n-------------------------------------\n/var/log/eb-commandprocessor.log\n-------------------------------------\n[2018-04-05T19:45:05.526Z] INFO [2853] : Running 2 of 2 actions: AppDeployPostHook...'
request_environment_info_response = {'EnvironmentInfo': [{'InfoType': 'tail', 'Ec2InstanceId': 'i-024a31a441247971d', 'SampleTimestamp': '2018-04-06T01:05:43.875Z', 'Message': 'https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com'}, {'InfoType': 'tail', 'Ec2InstanceId': 'i-0dce0f6c5e2d5fa48', 'SampleTimestamp': '2018-04-06T01:05:43.993Z', 'Message': 'https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com'}, {'InfoType': 'tail', 'Ec2InstanceId': 'i-090689581e5afcfc6', 'SampleTimestamp': '2018-04-06T01:05:43.721Z', 'Message': 'https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com'}, {'InfoType': 'tail', 'Ec2InstanceId': 'i-053efe7c102d0a540', 'SampleTimestamp': '2018-04-06T01:05:43.900Z', 'Message': 'https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com'}]} |
class ParadoxException(Exception):
pass
class ParadoxConnectError(ParadoxException):
def __init__(self) -> None:
super().__init__('Unable to connect to panel')
class ParadoxCommandError(ParadoxException):
pass
class ParadoxTimeout(ParadoxException):
pass
| class Paradoxexception(Exception):
pass
class Paradoxconnecterror(ParadoxException):
def __init__(self) -> None:
super().__init__('Unable to connect to panel')
class Paradoxcommanderror(ParadoxException):
pass
class Paradoxtimeout(ParadoxException):
pass |
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
def merge(l1, l2):
if not l1: return l2
if not l2: return l1
if l1[0] < l2[0]:
return [l1[0]] + merge(l1[1:], l2)
else:
return [l2[0]] + merge(l1, l2[1:])
nums = merge(nums1,nums2)
l = len(nums)
if l%2:
return nums[(l-1)//2]
else:
return (nums[l//2] +nums[l//2 -1])/2
| class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
def merge(l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1[0] < l2[0]:
return [l1[0]] + merge(l1[1:], l2)
else:
return [l2[0]] + merge(l1, l2[1:])
nums = merge(nums1, nums2)
l = len(nums)
if l % 2:
return nums[(l - 1) // 2]
else:
return (nums[l // 2] + nums[l // 2 - 1]) / 2 |
cities = [
'Riga',
'Daugavpils',
'Liepaja',
'Jelgava',
'Jurmala',
'Ventspils',
'Rezekne',
'Jekabpils',
'Valmiera',
'Ogre',
'Tukums',
'Cesis',
'Salaspils',
'Bolderaja',
'Kuldiga',
'Olaine',
'Saldus',
'Talsi',
'Dobele',
'Kraslava',
'Bauska',
'Ludza',
'Sigulda',
'Livani',
'Daugavgriva',
'Gulbene',
'Madona',
'Limbazi',
'Aizkraukle',
'Preili',
'Balvi',
'Karosta',
'Krustpils',
'Valka',
'Smiltene',
'Aizpute',
'Lielvarde',
'Kekava',
'Grobina',
'Iecava',
'Vilani',
'Plavinas',
'Rujiena',
'Kandava',
'Broceni',
'Salacgriva',
'Ozolnieki',
'Ikskile',
'Saulkrasti',
'Auce',
'Pinki',
'Ilukste',
'Skriveri',
'Ulbroka',
'Dagda',
'Skrunda',
'Karsava',
'Priekule',
'Priekuli',
'Vecumnieki',
'Mazsalaca',
'Kegums',
'Aluksne',
'Ergli',
'Viesite',
'Varaklani',
'Incukalns',
'Baldone',
'Jaunjelgava',
'Lubana',
'Zilupe',
'Mersrags',
'Cesvaine',
'Roja',
'Strenci',
'Vilaka',
'Ape',
'Aloja',
'Ligatne',
'Akniste',
'Nereta',
'Pavilosta',
'Jaunpils',
'Alsunga',
'Smarde',
'Vecpiebalga',
'Rucava',
'Marupe',
'Adazi',
'Aglona',
'Baltinava',
'Bergi',
'Carnikava',
'Drabesi',
'Dundaga',
'Cibla',
'Jaunpiebalga',
'Koceni',
'Koknese',
'Liegi',
'Loja',
'Malpils',
'Matisi',
'Murmuiza',
'Naukseni',
'Nica',
'Pilsrundale',
'Ragana',
'Rauna',
'Riebini',
'Ropazi',
'Garkalne',
'Rugaji',
'Sala',
'Stalbe',
'Vainode',
'Vecvarkava',
'Zelmeni'
]
| cities = ['Riga', 'Daugavpils', 'Liepaja', 'Jelgava', 'Jurmala', 'Ventspils', 'Rezekne', 'Jekabpils', 'Valmiera', 'Ogre', 'Tukums', 'Cesis', 'Salaspils', 'Bolderaja', 'Kuldiga', 'Olaine', 'Saldus', 'Talsi', 'Dobele', 'Kraslava', 'Bauska', 'Ludza', 'Sigulda', 'Livani', 'Daugavgriva', 'Gulbene', 'Madona', 'Limbazi', 'Aizkraukle', 'Preili', 'Balvi', 'Karosta', 'Krustpils', 'Valka', 'Smiltene', 'Aizpute', 'Lielvarde', 'Kekava', 'Grobina', 'Iecava', 'Vilani', 'Plavinas', 'Rujiena', 'Kandava', 'Broceni', 'Salacgriva', 'Ozolnieki', 'Ikskile', 'Saulkrasti', 'Auce', 'Pinki', 'Ilukste', 'Skriveri', 'Ulbroka', 'Dagda', 'Skrunda', 'Karsava', 'Priekule', 'Priekuli', 'Vecumnieki', 'Mazsalaca', 'Kegums', 'Aluksne', 'Ergli', 'Viesite', 'Varaklani', 'Incukalns', 'Baldone', 'Jaunjelgava', 'Lubana', 'Zilupe', 'Mersrags', 'Cesvaine', 'Roja', 'Strenci', 'Vilaka', 'Ape', 'Aloja', 'Ligatne', 'Akniste', 'Nereta', 'Pavilosta', 'Jaunpils', 'Alsunga', 'Smarde', 'Vecpiebalga', 'Rucava', 'Marupe', 'Adazi', 'Aglona', 'Baltinava', 'Bergi', 'Carnikava', 'Drabesi', 'Dundaga', 'Cibla', 'Jaunpiebalga', 'Koceni', 'Koknese', 'Liegi', 'Loja', 'Malpils', 'Matisi', 'Murmuiza', 'Naukseni', 'Nica', 'Pilsrundale', 'Ragana', 'Rauna', 'Riebini', 'Ropazi', 'Garkalne', 'Rugaji', 'Sala', 'Stalbe', 'Vainode', 'Vecvarkava', 'Zelmeni'] |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( s ) :
n = len ( s ) ;
sub_count = ( n * ( n + 1 ) ) // 2 ;
arr = [ 0 ] * sub_count ;
index = 0 ;
for i in range ( n ) :
for j in range ( 1 , n - i + 1 ) :
arr [ index ] = s [ i : i + j ] ;
index += 1 ;
arr.sort ( ) ;
res = "" ;
for i in range ( sub_count ) :
res += arr [ i ] ;
return res ;
#TOFILL
if __name__ == '__main__':
param = [
('sqGOi',),
('848580',),
('01001110011001',),
('ZhWXUKmeiI',),
('0917296541285',),
('01101001111100',),
('tjP kR',),
('999907',),
('011100',),
('qJPHNSJOUj',)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) | def f_gold(s):
n = len(s)
sub_count = n * (n + 1) // 2
arr = [0] * sub_count
index = 0
for i in range(n):
for j in range(1, n - i + 1):
arr[index] = s[i:i + j]
index += 1
arr.sort()
res = ''
for i in range(sub_count):
res += arr[i]
return res
if __name__ == '__main__':
param = [('sqGOi',), ('848580',), ('01001110011001',), ('ZhWXUKmeiI',), ('0917296541285',), ('01101001111100',), ('tjP kR',), ('999907',), ('011100',), ('qJPHNSJOUj',)]
n_success = 0
for (i, parameters_set) in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success += 1
print('#Results: %i, %i' % (n_success, len(param))) |
morse_translated_to_english = {
".-": "A",
"-...": "B",
"-.-.": "C",
"-..": "D",
".": "E",
"..-.": "F",
"--.": "G",
"....": "H",
"..": "I",
".---": "J",
"-.-": "K",
".-..": "L",
"--": "M",
"-.": "N",
"---": "O",
".--.": "P",
"--.-": "Q",
".-.": "R",
"...": "S",
"-": "T",
"..-": "U",
"...-": "V",
".--": "W",
"-..-": "X",
"-.--": "Y",
"--..": "Z",
"...---...": "SOS",
".----": "1",
"..---": "2",
"...--": "3",
"....-": "4",
".....": "5",
"-....": "6",
"--...": "7",
"---..": "8",
"----.": "9",
"-----": "0",
".-.-.-": ".",
"--..--": ",",
"..--..": "?",
".----.": "'",
"-.-.--": "!",
"-..-.": "/",
"-.--.": "(",
"-.--.-": ")",
".-...": "&",
"---...": ":",
"-.-.-.": ";",
"-...-": "=",
".-.-.": "+",
"-....-": "-",
"..--.-": "_",
".-..-.": '"',
"...-..-": "$",
".--.-.": "@",
}
english_translated_to_morse = dict()
for key, value in morse_translated_to_english.items():
english_translated_to_morse[value] = key
def morse_code_to_english(incoming_morse_code):
output = ""
word = ""
morse_code_list = incoming_morse_code.split(" ")
i = 0
for code in morse_code_list:
i += 1
if code != "" and len(morse_code_list) != i:
word = word + morse_translated_to_english.get(code, code)
elif len(morse_code_list) == i:
word = word + morse_translated_to_english.get(code, code)
output = output + " " + word
else:
output = f'{output} {word}'
word = ""
output = output.strip()
output = output.replace(" ", " ")
return output
def english_to_morse_code(incoming_english):
output = ""
letter = ""
english_list = list(incoming_english.upper())
i = 0
for letters in english_list:
i += 1
if letters != "" and len(english_list) != i:
letter = letter + " " + english_translated_to_morse.get(letters, letters)
elif len(english_list) == i:
letter = letter + " " + english_translated_to_morse.get(letters, letters)
output = output + " " + letter
else:
output = f'{output} {letter}'
output = output.strip()
output = output.replace(" ", " ")
return output
| morse_translated_to_english = {'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z', '...---...': 'SOS', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0', '.-.-.-': '.', '--..--': ',', '..--..': '?', '.----.': "'", '-.-.--': '!', '-..-.': '/', '-.--.': '(', '-.--.-': ')', '.-...': '&', '---...': ':', '-.-.-.': ';', '-...-': '=', '.-.-.': '+', '-....-': '-', '..--.-': '_', '.-..-.': '"', '...-..-': '$', '.--.-.': '@'}
english_translated_to_morse = dict()
for (key, value) in morse_translated_to_english.items():
english_translated_to_morse[value] = key
def morse_code_to_english(incoming_morse_code):
output = ''
word = ''
morse_code_list = incoming_morse_code.split(' ')
i = 0
for code in morse_code_list:
i += 1
if code != '' and len(morse_code_list) != i:
word = word + morse_translated_to_english.get(code, code)
elif len(morse_code_list) == i:
word = word + morse_translated_to_english.get(code, code)
output = output + ' ' + word
else:
output = f'{output} {word}'
word = ''
output = output.strip()
output = output.replace(' ', ' ')
return output
def english_to_morse_code(incoming_english):
output = ''
letter = ''
english_list = list(incoming_english.upper())
i = 0
for letters in english_list:
i += 1
if letters != '' and len(english_list) != i:
letter = letter + ' ' + english_translated_to_morse.get(letters, letters)
elif len(english_list) == i:
letter = letter + ' ' + english_translated_to_morse.get(letters, letters)
output = output + ' ' + letter
else:
output = f'{output} {letter}'
output = output.strip()
output = output.replace(' ', ' ')
return output |
#
# PySNMP MIB module Wellfleet-NAME-TABLE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NAME-TABLE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:41:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
IpAddress, iso, Integer32, TimeTicks, Counter32, ObjectIdentity, MibIdentifier, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ModuleIdentity, Unsigned32, Counter64, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "Integer32", "TimeTicks", "Counter32", "ObjectIdentity", "MibIdentifier", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ModuleIdentity", "Unsigned32", "Counter64", "Gauge32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
wfName, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfName")
wfNameEntry = MibIdentifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1))
wfNameDelete = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wfNameDelete.setStatus('mandatory')
if mibBuilder.loadTexts: wfNameDelete.setDescription('Create or Delete the Object Base Record')
wfNameName = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: wfNameName.setStatus('mandatory')
if mibBuilder.loadTexts: wfNameName.setDescription('The BCC name of an object')
mibBuilder.exportSymbols("Wellfleet-NAME-TABLE-MIB", wfNameEntry=wfNameEntry, wfNameName=wfNameName, wfNameDelete=wfNameDelete)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsUnion')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(ip_address, iso, integer32, time_ticks, counter32, object_identity, mib_identifier, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, module_identity, unsigned32, counter64, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'iso', 'Integer32', 'TimeTicks', 'Counter32', 'ObjectIdentity', 'MibIdentifier', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ModuleIdentity', 'Unsigned32', 'Counter64', 'Gauge32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
(wf_name,) = mibBuilder.importSymbols('Wellfleet-COMMON-MIB', 'wfName')
wf_name_entry = mib_identifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1))
wf_name_delete = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('created', 1), ('deleted', 2))).clone('created')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wfNameDelete.setStatus('mandatory')
if mibBuilder.loadTexts:
wfNameDelete.setDescription('Create or Delete the Object Base Record')
wf_name_name = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
wfNameName.setStatus('mandatory')
if mibBuilder.loadTexts:
wfNameName.setDescription('The BCC name of an object')
mibBuilder.exportSymbols('Wellfleet-NAME-TABLE-MIB', wfNameEntry=wfNameEntry, wfNameName=wfNameName, wfNameDelete=wfNameDelete) |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
__all__ = ["ModuleConfigs"]
class ModuleConfigs(object):
"""
This class maps to "/configurations" and "/configurationAttributes in command.json which includes configuration information of a service
"""
def __init__(self, configs, configAttributes):
self.__module_configs = configs
self.__module_config_attributes = configAttributes
def get_raw_config_dict(self):
"""
Sometimes the caller needs to access to module_configs directly
:return: config dict
"""
return self.__module_configs
def get_all_attributes(self, module_name, config_type):
"""
Retrieve attributes from /configurationAttributes/config_type
:param module_name:
:param config_type:
:return:
"""
if config_type not in self.__module_config_attributes:
return {}
try:
return self.__module_config_attributes[config_type]
except:
return {}
def get_all_properties(self, module_name, config_type):
if config_type not in self.__module_configs:
return {}
try:
return self.__module_configs[config_type]
except:
return {}
def get_properties(self, module_name, config_type, property_names, default=None):
properties = {}
try:
for property_name in property_names:
properties[property_name] = self.get_property_value(module_name, config_type, property_name, default)
except:
return {}
return properties
def get_property_value(self, module_name, config_type, property_name, default=None):
if config_type not in self.__module_configs or property_name not in self.__module_configs[config_type]:
return default
try:
value = self.__module_configs[config_type][property_name]
if value == None:
value = default
return value
except:
return default | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
__all__ = ['ModuleConfigs']
class Moduleconfigs(object):
"""
This class maps to "/configurations" and "/configurationAttributes in command.json which includes configuration information of a service
"""
def __init__(self, configs, configAttributes):
self.__module_configs = configs
self.__module_config_attributes = configAttributes
def get_raw_config_dict(self):
"""
Sometimes the caller needs to access to module_configs directly
:return: config dict
"""
return self.__module_configs
def get_all_attributes(self, module_name, config_type):
"""
Retrieve attributes from /configurationAttributes/config_type
:param module_name:
:param config_type:
:return:
"""
if config_type not in self.__module_config_attributes:
return {}
try:
return self.__module_config_attributes[config_type]
except:
return {}
def get_all_properties(self, module_name, config_type):
if config_type not in self.__module_configs:
return {}
try:
return self.__module_configs[config_type]
except:
return {}
def get_properties(self, module_name, config_type, property_names, default=None):
properties = {}
try:
for property_name in property_names:
properties[property_name] = self.get_property_value(module_name, config_type, property_name, default)
except:
return {}
return properties
def get_property_value(self, module_name, config_type, property_name, default=None):
if config_type not in self.__module_configs or property_name not in self.__module_configs[config_type]:
return default
try:
value = self.__module_configs[config_type][property_name]
if value == None:
value = default
return value
except:
return default |
""" Parking Cars in a List """
# create a list of cars
row = ['Ford','Audi','BMW','Lexus']
# park my Mercedes at the end of the row
row.append('Mercedes')
print(row)
print(row[4])
# swap the BMW at index 2 for a Jeep
row[2] = 'Jeep'
print(row)
# park a Honda at the end of the row
row.append('Honda')
print(row)
print(row[4])
# park a Kia at the front of the row
row.insert(0,'Kia')
print(row)
print(row[4])
# find my Mercedes and leave the list
print(row.index('Mercedes'))
print(row.pop(5))
print(row)
# find and remove the Lexus
row.remove('Lexus')
print(row)
| """ Parking Cars in a List """
row = ['Ford', 'Audi', 'BMW', 'Lexus']
row.append('Mercedes')
print(row)
print(row[4])
row[2] = 'Jeep'
print(row)
row.append('Honda')
print(row)
print(row[4])
row.insert(0, 'Kia')
print(row)
print(row[4])
print(row.index('Mercedes'))
print(row.pop(5))
print(row)
row.remove('Lexus')
print(row) |
#!/usr/bin/env python
#### provide two configuration dictionaries: global_setting and feature_set ####
###This is basic configuration
global_setting=dict(
max_len = 256, # max length for the dataset
)
feature_set=dict(
ccmpred=dict(
suffix = "ccmpred",
length = 1,
parser_name = "ccmpred_parser_2d",
type = "2d",
skip = False,
),
# secondary structure
ss2=dict(
suffix = "ss2",
length = 3,
parser_name = "ss2_parser_1d",
type = "1d",
skip = False,
),
# whether is on surface
solv=dict(
suffix = "solv",
length = 1,
parser_name = "solv_parser_1d",
type = "1d",
skip = False,
),
# colstats
colstats=dict(
suffix = "colstats",
length = 22,
parser_name = "colstats_parser_1d",
type = "1d",
skip = False,
),
#pairwise conatct features
pairstats=dict(
suffix = "pairstats",
length = 3,
parser_name = "pairstats_parser_2d",
type = "2d",
skip = False,
),
# EVFold output
evfold=dict(
suffix = "evfold",
length = 1,
parser_name = "evfold_parser_2d",
type = "2d",
skip = False,
),
# NEFF Count
neff=dict(
suffix = "hhmake",
length = 1,
parser_name = "neff_parser_1d",
type = "1d",
skip = False,
),
# STD-DEV of CCMPRED output
ccmpred_std=dict(
suffix = "ccmpred",
length = 1,
parser_name = "ccmpred_std_parser_1d",
type = "1d",
skip = False,
),
# STD_DEV of EVfold output
evfold_std=dict(
suffix = "evfold",
length = 1,
parser_name = "evfold_std_parser_1d",
type = "1d",
skip = False,
),
)
| global_setting = dict(max_len=256)
feature_set = dict(ccmpred=dict(suffix='ccmpred', length=1, parser_name='ccmpred_parser_2d', type='2d', skip=False), ss2=dict(suffix='ss2', length=3, parser_name='ss2_parser_1d', type='1d', skip=False), solv=dict(suffix='solv', length=1, parser_name='solv_parser_1d', type='1d', skip=False), colstats=dict(suffix='colstats', length=22, parser_name='colstats_parser_1d', type='1d', skip=False), pairstats=dict(suffix='pairstats', length=3, parser_name='pairstats_parser_2d', type='2d', skip=False), evfold=dict(suffix='evfold', length=1, parser_name='evfold_parser_2d', type='2d', skip=False), neff=dict(suffix='hhmake', length=1, parser_name='neff_parser_1d', type='1d', skip=False), ccmpred_std=dict(suffix='ccmpred', length=1, parser_name='ccmpred_std_parser_1d', type='1d', skip=False), evfold_std=dict(suffix='evfold', length=1, parser_name='evfold_std_parser_1d', type='1d', skip=False)) |
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if not nums:
return []
res = []
nums.sort()
for i, num in enumerate(nums):
if i > 0 and num == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
total = num + nums[left] + nums[right]
if total > 0:
right -= 1
elif total < 0:
left += 1
else:
res.append([num, nums[left], nums[right]])
left += 1
while nums[left] == nums[left - 1] and left < right:
left += 1
return res
obj = Solution()
print(obj.threeSum([-1,0,1,2,-1,-4]))
print(obj.threeSum([]))
print(obj.threeSum([-2,1,1,7,1,-8]))
print(obj.threeSum([0,0,0,0,0]))
| class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
if not nums:
return []
res = []
nums.sort()
for (i, num) in enumerate(nums):
if i > 0 and num == nums[i - 1]:
continue
(left, right) = (i + 1, len(nums) - 1)
while left < right:
total = num + nums[left] + nums[right]
if total > 0:
right -= 1
elif total < 0:
left += 1
else:
res.append([num, nums[left], nums[right]])
left += 1
while nums[left] == nums[left - 1] and left < right:
left += 1
return res
obj = solution()
print(obj.threeSum([-1, 0, 1, 2, -1, -4]))
print(obj.threeSum([]))
print(obj.threeSum([-2, 1, 1, 7, 1, -8]))
print(obj.threeSum([0, 0, 0, 0, 0])) |
#!/usr/bin/python3
with open('03_input', 'r') as f:
lines = f.readlines()
bits_list = [list(n.strip()) for n in lines]
bit_len = len(bits_list[0])
zeros = [0 for i in range(bit_len)]
ones = [0 for i in range(bit_len)]
for bits in bits_list:
for i, b in enumerate(bits):
if b == '0':
zeros[i] += 1
elif b == '1':
ones[i] += 1
most = ''
least = ''
for i in range(bit_len):
if zeros[i] > ones[i]:
most += '0'
least += '1'
else:
most += '1'
least += '0'
int_most = int(most, 2)
int_least = int(least, 2)
val = int_most * int_least
print(val)
| with open('03_input', 'r') as f:
lines = f.readlines()
bits_list = [list(n.strip()) for n in lines]
bit_len = len(bits_list[0])
zeros = [0 for i in range(bit_len)]
ones = [0 for i in range(bit_len)]
for bits in bits_list:
for (i, b) in enumerate(bits):
if b == '0':
zeros[i] += 1
elif b == '1':
ones[i] += 1
most = ''
least = ''
for i in range(bit_len):
if zeros[i] > ones[i]:
most += '0'
least += '1'
else:
most += '1'
least += '0'
int_most = int(most, 2)
int_least = int(least, 2)
val = int_most * int_least
print(val) |
# WHICH NUMBER IS NOT LIKE THE OTHERS EDABIT SOLUTION:
# creating a function to solve the problem.
def unique(lst):
# creating a for-loop to iterate for the elements in the list.
for i in lst:
# creating a nested if-statement to check for a distinct element.
if lst.count(i) == 1:
# returning the element if the condition is met.
return i
| def unique(lst):
for i in lst:
if lst.count(i) == 1:
return i |
# Complete the function below.
# Function to check ipv4
# @Return boolean
def validateIPV4(ipAddress):
isIPv4 = True
# ipv4 address is composed by octet
for octet in ipAddress:
try:
# pretty straigthforward, convert to int
# ensure per-octet value falls between [0,255]
tmp = int(octet)
if tmp<0 or tmp>255:
isIPv4 = False
break
except:
isIPv4 = False
break
return "IPv4" if isIPv4 else "Neither"
# Function to check ipv6
# @Return boolean
def validateIPV6(ipAddress):
isIPv6 = True
# ipv6 address is composed by hextet
for hextet in ipAddress:
try:
# straigthforward, convert hexa to int
# ensure per-hextet value falls between [0,65535]
tmp = int(str(hextet),16)
if (tmp<0) or tmp>65535:
isIPv6 = False
break
except:
isIPv6 = False
break
return "IPv6" if isIPv6 else "Neither"
# Function to check IP address
def checkIP(ip):
# list to store final result
result = []
for ipAddress in ip:
# ipv4 is composed by 4 blocks of octet and separated by dot (.)
if len(ipAddress.split(".")) == 4:
ipCategory = validateIPV4(ipAddress.split("."))
# ipv6 is composed by 8 blocks of hextet and separated by colon (:)
elif len(ipAddress.split(":")) == 8:
ipCategory = validateIPV6(ipAddress.split(":"))
else:
ipCategory = "Neither"
result.append(ipCategory)
return result
| def validate_ipv4(ipAddress):
is_i_pv4 = True
for octet in ipAddress:
try:
tmp = int(octet)
if tmp < 0 or tmp > 255:
is_i_pv4 = False
break
except:
is_i_pv4 = False
break
return 'IPv4' if isIPv4 else 'Neither'
def validate_ipv6(ipAddress):
is_i_pv6 = True
for hextet in ipAddress:
try:
tmp = int(str(hextet), 16)
if tmp < 0 or tmp > 65535:
is_i_pv6 = False
break
except:
is_i_pv6 = False
break
return 'IPv6' if isIPv6 else 'Neither'
def check_ip(ip):
result = []
for ip_address in ip:
if len(ipAddress.split('.')) == 4:
ip_category = validate_ipv4(ipAddress.split('.'))
elif len(ipAddress.split(':')) == 8:
ip_category = validate_ipv6(ipAddress.split(':'))
else:
ip_category = 'Neither'
result.append(ipCategory)
return result |
"""
Contains the Team object used represent NBA teams
"""
class Team:
"""
Object representing NBA teams containing:
team name -
three letter code -
unique team id -
nickname.
"""
def __init__(self, name, tricode, teamID, nickname):
self.name = name
self.tricode = tricode
self.id = teamID
self.nickname = nickname
def get_name(self):
return self.name
def get_tricode(self):
return self.tricode
def get_id(self):
return self.id
def get_nickname(self):
return self.nickname
def __str__(self):
return self.name + ", " + self.tricode
| """
Contains the Team object used represent NBA teams
"""
class Team:
"""
Object representing NBA teams containing:
team name -
three letter code -
unique team id -
nickname.
"""
def __init__(self, name, tricode, teamID, nickname):
self.name = name
self.tricode = tricode
self.id = teamID
self.nickname = nickname
def get_name(self):
return self.name
def get_tricode(self):
return self.tricode
def get_id(self):
return self.id
def get_nickname(self):
return self.nickname
def __str__(self):
return self.name + ', ' + self.tricode |
def kph(ms):
return ms * 3.6
def mph(ms):
return ms * 2.2369362920544
def knots(ms):
return ms * 1.9438444924574
def minPkm(ms): # minutes per kilometre
return ms * (100 / 6)
def c(ms): # speed of light
return ms / 299792458
def speedOfLight(ms):
return c(ms)
def mach(ms):
return ms / 340
def speedOfSound(ms):
return mach(ms) | def kph(ms):
return ms * 3.6
def mph(ms):
return ms * 2.2369362920544
def knots(ms):
return ms * 1.9438444924574
def min_pkm(ms):
return ms * (100 / 6)
def c(ms):
return ms / 299792458
def speed_of_light(ms):
return c(ms)
def mach(ms):
return ms / 340
def speed_of_sound(ms):
return mach(ms) |
# -*- encoding: utf-8 -*-
#
# Copyright 2015-2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
def test_create_user(runner, test_user):
assert test_user["name"] == "foo"
assert test_user["fullname"] == "Foo Bar"
assert test_user["email"] == "foo@example.org"
def test_create_admin(runner):
user = runner.invoke(
[
"user-create",
"--name",
"foo",
"--email",
"foo@example.org",
"--password",
"pass"
]
)["user"]
assert user["name"] == "foo"
assert user["fullname"] == "foo"
assert user["email"] == "foo@example.org"
def test_create_super_admin(runner):
user = runner.invoke(
[
"user-create",
"--name",
"foo",
"--email",
"foo@example.org",
"--password",
"pass"
]
)["user"]
assert user["name"] == "foo"
assert user["fullname"] == "foo"
assert user["email"] == "foo@example.org"
def test_create_inactive(runner):
user = runner.invoke(
[
"user-create",
"--name",
"foo",
"--password",
"pass",
"--email",
"foo@example.org",
"--no-active",
]
)["user"]
assert user["state"] == "inactive"
def test_list(runner):
users_cnt = len(runner.invoke(["user-list"])["users"])
runner.invoke(
[
"user-create",
"--name",
"bar",
"--email",
"bar@example.org",
"--password",
"pass",
]
)
new_users_cnt = len(runner.invoke(["user-list"])["users"])
assert new_users_cnt == users_cnt + 1
def test_update(runner, test_user):
runner.invoke(
[
"user-update",
test_user["id"],
"--etag",
test_user["etag"],
"--name",
"bar",
"--email",
"bar@example.org",
"--fullname",
"Barry White",
]
)
user = runner.invoke(["user-show", test_user["id"]])["user"]
assert user["name"] == "bar"
assert user["fullname"] == "Barry White"
assert user["email"] == "bar@example.org"
def test_update_active(runner, test_user, team_id):
assert test_user["state"] == "active"
result = runner.invoke(
["user-update", test_user["id"], "--etag", test_user["etag"], "--no-active"]
)
assert result["user"]["id"] == test_user["id"]
assert result["user"]["state"] == "inactive"
result = runner.invoke(
[
"user-update",
test_user["id"],
"--etag",
result["user"]["etag"],
"--name",
"foobar",
]
)
assert result["user"]["id"] == test_user["id"]
assert result["user"]["state"] == "inactive"
assert result["user"]["name"] == "foobar"
result = runner.invoke(
["user-update", test_user["id"], "--etag", result["user"]["etag"], "--active"]
)
assert result["user"]["state"] == "active"
def test_delete(runner, test_user, team_id):
result = runner.invoke_raw(
["user-delete", test_user["id"], "--etag", test_user["etag"]]
)
assert result.status_code == 204
def test_show(runner, test_user, team_id):
user = runner.invoke(["user-show", test_user["id"]])["user"]
assert user["name"] == test_user["name"]
def test_where_on_list(runner, test_user, team_id):
runner.invoke(
[
"user-create",
"--name",
"foo2",
"--email",
"foo2@example.org",
"--password",
"pass",
]
)
runner.invoke(
[
"user-create",
"--name",
"foo3",
"--email",
"foo3@example.org",
"--password",
"pass",
]
)
users_cnt = len(runner.invoke(["user-list"])["users"])
assert runner.invoke(["user-list"])["_meta"]["count"] == users_cnt
assert runner.invoke(["user-list", "--where", "name:foo"])["_meta"]["count"] == 1
| def test_create_user(runner, test_user):
assert test_user['name'] == 'foo'
assert test_user['fullname'] == 'Foo Bar'
assert test_user['email'] == 'foo@example.org'
def test_create_admin(runner):
user = runner.invoke(['user-create', '--name', 'foo', '--email', 'foo@example.org', '--password', 'pass'])['user']
assert user['name'] == 'foo'
assert user['fullname'] == 'foo'
assert user['email'] == 'foo@example.org'
def test_create_super_admin(runner):
user = runner.invoke(['user-create', '--name', 'foo', '--email', 'foo@example.org', '--password', 'pass'])['user']
assert user['name'] == 'foo'
assert user['fullname'] == 'foo'
assert user['email'] == 'foo@example.org'
def test_create_inactive(runner):
user = runner.invoke(['user-create', '--name', 'foo', '--password', 'pass', '--email', 'foo@example.org', '--no-active'])['user']
assert user['state'] == 'inactive'
def test_list(runner):
users_cnt = len(runner.invoke(['user-list'])['users'])
runner.invoke(['user-create', '--name', 'bar', '--email', 'bar@example.org', '--password', 'pass'])
new_users_cnt = len(runner.invoke(['user-list'])['users'])
assert new_users_cnt == users_cnt + 1
def test_update(runner, test_user):
runner.invoke(['user-update', test_user['id'], '--etag', test_user['etag'], '--name', 'bar', '--email', 'bar@example.org', '--fullname', 'Barry White'])
user = runner.invoke(['user-show', test_user['id']])['user']
assert user['name'] == 'bar'
assert user['fullname'] == 'Barry White'
assert user['email'] == 'bar@example.org'
def test_update_active(runner, test_user, team_id):
assert test_user['state'] == 'active'
result = runner.invoke(['user-update', test_user['id'], '--etag', test_user['etag'], '--no-active'])
assert result['user']['id'] == test_user['id']
assert result['user']['state'] == 'inactive'
result = runner.invoke(['user-update', test_user['id'], '--etag', result['user']['etag'], '--name', 'foobar'])
assert result['user']['id'] == test_user['id']
assert result['user']['state'] == 'inactive'
assert result['user']['name'] == 'foobar'
result = runner.invoke(['user-update', test_user['id'], '--etag', result['user']['etag'], '--active'])
assert result['user']['state'] == 'active'
def test_delete(runner, test_user, team_id):
result = runner.invoke_raw(['user-delete', test_user['id'], '--etag', test_user['etag']])
assert result.status_code == 204
def test_show(runner, test_user, team_id):
user = runner.invoke(['user-show', test_user['id']])['user']
assert user['name'] == test_user['name']
def test_where_on_list(runner, test_user, team_id):
runner.invoke(['user-create', '--name', 'foo2', '--email', 'foo2@example.org', '--password', 'pass'])
runner.invoke(['user-create', '--name', 'foo3', '--email', 'foo3@example.org', '--password', 'pass'])
users_cnt = len(runner.invoke(['user-list'])['users'])
assert runner.invoke(['user-list'])['_meta']['count'] == users_cnt
assert runner.invoke(['user-list', '--where', 'name:foo'])['_meta']['count'] == 1 |
# -*- coding: utf-8 -*-
even = 0
for i in range(5):
A = float(input())
if (A % 2) == 0:
even +=1
print("%i valores pares"%even) | even = 0
for i in range(5):
a = float(input())
if A % 2 == 0:
even += 1
print('%i valores pares' % even) |
class user():
def __init__(self,id,passwd):
self.id = id
self.passwd = passwd
def get_id(self):
pass
| class User:
def __init__(self, id, passwd):
self.id = id
self.passwd = passwd
def get_id(self):
pass |
def factorial(no):
if no == 1:
return no
else:
return no * factorial(no - 1)
"""
# Factorial using for loop Without Recursive
ans = 1
for i in range(1, no+1):
ans = ans * i
print(ans)
"""
def main():
no = int(input("Enter number : "))
# ret = no+1
print(factorial(no))
if __name__ == '__main__':
main()
| def factorial(no):
if no == 1:
return no
else:
return no * factorial(no - 1)
'\n# Factorial using for loop Without Recursive\nans = 1\nfor i in range(1, no+1):\n ans = ans * i\nprint(ans)\n'
def main():
no = int(input('Enter number : '))
print(factorial(no))
if __name__ == '__main__':
main() |
## using hashing ..
def duplicates_hash(arr, n):
s = dict()
for i in range(n):
if arr[i] in s:
s[arr[i]] = s[arr[i]]+1
else:
s[arr[i]] = 1
res = []
for i in s:
if s[i] > 1:
res.append(i)
if len(res)>0:
return res
else:
return -1
## using given array as hashmap because in question it is given that range of array -->[1,length of array]
def duplicates_arr(arr, n):
res = []
for i in range(n):
arr[arr[i]%n] = arr[arr[i]%n] + n
for i in range(n):
if (arr[i]//n>1):
res.append(i)
return res
## Driver code...!!!!1
if __name__ == "__main__":
n = int(input())
arr1 = list(map(int,input().split()))
print('using array',duplicates_arr(arr1.copy(),n)) ## pass copy of main input array..
print('using hashmap',duplicates_hash(arr1,n))
'''
sample input
5
2 3 1 2 3
'''
| def duplicates_hash(arr, n):
s = dict()
for i in range(n):
if arr[i] in s:
s[arr[i]] = s[arr[i]] + 1
else:
s[arr[i]] = 1
res = []
for i in s:
if s[i] > 1:
res.append(i)
if len(res) > 0:
return res
else:
return -1
def duplicates_arr(arr, n):
res = []
for i in range(n):
arr[arr[i] % n] = arr[arr[i] % n] + n
for i in range(n):
if arr[i] // n > 1:
res.append(i)
return res
if __name__ == '__main__':
n = int(input())
arr1 = list(map(int, input().split()))
print('using array', duplicates_arr(arr1.copy(), n))
print('using hashmap', duplicates_hash(arr1, n))
'\nsample input\n5\n2 3 1 2 3\n' |
lastA = 116
lastB = 299
judgeCounter = 0
for i in range(40000000):
# Generation cycle
aRes = (lastA * 16807) % 2147483647
bRes = (lastB * 48271) % 2147483647
# Judging time
if (aRes % 65536 == bRes % 65536):
print("Match found! With ", aRes, " and ", bRes, sep="")
judgeCounter += 1
# Setup for next round
lastA = aRes
lastB = bRes
print("Final judge score, part 1:", judgeCounter)
## Part 2
lastA = 116
lastB = 299
judgeCounter = 0
for i in range(5000000):
# Generation cycle
aRes = (lastA * 16807) % 2147483647
while (aRes % 4 != 0):
aRes = (aRes * 16807) % 2147483647
bRes = (lastB * 48271) % 2147483647
while (bRes % 8 != 0):
bRes = (bRes * 48271) % 2147483647
# Judging time
if (aRes % 65536 == bRes % 65536):
print(i, ": Match found!", sep="")
judgeCounter += 1
# Setup for next round
lastA = aRes
lastB = bRes
print("Final judge score, part 2:", judgeCounter)
| last_a = 116
last_b = 299
judge_counter = 0
for i in range(40000000):
a_res = lastA * 16807 % 2147483647
b_res = lastB * 48271 % 2147483647
if aRes % 65536 == bRes % 65536:
print('Match found! With ', aRes, ' and ', bRes, sep='')
judge_counter += 1
last_a = aRes
last_b = bRes
print('Final judge score, part 1:', judgeCounter)
last_a = 116
last_b = 299
judge_counter = 0
for i in range(5000000):
a_res = lastA * 16807 % 2147483647
while aRes % 4 != 0:
a_res = aRes * 16807 % 2147483647
b_res = lastB * 48271 % 2147483647
while bRes % 8 != 0:
b_res = bRes * 48271 % 2147483647
if aRes % 65536 == bRes % 65536:
print(i, ': Match found!', sep='')
judge_counter += 1
last_a = aRes
last_b = bRes
print('Final judge score, part 2:', judgeCounter) |
"""In this little assignment you are given a string of space separated numbers,
and have to return the highest and lowest number.
=== Example: ===
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"
=== Notes: ===
All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space,
and highest number is first.
"""
def high_and_low(numbers: str) -> str:
all_nums = tuple(int(num) for num in numbers.split())
low = min(all_nums)
high = max(all_nums)
return f"{high} {low}"
| """In this little assignment you are given a string of space separated numbers,
and have to return the highest and lowest number.
=== Example: ===
high_and_low("1 2 3 4 5") # return "5 1"
high_and_low("1 2 -3 4 5") # return "5 -3"
high_and_low("1 9 3 4 -5") # return "9 -5"
=== Notes: ===
All numbers are valid Int32, no need to validate them.
There will always be at least one number in the input string.
Output string must be two numbers separated by a single space,
and highest number is first.
"""
def high_and_low(numbers: str) -> str:
all_nums = tuple((int(num) for num in numbers.split()))
low = min(all_nums)
high = max(all_nums)
return f'{high} {low}' |
#
# PySNMP MIB module ZYXEL-DIFFSERV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-DIFFSERV-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:49:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection")
dot1dBasePort, = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePort")
EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
TimeTicks, Counter64, MibIdentifier, Bits, ObjectIdentity, IpAddress, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Unsigned32, Gauge32, Integer32, NotificationType, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Counter64", "MibIdentifier", "Bits", "ObjectIdentity", "IpAddress", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Unsigned32", "Gauge32", "Integer32", "NotificationType", "Counter32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt")
zyxelDiffserv = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22))
if mibBuilder.loadTexts: zyxelDiffserv.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts: zyxelDiffserv.setOrganization('Enterprise Solution ZyXEL')
if mibBuilder.loadTexts: zyxelDiffserv.setContactInfo('')
if mibBuilder.loadTexts: zyxelDiffserv.setDescription('The subtree for Differentiated services (Diffserv)')
zyxelDiffservSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1))
zyDiffservState = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 1), EnabledStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyDiffservState.setStatus('current')
if mibBuilder.loadTexts: zyDiffservState.setDescription('Enable/Disable DiffServ on the switch. DiffServ is a class of service (CoS) model that marks packets so that they receive specific per-hop treatment at DiffServ-compliant network devices along the route based on the application types and traffic flow.')
zyxelDiffservMapTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2), )
if mibBuilder.loadTexts: zyxelDiffservMapTable.setStatus('current')
if mibBuilder.loadTexts: zyxelDiffservMapTable.setDescription('The table contains Diffserv map configuration. ')
zyxelDiffservMapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1), ).setIndexNames((0, "ZYXEL-DIFFSERV-MIB", "zyDiffservMapDscp"))
if mibBuilder.loadTexts: zyxelDiffservMapEntry.setStatus('current')
if mibBuilder.loadTexts: zyxelDiffservMapEntry.setDescription('An entry contains Diffserv map configuration.')
zyDiffservMapDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 1), Integer32())
if mibBuilder.loadTexts: zyDiffservMapDscp.setStatus('current')
if mibBuilder.loadTexts: zyDiffservMapDscp.setDescription('The DSCP classification identification number.')
zyDiffservMapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyDiffservMapPriority.setStatus('current')
if mibBuilder.loadTexts: zyDiffservMapPriority.setDescription('Set the IEEE 802.1p priority mapping.')
zyxelDiffservPortTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3), )
if mibBuilder.loadTexts: zyxelDiffservPortTable.setStatus('current')
if mibBuilder.loadTexts: zyxelDiffservPortTable.setDescription('The table contains Diffserv port configuration.')
zyxelDiffservPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1), ).setIndexNames((0, "BRIDGE-MIB", "dot1dBasePort"))
if mibBuilder.loadTexts: zyxelDiffservPortEntry.setStatus('current')
if mibBuilder.loadTexts: zyxelDiffservPortEntry.setDescription('An entry contains Diffserv port configuration.')
zyDiffservPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1, 1), EnabledStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zyDiffservPortState.setStatus('current')
if mibBuilder.loadTexts: zyDiffservPortState.setDescription('Enable/Disable DiffServ on the port.')
mibBuilder.exportSymbols("ZYXEL-DIFFSERV-MIB", zyDiffservState=zyDiffservState, zyxelDiffservMapTable=zyxelDiffservMapTable, zyxelDiffservPortTable=zyxelDiffservPortTable, zyxelDiffservSetup=zyxelDiffservSetup, zyDiffservPortState=zyDiffservPortState, zyxelDiffservPortEntry=zyxelDiffservPortEntry, PYSNMP_MODULE_ID=zyxelDiffserv, zyxelDiffserv=zyxelDiffserv, zyDiffservMapDscp=zyDiffservMapDscp, zyxelDiffservMapEntry=zyxelDiffservMapEntry, zyDiffservMapPriority=zyDiffservMapPriority)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection')
(dot1d_base_port,) = mibBuilder.importSymbols('BRIDGE-MIB', 'dot1dBasePort')
(enabled_status,) = mibBuilder.importSymbols('P-BRIDGE-MIB', 'EnabledStatus')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(time_ticks, counter64, mib_identifier, bits, object_identity, ip_address, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, unsigned32, gauge32, integer32, notification_type, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'Counter64', 'MibIdentifier', 'Bits', 'ObjectIdentity', 'IpAddress', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'Unsigned32', 'Gauge32', 'Integer32', 'NotificationType', 'Counter32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
(es_mgmt,) = mibBuilder.importSymbols('ZYXEL-ES-SMI', 'esMgmt')
zyxel_diffserv = module_identity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22))
if mibBuilder.loadTexts:
zyxelDiffserv.setLastUpdated('201207010000Z')
if mibBuilder.loadTexts:
zyxelDiffserv.setOrganization('Enterprise Solution ZyXEL')
if mibBuilder.loadTexts:
zyxelDiffserv.setContactInfo('')
if mibBuilder.loadTexts:
zyxelDiffserv.setDescription('The subtree for Differentiated services (Diffserv)')
zyxel_diffserv_setup = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1))
zy_diffserv_state = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 1), enabled_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyDiffservState.setStatus('current')
if mibBuilder.loadTexts:
zyDiffservState.setDescription('Enable/Disable DiffServ on the switch. DiffServ is a class of service (CoS) model that marks packets so that they receive specific per-hop treatment at DiffServ-compliant network devices along the route based on the application types and traffic flow.')
zyxel_diffserv_map_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2))
if mibBuilder.loadTexts:
zyxelDiffservMapTable.setStatus('current')
if mibBuilder.loadTexts:
zyxelDiffservMapTable.setDescription('The table contains Diffserv map configuration. ')
zyxel_diffserv_map_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1)).setIndexNames((0, 'ZYXEL-DIFFSERV-MIB', 'zyDiffservMapDscp'))
if mibBuilder.loadTexts:
zyxelDiffservMapEntry.setStatus('current')
if mibBuilder.loadTexts:
zyxelDiffservMapEntry.setDescription('An entry contains Diffserv map configuration.')
zy_diffserv_map_dscp = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 1), integer32())
if mibBuilder.loadTexts:
zyDiffservMapDscp.setStatus('current')
if mibBuilder.loadTexts:
zyDiffservMapDscp.setDescription('The DSCP classification identification number.')
zy_diffserv_map_priority = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 2), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyDiffservMapPriority.setStatus('current')
if mibBuilder.loadTexts:
zyDiffservMapPriority.setDescription('Set the IEEE 802.1p priority mapping.')
zyxel_diffserv_port_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3))
if mibBuilder.loadTexts:
zyxelDiffservPortTable.setStatus('current')
if mibBuilder.loadTexts:
zyxelDiffservPortTable.setDescription('The table contains Diffserv port configuration.')
zyxel_diffserv_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1)).setIndexNames((0, 'BRIDGE-MIB', 'dot1dBasePort'))
if mibBuilder.loadTexts:
zyxelDiffservPortEntry.setStatus('current')
if mibBuilder.loadTexts:
zyxelDiffservPortEntry.setDescription('An entry contains Diffserv port configuration.')
zy_diffserv_port_state = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1, 1), enabled_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
zyDiffservPortState.setStatus('current')
if mibBuilder.loadTexts:
zyDiffservPortState.setDescription('Enable/Disable DiffServ on the port.')
mibBuilder.exportSymbols('ZYXEL-DIFFSERV-MIB', zyDiffservState=zyDiffservState, zyxelDiffservMapTable=zyxelDiffservMapTable, zyxelDiffservPortTable=zyxelDiffservPortTable, zyxelDiffservSetup=zyxelDiffservSetup, zyDiffservPortState=zyDiffservPortState, zyxelDiffservPortEntry=zyxelDiffservPortEntry, PYSNMP_MODULE_ID=zyxelDiffserv, zyxelDiffserv=zyxelDiffserv, zyDiffservMapDscp=zyDiffservMapDscp, zyxelDiffservMapEntry=zyxelDiffservMapEntry, zyDiffservMapPriority=zyDiffservMapPriority) |
PLUGIN_URL_NAME_PREFIX = 'djangocms_alias'
CREATE_ALIAS_URL_NAME = '{}_create'.format(PLUGIN_URL_NAME_PREFIX)
DELETE_ALIAS_URL_NAME = '{}_delete'.format(PLUGIN_URL_NAME_PREFIX)
DETACH_ALIAS_PLUGIN_URL_NAME = '{}_detach_plugin'.format(PLUGIN_URL_NAME_PREFIX) # noqa: E501
LIST_ALIASES_URL_NAME = '{}_list'.format(PLUGIN_URL_NAME_PREFIX)
CATEGORY_LIST_URL_NAME = '{}_category_list'.format(PLUGIN_URL_NAME_PREFIX)
SET_ALIAS_POSITION_URL_NAME = '{}_set_alias_position'.format(PLUGIN_URL_NAME_PREFIX) # noqa: E501
SELECT2_ALIAS_URL_NAME = '{}_select2'.format(PLUGIN_URL_NAME_PREFIX)
USAGE_ALIAS_URL_NAME = '{}_alias_usage'.format(PLUGIN_URL_NAME_PREFIX)
| plugin_url_name_prefix = 'djangocms_alias'
create_alias_url_name = '{}_create'.format(PLUGIN_URL_NAME_PREFIX)
delete_alias_url_name = '{}_delete'.format(PLUGIN_URL_NAME_PREFIX)
detach_alias_plugin_url_name = '{}_detach_plugin'.format(PLUGIN_URL_NAME_PREFIX)
list_aliases_url_name = '{}_list'.format(PLUGIN_URL_NAME_PREFIX)
category_list_url_name = '{}_category_list'.format(PLUGIN_URL_NAME_PREFIX)
set_alias_position_url_name = '{}_set_alias_position'.format(PLUGIN_URL_NAME_PREFIX)
select2_alias_url_name = '{}_select2'.format(PLUGIN_URL_NAME_PREFIX)
usage_alias_url_name = '{}_alias_usage'.format(PLUGIN_URL_NAME_PREFIX) |
class Party:
def __init__(self):
self.party_people = []
self.party_people_counter = 0
party = Party()
people = input()
while people != 'End':
party.party_people.append(people)
party.party_people_counter += 1
people = input()
print(f'Going: {", ".join(party.party_people)}')
print(f'Total: {party.party_people_counter}')
| class Party:
def __init__(self):
self.party_people = []
self.party_people_counter = 0
party = party()
people = input()
while people != 'End':
party.party_people.append(people)
party.party_people_counter += 1
people = input()
print(f"Going: {', '.join(party.party_people)}")
print(f'Total: {party.party_people_counter}') |
class Solution:
def __init__(self):
self.count = 0
def waysToStep(self, n: int) -> int:
def dfs(n):
if n == 1:
self.count += 1
elif n == 2:
self.count += 2
elif n == 3:
self.count += 4
else:
dfs(n - 1)
dfs(n - 2)
dfs(n - 3)
dfs(n)
return self.count
def waysToStep(self, n: int) -> int:
if n < 3:
return n
elif n == 3:
return 4
dp0, dp1, dp2 = 1, 2, 4
for _ in range(4, n + 1):
dp0, dp1, dp2 = dp1, dp2, (dp0 + dp1 + dp2) % 1000000007
return dp2
| class Solution:
def __init__(self):
self.count = 0
def ways_to_step(self, n: int) -> int:
def dfs(n):
if n == 1:
self.count += 1
elif n == 2:
self.count += 2
elif n == 3:
self.count += 4
else:
dfs(n - 1)
dfs(n - 2)
dfs(n - 3)
dfs(n)
return self.count
def ways_to_step(self, n: int) -> int:
if n < 3:
return n
elif n == 3:
return 4
(dp0, dp1, dp2) = (1, 2, 4)
for _ in range(4, n + 1):
(dp0, dp1, dp2) = (dp1, dp2, (dp0 + dp1 + dp2) % 1000000007)
return dp2 |
# Determine whether a number is a perfect number, an Armstrong number or a palindrome.
def perfect_number(n):
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
return True
else:
return False
def armstrong(n):
sum = 0
temp = n
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if n == sum:
return True
else:
return False
def palindrome(n):
temp = n
rev = 0
while(n > 0):
dig = n % 10
rev = rev*10+dig
n = n//10
if(temp == rev):
return True
else:
return False
k = True
while k == True:
n = int(input("Enter a number: "))
if perfect_number(n) == True:
print(n, " is a Perfect number!")
elif armstrong(n) == True:
print(n, " is an Armstrong number!")
elif palindrome(n) == True:
print("The number is a palindrome!")
else:
print("The number is a Unknow!")
option = input('Do you want to try again.(y/n): ').lower()
if option == 'y':
continue
else:
k = False
| def perfect_number(n):
sum1 = 0
for i in range(1, n):
if n % i == 0:
sum1 = sum1 + i
if sum1 == n:
return True
else:
return False
def armstrong(n):
sum = 0
temp = n
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if n == sum:
return True
else:
return False
def palindrome(n):
temp = n
rev = 0
while n > 0:
dig = n % 10
rev = rev * 10 + dig
n = n // 10
if temp == rev:
return True
else:
return False
k = True
while k == True:
n = int(input('Enter a number: '))
if perfect_number(n) == True:
print(n, ' is a Perfect number!')
elif armstrong(n) == True:
print(n, ' is an Armstrong number!')
elif palindrome(n) == True:
print('The number is a palindrome!')
else:
print('The number is a Unknow!')
option = input('Do you want to try again.(y/n): ').lower()
if option == 'y':
continue
else:
k = False |
# Created by MechAviv
# [Kyrin] | [1090000]
# Nautilus : Navigation Room
sm.setSpeakerID(1090000)
sm.sendSayOkay("Welcome aboard the Nautilus. The ship isn't headed anywhere for a while. How about going out to the deck?") | sm.setSpeakerID(1090000)
sm.sendSayOkay("Welcome aboard the Nautilus. The ship isn't headed anywhere for a while. How about going out to the deck?") |
def deduplicate_list(list_with_dups):
return list(dict.fromkeys(list_with_dups))
def filter_list_by_set(original_list, filter_set):
return [elem for elem in original_list if elem not in filter_set]
def write_to_file(filename, text, message): # pragma: no cover
with open(filename, 'w') as f:
f.write(text)
print(message)
| def deduplicate_list(list_with_dups):
return list(dict.fromkeys(list_with_dups))
def filter_list_by_set(original_list, filter_set):
return [elem for elem in original_list if elem not in filter_set]
def write_to_file(filename, text, message):
with open(filename, 'w') as f:
f.write(text)
print(message) |
#
# PySNMP MIB module HM2-DNS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-DNS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:31:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint")
HmActionValue, HmEnabledStatus, hm2ConfigurationMibs = mibBuilder.importSymbols("HM2-TC-MIB", "HmActionValue", "HmEnabledStatus", "hm2ConfigurationMibs")
InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Gauge32, Unsigned32, ModuleIdentity, NotificationType, TimeTicks, Counter32, Integer32, Counter64, IpAddress, MibIdentifier, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Unsigned32", "ModuleIdentity", "NotificationType", "TimeTicks", "Counter32", "Integer32", "Counter64", "IpAddress", "MibIdentifier", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits")
DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus")
hm2DnsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90))
hm2DnsMib.setRevisions(('2011-06-17 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hm2DnsMib.setRevisionsDescriptions(('Initial version.',))
if mibBuilder.loadTexts: hm2DnsMib.setLastUpdated('201106170000Z')
if mibBuilder.loadTexts: hm2DnsMib.setOrganization('Hirschmann Automation and Control GmbH')
if mibBuilder.loadTexts: hm2DnsMib.setContactInfo('Postal: Stuttgarter Str. 45-51 72654 Neckartenzlingen Germany Phone: +49 7127 140 E-mail: hac.support@belden.com')
if mibBuilder.loadTexts: hm2DnsMib.setDescription('Hirschmann DNS MIB for DNS client, DNS client cache and DNS caching server. Copyright (C) 2011. All Rights Reserved.')
hm2DnsMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 0))
hm2DnsMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1))
hm2DnsMibSNMPExtensionGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 3))
hm2DnsClientGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1))
hm2DnsCacheGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2))
hm2DnsCachingServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3))
hm2DnsClientAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 1), HmEnabledStatus().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsClientAdminState.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientAdminState.setDescription('The operational status of DNS client. If disabled, no host name lookups will be done for names entered on the CLI and in the configuration of services e.g. NTP.')
hm2DnsClientConfigSource = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("user", 1), ("mgmt-dhcp", 2), ("provider", 3))).clone('mgmt-dhcp')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsClientConfigSource.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientConfigSource.setDescription('DNS client server source. If the value is set to user(1), the variables from hm2DnsClientServerCfgTable will be used. If the value is set to mgmt-dhcp(2), the DNS servers received by DHCP on the management interface will be used. If the value is set to provider(3), the DNS configuration will be taken from DHCP, PPP or PPPoE on the primary WAN link.')
hm2DnsClientServerCfgTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3), )
if mibBuilder.loadTexts: hm2DnsClientServerCfgTable.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerCfgTable.setDescription('The table that contains the DNS Servers entries configured by the user in the system.')
hm2DnsClientServerCfgEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientServerIndex"))
if mibBuilder.loadTexts: hm2DnsClientServerCfgEntry.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerCfgEntry.setDescription('An entry contains the IP address of a DNS server configured in the system.')
hm2DnsClientServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4)))
if mibBuilder.loadTexts: hm2DnsClientServerIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerIndex.setDescription('The unique index used for each server added in the DNS servers table.')
hm2DnsClientServerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 2), InetAddressType().clone('ipv4')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsClientServerAddressType.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerAddressType.setDescription('Address type for DNS server. Currently, only ipv4 is supported.')
hm2DnsClientServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 3), InetAddress().clone(hexValue="00000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsClientServerAddress.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerAddress.setDescription('The IP address of the DNS server.')
hm2DnsClientServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DnsClientServerRowStatus.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerRowStatus.setDescription('Describes the status of a row in the table.')
hm2DnsClientServerDiagTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4), )
if mibBuilder.loadTexts: hm2DnsClientServerDiagTable.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerDiagTable.setDescription('The table that contains the DNS Servers entries configured and used in the system.')
hm2DnsClientServerDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientServerDiagIndex"))
if mibBuilder.loadTexts: hm2DnsClientServerDiagEntry.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerDiagEntry.setDescription('An entry contains the IP address of a DNS server used in the system.')
hm2DnsClientServerDiagIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4)))
if mibBuilder.loadTexts: hm2DnsClientServerDiagIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerDiagIndex.setDescription('The unique index used for each server added in the DNS servers table.')
hm2DnsClientServerDiagAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 2), InetAddressType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DnsClientServerDiagAddressType.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerDiagAddressType.setDescription('Address type for DNS server used. Currently, only ipv4 is supported.')
hm2DnsClientServerDiagAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 3), InetAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hm2DnsClientServerDiagAddress.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientServerDiagAddress.setDescription('The IP address of the DNS server used by the system. The entry can be configured by the provider, e.g. through DHCP client or PPPoE client.')
hm2DnsClientGlobalGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5))
hm2DnsClientDefaultDomainName = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsClientDefaultDomainName.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientDefaultDomainName.setDescription('The default domain name for unqualified hostnames.')
hm2DnsClientRequestTimeout = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3600)).clone(3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsClientRequestTimeout.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientRequestTimeout.setDescription('The timeout before retransmitting a request to the server. The timeout value is configured and displayed in seconds.')
hm2DnsClientRequestRetransmits = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100)).clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsClientRequestRetransmits.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientRequestRetransmits.setDescription('The number of times the request is retransmitted. The request is retransmitted provided the maximum timeout value allows this many number of retransmits.')
hm2DnsClientCacheAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 4), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsClientCacheAdminState.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientCacheAdminState.setDescription('Enables/Disables DNS client cache functionality of the device.')
hm2DnsClientStaticHostConfigTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6), )
if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigTable.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigTable.setDescription('Static table of DNS hostname to IP address table')
hm2DnsClientStaticHostConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientStaticIndex"))
if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigEntry.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigEntry.setDescription('An entry in the static DNS hostname IP address list. Rows may be created or deleted at any time by the DNS resolver and by SNMP SET requests.')
hm2DnsClientStaticIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64)))
if mibBuilder.loadTexts: hm2DnsClientStaticIndex.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientStaticIndex.setDescription('The index of the entry.')
hm2DnsClientStaticHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DnsClientStaticHostName.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientStaticHostName.setDescription('The static hostname.')
hm2DnsClientStaticHostAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 3), InetAddressType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DnsClientStaticHostAddressType.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientStaticHostAddressType.setDescription('Address type for static hosts used. Currently, only ipv4 is supported.')
hm2DnsClientStaticHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 4), InetAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DnsClientStaticHostIPAddress.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientStaticHostIPAddress.setDescription('The IP address of the static host.')
hm2DnsClientStaticHostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hm2DnsClientStaticHostStatus.setStatus('current')
if mibBuilder.loadTexts: hm2DnsClientStaticHostStatus.setDescription('Describes the status of a row in the table.')
hm2DnsCachingServerGlobalGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1))
hm2DnsCachingServerAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsCachingServerAdminState.setStatus('current')
if mibBuilder.loadTexts: hm2DnsCachingServerAdminState.setDescription('Enables/Disables DNS caching server functionality of the device.')
hm2DnsCacheAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsCacheAdminState.setStatus('deprecated')
if mibBuilder.loadTexts: hm2DnsCacheAdminState.setDescription('Enables/Disables DNS cache functionality of the device. **NOTE: this object is deprecated and replaced by hm2DnsClientCacheAdminState/hm2DnsCachingServerAdminState**.')
hm2DnsCacheFlushAction = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 2), HmActionValue().clone('noop')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hm2DnsCacheFlushAction.setStatus('deprecated')
if mibBuilder.loadTexts: hm2DnsCacheFlushAction.setDescription('Setting this value to action will flush the DNS cache. After flushing the cache, it will be set to noop automatically. **NOTE: this object is deprecated and replaced by hm2DevMgmtActionFlushDnsClientCache/hm2DevMgmtActionFlushDnsCachingServerCache**.')
hm2DnsCHHostNameAlreadyExistsSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 1))
if mibBuilder.loadTexts: hm2DnsCHHostNameAlreadyExistsSESError.setStatus('current')
if mibBuilder.loadTexts: hm2DnsCHHostNameAlreadyExistsSESError.setDescription('The host name entered exists and is associated with an IP. The change attempt was canceled.')
hm2DnsCHBadIpNotAcceptedSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 2))
if mibBuilder.loadTexts: hm2DnsCHBadIpNotAcceptedSESError.setStatus('current')
if mibBuilder.loadTexts: hm2DnsCHBadIpNotAcceptedSESError.setDescription('The Ip Adress entered is not a valid one for a host. The change attempt was canceled.')
hm2DnsCHBadRowCannotBeActivatedSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 3))
if mibBuilder.loadTexts: hm2DnsCHBadRowCannotBeActivatedSESError.setStatus('current')
if mibBuilder.loadTexts: hm2DnsCHBadRowCannotBeActivatedSESError.setDescription('The instance cannot be activated due to compliance issues. Please modify the entry and try again.')
mibBuilder.exportSymbols("HM2-DNS-MIB", hm2DnsCachingServerGlobalGroup=hm2DnsCachingServerGlobalGroup, hm2DnsClientServerIndex=hm2DnsClientServerIndex, hm2DnsClientServerAddress=hm2DnsClientServerAddress, hm2DnsClientServerCfgTable=hm2DnsClientServerCfgTable, PYSNMP_MODULE_ID=hm2DnsMib, hm2DnsClientServerDiagAddress=hm2DnsClientServerDiagAddress, hm2DnsClientStaticHostConfigTable=hm2DnsClientStaticHostConfigTable, hm2DnsClientGlobalGroup=hm2DnsClientGlobalGroup, hm2DnsCacheGroup=hm2DnsCacheGroup, hm2DnsClientServerDiagEntry=hm2DnsClientServerDiagEntry, hm2DnsMibSNMPExtensionGroup=hm2DnsMibSNMPExtensionGroup, hm2DnsClientGroup=hm2DnsClientGroup, hm2DnsMibObjects=hm2DnsMibObjects, hm2DnsClientDefaultDomainName=hm2DnsClientDefaultDomainName, hm2DnsClientStaticHostStatus=hm2DnsClientStaticHostStatus, hm2DnsCacheAdminState=hm2DnsCacheAdminState, hm2DnsClientRequestTimeout=hm2DnsClientRequestTimeout, hm2DnsClientServerDiagAddressType=hm2DnsClientServerDiagAddressType, hm2DnsCachingServerGroup=hm2DnsCachingServerGroup, hm2DnsClientServerDiagTable=hm2DnsClientServerDiagTable, hm2DnsCHBadIpNotAcceptedSESError=hm2DnsCHBadIpNotAcceptedSESError, hm2DnsClientAdminState=hm2DnsClientAdminState, hm2DnsClientStaticHostName=hm2DnsClientStaticHostName, hm2DnsClientRequestRetransmits=hm2DnsClientRequestRetransmits, hm2DnsMibNotifications=hm2DnsMibNotifications, hm2DnsClientConfigSource=hm2DnsClientConfigSource, hm2DnsClientServerRowStatus=hm2DnsClientServerRowStatus, hm2DnsClientServerDiagIndex=hm2DnsClientServerDiagIndex, hm2DnsClientCacheAdminState=hm2DnsClientCacheAdminState, hm2DnsCHHostNameAlreadyExistsSESError=hm2DnsCHHostNameAlreadyExistsSESError, hm2DnsCacheFlushAction=hm2DnsCacheFlushAction, hm2DnsClientStaticIndex=hm2DnsClientStaticIndex, hm2DnsClientStaticHostAddressType=hm2DnsClientStaticHostAddressType, hm2DnsCachingServerAdminState=hm2DnsCachingServerAdminState, hm2DnsCHBadRowCannotBeActivatedSESError=hm2DnsCHBadRowCannotBeActivatedSESError, hm2DnsClientServerAddressType=hm2DnsClientServerAddressType, hm2DnsMib=hm2DnsMib, hm2DnsClientStaticHostIPAddress=hm2DnsClientStaticHostIPAddress, hm2DnsClientServerCfgEntry=hm2DnsClientServerCfgEntry, hm2DnsClientStaticHostConfigEntry=hm2DnsClientStaticHostConfigEntry)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint')
(hm_action_value, hm_enabled_status, hm2_configuration_mibs) = mibBuilder.importSymbols('HM2-TC-MIB', 'HmActionValue', 'HmEnabledStatus', 'hm2ConfigurationMibs')
(inet_address_type, inet_address) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressType', 'InetAddress')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(gauge32, unsigned32, module_identity, notification_type, time_ticks, counter32, integer32, counter64, ip_address, mib_identifier, iso, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Unsigned32', 'ModuleIdentity', 'NotificationType', 'TimeTicks', 'Counter32', 'Integer32', 'Counter64', 'IpAddress', 'MibIdentifier', 'iso', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits')
(display_string, textual_convention, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'RowStatus')
hm2_dns_mib = module_identity((1, 3, 6, 1, 4, 1, 248, 11, 90))
hm2DnsMib.setRevisions(('2011-06-17 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
hm2DnsMib.setRevisionsDescriptions(('Initial version.',))
if mibBuilder.loadTexts:
hm2DnsMib.setLastUpdated('201106170000Z')
if mibBuilder.loadTexts:
hm2DnsMib.setOrganization('Hirschmann Automation and Control GmbH')
if mibBuilder.loadTexts:
hm2DnsMib.setContactInfo('Postal: Stuttgarter Str. 45-51 72654 Neckartenzlingen Germany Phone: +49 7127 140 E-mail: hac.support@belden.com')
if mibBuilder.loadTexts:
hm2DnsMib.setDescription('Hirschmann DNS MIB for DNS client, DNS client cache and DNS caching server. Copyright (C) 2011. All Rights Reserved.')
hm2_dns_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 0))
hm2_dns_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1))
hm2_dns_mib_snmp_extension_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 3))
hm2_dns_client_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1))
hm2_dns_cache_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2))
hm2_dns_caching_server_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3))
hm2_dns_client_admin_state = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 1), hm_enabled_status().clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsClientAdminState.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientAdminState.setDescription('The operational status of DNS client. If disabled, no host name lookups will be done for names entered on the CLI and in the configuration of services e.g. NTP.')
hm2_dns_client_config_source = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('user', 1), ('mgmt-dhcp', 2), ('provider', 3))).clone('mgmt-dhcp')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsClientConfigSource.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientConfigSource.setDescription('DNS client server source. If the value is set to user(1), the variables from hm2DnsClientServerCfgTable will be used. If the value is set to mgmt-dhcp(2), the DNS servers received by DHCP on the management interface will be used. If the value is set to provider(3), the DNS configuration will be taken from DHCP, PPP or PPPoE on the primary WAN link.')
hm2_dns_client_server_cfg_table = mib_table((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3))
if mibBuilder.loadTexts:
hm2DnsClientServerCfgTable.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerCfgTable.setDescription('The table that contains the DNS Servers entries configured by the user in the system.')
hm2_dns_client_server_cfg_entry = mib_table_row((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1)).setIndexNames((0, 'HM2-DNS-MIB', 'hm2DnsClientServerIndex'))
if mibBuilder.loadTexts:
hm2DnsClientServerCfgEntry.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerCfgEntry.setDescription('An entry contains the IP address of a DNS server configured in the system.')
hm2_dns_client_server_index = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 4)))
if mibBuilder.loadTexts:
hm2DnsClientServerIndex.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerIndex.setDescription('The unique index used for each server added in the DNS servers table.')
hm2_dns_client_server_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 2), inet_address_type().clone('ipv4')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsClientServerAddressType.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerAddressType.setDescription('Address type for DNS server. Currently, only ipv4 is supported.')
hm2_dns_client_server_address = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 3), inet_address().clone(hexValue='00000000')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsClientServerAddress.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerAddress.setDescription('The IP address of the DNS server.')
hm2_dns_client_server_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 4), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hm2DnsClientServerRowStatus.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerRowStatus.setDescription('Describes the status of a row in the table.')
hm2_dns_client_server_diag_table = mib_table((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4))
if mibBuilder.loadTexts:
hm2DnsClientServerDiagTable.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerDiagTable.setDescription('The table that contains the DNS Servers entries configured and used in the system.')
hm2_dns_client_server_diag_entry = mib_table_row((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1)).setIndexNames((0, 'HM2-DNS-MIB', 'hm2DnsClientServerDiagIndex'))
if mibBuilder.loadTexts:
hm2DnsClientServerDiagEntry.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerDiagEntry.setDescription('An entry contains the IP address of a DNS server used in the system.')
hm2_dns_client_server_diag_index = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 4)))
if mibBuilder.loadTexts:
hm2DnsClientServerDiagIndex.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerDiagIndex.setDescription('The unique index used for each server added in the DNS servers table.')
hm2_dns_client_server_diag_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 2), inet_address_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hm2DnsClientServerDiagAddressType.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerDiagAddressType.setDescription('Address type for DNS server used. Currently, only ipv4 is supported.')
hm2_dns_client_server_diag_address = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 3), inet_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hm2DnsClientServerDiagAddress.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientServerDiagAddress.setDescription('The IP address of the DNS server used by the system. The entry can be configured by the provider, e.g. through DHCP client or PPPoE client.')
hm2_dns_client_global_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5))
hm2_dns_client_default_domain_name = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsClientDefaultDomainName.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientDefaultDomainName.setDescription('The default domain name for unqualified hostnames.')
hm2_dns_client_request_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 3600)).clone(3)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsClientRequestTimeout.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientRequestTimeout.setDescription('The timeout before retransmitting a request to the server. The timeout value is configured and displayed in seconds.')
hm2_dns_client_request_retransmits = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 100)).clone(2)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsClientRequestRetransmits.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientRequestRetransmits.setDescription('The number of times the request is retransmitted. The request is retransmitted provided the maximum timeout value allows this many number of retransmits.')
hm2_dns_client_cache_admin_state = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 4), hm_enabled_status().clone('enable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsClientCacheAdminState.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientCacheAdminState.setDescription('Enables/Disables DNS client cache functionality of the device.')
hm2_dns_client_static_host_config_table = mib_table((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6))
if mibBuilder.loadTexts:
hm2DnsClientStaticHostConfigTable.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostConfigTable.setDescription('Static table of DNS hostname to IP address table')
hm2_dns_client_static_host_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1)).setIndexNames((0, 'HM2-DNS-MIB', 'hm2DnsClientStaticIndex'))
if mibBuilder.loadTexts:
hm2DnsClientStaticHostConfigEntry.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostConfigEntry.setDescription('An entry in the static DNS hostname IP address list. Rows may be created or deleted at any time by the DNS resolver and by SNMP SET requests.')
hm2_dns_client_static_index = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 64)))
if mibBuilder.loadTexts:
hm2DnsClientStaticIndex.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientStaticIndex.setDescription('The index of the entry.')
hm2_dns_client_static_host_name = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostName.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostName.setDescription('The static hostname.')
hm2_dns_client_static_host_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 3), inet_address_type()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostAddressType.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostAddressType.setDescription('Address type for static hosts used. Currently, only ipv4 is supported.')
hm2_dns_client_static_host_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 4), inet_address()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostIPAddress.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostIPAddress.setDescription('The IP address of the static host.')
hm2_dns_client_static_host_status = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 5), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostStatus.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsClientStaticHostStatus.setDescription('Describes the status of a row in the table.')
hm2_dns_caching_server_global_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1))
hm2_dns_caching_server_admin_state = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1, 1), hm_enabled_status().clone('enable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsCachingServerAdminState.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsCachingServerAdminState.setDescription('Enables/Disables DNS caching server functionality of the device.')
hm2_dns_cache_admin_state = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 1), hm_enabled_status().clone('enable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsCacheAdminState.setStatus('deprecated')
if mibBuilder.loadTexts:
hm2DnsCacheAdminState.setDescription('Enables/Disables DNS cache functionality of the device. **NOTE: this object is deprecated and replaced by hm2DnsClientCacheAdminState/hm2DnsCachingServerAdminState**.')
hm2_dns_cache_flush_action = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 2), hm_action_value().clone('noop')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hm2DnsCacheFlushAction.setStatus('deprecated')
if mibBuilder.loadTexts:
hm2DnsCacheFlushAction.setDescription('Setting this value to action will flush the DNS cache. After flushing the cache, it will be set to noop automatically. **NOTE: this object is deprecated and replaced by hm2DevMgmtActionFlushDnsClientCache/hm2DevMgmtActionFlushDnsCachingServerCache**.')
hm2_dns_ch_host_name_already_exists_ses_error = object_identity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 1))
if mibBuilder.loadTexts:
hm2DnsCHHostNameAlreadyExistsSESError.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsCHHostNameAlreadyExistsSESError.setDescription('The host name entered exists and is associated with an IP. The change attempt was canceled.')
hm2_dns_ch_bad_ip_not_accepted_ses_error = object_identity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 2))
if mibBuilder.loadTexts:
hm2DnsCHBadIpNotAcceptedSESError.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsCHBadIpNotAcceptedSESError.setDescription('The Ip Adress entered is not a valid one for a host. The change attempt was canceled.')
hm2_dns_ch_bad_row_cannot_be_activated_ses_error = object_identity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 3))
if mibBuilder.loadTexts:
hm2DnsCHBadRowCannotBeActivatedSESError.setStatus('current')
if mibBuilder.loadTexts:
hm2DnsCHBadRowCannotBeActivatedSESError.setDescription('The instance cannot be activated due to compliance issues. Please modify the entry and try again.')
mibBuilder.exportSymbols('HM2-DNS-MIB', hm2DnsCachingServerGlobalGroup=hm2DnsCachingServerGlobalGroup, hm2DnsClientServerIndex=hm2DnsClientServerIndex, hm2DnsClientServerAddress=hm2DnsClientServerAddress, hm2DnsClientServerCfgTable=hm2DnsClientServerCfgTable, PYSNMP_MODULE_ID=hm2DnsMib, hm2DnsClientServerDiagAddress=hm2DnsClientServerDiagAddress, hm2DnsClientStaticHostConfigTable=hm2DnsClientStaticHostConfigTable, hm2DnsClientGlobalGroup=hm2DnsClientGlobalGroup, hm2DnsCacheGroup=hm2DnsCacheGroup, hm2DnsClientServerDiagEntry=hm2DnsClientServerDiagEntry, hm2DnsMibSNMPExtensionGroup=hm2DnsMibSNMPExtensionGroup, hm2DnsClientGroup=hm2DnsClientGroup, hm2DnsMibObjects=hm2DnsMibObjects, hm2DnsClientDefaultDomainName=hm2DnsClientDefaultDomainName, hm2DnsClientStaticHostStatus=hm2DnsClientStaticHostStatus, hm2DnsCacheAdminState=hm2DnsCacheAdminState, hm2DnsClientRequestTimeout=hm2DnsClientRequestTimeout, hm2DnsClientServerDiagAddressType=hm2DnsClientServerDiagAddressType, hm2DnsCachingServerGroup=hm2DnsCachingServerGroup, hm2DnsClientServerDiagTable=hm2DnsClientServerDiagTable, hm2DnsCHBadIpNotAcceptedSESError=hm2DnsCHBadIpNotAcceptedSESError, hm2DnsClientAdminState=hm2DnsClientAdminState, hm2DnsClientStaticHostName=hm2DnsClientStaticHostName, hm2DnsClientRequestRetransmits=hm2DnsClientRequestRetransmits, hm2DnsMibNotifications=hm2DnsMibNotifications, hm2DnsClientConfigSource=hm2DnsClientConfigSource, hm2DnsClientServerRowStatus=hm2DnsClientServerRowStatus, hm2DnsClientServerDiagIndex=hm2DnsClientServerDiagIndex, hm2DnsClientCacheAdminState=hm2DnsClientCacheAdminState, hm2DnsCHHostNameAlreadyExistsSESError=hm2DnsCHHostNameAlreadyExistsSESError, hm2DnsCacheFlushAction=hm2DnsCacheFlushAction, hm2DnsClientStaticIndex=hm2DnsClientStaticIndex, hm2DnsClientStaticHostAddressType=hm2DnsClientStaticHostAddressType, hm2DnsCachingServerAdminState=hm2DnsCachingServerAdminState, hm2DnsCHBadRowCannotBeActivatedSESError=hm2DnsCHBadRowCannotBeActivatedSESError, hm2DnsClientServerAddressType=hm2DnsClientServerAddressType, hm2DnsMib=hm2DnsMib, hm2DnsClientStaticHostIPAddress=hm2DnsClientStaticHostIPAddress, hm2DnsClientServerCfgEntry=hm2DnsClientServerCfgEntry, hm2DnsClientStaticHostConfigEntry=hm2DnsClientStaticHostConfigEntry) |
class Params:
def __init__(self):
self.embed_size = 75
self.epochs = 2000
self.learning_rate = 0.01
self.top_k = 20
self.ent_top_k = [1, 5, 10, 50]
self.lambda_3 = 0.7
self.generate_sim = 10
self.csls = 5
self.heuristic = True
self.is_save = True
self.mu1 = 1.0
self.mu2 = 1.0
self.nums_threads = 10
self.nums_threads_batch = 1
self.margin_rel = 0.5
self.margin_neg_triple = 1.2
self.margin_ent = 0.5
self.nums_neg = 10
self.nums_neg_neighbor = 10
self.epsilon = 0.95
self.batch_size = 10000
self.is_disc = True
self.nn = 5
def print(self):
print("Parameters used in this running are as follows:")
items = sorted(self.__dict__.items(), key=lambda d: d[0])
for item in items:
print("%s: %s" % item)
print()
P = Params()
P.print()
if __name__ == '__main__':
print("w" + str(1))
| class Params:
def __init__(self):
self.embed_size = 75
self.epochs = 2000
self.learning_rate = 0.01
self.top_k = 20
self.ent_top_k = [1, 5, 10, 50]
self.lambda_3 = 0.7
self.generate_sim = 10
self.csls = 5
self.heuristic = True
self.is_save = True
self.mu1 = 1.0
self.mu2 = 1.0
self.nums_threads = 10
self.nums_threads_batch = 1
self.margin_rel = 0.5
self.margin_neg_triple = 1.2
self.margin_ent = 0.5
self.nums_neg = 10
self.nums_neg_neighbor = 10
self.epsilon = 0.95
self.batch_size = 10000
self.is_disc = True
self.nn = 5
def print(self):
print('Parameters used in this running are as follows:')
items = sorted(self.__dict__.items(), key=lambda d: d[0])
for item in items:
print('%s: %s' % item)
print()
p = params()
P.print()
if __name__ == '__main__':
print('w' + str(1)) |
"""
with open("scrabble.txt", 'r') as f:
count = 0
for line in f:
if count > 5:
break
print(line)
count += 1
"""
#1: Compute scrabble tile score of given string input
#2: Compute all "valid scrabble" words that you could make
# with all char from an input string. Returns list of
# valid words; if no words, returns empty list
"""
chars=input("input your characters in ALL CAPS: ")
charsList=sorted(list(chars))
final=[]
with open("scrabble.txt", 'r') as f:
for line in f:
line=line.strip()
if sorted(list(line)) == charsList:
final.append(line)
print(final)
"""
#3: The game of ghost is played by taking turns with
# a partner to add a letter to an increasingly long
# word. The first person to make a valid scrabble word
# of length 3 or more loses. Must continuously be valid word.
#3a:Write a bot to play ghost against you.
#This program is currently nonfunctional - something is not working in the block at line 48
#Will split into functions in free time but am hungry
word=""
with open("scrabble.txt", 'r') as g:
flip = 1
while flip == 1:
flip=0
char=input("input a character in ALL CAPS: ")
word=word+char
for line in g:
temp=""
line=line.strip()
if line==word:
print("you made the word "+line+", so you lost")
break
for charac in line:
temp=temp+charac
if temp==word:
flip = 1
break
print(word + " is no longer a valid word, so you lost")
| """
with open("scrabble.txt", 'r') as f:
count = 0
for line in f:
if count > 5:
break
print(line)
count += 1
"""
'\nchars=input("input your characters in ALL CAPS: ")\ncharsList=sorted(list(chars))\nfinal=[]\nwith open("scrabble.txt", \'r\') as f:\n for line in f:\n line=line.strip()\n if sorted(list(line)) == charsList:\n final.append(line)\nprint(final)\n'
word = ''
with open('scrabble.txt', 'r') as g:
flip = 1
while flip == 1:
flip = 0
char = input('input a character in ALL CAPS: ')
word = word + char
for line in g:
temp = ''
line = line.strip()
if line == word:
print('you made the word ' + line + ', so you lost')
break
for charac in line:
temp = temp + charac
if temp == word:
flip = 1
break
print(word + ' is no longer a valid word, so you lost') |
class Solution:
def longestPalindrome(self, s: str) -> int:
m = {}
for c in s:
if c in m:
m[c] += 1
else:
m[c] = 1
ans = 0
longest_odd = 0
longest_char = None;
for key in m:
if m[key] % 2 == 1:
if longest_odd < m[key]:
longest_char = key
else:
ans += m[key]
for key in m:
if m[key] % 2 == 1:
if key == longest_char:
ans += m[key]
else:
ans += m[key] - 1
return ans
| class Solution:
def longest_palindrome(self, s: str) -> int:
m = {}
for c in s:
if c in m:
m[c] += 1
else:
m[c] = 1
ans = 0
longest_odd = 0
longest_char = None
for key in m:
if m[key] % 2 == 1:
if longest_odd < m[key]:
longest_char = key
else:
ans += m[key]
for key in m:
if m[key] % 2 == 1:
if key == longest_char:
ans += m[key]
else:
ans += m[key] - 1
return ans |
# https://www.hackerrank.com/challenges/icecream-parlor/problem
t = int(input())
for _ in range(t):
m = int(input())
n = int(input())
cost = list(map(int, input().split()))
memo = {}
for i, c in enumerate(cost):
if (m - c) in memo:
print('%s %s' % (memo[m - c], i + 1))
break
memo[c] = i + 1
| t = int(input())
for _ in range(t):
m = int(input())
n = int(input())
cost = list(map(int, input().split()))
memo = {}
for (i, c) in enumerate(cost):
if m - c in memo:
print('%s %s' % (memo[m - c], i + 1))
break
memo[c] = i + 1 |
# Enum for allegiances
ALLEGIANCE_MAP = {
0: "Shadow",
1: "Neutral",
2: "Hunter"
}
# Enum for card types
CARD_COLOR_MAP = {
0: "White",
1: "Black",
2: "Green"
}
# Enum for text colors
TEXT_COLORS = {
'server': 'rgb(200,200,200)',
'number': 'rgb(153,204,255)',
'White': 'rgb(255,255,255)',
'Black': 'rgb(75,75,75)',
'Green': 'rgb(143,194,0)',
'shadow': 'rgb(128,0,0)',
'neutral': 'rgb(255,255,153)',
'hunter': 'rgb(51,51,255)',
'Weird Woods': 'rgb(102,153,153)',
'Church': 'rgb(255,255,255)',
'Cemetery': 'rgb(75,75,75)',
'Erstwhile Altar': 'rgb(204,68,0)',
'Hermit\'s Cabin': 'rgb(143,194,0)',
'Underworld Gate': 'rgb(150,0,150)'
}
# Number of gameplay tests to run
N_GAMEPLAY_TESTS = 250
| allegiance_map = {0: 'Shadow', 1: 'Neutral', 2: 'Hunter'}
card_color_map = {0: 'White', 1: 'Black', 2: 'Green'}
text_colors = {'server': 'rgb(200,200,200)', 'number': 'rgb(153,204,255)', 'White': 'rgb(255,255,255)', 'Black': 'rgb(75,75,75)', 'Green': 'rgb(143,194,0)', 'shadow': 'rgb(128,0,0)', 'neutral': 'rgb(255,255,153)', 'hunter': 'rgb(51,51,255)', 'Weird Woods': 'rgb(102,153,153)', 'Church': 'rgb(255,255,255)', 'Cemetery': 'rgb(75,75,75)', 'Erstwhile Altar': 'rgb(204,68,0)', "Hermit's Cabin": 'rgb(143,194,0)', 'Underworld Gate': 'rgb(150,0,150)'}
n_gameplay_tests = 250 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""app: The package to hold shell CLI entry points.
1. cistat-cli added for demo.
#. cache commands under progress.
..moduleauthor:: Max Wu < http: // maxwu.me >
"""
| """app: The package to hold shell CLI entry points.
1. cistat-cli added for demo.
#. cache commands under progress.
..moduleauthor:: Max Wu < http: // maxwu.me >
""" |
with open('binary_numbers.txt') as f:
lines = f.readlines()
length = len(lines)
# Part One
def most_common(strings): # Creates a list of amount of 1's at each index for all lines in the string. E.g. a = [1, 3, 2] will have 3 binary numbers with 1 at index 1.
indices = []
bit_length = len(strings[0].strip())
for _ in range(bit_length):
indices.append(0)
for line in strings:
line = line.strip()
for index, char in enumerate(line):
if char == "1":
indices[index] += 1
return indices
def binary_converter(list, list_length):
output_str = ""
for index in list:
if index / list_length >= 0.5:
output_str += "1"
else:
output_str += "0"
return output_str
# function to flip bits
def flip_bits(binary_str):
output_str = ""
for char in binary_str:
if char == "1":
output_str += "0"
else:
output_str += "1"
return output_str
# function to convert binary to decimal
def binary_to_decimal(binary_str):
decimal = 0
for index, char in enumerate(binary_str):
if char == "1":
decimal += 2**(len(binary_str) - index - 1)
return decimal
gamma_binary = binary_converter(most_common(lines), length)
epsilon_binary = flip_bits(binary_converter(most_common(lines), length))
gamma_decimal = binary_to_decimal(gamma_binary)
epsilon_decimal = binary_to_decimal(epsilon_binary)
print("Gamma binary: {} \nEpsilon binary: {}".format(gamma_binary, epsilon_binary))
print("Gamma decimal: {} \nEpsilon decimal: {}".format(gamma_decimal, epsilon_decimal))
print("Power consumption: {}".format(gamma_decimal * epsilon_decimal))
# Part Two
def most_common_with_zeros(list, list_length):
indices = []
for index in list:
if index / list_length >= 0.5:
indices.append(1)
else:
indices.append(0)
return indices
def least_common_with_zeros(list, list_length):
indices = []
for index in list:
if index / list_length <= 0.5:
indices.append(1)
else:
indices.append(0)
return indices
def oxygen_generator_rating(most_common_list, list):
line_length = len(list[0].strip())
trimmed = list
for i in range(line_length):
mc_index = most_common_at_index(trimmed, i)
temp = trim_elements(mc_index, i, trimmed)
trimmed = temp
if len(trimmed) == 1:
return trimmed[0]
def co2_scrubber_rating(least_common_list, list):
line_length = len(list[0].strip())
trimmed = list
for i in range(line_length):
lc_index = least_common_at_index(trimmed, i)
temp = trim_elements(lc_index, i, trimmed)
trimmed = temp
if len(trimmed) == 1:
return trimmed[0]
def most_common_at_index(list, index_number):
length = len(list)
ind = 0
for element in list:
if element[index_number] == "1":
ind += 1
if ind / length >= 0.5:
return 1
else:
return 0
def least_common_at_index(list, index_number):
length = len(list)
ind = 0
for element in list:
if element[index_number] == "1":
ind += 1
if ind / length < 0.5:
return 1
else:
return 0
def trim_elements(binary_number, index, list):
return_list = []
for element in list:
if int(element[index]) == binary_number:
return_list.append(element)
return return_list
def magic_binary(binary_str): # How did i never know about this? Turns binary to decimal
return int(binary_str, 2)
def flip_list(list):
output_list = []
for item in list:
if item == 1:
output_list.append(0)
else:
output_list.append(1)
return output_list
mci = most_common_with_zeros(most_common(lines), length)
ogr = oxygen_generator_rating(mci, lines)
dec_ogr = magic_binary(ogr)
lci = least_common_with_zeros(most_common(lines), length)
# lci = flip_list(mci)
cosr = co2_scrubber_rating(lci, lines)
dec_cosr = magic_binary(cosr)
print("Most common: {}".format(most_common(lines)))
print("Most common with zeros: {}".format(mci))
print("Least common with zeros: {}".format(lci))
print("Oxygen Generator Rating: | binary: {} | decimal: {}".format(ogr, dec_ogr))
print("CO2 Scrubber Rate: | binary {} | decimal: {}".format(cosr, dec_cosr))
print("Life Support Rating: {}.".format(dec_ogr * dec_cosr))
#print(oxygen_generator_rating(most_common_with_zeros(lines), lines)) | with open('binary_numbers.txt') as f:
lines = f.readlines()
length = len(lines)
def most_common(strings):
indices = []
bit_length = len(strings[0].strip())
for _ in range(bit_length):
indices.append(0)
for line in strings:
line = line.strip()
for (index, char) in enumerate(line):
if char == '1':
indices[index] += 1
return indices
def binary_converter(list, list_length):
output_str = ''
for index in list:
if index / list_length >= 0.5:
output_str += '1'
else:
output_str += '0'
return output_str
def flip_bits(binary_str):
output_str = ''
for char in binary_str:
if char == '1':
output_str += '0'
else:
output_str += '1'
return output_str
def binary_to_decimal(binary_str):
decimal = 0
for (index, char) in enumerate(binary_str):
if char == '1':
decimal += 2 ** (len(binary_str) - index - 1)
return decimal
gamma_binary = binary_converter(most_common(lines), length)
epsilon_binary = flip_bits(binary_converter(most_common(lines), length))
gamma_decimal = binary_to_decimal(gamma_binary)
epsilon_decimal = binary_to_decimal(epsilon_binary)
print('Gamma binary: {} \nEpsilon binary: {}'.format(gamma_binary, epsilon_binary))
print('Gamma decimal: {} \nEpsilon decimal: {}'.format(gamma_decimal, epsilon_decimal))
print('Power consumption: {}'.format(gamma_decimal * epsilon_decimal))
def most_common_with_zeros(list, list_length):
indices = []
for index in list:
if index / list_length >= 0.5:
indices.append(1)
else:
indices.append(0)
return indices
def least_common_with_zeros(list, list_length):
indices = []
for index in list:
if index / list_length <= 0.5:
indices.append(1)
else:
indices.append(0)
return indices
def oxygen_generator_rating(most_common_list, list):
line_length = len(list[0].strip())
trimmed = list
for i in range(line_length):
mc_index = most_common_at_index(trimmed, i)
temp = trim_elements(mc_index, i, trimmed)
trimmed = temp
if len(trimmed) == 1:
return trimmed[0]
def co2_scrubber_rating(least_common_list, list):
line_length = len(list[0].strip())
trimmed = list
for i in range(line_length):
lc_index = least_common_at_index(trimmed, i)
temp = trim_elements(lc_index, i, trimmed)
trimmed = temp
if len(trimmed) == 1:
return trimmed[0]
def most_common_at_index(list, index_number):
length = len(list)
ind = 0
for element in list:
if element[index_number] == '1':
ind += 1
if ind / length >= 0.5:
return 1
else:
return 0
def least_common_at_index(list, index_number):
length = len(list)
ind = 0
for element in list:
if element[index_number] == '1':
ind += 1
if ind / length < 0.5:
return 1
else:
return 0
def trim_elements(binary_number, index, list):
return_list = []
for element in list:
if int(element[index]) == binary_number:
return_list.append(element)
return return_list
def magic_binary(binary_str):
return int(binary_str, 2)
def flip_list(list):
output_list = []
for item in list:
if item == 1:
output_list.append(0)
else:
output_list.append(1)
return output_list
mci = most_common_with_zeros(most_common(lines), length)
ogr = oxygen_generator_rating(mci, lines)
dec_ogr = magic_binary(ogr)
lci = least_common_with_zeros(most_common(lines), length)
cosr = co2_scrubber_rating(lci, lines)
dec_cosr = magic_binary(cosr)
print('Most common: {}'.format(most_common(lines)))
print('Most common with zeros: {}'.format(mci))
print('Least common with zeros: {}'.format(lci))
print('Oxygen Generator Rating: | binary: {} | decimal: {}'.format(ogr, dec_ogr))
print('CO2 Scrubber Rate: | binary {} | decimal: {}'.format(cosr, dec_cosr))
print('Life Support Rating: {}.'.format(dec_ogr * dec_cosr)) |
"""
Sensor of Library to measure the 5g signal
How to import:
from Sensors.{sensor_package}.lib import device
How to use:
with device() as sensor:
print(sensor.read_power())
""" | """
Sensor of Library to measure the 5g signal
How to import:
from Sensors.{sensor_package}.lib import device
How to use:
with device() as sensor:
print(sensor.read_power())
""" |
class DarkKeeperError(Exception):
pass
class DarkKeeperCacheError(DarkKeeperError):
pass
class DarkKeeperCacheReadError(DarkKeeperCacheError):
pass
class DarkKeeperCacheWriteError(DarkKeeperCacheError):
pass
class DarkKeeperParseError(DarkKeeperError):
pass
class DarkKeeperParseContentError(DarkKeeperParseError):
pass
class DarkKeeperRequestError(DarkKeeperError):
pass
class DarkKeeperRequestResponseError(DarkKeeperRequestError):
pass
class DarkKeeperMongoError(DarkKeeperError):
pass
class DarkKeeperParseUriMongoError(DarkKeeperMongoError):
pass
| class Darkkeepererror(Exception):
pass
class Darkkeepercacheerror(DarkKeeperError):
pass
class Darkkeepercachereaderror(DarkKeeperCacheError):
pass
class Darkkeepercachewriteerror(DarkKeeperCacheError):
pass
class Darkkeeperparseerror(DarkKeeperError):
pass
class Darkkeeperparsecontenterror(DarkKeeperParseError):
pass
class Darkkeeperrequesterror(DarkKeeperError):
pass
class Darkkeeperrequestresponseerror(DarkKeeperRequestError):
pass
class Darkkeepermongoerror(DarkKeeperError):
pass
class Darkkeeperparseurimongoerror(DarkKeeperMongoError):
pass |
"""
Program: bouncy.py
Project 4.8
This program calculates the total distance a ball travels as it bounces given:
1. the initial height of the ball
2. its bounciness index
3. the number of times the ball is allowed to continue bouncing
"""
height = float(input("Enter the height from which the ball is dropped: "))
bounciness = float(input("Enter the bounciness index of the ball: "))
distance = 0
bounces = int(input("Enter the number of times the ball is allowed to continue bouncing: "))
for eachPass in range(bounces):
distance += height
height *= bounciness
distance += height
print('\nTotal distance traveled is:', distance, 'units.')
| """
Program: bouncy.py
Project 4.8
This program calculates the total distance a ball travels as it bounces given:
1. the initial height of the ball
2. its bounciness index
3. the number of times the ball is allowed to continue bouncing
"""
height = float(input('Enter the height from which the ball is dropped: '))
bounciness = float(input('Enter the bounciness index of the ball: '))
distance = 0
bounces = int(input('Enter the number of times the ball is allowed to continue bouncing: '))
for each_pass in range(bounces):
distance += height
height *= bounciness
distance += height
print('\nTotal distance traveled is:', distance, 'units.') |
def initialize(n):
for key in ['queen','row','col','rwtose','swtose']:
board[key]={}
for i in range(n):
board['queen'][i]=-1
board['row'][i]=0
board['col'][i]=0
for i in range(-(n-1),n):
board['rwtose'][i]=0
for i in range(2*n-1):
board['swtose'][i]=0
def free(i,j):
return(
board['row'][i]==0 and
board['col'][j]==0 and
board['rwtose'][j-i]==0 and
board['swtose'][j+i]==0
)
def addqueen(i,j):
board['queen'][i]=j
board['row'][i]=1
board['col'][j]=1
board['rwtose'][j-i]=1
board['swtose'][j+i]=1
def undoqueen(i,j):
board['queen'][i]=-1
board['row'][i]=0
board['col'][j]=0
board['rwtose'][j-i]=0
board['swtose'][j+i]=0
def printboard():
for row in sorted(board['queen'].keys()):
print((row,board['queen'][row]),end=" ")
print(" ")
def placequeen(i):
n=len(board['queen'].keys())
for j in range(n):
if free(i,j):
addqueen(i,j)
if i==n-1:
printboard()#remove for single solution
# return(True)
else:
extendsoln=placequeen(i+1)
# if(extendsoln):
# return True
# else:
undoqueen(i,j)
# else:
# return(False)
board={}
n=int(input("How many queen?"))
initialize(n)
placequeen(0)
# if placequeen(0):
# printboard()
| def initialize(n):
for key in ['queen', 'row', 'col', 'rwtose', 'swtose']:
board[key] = {}
for i in range(n):
board['queen'][i] = -1
board['row'][i] = 0
board['col'][i] = 0
for i in range(-(n - 1), n):
board['rwtose'][i] = 0
for i in range(2 * n - 1):
board['swtose'][i] = 0
def free(i, j):
return board['row'][i] == 0 and board['col'][j] == 0 and (board['rwtose'][j - i] == 0) and (board['swtose'][j + i] == 0)
def addqueen(i, j):
board['queen'][i] = j
board['row'][i] = 1
board['col'][j] = 1
board['rwtose'][j - i] = 1
board['swtose'][j + i] = 1
def undoqueen(i, j):
board['queen'][i] = -1
board['row'][i] = 0
board['col'][j] = 0
board['rwtose'][j - i] = 0
board['swtose'][j + i] = 0
def printboard():
for row in sorted(board['queen'].keys()):
print((row, board['queen'][row]), end=' ')
print(' ')
def placequeen(i):
n = len(board['queen'].keys())
for j in range(n):
if free(i, j):
addqueen(i, j)
if i == n - 1:
printboard()
else:
extendsoln = placequeen(i + 1)
undoqueen(i, j)
board = {}
n = int(input('How many queen?'))
initialize(n)
placequeen(0) |
class PackageManager:
"""
An object that contains the name used by dotstar and the true name of the PM (the one used by the OS, that dotstar
calls when installing).
dotstar don't uses the same name as the OS because snap has two mods of installation (sandbox and classic)
so we have to differentiate them.
Contains too the command shape, a string with a %s placeholder
"""
def __init__(
self,
dotstar_name: str,
system_name: str,
command_shape: str,
multiple_apps_query_support: bool
) -> None:
"""
:param dotstar_name: the name of the PM that dotstar uses
:param system_name: the name of the PM that the OS uses
:param command_shape: the shape of the command. Must have a %s placeholder
:param multiple_apps_query_support: if the PM supports query with multiple names (like "pacman -Sy atom gedit")
"""
self.dotstar_name = dotstar_name
self.system_name = system_name
self.command_shape = command_shape
self.multiple_apps_query_support = multiple_apps_query_support
| class Packagemanager:
"""
An object that contains the name used by dotstar and the true name of the PM (the one used by the OS, that dotstar
calls when installing).
dotstar don't uses the same name as the OS because snap has two mods of installation (sandbox and classic)
so we have to differentiate them.
Contains too the command shape, a string with a %s placeholder
"""
def __init__(self, dotstar_name: str, system_name: str, command_shape: str, multiple_apps_query_support: bool) -> None:
"""
:param dotstar_name: the name of the PM that dotstar uses
:param system_name: the name of the PM that the OS uses
:param command_shape: the shape of the command. Must have a %s placeholder
:param multiple_apps_query_support: if the PM supports query with multiple names (like "pacman -Sy atom gedit")
"""
self.dotstar_name = dotstar_name
self.system_name = system_name
self.command_shape = command_shape
self.multiple_apps_query_support = multiple_apps_query_support |
def raizI(x,b):
if b** 2>x:
return b-1
return raizI (x,b+1)
raizI(11,5) | def raiz_i(x, b):
if b ** 2 > x:
return b - 1
return raiz_i(x, b + 1)
raiz_i(11, 5) |
lambda x: xx
def write2(): pass
def write(*args, **kw):
raise NotImplementedError
async def foo(one, *args, **kw):
"""
Args:
args: Test
"""
data = yield from read_data(db)
| lambda x: xx
def write2():
pass
def write(*args, **kw):
raise NotImplementedError
async def foo(one, *args, **kw):
"""
Args:
args: Test
"""
data = (yield from read_data(db)) |
class Solution:
def numberOfSteps (self, num: int) -> int:
count = 0
while num!=0:
print(num,count)
if num==1:
count+=1
return count
if num%2==0:
count+=1
else:
count+=2
num = num>>1
| class Solution:
def number_of_steps(self, num: int) -> int:
count = 0
while num != 0:
print(num, count)
if num == 1:
count += 1
return count
if num % 2 == 0:
count += 1
else:
count += 2
num = num >> 1 |
class ErrorSeverity(object):
FATAL = 'fatal'
ERROR = 'error'
WARNING = 'warning'
ALLOWED_VALUES = (FATAL, ERROR, WARNING)
@classmethod
def validate(cls, value):
return value in cls.ALLOWED_VALUES
| class Errorseverity(object):
fatal = 'fatal'
error = 'error'
warning = 'warning'
allowed_values = (FATAL, ERROR, WARNING)
@classmethod
def validate(cls, value):
return value in cls.ALLOWED_VALUES |
#!/usr/bin/env python3
def write_csv(filename, content):
with open(filename, 'w') as csvfile:
for line in content:
for i, item in enumerate(line):
csvfile.write(str(item))
if i != len(line) - 1:
csvfile.write(',')
csvfile.write('\n')
def read_csv(filename):
with open(filename, 'r') as content:
return [[v for v in line.replace('\n', '').split(',')] for line in content]
| def write_csv(filename, content):
with open(filename, 'w') as csvfile:
for line in content:
for (i, item) in enumerate(line):
csvfile.write(str(item))
if i != len(line) - 1:
csvfile.write(',')
csvfile.write('\n')
def read_csv(filename):
with open(filename, 'r') as content:
return [[v for v in line.replace('\n', '').split(',')] for line in content] |
'''Change the database in this file
Change the database in this script locally
Careful here
'''
| """Change the database in this file
Change the database in this script locally
Careful here
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.