content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Problem : Find out the missing number
Author : Alok Tripathi
"""
def getMissingNo(arr):
n = len(arr)
# Sum of (N+1) * (N+2) natural number [n is length of arr]
total = (n + 1) * (n + 2) / 2
sum_of_arr = sum(arr)
return int(total - sum_of_arr) # sum of n... natural no. - sum of array
if __name__ == "__main__":
arr = [1, 2, 3, 5]
miss = getMissingNo(arr)
print(miss)
| """
Problem : Find out the missing number
Author : Alok Tripathi
"""
def get_missing_no(arr):
n = len(arr)
total = (n + 1) * (n + 2) / 2
sum_of_arr = sum(arr)
return int(total - sum_of_arr)
if __name__ == '__main__':
arr = [1, 2, 3, 5]
miss = get_missing_no(arr)
print(miss) |
a = int(input())
v = 0
for x in range(1,10+1):
print(v+1,"x",a,"=",a*(v+1))
v = v+ 1
| a = int(input())
v = 0
for x in range(1, 10 + 1):
print(v + 1, 'x', a, '=', a * (v + 1))
v = v + 1 |
"""
A OISC emulation using the Subleq operation.
Tom Findlay (findlaytel@gmail.com)
Feb. 2021
"""
class whisk:
def __init__(self, memory=30000):
self.memory = [0]*memory
def subleq(self,addr):
if addr < 0:
return None
A = self.memory[addr]
B = self.memory[addr+1]
C = self.memory[addr+2]
if B == -1:
print(chr(self.memory[A]), end="")
return addr+3
else:
sub = self.memory[B] - self.memory[A]
self.memory[B] = sub
if sub <= 0:
return C
return addr+3
def run(self, code):
code = code.split()
code = [int(i) for i in code]
self.memory[0:len(code)] = code
pc = 0
while pc != None:
pc = self.subleq(pc)
return True
if __name__ == "__main__":
f = open("output.slq", "r")
code = f.read()
f.close()
w = whisk()
w.run(code)
| """
A OISC emulation using the Subleq operation.
Tom Findlay (findlaytel@gmail.com)
Feb. 2021
"""
class Whisk:
def __init__(self, memory=30000):
self.memory = [0] * memory
def subleq(self, addr):
if addr < 0:
return None
a = self.memory[addr]
b = self.memory[addr + 1]
c = self.memory[addr + 2]
if B == -1:
print(chr(self.memory[A]), end='')
return addr + 3
else:
sub = self.memory[B] - self.memory[A]
self.memory[B] = sub
if sub <= 0:
return C
return addr + 3
def run(self, code):
code = code.split()
code = [int(i) for i in code]
self.memory[0:len(code)] = code
pc = 0
while pc != None:
pc = self.subleq(pc)
return True
if __name__ == '__main__':
f = open('output.slq', 'r')
code = f.read()
f.close()
w = whisk()
w.run(code) |
# Implementation using list
# Initializing queue using a list
myQueue = []
# Adding elements to the queue
myQueue.append(1)
myQueue.append(2)
myQueue.append(3)
# Printing the queue
print("Initial queue:", myQueue)
# Size of the queue
print("Size: ", len(myQueue))
# Check if queue is empty
if not myQueue:
print("Queue is empty")
else:
print("Queue is not empty")
# Peek operation
print("First element in the queue: ", myQueue[0])
# Removing an element from the queue
print("Dequeued element:", myQueue.pop(0))
print("Queue after dequeue operation:", myQueue) | my_queue = []
myQueue.append(1)
myQueue.append(2)
myQueue.append(3)
print('Initial queue:', myQueue)
print('Size: ', len(myQueue))
if not myQueue:
print('Queue is empty')
else:
print('Queue is not empty')
print('First element in the queue: ', myQueue[0])
print('Dequeued element:', myQueue.pop(0))
print('Queue after dequeue operation:', myQueue) |
#!/usr/bin/env python3
def merge(A,l,m,r):
L,R = A[l:m+1],A[m+1:r+1] #copied
L.append(float("inf"))
R.append(float("inf"))
i,j = 0,0
for k in range(l,r+1):
A[k]= L[i] if L[i]<R[j] else R[j]
i,j =(1+i,j) if L[i]<R[j] else (i,j+1)
def merge_sort(A,l,r):
if l<r:
m = l+((r-l)>>1)
merge_sort(A,l,m)
merge_sort(A,m+1,r)
print(A,l,m,r)
merge(A,l,m,r)
A = [5,2,4,7,1,3,2,6]
merge_sort(A,0,len(A)-1)
print(A)
| def merge(A, l, m, r):
(l, r) = (A[l:m + 1], A[m + 1:r + 1])
L.append(float('inf'))
R.append(float('inf'))
(i, j) = (0, 0)
for k in range(l, r + 1):
A[k] = L[i] if L[i] < R[j] else R[j]
(i, j) = (1 + i, j) if L[i] < R[j] else (i, j + 1)
def merge_sort(A, l, r):
if l < r:
m = l + (r - l >> 1)
merge_sort(A, l, m)
merge_sort(A, m + 1, r)
print(A, l, m, r)
merge(A, l, m, r)
a = [5, 2, 4, 7, 1, 3, 2, 6]
merge_sort(A, 0, len(A) - 1)
print(A) |
# str(Color())
class Color:
color = 'orange'
def __str__(self):
return Color.color
print(str(Color()))
| class Color:
color = 'orange'
def __str__(self):
return Color.color
print(str(color())) |
# 1. Define a function that accepts 2 values and returns
# its sum, subtraction and multiplication.
# SOLUTION:
def result(a, b):
sum = a+b
sub = a-b
mul = a*b
print(f"Sum is {sum}, Sub is {sub}, & Multiply is {mul}")
a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
result(a,b)
# 2. Define a function in python that accepts 3 digits
# and returns the highest of the three digits
def max(a, b, c):
if a > b and a > c:
print(f"{a} is maximum among all")
elif b > a and b > c:
print(f"{b} is maximum among all")
else:
print(f"{c} is maximum among all")
max(30,22,18)
# 3. Define a function that counts vowels
# and consonants in a word that you send in.
def count(val):
vov = 0
con = 0
for i in range(len(val)):
if val[i] in ['a','e','i','o','u']:
vov = vov+1
else:
con = con + 1
print("Count of vowels is ",vov)
print("Count of consonant is ",con)
x = input("Enter a word: ")
count(x) | def result(a, b):
sum = a + b
sub = a - b
mul = a * b
print(f'Sum is {sum}, Sub is {sub}, & Multiply is {mul}')
a = int(input('Enter value of a: '))
b = int(input('Enter value of b: '))
result(a, b)
def max(a, b, c):
if a > b and a > c:
print(f'{a} is maximum among all')
elif b > a and b > c:
print(f'{b} is maximum among all')
else:
print(f'{c} is maximum among all')
max(30, 22, 18)
def count(val):
vov = 0
con = 0
for i in range(len(val)):
if val[i] in ['a', 'e', 'i', 'o', 'u']:
vov = vov + 1
else:
con = con + 1
print('Count of vowels is ', vov)
print('Count of consonant is ', con)
x = input('Enter a word: ')
count(x) |
################################################################
### User input parameters for C3S-LAA
################################################################
### Required dependencies and input files
# Path for the AMOS package that contains minimus assembler
amos_path = "/usr/local/amos/bin/"
# C3S-LAA input files
primer_info_file = "primer_pairs_info.txt"
barcode_info_file = "barcode_pairs_info.txt"
fofn = "/mnt/data27/ffrancis/PacBio_sequence_files/EqPCR_raw/F03_1/Analysis_Results/m160901_060459_42157_c101086112550000001823264003091775_s1_p0.bas.h5"
ccs = "/mnt/data27/ffrancis/PacBio_sequence_files/old/primer_pair_based_grouping/Eq_wisser_PCR-ccs-opt-smrtanalysis-userdata-jobs-020-020256-data-reads_of_insert.fasta"
# Output path
consensus_output = "./output/"
### C3S-LAA parameters
trim_bp = 21 # number of bases corresponding to padding + barcode that need to be trimmed from the amplicon consensus
barcode_subset = 0 # (1: yes; 0: no)
min_read_length = 0 # reads >= "min_read_length" will be searched for the presence of primer sequences
min_read_len_filter = 1 # (1: filter; 0: no filter)
primer_search_space = 100 # searches for the primer sequence within n bases from the read terminals
max_barcode_length = 0 # barcode seq length
max_padding_length = 5 # padding seq length
### torque script settings
walltime = 190 # walltime for consensus calling
node = "1" # node no. for consensus calling
processors = 12 # no. processors for consensus calling
no_reads_threshold = 100 # consens sequences generated from >= "no_reads_threshold" will be used for assembly
| amos_path = '/usr/local/amos/bin/'
primer_info_file = 'primer_pairs_info.txt'
barcode_info_file = 'barcode_pairs_info.txt'
fofn = '/mnt/data27/ffrancis/PacBio_sequence_files/EqPCR_raw/F03_1/Analysis_Results/m160901_060459_42157_c101086112550000001823264003091775_s1_p0.bas.h5'
ccs = '/mnt/data27/ffrancis/PacBio_sequence_files/old/primer_pair_based_grouping/Eq_wisser_PCR-ccs-opt-smrtanalysis-userdata-jobs-020-020256-data-reads_of_insert.fasta'
consensus_output = './output/'
trim_bp = 21
barcode_subset = 0
min_read_length = 0
min_read_len_filter = 1
primer_search_space = 100
max_barcode_length = 0
max_padding_length = 5
walltime = 190
node = '1'
processors = 12
no_reads_threshold = 100 |
# general
make_debug = False
make_task = ""
build_type = "Release"
app_name = "MyApp"
| make_debug = False
make_task = ''
build_type = 'Release'
app_name = 'MyApp' |
sum = 0
for num in range(1,1000):
if (num % 3 == 0 or num % 5 == 0):
sum += num
print(sum) | sum = 0
for num in range(1, 1000):
if num % 3 == 0 or num % 5 == 0:
sum += num
print(sum) |
def split_lines(el):
return el.split('\n')
split_lines('10\n is\n the\n perfect\n number')
| def split_lines(el):
return el.split('\n')
split_lines('10\n is\n the\n perfect\n number') |
class Solution:
# @param {integer[]} prices
# @return {integer}
def maxProfit(self, prices):
if len(prices) < 2:
return 0
minn = prices[:-1]
maxn = prices[1:]
mi = minn[0]
for i in range(1, len(minn)):
if minn[i] > mi:
minn[i] = mi
else:
mi = minn[i]
ma = maxn[-1] # the last element
for i in range(len(maxn) - 1, 0, -1):
if maxn[i] > ma:
ma = maxn[i]
else:
maxn[i] = ma
res = 0
for i in range(len(maxn)):
if maxn[i] - minn[i] > res:
res = maxn[i] - minn[i]
return res
| class Solution:
def max_profit(self, prices):
if len(prices) < 2:
return 0
minn = prices[:-1]
maxn = prices[1:]
mi = minn[0]
for i in range(1, len(minn)):
if minn[i] > mi:
minn[i] = mi
else:
mi = minn[i]
ma = maxn[-1]
for i in range(len(maxn) - 1, 0, -1):
if maxn[i] > ma:
ma = maxn[i]
else:
maxn[i] = ma
res = 0
for i in range(len(maxn)):
if maxn[i] - minn[i] > res:
res = maxn[i] - minn[i]
return res |
class ManagedFile:
"""
Manager for open with context manager
"""
def __init__(self,name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, exc_type,exc_val, exc_tb):
if self.file:
self.file.close()
| class Managedfile:
"""
Manager for open with context manager
"""
def __init__(self, name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close() |
__all__ = ['UndefinedType', 'undefined']
class _SingletonMeta(type):
def __call__(self, *args, **kwargs):
if not hasattr(self, '__instance__'):
self.__instance__ = super().__call__(*args, **kwargs)
return self.__instance__
class UndefinedType(metaclass=_SingletonMeta):
'''A new singleton constant to Python that is passed in
when a parameter is not mapped to an argument.'''
__slots__ = () # instance has no property `__dict__`
__repr__ = staticmethod(lambda: 'undefined') # type: ignore # staticmethod for speed up
__bool__ = staticmethod(lambda: False)
undefined = UndefinedType()
| __all__ = ['UndefinedType', 'undefined']
class _Singletonmeta(type):
def __call__(self, *args, **kwargs):
if not hasattr(self, '__instance__'):
self.__instance__ = super().__call__(*args, **kwargs)
return self.__instance__
class Undefinedtype(metaclass=_SingletonMeta):
"""A new singleton constant to Python that is passed in
when a parameter is not mapped to an argument."""
__slots__ = ()
__repr__ = staticmethod(lambda : 'undefined')
__bool__ = staticmethod(lambda : False)
undefined = undefined_type() |
def bubbleSort(alist):
for passnum in range(len(alist) - 1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i + 1]:
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubbleSort(alist)
print(alist)
# short bubble sort will return if the list doesn't need to sorted that much.
def shortBubbleSort(alist):
exchanges = True
passnum = len(alist) - 1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i] > alist[i + 1]:
exchanges = True
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
passnum = passnum - 1
alist = [20, 30, 40, 90, 50, 60, 70, 80, 100, 110]
shortBubbleSort(alist)
print(alist)
| def bubble_sort(alist):
for passnum in range(len(alist) - 1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i + 1]:
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubble_sort(alist)
print(alist)
def short_bubble_sort(alist):
exchanges = True
passnum = len(alist) - 1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i] > alist[i + 1]:
exchanges = True
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
passnum = passnum - 1
alist = [20, 30, 40, 90, 50, 60, 70, 80, 100, 110]
short_bubble_sort(alist)
print(alist) |
def format_search_terms(search_terms):
s=''
q=[]
if search_terms != None:
for term in search_terms:
q.append(term)
q.append('%20')
s= ''.join(q)
return s
def format_from_user(from_user):
s=''
q=[]
if from_user != None:
q.append('from%3A')
q.append(from_user)
q.append('%20')
s = ''.join(q)
return s
def format_reply_to(reply_to):
s=''
q=[]
if reply_to != None:
q.append('to%3A')
q.append(reply_to)
q.append('%20')
s = ''.join(q)
return s
def format_not_including(not_including):
s=''
q=[]
if not_including != None:
q.append('%2D')
q.append(not_including)
q.append('%20')
s = ''.join(q)
return s
def format_phrases(phrases):
s=''
q=[]
if phrases != None:
for phrase in phrases:
q.append('%22')
q.append(phrase)
q.append('%22')
q.append('%20')
s = ''.join(q)
return s
def format_filter(filters):
s=''
q=[]
if filters != None:
for filter in filters:
q.append('filter')
q.append('%3A')
q.append(filter)
q.append('%20')
s = ''.join(q)
return s
def format_not_filter(filters):
s=''
q=[]
if filters != None:
for filter in filters:
q.append('%2D')
q.append('filter')
q.append('%3A')
q.append(filter)
q.append('%20')
s = ''.join(q)
return s
def format_positive(positive):
s=''
if positive != None:
if positive is True:
s = '%3A%29%20'
else:
s = '%3A%28%20'
return s
def format_since(since):
s=''
q=[]
if since != None:
q.append('&')
q.append('since=')
q.append(since)
q.append('%20')
s = ''.join(q)
return s
def format_until(since):
s=''
q=[]
if since != None:
q.append('until%A')
q.append(since)
q.append('%20')
s = ''.join(q)
return s
def format_geocode(geocode):
s=''
q=[]
if geocode != None:
q.append('&geocode=')
q.append(geocode)
s = ''.join(q)
return s
def format_lang(lang):
s=''
q=[]
if lang != None:
q.append('&lang=')
q.append(lang)
s = ''.join(q)
return s
def format_locale(locale):
s=''
q=[]
if locale != None:
q.append('&locale=')
q.append(locale)
s = ''.join(q)
return s
def format_result_type(result_type):
s=''
q=[]
if result_type != None:
q.append('&result_type=')
q.append(result_type)
s = ''.join(q)
return s
def format_count(count):
s=''
q=[]
if count != None:
q.append('&count=')
q.append(count)
s = ''.join(q)
return s
def format_since_id(since_id):
s=''
q=[]
if since_id != None:
q.append('&since_id=')
q.append(since_id)
s = ''.join(q)
return s
def format_max_id(max_id):
s=''
q=[]
if max_id != None:
q.append('&max_id=')
q.append(max_id)
s = ''.join(q)
return s
def format_include_entities(include_entities):
s=''
q=[]
if include_entities != None:
q.append('&include_entities=')
q.append(include_entities)
s = ''.join(q)
return s | def format_search_terms(search_terms):
s = ''
q = []
if search_terms != None:
for term in search_terms:
q.append(term)
q.append('%20')
s = ''.join(q)
return s
def format_from_user(from_user):
s = ''
q = []
if from_user != None:
q.append('from%3A')
q.append(from_user)
q.append('%20')
s = ''.join(q)
return s
def format_reply_to(reply_to):
s = ''
q = []
if reply_to != None:
q.append('to%3A')
q.append(reply_to)
q.append('%20')
s = ''.join(q)
return s
def format_not_including(not_including):
s = ''
q = []
if not_including != None:
q.append('%2D')
q.append(not_including)
q.append('%20')
s = ''.join(q)
return s
def format_phrases(phrases):
s = ''
q = []
if phrases != None:
for phrase in phrases:
q.append('%22')
q.append(phrase)
q.append('%22')
q.append('%20')
s = ''.join(q)
return s
def format_filter(filters):
s = ''
q = []
if filters != None:
for filter in filters:
q.append('filter')
q.append('%3A')
q.append(filter)
q.append('%20')
s = ''.join(q)
return s
def format_not_filter(filters):
s = ''
q = []
if filters != None:
for filter in filters:
q.append('%2D')
q.append('filter')
q.append('%3A')
q.append(filter)
q.append('%20')
s = ''.join(q)
return s
def format_positive(positive):
s = ''
if positive != None:
if positive is True:
s = '%3A%29%20'
else:
s = '%3A%28%20'
return s
def format_since(since):
s = ''
q = []
if since != None:
q.append('&')
q.append('since=')
q.append(since)
q.append('%20')
s = ''.join(q)
return s
def format_until(since):
s = ''
q = []
if since != None:
q.append('until%A')
q.append(since)
q.append('%20')
s = ''.join(q)
return s
def format_geocode(geocode):
s = ''
q = []
if geocode != None:
q.append('&geocode=')
q.append(geocode)
s = ''.join(q)
return s
def format_lang(lang):
s = ''
q = []
if lang != None:
q.append('&lang=')
q.append(lang)
s = ''.join(q)
return s
def format_locale(locale):
s = ''
q = []
if locale != None:
q.append('&locale=')
q.append(locale)
s = ''.join(q)
return s
def format_result_type(result_type):
s = ''
q = []
if result_type != None:
q.append('&result_type=')
q.append(result_type)
s = ''.join(q)
return s
def format_count(count):
s = ''
q = []
if count != None:
q.append('&count=')
q.append(count)
s = ''.join(q)
return s
def format_since_id(since_id):
s = ''
q = []
if since_id != None:
q.append('&since_id=')
q.append(since_id)
s = ''.join(q)
return s
def format_max_id(max_id):
s = ''
q = []
if max_id != None:
q.append('&max_id=')
q.append(max_id)
s = ''.join(q)
return s
def format_include_entities(include_entities):
s = ''
q = []
if include_entities != None:
q.append('&include_entities=')
q.append(include_entities)
s = ''.join(q)
return s |
class EventBrokerError(Exception):
pass
class EventBrokerAuthError(EventBrokerError):
pass
| class Eventbrokererror(Exception):
pass
class Eventbrokerautherror(EventBrokerError):
pass |
# We'll use a greedy algorithm to check to see if we have a
# new max sum as we iterate along the along. If at any time
# our sum becomes negative, we reset the sum.
def largestContiguousSum(arr):
maxSum = 0
currentSum = 0
for i, _ in enumerate(arr):
currentSum += arr[i]
maxSum = max(currentSum, maxSum)
if currentSum < 0:
currentSum = 0
return maxSum
# Tests
print(largestContiguousSum([5, -9, 6, -2, 3])) # should print 7
print(largestContiguousSum([1, 23, 90, 0, -9])) # should print 114
print(largestContiguousSum([2, 3, -8, -1, 2, 4, -2, 3])) # should print 7
| def largest_contiguous_sum(arr):
max_sum = 0
current_sum = 0
for (i, _) in enumerate(arr):
current_sum += arr[i]
max_sum = max(currentSum, maxSum)
if currentSum < 0:
current_sum = 0
return maxSum
print(largest_contiguous_sum([5, -9, 6, -2, 3]))
print(largest_contiguous_sum([1, 23, 90, 0, -9]))
print(largest_contiguous_sum([2, 3, -8, -1, 2, 4, -2, 3])) |
def diagonalDifference(arr):
diagonal1 = 0
diagonal2 = 0
for pos, line in enumerate(arr):
diagonal1 += line[pos]
diagonal2 += line[len(arr)-1 - pos]
return abs(diagonal1 - diagonal2)
| def diagonal_difference(arr):
diagonal1 = 0
diagonal2 = 0
for (pos, line) in enumerate(arr):
diagonal1 += line[pos]
diagonal2 += line[len(arr) - 1 - pos]
return abs(diagonal1 - diagonal2) |
class MaterialSubsurfaceScattering:
back = None
color = None
color_factor = None
error_threshold = None
front = None
ior = None
radius = None
scale = None
texture_factor = None
use = None
| class Materialsubsurfacescattering:
back = None
color = None
color_factor = None
error_threshold = None
front = None
ior = None
radius = None
scale = None
texture_factor = None
use = None |
shiboken_library_soversion = str(6.1)
version = "6.1.1"
version_info = (6, 1, 1, "", "")
__build_date__ = '2021-06-03T07:46:50+00:00'
__setup_py_package_version__ = '6.1.1'
| shiboken_library_soversion = str(6.1)
version = '6.1.1'
version_info = (6, 1, 1, '', '')
__build_date__ = '2021-06-03T07:46:50+00:00'
__setup_py_package_version__ = '6.1.1' |
# S1
input_list = []
for i in range(int(6)):
input_list.append(input())
win_counter = 0
loss_counter = 0
for i in input_list:
if i == "W":
win_counter += 1
else:
loss_counter += 1
if win_counter == 1 or win_counter == 2:
print("3")
elif win_counter == 3 or win_counter == 4:
print("2")
elif win_counter == 5 or win_counter == 6:
print("1")
else:
print("-1")
# S2
def row_sum(matrix, row_num):
sum = 0
for i in range(4):
sum += int(matrix[row_num][i])
return sum
def col_sum(matrix, col_num):
sum = 0
for i in range(4):
sum += int(matrix[i][col_num])
return sum
input_list = []
for i in range(int(4)):
input_list.append(input().split())
#horizontal sum
h_sum = 0
sum_row_1 = row_sum(input_list, 0)
sum_row_2 = row_sum(input_list, 1)
sum_row_3 = row_sum(input_list, 2)
sum_row_4 = row_sum(input_list, 3)
sum_col_1 = col_sum(input_list, 0)
sum_col_2 = col_sum(input_list, 1)
sum_col_3 = col_sum(input_list, 2)
sum_col_4 = col_sum(input_list, 3)
if sum_row_1 == sum_row_2 == sum_row_3 == sum_row_4 == sum_col_1 == sum_col_2 == sum_col_3 == sum_col_4:
print('MAGIC')
else:
print("NOT MAGIC")
S3
a = input()
def palindromes(word):
i = 0
j = len(word) - 1
if len(word) == 0:
return 0
while i != j and i+1 != j:
if word[i] == word[j]:
i += 1
j -= 1
else:
return 0
if i+1 == j:
if word[i] != word[j]:
return 0
return len(word)
# check
result_num = 0
for i in range(len(a)):
for j in range(len(a), -1, -1):
word = a[i:j]
max_num = palindromes(word)
result_num = max(max_num, result_num)
print (result_num)
print(palindromes(a))
# S4
d_time = list(input())
del d_time[2]
# converting to integers
x = 0
while x < len(d_time):
d_time[x] = int(d_time[x])
x += 1
ten = [1, 0, 0, 0]
time = 0
add_time = 1
# Cycling through two hours of time
while time != 120:
# Defining rush hour
if d_time[1] >= 7 and d_time[1] <= 9 or d_time == ten:
rush_hour = True
else:
rush_hour = False
if rush_hour == True:
add_time = 0.5
else:
add_time = 1
# new minute
if d_time[3] != 9 and d_time[1] != 4:
d_time[3] += 1
# new multiple of ten miinutes
elif d_time[3] == 9 and d_time[2] != 5:
d_time[3] = 0
d_time[2] += 1
# new one-digit hour
elif d_time[3] == 9 and d_time[2] == 5 and d_time[1] != 9:
d_time[1] += 1
d_time[2] = 0
d_time[3] = 0
# switch to 10
elif d_time[1] == 9 and d_time[2] == 5 and d_time[3] == 9:
d_time[0] = 1
d_time[1] = 0
d_time[2] = 0
d_time[3] = 0
# new two-digit time
elif d_time[2] == 5 and d_time[3] == 9 and d_time[0] == 1:
# not to 20
if d_time[1] != 9:
d_time[1] += 1
# to 20
elif d_time[1] == 9:
d_time[0] = 2
d_time[1] = 0
d_time[2] = 0
d_time[3] = 0
# to 00:01
elif d_time[0] == 2 and d_time[1] == 4:
d_time[0] = 0
d_time[1] = 0
d_time[2] = 0
d_time[3] = 1
time += add_time
print(d_time[0], d_time[1], ':', d_time[2], d_time[3])
#S5
question = int(input())
num_people = int(input())
dmoj_v = input().split()
peg_v = input().split()
# convert lists to ints
for s in range(len(dmoj_v)):
dmoj_v[s] = int(dmoj_v[s])
for s in range(len(peg_v)):
peg_v[s] = int(peg_v[s])
# problem one
if question == 1:
x, total_speed = 0, 0
while x < num_people:
speeds = [max(dmoj_v), max(peg_v)]
bike_speed = max(speeds)
# take used up speeds off of the list
dmoj_v.pop(dmoj_v.index(max(dmoj_v)))
peg_v.pop(peg_v.index(max(peg_v)))
# add to total speed and reset bike speed
total_speed += bike_speed
bike_speed = 0
x += 1
elif question == 2:
x, total_speed = 0,0
while x < num_people:
speeds = [max(dmoj_v), min(peg_v)]
bike_speed = max(speeds)
dmoj_v.pop(dmoj_v.index(max(dmoj_v)))
peg_v.pop(peg_v.index(min(peg_v)))
total_speed += bike_speed
bike_speed = 0
x += 1
# output results
print(total_speed)
| input_list = []
for i in range(int(6)):
input_list.append(input())
win_counter = 0
loss_counter = 0
for i in input_list:
if i == 'W':
win_counter += 1
else:
loss_counter += 1
if win_counter == 1 or win_counter == 2:
print('3')
elif win_counter == 3 or win_counter == 4:
print('2')
elif win_counter == 5 or win_counter == 6:
print('1')
else:
print('-1')
def row_sum(matrix, row_num):
sum = 0
for i in range(4):
sum += int(matrix[row_num][i])
return sum
def col_sum(matrix, col_num):
sum = 0
for i in range(4):
sum += int(matrix[i][col_num])
return sum
input_list = []
for i in range(int(4)):
input_list.append(input().split())
h_sum = 0
sum_row_1 = row_sum(input_list, 0)
sum_row_2 = row_sum(input_list, 1)
sum_row_3 = row_sum(input_list, 2)
sum_row_4 = row_sum(input_list, 3)
sum_col_1 = col_sum(input_list, 0)
sum_col_2 = col_sum(input_list, 1)
sum_col_3 = col_sum(input_list, 2)
sum_col_4 = col_sum(input_list, 3)
if sum_row_1 == sum_row_2 == sum_row_3 == sum_row_4 == sum_col_1 == sum_col_2 == sum_col_3 == sum_col_4:
print('MAGIC')
else:
print('NOT MAGIC')
S3
a = input()
def palindromes(word):
i = 0
j = len(word) - 1
if len(word) == 0:
return 0
while i != j and i + 1 != j:
if word[i] == word[j]:
i += 1
j -= 1
else:
return 0
if i + 1 == j:
if word[i] != word[j]:
return 0
return len(word)
result_num = 0
for i in range(len(a)):
for j in range(len(a), -1, -1):
word = a[i:j]
max_num = palindromes(word)
result_num = max(max_num, result_num)
print(result_num)
print(palindromes(a))
d_time = list(input())
del d_time[2]
x = 0
while x < len(d_time):
d_time[x] = int(d_time[x])
x += 1
ten = [1, 0, 0, 0]
time = 0
add_time = 1
while time != 120:
if d_time[1] >= 7 and d_time[1] <= 9 or d_time == ten:
rush_hour = True
else:
rush_hour = False
if rush_hour == True:
add_time = 0.5
else:
add_time = 1
if d_time[3] != 9 and d_time[1] != 4:
d_time[3] += 1
elif d_time[3] == 9 and d_time[2] != 5:
d_time[3] = 0
d_time[2] += 1
elif d_time[3] == 9 and d_time[2] == 5 and (d_time[1] != 9):
d_time[1] += 1
d_time[2] = 0
d_time[3] = 0
elif d_time[1] == 9 and d_time[2] == 5 and (d_time[3] == 9):
d_time[0] = 1
d_time[1] = 0
d_time[2] = 0
d_time[3] = 0
elif d_time[2] == 5 and d_time[3] == 9 and (d_time[0] == 1):
if d_time[1] != 9:
d_time[1] += 1
elif d_time[1] == 9:
d_time[0] = 2
d_time[1] = 0
d_time[2] = 0
d_time[3] = 0
elif d_time[0] == 2 and d_time[1] == 4:
d_time[0] = 0
d_time[1] = 0
d_time[2] = 0
d_time[3] = 1
time += add_time
print(d_time[0], d_time[1], ':', d_time[2], d_time[3])
question = int(input())
num_people = int(input())
dmoj_v = input().split()
peg_v = input().split()
for s in range(len(dmoj_v)):
dmoj_v[s] = int(dmoj_v[s])
for s in range(len(peg_v)):
peg_v[s] = int(peg_v[s])
if question == 1:
(x, total_speed) = (0, 0)
while x < num_people:
speeds = [max(dmoj_v), max(peg_v)]
bike_speed = max(speeds)
dmoj_v.pop(dmoj_v.index(max(dmoj_v)))
peg_v.pop(peg_v.index(max(peg_v)))
total_speed += bike_speed
bike_speed = 0
x += 1
elif question == 2:
(x, total_speed) = (0, 0)
while x < num_people:
speeds = [max(dmoj_v), min(peg_v)]
bike_speed = max(speeds)
dmoj_v.pop(dmoj_v.index(max(dmoj_v)))
peg_v.pop(peg_v.index(min(peg_v)))
total_speed += bike_speed
bike_speed = 0
x += 1
print(total_speed) |
"""
Given a list of possibly overlapping intervals, return a new list of
intervals where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should
return [(1, 3), (4, 10), (20, 25)].
Source: Daily Coding Problems (https://www.dailycodingproblem.com/)
"""
| """
Given a list of possibly overlapping intervals, return a new list of
intervals where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should
return [(1, 3), (4, 10), (20, 25)].
Source: Daily Coding Problems (https://www.dailycodingproblem.com/)
""" |
class Evaluator:
@staticmethod
def zip_evaluate(coefs, words):
if (len(coefs) != len(words)):
return -1
return sum([coeff * len(word) for (coeff, word)
in zip(coefs, words)])
@staticmethod
def enumerate_evaluate(coefs, words):
if (len(coefs) != len(words)):
return -1
return sum([coef * len(words[i]) for (i, coef) in enumerate(coefs)])
words = ["Le", "Lorem", "Ipsum", "est", "simple"]
coefs = [1.0, 2.0, 1.0, 4.0, 0.5]
print(Evaluator.zip_evaluate(coefs, words))
words = ["Le", "Lorem", "Ipsum", "est", "simple"]
coefs = [1.0, 2.0, 1.0, 4.0, 0.5]
print(Evaluator.enumerate_evaluate(coefs, words))
words = ["Le", "Lorem", "Ipsum", "n'", "est", "pas", "simple"]
coefs = [0.0, -1.0, 1.0, -12.0, 0.0, 42.42]
print(Evaluator.enumerate_evaluate(coefs, words))
| class Evaluator:
@staticmethod
def zip_evaluate(coefs, words):
if len(coefs) != len(words):
return -1
return sum([coeff * len(word) for (coeff, word) in zip(coefs, words)])
@staticmethod
def enumerate_evaluate(coefs, words):
if len(coefs) != len(words):
return -1
return sum([coef * len(words[i]) for (i, coef) in enumerate(coefs)])
words = ['Le', 'Lorem', 'Ipsum', 'est', 'simple']
coefs = [1.0, 2.0, 1.0, 4.0, 0.5]
print(Evaluator.zip_evaluate(coefs, words))
words = ['Le', 'Lorem', 'Ipsum', 'est', 'simple']
coefs = [1.0, 2.0, 1.0, 4.0, 0.5]
print(Evaluator.enumerate_evaluate(coefs, words))
words = ['Le', 'Lorem', 'Ipsum', "n'", 'est', 'pas', 'simple']
coefs = [0.0, -1.0, 1.0, -12.0, 0.0, 42.42]
print(Evaluator.enumerate_evaluate(coefs, words)) |
# You are given an array of desired filenames in the order of their creation.
# Since two files cannot have equal names, the one which comes later will have
# an addition to its name in a form of (k), where k is the smallest positive
# integer such that the obtained name is not used yet.
#
# Return an array of names that will be given to the files.
#
# Example
#
# For names = ["doc", "doc", "image", "doc(1)", "doc"], the output should be
# fileNaming(names) = ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"].
def fileNaming(names):
new_names = []
for name in names:
if name in new_names:
name = add_suffix(name, new_names)
new_names.append(name)
return new_names
def add_suffix(name, new_names):
count = 1
new_name = name + "(" + str(count) + ")"
while new_name in new_names:
count += 1
new_name = name + "(" + str(count) + ")"
return new_name
print(fileNaming(["doc", "doc", "image", "doc(1)", "doc"]))
| def file_naming(names):
new_names = []
for name in names:
if name in new_names:
name = add_suffix(name, new_names)
new_names.append(name)
return new_names
def add_suffix(name, new_names):
count = 1
new_name = name + '(' + str(count) + ')'
while new_name in new_names:
count += 1
new_name = name + '(' + str(count) + ')'
return new_name
print(file_naming(['doc', 'doc', 'image', 'doc(1)', 'doc'])) |
load("@dwtj_rules_markdown//markdown:defs.bzl", "markdown_library")
def index_md(name = "index_md"):
markdown_library(
name = name,
srcs = ["INDEX.md"],
)
| load('@dwtj_rules_markdown//markdown:defs.bzl', 'markdown_library')
def index_md(name='index_md'):
markdown_library(name=name, srcs=['INDEX.md']) |
length_check_fields=['reset_pc', 'physical_addr_size']
bsc_cmd = '''bsc -u -verilog -elab -vdir {0} -bdir {1} -info-dir {1} \
+RTS -K40000M -RTS -check-assert -keep-fires \
-opt-undetermined-vals -remove-false-rules -remove-empty-rules \
-remove-starved-rules -remove-dollar -unspecified-to X -show-schedule \
-show-module-use {2}'''
bsc_defines = ''
verilator_cmd = ''' -O3 -LDFLAGS "-static" --x-assign fast \
--x-initial fast --noassert sim_main.cpp --bbox-sys -Wno-STMTDLY \
-Wno-UNOPTFLAT -Wno-WIDTH -Wno-lint -Wno-COMBDLY -Wno-INITIALDLY \
--autoflush {0} {1} --threads {2} -DBSV_RESET_FIFO_HEAD \
-DBSV_RESET_FIFO_ARRAY --output-split 20000 \
--output-split-ctrace 10000'''
makefile_temp='''
VERILOGDIR:={0}
BSVBUILDDIR:={1}
BSVOUTDIR:={2}
BSCCMD:={3}
BSC_DEFINES:={4}
BSVINCDIR:={5}
BS_VERILOG_LIB:={6}lib/Verilog/
TOP_MODULE:={7}
TOP_DIR:={8}
TOP_FILE:={9}
XLEN:={10}
TOP_BIN={11}
ISA={12}
FPGA=xc7a100tcsg324-1
SYNTHTOP=fpga_top
BSCAN2E=enable
include depends.mk
'''
dependency_yaml='''
c-class:
url: https://gitlab.com/shaktiproject/cores/c-class
checkout: 1.9.6
caches_mmu:
url: https://gitlab.com/shaktiproject/uncore/caches_mmu
checkout: 8.2.1
common_bsv:
url: https://gitlab.com/shaktiproject/common_bsv
checkout: master
fabrics:
url: https://gitlab.com/shaktiproject/uncore/fabrics
checkout: 1.2.0
common_verilog:
url: https://gitlab.com/shaktiproject/common_verilog
checkout: master
patch:
devices:
url: https://gitlab.com/shaktiproject/uncore/devices
checkout: 6.3.0
'''
| length_check_fields = ['reset_pc', 'physical_addr_size']
bsc_cmd = 'bsc -u -verilog -elab -vdir {0} -bdir {1} -info-dir {1} +RTS -K40000M -RTS -check-assert -keep-fires -opt-undetermined-vals -remove-false-rules -remove-empty-rules -remove-starved-rules -remove-dollar -unspecified-to X -show-schedule -show-module-use {2}'
bsc_defines = ''
verilator_cmd = ' -O3 -LDFLAGS "-static" --x-assign fast --x-initial fast --noassert sim_main.cpp --bbox-sys -Wno-STMTDLY -Wno-UNOPTFLAT -Wno-WIDTH -Wno-lint -Wno-COMBDLY -Wno-INITIALDLY --autoflush {0} {1} --threads {2} -DBSV_RESET_FIFO_HEAD -DBSV_RESET_FIFO_ARRAY --output-split 20000 --output-split-ctrace 10000'
makefile_temp = '\nVERILOGDIR:={0}\n\nBSVBUILDDIR:={1}\n\nBSVOUTDIR:={2}\n\nBSCCMD:={3}\n\nBSC_DEFINES:={4}\n\nBSVINCDIR:={5}\n\nBS_VERILOG_LIB:={6}lib/Verilog/\n\nTOP_MODULE:={7}\n\nTOP_DIR:={8}\n\nTOP_FILE:={9}\n\nXLEN:={10}\n\nTOP_BIN={11}\n\nISA={12}\n\nFPGA=xc7a100tcsg324-1\n\nSYNTHTOP=fpga_top\n\nBSCAN2E=enable\n\ninclude depends.mk\n'
dependency_yaml = '\nc-class:\n url: https://gitlab.com/shaktiproject/cores/c-class\n checkout: 1.9.6\ncaches_mmu:\n url: https://gitlab.com/shaktiproject/uncore/caches_mmu\n checkout: 8.2.1\ncommon_bsv:\n url: https://gitlab.com/shaktiproject/common_bsv\n checkout: master\nfabrics:\n url: https://gitlab.com/shaktiproject/uncore/fabrics\n checkout: 1.2.0\ncommon_verilog:\n url: https://gitlab.com/shaktiproject/common_verilog\n checkout: master\n patch:\ndevices:\n url: https://gitlab.com/shaktiproject/uncore/devices\n checkout: 6.3.0\n' |
BOT_NAME = 'naver_movie'
SPIDER_MODULES = ['naver_movie.spiders']
NEWSPIDER_MODULE = 'naver_movie.spiders'
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 2
COOKIES_ENABLED = True
DEFAULT_REQUEST_HEADERS = {
"Referer": "https://movie.naver.com/"
}
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
'scrapy.downloadermiddlewares.retry.RetryMiddleware': None,
'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400,
'scrapy_fake_useragent.middleware.RetryUserAgentMiddleware': 401,
}
RETRY_ENABLED = True
RETRY_TIMES = 2
ITEM_PIPELINES = {
'naver_movie.pipelines.NaverMoviePipeline': 300,
}
| bot_name = 'naver_movie'
spider_modules = ['naver_movie.spiders']
newspider_module = 'naver_movie.spiders'
robotstxt_obey = False
download_delay = 2
cookies_enabled = True
default_request_headers = {'Referer': 'https://movie.naver.com/'}
downloader_middlewares = {'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, 'scrapy.downloadermiddlewares.retry.RetryMiddleware': None, 'scrapy_fake_useragent.middleware.RandomUserAgentMiddleware': 400, 'scrapy_fake_useragent.middleware.RetryUserAgentMiddleware': 401}
retry_enabled = True
retry_times = 2
item_pipelines = {'naver_movie.pipelines.NaverMoviePipeline': 300} |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
# print(head)
slow, fast = head, head
pre = None
while fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
def helper(node):
if not node.next: return node
last = helper(node.next)
node.next.next = node
node.next = None
return last
tmp = head
p1, last = head, helper(slow)
p2 = last
while p1 and p2:
if p1.val == p2.val:
p1 = p1.next
p2 = p2.next
else:
pre.next = helper(last)
return False
pre.next = helper(last)
# print(head)
return True
| class Solution:
def is_palindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
(slow, fast) = (head, head)
pre = None
while fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
def helper(node):
if not node.next:
return node
last = helper(node.next)
node.next.next = node
node.next = None
return last
tmp = head
(p1, last) = (head, helper(slow))
p2 = last
while p1 and p2:
if p1.val == p2.val:
p1 = p1.next
p2 = p2.next
else:
pre.next = helper(last)
return False
pre.next = helper(last)
return True |
#
# @lc app=leetcode id=557 lang=python
#
# [557] Reverse Words in a String III
#
# https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
#
# algorithms
# Easy (63.15%)
# Likes: 624
# Dislikes: 67
# Total Accepted: 127.4K
# Total Submissions: 198.3K
# Testcase Example: `"Let's take LeetCode contest"`
#
# Given a string, you need to reverse the order of characters in each word
# within a sentence while still preserving whitespace and initial word order.
#
# Example 1:
#
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
#
#
#
# Note:
# In the string, each word is separated by single space and there will not be
# any extra space in the string.
#
#
class Solution(object):
def _reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
sl = s.split()
ls = []
for l in sl:
ls.append(''.join(list(l)[::-1]))
return ' '.join(ls)
def __reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
sl = s.split()
for index, value in enumerate(sl):
sl[index] = ''.join(list(value)[::-1])
return ' '.join(sl)
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(s.split()[::-1])[::-1]
| class Solution(object):
def _reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
sl = s.split()
ls = []
for l in sl:
ls.append(''.join(list(l)[::-1]))
return ' '.join(ls)
def __reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
sl = s.split()
for (index, value) in enumerate(sl):
sl[index] = ''.join(list(value)[::-1])
return ' '.join(sl)
def reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(s.split()[::-1])[::-1] |
n = float(input())
whole = int(n)
fractional = int(round((n % 1), 2) * 100)
print(whole, fractional)
| n = float(input())
whole = int(n)
fractional = int(round(n % 1, 2) * 100)
print(whole, fractional) |
class Spam(object):
def __init__(self, key, value):
self.list_ = [value]
self.dict_ = {key : value}
self.list_.append(value)
self.dict_[key] = value
print(f'List: {self.list_}')
print(f'Dict: {self.dict_}')
Spam('Key 1', 'Value 1')
Spam('Key 2', 'Value 2')
| class Spam(object):
def __init__(self, key, value):
self.list_ = [value]
self.dict_ = {key: value}
self.list_.append(value)
self.dict_[key] = value
print(f'List: {self.list_}')
print(f'Dict: {self.dict_}')
spam('Key 1', 'Value 1')
spam('Key 2', 'Value 2') |
lista = [5,7,9,2,4,3,1,6,8]
comparaciones = 0
for i in range(len(lista) -1): #recorre la lista
for j in range(len(lista)-1): #sirve para comparar los elementos de la lista
#print('Comparando: ' , lista[j], "con ", lista[j+1])
if(lista[j] > lista[j+1]):
#lista[j], lista[j+1] = lista[j+1] , lista[j]
comparaciones += 1
temporal = lista[j]
lista[j] = lista[j+1]
lista[j+1] = temporal
#print("Intecambiando: ", lista[j], "por ", lista[j+1])
print(lista)
print(lista)
#OPTIMIZAR CODIGO
#CONCENTINELA
lista = [5,7,9,2,4,3,1,6,8]
comparaciones = 0
hay_cambios = True
while hay_cambios: #recorre la lista
hay_cambios = False
for j in range(len(lista)-1): #sirve para comparar los elementos de la lista
#print('Comparando: ' , lista[j], "con ", lista[j+1])
comparaciones += 1
if(lista[j] > lista[j+1]):
#lista[j], lista[j+1] = lista[j+1] , lista[j]
temporal = lista[j]
lista[j] = lista[j+1]
lista[j+1] = temporal
hay_cambios = True
#print("Intecambiando: ", lista[j], "por ", lista[j+1])
print(lista)
print(comparaciones)
lista = [5,7,9,2,4,3,1,6,8]
comparaciones = 0
for i in range(len(lista) -1): #recorre la lista
for j in range(len(lista) - i -1): #sirve para comparar los elementos de la lista
#print('Comparando: ' , lista[j], "con ", lista[j+1])
if(lista[j] > lista[j+1]):
#lista[j], lista[j+1] = lista[j+1] , lista[j]
comparaciones += 1
temporal = lista[j]
lista[j] = lista[j+1]
lista[j+1] = temporal
print(lista)
#print("Intecambiando: ", lista[j], "por ", lista[j+1])
print(lista)
print(comparaciones)
lista = [5,7,9,2,4,3,1,6,8]
comparaciones = 0
hay_cambios = True
i = 0
while hay_cambios and i < len(lista)-1: #recorre la lista
hay_cambios = False
for j in range(len(lista) -i -1): #sirve para comparar los elementos de la lista
#print('Comparando: ' , lista[j], "con ", lista[j+1])
comparaciones += 1
if(lista[j] > lista[j+1]):
#lista[j], lista[j+1] = lista[j+1] , lista[j]
temporal = lista[j]
lista[j] = lista[j+1]
lista[j+1] = temporal
hay_cambios = True
#print("Intecambiando: ", lista[j], "por ", lista[j+1])
i +=1
print(lista)
print(comparaciones) | lista = [5, 7, 9, 2, 4, 3, 1, 6, 8]
comparaciones = 0
for i in range(len(lista) - 1):
for j in range(len(lista) - 1):
if lista[j] > lista[j + 1]:
comparaciones += 1
temporal = lista[j]
lista[j] = lista[j + 1]
lista[j + 1] = temporal
print(lista)
print(lista)
lista = [5, 7, 9, 2, 4, 3, 1, 6, 8]
comparaciones = 0
hay_cambios = True
while hay_cambios:
hay_cambios = False
for j in range(len(lista) - 1):
comparaciones += 1
if lista[j] > lista[j + 1]:
temporal = lista[j]
lista[j] = lista[j + 1]
lista[j + 1] = temporal
hay_cambios = True
print(lista)
print(comparaciones)
lista = [5, 7, 9, 2, 4, 3, 1, 6, 8]
comparaciones = 0
for i in range(len(lista) - 1):
for j in range(len(lista) - i - 1):
if lista[j] > lista[j + 1]:
comparaciones += 1
temporal = lista[j]
lista[j] = lista[j + 1]
lista[j + 1] = temporal
print(lista)
print(lista)
print(comparaciones)
lista = [5, 7, 9, 2, 4, 3, 1, 6, 8]
comparaciones = 0
hay_cambios = True
i = 0
while hay_cambios and i < len(lista) - 1:
hay_cambios = False
for j in range(len(lista) - i - 1):
comparaciones += 1
if lista[j] > lista[j + 1]:
temporal = lista[j]
lista[j] = lista[j + 1]
lista[j + 1] = temporal
hay_cambios = True
i += 1
print(lista)
print(comparaciones) |
#
# PySNMP MIB module SW-TRUNK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-TRUNK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:05:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
enterprises, Gauge32, ObjectIdentity, Integer32, Counter32, ModuleIdentity, Bits, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, NotificationType, Unsigned32, MibIdentifier, iso, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "Gauge32", "ObjectIdentity", "Integer32", "Counter32", "ModuleIdentity", "Bits", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "NotificationType", "Unsigned32", "MibIdentifier", "iso", "Counter64")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class TrunkSetList(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 1)
fixedLength = 1
marconi = MibIdentifier((1, 3, 6, 1, 4, 1, 326))
systems = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2))
external = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20))
dlink = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1))
dlinkcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 1))
golf = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2))
golfproducts = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1))
es2000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1, 3))
golfcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2))
marconi_mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2)).setLabel("marconi-mgmt")
es2000Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28))
swL2Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2))
swPortTrunk = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6))
swPortTrunkCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1), )
if mibBuilder.loadTexts: swPortTrunkCtrlTable.setStatus('mandatory')
swPortTrunkCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1), ).setIndexNames((0, "SW-TRUNK-MIB", "swPortTrunkCtrlIndex"))
if mibBuilder.loadTexts: swPortTrunkCtrlEntry.setStatus('mandatory')
swPortTrunkCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortTrunkCtrlIndex.setStatus('mandatory')
swPortTrunkCtrlAnchorPort = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortTrunkCtrlAnchorPort.setStatus('mandatory')
swPortTrunkCtrlMasterPort = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortTrunkCtrlMasterPort.setStatus('mandatory')
swPortTrunkCtrlName = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortTrunkCtrlName.setStatus('mandatory')
swPortTrunkCtrlMember = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 5), TrunkSetList()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortTrunkCtrlMember.setStatus('mandatory')
swPortTrunkCtrlState = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("enabled", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortTrunkCtrlState.setStatus('mandatory')
swPortTrunkMemberTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2), )
if mibBuilder.loadTexts: swPortTrunkMemberTable.setStatus('mandatory')
swPortTrunkMemberEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1), ).setIndexNames((0, "SW-TRUNK-MIB", "swPortTrunkMemberIndex"), (0, "SW-TRUNK-MIB", "swPortTrunkMemberUnitIndex"), (0, "SW-TRUNK-MIB", "swPortTrunkMemberModuleIndex"), (0, "SW-TRUNK-MIB", "swPortTrunkMemberPortIndex"))
if mibBuilder.loadTexts: swPortTrunkMemberEntry.setStatus('mandatory')
swPortTrunkMemberIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortTrunkMemberIndex.setStatus('mandatory')
swPortTrunkMemberUnitIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortTrunkMemberUnitIndex.setStatus('mandatory')
swPortTrunkMemberModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortTrunkMemberModuleIndex.setStatus('mandatory')
swPortTrunkMemberPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortTrunkMemberPortIndex.setStatus('mandatory')
mibBuilder.exportSymbols("SW-TRUNK-MIB", TrunkSetList=TrunkSetList, swPortTrunkMemberIndex=swPortTrunkMemberIndex, swPortTrunkCtrlAnchorPort=swPortTrunkCtrlAnchorPort, marconi=marconi, swPortTrunkCtrlName=swPortTrunkCtrlName, swPortTrunkCtrlTable=swPortTrunkCtrlTable, dlinkcommon=dlinkcommon, external=external, swPortTrunkCtrlIndex=swPortTrunkCtrlIndex, swPortTrunkMemberPortIndex=swPortTrunkMemberPortIndex, swPortTrunkMemberUnitIndex=swPortTrunkMemberUnitIndex, systems=systems, dlink=dlink, swPortTrunkMemberModuleIndex=swPortTrunkMemberModuleIndex, swPortTrunkCtrlEntry=swPortTrunkCtrlEntry, golfcommon=golfcommon, swPortTrunkMemberEntry=swPortTrunkMemberEntry, swPortTrunkCtrlMember=swPortTrunkCtrlMember, es2000Mgmt=es2000Mgmt, golf=golf, swPortTrunkMemberTable=swPortTrunkMemberTable, swPortTrunk=swPortTrunk, swPortTrunkCtrlState=swPortTrunkCtrlState, swPortTrunkCtrlMasterPort=swPortTrunkCtrlMasterPort, marconi_mgmt=marconi_mgmt, swL2Mgmt=swL2Mgmt, es2000=es2000, golfproducts=golfproducts)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, single_value_constraint, constraints_union, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(enterprises, gauge32, object_identity, integer32, counter32, module_identity, bits, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, notification_type, unsigned32, mib_identifier, iso, counter64) = mibBuilder.importSymbols('SNMPv2-SMI', 'enterprises', 'Gauge32', 'ObjectIdentity', 'Integer32', 'Counter32', 'ModuleIdentity', 'Bits', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'NotificationType', 'Unsigned32', 'MibIdentifier', 'iso', 'Counter64')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
class Trunksetlist(OctetString):
subtype_spec = OctetString.subtypeSpec + value_size_constraint(1, 1)
fixed_length = 1
marconi = mib_identifier((1, 3, 6, 1, 4, 1, 326))
systems = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2))
external = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20))
dlink = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1))
dlinkcommon = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 1))
golf = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2))
golfproducts = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1))
es2000 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1, 3))
golfcommon = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2))
marconi_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2)).setLabel('marconi-mgmt')
es2000_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28))
sw_l2_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2))
sw_port_trunk = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6))
sw_port_trunk_ctrl_table = mib_table((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1))
if mibBuilder.loadTexts:
swPortTrunkCtrlTable.setStatus('mandatory')
sw_port_trunk_ctrl_entry = mib_table_row((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1)).setIndexNames((0, 'SW-TRUNK-MIB', 'swPortTrunkCtrlIndex'))
if mibBuilder.loadTexts:
swPortTrunkCtrlEntry.setStatus('mandatory')
sw_port_trunk_ctrl_index = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortTrunkCtrlIndex.setStatus('mandatory')
sw_port_trunk_ctrl_anchor_port = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 2), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swPortTrunkCtrlAnchorPort.setStatus('mandatory')
sw_port_trunk_ctrl_master_port = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 3), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortTrunkCtrlMasterPort.setStatus('mandatory')
sw_port_trunk_ctrl_name = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swPortTrunkCtrlName.setStatus('mandatory')
sw_port_trunk_ctrl_member = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 5), trunk_set_list()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swPortTrunkCtrlMember.setStatus('mandatory')
sw_port_trunk_ctrl_state = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('other', 1), ('disabled', 2), ('enabled', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swPortTrunkCtrlState.setStatus('mandatory')
sw_port_trunk_member_table = mib_table((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2))
if mibBuilder.loadTexts:
swPortTrunkMemberTable.setStatus('mandatory')
sw_port_trunk_member_entry = mib_table_row((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1)).setIndexNames((0, 'SW-TRUNK-MIB', 'swPortTrunkMemberIndex'), (0, 'SW-TRUNK-MIB', 'swPortTrunkMemberUnitIndex'), (0, 'SW-TRUNK-MIB', 'swPortTrunkMemberModuleIndex'), (0, 'SW-TRUNK-MIB', 'swPortTrunkMemberPortIndex'))
if mibBuilder.loadTexts:
swPortTrunkMemberEntry.setStatus('mandatory')
sw_port_trunk_member_index = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortTrunkMemberIndex.setStatus('mandatory')
sw_port_trunk_member_unit_index = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortTrunkMemberUnitIndex.setStatus('mandatory')
sw_port_trunk_member_module_index = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 3), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortTrunkMemberModuleIndex.setStatus('mandatory')
sw_port_trunk_member_port_index = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 4), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortTrunkMemberPortIndex.setStatus('mandatory')
mibBuilder.exportSymbols('SW-TRUNK-MIB', TrunkSetList=TrunkSetList, swPortTrunkMemberIndex=swPortTrunkMemberIndex, swPortTrunkCtrlAnchorPort=swPortTrunkCtrlAnchorPort, marconi=marconi, swPortTrunkCtrlName=swPortTrunkCtrlName, swPortTrunkCtrlTable=swPortTrunkCtrlTable, dlinkcommon=dlinkcommon, external=external, swPortTrunkCtrlIndex=swPortTrunkCtrlIndex, swPortTrunkMemberPortIndex=swPortTrunkMemberPortIndex, swPortTrunkMemberUnitIndex=swPortTrunkMemberUnitIndex, systems=systems, dlink=dlink, swPortTrunkMemberModuleIndex=swPortTrunkMemberModuleIndex, swPortTrunkCtrlEntry=swPortTrunkCtrlEntry, golfcommon=golfcommon, swPortTrunkMemberEntry=swPortTrunkMemberEntry, swPortTrunkCtrlMember=swPortTrunkCtrlMember, es2000Mgmt=es2000Mgmt, golf=golf, swPortTrunkMemberTable=swPortTrunkMemberTable, swPortTrunk=swPortTrunk, swPortTrunkCtrlState=swPortTrunkCtrlState, swPortTrunkCtrlMasterPort=swPortTrunkCtrlMasterPort, marconi_mgmt=marconi_mgmt, swL2Mgmt=swL2Mgmt, es2000=es2000, golfproducts=golfproducts) |
class Twitter():
Consumer_Key = ''
Consumer_Secret = ''
Access_Token = ''
Access_Token_Secret = ''
CONNECTION_STRING = "sqlite:///Twitter.db"
LANG = ["en"]
| class Twitter:
consumer__key = ''
consumer__secret = ''
access__token = ''
access__token__secret = ''
connection_string = 'sqlite:///Twitter.db'
lang = ['en'] |
feature_types = {
# features with continuous numeric values
"continuous": [
"number_diagnoses",
"time_in_hospital",
"number_inpatient",
"number_emergency",
"num_procedures",
"num_medications",
"num_lab_procedures"],
# features which describe buckets of a continuous-valued feature
"range": ["age", "weight"],
# features which take one of two or more non-continuous values
"categorical": [
"diabetesMed",
"chlorpropamide",
"repaglinide",
"medical_specialty",
"rosiglitazone",
"miglitol",
"glipizide",
"acetohexamide",
"admission_source_id",
"glipizide-metformin",
"glyburide",
"metformin",
"tolbutamide",
"pioglitazone",
"glimepiride-pioglitazone",
"glimepiride",
"glyburide-metformin",
"A1Cresult",
"troglitazone",
"metformin-rosiglitazone",
"max_glu_serum",
"acarbose",
"metformin-pioglitazone",
"payer_code",
"discharge_disposition_id",
"change",
"gender",
"nateglinide",
"tolazamide",
"race",
"number_outpatient",
"insulin",
"admission_type_id",
"diag_1", "diag_2", "diag_3"],
# features which are either unique or constant for all samples
"constant": ["patient_nbr", "encounter_id", "examide", "citoglipton"]}
| feature_types = {'continuous': ['number_diagnoses', 'time_in_hospital', 'number_inpatient', 'number_emergency', 'num_procedures', 'num_medications', 'num_lab_procedures'], 'range': ['age', 'weight'], 'categorical': ['diabetesMed', 'chlorpropamide', 'repaglinide', 'medical_specialty', 'rosiglitazone', 'miglitol', 'glipizide', 'acetohexamide', 'admission_source_id', 'glipizide-metformin', 'glyburide', 'metformin', 'tolbutamide', 'pioglitazone', 'glimepiride-pioglitazone', 'glimepiride', 'glyburide-metformin', 'A1Cresult', 'troglitazone', 'metformin-rosiglitazone', 'max_glu_serum', 'acarbose', 'metformin-pioglitazone', 'payer_code', 'discharge_disposition_id', 'change', 'gender', 'nateglinide', 'tolazamide', 'race', 'number_outpatient', 'insulin', 'admission_type_id', 'diag_1', 'diag_2', 'diag_3'], 'constant': ['patient_nbr', 'encounter_id', 'examide', 'citoglipton']} |
def main() :
#Create a set
lstOrganizations = {"sharjeelswork", "Fiserv", "R Systems"}
print(lstOrganizations) # Sets are unordered, so the items will appear in a random order.
"""Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword."""
#Loop through the set, and print the values
for organization in lstOrganizations:
print(organization)
#Check if "banana" is present in the set
print("gopesh" in lstOrganizations)
"""Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method."""
lstOrganizations.add("nashit")
print(lstOrganizations)
lstOrganizations.update(["Edynamic", "Sitecore"])
print(lstOrganizations)
#Get the number of items in a set
print(len(lstOrganizations))
#Remove Item : To remove an item in a set, use the remove(), or the discard() method.
lstOrganizations.remove("nashit") #If the item to remove does not exist, remove() will raise an error.
print(lstOrganizations)
#To remove an item, use discard
lstOrganizations.discard("Sitecore") #If the item to remove does not exist, discard() will NOT raise an error.
print(lstOrganizations)
"""You can also use the pop(), method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.
The return value of the pop() method is the removed item."""
removedItem = lstOrganizations.pop()
print(removedItem)
print(lstOrganizations)
#The clear() method empties the set
lstOrganizations.clear()
#The del keyword will delete the set completely
del lstOrganizations
#The set() Constructor : It is also possible to use the set() constructor to make a set.
lstOrganizations = set(("sharjeelswork", "Fiserv", "R Systems")) # note the double round-brackets
print(lstOrganizations)
main()
| def main():
lst_organizations = {'sharjeelswork', 'Fiserv', 'R Systems'}
print(lstOrganizations)
'Access Items\n\tYou cannot access items in a set by referring to an index, since sets are unordered the items has no index.\n\tBut you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.'
for organization in lstOrganizations:
print(organization)
print('gopesh' in lstOrganizations)
'Change Items\n\tOnce a set is created, you cannot change its items, but you can add new items.\n\tAdd Items\n\t\tTo add one item to a set use the add() method.\n\t\tTo add more than one item to a set use the update() method.'
lstOrganizations.add('nashit')
print(lstOrganizations)
lstOrganizations.update(['Edynamic', 'Sitecore'])
print(lstOrganizations)
print(len(lstOrganizations))
lstOrganizations.remove('nashit')
print(lstOrganizations)
lstOrganizations.discard('Sitecore')
print(lstOrganizations)
'You can also use the pop(), method to remove an item, but this method will remove the last item. \n\tRemember that sets are unordered, so you will not know what item that gets removed. \n\tThe return value of the pop() method is the removed item.'
removed_item = lstOrganizations.pop()
print(removedItem)
print(lstOrganizations)
lstOrganizations.clear()
del lstOrganizations
lst_organizations = set(('sharjeelswork', 'Fiserv', 'R Systems'))
print(lstOrganizations)
main() |
while True:
try:
input()
alice = set(input().split())
beatriz = set(input().split())
repeticoes = [1 for carta in alice if carta in beatriz]
print(min([len(alice), len(beatriz)]) - len(repeticoes))
except EOFError:
break
| while True:
try:
input()
alice = set(input().split())
beatriz = set(input().split())
repeticoes = [1 for carta in alice if carta in beatriz]
print(min([len(alice), len(beatriz)]) - len(repeticoes))
except EOFError:
break |
def square(a):
return(a*a)
# a=int(input("enter the number"))
# square(a)
s=[2,3,4,5,6,7,8,9,10]
print(list(map(square,s)))
| def square(a):
return a * a
s = [2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(map(square, s))) |
"""
@file
@brief Exception for Mokadi.
"""
class MokadiException(Exception):
"""
Mokadi exception.
"""
pass # pylint: disable=W0107
class CognitiveException(Exception):
"""
Failure when calling the API.
"""
pass # pylint: disable=W0107
class WikipediaException(Exception):
"""
Issue with :epkg:`wikipedia`.
"""
pass # pylint: disable=W0107
class MokadiAuthentification(Exception):
"""
Issue with authentification.
"""
pass # pylint: disable=W0107
| """
@file
@brief Exception for Mokadi.
"""
class Mokadiexception(Exception):
"""
Mokadi exception.
"""
pass
class Cognitiveexception(Exception):
"""
Failure when calling the API.
"""
pass
class Wikipediaexception(Exception):
"""
Issue with :epkg:`wikipedia`.
"""
pass
class Mokadiauthentification(Exception):
"""
Issue with authentification.
"""
pass |
features = [
"mtarg1",
"mtarg2",
"mtarg3",
"roll",
"pitch",
"LACCX",
"LACCY",
"LACCZ",
"GYROX",
"GYROY",
"SC1I",
"SC2I",
"SC3I",
"BT1I",
"BT2I",
"vout",
"iout",
"cpuUsage",
]
fault_features = ["fault", "fault_type", "fault_value", "fault_duration"]
| features = ['mtarg1', 'mtarg2', 'mtarg3', 'roll', 'pitch', 'LACCX', 'LACCY', 'LACCZ', 'GYROX', 'GYROY', 'SC1I', 'SC2I', 'SC3I', 'BT1I', 'BT2I', 'vout', 'iout', 'cpuUsage']
fault_features = ['fault', 'fault_type', 'fault_value', 'fault_duration'] |
READ_ME ="""
INDEXICAL is designed to assist in the creation of book indexes.
It offers the following functionality:
(1) Analyze a readable PDF, extracting capitalized phrases, italicized phrases,
phrases in double quotation marks, and phrases surrounding by parentheses.
(2) Filter through the results of (1) to generate a list of proper names and titles,
correlating the latter to the former, while defining SUBHEADINGS, and attaching
optional SEARCH PHRASES to HEADINGS and SUBHEADINGS, OR A LIST OF THE PAGES
in which the ENTRY is found.
(3) Run INDIVIDUAL searches on the interpreted PDF.
SEARCHES allow unlimited logical complexity, and can be run by PAGE, SENTENCE,
or for LITERAL PHRASES over PAGES, DESCRIMINATING BY NUMBER of APPEARANCE for
LITERAL SEARCHES and PAGES OF APPEARANCE for all searches.
(4) READ in PROPER NAMES, TITLES, and CONCEPTS from an EXCEL FILE.
(5) RUN individual searches over a group of entries, and paste the results back
into an EXCEL FILE, including the properly formatted results of the search.
(6) GENERATE an INDEX from all terms, using, in each case, either the an automatically
generates SEARCH PHRASE, the optional preset SEARCH PHRASE, or the
pre-determined PAGES.
(7) FORMAT THE INDEX, FOLLOWING THE SPECIFICATIONS for ALPHABETIZING and PAGE RANGE DISPLAY
of the CHICAGO MANUAL OF SYLE
(8) GENERATE a REVERSE INDEX from a given INDEX.
(9) SCROLL THROUGH PAGES OF THE TEXT, SHOWING THE INDEXED TERMS for EACH PAGE,
and identifying INDEXED TERMS that may not match the PAGE.
"""
| read_me = '\nINDEXICAL is designed to assist in the creation of book indexes.\n\nIt offers the following functionality:\n\n(1) Analyze a readable PDF, extracting capitalized phrases, italicized phrases,\nphrases in double quotation marks, and phrases surrounding by parentheses.\n\n(2) Filter through the results of (1) to generate a list of proper names and titles,\ncorrelating the latter to the former, while defining SUBHEADINGS, and attaching\noptional SEARCH PHRASES to HEADINGS and SUBHEADINGS, OR A LIST OF THE PAGES\nin which the ENTRY is found.\n\n(3) Run INDIVIDUAL searches on the interpreted PDF.\nSEARCHES allow unlimited logical complexity, and can be run by PAGE, SENTENCE,\nor for LITERAL PHRASES over PAGES, DESCRIMINATING BY NUMBER of APPEARANCE for\nLITERAL SEARCHES and PAGES OF APPEARANCE for all searches.\n\n(4) READ in PROPER NAMES, TITLES, and CONCEPTS from an EXCEL FILE.\n\n(5) RUN individual searches over a group of entries, and paste the results back\ninto an EXCEL FILE, including the properly formatted results of the search.\n\n(6) GENERATE an INDEX from all terms, using, in each case, either the an automatically\ngenerates SEARCH PHRASE, the optional preset SEARCH PHRASE, or the\npre-determined PAGES.\n\n(7) FORMAT THE INDEX, FOLLOWING THE SPECIFICATIONS for ALPHABETIZING and PAGE RANGE DISPLAY\nof the CHICAGO MANUAL OF SYLE \n\n(8) GENERATE a REVERSE INDEX from a given INDEX.\n\n(9) SCROLL THROUGH PAGES OF THE TEXT, SHOWING THE INDEXED TERMS for EACH PAGE,\nand identifying INDEXED TERMS that may not match the PAGE.\n' |
"""Implements a class for Latin Square puzzles.
A Latin Square is a square grid of numbers from 1..N, where a number may not
be repeated in the same row or column. Such squares form the basis of puzzles
like Sudoku, Kenken(tm), and their variants.
Classes:
LatinSquare: Implements a square puzzle constrained by not repeating
values in the same row or column.
Functions:
build_empty_grid: Build a 2D array (list of lists) for puzzle.
char2int: Convert bewteen character and integer representation of a cell value.
int2char: Reverse of char2int.
count_clues: Given a string or 2D array representing a puzzle, return
the number of starting clues in the puzzle.
from_string: Given a string representing a puzzle, return the 2D array
equivalent. All class methods expect the array version.
"""
DEFAULT_PUZZLE_SIZE = 9
EMPTY_CELL = None
# Have only tested up to 25x25 so set that max size here
# higher values may work but aren't tested
MAX_PUZZLE_SIZE = 25
MIN_PUZZLE_SIZE = 1
MIN_CELL_VALUE = 1 # 0 evals to False so can be confused with EMPTY_CELL
CELL_VALUES = "123456789ABCDEFGHIJKLMNOP"
assert MAX_PUZZLE_SIZE == len(CELL_VALUES)
def build_empty_grid(grid_size):
"""Builds a 2D array grid_size * grid_size, each cell element is None."""
assert MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE
ret = [[] for x in range(grid_size)]
for x in range(grid_size):
ret[x] = [EMPTY_CELL for y in range(grid_size)]
return ret
def char2int(char):
"""Converts character char to an int representation."""
if char in (".", "0"):
return EMPTY_CELL
return CELL_VALUES.index(char) + 1
def int2char(value):
"""Converts back from an int value to character value for a cell."""
if not value:
return "."
return CELL_VALUES[value - 1]
def count_clues(puzzle_grid):
"""Counts clues in a puzzle_grid, which can be a list of lists or string."""
if isinstance(puzzle_grid, list):
return sum([1 for sublist in puzzle_grid for i in sublist if i])
return len(puzzle_grid) - puzzle_grid.count(".")
def from_string(puzzle_string):
"""Takes a string and converts it to a list of lists of integers.
Puzzles are expected to be 2D arrays of ints, but it's convenient to store
test data as strings (e.g. '89.4...5614.35..9.......8..9.....'). So this
will split a string (using period for "empty cell") and return the 2D array.
Args:
puzzle_string: A string with 1 character per cell. Use uppercase letters
for integer values >= 10 (A=10; B=11; etc). Trailing blanks are
stripped.
Returns:
A list of lists of ints.
Raises:
ValueError: puzzle_string length is not a square (e.g. 4, 9, 16, 25);
or a character value in string is out of range.
"""
s = puzzle_string.rstrip()
grid_size = int(len(s) ** (1 / 2))
if not MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE:
raise ValueError(f"puzzle_string {grid_size}x{grid_size} is out of range")
if grid_size ** 2 != len(s):
raise ValueError(f"puzzle_string {grid_size}x{grid_size} is not a square")
ret = build_empty_grid(grid_size)
for i, ch in enumerate(s):
v = char2int(ch)
if v and MIN_CELL_VALUE <= v <= grid_size:
ret[i // grid_size][i % grid_size] = v
elif v:
raise ValueError(f"Cell value {v} at {i} out of range [1:{grid_size}]")
return ret
class LatinSquare:
"""Implements a Latin Square "puzzle".
A Latin Square is a 2D matrix where the values in each cell cannot be
repeated in the same row or column.
Dimensions are always square (ie. width==height==grid_size). If no
values are passed to constructor, will build an empty grid of size
DEFAULT_PUZZLE_SIZE (9).
Attributes:
size: Dimensions of the square (length, height) in a tuple.
num_cells: Total number of cells (grid_size * grid_size)
max_value: Equal to grid_size, it's the max value of a cell, and
also the grid's length and height.
complete_set: Set of values from [1..max_value] that must exist once
in each row and column in a solved puzzle.
Args:
starting_grid: A list of lists of integers (2D array of ints).
Pass None to start with an empty grid.
grid_size: The number of cells for the width and height of the
grid. Default value is 9, for a 9x9 grid (81 cells). If not
set, size is set to len(starting_grid), otherwise must be
consistent with len(starting_grid) as a check for "bad" data.
Raises:
ValueError: An inconsistency exists in the starting_grid;
or the grid_size is too small or too large (1 to 25)
"""
def __init__(self, grid_size=None, starting_grid=None):
# If a starting_grid is passed, that sets the size
if starting_grid and grid_size:
if len(starting_grid) != grid_size:
raise ValueError(f"starting_grid is not {grid_size}x{grid_size}")
elif starting_grid:
grid_size = len(starting_grid)
elif grid_size is None:
grid_size = DEFAULT_PUZZLE_SIZE
if not MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE:
raise ValueError(
f"grid_size={grid_size} outside [{MIN_PUZZLE_SIZE}:{MAX_PUZZLE_SIZE}]"
)
# Attributes
self.size = (grid_size, grid_size)
self.num_cells = grid_size * grid_size
self.max_value = grid_size
self.complete_set = set(range(MIN_CELL_VALUE, grid_size + 1))
# Protected
self._grid = build_empty_grid(grid_size)
self.__num_empty_cells = grid_size * grid_size
# Initialize constraints
self.__allowed_values_for_row = [
set(self.complete_set) for i in range(grid_size)
]
self.__allowed_values_for_col = [
set(self.complete_set) for i in range(grid_size)
]
# Accept a starting puzzle
if starting_grid:
self.init_puzzle(starting_grid)
def init_puzzle(self, starting_grid):
"""Initializes a puzzle grid based on contents of starting_grid.
Clears the existing puzzle and resets internal state (e.g. count of
empty cells remaining).
Args:
starting_grid: A list of lists of integers (2D array of ints).
To help catch data errors, must be the same size as what the
instance was initialized for.
Raises:
ValueError: Size of starting_grid (len) is not what was expected
from the initial grid_size; or constraint on cell values is
violated (e.g. dupicate value in a row)
"""
self.clear_all()
# Check that new grid is correct number of rows
if len(starting_grid) != self.max_value:
raise ValueError(f"Exepect {self.max_value} rows, got {len(starting_grid)}")
# Check that new grid has correct number of cols
for x, row in enumerate(starting_grid):
if len(row) != self.max_value:
raise ValueError(
f"Expect {self.max_value} columns in row {x}, got {len(row)}")
for y, val in enumerate(row):
if val:
self.set(x, y, val)
def num_empty_cells(self):
"""Returns the number of empty cells remaining."""
return self.__num_empty_cells
def get(self, x, y):
"""Returns the cell value at (x, y)"""
return self._grid[x][y]
def set(self, x, y, value):
"""Sets the call at x,y to value
The set operation must obey the rules of the contraints. In this class
- no value can be repeated in a row
- no value can be repeated in a column
If a constraint is violated then a ValueError exception is raised.
Args:
x, y: Cell position in row, column order.
value: Integer value to write into the cell.
Raises:
ValueError: Cell value out of range [1:max_value]
IndexError: x,y location out of range [0:max_value-1]
"""
if value < MIN_CELL_VALUE or value > self.max_value:
raise ValueError(f"Value {value} out of range [{MIN_CELL_VALUE}:{self.max_value}]")
if self._grid[x][y] == value:
return
# Clear value first to update constraints
if self._grid[x][y]:
self.clear(x, y)
# Write value if allowed
if value in self.get_allowed_values(x, y):
self._grid[x][y] = value
self.__num_empty_cells -= 1
else:
raise ValueError(f"Value {value} not allowed at {x},{y}")
# Update constraints
self.__allowed_values_for_row[x].remove(value)
self.__allowed_values_for_col[y].remove(value)
def clear(self, x, y):
"""Clears the value for a cell at x,y and update constraints"""
# Is OK to "clear" an already empty cell (no-op)
if self._grid[x][y] == EMPTY_CELL:
return
# Stash previous value before clearing, to update constraints
prev = self._grid[x][y]
self._grid[x][y] = EMPTY_CELL
self.__num_empty_cells += 1
# Put previous value back into allowed list
self.__allowed_values_for_row[x].add(prev)
self.__allowed_values_for_col[y].add(prev)
def clear_all(self):
"""Clears the entire puzzle grid"""
for x in range(self.max_value):
for y in range(self.max_value):
self.clear(x, y)
def is_empty(self, x, y):
"""Returns True if the cell is empty"""
return self._grid[x][y] == EMPTY_CELL
def find_empty_cell(self):
"""Returns the next empty cell as tuple (x, y)
Search starts at 0,0 and continues along the row. Returns at the first
empty cell found. Returns empty tuple if no empty cells left.
"""
for x, row in enumerate(self._grid):
for y, v in enumerate(row):
if not v:
return (x, y)
return ()
def next_empty_cell(self):
"""Generator that returns the next empty cell that exists in the grid
Search starts at 0,0, just like `find_empty_cell`. However each
subsequent call will resume where the previous invocation left off
(assuming this is being called as a generator function). Returns an
empty tuple at the end of the list.
"""
for x, row in enumerate(self._grid):
for y, v in enumerate(row):
if not v:
yield (x, y)
return ()
def next_best_empty_cell(self):
"""Generator method that returns the next "best" empty cell
Next best cell is the one with the fewest possible values. Returns an
empty tuple when it reaches the end of the list.
"""
max_possibilities = 1
while max_possibilities <= self.max_value:
for x, row in enumerate(self._grid):
for y, v in enumerate(row):
if not v and len(self.get_allowed_values(x, y)) <= max_possibilities:
yield (x, y)
max_possibilities += 1
return ()
def get_row_values(self, x):
"""Return the list of set values from row x as a list"""
return [i for i in self._grid[x] if i != EMPTY_CELL]
def get_column_values(self, y):
"""Return the list of set values from column y as a list"""
return [i[y] for i in self._grid if i[y] != EMPTY_CELL]
def get_allowed_values(self, x, y):
"""Returns the current set of allowed values at x,y as a set
This is based on the intersection of the sets of allowed values for
the same row and column. If there is already a value in a cell, then
it is the only allowed value.
"""
if self._grid[x][y]:
return {self._grid[x][y]}
return self.__allowed_values_for_row[x] & self.__allowed_values_for_col[y]
def is_valid(self):
"""Returns True if the puzzle is in a valid state, False if rules broken.
This fuction should *always* return True, because it should not be
possible to get into an invalid state. However since caller clould
always access self._grid directly, and since we could introduce a bug,
this function can perform an additional check.
Empty cells are allowed -- this is not checking that the puzzle is
solved.
"""
for x in range(self.max_value):
values = self.get_row_values(x)
if len(values) != len(set(values)):
return False
for y in range(self.max_value):
values = self.get_column_values(y)
if len(values) != len(set(values)):
return False
return True
def is_solved(self):
"""Returns True if there are no empty cells left, and the puzzle is valid"""
if self.is_valid():
for i in range(self.max_value):
for j in range(self.max_value):
if self.is_empty(i, j):
return False
return True
return False
def __str__(self):
"""Return a string representation of the puzzle as a 2D grid"""
blurb = [["-" if v is None else v for v in row] for row in self._grid]
return "\n".join(" ".join(map(str, sl)) for sl in blurb)
def __repr__(self):
"""Return an unambiguous string representation of the puzzle"""
puz = "".join([int2char(i) for sublist in self._grid for i in sublist])
ret = f"{self.__class__.__name__}({self.max_value}, '{puz}')"
return ret
| """Implements a class for Latin Square puzzles.
A Latin Square is a square grid of numbers from 1..N, where a number may not
be repeated in the same row or column. Such squares form the basis of puzzles
like Sudoku, Kenken(tm), and their variants.
Classes:
LatinSquare: Implements a square puzzle constrained by not repeating
values in the same row or column.
Functions:
build_empty_grid: Build a 2D array (list of lists) for puzzle.
char2int: Convert bewteen character and integer representation of a cell value.
int2char: Reverse of char2int.
count_clues: Given a string or 2D array representing a puzzle, return
the number of starting clues in the puzzle.
from_string: Given a string representing a puzzle, return the 2D array
equivalent. All class methods expect the array version.
"""
default_puzzle_size = 9
empty_cell = None
max_puzzle_size = 25
min_puzzle_size = 1
min_cell_value = 1
cell_values = '123456789ABCDEFGHIJKLMNOP'
assert MAX_PUZZLE_SIZE == len(CELL_VALUES)
def build_empty_grid(grid_size):
"""Builds a 2D array grid_size * grid_size, each cell element is None."""
assert MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE
ret = [[] for x in range(grid_size)]
for x in range(grid_size):
ret[x] = [EMPTY_CELL for y in range(grid_size)]
return ret
def char2int(char):
"""Converts character char to an int representation."""
if char in ('.', '0'):
return EMPTY_CELL
return CELL_VALUES.index(char) + 1
def int2char(value):
"""Converts back from an int value to character value for a cell."""
if not value:
return '.'
return CELL_VALUES[value - 1]
def count_clues(puzzle_grid):
"""Counts clues in a puzzle_grid, which can be a list of lists or string."""
if isinstance(puzzle_grid, list):
return sum([1 for sublist in puzzle_grid for i in sublist if i])
return len(puzzle_grid) - puzzle_grid.count('.')
def from_string(puzzle_string):
"""Takes a string and converts it to a list of lists of integers.
Puzzles are expected to be 2D arrays of ints, but it's convenient to store
test data as strings (e.g. '89.4...5614.35..9.......8..9.....'). So this
will split a string (using period for "empty cell") and return the 2D array.
Args:
puzzle_string: A string with 1 character per cell. Use uppercase letters
for integer values >= 10 (A=10; B=11; etc). Trailing blanks are
stripped.
Returns:
A list of lists of ints.
Raises:
ValueError: puzzle_string length is not a square (e.g. 4, 9, 16, 25);
or a character value in string is out of range.
"""
s = puzzle_string.rstrip()
grid_size = int(len(s) ** (1 / 2))
if not MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE:
raise value_error(f'puzzle_string {grid_size}x{grid_size} is out of range')
if grid_size ** 2 != len(s):
raise value_error(f'puzzle_string {grid_size}x{grid_size} is not a square')
ret = build_empty_grid(grid_size)
for (i, ch) in enumerate(s):
v = char2int(ch)
if v and MIN_CELL_VALUE <= v <= grid_size:
ret[i // grid_size][i % grid_size] = v
elif v:
raise value_error(f'Cell value {v} at {i} out of range [1:{grid_size}]')
return ret
class Latinsquare:
"""Implements a Latin Square "puzzle".
A Latin Square is a 2D matrix where the values in each cell cannot be
repeated in the same row or column.
Dimensions are always square (ie. width==height==grid_size). If no
values are passed to constructor, will build an empty grid of size
DEFAULT_PUZZLE_SIZE (9).
Attributes:
size: Dimensions of the square (length, height) in a tuple.
num_cells: Total number of cells (grid_size * grid_size)
max_value: Equal to grid_size, it's the max value of a cell, and
also the grid's length and height.
complete_set: Set of values from [1..max_value] that must exist once
in each row and column in a solved puzzle.
Args:
starting_grid: A list of lists of integers (2D array of ints).
Pass None to start with an empty grid.
grid_size: The number of cells for the width and height of the
grid. Default value is 9, for a 9x9 grid (81 cells). If not
set, size is set to len(starting_grid), otherwise must be
consistent with len(starting_grid) as a check for "bad" data.
Raises:
ValueError: An inconsistency exists in the starting_grid;
or the grid_size is too small or too large (1 to 25)
"""
def __init__(self, grid_size=None, starting_grid=None):
if starting_grid and grid_size:
if len(starting_grid) != grid_size:
raise value_error(f'starting_grid is not {grid_size}x{grid_size}')
elif starting_grid:
grid_size = len(starting_grid)
elif grid_size is None:
grid_size = DEFAULT_PUZZLE_SIZE
if not MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE:
raise value_error(f'grid_size={grid_size} outside [{MIN_PUZZLE_SIZE}:{MAX_PUZZLE_SIZE}]')
self.size = (grid_size, grid_size)
self.num_cells = grid_size * grid_size
self.max_value = grid_size
self.complete_set = set(range(MIN_CELL_VALUE, grid_size + 1))
self._grid = build_empty_grid(grid_size)
self.__num_empty_cells = grid_size * grid_size
self.__allowed_values_for_row = [set(self.complete_set) for i in range(grid_size)]
self.__allowed_values_for_col = [set(self.complete_set) for i in range(grid_size)]
if starting_grid:
self.init_puzzle(starting_grid)
def init_puzzle(self, starting_grid):
"""Initializes a puzzle grid based on contents of starting_grid.
Clears the existing puzzle and resets internal state (e.g. count of
empty cells remaining).
Args:
starting_grid: A list of lists of integers (2D array of ints).
To help catch data errors, must be the same size as what the
instance was initialized for.
Raises:
ValueError: Size of starting_grid (len) is not what was expected
from the initial grid_size; or constraint on cell values is
violated (e.g. dupicate value in a row)
"""
self.clear_all()
if len(starting_grid) != self.max_value:
raise value_error(f'Exepect {self.max_value} rows, got {len(starting_grid)}')
for (x, row) in enumerate(starting_grid):
if len(row) != self.max_value:
raise value_error(f'Expect {self.max_value} columns in row {x}, got {len(row)}')
for (y, val) in enumerate(row):
if val:
self.set(x, y, val)
def num_empty_cells(self):
"""Returns the number of empty cells remaining."""
return self.__num_empty_cells
def get(self, x, y):
"""Returns the cell value at (x, y)"""
return self._grid[x][y]
def set(self, x, y, value):
"""Sets the call at x,y to value
The set operation must obey the rules of the contraints. In this class
- no value can be repeated in a row
- no value can be repeated in a column
If a constraint is violated then a ValueError exception is raised.
Args:
x, y: Cell position in row, column order.
value: Integer value to write into the cell.
Raises:
ValueError: Cell value out of range [1:max_value]
IndexError: x,y location out of range [0:max_value-1]
"""
if value < MIN_CELL_VALUE or value > self.max_value:
raise value_error(f'Value {value} out of range [{MIN_CELL_VALUE}:{self.max_value}]')
if self._grid[x][y] == value:
return
if self._grid[x][y]:
self.clear(x, y)
if value in self.get_allowed_values(x, y):
self._grid[x][y] = value
self.__num_empty_cells -= 1
else:
raise value_error(f'Value {value} not allowed at {x},{y}')
self.__allowed_values_for_row[x].remove(value)
self.__allowed_values_for_col[y].remove(value)
def clear(self, x, y):
"""Clears the value for a cell at x,y and update constraints"""
if self._grid[x][y] == EMPTY_CELL:
return
prev = self._grid[x][y]
self._grid[x][y] = EMPTY_CELL
self.__num_empty_cells += 1
self.__allowed_values_for_row[x].add(prev)
self.__allowed_values_for_col[y].add(prev)
def clear_all(self):
"""Clears the entire puzzle grid"""
for x in range(self.max_value):
for y in range(self.max_value):
self.clear(x, y)
def is_empty(self, x, y):
"""Returns True if the cell is empty"""
return self._grid[x][y] == EMPTY_CELL
def find_empty_cell(self):
"""Returns the next empty cell as tuple (x, y)
Search starts at 0,0 and continues along the row. Returns at the first
empty cell found. Returns empty tuple if no empty cells left.
"""
for (x, row) in enumerate(self._grid):
for (y, v) in enumerate(row):
if not v:
return (x, y)
return ()
def next_empty_cell(self):
"""Generator that returns the next empty cell that exists in the grid
Search starts at 0,0, just like `find_empty_cell`. However each
subsequent call will resume where the previous invocation left off
(assuming this is being called as a generator function). Returns an
empty tuple at the end of the list.
"""
for (x, row) in enumerate(self._grid):
for (y, v) in enumerate(row):
if not v:
yield (x, y)
return ()
def next_best_empty_cell(self):
"""Generator method that returns the next "best" empty cell
Next best cell is the one with the fewest possible values. Returns an
empty tuple when it reaches the end of the list.
"""
max_possibilities = 1
while max_possibilities <= self.max_value:
for (x, row) in enumerate(self._grid):
for (y, v) in enumerate(row):
if not v and len(self.get_allowed_values(x, y)) <= max_possibilities:
yield (x, y)
max_possibilities += 1
return ()
def get_row_values(self, x):
"""Return the list of set values from row x as a list"""
return [i for i in self._grid[x] if i != EMPTY_CELL]
def get_column_values(self, y):
"""Return the list of set values from column y as a list"""
return [i[y] for i in self._grid if i[y] != EMPTY_CELL]
def get_allowed_values(self, x, y):
"""Returns the current set of allowed values at x,y as a set
This is based on the intersection of the sets of allowed values for
the same row and column. If there is already a value in a cell, then
it is the only allowed value.
"""
if self._grid[x][y]:
return {self._grid[x][y]}
return self.__allowed_values_for_row[x] & self.__allowed_values_for_col[y]
def is_valid(self):
"""Returns True if the puzzle is in a valid state, False if rules broken.
This fuction should *always* return True, because it should not be
possible to get into an invalid state. However since caller clould
always access self._grid directly, and since we could introduce a bug,
this function can perform an additional check.
Empty cells are allowed -- this is not checking that the puzzle is
solved.
"""
for x in range(self.max_value):
values = self.get_row_values(x)
if len(values) != len(set(values)):
return False
for y in range(self.max_value):
values = self.get_column_values(y)
if len(values) != len(set(values)):
return False
return True
def is_solved(self):
"""Returns True if there are no empty cells left, and the puzzle is valid"""
if self.is_valid():
for i in range(self.max_value):
for j in range(self.max_value):
if self.is_empty(i, j):
return False
return True
return False
def __str__(self):
"""Return a string representation of the puzzle as a 2D grid"""
blurb = [['-' if v is None else v for v in row] for row in self._grid]
return '\n'.join((' '.join(map(str, sl)) for sl in blurb))
def __repr__(self):
"""Return an unambiguous string representation of the puzzle"""
puz = ''.join([int2char(i) for sublist in self._grid for i in sublist])
ret = f"{self.__class__.__name__}({self.max_value}, '{puz}')"
return ret |
maxsimal = 0
while True:
a = int(input("Masukan bilangan = "))
if maxsimal < a:
maxsimal = a
if a == 0:
break
print("Bilangan Terbesarnya Adalah = ", maxsimal)
| maxsimal = 0
while True:
a = int(input('Masukan bilangan = '))
if maxsimal < a:
maxsimal = a
if a == 0:
break
print('Bilangan Terbesarnya Adalah = ', maxsimal) |
class Holding(object):
def __init__(self, name, symbol, sector, market_val_percent, market_value, number_of_shares):
self.name = name
self.symbol = symbol
self.sector = sector
self.market_val_percent = market_val_percent
self.market_value = market_value
self.number_of_shares = number_of_shares
def __eq__(self, other):
return (
self.__class__ == other.__class__ and
self.name == other.name and self.symbol == other.symbol and self.sector == other.sector and
self.market_val_percent == other.market_val_percent and
self.market_value == other.market_value and
self.number_of_shares == other.number_of_shares
)
| class Holding(object):
def __init__(self, name, symbol, sector, market_val_percent, market_value, number_of_shares):
self.name = name
self.symbol = symbol
self.sector = sector
self.market_val_percent = market_val_percent
self.market_value = market_value
self.number_of_shares = number_of_shares
def __eq__(self, other):
return self.__class__ == other.__class__ and self.name == other.name and (self.symbol == other.symbol) and (self.sector == other.sector) and (self.market_val_percent == other.market_val_percent) and (self.market_value == other.market_value) and (self.number_of_shares == other.number_of_shares) |
# rps data for the rock-paper-scissors portion of the red-green game
# to be imported by rg.cgi
# this file represents the "host throw" for each numbered round
rps_data = {
0: "rock",
1: "rock",
2: "scissors",
3: "paper",
4: "paper",
5: "scissors",
6: "rock",
7: "scissors",
8: "paper",
9: "paper",
10: "scissors",
11: "rock",
12: "paper",
13: "paper",
14: "rock",
15: "scissors",
16: "scissors",
17: "scissors",
18: "rock",
19: "scissors",
20: "paper",
21: "rock",
22: "paper",
23: "scissors",
24: "rock",
25: "scissors",
26: "rock",
27: "rock",
28: "paper",
29: "paper",
30: "rock",
31: "paper",
32: "paper",
33: "scissors",
34: "rock",
35: "rock",
36: "scissors",
37: "rock",
38: "rock",
39: "paper",
40: "rock",
41: "rock",
42: "paper",
43: "paper",
44: "paper",
45: "paper",
46: "scissors",
47: "rock",
48: "scissors",
49: "scissors",
}
| rps_data = {0: 'rock', 1: 'rock', 2: 'scissors', 3: 'paper', 4: 'paper', 5: 'scissors', 6: 'rock', 7: 'scissors', 8: 'paper', 9: 'paper', 10: 'scissors', 11: 'rock', 12: 'paper', 13: 'paper', 14: 'rock', 15: 'scissors', 16: 'scissors', 17: 'scissors', 18: 'rock', 19: 'scissors', 20: 'paper', 21: 'rock', 22: 'paper', 23: 'scissors', 24: 'rock', 25: 'scissors', 26: 'rock', 27: 'rock', 28: 'paper', 29: 'paper', 30: 'rock', 31: 'paper', 32: 'paper', 33: 'scissors', 34: 'rock', 35: 'rock', 36: 'scissors', 37: 'rock', 38: 'rock', 39: 'paper', 40: 'rock', 41: 'rock', 42: 'paper', 43: 'paper', 44: 'paper', 45: 'paper', 46: 'scissors', 47: 'rock', 48: 'scissors', 49: 'scissors'} |
user_info = {}
while True:
print("\n\t\t\tUnits:metric")
name = str(input("Enter your name: "))
height = float(input("Input your height in meters(For instance:1.89): "))
weight = float(input("Input your weight in kilogram(For instance:69): "))
age = int(input("Input your age: "))
sex = str(input("Input your sex: "))
bmi = (weight/(height*height))
print("Your body mass index (or BMI) is: ", round(bmi, 2))
if sex == 'male':
if bmi < 15:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Very severely underweight:\
\nIt is important to know whether a serious disease \
or other conditions have caused the emaciation. Whatever \
the case, medical help is advisable.\n\t\t\tPossible causes: \
\nUndernourishment \
\nMaldigestion \
\nEating disorders: anorexia, bulimia \
\nSlimming caused by a disease")
elif 15 < bmi < 16:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Severely underweight:\
\nIt is important to know whether a serious disease \
or other conditions have caused the emaciation. Whatever \
the case, medical help is advisable.\n\t\t\tPossible causes: \
\nUndernourishment \
\nMaldigestion \
\nEating disorders: anorexia, bulimia \
\nSlimming caused by a disease")
elif 16 < bmi < 18.5:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Underweight:\
\nIt is important to know whether a serious disease \
or other conditions have caused the emaciation. Whatever \
the case, medical help is advisable.\n\t\t\tPossible causes: \
\nUndernourishment \
\nMaldigestion \
\nEating disorders: anorexia, bulimia \
\nSlimming caused by a disease")
elif 18.5 < bmi < 25:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Normal(healthy weight):\
\nPlay physical games and do physical \
exercise at least for an hour daily at \
moderate to vigorous intensity.Try out a \
variety of foods, including fresh \
fruit and vegetables.Eat and drink what \
you like, but not too much sweets \
and sweetened drinks.")
elif 25 < bmi < 30:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Overweight:\
\nPlay physical games and do physical \
exercise at least for an hour daily at \
moderate to vigorous intensity.Try out a \
variety of foods, including fresh \
fruit and vegetables.Eat and drink what \
you like, but not too much sweets \
and sweetened drinks.")
elif 30 < bmi < 35:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Moderately obese:\
\nPlay physical games and do physical \
exercise at least for an hour daily at \
moderate to vigorous intensity.Try out a \
variety of foods, including fresh \
fruit and vegetables.Eat and drink what \
you like, but not too much sweets \
and sweetened drinks.")
elif 35 < bmi < 40:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Severely obese:\
\nPlay physical games and do physical \
exercise at least for an hour daily at \
moderate to vigorous intensity.Try out a \
variety of foods, including fresh \
fruit and vegetables.Eat and drink what \
you like, but not too much sweets \
and sweetened drinks.")
elif bmi > 40:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Very severely obese:\
\nPlay physical games and do physical \
exercise at least for an hour daily at \
moderate to vigorous intensity.Try out a \
variety of foods, including fresh \
fruit and vegetables.Eat and drink what \
you like, but not too much sweets \
and sweetened drinks.")
else:
print("There is an error with your input")
else:
if bmi < 18.5:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Underweight:\
\nIt is important to know whether a serious disease \
or other conditions have caused the emaciation. Whatever \
the case, medical help is advisable.\n\t\t\tPossible causes: \
\nUndernourishment \
\nMaldigestion \
\nEating disorders: anorexia, bulimia \
\nSlimming caused by a disease")
elif 18.5 < bmi < 24.9:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Healthy weight:\
\nPlay physical games and do physical \
exercise at least for an hour daily at \
moderate to vigorous intensity.Try out a \
variety of foods, including fresh \
fruit and vegetables.Eat and drink what \
you like, but not too much sweets \
and sweetened drinks.")
elif 25 < bmi < 29.9:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Overweight:\
\nPlay physical games and do physical \
exercise at least for an hour daily at \
moderate to vigorous intensity.Try out a \
variety of foods, including fresh \
fruit and vegetables.Eat and drink what \
you like, but not too much sweets \
and sweetened drinks.")
elif bmi > 30:
print("\n\t\t\tYour BMI is", round(bmi, 2), "Moderately obese:\
\nPlay physical games and do physical \
exercise at least for an hour daily at \
moderate to vigorous intensity.Try out a \
variety of foods, including fresh \
fruit and vegetables.Eat and drink what \
you like, but not too much sweets \
and sweetened drinks.")
else:
print("There is an error with your input")
print('\n\n10' + '=' * (int(round(bmi, 0))-10-1)+'|'+'=\
'*(60-int(round(bmi, 0))-1)+'60')
if not name:
break
user_info[name] = height, weight, age, sex
print(user_info)
print(user_info.get(str(input("Enter your name: "))))
| user_info = {}
while True:
print('\n\t\t\tUnits:metric')
name = str(input('Enter your name: '))
height = float(input('Input your height in meters(For instance:1.89): '))
weight = float(input('Input your weight in kilogram(For instance:69): '))
age = int(input('Input your age: '))
sex = str(input('Input your sex: '))
bmi = weight / (height * height)
print('Your body mass index (or BMI) is: ', round(bmi, 2))
if sex == 'male':
if bmi < 15:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Very severely underweight:\nIt is important to know whether a serious disease or other conditions have caused the emaciation. Whatever the case, medical help is advisable.\n\t\t\tPossible causes: \nUndernourishment \nMaldigestion \nEating disorders: anorexia, bulimia \nSlimming caused by a disease')
elif 15 < bmi < 16:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Severely underweight:\nIt is important to know whether a serious disease or other conditions have caused the emaciation. Whatever the case, medical help is advisable.\n\t\t\tPossible causes: \nUndernourishment \nMaldigestion \nEating disorders: anorexia, bulimia \nSlimming caused by a disease')
elif 16 < bmi < 18.5:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Underweight:\nIt is important to know whether a serious disease or other conditions have caused the emaciation. Whatever the case, medical help is advisable.\n\t\t\tPossible causes: \nUndernourishment \nMaldigestion \nEating disorders: anorexia, bulimia \nSlimming caused by a disease')
elif 18.5 < bmi < 25:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Normal(healthy weight):\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.')
elif 25 < bmi < 30:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Overweight:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.')
elif 30 < bmi < 35:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Moderately obese:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.')
elif 35 < bmi < 40:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Severely obese:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.')
elif bmi > 40:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Very severely obese:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.')
else:
print('There is an error with your input')
elif bmi < 18.5:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Underweight:\nIt is important to know whether a serious disease or other conditions have caused the emaciation. Whatever the case, medical help is advisable.\n\t\t\tPossible causes: \nUndernourishment \nMaldigestion \nEating disorders: anorexia, bulimia \nSlimming caused by a disease')
elif 18.5 < bmi < 24.9:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Healthy weight:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.')
elif 25 < bmi < 29.9:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Overweight:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.')
elif bmi > 30:
print('\n\t\t\tYour BMI is', round(bmi, 2), 'Moderately obese:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.')
else:
print('There is an error with your input')
print('\n\n10' + '=' * (int(round(bmi, 0)) - 10 - 1) + '|' + '=' * (60 - int(round(bmi, 0)) - 1) + '60')
if not name:
break
user_info[name] = (height, weight, age, sex)
print(user_info)
print(user_info.get(str(input('Enter your name: ')))) |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
def getHeaders(fileName):
headers = []
headerList = ['User-Agent','Cookie']
with open(fileName, 'r') as fp:
for line in fp.readlines():
name, value = line.split(':', 1)
if name in headerList:
headers.append((name.strip(), value.strip()))
return headers
if __name__=="__main__":
headers = getHeaders('headersRaw.txt')
print(headers) | def get_headers(fileName):
headers = []
header_list = ['User-Agent', 'Cookie']
with open(fileName, 'r') as fp:
for line in fp.readlines():
(name, value) = line.split(':', 1)
if name in headerList:
headers.append((name.strip(), value.strip()))
return headers
if __name__ == '__main__':
headers = get_headers('headersRaw.txt')
print(headers) |
class ComponentsAssembly:
def __init__(self, broker, strategy, datafeed, sizer, metrics_collection, *args):
self._components = [broker, strategy, datafeed, sizer, metrics_collection, *args]
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index < len(self._components):
component = self._components[self.index]
self.index += 1
return component
raise StopIteration
def __getitem__(self, item):
return self._components[item]
def __setitem__(self, key, value):
self._components[key] = value
def append(self, item):
self._components.append(item)
| class Componentsassembly:
def __init__(self, broker, strategy, datafeed, sizer, metrics_collection, *args):
self._components = [broker, strategy, datafeed, sizer, metrics_collection, *args]
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index < len(self._components):
component = self._components[self.index]
self.index += 1
return component
raise StopIteration
def __getitem__(self, item):
return self._components[item]
def __setitem__(self, key, value):
self._components[key] = value
def append(self, item):
self._components.append(item) |
# Lecture 3.6, slide 2
# Defines the value to take the square root of, epsilon, and the number of guesses.
x = 9
epsilon = 0.01
numGuesses = 0
# Here, 0 < x < 1, then the low is x and the high is 1 - the sqrt(x) > x if 0 < x < 1.
# If x > 1, then the low is 0 and the high is x - the sqrt(x) < x if x > 1.
if (x >= 0 and x < 1):
low = x
high = 1.0
elif (x >= 1):
low = 0.0
high = x
# Sets the initial answer to the average of low and high.
ans = (low + high) / 2.0
# While the answer is still not close enough to epsilon, continue searching.
while (abs(ans ** 2 - x) >= epsilon):
# For each case, it prints the low and high values.
print ('low = ' + str(low) + ' ; high = ' + str(high) + ' ; ans = ' + str(ans))
numGuesses += 1
# If the guess is lower than x, then set the new ans = low.
# If the guess is higher than x, then set the new ans = high.
if (ans ** 2) < x:
low = ans
elif (ans ** 2) >= x:
high = ans
# At the end, the answer is updated.
ans = (low + high) / 2.0
# Prints the number of guesses and the final guess.
print ('Number of guesses taken: ' + str(numGuesses))
print (str(ans) + ' is close to the squre root of ' + str(x)) | x = 9
epsilon = 0.01
num_guesses = 0
if x >= 0 and x < 1:
low = x
high = 1.0
elif x >= 1:
low = 0.0
high = x
ans = (low + high) / 2.0
while abs(ans ** 2 - x) >= epsilon:
print('low = ' + str(low) + ' ; high = ' + str(high) + ' ; ans = ' + str(ans))
num_guesses += 1
if ans ** 2 < x:
low = ans
elif ans ** 2 >= x:
high = ans
ans = (low + high) / 2.0
print('Number of guesses taken: ' + str(numGuesses))
print(str(ans) + ' is close to the squre root of ' + str(x)) |
# ctx.addClock("csi_rx_i.dphy_clk", 96)
# ctx.addClock("video_clk", 24)
# ctx.addClock("uart_i.sys_clk_i", 12)
ctx.addClock("EXTERNAL_CLK", 12)
# ctx.addClock("clk", 25)
| ctx.addClock('EXTERNAL_CLK', 12) |
class Solution:
def soupServings(self, N: int) -> float:
def dfs(a: int, b: int) -> float:
if a <= 0 and b <= 0:
return 0.5
if a <= 0:
return 1.0
if b <= 0:
return 0.0
if memo[a][b] > 0:
return memo[a][b]
memo[a][b] = 0.25 * (dfs(a - 4, b) +
dfs(a - 3, b - 1) +
dfs(a - 2, b - 2) +
dfs(a - 1, b - 3))
return memo[a][b]
memo = [[0.0] * 192 for _ in range(192)]
return 1 if N >= 4800 else dfs((N + 24) // 25, (N + 24) // 25)
| class Solution:
def soup_servings(self, N: int) -> float:
def dfs(a: int, b: int) -> float:
if a <= 0 and b <= 0:
return 0.5
if a <= 0:
return 1.0
if b <= 0:
return 0.0
if memo[a][b] > 0:
return memo[a][b]
memo[a][b] = 0.25 * (dfs(a - 4, b) + dfs(a - 3, b - 1) + dfs(a - 2, b - 2) + dfs(a - 1, b - 3))
return memo[a][b]
memo = [[0.0] * 192 for _ in range(192)]
return 1 if N >= 4800 else dfs((N + 24) // 25, (N + 24) // 25) |
# First we define a variable "to_find" which contains the alphabet to be checked for in the file
# fo is the file which is to be read.
to_find="e"
fo = open('E:/file1.txt' ,'r+')
count=0
for line in fo:
for word in line.split():
if word.find(to_find)!=-1:
count=count+1
print(count)
| to_find = 'e'
fo = open('E:/file1.txt', 'r+')
count = 0
for line in fo:
for word in line.split():
if word.find(to_find) != -1:
count = count + 1
print(count) |
DELIVERY_TYPES = (
(1, "Vaginal Birth"), # Execise care when changing...
(2, "Caesarian")
)
| delivery_types = ((1, 'Vaginal Birth'), (2, 'Caesarian')) |
class Solution:
def makeGood(self, s: str) -> str:
i = 0
string = list(s)
while i < len(string) - 1:
a = string[i]
b = string[i + 1]
if a.lower() == b.lower() and a != b:
string.pop(i)
string.pop(i)
i = 0
else:
i += 1
return "".join(string)
if __name__ == "__main__":
# fmt: off
test_cases = [
"leEeetcode",
"abBAcC",
]
results = [
"leetcode",
"",
]
# fmt: on
app = Solution()
for test_case, correct_result in zip(test_cases, results):
my_result = app.makeGood(test_case)
assert (
my_result == correct_result
), f"My result: {my_result}, correct result: {correct_result}\nTest Case: {test_case}"
| class Solution:
def make_good(self, s: str) -> str:
i = 0
string = list(s)
while i < len(string) - 1:
a = string[i]
b = string[i + 1]
if a.lower() == b.lower() and a != b:
string.pop(i)
string.pop(i)
i = 0
else:
i += 1
return ''.join(string)
if __name__ == '__main__':
test_cases = ['leEeetcode', 'abBAcC']
results = ['leetcode', '']
app = solution()
for (test_case, correct_result) in zip(test_cases, results):
my_result = app.makeGood(test_case)
assert my_result == correct_result, f'My result: {my_result}, correct result: {correct_result}\nTest Case: {test_case}' |
l,j,k=[list(input()) for i in range(3)]
l.extend(j)
for i in l:
if i not in k :
k.append(i)
break
k.remove(i)
print('YES' if k==[] else 'NO')
| (l, j, k) = [list(input()) for i in range(3)]
l.extend(j)
for i in l:
if i not in k:
k.append(i)
break
k.remove(i)
print('YES' if k == [] else 'NO') |
#
# PySNMP MIB module CXQLLC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXQLLC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:33:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
cxQLLC, ThruputClass, Alias, SapIndex = mibBuilder.importSymbols("CXProduct-SMI", "cxQLLC", "ThruputClass", "Alias", "SapIndex")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, NotificationType, Gauge32, Unsigned32, MibIdentifier, IpAddress, Counter64, Counter32, Bits, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ModuleIdentity, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Gauge32", "Unsigned32", "MibIdentifier", "IpAddress", "Counter64", "Counter32", "Bits", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "ModuleIdentity", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class X25Address(DisplayString):
subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(0, 15)
class PacketSize(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(4, 5, 6, 7, 8, 9, 10, 11, 12))
namedValues = NamedValues(("bytes16", 4), ("bytes32", 5), ("bytes64", 6), ("bytes128", 7), ("bytes256", 8), ("bytes512", 9), ("bytes1024", 10), ("bytes2048", 11), ("bytes4096", 12))
qllcSapTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1), )
if mibBuilder.loadTexts: qllcSapTable.setReference('Memotec Communications Inc.')
if mibBuilder.loadTexts: qllcSapTable.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapTable.setDescription('A table containing configuration information for each QLLC service access point.')
qllcSapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1), ).setIndexNames((0, "CXQLLC-MIB", "qllcSapNumber"))
if mibBuilder.loadTexts: qllcSapEntry.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapEntry.setDescription('Defines a row in the qllcSapTable. Each row contains the objects which are used to define a service access point.')
qllcSapNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 1), SapIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcSapNumber.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapNumber.setDescription('Identifies a SAP (service access point) in the qllcSapTable.')
qllcSapRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcSapRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative')
qllcSapType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("lower", 1), ("upper", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcSapType.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapType.setDescription("Specifies this SAP (service access point) as either 'upper' or 'lower'. Options: lower (1): This is a lower SAP which communicates with the X.25 layer. upper (2): This is an upper SAP, which acts as an inter-layer port communicating with the SNA Link Conversion layer. Configuration Changed: administrative")
qllcSapAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 4), Alias()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcSapAlias.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapAlias.setDescription('Identifies this service access point by a textual name. Names must be unique across all service access points at all layers. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative')
qllcSapCompanionAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 5), Alias()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcSapCompanionAlias.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapCompanionAlias.setDescription('Identifies the X.25 SAP that this SAP communicates with. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative')
qllcSapSnalcRef = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 8))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcSapSnalcRef.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapSnalcRef.setDescription('This object applies only to lower SAPs (service access points). Determines the upper SAP (service access point) that is associated with this SAP. Range of Values: 0 - 8 Default Value: none Configuration Changed: administrative')
qllcSapOperationalMode = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("offline", 1), ("online", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcSapOperationalMode.setStatus('mandatory')
if mibBuilder.loadTexts: qllcSapOperationalMode.setDescription('Identifies the operational state of this SAP (service access point). Options: offLine (1): Indicates that this SAP is not operational. onLine (2): Indicates that this SAP is operational.')
qllcDteTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2), )
if mibBuilder.loadTexts: qllcDteTable.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteTable.setDescription('The DTE table contains the parameter settings that are used to create an X.25 Call Request packet for calls established by a particular lower service access point for a particular control unit.')
qllcDteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1), ).setIndexNames((0, "CXQLLC-MIB", "qllcDteSap"), (0, "CXQLLC-MIB", "qllcDteIndex"))
if mibBuilder.loadTexts: qllcDteEntry.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteEntry.setDescription('Defines a row in the qllcDteTable. Each row contains the objects which are used to define a the parameters for an X.25 Call Request packet.')
qllcDteSap = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 1), SapIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteSap.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteSap.setDescription('Identifies the SAP (service access point) associated with this entry. Configuration Changed: administrative ')
qllcDteIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteIndex.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteIndex.setDescription('Identifies the control unit address associated with this DTE entry. Configuration Changed: administrative ')
qllcDteRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative')
qllcDteType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("terminalInterfaceUnit", 1), ("hostInterfaceUnit", 2))).clone('terminalInterfaceUnit')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteType.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteType.setDescription('Determines the type of interface (HIU or TIU) associated with this DTE. Options: terminalInterfaceUnit (1): The SAP type is a TIU, which means it is connected to one or more control units (secondary link stations). The TIU emulates a primary link station, and polls the attached control units. The SDLC interface can support a total of 64 control units across all TIU SAPs. hostInterfaceUnit (2): The SAP type is an HIU, which means it is connected to an SNA host (primary link station). The HIU emulates the control units connected to a TIU. It responds to polls issued by the host. Default Value: terminalInterfaceUnit (1) Configuration Changed: administrative')
qllcDteCalledAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 5), X25Address()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteCalledAddress.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteCalledAddress.setDescription('Determines the DTE to call to establish a QLLC connection. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative')
qllcDteCallingAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 6), X25Address()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteCallingAddress.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteCallingAddress.setDescription('Determines the DTE address of the caller. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative')
qllcDteDBitCall = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2))).clone('yes')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteDBitCall.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteDBitCall.setDescription('Determines if segmentation is supported and is to be performed by the QLLC layer for the specific DTE entry. Options: no (1): QLLC does not support segmentation. yes (2): QLLC supports segmentation. (For future use.) Default Value: yes (2) Configuration Changed: administrative and operative')
qllcDteWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 7)).clone(7)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteWindow.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteWindow.setDescription('Determines the transmit and receive window sizes for this DTE. This window size is used when establishing calls from this DTE, or when receiving calls at this DTE. QLLC only supports modulo 8 window size. Range of Values: 1 - 7 Default Value: 7 Configuration Changed: administrative and operative')
qllcDtePacketSize = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 9), PacketSize().clone('bytes128')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDtePacketSize.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDtePacketSize.setDescription('Determines the transmit and receive packet size for this DTE when flow control negotiation (x25SapSbscrFlowCntrlParamNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bytes16 (4): 16 bytes bytes32 (5): 32 bytes bytes64 (6): 64 bytes bytes128 (7): 128 bytes bytes256 (8): 256 bytes bytes512 (9): 512 bytes bytes1024 (10): 1024 bytes bytes2048 (11): 2048 bytes bytes4096 (12): 4096 bytes Default Value: bytes128 (7) Related Objects: x25SapSbscrFlowCntrlParamNegotiation Configuration Changed: administrative and operative')
qllcDteThroughput = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 10), ThruputClass().clone('bps9600')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteThroughput.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteThroughput.setDescription('Determines the transmit and receive throughput class for this DTE when flow control negotiation (x25SapSbscrThruputClassNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bps75 (3) bps150 (4) bps300 (5) bps600 (6) bps1200 (7) bps2400 (8) bps4800 (9) bps9600 (10) bps19200 (11) bps38400 (12) bps64000 (13) Default Value: bps9600 (10) Related Objects: x25SapSbscrThruputClassNegotiation Configuration Changed: administrative and operative')
qllcDteUserData = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteUserData.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteUserData.setDescription('Determines the data included in the call user data field of each outgoing call initiated by this DTE. Call user data can only be included when calling non-Memotec devices. In this case, up to 12 characters can be specified. The format of the call user data field is determined by the value of the qllcDteMemotec object. Related Object: qllcDteMemotec Range of Values: 0 - 12 characters Default Value: none Configuration Changed: administrative and operative')
qllcDteFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 12), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteFacility.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteFacility.setDescription('Determines the facility codes and associated parameters for this DTE. Default Value: 0 Range of Values: 0 - 20 hexadecimal characters Configuration Changed: administrative and operative')
qllcDteMemotec = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("nonmemotec", 1), ("cx900", 2), ("legacy", 3), ("pvc", 4))).clone('cx900')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteMemotec.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteMemotec.setDescription('Determines the type of product that the called DTE address is associated with, which in turn determines how the call user data (CUD) field is constructed for all outgoing calls from this DTE. This object also determines whether the call is associated to a Switched Virtual Circuit (SVC) or a Permanent Virtual Circuit (PVC). Options: (1): Called DTE address is a non- Memotec product. CUD field = QLLC protocol ID + value of object qllcDteUserData (2): Called DTE is a Memotec CX900 product. CUD field = QLLC protocol ID + value of object qllcDteIndex (3): Called DTE is an older Memotec product (including CX1000). CUD field = QLLC protocol ID + / + Port Group GE + CU Alias + FF + Port + FF + FF (4): The DTE is connected through a Permanent Virtual Circuit (PVC), and can be either TIU or HIU. Note that if the DTE is configured for an SVC but a PVC call is received, the QLLC layer will attempt to connect to the PVC. Default Value: cx900 (2) Related Objects: qllcDteUserData qllcDteCalledAddress qllcDteConnectMethod Configuration Changed: administrative and operative')
qllcDtePvc = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2))).clone('no')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDtePvc.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDtePvc.setDescription('Determines if this DTE makes its calls on a PVC (permanent virtual circuit). Options: no (1): This DTE does not make its calls on a PVC (all calls are switched). yes (2): This DTE makes its calls on a PVC. (For future use.) Default Value: no (1) Configuration Changed: administrative ')
qllcDteConnectMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("userdata", 1), ("callingaddress", 2))).clone('userdata')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: qllcDteConnectMethod.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteConnectMethod.setDescription("Determines if this DTE accepts calls by validating the user-data field, or by matching the calling address with its corresponding called address. Note: This object only applies to the HIU. Options: userdata (1): The HIU DTE validates the call using the user-data field. callingaddress (2): The HIU DTE validates the call by matching the call's calling address with the configured called address. Default Value: userdata (1) Configuration Changed: administrative ")
qllcDteControl = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("clearStats", 1)))).setMaxAccess("writeonly")
if mibBuilder.loadTexts: qllcDteControl.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteControl.setDescription('Clears all statistics for this service access point. Options: clearStats (1): Clear statistics. Default Value: none Configuration Changed: administrative and operative')
qllcDteStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("connected", 1), ("pendingConnect", 2), ("disconnected", 3), ("pendingDisconnect", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteStatus.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteStatus.setDescription('Indicates the connection status of this DTE. Options: connected (1): This DTE is connected. pendingConnect (2): This DTE has issued a call and is waiting for it to complete. disconnected (3): This DTE is not connected. pendingDisconnect (4): This DTE has issued a call clear and is waiting for it to complete. Configuration Changed: administrative and operative')
qllcDteOperationalMode = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("offline", 1), ("online", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteOperationalMode.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteOperationalMode.setDescription('Indicates the operational state of this DTE. Options: offLine (1): Indicates that this DTE is not operational. onLine (2): Indicates that this DTE is operational.')
qllcDteState = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=NamedValues(("opened", 1), ("closed", 2), ("xidcmd", 3), ("tstcmd", 4), ("xidrsp", 5), ("tstrsp", 6), ("reset", 7), ("setmode", 8), ("disc", 9), ("reqdisc", 10), ("unknown", 11)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteState.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteState.setDescription('Indicates the state of this DTE with regards to SNA traffic. Options: opened (1): Indicates that this DTE is in data transfer mode (a QSM was sent and a QUA was received). closed (2): Indicates that this DTE is not in data transfer mode (QSM not sent or QUA not received). xidcmd (3): Indicates that an XID was sent by the TIU and received by the HIU. tstcmd (4): Indicates that a TEST was sent by the TIU and received by the HIU. xiddrsp (5): Indicates that the HIU received an XID response from the TIU, or that the TIU received an XID response from the control unit. tsttrsp (6): Indicates that the HIU received a TEST response from the TIU, or that the TIU received a TEST response from the control unit. reset (7): Indicates that an X.25 reset was received. setmode (8): Indicates that a QSM was received. disc (9): Indicates that the HIU received a DISC from the host, or that the TIU sent a DISC to the control unit. reqdisc (10): Indicates that the HIU sent a DISC to the host, or that the TIU received a DISC from the control unit. unknown (11): Indicates that an unknown condition has occurred. ')
qllcDteConnectionType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("svc", 2), ("pvc", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteConnectionType.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteConnectionType.setDescription('Identifies the type of X.25 connection that the DTE is supporting. Options: none (1): No X.25 connection exists yet. svc (2): The QLLC DTE is transmitting SNA data over a Switched Virtual Circuit (SVC). pvc (3): The QLLC DTE is transmitting SNA data over a Permanent Virtual Circuit (PVC).')
qllcDteCalls = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 40), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteCalls.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteCalls.setDescription('Indicates the number of incoming calls received by this DTE.')
qllcDteClears = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 41), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteClears.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteClears.setDescription('Indicates the number of calls cleared by this DTE.')
qllcDteTxPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 42), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteTxPackets.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteTxPackets.setDescription('Indicates the number of data packets sent by this DTE.')
qllcDteRxPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 43), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteRxPackets.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteRxPackets.setDescription('Indicates the number of data packets received by this DTE.')
qllcDteQdc = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 44), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteQdc.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteQdc.setDescription('Indicates the number of SNA disconnects sent and received by this DTE.')
qllcDteQxid = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 45), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteQxid.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteQxid.setDescription('Indicates the number of SNA XIDs sent and received by this DTE.')
qllcDteQua = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 46), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteQua.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteQua.setDescription('Indicates the number of unnumbered acknowledgments sent and received by this DTE.')
qllcDteQsm = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 47), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteQsm.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteQsm.setDescription('Indicates the number of SNRMs sent and received by this DTE.')
qllcDteX25Reset = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 48), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteX25Reset.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteX25Reset.setDescription('Indicates the number of X.25 resets sent and received by this DTE.')
qllcDteSnalcRnr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 49), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteSnalcRnr.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteSnalcRnr.setDescription('Indicates the number of SNA link conversion layer flow control RNRs sent and received by this DTE.')
qllcDteSnalcRr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 50), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteSnalcRr.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteSnalcRr.setDescription('Indicates the number of SNA link conversion layer flow control RRs sent and received by this DTE.')
qllcDteX25Rnr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 51), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteX25Rnr.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteX25Rnr.setDescription('Indicates the number of X.25 flow control RNRs sent and received by this DTE.')
qllcDteX25Rr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 52), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcDteX25Rr.setStatus('mandatory')
if mibBuilder.loadTexts: qllcDteX25Rr.setDescription('Indicates the number of X.25 flow control RRs sent and received by this DTE.')
qllcMibLevel = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: qllcMibLevel.setStatus('mandatory')
if mibBuilder.loadTexts: qllcMibLevel.setDescription('Used to determine current MIB module release supported by the agent. Object is in decimal.')
mibBuilder.exportSymbols("CXQLLC-MIB", qllcSapAlias=qllcSapAlias, qllcDteCalls=qllcDteCalls, qllcDteClears=qllcDteClears, qllcSapTable=qllcSapTable, qllcDtePacketSize=qllcDtePacketSize, qllcDteStatus=qllcDteStatus, qllcSapCompanionAlias=qllcSapCompanionAlias, qllcDteRowStatus=qllcDteRowStatus, qllcDteQdc=qllcDteQdc, qllcDtePvc=qllcDtePvc, qllcDteQua=qllcDteQua, qllcSapOperationalMode=qllcSapOperationalMode, qllcDteOperationalMode=qllcDteOperationalMode, qllcDteDBitCall=qllcDteDBitCall, qllcSapRowStatus=qllcSapRowStatus, qllcDteEntry=qllcDteEntry, qllcDteCalledAddress=qllcDteCalledAddress, qllcDteConnectionType=qllcDteConnectionType, qllcDteType=qllcDteType, qllcDteSnalcRr=qllcDteSnalcRr, qllcDteX25Rnr=qllcDteX25Rnr, qllcMibLevel=qllcMibLevel, qllcDteQsm=qllcDteQsm, qllcDteTxPackets=qllcDteTxPackets, qllcDteMemotec=qllcDteMemotec, qllcDteQxid=qllcDteQxid, qllcDteTable=qllcDteTable, qllcDteSap=qllcDteSap, qllcDteThroughput=qllcDteThroughput, qllcDteConnectMethod=qllcDteConnectMethod, qllcDteX25Reset=qllcDteX25Reset, qllcSapNumber=qllcSapNumber, qllcDteSnalcRnr=qllcDteSnalcRnr, qllcSapEntry=qllcSapEntry, qllcDteControl=qllcDteControl, qllcDteFacility=qllcDteFacility, qllcDteState=qllcDteState, PacketSize=PacketSize, qllcSapType=qllcSapType, qllcSapSnalcRef=qllcSapSnalcRef, qllcDteCallingAddress=qllcDteCallingAddress, qllcDteIndex=qllcDteIndex, qllcDteUserData=qllcDteUserData, X25Address=X25Address, qllcDteX25Rr=qllcDteX25Rr, qllcDteRxPackets=qllcDteRxPackets, qllcDteWindow=qllcDteWindow)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection')
(cx_qllc, thruput_class, alias, sap_index) = mibBuilder.importSymbols('CXProduct-SMI', 'cxQLLC', 'ThruputClass', 'Alias', 'SapIndex')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(iso, notification_type, gauge32, unsigned32, mib_identifier, ip_address, counter64, counter32, bits, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, module_identity, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'NotificationType', 'Gauge32', 'Unsigned32', 'MibIdentifier', 'IpAddress', 'Counter64', 'Counter32', 'Bits', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'ModuleIdentity', 'Integer32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
class X25Address(DisplayString):
subtype_spec = DisplayString.subtypeSpec + value_size_constraint(0, 15)
class Packetsize(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(4, 5, 6, 7, 8, 9, 10, 11, 12))
named_values = named_values(('bytes16', 4), ('bytes32', 5), ('bytes64', 6), ('bytes128', 7), ('bytes256', 8), ('bytes512', 9), ('bytes1024', 10), ('bytes2048', 11), ('bytes4096', 12))
qllc_sap_table = mib_table((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1))
if mibBuilder.loadTexts:
qllcSapTable.setReference('Memotec Communications Inc.')
if mibBuilder.loadTexts:
qllcSapTable.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapTable.setDescription('A table containing configuration information for each QLLC service access point.')
qllc_sap_entry = mib_table_row((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1)).setIndexNames((0, 'CXQLLC-MIB', 'qllcSapNumber'))
if mibBuilder.loadTexts:
qllcSapEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapEntry.setDescription('Defines a row in the qllcSapTable. Each row contains the objects which are used to define a service access point.')
qllc_sap_number = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 1), sap_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcSapNumber.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapNumber.setDescription('Identifies a SAP (service access point) in the qllcSapTable.')
qllc_sap_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('invalid', 1), ('valid', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcSapRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative')
qllc_sap_type = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('lower', 1), ('upper', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcSapType.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapType.setDescription("Specifies this SAP (service access point) as either 'upper' or 'lower'. Options: lower (1): This is a lower SAP which communicates with the X.25 layer. upper (2): This is an upper SAP, which acts as an inter-layer port communicating with the SNA Link Conversion layer. Configuration Changed: administrative")
qllc_sap_alias = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 4), alias()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcSapAlias.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapAlias.setDescription('Identifies this service access point by a textual name. Names must be unique across all service access points at all layers. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative')
qllc_sap_companion_alias = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 5), alias()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcSapCompanionAlias.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapCompanionAlias.setDescription('Identifies the X.25 SAP that this SAP communicates with. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative')
qllc_sap_snalc_ref = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 8))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcSapSnalcRef.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapSnalcRef.setDescription('This object applies only to lower SAPs (service access points). Determines the upper SAP (service access point) that is associated with this SAP. Range of Values: 0 - 8 Default Value: none Configuration Changed: administrative')
qllc_sap_operational_mode = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('offline', 1), ('online', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcSapOperationalMode.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcSapOperationalMode.setDescription('Identifies the operational state of this SAP (service access point). Options: offLine (1): Indicates that this SAP is not operational. onLine (2): Indicates that this SAP is operational.')
qllc_dte_table = mib_table((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2))
if mibBuilder.loadTexts:
qllcDteTable.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteTable.setDescription('The DTE table contains the parameter settings that are used to create an X.25 Call Request packet for calls established by a particular lower service access point for a particular control unit.')
qllc_dte_entry = mib_table_row((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1)).setIndexNames((0, 'CXQLLC-MIB', 'qllcDteSap'), (0, 'CXQLLC-MIB', 'qllcDteIndex'))
if mibBuilder.loadTexts:
qllcDteEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteEntry.setDescription('Defines a row in the qllcDteTable. Each row contains the objects which are used to define a the parameters for an X.25 Call Request packet.')
qllc_dte_sap = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 1), sap_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteSap.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteSap.setDescription('Identifies the SAP (service access point) associated with this entry. Configuration Changed: administrative ')
qllc_dte_index = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 64))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteIndex.setDescription('Identifies the control unit address associated with this DTE entry. Configuration Changed: administrative ')
qllc_dte_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('invalid', 1), ('valid', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative')
qllc_dte_type = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('terminalInterfaceUnit', 1), ('hostInterfaceUnit', 2))).clone('terminalInterfaceUnit')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteType.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteType.setDescription('Determines the type of interface (HIU or TIU) associated with this DTE. Options: terminalInterfaceUnit (1): The SAP type is a TIU, which means it is connected to one or more control units (secondary link stations). The TIU emulates a primary link station, and polls the attached control units. The SDLC interface can support a total of 64 control units across all TIU SAPs. hostInterfaceUnit (2): The SAP type is an HIU, which means it is connected to an SNA host (primary link station). The HIU emulates the control units connected to a TIU. It responds to polls issued by the host. Default Value: terminalInterfaceUnit (1) Configuration Changed: administrative')
qllc_dte_called_address = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 5), x25_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteCalledAddress.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteCalledAddress.setDescription('Determines the DTE to call to establish a QLLC connection. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative')
qllc_dte_calling_address = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 6), x25_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteCallingAddress.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteCallingAddress.setDescription('Determines the DTE address of the caller. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative')
qllc_dte_d_bit_call = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('no', 1), ('yes', 2))).clone('yes')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteDBitCall.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteDBitCall.setDescription('Determines if segmentation is supported and is to be performed by the QLLC layer for the specific DTE entry. Options: no (1): QLLC does not support segmentation. yes (2): QLLC supports segmentation. (For future use.) Default Value: yes (2) Configuration Changed: administrative and operative')
qllc_dte_window = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(1, 7)).clone(7)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteWindow.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteWindow.setDescription('Determines the transmit and receive window sizes for this DTE. This window size is used when establishing calls from this DTE, or when receiving calls at this DTE. QLLC only supports modulo 8 window size. Range of Values: 1 - 7 Default Value: 7 Configuration Changed: administrative and operative')
qllc_dte_packet_size = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 9), packet_size().clone('bytes128')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDtePacketSize.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDtePacketSize.setDescription('Determines the transmit and receive packet size for this DTE when flow control negotiation (x25SapSbscrFlowCntrlParamNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bytes16 (4): 16 bytes bytes32 (5): 32 bytes bytes64 (6): 64 bytes bytes128 (7): 128 bytes bytes256 (8): 256 bytes bytes512 (9): 512 bytes bytes1024 (10): 1024 bytes bytes2048 (11): 2048 bytes bytes4096 (12): 4096 bytes Default Value: bytes128 (7) Related Objects: x25SapSbscrFlowCntrlParamNegotiation Configuration Changed: administrative and operative')
qllc_dte_throughput = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 10), thruput_class().clone('bps9600')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteThroughput.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteThroughput.setDescription('Determines the transmit and receive throughput class for this DTE when flow control negotiation (x25SapSbscrThruputClassNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bps75 (3) bps150 (4) bps300 (5) bps600 (6) bps1200 (7) bps2400 (8) bps4800 (9) bps9600 (10) bps19200 (11) bps38400 (12) bps64000 (13) Default Value: bps9600 (10) Related Objects: x25SapSbscrThruputClassNegotiation Configuration Changed: administrative and operative')
qllc_dte_user_data = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 11), display_string().subtype(subtypeSpec=value_size_constraint(0, 12))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteUserData.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteUserData.setDescription('Determines the data included in the call user data field of each outgoing call initiated by this DTE. Call user data can only be included when calling non-Memotec devices. In this case, up to 12 characters can be specified. The format of the call user data field is determined by the value of the qllcDteMemotec object. Related Object: qllcDteMemotec Range of Values: 0 - 12 characters Default Value: none Configuration Changed: administrative and operative')
qllc_dte_facility = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 12), octet_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteFacility.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteFacility.setDescription('Determines the facility codes and associated parameters for this DTE. Default Value: 0 Range of Values: 0 - 20 hexadecimal characters Configuration Changed: administrative and operative')
qllc_dte_memotec = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 13), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('nonmemotec', 1), ('cx900', 2), ('legacy', 3), ('pvc', 4))).clone('cx900')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteMemotec.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteMemotec.setDescription('Determines the type of product that the called DTE address is associated with, which in turn determines how the call user data (CUD) field is constructed for all outgoing calls from this DTE. This object also determines whether the call is associated to a Switched Virtual Circuit (SVC) or a Permanent Virtual Circuit (PVC). Options: (1): Called DTE address is a non- Memotec product. CUD field = QLLC protocol ID + value of object qllcDteUserData (2): Called DTE is a Memotec CX900 product. CUD field = QLLC protocol ID + value of object qllcDteIndex (3): Called DTE is an older Memotec product (including CX1000). CUD field = QLLC protocol ID + / + Port Group GE + CU Alias + FF + Port + FF + FF (4): The DTE is connected through a Permanent Virtual Circuit (PVC), and can be either TIU or HIU. Note that if the DTE is configured for an SVC but a PVC call is received, the QLLC layer will attempt to connect to the PVC. Default Value: cx900 (2) Related Objects: qllcDteUserData qllcDteCalledAddress qllcDteConnectMethod Configuration Changed: administrative and operative')
qllc_dte_pvc = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('no', 1), ('yes', 2))).clone('no')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDtePvc.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDtePvc.setDescription('Determines if this DTE makes its calls on a PVC (permanent virtual circuit). Options: no (1): This DTE does not make its calls on a PVC (all calls are switched). yes (2): This DTE makes its calls on a PVC. (For future use.) Default Value: no (1) Configuration Changed: administrative ')
qllc_dte_connect_method = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 15), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('userdata', 1), ('callingaddress', 2))).clone('userdata')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
qllcDteConnectMethod.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteConnectMethod.setDescription("Determines if this DTE accepts calls by validating the user-data field, or by matching the calling address with its corresponding called address. Note: This object only applies to the HIU. Options: userdata (1): The HIU DTE validates the call using the user-data field. callingaddress (2): The HIU DTE validates the call by matching the call's calling address with the configured called address. Default Value: userdata (1) Configuration Changed: administrative ")
qllc_dte_control = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1))).clone(namedValues=named_values(('clearStats', 1)))).setMaxAccess('writeonly')
if mibBuilder.loadTexts:
qllcDteControl.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteControl.setDescription('Clears all statistics for this service access point. Options: clearStats (1): Clear statistics. Default Value: none Configuration Changed: administrative and operative')
qllc_dte_status = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 30), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('connected', 1), ('pendingConnect', 2), ('disconnected', 3), ('pendingDisconnect', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteStatus.setDescription('Indicates the connection status of this DTE. Options: connected (1): This DTE is connected. pendingConnect (2): This DTE has issued a call and is waiting for it to complete. disconnected (3): This DTE is not connected. pendingDisconnect (4): This DTE has issued a call clear and is waiting for it to complete. Configuration Changed: administrative and operative')
qllc_dte_operational_mode = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 31), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('offline', 1), ('online', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteOperationalMode.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteOperationalMode.setDescription('Indicates the operational state of this DTE. Options: offLine (1): Indicates that this DTE is not operational. onLine (2): Indicates that this DTE is operational.')
qllc_dte_state = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 32), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=named_values(('opened', 1), ('closed', 2), ('xidcmd', 3), ('tstcmd', 4), ('xidrsp', 5), ('tstrsp', 6), ('reset', 7), ('setmode', 8), ('disc', 9), ('reqdisc', 10), ('unknown', 11)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteState.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteState.setDescription('Indicates the state of this DTE with regards to SNA traffic. Options: opened (1): Indicates that this DTE is in data transfer mode (a QSM was sent and a QUA was received). closed (2): Indicates that this DTE is not in data transfer mode (QSM not sent or QUA not received). xidcmd (3): Indicates that an XID was sent by the TIU and received by the HIU. tstcmd (4): Indicates that a TEST was sent by the TIU and received by the HIU. xiddrsp (5): Indicates that the HIU received an XID response from the TIU, or that the TIU received an XID response from the control unit. tsttrsp (6): Indicates that the HIU received a TEST response from the TIU, or that the TIU received a TEST response from the control unit. reset (7): Indicates that an X.25 reset was received. setmode (8): Indicates that a QSM was received. disc (9): Indicates that the HIU received a DISC from the host, or that the TIU sent a DISC to the control unit. reqdisc (10): Indicates that the HIU sent a DISC to the host, or that the TIU received a DISC from the control unit. unknown (11): Indicates that an unknown condition has occurred. ')
qllc_dte_connection_type = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 33), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('none', 1), ('svc', 2), ('pvc', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteConnectionType.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteConnectionType.setDescription('Identifies the type of X.25 connection that the DTE is supporting. Options: none (1): No X.25 connection exists yet. svc (2): The QLLC DTE is transmitting SNA data over a Switched Virtual Circuit (SVC). pvc (3): The QLLC DTE is transmitting SNA data over a Permanent Virtual Circuit (PVC).')
qllc_dte_calls = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 40), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteCalls.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteCalls.setDescription('Indicates the number of incoming calls received by this DTE.')
qllc_dte_clears = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 41), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteClears.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteClears.setDescription('Indicates the number of calls cleared by this DTE.')
qllc_dte_tx_packets = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 42), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteTxPackets.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteTxPackets.setDescription('Indicates the number of data packets sent by this DTE.')
qllc_dte_rx_packets = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 43), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteRxPackets.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteRxPackets.setDescription('Indicates the number of data packets received by this DTE.')
qllc_dte_qdc = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 44), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteQdc.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteQdc.setDescription('Indicates the number of SNA disconnects sent and received by this DTE.')
qllc_dte_qxid = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 45), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteQxid.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteQxid.setDescription('Indicates the number of SNA XIDs sent and received by this DTE.')
qllc_dte_qua = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 46), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteQua.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteQua.setDescription('Indicates the number of unnumbered acknowledgments sent and received by this DTE.')
qllc_dte_qsm = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 47), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteQsm.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteQsm.setDescription('Indicates the number of SNRMs sent and received by this DTE.')
qllc_dte_x25_reset = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 48), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteX25Reset.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteX25Reset.setDescription('Indicates the number of X.25 resets sent and received by this DTE.')
qllc_dte_snalc_rnr = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 49), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteSnalcRnr.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteSnalcRnr.setDescription('Indicates the number of SNA link conversion layer flow control RNRs sent and received by this DTE.')
qllc_dte_snalc_rr = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 50), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteSnalcRr.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteSnalcRr.setDescription('Indicates the number of SNA link conversion layer flow control RRs sent and received by this DTE.')
qllc_dte_x25_rnr = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 51), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteX25Rnr.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteX25Rnr.setDescription('Indicates the number of X.25 flow control RNRs sent and received by this DTE.')
qllc_dte_x25_rr = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 52), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcDteX25Rr.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcDteX25Rr.setDescription('Indicates the number of X.25 flow control RRs sent and received by this DTE.')
qllc_mib_level = mib_scalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 3), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
qllcMibLevel.setStatus('mandatory')
if mibBuilder.loadTexts:
qllcMibLevel.setDescription('Used to determine current MIB module release supported by the agent. Object is in decimal.')
mibBuilder.exportSymbols('CXQLLC-MIB', qllcSapAlias=qllcSapAlias, qllcDteCalls=qllcDteCalls, qllcDteClears=qllcDteClears, qllcSapTable=qllcSapTable, qllcDtePacketSize=qllcDtePacketSize, qllcDteStatus=qllcDteStatus, qllcSapCompanionAlias=qllcSapCompanionAlias, qllcDteRowStatus=qllcDteRowStatus, qllcDteQdc=qllcDteQdc, qllcDtePvc=qllcDtePvc, qllcDteQua=qllcDteQua, qllcSapOperationalMode=qllcSapOperationalMode, qllcDteOperationalMode=qllcDteOperationalMode, qllcDteDBitCall=qllcDteDBitCall, qllcSapRowStatus=qllcSapRowStatus, qllcDteEntry=qllcDteEntry, qllcDteCalledAddress=qllcDteCalledAddress, qllcDteConnectionType=qllcDteConnectionType, qllcDteType=qllcDteType, qllcDteSnalcRr=qllcDteSnalcRr, qllcDteX25Rnr=qllcDteX25Rnr, qllcMibLevel=qllcMibLevel, qllcDteQsm=qllcDteQsm, qllcDteTxPackets=qllcDteTxPackets, qllcDteMemotec=qllcDteMemotec, qllcDteQxid=qllcDteQxid, qllcDteTable=qllcDteTable, qllcDteSap=qllcDteSap, qllcDteThroughput=qllcDteThroughput, qllcDteConnectMethod=qllcDteConnectMethod, qllcDteX25Reset=qllcDteX25Reset, qllcSapNumber=qllcSapNumber, qllcDteSnalcRnr=qllcDteSnalcRnr, qllcSapEntry=qllcSapEntry, qllcDteControl=qllcDteControl, qllcDteFacility=qllcDteFacility, qllcDteState=qllcDteState, PacketSize=PacketSize, qllcSapType=qllcSapType, qllcSapSnalcRef=qllcSapSnalcRef, qllcDteCallingAddress=qllcDteCallingAddress, qllcDteIndex=qllcDteIndex, qllcDteUserData=qllcDteUserData, X25Address=X25Address, qllcDteX25Rr=qllcDteX25Rr, qllcDteRxPackets=qllcDteRxPackets, qllcDteWindow=qllcDteWindow) |
class Solution:
"""
https://leetcode.com/problems/move-zeroes/
Given an array nums, write a function to move all 0's to the end of
it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your
function, nums should be [1, 3, 12, 0, 0].
Note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
"""
@staticmethod
def moveZeroes(nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place.
"""
# nums.sort(key=lambda a: a == 0)
zero_pos = 0
for i in range(len(nums)):
if nums[i] != 0:
if zero_pos != i:
nums[i], nums[zero_pos] = nums[zero_pos], nums[i]
zero_pos += 1
| class Solution:
"""
https://leetcode.com/problems/move-zeroes/
Given an array nums, write a function to move all 0's to the end of
it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your
function, nums should be [1, 3, 12, 0, 0].
Note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
"""
@staticmethod
def move_zeroes(nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place.
"""
zero_pos = 0
for i in range(len(nums)):
if nums[i] != 0:
if zero_pos != i:
(nums[i], nums[zero_pos]) = (nums[zero_pos], nums[i])
zero_pos += 1 |
RGB2HEX = 1
RGB2HSV = 2
RGB2HSL = 3
HEX2RGB = 4
HSV2RGB = 5
OPCV_RGB2HSV = 100
OPCV_HSV2RGB = 101 | rgb2_hex = 1
rgb2_hsv = 2
rgb2_hsl = 3
hex2_rgb = 4
hsv2_rgb = 5
opcv_rgb2_hsv = 100
opcv_hsv2_rgb = 101 |
class ImageGroupsComponent:
def __init__(self, key=None, imageGroup=None):
self.key = 'imagegroups'
self.current = None
self.animationList = {}
self.alpha = 255
self.hue = None
self.playing = True
if key is not None and imageGroup is not None:
self.add(key, imageGroup)
def getCurrentImageGroup(self):
if self.animationList == {} or self.current is None:
return None
return self.animationList[self.current]
def add(self, state, animation):
self.animationList[state] = animation
if self.current == None:
self.current = state
def pause(self):
self.playing = False
def play(self):
self.playing = True
def stop(self):
self.playing = False
self.animationList[self.current].reset() | class Imagegroupscomponent:
def __init__(self, key=None, imageGroup=None):
self.key = 'imagegroups'
self.current = None
self.animationList = {}
self.alpha = 255
self.hue = None
self.playing = True
if key is not None and imageGroup is not None:
self.add(key, imageGroup)
def get_current_image_group(self):
if self.animationList == {} or self.current is None:
return None
return self.animationList[self.current]
def add(self, state, animation):
self.animationList[state] = animation
if self.current == None:
self.current = state
def pause(self):
self.playing = False
def play(self):
self.playing = True
def stop(self):
self.playing = False
self.animationList[self.current].reset() |
class Tag(object):
def __init__(self, tag_name : str, type_ = None):
self.__tag_name = tag_name
self.__type : str = type_ if type_ is not None else ""
@property
def type(self) -> str:
return self.__type
@property
def name(self) -> str:
return self.__tag_name
def __str__(self) -> str:
return self.type + ":" + self.__tag_name
def __eq__(self, o: object):
return str(o).lower() == str(self).lower()
def __hash__(self) -> int:
return hash(str(self))
def __repr__(self) -> str:
return "<%s>" % str(self)
| class Tag(object):
def __init__(self, tag_name: str, type_=None):
self.__tag_name = tag_name
self.__type: str = type_ if type_ is not None else ''
@property
def type(self) -> str:
return self.__type
@property
def name(self) -> str:
return self.__tag_name
def __str__(self) -> str:
return self.type + ':' + self.__tag_name
def __eq__(self, o: object):
return str(o).lower() == str(self).lower()
def __hash__(self) -> int:
return hash(str(self))
def __repr__(self) -> str:
return '<%s>' % str(self) |
#First go
print("Hello, World!")
message = "Hello, World!"
print(message)
#-------> print "Hello World!" is Python 2 syntax, use print("Hello World!") for Python 3
| print('Hello, World!')
message = 'Hello, World!'
print(message) |
"""
This is a module defined in sub-package
It defines following importable objects
- two module top level functions
- one class
"""
def top_level_function1() -> None:
""" This is first top level function
"""
def top_level_function2() -> None:
""" This is second top level function
"""
class Class:
""" A sample class
"""
def __init__(self) -> None:
''' Initializer that does nothing
'''
return
| """
This is a module defined in sub-package
It defines following importable objects
- two module top level functions
- one class
"""
def top_level_function1() -> None:
""" This is first top level function
"""
def top_level_function2() -> None:
""" This is second top level function
"""
class Class:
""" A sample class
"""
def __init__(self) -> None:
""" Initializer that does nothing
"""
return |
# https://leetcode.com/problems/minimum-depth-of-binary-tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
if not root:
return 0
ans = set()
def helper(node, depth):
if (not node.left) and (not node.right):
ans.add(depth)
return
if node.right:
helper(node.right, depth + 1)
if node.left:
helper(node.left, depth + 1)
helper(root, 1)
return min(ans)
| class Solution:
def min_depth(self, root):
if not root:
return 0
ans = set()
def helper(node, depth):
if not node.left and (not node.right):
ans.add(depth)
return
if node.right:
helper(node.right, depth + 1)
if node.left:
helper(node.left, depth + 1)
helper(root, 1)
return min(ans) |
EXCHANGE_CFFEX = 0
EXCHANGE_SHFE = 1
EXCHANGE_DCE = 2
EXCHANGE_SSEOPT = 3
EXCHANGE_CZCE = 4
EXCHANGE_SZSE = 5
EXCHANGE_SSE = 6
EXCHANGE_UNKNOWN = 7
| exchange_cffex = 0
exchange_shfe = 1
exchange_dce = 2
exchange_sseopt = 3
exchange_czce = 4
exchange_szse = 5
exchange_sse = 6
exchange_unknown = 7 |
numerator = int(input("Enter a numerator: "))
denominator = int(input("Enter denominator: "))
while denominator == 0:
print("Denominator cannot be 0")
denominator = int(input("Enter denominator: "))
if int(numerator / denominator) * denominator == numerator:
print("Divides evenly!")
else:
print("Doesn't divide evenly.") | numerator = int(input('Enter a numerator: '))
denominator = int(input('Enter denominator: '))
while denominator == 0:
print('Denominator cannot be 0')
denominator = int(input('Enter denominator: '))
if int(numerator / denominator) * denominator == numerator:
print('Divides evenly!')
else:
print("Doesn't divide evenly.") |
class Solution:
#Function to find sum of weights of edges of the Minimum Spanning Tree.
def spanningTree(self, V, adj):
#code here
##findpar with rank compression
def findpar(x):
if parent[x]==x:
return x
else:
parent[x]=findpar(parent[x])
return parent[x]
##Union by rank
def union(x,y):
lp_x=findpar(x)
lp_y=findpar(y)
if rank[lp_x]>rank[lp_y]:
parent[lp_y]=lp_x
elif rank[lp_x]<rank[lp_y]:
parent[lp_x]=lp_y
else:
parent[lp_y]=lp_x
rank[lp_x] += 1
# print(adj)
s=0
parent=[]
E={}
rank=[0 for i in range(V)]
for i in range(V):
parent.append(i)
for i in range(len(adj)):
edges=adj[i]
# print(edges)
for edge in edges:
u=i
v=edge[0]
w=edge[1]
if (u,v) not in E and (v,u) not in E:
E[(u,v)]=w
# print(E)
Ef={}
Ef=sorted(E.items(),key=lambda x:x[1])
# print(Ef)
for i in Ef:
# print(i)
w=i[1]
u=i[0][0]
v=i[0][1]
# print(u,v,w)
lp_u=findpar(u)
lp_v=findpar(v)
if lp_u!=lp_v:
union(u,v)
s += w
return s
| class Solution:
def spanning_tree(self, V, adj):
def findpar(x):
if parent[x] == x:
return x
else:
parent[x] = findpar(parent[x])
return parent[x]
def union(x, y):
lp_x = findpar(x)
lp_y = findpar(y)
if rank[lp_x] > rank[lp_y]:
parent[lp_y] = lp_x
elif rank[lp_x] < rank[lp_y]:
parent[lp_x] = lp_y
else:
parent[lp_y] = lp_x
rank[lp_x] += 1
s = 0
parent = []
e = {}
rank = [0 for i in range(V)]
for i in range(V):
parent.append(i)
for i in range(len(adj)):
edges = adj[i]
for edge in edges:
u = i
v = edge[0]
w = edge[1]
if (u, v) not in E and (v, u) not in E:
E[u, v] = w
ef = {}
ef = sorted(E.items(), key=lambda x: x[1])
for i in Ef:
w = i[1]
u = i[0][0]
v = i[0][1]
lp_u = findpar(u)
lp_v = findpar(v)
if lp_u != lp_v:
union(u, v)
s += w
return s |
class Pegawai:
def __init__(self, nama, email, gaji):
self.__namaPegawai = nama
self.__emailPegawai = email
self.__gajiPegawai = gaji
# decoration ini digunakan untuk mengakses property
# nama pegawai agar dapat diakses tanpa menggunakan
# intance.namaPegawai() melainkan instance.namaPegawai
@property
def namaPegawai(self):
return self.__namaPegawai
# nama dari decoration harus sama dengan nama property
# kemudian diakhiri dengan kata setter untuk menandakan bahwa ini adalah setter dari property
@namaPegawai.setter
def namaPegawai(self, nama):
self.__namaPegawai = nama
@property
def emailPegawai(self):
return self.__emailPegawai
@emailPegawai.setter
def emailPegawai(self, email):
self.__emailPegawai = email
@property
def gajiPegawai(self):
return self.__gajiPegawai
@gajiPegawai.setter
def gajiPegawai(self, gaji):
self.__gajiPegawai = gaji
def __str__(self):
return "Nama Pegawai : {} \nEmail : {}\nGajiPegawai : {}".format(self.namaPegawai,self.emailPegawai,self.gajiPegawai) | class Pegawai:
def __init__(self, nama, email, gaji):
self.__namaPegawai = nama
self.__emailPegawai = email
self.__gajiPegawai = gaji
@property
def nama_pegawai(self):
return self.__namaPegawai
@namaPegawai.setter
def nama_pegawai(self, nama):
self.__namaPegawai = nama
@property
def email_pegawai(self):
return self.__emailPegawai
@emailPegawai.setter
def email_pegawai(self, email):
self.__emailPegawai = email
@property
def gaji_pegawai(self):
return self.__gajiPegawai
@gajiPegawai.setter
def gaji_pegawai(self, gaji):
self.__gajiPegawai = gaji
def __str__(self):
return 'Nama Pegawai : {} \nEmail : {}\nGajiPegawai : {}'.format(self.namaPegawai, self.emailPegawai, self.gajiPegawai) |
snippet_normalize (cr, width, height)
cr.set_line_width (0.12)
cr.set_line_cap (cairo.LINE_CAP_BUTT) #/* default */
cr.move_to (0.25, 0.2); cr.line_to (0.25, 0.8)
cr.stroke ()
cr.set_line_cap (cairo.LINE_CAP_ROUND)
cr.move_to (0.5, 0.2); cr.line_to (0.5, 0.8)
cr.stroke ()
cr.set_line_cap (cairo.LINE_CAP_SQUARE)
cr.move_to (0.75, 0.2); cr.line_to (0.75, 0.8)
cr.stroke ()
#/* draw helping lines */
cr.set_source_rgb (1,0.2,0.2)
cr.set_line_width (0.01)
cr.move_to (0.25, 0.2); cr.line_to (0.25, 0.8)
cr.move_to (0.5, 0.2); cr.line_to (0.5, 0.8)
cr.move_to (0.75, 0.2); cr.line_to (0.75, 0.8)
cr.stroke ()
| snippet_normalize(cr, width, height)
cr.set_line_width(0.12)
cr.set_line_cap(cairo.LINE_CAP_BUTT)
cr.move_to(0.25, 0.2)
cr.line_to(0.25, 0.8)
cr.stroke()
cr.set_line_cap(cairo.LINE_CAP_ROUND)
cr.move_to(0.5, 0.2)
cr.line_to(0.5, 0.8)
cr.stroke()
cr.set_line_cap(cairo.LINE_CAP_SQUARE)
cr.move_to(0.75, 0.2)
cr.line_to(0.75, 0.8)
cr.stroke()
cr.set_source_rgb(1, 0.2, 0.2)
cr.set_line_width(0.01)
cr.move_to(0.25, 0.2)
cr.line_to(0.25, 0.8)
cr.move_to(0.5, 0.2)
cr.line_to(0.5, 0.8)
cr.move_to(0.75, 0.2)
cr.line_to(0.75, 0.8)
cr.stroke() |
class DiscreteEnvWrapper:
def __init__(self, env):
self.__env = env
def reset(self):
return self.__env.reset()
def step(self, action):
next_state, reward, done, info = self.__env.step(action)
return next_state, reward, done, info
def render(self):
self.__env.render()
def close(self):
self.__env.close()
def get_random_action(self):
return self.__env.action_space.sample()
def get_total_actions(self):
return self.__env.action_space.n
def get_total_states(self):
return self.__env.observation_space.n
def seed(self, seed=None, set_action_seed=True):
if set_action_seed:
self.__env.action_space.seed(seed)
return self.__env.seed(seed)
| class Discreteenvwrapper:
def __init__(self, env):
self.__env = env
def reset(self):
return self.__env.reset()
def step(self, action):
(next_state, reward, done, info) = self.__env.step(action)
return (next_state, reward, done, info)
def render(self):
self.__env.render()
def close(self):
self.__env.close()
def get_random_action(self):
return self.__env.action_space.sample()
def get_total_actions(self):
return self.__env.action_space.n
def get_total_states(self):
return self.__env.observation_space.n
def seed(self, seed=None, set_action_seed=True):
if set_action_seed:
self.__env.action_space.seed(seed)
return self.__env.seed(seed) |
def mse(x, target):
n = max(x.numel(), target.numel())
return (x - target).pow(2).sum() / n
def snr(x, target):
noise = (x - target).pow(2).sum()
signal = target.pow(2).sum()
SNR = 10 * (signal / noise).log10_()
return SNR
| def mse(x, target):
n = max(x.numel(), target.numel())
return (x - target).pow(2).sum() / n
def snr(x, target):
noise = (x - target).pow(2).sum()
signal = target.pow(2).sum()
snr = 10 * (signal / noise).log10_()
return SNR |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
size = len(preorder)
root = TreeNode(preorder[0])
s = []
s.append(root)
i = 1
while (i < size):
temp = None
while(len(s)>0 and preorder[i] > s[-1].val):
temp = s.pop()
if (temp != None):
temp.right = TreeNode(preorder[i])
s.append(temp.right)
else:
temp = s[-1]
temp.left = TreeNode(preorder[i])
s.append(temp.left)
i = i+1
return root
| class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def bst_from_preorder(self, preorder: List[int]) -> TreeNode:
size = len(preorder)
root = tree_node(preorder[0])
s = []
s.append(root)
i = 1
while i < size:
temp = None
while len(s) > 0 and preorder[i] > s[-1].val:
temp = s.pop()
if temp != None:
temp.right = tree_node(preorder[i])
s.append(temp.right)
else:
temp = s[-1]
temp.left = tree_node(preorder[i])
s.append(temp.left)
i = i + 1
return root |
def get_account(account_id: int):
return {
'account_id': 1,
'email': 'noreply@gerenciagram.com',
'first_name': 'Gerenciagram'
}
| def get_account(account_id: int):
return {'account_id': 1, 'email': 'noreply@gerenciagram.com', 'first_name': 'Gerenciagram'} |
__author__ = 'Michael Andrew michael@hazardmedia.co.nz'
class SoundModel(object):
sound = None
path = ""
delay = 0
delay_min = 0
delay_max = 0
def __init__(self, sound, path, delay=0, delay_min=0, delay_max=0):
self.sound = sound
self.path = path
self.delay = delay
self.delay_min = delay_min
self.delay_max = delay_max | __author__ = 'Michael Andrew michael@hazardmedia.co.nz'
class Soundmodel(object):
sound = None
path = ''
delay = 0
delay_min = 0
delay_max = 0
def __init__(self, sound, path, delay=0, delay_min=0, delay_max=0):
self.sound = sound
self.path = path
self.delay = delay
self.delay_min = delay_min
self.delay_max = delay_max |
max_strlen=[]
max_strindex=[]
for i in range(1,11):
file_name="sample."+str(i)
with open(file_name,"rb") as f:
offsets=[]
len_of_file=[]
for strand in f.readlines():
offsets.append(sum(len_of_file))
len_of_file.append(len(strand))
max_strlen.append(max(len_of_file))
max_strindex.append(len_of_file.index(max(len_of_file)))
print("The lengths of strand in file {} are:\n{}".format(file_name,str(len_of_file)[1:-1]))
print("The offsets for each strand to appear in file {} are:\n{}".format(file_name,str(offsets)[1:-1]))
print("The file name of the largest strand that appears is: sample.{}".format(max_strlen.index(max(max_strlen))+1))
# file=open("sample.1","rb")
# # print(type(file.readlines()[1][:-1].decode("gbk")))
# # print(len(file.readline()[:-1]))
# # e=[]
# # for i in file.readlines():
# # e.append(len(i))
# # print(sum(e))
# # print(file.read())
# print(len(file.read()))
| max_strlen = []
max_strindex = []
for i in range(1, 11):
file_name = 'sample.' + str(i)
with open(file_name, 'rb') as f:
offsets = []
len_of_file = []
for strand in f.readlines():
offsets.append(sum(len_of_file))
len_of_file.append(len(strand))
max_strlen.append(max(len_of_file))
max_strindex.append(len_of_file.index(max(len_of_file)))
print('The lengths of strand in file {} are:\n{}'.format(file_name, str(len_of_file)[1:-1]))
print('The offsets for each strand to appear in file {} are:\n{}'.format(file_name, str(offsets)[1:-1]))
print('The file name of the largest strand that appears is: sample.{}'.format(max_strlen.index(max(max_strlen)) + 1)) |
tokens = ('IMPLY', 'LPAREN', 'RPAREN', 'PREDICATENAME', 'PREDICATEVAR')
precedence = (
('left', 'IMPLY'),
('left', '|', '&'),
('right', '~'),
)
t_ignore = ' \t'
t_IMPLY = r'=>'
t_RPAREN = r'\)'
t_LPAREN = r'\('
literals = ['|', ',', '&', '~']
def t_PREDICATENAME(t):
r'[A-Z][a-zA-Z0-9_]*'
t.value = str(t.value)
return t
def t_PREDICATEVAR(t):
r'[a-z]'
t.value = str(t.value)
return t
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
| tokens = ('IMPLY', 'LPAREN', 'RPAREN', 'PREDICATENAME', 'PREDICATEVAR')
precedence = (('left', 'IMPLY'), ('left', '|', '&'), ('right', '~'))
t_ignore = ' \t'
t_imply = '=>'
t_rparen = '\\)'
t_lparen = '\\('
literals = ['|', ',', '&', '~']
def t_predicatename(t):
"""[A-Z][a-zA-Z0-9_]*"""
t.value = str(t.value)
return t
def t_predicatevar(t):
"""[a-z]"""
t.value = str(t.value)
return t
def t_newline(t):
"""\\n+"""
t.lexer.lineno += t.value.count('\n')
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1) |
for i in range(int(input())):
n = int(input())
a = [0 for j in range(32)]
for j in range(n):
s = input()
p = 0
if('a' in s):
p|=1
if('e' in s):
p|=2
if('i' in s):
p|=4
if('o' in s):
p|=8
if('u' in s):
p|=16
a[p]+=1
c = 0
for j in range(32):
for k in range(j+1,32):
if(j|k==31):
c+=a[j]*a[k]
c+=int(a[31]*(a[31]-1)/2)
print(c)
| for i in range(int(input())):
n = int(input())
a = [0 for j in range(32)]
for j in range(n):
s = input()
p = 0
if 'a' in s:
p |= 1
if 'e' in s:
p |= 2
if 'i' in s:
p |= 4
if 'o' in s:
p |= 8
if 'u' in s:
p |= 16
a[p] += 1
c = 0
for j in range(32):
for k in range(j + 1, 32):
if j | k == 31:
c += a[j] * a[k]
c += int(a[31] * (a[31] - 1) / 2)
print(c) |
begin_unit
comment|'# Copyright 2013 OpenStack Foundation'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# http://www.apache.org/licenses/LICENSE-2.0'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Unless required by applicable law or agreed to in writing, software'
nl|'\n'
comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT'
nl|'\n'
comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the'
nl|'\n'
comment|'# License for the specific language governing permissions and limitations'
nl|'\n'
comment|'# under the License.'
nl|'\n'
nl|'\n'
name|'import'
name|'datetime'
newline|'\n'
nl|'\n'
name|'from'
name|'nova'
name|'import'
name|'db'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|variable|FAKE_UUID
name|'FAKE_UUID'
op|'='
string|"'b48316c5-71e8-45e4-9884-6c78055b9b13'"
newline|'\n'
DECL|variable|FAKE_REQUEST_ID1
name|'FAKE_REQUEST_ID1'
op|'='
string|"'req-3293a3f1-b44c-4609-b8d2-d81b105636b8'"
newline|'\n'
DECL|variable|FAKE_REQUEST_ID2
name|'FAKE_REQUEST_ID2'
op|'='
string|"'req-25517360-b757-47d3-be45-0e8d2a01b36a'"
newline|'\n'
DECL|variable|FAKE_ACTION_ID1
name|'FAKE_ACTION_ID1'
op|'='
number|'123'
newline|'\n'
DECL|variable|FAKE_ACTION_ID2
name|'FAKE_ACTION_ID2'
op|'='
number|'456'
newline|'\n'
nl|'\n'
DECL|variable|FAKE_ACTIONS
name|'FAKE_ACTIONS'
op|'='
op|'{'
nl|'\n'
name|'FAKE_UUID'
op|':'
op|'{'
nl|'\n'
name|'FAKE_REQUEST_ID1'
op|':'
op|'{'
string|"'id'"
op|':'
name|'FAKE_ACTION_ID1'
op|','
nl|'\n'
string|"'action'"
op|':'
string|"'reboot'"
op|','
nl|'\n'
string|"'instance_uuid'"
op|':'
name|'FAKE_UUID'
op|','
nl|'\n'
string|"'request_id'"
op|':'
name|'FAKE_REQUEST_ID1'
op|','
nl|'\n'
string|"'project_id'"
op|':'
string|"'147'"
op|','
nl|'\n'
string|"'user_id'"
op|':'
string|"'789'"
op|','
nl|'\n'
string|"'start_time'"
op|':'
name|'datetime'
op|'.'
name|'datetime'
op|'('
nl|'\n'
number|'2012'
op|','
number|'12'
op|','
number|'5'
op|','
number|'0'
op|','
number|'0'
op|','
number|'0'
op|','
number|'0'
op|')'
op|','
nl|'\n'
string|"'finish_time'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'message'"
op|':'
string|"''"
op|','
nl|'\n'
string|"'created_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'updated_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted'"
op|':'
name|'False'
op|','
nl|'\n'
op|'}'
op|','
nl|'\n'
name|'FAKE_REQUEST_ID2'
op|':'
op|'{'
string|"'id'"
op|':'
name|'FAKE_ACTION_ID2'
op|','
nl|'\n'
string|"'action'"
op|':'
string|"'resize'"
op|','
nl|'\n'
string|"'instance_uuid'"
op|':'
name|'FAKE_UUID'
op|','
nl|'\n'
string|"'request_id'"
op|':'
name|'FAKE_REQUEST_ID2'
op|','
nl|'\n'
string|"'user_id'"
op|':'
string|"'789'"
op|','
nl|'\n'
string|"'project_id'"
op|':'
string|"'842'"
op|','
nl|'\n'
string|"'start_time'"
op|':'
name|'datetime'
op|'.'
name|'datetime'
op|'('
nl|'\n'
number|'2012'
op|','
number|'12'
op|','
number|'5'
op|','
number|'1'
op|','
number|'0'
op|','
number|'0'
op|','
number|'0'
op|')'
op|','
nl|'\n'
string|"'finish_time'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'message'"
op|':'
string|"''"
op|','
nl|'\n'
string|"'created_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'updated_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted'"
op|':'
name|'False'
op|','
nl|'\n'
op|'}'
nl|'\n'
op|'}'
nl|'\n'
op|'}'
newline|'\n'
nl|'\n'
DECL|variable|FAKE_EVENTS
name|'FAKE_EVENTS'
op|'='
op|'{'
nl|'\n'
name|'FAKE_ACTION_ID1'
op|':'
op|'['
op|'{'
string|"'id'"
op|':'
number|'1'
op|','
nl|'\n'
string|"'action_id'"
op|':'
name|'FAKE_ACTION_ID1'
op|','
nl|'\n'
string|"'event'"
op|':'
string|"'schedule'"
op|','
nl|'\n'
string|"'start_time'"
op|':'
name|'datetime'
op|'.'
name|'datetime'
op|'('
nl|'\n'
number|'2012'
op|','
number|'12'
op|','
number|'5'
op|','
number|'1'
op|','
number|'0'
op|','
number|'2'
op|','
number|'0'
op|')'
op|','
nl|'\n'
string|"'finish_time'"
op|':'
name|'datetime'
op|'.'
name|'datetime'
op|'('
nl|'\n'
number|'2012'
op|','
number|'12'
op|','
number|'5'
op|','
number|'1'
op|','
number|'2'
op|','
number|'0'
op|','
number|'0'
op|')'
op|','
nl|'\n'
string|"'result'"
op|':'
string|"'Success'"
op|','
nl|'\n'
string|"'traceback'"
op|':'
string|"''"
op|','
nl|'\n'
string|"'created_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'updated_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted'"
op|':'
name|'False'
op|','
nl|'\n'
op|'}'
op|','
nl|'\n'
op|'{'
string|"'id'"
op|':'
number|'2'
op|','
nl|'\n'
string|"'action_id'"
op|':'
name|'FAKE_ACTION_ID1'
op|','
nl|'\n'
string|"'event'"
op|':'
string|"'compute_create'"
op|','
nl|'\n'
string|"'start_time'"
op|':'
name|'datetime'
op|'.'
name|'datetime'
op|'('
nl|'\n'
number|'2012'
op|','
number|'12'
op|','
number|'5'
op|','
number|'1'
op|','
number|'3'
op|','
number|'0'
op|','
number|'0'
op|')'
op|','
nl|'\n'
string|"'finish_time'"
op|':'
name|'datetime'
op|'.'
name|'datetime'
op|'('
nl|'\n'
number|'2012'
op|','
number|'12'
op|','
number|'5'
op|','
number|'1'
op|','
number|'4'
op|','
number|'0'
op|','
number|'0'
op|')'
op|','
nl|'\n'
string|"'result'"
op|':'
string|"'Success'"
op|','
nl|'\n'
string|"'traceback'"
op|':'
string|"''"
op|','
nl|'\n'
string|"'created_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'updated_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted'"
op|':'
name|'False'
op|','
nl|'\n'
op|'}'
nl|'\n'
op|']'
op|','
nl|'\n'
name|'FAKE_ACTION_ID2'
op|':'
op|'['
op|'{'
string|"'id'"
op|':'
number|'3'
op|','
nl|'\n'
string|"'action_id'"
op|':'
name|'FAKE_ACTION_ID2'
op|','
nl|'\n'
string|"'event'"
op|':'
string|"'schedule'"
op|','
nl|'\n'
string|"'start_time'"
op|':'
name|'datetime'
op|'.'
name|'datetime'
op|'('
nl|'\n'
number|'2012'
op|','
number|'12'
op|','
number|'5'
op|','
number|'3'
op|','
number|'0'
op|','
number|'0'
op|','
number|'0'
op|')'
op|','
nl|'\n'
string|"'finish_time'"
op|':'
name|'datetime'
op|'.'
name|'datetime'
op|'('
nl|'\n'
number|'2012'
op|','
number|'12'
op|','
number|'5'
op|','
number|'3'
op|','
number|'2'
op|','
number|'0'
op|','
number|'0'
op|')'
op|','
nl|'\n'
string|"'result'"
op|':'
string|"'Error'"
op|','
nl|'\n'
string|"'traceback'"
op|':'
string|"''"
op|','
nl|'\n'
string|"'created_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'updated_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted'"
op|':'
name|'False'
op|','
nl|'\n'
op|'}'
nl|'\n'
op|']'
nl|'\n'
op|'}'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|fake_action_event_start
name|'def'
name|'fake_action_event_start'
op|'('
op|'*'
name|'args'
op|')'
op|':'
newline|'\n'
indent|' '
name|'return'
name|'FAKE_EVENTS'
op|'['
name|'FAKE_ACTION_ID1'
op|']'
op|'['
number|'0'
op|']'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|fake_action_event_finish
dedent|''
name|'def'
name|'fake_action_event_finish'
op|'('
op|'*'
name|'args'
op|')'
op|':'
newline|'\n'
indent|' '
name|'return'
name|'FAKE_EVENTS'
op|'['
name|'FAKE_ACTION_ID1'
op|']'
op|'['
number|'0'
op|']'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|stub_out_action_events
dedent|''
name|'def'
name|'stub_out_action_events'
op|'('
name|'stubs'
op|')'
op|':'
newline|'\n'
indent|' '
name|'stubs'
op|'.'
name|'Set'
op|'('
name|'db'
op|','
string|"'action_event_start'"
op|','
name|'fake_action_event_start'
op|')'
newline|'\n'
name|'stubs'
op|'.'
name|'Set'
op|'('
name|'db'
op|','
string|"'action_event_finish'"
op|','
name|'fake_action_event_finish'
op|')'
newline|'\n'
dedent|''
endmarker|''
end_unit
| begin_unit
comment | '# Copyright 2013 OpenStack Foundation'
nl | '\n'
comment | '#'
nl | '\n'
comment | '# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl | '\n'
comment | '# not use this file except in compliance with the License. You may obtain'
nl | '\n'
comment | '# a copy of the License at'
nl | '\n'
comment | '#'
nl | '\n'
comment | '# http://www.apache.org/licenses/LICENSE-2.0'
nl | '\n'
comment | '#'
nl | '\n'
comment | '# Unless required by applicable law or agreed to in writing, software'
nl | '\n'
comment | '# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT'
nl | '\n'
comment | '# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the'
nl | '\n'
comment | '# License for the specific language governing permissions and limitations'
nl | '\n'
comment | '# under the License.'
nl | '\n'
nl | '\n'
name | 'import'
name | 'datetime'
newline | '\n'
nl | '\n'
name | 'from'
name | 'nova'
name | 'import'
name | 'db'
newline | '\n'
nl | '\n'
nl | '\n'
DECL | variable | FAKE_UUID
name | 'FAKE_UUID'
op | '='
string | "'b48316c5-71e8-45e4-9884-6c78055b9b13'"
newline | '\n'
DECL | variable | FAKE_REQUEST_ID1
name | 'FAKE_REQUEST_ID1'
op | '='
string | "'req-3293a3f1-b44c-4609-b8d2-d81b105636b8'"
newline | '\n'
DECL | variable | FAKE_REQUEST_ID2
name | 'FAKE_REQUEST_ID2'
op | '='
string | "'req-25517360-b757-47d3-be45-0e8d2a01b36a'"
newline | '\n'
DECL | variable | FAKE_ACTION_ID1
name | 'FAKE_ACTION_ID1'
op | '='
number | '123'
newline | '\n'
DECL | variable | FAKE_ACTION_ID2
name | 'FAKE_ACTION_ID2'
op | '='
number | '456'
newline | '\n'
nl | '\n'
DECL | variable | FAKE_ACTIONS
name | 'FAKE_ACTIONS'
op | '='
op | '{'
nl | '\n'
name | 'FAKE_UUID'
op | ':'
op | '{'
nl | '\n'
name | 'FAKE_REQUEST_ID1'
op | ':'
op | '{'
string | "'id'"
op | ':'
name | 'FAKE_ACTION_ID1'
op | ','
nl | '\n'
string | "'action'"
op | ':'
string | "'reboot'"
op | ','
nl | '\n'
string | "'instance_uuid'"
op | ':'
name | 'FAKE_UUID'
op | ','
nl | '\n'
string | "'request_id'"
op | ':'
name | 'FAKE_REQUEST_ID1'
op | ','
nl | '\n'
string | "'project_id'"
op | ':'
string | "'147'"
op | ','
nl | '\n'
string | "'user_id'"
op | ':'
string | "'789'"
op | ','
nl | '\n'
string | "'start_time'"
op | ':'
name | 'datetime'
op | '.'
name | 'datetime'
op | '('
nl | '\n'
number | '2012'
op | ','
number | '12'
op | ','
number | '5'
op | ','
number | '0'
op | ','
number | '0'
op | ','
number | '0'
op | ','
number | '0'
op | ')'
op | ','
nl | '\n'
string | "'finish_time'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'message'"
op | ':'
string | "''"
op | ','
nl | '\n'
string | "'created_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'updated_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted'"
op | ':'
name | 'False'
op | ','
nl | '\n'
op | '}'
op | ','
nl | '\n'
name | 'FAKE_REQUEST_ID2'
op | ':'
op | '{'
string | "'id'"
op | ':'
name | 'FAKE_ACTION_ID2'
op | ','
nl | '\n'
string | "'action'"
op | ':'
string | "'resize'"
op | ','
nl | '\n'
string | "'instance_uuid'"
op | ':'
name | 'FAKE_UUID'
op | ','
nl | '\n'
string | "'request_id'"
op | ':'
name | 'FAKE_REQUEST_ID2'
op | ','
nl | '\n'
string | "'user_id'"
op | ':'
string | "'789'"
op | ','
nl | '\n'
string | "'project_id'"
op | ':'
string | "'842'"
op | ','
nl | '\n'
string | "'start_time'"
op | ':'
name | 'datetime'
op | '.'
name | 'datetime'
op | '('
nl | '\n'
number | '2012'
op | ','
number | '12'
op | ','
number | '5'
op | ','
number | '1'
op | ','
number | '0'
op | ','
number | '0'
op | ','
number | '0'
op | ')'
op | ','
nl | '\n'
string | "'finish_time'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'message'"
op | ':'
string | "''"
op | ','
nl | '\n'
string | "'created_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'updated_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted'"
op | ':'
name | 'False'
op | ','
nl | '\n'
op | '}'
nl | '\n'
op | '}'
nl | '\n'
op | '}'
newline | '\n'
nl | '\n'
DECL | variable | FAKE_EVENTS
name | 'FAKE_EVENTS'
op | '='
op | '{'
nl | '\n'
name | 'FAKE_ACTION_ID1'
op | ':'
op | '['
op | '{'
string | "'id'"
op | ':'
number | '1'
op | ','
nl | '\n'
string | "'action_id'"
op | ':'
name | 'FAKE_ACTION_ID1'
op | ','
nl | '\n'
string | "'event'"
op | ':'
string | "'schedule'"
op | ','
nl | '\n'
string | "'start_time'"
op | ':'
name | 'datetime'
op | '.'
name | 'datetime'
op | '('
nl | '\n'
number | '2012'
op | ','
number | '12'
op | ','
number | '5'
op | ','
number | '1'
op | ','
number | '0'
op | ','
number | '2'
op | ','
number | '0'
op | ')'
op | ','
nl | '\n'
string | "'finish_time'"
op | ':'
name | 'datetime'
op | '.'
name | 'datetime'
op | '('
nl | '\n'
number | '2012'
op | ','
number | '12'
op | ','
number | '5'
op | ','
number | '1'
op | ','
number | '2'
op | ','
number | '0'
op | ','
number | '0'
op | ')'
op | ','
nl | '\n'
string | "'result'"
op | ':'
string | "'Success'"
op | ','
nl | '\n'
string | "'traceback'"
op | ':'
string | "''"
op | ','
nl | '\n'
string | "'created_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'updated_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted'"
op | ':'
name | 'False'
op | ','
nl | '\n'
op | '}'
op | ','
nl | '\n'
op | '{'
string | "'id'"
op | ':'
number | '2'
op | ','
nl | '\n'
string | "'action_id'"
op | ':'
name | 'FAKE_ACTION_ID1'
op | ','
nl | '\n'
string | "'event'"
op | ':'
string | "'compute_create'"
op | ','
nl | '\n'
string | "'start_time'"
op | ':'
name | 'datetime'
op | '.'
name | 'datetime'
op | '('
nl | '\n'
number | '2012'
op | ','
number | '12'
op | ','
number | '5'
op | ','
number | '1'
op | ','
number | '3'
op | ','
number | '0'
op | ','
number | '0'
op | ')'
op | ','
nl | '\n'
string | "'finish_time'"
op | ':'
name | 'datetime'
op | '.'
name | 'datetime'
op | '('
nl | '\n'
number | '2012'
op | ','
number | '12'
op | ','
number | '5'
op | ','
number | '1'
op | ','
number | '4'
op | ','
number | '0'
op | ','
number | '0'
op | ')'
op | ','
nl | '\n'
string | "'result'"
op | ':'
string | "'Success'"
op | ','
nl | '\n'
string | "'traceback'"
op | ':'
string | "''"
op | ','
nl | '\n'
string | "'created_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'updated_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted'"
op | ':'
name | 'False'
op | ','
nl | '\n'
op | '}'
nl | '\n'
op | ']'
op | ','
nl | '\n'
name | 'FAKE_ACTION_ID2'
op | ':'
op | '['
op | '{'
string | "'id'"
op | ':'
number | '3'
op | ','
nl | '\n'
string | "'action_id'"
op | ':'
name | 'FAKE_ACTION_ID2'
op | ','
nl | '\n'
string | "'event'"
op | ':'
string | "'schedule'"
op | ','
nl | '\n'
string | "'start_time'"
op | ':'
name | 'datetime'
op | '.'
name | 'datetime'
op | '('
nl | '\n'
number | '2012'
op | ','
number | '12'
op | ','
number | '5'
op | ','
number | '3'
op | ','
number | '0'
op | ','
number | '0'
op | ','
number | '0'
op | ')'
op | ','
nl | '\n'
string | "'finish_time'"
op | ':'
name | 'datetime'
op | '.'
name | 'datetime'
op | '('
nl | '\n'
number | '2012'
op | ','
number | '12'
op | ','
number | '5'
op | ','
number | '3'
op | ','
number | '2'
op | ','
number | '0'
op | ','
number | '0'
op | ')'
op | ','
nl | '\n'
string | "'result'"
op | ':'
string | "'Error'"
op | ','
nl | '\n'
string | "'traceback'"
op | ':'
string | "''"
op | ','
nl | '\n'
string | "'created_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'updated_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted_at'"
op | ':'
name | 'None'
op | ','
nl | '\n'
string | "'deleted'"
op | ':'
name | 'False'
op | ','
nl | '\n'
op | '}'
nl | '\n'
op | ']'
nl | '\n'
op | '}'
newline | '\n'
nl | '\n'
nl | '\n'
DECL | function | fake_action_event_start
name | 'def'
name | 'fake_action_event_start'
op | '('
op | '*'
name | 'args'
op | ')'
op | ':'
newline | '\n'
indent | ' '
name | 'return'
name | 'FAKE_EVENTS'
op | '['
name | 'FAKE_ACTION_ID1'
op | ']'
op | '['
number | '0'
op | ']'
newline | '\n'
nl | '\n'
nl | '\n'
DECL | function | fake_action_event_finish
dedent | ''
name | 'def'
name | 'fake_action_event_finish'
op | '('
op | '*'
name | 'args'
op | ')'
op | ':'
newline | '\n'
indent | ' '
name | 'return'
name | 'FAKE_EVENTS'
op | '['
name | 'FAKE_ACTION_ID1'
op | ']'
op | '['
number | '0'
op | ']'
newline | '\n'
nl | '\n'
nl | '\n'
DECL | function | stub_out_action_events
dedent | ''
name | 'def'
name | 'stub_out_action_events'
op | '('
name | 'stubs'
op | ')'
op | ':'
newline | '\n'
indent | ' '
name | 'stubs'
op | '.'
name | 'Set'
op | '('
name | 'db'
op | ','
string | "'action_event_start'"
op | ','
name | 'fake_action_event_start'
op | ')'
newline | '\n'
name | 'stubs'
op | '.'
name | 'Set'
op | '('
name | 'db'
op | ','
string | "'action_event_finish'"
op | ','
name | 'fake_action_event_finish'
op | ')'
newline | '\n'
dedent | ''
endmarker | ''
end_unit |
## https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/
## Restrictions with multiple metaclasses
# class Meta1(type):
# pass
# class Meta2(type):
# pass
# class Base1(metaclass=Meta1):
# pass
# class Base2(metaclass=Meta2):
# pass
# class Foobar(Base1, Base2):
# pass
# class Meta(type):
# pass
# class SubMeta(Meta):
# pass
class Base1(metaclass=Meta):
pass
class Base2(metaclass=SubMeta):
pass
class Foobar(Base1, Base2):
pass
type(Foobar)
| class Base1(metaclass=Meta):
pass
class Base2(metaclass=SubMeta):
pass
class Foobar(Base1, Base2):
pass
type(Foobar) |
# 14. Longest Common Prefix
# Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix = ""
if not strs: return prefix
shortest = min(strs, key = len)
for i in range(len(shortest)):
if all([x.startswith(shortest[:i+1]) for x in strs]):
prefix = shortest[:i+1]
else:
break
return prefix | class Solution(object):
def longest_common_prefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix = ''
if not strs:
return prefix
shortest = min(strs, key=len)
for i in range(len(shortest)):
if all([x.startswith(shortest[:i + 1]) for x in strs]):
prefix = shortest[:i + 1]
else:
break
return prefix |
STRING_FILTER = 'string'
CHOICE_FILTER = 'choice'
BOOLEAN_FILTER = 'boolean'
RADIO_FILTER = 'radio'
HALF_WIDTH_FILTER = 'half_width'
FULL_WIDTH_FILTER = 'full_width'
VALID_FILTERS = (
STRING_FILTER,
CHOICE_FILTER,
BOOLEAN_FILTER,
RADIO_FILTER,
)
VALID_FILTER_WIDTHS = (
HALF_WIDTH_FILTER,
FULL_WIDTH_FILTER,
)
SORT_PARAM = 'sort'
LAYOUT_PARAM = 'layout'
# These constructors are using pascal case to masquerade as classes, but they're simply
# generating dictionaries that declare the desired structure for the UI. This helps to
# reduce verbosity when declaring options, while also providing an API that'll allow us
# to add more features/validation/etc.
def ListViewOptions(filters=None, sorts=None, layouts=None):
assert isinstance(filters, (dict, type(None)))
assert isinstance(sorts, (dict, type(None)))
assert isinstance(layouts, (dict, type(None)))
return {
'filters': filters,
'sorts': sorts,
'layouts': layouts,
}
def FilterOptions(children):
assert isinstance(children, list)
return {
'object_type': 'filter_options',
'children': children,
}
def FilterGroup(title, children):
assert isinstance(title, str)
assert isinstance(children, list)
for obj in children:
assert isinstance(obj, dict)
return {
'object_type': 'filter_group',
'title': title,
'children': children,
}
def Filter(
name, label, type, value, results_description, choices=None, multiple=None, clearable=None,
width=None, is_default=None,
):
if width is None:
width = HALF_WIDTH_FILTER
assert type in VALID_FILTERS
assert width in VALID_FILTER_WIDTHS
return {
'object_type': 'filter',
'name': name,
'label': label,
'type': type,
'value': value,
'results_description': results_description,
'choices': choices,
'multiple': multiple,
'clearable': clearable,
'width': width,
'is_default': is_default,
}
def SortOptions(children):
assert isinstance(children, list)
return {
'object_type': 'sort_options',
'children': children,
}
def Sort(label, value, is_selected, results_description, name=None, is_default=None):
if name is None:
name = SORT_PARAM
return {
'object_type': 'sort',
'name': name,
'label': label,
'value': value,
'is_selected': is_selected,
'results_description': results_description,
'is_default': is_default,
}
def LayoutOptions(children):
assert isinstance(children, list)
return {
'object_type': 'layout_options',
'children': children,
}
def Layout(label, value, is_selected, icon_class, template=None, name=None):
if name is None:
name = LAYOUT_PARAM
return {
'object_type': 'layout',
'name': name,
'label': label,
'value': value,
'is_selected': is_selected,
'icon_class': icon_class,
'template': template,
}
| string_filter = 'string'
choice_filter = 'choice'
boolean_filter = 'boolean'
radio_filter = 'radio'
half_width_filter = 'half_width'
full_width_filter = 'full_width'
valid_filters = (STRING_FILTER, CHOICE_FILTER, BOOLEAN_FILTER, RADIO_FILTER)
valid_filter_widths = (HALF_WIDTH_FILTER, FULL_WIDTH_FILTER)
sort_param = 'sort'
layout_param = 'layout'
def list_view_options(filters=None, sorts=None, layouts=None):
assert isinstance(filters, (dict, type(None)))
assert isinstance(sorts, (dict, type(None)))
assert isinstance(layouts, (dict, type(None)))
return {'filters': filters, 'sorts': sorts, 'layouts': layouts}
def filter_options(children):
assert isinstance(children, list)
return {'object_type': 'filter_options', 'children': children}
def filter_group(title, children):
assert isinstance(title, str)
assert isinstance(children, list)
for obj in children:
assert isinstance(obj, dict)
return {'object_type': 'filter_group', 'title': title, 'children': children}
def filter(name, label, type, value, results_description, choices=None, multiple=None, clearable=None, width=None, is_default=None):
if width is None:
width = HALF_WIDTH_FILTER
assert type in VALID_FILTERS
assert width in VALID_FILTER_WIDTHS
return {'object_type': 'filter', 'name': name, 'label': label, 'type': type, 'value': value, 'results_description': results_description, 'choices': choices, 'multiple': multiple, 'clearable': clearable, 'width': width, 'is_default': is_default}
def sort_options(children):
assert isinstance(children, list)
return {'object_type': 'sort_options', 'children': children}
def sort(label, value, is_selected, results_description, name=None, is_default=None):
if name is None:
name = SORT_PARAM
return {'object_type': 'sort', 'name': name, 'label': label, 'value': value, 'is_selected': is_selected, 'results_description': results_description, 'is_default': is_default}
def layout_options(children):
assert isinstance(children, list)
return {'object_type': 'layout_options', 'children': children}
def layout(label, value, is_selected, icon_class, template=None, name=None):
if name is None:
name = LAYOUT_PARAM
return {'object_type': 'layout', 'name': name, 'label': label, 'value': value, 'is_selected': is_selected, 'icon_class': icon_class, 'template': template} |
class Passenger():
def __init__(self, weight, floor, destination, time):
self.weight = weight
self.floor = floor
self.destination = destination
self.elevator = None
self.created_at = time
def enter(self, elevator):
'''
Input: the elevator that the passenger attempts to enter
'''
if elevator.enter(self):
self.elevator = elevator
self.elevator.request(self.destination)
return True
return False
def leave_if_arrived(self):
if self.destination == self.floor:
self.elevator.leave(self)
return True
return False
def update_floor(self, floor):
'''Allows the elevator to update the floor attribute of the passenger'''
self.floor = floor
| class Passenger:
def __init__(self, weight, floor, destination, time):
self.weight = weight
self.floor = floor
self.destination = destination
self.elevator = None
self.created_at = time
def enter(self, elevator):
"""
Input: the elevator that the passenger attempts to enter
"""
if elevator.enter(self):
self.elevator = elevator
self.elevator.request(self.destination)
return True
return False
def leave_if_arrived(self):
if self.destination == self.floor:
self.elevator.leave(self)
return True
return False
def update_floor(self, floor):
"""Allows the elevator to update the floor attribute of the passenger"""
self.floor = floor |
# ============================================================
# Title: Keep Talking and Nobody Explodes Solver: Who's on First?
# Author: Ryan J. Slater
# Date: 4/4/2019
# ============================================================
def solveSimonSays(textList, # List of strings [displayText, topLeft, topRight, middleLeft, middleRight, bottomLeft, bottomRight]
bombSpecs): # Dictionary of bomb specs such as serial number last digit, parallel port, battery count, etc
# Top Left
if textList[0] in ['ur']:
return getResponsesFromWord(textList[1])
# Top Right
elif textList[0] in ['first', 'okay', 'c']:
return getResponsesFromWord(textList[2])
# Middle Left
elif textList[0] in ['yes', 'nothing', 'led', 'they are']:
return getResponsesFromWord(textList[3])
# Middle Right
elif textList[0] in ['blank', 'read', 'red', 'you', 'you\'re', 'their']:
return getResponsesFromWord(textList[4])
# Bottom Left
elif textList[0] in ['', 'reed', 'leed', 'they\'re']:
return getResponsesFromWord(textList[5])
# Bottom Right
elif textList[0] in ['display', 'says', 'no', 'lead', 'hold on', 'you are', 'there', 'see', 'cee']:
return getResponsesFromWord(textList[6])
def getResponsesFromWord(word): # Word to be used as the key for step 2
# Returns a csv string in the order of words to try
if word == 'ready':
return 'YES, OKAY, WHAT, MIDDLE, LEFT, PRESS, RIGHT, BLANK, READY, NO, FIRST, UHHH, NOTHING, WAIT'.lower()
elif word == 'first':
return 'LEFT, OKAY, YES, MIDDLE, NO, RIGHT, NOTHING, UHHH, WAIT, READY, BLANK, WHAT, PRESS, FIRST'.lower()
elif word == 'no':
return 'BLANK, UHHH, WAIT, FIRST, WHAT, READY, RIGHT, YES, NOTHING, LEFT, PRESS, OKAY, NO, MIDDLE'.lower()
elif word == 'blank':
return 'WAIT, RIGHT, OKAY, MIDDLE, BLANK, PRESS, READY, NOTHING, NO, WHAT, LEFT, UHHH, YES, FIRST'.lower()
elif word == 'nothing':
return 'UHHH, RIGHT, OKAY, MIDDLE, YES, BLANK, NO, PRESS, LEFT, WHAT, WAIT, FIRST, NOTHING, READY'.lower()
elif word == 'yes':
return 'OKAY, RIGHT, UHHH, MIDDLE, FIRST, WHAT, PRESS, READY, NOTHING, YES, LEFT, BLANK, NO, WAIT'.lower()
elif word == 'what':
return 'UHHH, WHAT, LEFT, NOTHING, READY, BLANK, MIDDLE, NO, OKAY, FIRST, WAIT, YES, PRESS, RIGHT'.lower()
elif word == 'uhhh':
return 'READY, NOTHING, LEFT, WHAT, OKAY, YES, RIGHT, NO, PRESS, BLANK, UHHH, MIDDLE, WAIT, FIRST'.lower()
elif word == 'left':
return 'RIGHT, LEFT, FIRST, NO, MIDDLE, YES, BLANK, WHAT, UHHH, WAIT, PRESS, READY, OKAY, NOTHING'.lower()
elif word == 'right':
return 'YES, NOTHING, READY, PRESS, NO, WAIT, WHAT, RIGHT, MIDDLE, LEFT, UHHH, BLANK, OKAY, FIRST'.lower()
elif word == 'middle':
return 'BLANK, READY, OKAY, WHAT, NOTHING, PRESS, NO, WAIT, LEFT, MIDDLE, RIGHT, FIRST, UHHH, YES'.lower()
elif word == 'okay':
return 'MIDDLE, NO, FIRST, YES, UHHH, NOTHING, WAIT, OKAY, LEFT, READY, BLANK, PRESS, WHAT, RIGHT'.lower()
elif word == 'wait':
return 'UHHH, NO, BLANK, OKAY, YES, LEFT, FIRST, PRESS, WHAT, WAIT, NOTHING, READY, RIGHT, MIDDLE'.lower()
elif word == 'press':
return 'RIGHT, MIDDLE, YES, READY, PRESS, OKAY, NOTHING, UHHH, BLANK, LEFT, FIRST, WHAT, NO, WAIT'.lower()
elif word == 'you':
return 'SURE, YOU ARE, YOUR, YOU\'RE, NEXT, UH HUH, UR, HOLD, WHAT?, YOU, UH UH, LIKE, DONE, U'.lower()
elif word == 'you are':
return 'YOUR, NEXT, LIKE, UH HUH, WHAT?, DONE, UH UH, HOLD, YOU, U, YOU\'RE, SURE, UR, YOU ARE'.lower()
elif word == 'your':
return 'UH UH, YOU ARE, UH HUH, YOUR, NEXT, UR, SURE, U, YOU\'RE, YOU, WHAT?, HOLD, LIKE, DONE'.lower()
elif word == 'you\'re':
return 'YOU, YOU\'RE, UR, NEXT, UH UH, YOU ARE, U, YOUR, WHAT?, UH HUH, SURE, DONE, LIKE, HOLD'.lower()
elif word == 'ur':
return 'DONE, U, UR, UH HUH, WHAT?, SURE, YOUR, HOLD, YOU\'RE, LIKE, NEXT, UH UH, YOU ARE, YOU'.lower()
elif word == 'u':
return 'UH HUH, SURE, NEXT, WHAT?, YOU\'RE, UR, UH UH, DONE, U, YOU, LIKE, HOLD, YOU ARE, YOUR'.lower()
elif word == 'uh huh':
return 'UH HUH, YOUR, YOU ARE, YOU, DONE, HOLD, UH UH, NEXT, SURE, LIKE, YOU\'RE, UR, U, WHAT?'.lower()
elif word == 'uh uh':
return 'UR, U, YOU ARE, YOU\'RE, NEXT, UH UH, DONE, YOU, UH HUH, LIKE, YOUR, SURE, HOLD, WHAT?'.lower()
elif word == 'what?':
return 'YOU, HOLD, YOU\'RE, YOUR, U, DONE, UH UH, LIKE, YOU ARE, UH HUH, UR, NEXT, WHAT?, SURE'.lower()
elif word == 'done':
return 'SURE, UH HUH, NEXT, WHAT?, YOUR, UR, YOU\'RE, HOLD, LIKE, YOU, U, YOU ARE, UH UH, DONE'.lower()
elif word == 'next':
return 'WHAT?, UH HUH, UH UH, YOUR, HOLD, SURE, NEXT, LIKE, DONE, YOU ARE, UR, YOU\'RE, U, YOU'.lower()
elif word == 'hold':
return 'YOU ARE, U, DONE, UH UH, YOU, UR, SURE, WHAT?, YOU\'RE, NEXT, HOLD, UH HUH, YOUR, LIKE'.lower()
elif word == 'sure':
return 'YOU ARE, DONE, LIKE, YOU\'RE, YOU, HOLD, UH HUH, UR, SURE, U, WHAT?, NEXT, YOUR, UH UH'.lower()
elif word == 'like':
return 'YOU\'RE, NEXT, U, UR, HOLD, DONE, UH UH, WHAT?, UH HUH, YOU, LIKE, SURE, YOU ARE, YOUR'.lower()
| def solve_simon_says(textList, bombSpecs):
if textList[0] in ['ur']:
return get_responses_from_word(textList[1])
elif textList[0] in ['first', 'okay', 'c']:
return get_responses_from_word(textList[2])
elif textList[0] in ['yes', 'nothing', 'led', 'they are']:
return get_responses_from_word(textList[3])
elif textList[0] in ['blank', 'read', 'red', 'you', "you're", 'their']:
return get_responses_from_word(textList[4])
elif textList[0] in ['', 'reed', 'leed', "they're"]:
return get_responses_from_word(textList[5])
elif textList[0] in ['display', 'says', 'no', 'lead', 'hold on', 'you are', 'there', 'see', 'cee']:
return get_responses_from_word(textList[6])
def get_responses_from_word(word):
if word == 'ready':
return 'YES, OKAY, WHAT, MIDDLE, LEFT, PRESS, RIGHT, BLANK, READY, NO, FIRST, UHHH, NOTHING, WAIT'.lower()
elif word == 'first':
return 'LEFT, OKAY, YES, MIDDLE, NO, RIGHT, NOTHING, UHHH, WAIT, READY, BLANK, WHAT, PRESS, FIRST'.lower()
elif word == 'no':
return 'BLANK, UHHH, WAIT, FIRST, WHAT, READY, RIGHT, YES, NOTHING, LEFT, PRESS, OKAY, NO, MIDDLE'.lower()
elif word == 'blank':
return 'WAIT, RIGHT, OKAY, MIDDLE, BLANK, PRESS, READY, NOTHING, NO, WHAT, LEFT, UHHH, YES, FIRST'.lower()
elif word == 'nothing':
return 'UHHH, RIGHT, OKAY, MIDDLE, YES, BLANK, NO, PRESS, LEFT, WHAT, WAIT, FIRST, NOTHING, READY'.lower()
elif word == 'yes':
return 'OKAY, RIGHT, UHHH, MIDDLE, FIRST, WHAT, PRESS, READY, NOTHING, YES, LEFT, BLANK, NO, WAIT'.lower()
elif word == 'what':
return 'UHHH, WHAT, LEFT, NOTHING, READY, BLANK, MIDDLE, NO, OKAY, FIRST, WAIT, YES, PRESS, RIGHT'.lower()
elif word == 'uhhh':
return 'READY, NOTHING, LEFT, WHAT, OKAY, YES, RIGHT, NO, PRESS, BLANK, UHHH, MIDDLE, WAIT, FIRST'.lower()
elif word == 'left':
return 'RIGHT, LEFT, FIRST, NO, MIDDLE, YES, BLANK, WHAT, UHHH, WAIT, PRESS, READY, OKAY, NOTHING'.lower()
elif word == 'right':
return 'YES, NOTHING, READY, PRESS, NO, WAIT, WHAT, RIGHT, MIDDLE, LEFT, UHHH, BLANK, OKAY, FIRST'.lower()
elif word == 'middle':
return 'BLANK, READY, OKAY, WHAT, NOTHING, PRESS, NO, WAIT, LEFT, MIDDLE, RIGHT, FIRST, UHHH, YES'.lower()
elif word == 'okay':
return 'MIDDLE, NO, FIRST, YES, UHHH, NOTHING, WAIT, OKAY, LEFT, READY, BLANK, PRESS, WHAT, RIGHT'.lower()
elif word == 'wait':
return 'UHHH, NO, BLANK, OKAY, YES, LEFT, FIRST, PRESS, WHAT, WAIT, NOTHING, READY, RIGHT, MIDDLE'.lower()
elif word == 'press':
return 'RIGHT, MIDDLE, YES, READY, PRESS, OKAY, NOTHING, UHHH, BLANK, LEFT, FIRST, WHAT, NO, WAIT'.lower()
elif word == 'you':
return "SURE, YOU ARE, YOUR, YOU'RE, NEXT, UH HUH, UR, HOLD, WHAT?, YOU, UH UH, LIKE, DONE, U".lower()
elif word == 'you are':
return "YOUR, NEXT, LIKE, UH HUH, WHAT?, DONE, UH UH, HOLD, YOU, U, YOU'RE, SURE, UR, YOU ARE".lower()
elif word == 'your':
return "UH UH, YOU ARE, UH HUH, YOUR, NEXT, UR, SURE, U, YOU'RE, YOU, WHAT?, HOLD, LIKE, DONE".lower()
elif word == "you're":
return "YOU, YOU'RE, UR, NEXT, UH UH, YOU ARE, U, YOUR, WHAT?, UH HUH, SURE, DONE, LIKE, HOLD".lower()
elif word == 'ur':
return "DONE, U, UR, UH HUH, WHAT?, SURE, YOUR, HOLD, YOU'RE, LIKE, NEXT, UH UH, YOU ARE, YOU".lower()
elif word == 'u':
return "UH HUH, SURE, NEXT, WHAT?, YOU'RE, UR, UH UH, DONE, U, YOU, LIKE, HOLD, YOU ARE, YOUR".lower()
elif word == 'uh huh':
return "UH HUH, YOUR, YOU ARE, YOU, DONE, HOLD, UH UH, NEXT, SURE, LIKE, YOU'RE, UR, U, WHAT?".lower()
elif word == 'uh uh':
return "UR, U, YOU ARE, YOU'RE, NEXT, UH UH, DONE, YOU, UH HUH, LIKE, YOUR, SURE, HOLD, WHAT?".lower()
elif word == 'what?':
return "YOU, HOLD, YOU'RE, YOUR, U, DONE, UH UH, LIKE, YOU ARE, UH HUH, UR, NEXT, WHAT?, SURE".lower()
elif word == 'done':
return "SURE, UH HUH, NEXT, WHAT?, YOUR, UR, YOU'RE, HOLD, LIKE, YOU, U, YOU ARE, UH UH, DONE".lower()
elif word == 'next':
return "WHAT?, UH HUH, UH UH, YOUR, HOLD, SURE, NEXT, LIKE, DONE, YOU ARE, UR, YOU'RE, U, YOU".lower()
elif word == 'hold':
return "YOU ARE, U, DONE, UH UH, YOU, UR, SURE, WHAT?, YOU'RE, NEXT, HOLD, UH HUH, YOUR, LIKE".lower()
elif word == 'sure':
return "YOU ARE, DONE, LIKE, YOU'RE, YOU, HOLD, UH HUH, UR, SURE, U, WHAT?, NEXT, YOUR, UH UH".lower()
elif word == 'like':
return "YOU'RE, NEXT, U, UR, HOLD, DONE, UH UH, WHAT?, UH HUH, YOU, LIKE, SURE, YOU ARE, YOUR".lower() |
#coding:utf-8
#pulic
BASE_DIR = "/home/dengerqiang/Documents/WORK/"
VQA_BASE = BASE_DIR + 'VQA/'
DATA10 = VQA_BASE + "data1.0/"
DATA20 = VQA_BASE + "data2.0/"
IMAGE_DIR = VQA_BASE + "images/"
GLOVE_DIR = BASE_DIR + 'glove/'
NLTK_DIR = BASE_DIR + "nltk_data"
#private
WORK_DIR = BASE_DIR+ "VQA/DenseCoAttention/"
GLOVE_FILE = "glove.6B.100d.pt"
#global arguments
RNN_DIM = 100
CNN_TYPE = "resnet152" | base_dir = '/home/dengerqiang/Documents/WORK/'
vqa_base = BASE_DIR + 'VQA/'
data10 = VQA_BASE + 'data1.0/'
data20 = VQA_BASE + 'data2.0/'
image_dir = VQA_BASE + 'images/'
glove_dir = BASE_DIR + 'glove/'
nltk_dir = BASE_DIR + 'nltk_data'
work_dir = BASE_DIR + 'VQA/DenseCoAttention/'
glove_file = 'glove.6B.100d.pt'
rnn_dim = 100
cnn_type = 'resnet152' |
#!/usr/bin/python
class RedditUser:
def __init__(
self,
name: str,
can_submit_guess: bool = True,
is_potential_winner: bool = False,
num_guesses: int = 0,
):
"""
Parametrized constructor
"""
self.name = name
self.can_submit_guess = can_submit_guess
self.is_potential_winner = is_potential_winner
self.num_guesses = num_guesses
| class Reddituser:
def __init__(self, name: str, can_submit_guess: bool=True, is_potential_winner: bool=False, num_guesses: int=0):
"""
Parametrized constructor
"""
self.name = name
self.can_submit_guess = can_submit_guess
self.is_potential_winner = is_potential_winner
self.num_guesses = num_guesses |
def toMinutesArray(times: str):
res = [0, 0]
startEnd = times.split()
hourMin = startEnd[0].split(':')
res[0] = int(hourMin[0]) * 60 + int(hourMin[1])
hourMin = startEnd[1].split(':')
res[1] = int(hourMin[0]) * 60 + int(hourMin[1])
return res
MAX_MINS = 1500
N = int(input())
table = [0] * MAX_MINS
res = 0
for i in range(N):
startEnd = toMinutesArray(input())
table[startEnd[0]] += 1
table[startEnd[1]] -= 1
for i in range(1, MAX_MINS):
table[i] += table[i-1]
res = max(res, table[i])
print(res)
| def to_minutes_array(times: str):
res = [0, 0]
start_end = times.split()
hour_min = startEnd[0].split(':')
res[0] = int(hourMin[0]) * 60 + int(hourMin[1])
hour_min = startEnd[1].split(':')
res[1] = int(hourMin[0]) * 60 + int(hourMin[1])
return res
max_mins = 1500
n = int(input())
table = [0] * MAX_MINS
res = 0
for i in range(N):
start_end = to_minutes_array(input())
table[startEnd[0]] += 1
table[startEnd[1]] -= 1
for i in range(1, MAX_MINS):
table[i] += table[i - 1]
res = max(res, table[i])
print(res) |
# For the central discovery server
LOG_FILE = 'discovered.pkl'
DISCOVERY_PORT = 4444
MESSAGING_PORT = 8192
PROMPT_FILE = 'prompt'
SHARED_FOLDER = 'shared'
DOWNLOAD_FOLDER = 'download'
CHUNK_SIZE = 1000000 | log_file = 'discovered.pkl'
discovery_port = 4444
messaging_port = 8192
prompt_file = 'prompt'
shared_folder = 'shared'
download_folder = 'download'
chunk_size = 1000000 |
class FindImage:
def __init__(self, image_repo):
self.image_repo = image_repo
def by_ayah_id(self, ayah_id):
return self.image_repo.find_by_ayah_id(ayah_id) | class Findimage:
def __init__(self, image_repo):
self.image_repo = image_repo
def by_ayah_id(self, ayah_id):
return self.image_repo.find_by_ayah_id(ayah_id) |
# Copyright 2020 Google LLC
#
# 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
#
# https://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.
"""
Rules for generating ruby code with protoc
including rules for ruby, grpc-ruby, and various flavors of gapic-generator-ruby
"""
load(
":private/ruby_gapic_library_internal.bzl",
_ruby_gapic_library_internal = "ruby_gapic_library_internal",
)
load("@rules_gapic//:gapic.bzl", "proto_custom_library")
##
# A macro over the proto_custom_library that generates a library
# using the gapic-generator entrypoint
#
# name: name of the rule
# srcs: proto files wrapped in the proto_library rule
# extra_protoc_parameters: a list of the generator parameters in the form of "key=value" strings
# (e.g. gem-name=a-gem-name-v1)
# yml_configs: a list of labels of the yaml configs (or an empty list)
# grpc_service_config: a label to the grpc service config
#
def ruby_gapic_library(
name,
srcs,
extra_protoc_parameters = [],
yml_configs = [],
grpc_service_config = None,
**kwargs):
_ruby_gapic_library_internal(
name,
srcs,
Label("//rules_ruby_gapic/gapic-generator:gapic_generator_ruby"),
extra_protoc_parameters,
yml_configs,
grpc_service_config
)
##
# A macro over the proto_custom_library that generates a library
# using the gapic-generator-cloud entrypoint
#
# name: name of the rule
# srcs: proto files wrapped in the proto_library rule
# ruby_cloud_title: cloud gem's title.
# It is separated from the extra_protoc_parameters because of issues with build_gen: https://github.com/googleapis/gapic-generator-ruby/issues/539
# ruby_cloud_description: cloud gem's description.
# It is separated from the extra_protoc_parameters because of issues with build_gen: https://github.com/googleapis/gapic-generator-ruby/issues/539
# extra_protoc_parameters: a list of the generator parameters in the form of "key=value" strings
# (e.g. ruby-cloud-gem-name=google-cloud-gem-name-v1)
# grpc_service_config: a label to the grpc service config
#
def ruby_cloud_gapic_library(
name,
srcs,
ruby_cloud_title = "",
ruby_cloud_description = "",
extra_protoc_parameters = [],
grpc_service_config = None,
**kwargs):
if extra_protoc_parameters:
for key_val_string in extra_protoc_parameters:
key_val_split = key_val_string.split("=", 1)
if len(key_val_split) < 2:
fail("Parameter '{key_val_string}' is not in the 'key=value' format".format(key_val_string=key_val_string))
key = key_val_split[0].strip()
if key == "ruby-cloud-title":
fail("Parameter 'ruby-cloud-title' should be specified in a separate Bazel rule attribute 'ruby_cloud_title'")
if key == "ruby-cloud-description":
fail("Parameter 'ruby-cloud-description' should be specified in a separate Bazel rule attribute 'ruby_cloud_description'")
if ruby_cloud_title:
extra_protoc_parameters.append("ruby-cloud-title={value}".format(value = ruby_cloud_title))
if ruby_cloud_description:
extra_protoc_parameters.append("ruby-cloud-description={value}".format(value = ruby_cloud_description))
_ruby_gapic_library_internal(
name,
srcs,
Label("//rules_ruby_gapic/gapic-generator-cloud:gapic_generator_cloud"),
extra_protoc_parameters,
[],
grpc_service_config
)
##
# A macro over the proto_custom_library that generates a library
# using the gapic-generator-ads entrypoint
#
# name: name of the rule
# srcs: proto files wrapped in the proto_library rule
# extra_protoc_parameters: a list of the generator parameters in the form of "key=value" strings
# (e.g. gem-name=google-ads-googleads)
# grpc_service_config: a label to the grpc service config
#
def ruby_ads_gapic_library(
name,
srcs,
extra_protoc_parameters = [],
grpc_service_config = None,
**kwargs):
_ruby_gapic_library_internal(
name,
srcs,
Label("//rules_ruby_gapic/gapic-generator-ads:gapic_generator_ads"),
extra_protoc_parameters,
[],
grpc_service_config
)
##
# A macro over the proto_custom_library that runs protoc with a ruby plugin
#
# name: name of the rule
# deps: proto files wrapped in the proto_library rule
#
def ruby_proto_library(name, deps, **kwargs):
# Build zip file of protoc output
proto_custom_library(
name = name,
deps = deps,
output_type = "ruby",
output_suffix = ".srcjar",
**kwargs
)
##
# A macro over the proto_custom_library that runs protoc with a grpc-ruby plugin
#
# name: name of the rule
# srcs: proto files wrapped in the proto_library rule
# deps: a ruby_proto_library output
#
def ruby_grpc_library(name, srcs, deps, **kwargs):
# Build zip file of grpc output
proto_custom_library(
name = name,
deps = srcs,
plugin = Label("@com_github_grpc_grpc//src/compiler:grpc_ruby_plugin"),
output_type = "grpc",
output_suffix = ".srcjar",
**kwargs
)
| """
Rules for generating ruby code with protoc
including rules for ruby, grpc-ruby, and various flavors of gapic-generator-ruby
"""
load(':private/ruby_gapic_library_internal.bzl', _ruby_gapic_library_internal='ruby_gapic_library_internal')
load('@rules_gapic//:gapic.bzl', 'proto_custom_library')
def ruby_gapic_library(name, srcs, extra_protoc_parameters=[], yml_configs=[], grpc_service_config=None, **kwargs):
_ruby_gapic_library_internal(name, srcs, label('//rules_ruby_gapic/gapic-generator:gapic_generator_ruby'), extra_protoc_parameters, yml_configs, grpc_service_config)
def ruby_cloud_gapic_library(name, srcs, ruby_cloud_title='', ruby_cloud_description='', extra_protoc_parameters=[], grpc_service_config=None, **kwargs):
if extra_protoc_parameters:
for key_val_string in extra_protoc_parameters:
key_val_split = key_val_string.split('=', 1)
if len(key_val_split) < 2:
fail("Parameter '{key_val_string}' is not in the 'key=value' format".format(key_val_string=key_val_string))
key = key_val_split[0].strip()
if key == 'ruby-cloud-title':
fail("Parameter 'ruby-cloud-title' should be specified in a separate Bazel rule attribute 'ruby_cloud_title'")
if key == 'ruby-cloud-description':
fail("Parameter 'ruby-cloud-description' should be specified in a separate Bazel rule attribute 'ruby_cloud_description'")
if ruby_cloud_title:
extra_protoc_parameters.append('ruby-cloud-title={value}'.format(value=ruby_cloud_title))
if ruby_cloud_description:
extra_protoc_parameters.append('ruby-cloud-description={value}'.format(value=ruby_cloud_description))
_ruby_gapic_library_internal(name, srcs, label('//rules_ruby_gapic/gapic-generator-cloud:gapic_generator_cloud'), extra_protoc_parameters, [], grpc_service_config)
def ruby_ads_gapic_library(name, srcs, extra_protoc_parameters=[], grpc_service_config=None, **kwargs):
_ruby_gapic_library_internal(name, srcs, label('//rules_ruby_gapic/gapic-generator-ads:gapic_generator_ads'), extra_protoc_parameters, [], grpc_service_config)
def ruby_proto_library(name, deps, **kwargs):
proto_custom_library(name=name, deps=deps, output_type='ruby', output_suffix='.srcjar', **kwargs)
def ruby_grpc_library(name, srcs, deps, **kwargs):
proto_custom_library(name=name, deps=srcs, plugin=label('@com_github_grpc_grpc//src/compiler:grpc_ruby_plugin'), output_type='grpc', output_suffix='.srcjar', **kwargs) |
# -*- coding: utf-8 -*-
"""
> 005 @ Jane Street
~~~~~~~~~~~~~~~~~~~
```cons(a, b)``` constructs a pair, and ```car(pair)``` and ```cdr(pair)``` returns
the first and last element of that pair. For example, ```car(cons(3, 4))``` returns
```3```, and ```cdr(cons(3, 4))``` returns ```4```.
Given this implementation of cons:
```Python
def cons(a, b):
def pair(f):
return f(a, b)
return pair
```
Implement ```car``` and ```cdr```.
"""
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(f):
def left(a, b):
return a
return f(left)
def cdr(f):
def right(a, b):
return b
return f(right)
if __name__ == "__main__":
assert car(cons(3, 4)) == 3
assert cdr(cons(3, 4)) == 4
| """
> 005 @ Jane Street
~~~~~~~~~~~~~~~~~~~
```cons(a, b)``` constructs a pair, and ```car(pair)``` and ```cdr(pair)``` returns
the first and last element of that pair. For example, ```car(cons(3, 4))``` returns
```3```, and ```cdr(cons(3, 4))``` returns ```4```.
Given this implementation of cons:
```Python
def cons(a, b):
def pair(f):
return f(a, b)
return pair
```
Implement ```car``` and ```cdr```.
"""
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(f):
def left(a, b):
return a
return f(left)
def cdr(f):
def right(a, b):
return b
return f(right)
if __name__ == '__main__':
assert car(cons(3, 4)) == 3
assert cdr(cons(3, 4)) == 4 |
# To review... adding up the lengths of strings in a list
# e.g. totalLength(["UCSB","Apple","Pie"]) should be: 12
# because len("UCSB")=4, len("Apple")=5, and len("Pie")=3, and 4+5+3 = 12
def totalLength(listOfStrings):
" add up length of all the strings "
# for now, ignore errors.. assume they are all of type str
count = 0
for string in listOfStrings:
count = count + len(string)
return count
def test_totalLength_1():
assert totalLength(["UCSB","Apple","Pie"])==12
def test_totalLength_2():
assert totalLength([])==0
def test_totalLength_3():
assert totalLength(["Cal Poly"])==8
| def total_length(listOfStrings):
""" add up length of all the strings """
count = 0
for string in listOfStrings:
count = count + len(string)
return count
def test_total_length_1():
assert total_length(['UCSB', 'Apple', 'Pie']) == 12
def test_total_length_2():
assert total_length([]) == 0
def test_total_length_3():
assert total_length(['Cal Poly']) == 8 |
T = int(input(''))
X = 0
Y = 0
for i in range(T):
B = int(input(''))
A1, D1, L1 = map(int, input().split())
A2, D2, L2 = map(int, input().split())
X = (A1 + D1) / 2
if L1 % 2 == 0:
X = X + L1
Y = (A2 + D2) / 2
if L2 % 2 == 0:
Y = Y + L1
if X == Y:
print('Empate')
elif X > Y:
print('Dabriel')
else:
print('Guarte')
| t = int(input(''))
x = 0
y = 0
for i in range(T):
b = int(input(''))
(a1, d1, l1) = map(int, input().split())
(a2, d2, l2) = map(int, input().split())
x = (A1 + D1) / 2
if L1 % 2 == 0:
x = X + L1
y = (A2 + D2) / 2
if L2 % 2 == 0:
y = Y + L1
if X == Y:
print('Empate')
elif X > Y:
print('Dabriel')
else:
print('Guarte') |
class Solution:
def XXX(self, n: int) -> str:
ans = '1#'
for i in range(1, n):
t, cnt = '', 1
for j in range(1, len(ans)):
if ans[j] == ans[j - 1]:
cnt += 1
else:
t += (str(cnt) + ans[j - 1])
cnt = 1
t += '#'
ans = t
return ans[:-1]
| class Solution:
def xxx(self, n: int) -> str:
ans = '1#'
for i in range(1, n):
(t, cnt) = ('', 1)
for j in range(1, len(ans)):
if ans[j] == ans[j - 1]:
cnt += 1
else:
t += str(cnt) + ans[j - 1]
cnt = 1
t += '#'
ans = t
return ans[:-1] |
# This kata was seen in programming competitions with a wide range of variations. A strict bouncy array of numbers, of
# length three or longer, is an array that each term (neither the first nor the last element) is strictly higher or lower
# than its neighbours.
# For example, the array:
# arr = [7,9,6,10,5,11,10,12,13,4,2,5,1,6,4,8] (length = 16)
# The two longest bouncy subarrays of arr are
# [7,9,6,10,5,11,10,12] (length = 8) and [4,2,5,1,6,4,8] (length = 7)
# According to the given definition, the arrays [8,1,4,6,7], [1,2,2,1,4,5], are not bouncy.
# For the special case of length 2 arrays, we will consider them strict bouncy if the two elements are different.
# The arrays [-1,4] and [0,-10] are both bouncy, while [0,0] is not.
# An array of length 1 will be considered strict bouncy itself.
# You will be given an array of integers and you should output the longest strict bouncy subarray.
# In the case of having more than one bouncy subarray of same length, it should be output the subarray with its first term of lowest index in the original array.
# Let's see the result for the first given example.
# arr = [7,9,6,10,5,11,10,12,13,4,2,5,1,6,4,8]
# longest_bouncy_list(arr) === [7,9,6,10,5,11,10,12]
# See more examples in the example tests box.
# Features of the random tests
# length of the array inputs up to 1000
# -500 <= arr[i] <= 500
# Toy Problem in Progress
# Giant Failure - Still in progress
def longest_bouncy_list(arr):
bounce = ''
count = 0
value = []
depths = [[] for i in range(4)]
if arr[1:] == arr[:-1]:
return [arr[0]]
if arr[0] < arr[1]:
bounce = 'low'
elif arr[0] > arr[1]:
bounce = 'high'
for x, y in zip(arr[::], arr[1::]):
current_depth = 0
if bounce == 'high' and x > y:
print("true high:", 'x:', x, 'y:', y)
count += 1
bounce = 'low'
depths[current_depth].append(x)
elif bounce == 'low' and x < y:
print("true low:", 'x:', x, 'y:', y)
count += 1
bounce = 'high'
depths[current_depth].append(x)
elif bounce == 'low' and x > y or bounce == 'high' and x < y:
current_depth += 1
depths[current_depth].append(x)
depths[current_depth].append(y)
print('break:', 'x:', x, 'y:', y)
print('depths:', depths)
arr4 = [10, 8, 1, -11, -14, 7, 0, 8, -2, 2, -9,
9, -2, 14, -16, -12, -12, -8, -1, -13, -11, 11]
print(longest_bouncy_list(arr4))
# [-11, -14, 7, 0, 8, -2, 2, -9, 9, -2, 14, -16, -12]
# [13, 2]
arr1 = [7, 9, 6, 10, 5, 11, 10, 12, 13, 4, 2, 5, 1, 6, 4, 8]
print(longest_bouncy_list(arr1))
# [7, 9, 6, 10, 5, 11, 10, 12]
# arr2 = [7, 7, 7, 7, 7]
# print(longest_bouncy_list(arr2))
# # [7]
# arr3 = [1, 2, 3, 4, 5, 6]
# print(longest_bouncy_list(arr3))
# [1,2]
| def longest_bouncy_list(arr):
bounce = ''
count = 0
value = []
depths = [[] for i in range(4)]
if arr[1:] == arr[:-1]:
return [arr[0]]
if arr[0] < arr[1]:
bounce = 'low'
elif arr[0] > arr[1]:
bounce = 'high'
for (x, y) in zip(arr[:], arr[1:]):
current_depth = 0
if bounce == 'high' and x > y:
print('true high:', 'x:', x, 'y:', y)
count += 1
bounce = 'low'
depths[current_depth].append(x)
elif bounce == 'low' and x < y:
print('true low:', 'x:', x, 'y:', y)
count += 1
bounce = 'high'
depths[current_depth].append(x)
elif bounce == 'low' and x > y or (bounce == 'high' and x < y):
current_depth += 1
depths[current_depth].append(x)
depths[current_depth].append(y)
print('break:', 'x:', x, 'y:', y)
print('depths:', depths)
arr4 = [10, 8, 1, -11, -14, 7, 0, 8, -2, 2, -9, 9, -2, 14, -16, -12, -12, -8, -1, -13, -11, 11]
print(longest_bouncy_list(arr4))
arr1 = [7, 9, 6, 10, 5, 11, 10, 12, 13, 4, 2, 5, 1, 6, 4, 8]
print(longest_bouncy_list(arr1)) |
DEFAULTS = {
'label': "{win[title]}",
'label_alt': "[class_name='{win[class_name]}' exe='{win[process][name]}' hwnd={win[hwnd]}]",
'label_no_window': None,
'max_length': None,
'max_length_ellipsis': '...',
'monitor_exclusive': True,
'ignore_windows': {
'classes': [],
'processes': [],
'titles': []
},
'callbacks': {
'on_left': 'toggle_label',
'on_middle': 'do_nothing',
'on_right': 'do_nothing'
}
}
VALIDATION_SCHEMA = {
'label': {
'type': 'string',
'default': DEFAULTS['label']
},
'label_alt': {
'type': 'string',
'default': DEFAULTS['label_alt']
},
'label_no_window': {
'type': 'string',
'nullable': True,
'default': DEFAULTS['label_no_window']
},
'max_length': {
'type': 'integer',
'min': 1,
'nullable': True,
'default': DEFAULTS['max_length']
},
'max_length_ellipsis': {
'type': 'string',
'default': DEFAULTS['max_length_ellipsis']
},
'monitor_exclusive': {
'type': 'boolean',
'required': False,
'default': DEFAULTS['monitor_exclusive']
},
'ignore_window': {
'type': 'dict',
'schema': {
'classes': {
'type': 'list',
'schema': {
'type': 'string'
},
'default': DEFAULTS['ignore_windows']['classes']
},
'processes': {
'type': 'list',
'schema': {
'type': 'string'
},
'default': DEFAULTS['ignore_windows']['processes']
},
'titles': {
'type': 'list',
'schema': {
'type': 'string'
},
'default': DEFAULTS['ignore_windows']['titles']
}
},
'default': DEFAULTS['ignore_windows']
},
'callbacks': {
'type': 'dict',
'schema': {
'on_left': {
'type': 'string',
'default': DEFAULTS['callbacks']['on_left'],
},
'on_middle': {
'type': 'string',
'default': DEFAULTS['callbacks']['on_middle'],
},
'on_right': {
'type': 'string',
'default': DEFAULTS['callbacks']['on_right']
}
},
'default': DEFAULTS['callbacks']
}
}
| defaults = {'label': '{win[title]}', 'label_alt': "[class_name='{win[class_name]}' exe='{win[process][name]}' hwnd={win[hwnd]}]", 'label_no_window': None, 'max_length': None, 'max_length_ellipsis': '...', 'monitor_exclusive': True, 'ignore_windows': {'classes': [], 'processes': [], 'titles': []}, 'callbacks': {'on_left': 'toggle_label', 'on_middle': 'do_nothing', 'on_right': 'do_nothing'}}
validation_schema = {'label': {'type': 'string', 'default': DEFAULTS['label']}, 'label_alt': {'type': 'string', 'default': DEFAULTS['label_alt']}, 'label_no_window': {'type': 'string', 'nullable': True, 'default': DEFAULTS['label_no_window']}, 'max_length': {'type': 'integer', 'min': 1, 'nullable': True, 'default': DEFAULTS['max_length']}, 'max_length_ellipsis': {'type': 'string', 'default': DEFAULTS['max_length_ellipsis']}, 'monitor_exclusive': {'type': 'boolean', 'required': False, 'default': DEFAULTS['monitor_exclusive']}, 'ignore_window': {'type': 'dict', 'schema': {'classes': {'type': 'list', 'schema': {'type': 'string'}, 'default': DEFAULTS['ignore_windows']['classes']}, 'processes': {'type': 'list', 'schema': {'type': 'string'}, 'default': DEFAULTS['ignore_windows']['processes']}, 'titles': {'type': 'list', 'schema': {'type': 'string'}, 'default': DEFAULTS['ignore_windows']['titles']}}, 'default': DEFAULTS['ignore_windows']}, 'callbacks': {'type': 'dict', 'schema': {'on_left': {'type': 'string', 'default': DEFAULTS['callbacks']['on_left']}, 'on_middle': {'type': 'string', 'default': DEFAULTS['callbacks']['on_middle']}, 'on_right': {'type': 'string', 'default': DEFAULTS['callbacks']['on_right']}}, 'default': DEFAULTS['callbacks']}} |
#!python3
class Error(Exception):
pass
class IncompatibleArgumentError(Error):
pass
class DataShapeError(Error):
pass | class Error(Exception):
pass
class Incompatibleargumenterror(Error):
pass
class Datashapeerror(Error):
pass |
x = 9
def f(x):
return x
| x = 9
def f(x):
return x |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTilt(self, root: TreeNode) -> int:
tilt = [0]
def dfs(node):
if node is None: return 0
left = dfs(node.left)
right = dfs(node.right)
tilt[0] += abs(left - right)
return left + right + node.val
dfs(root)
return tilt[0]
| class Solution:
def find_tilt(self, root: TreeNode) -> int:
tilt = [0]
def dfs(node):
if node is None:
return 0
left = dfs(node.left)
right = dfs(node.right)
tilt[0] += abs(left - right)
return left + right + node.val
dfs(root)
return tilt[0] |
def test_filtering_sequential_blocks_with_bounded_range(
w3,
emitter,
Emitter,
wait_for_transaction):
builder = emitter.events.LogNoArguments.build_filter()
builder.fromBlock = "latest"
initial_block_number = w3.eth.block_number
builder.toBlock = initial_block_number + 100
filter_ = builder.deploy(w3)
for i in range(100):
emitter.functions.logNoArgs(which=1).transact()
assert w3.eth.block_number == initial_block_number + 100
assert len(filter_.get_new_entries()) == 100
def test_filtering_starting_block_range(
w3,
emitter,
Emitter,
wait_for_transaction):
for i in range(10):
emitter.functions.logNoArgs(which=1).transact()
builder = emitter.events.LogNoArguments.build_filter()
filter_ = builder.deploy(w3)
initial_block_number = w3.eth.block_number
for i in range(10):
emitter.functions.logNoArgs(which=1).transact()
assert w3.eth.block_number == initial_block_number + 10
assert len(filter_.get_new_entries()) == 10
def test_requesting_results_with_no_new_blocks(w3, emitter):
builder = emitter.events.LogNoArguments.build_filter()
filter_ = builder.deploy(w3)
assert len(filter_.get_new_entries()) == 0
| def test_filtering_sequential_blocks_with_bounded_range(w3, emitter, Emitter, wait_for_transaction):
builder = emitter.events.LogNoArguments.build_filter()
builder.fromBlock = 'latest'
initial_block_number = w3.eth.block_number
builder.toBlock = initial_block_number + 100
filter_ = builder.deploy(w3)
for i in range(100):
emitter.functions.logNoArgs(which=1).transact()
assert w3.eth.block_number == initial_block_number + 100
assert len(filter_.get_new_entries()) == 100
def test_filtering_starting_block_range(w3, emitter, Emitter, wait_for_transaction):
for i in range(10):
emitter.functions.logNoArgs(which=1).transact()
builder = emitter.events.LogNoArguments.build_filter()
filter_ = builder.deploy(w3)
initial_block_number = w3.eth.block_number
for i in range(10):
emitter.functions.logNoArgs(which=1).transact()
assert w3.eth.block_number == initial_block_number + 10
assert len(filter_.get_new_entries()) == 10
def test_requesting_results_with_no_new_blocks(w3, emitter):
builder = emitter.events.LogNoArguments.build_filter()
filter_ = builder.deploy(w3)
assert len(filter_.get_new_entries()) == 0 |
"""
reverse words
author oinegexruam@
"""
def reverse_word(word):
word_reverse = ''
for i in range(1, len(word) + 1):
index_reverse = len(word) - i
word_reverse += word[index_reverse]
return word_reverse
reverse_word(str(input('type a word: ')))
| """
reverse words
author oinegexruam@
"""
def reverse_word(word):
word_reverse = ''
for i in range(1, len(word) + 1):
index_reverse = len(word) - i
word_reverse += word[index_reverse]
return word_reverse
reverse_word(str(input('type a word: '))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.