content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
#############################################################################
# Copyright 2016 Mass KonFuzion
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#############################################################################
class CollisionGeomType:
aabb = 0
# TODO add more types? Or otherwise, get rid of this crap? I'm not sure if we'll need it
| class Collisiongeomtype:
aabb = 0 |
class Virus(object):
'''Properties and attributes of the virus used in Simulation.'''
def __init__(self, name, repro_rate, mortality_rate):
self.name = name
self.repro_rate = repro_rate
self.mortality_rate = mortality_rate
def test_virus_instantiation():
#TODO: Create your own test that models the virus you are working with
'''Check to make sure that the virus instantiator is working.'''
virus = Virus("HIV", 0.8, 0.3)
assert virus.name == "HIV"
assert virus.repro_rate == 0.8
assert virus.mortality_rate == 0.3
| class Virus(object):
"""Properties and attributes of the virus used in Simulation."""
def __init__(self, name, repro_rate, mortality_rate):
self.name = name
self.repro_rate = repro_rate
self.mortality_rate = mortality_rate
def test_virus_instantiation():
"""Check to make sure that the virus instantiator is working."""
virus = virus('HIV', 0.8, 0.3)
assert virus.name == 'HIV'
assert virus.repro_rate == 0.8
assert virus.mortality_rate == 0.3 |
def getInnerBlocks(string, begin, end, sep = [","]):
ret_list = []
if not isinstance(string, str):
return None
# read a name until depth 1. Store until depth 0, and append it along with
# the contents.
# at depth 0, ignore separators
cname = ""
depth = 0
last_name = ""
cstr = ""
clist = []
for char in string:
if char == end:
depth -= 1
if depth == 0:
clist.append(cstr)
ret_list.append({
'name': last_name,
'params': clist
})
clist = []
cstr = ""
if depth == 0:
if char not in sep and char not in [begin, end]:
cname += str(char)
elif depth == 1:
if char in sep:
clist.append(cstr)
cstr = ""
else:
cstr += str(char)
elif depth == 2:
cstr += str(char)
if char == begin:
depth += 1
if depth == 1:
last_name = cname
cname = ""
ret = []
for item in ret_list:
name = item['name'].strip()
params = []
for i in item['params']:
inner = getInnerBlocks(i.strip(), begin, end, sep)
if inner and len(inner) != 0:
params.extend(inner)
else:
params.append(i.strip())
ret.append({
'name': name,
'params': params
})
return ret
print(getInnerBlocks('2,3', '(', ')')) | def get_inner_blocks(string, begin, end, sep=[',']):
ret_list = []
if not isinstance(string, str):
return None
cname = ''
depth = 0
last_name = ''
cstr = ''
clist = []
for char in string:
if char == end:
depth -= 1
if depth == 0:
clist.append(cstr)
ret_list.append({'name': last_name, 'params': clist})
clist = []
cstr = ''
if depth == 0:
if char not in sep and char not in [begin, end]:
cname += str(char)
elif depth == 1:
if char in sep:
clist.append(cstr)
cstr = ''
else:
cstr += str(char)
elif depth == 2:
cstr += str(char)
if char == begin:
depth += 1
if depth == 1:
last_name = cname
cname = ''
ret = []
for item in ret_list:
name = item['name'].strip()
params = []
for i in item['params']:
inner = get_inner_blocks(i.strip(), begin, end, sep)
if inner and len(inner) != 0:
params.extend(inner)
else:
params.append(i.strip())
ret.append({'name': name, 'params': params})
return ret
print(get_inner_blocks('2,3', '(', ')')) |
def solve(n):
a = []
for _ in range(n):
name, h = input().split()
h = float(h)
a.append((name, h))
a.sort(key = lambda t: t[1], reverse=True)
m = a[0][1]
for n, h in a:
if h != m: break
print(n, end = " ")
print()
while True:
n = int(input())
if n == 0: break
solve(n)
| def solve(n):
a = []
for _ in range(n):
(name, h) = input().split()
h = float(h)
a.append((name, h))
a.sort(key=lambda t: t[1], reverse=True)
m = a[0][1]
for (n, h) in a:
if h != m:
break
print(n, end=' ')
print()
while True:
n = int(input())
if n == 0:
break
solve(n) |
# IDLE (Python 3.8.0)
# module_for_lists_of_terms
def termal_generator(lict):
length_of_termal_generator = 16
padding = length_of_termal_generator - len(lict)
count = padding
while count != 0:
lict.append([''])
count = count - 1
termal_lict = []
for first_inner in lict[0]:
for second_inner in lict[1]:
for third_inner in lict[2]:
for fourth_inner in lict[3]:
for fifth_inner in lict[4]:
for sixth_inner in lict[5]:
for seventh_inner in lict[6]:
for eighth_inner in lict[7]:
for ninth_inner in lict[8]:
for tenth_inner in lict[9]:
for eleventh_inner in lict[10]:
for twelfth_inner in lict[11]:
for thirteenth_inner in lict[12]:
for fourteenth_inner in lict [13]:
for fifteenth_inner in lict [14]:
for sixteenth_inner in lict[15]:
term = (
first_inner + second_inner +
third_inner + fourth_inner +
fifth_inner + sixth_inner +
seventh_inner + eighth_inner +
ninth_inner + tenth_inner +
eleventh_inner + twelfth_inner +
thirteenth_inner + fourteenth_inner +
fifteenth_inner + sixteenth_inner
)
termal_lict.append(term)
return termal_lict
def user_input_handling_function_second(dictionary):
print()
user_input = input('Enter: ')
print()
good_to_go = 'no'
errors = []
lict = []
while good_to_go == 'no':
for key in dictionary:
lict.append(key)
for element in user_input:
if element not in lict:
print('The form can only contain a combination of the characters that represent the lists of characters.')
errors.append('yes')
break
if len(user_input) < 2:
print('The form is too short. It can\'t be less than two-characters long.')
errors.append('yes')
if len(user_input) > 8:
print('The form is too long. It can\'t be more than eight-characters long.')
errors.append('yes')
if 'yes' in errors:
good_to_go = 'no'
errors = []
print()
user_input = input('Re-enter: ')
print()
else:
good_to_go = 'yes'
return user_input
def user_input_handling_function_third():
print()
user_input = input('Enter: ')
print()
good_to_go = 'no'
errors = []
yes_or_no = ['yes', 'no']
while good_to_go == 'no':
if user_input not in yes_or_no:
print('You have to answer yes or no.')
errors.append('yes')
if 'yes' in errors:
good_to_go = 'no'
errors = []
print()
user_input = input('Re-enter: ')
print()
else:
good_to_go = 'yes'
return user_input
def user_input_handling_function_fourth(dictionary):
print()
user_input = input('Enter: ')
print()
good_to_go = 'no'
errors = []
while good_to_go == 'no':
if user_input not in dictionary:
print('The form you entered does not match one of the forms in your termal_dictionary. Each form in your')
print('termal_dictionary is a name (key) that has an associated definition (value) that is a list of terms')
print('that all have the same form as the name (key).')
errors.append('yes')
if 'yes' in errors:
good_to_go = 'no'
errors = []
print()
user_input = input('Re-enter: ')
print()
else:
good_to_go = 'yes'
return user_input
def user_input_handling_function_eighth():
print()
user_input = input('Enter: ')
print()
good_to_go = 'no'
errors = []
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-']
while good_to_go == 'no':
if user_input == 'None':
user_input = None
return user_input
else:
for inner in user_input:
if inner not in digits:
print('The number must be an integer that consists of digits. For example: 1, -2, etc. or the keyword:')
print('None.')
errors.append('yes')
break
if 'yes' in errors:
good_to_go = 'no'
errors = []
print()
user_input = input('Re-enter: ')
print()
else:
good_to_go = 'yes'
return int(user_input)
def user_input_handling_function_ninth():
''' a parser '''
print()
user_input = input('Enter: ')
print()
term = ''
lict = []
for element in user_input:
if element != ' ':
term = term + element
else:
lict.append(term)
term = ''
lict.append(term) # because term might not be empty....
return lict
def user_input_handling_function_tenth(dictionary):
''' a dictionary checker '''
user_input = user_input_handling_function_ninth()
good_to_go = 'no'
errors = []
while good_to_go == 'no':
string = ''
lict = []
for element in user_input:
string = string + element
for key in dictionary:
for element in dictionary[key]:
lict.append(element)
for element in string:
if element not in lict:
print('One of your unwanted characters or combination of characters does not match the characters you')
print('entered earlier.')
errors.append('yes')
break
if 'yes' in errors:
print()
user_input = input('Re-enter: ')
print()
good_to_go = 'no'
errors = []
else:
good_to_go = 'yes'
return user_input
def print_vertical_lict(lict):
for element in lict:
print(element)
def print_horizontal_lict(lict):
string = ''
for element in lict:
string = string + str(element) + ', '
print(string)
print()
def write_vertical_lict(file_name, lict): # <--
file = open(file_name, 'w')
for element in lict:
element = str(element) + '\n'
file.write(element)
file.close()
def write_horizontal_lict(file_name, lict):
if '.txt' not in file_name:
file_name = file_name + '.txt'
row = ''
for index in range(len(lict)):
lict[index] = str(lict[index]) + ', '
if len(row + lict[index]) > 100:
lict[index - 1] = lict[index - 1] + '\n'
row = lict[index]
else:
row = row + lict[index]
file = open(file_name, 'w')
for term in lict:
file.write(term)
file.close()
| def termal_generator(lict):
length_of_termal_generator = 16
padding = length_of_termal_generator - len(lict)
count = padding
while count != 0:
lict.append([''])
count = count - 1
termal_lict = []
for first_inner in lict[0]:
for second_inner in lict[1]:
for third_inner in lict[2]:
for fourth_inner in lict[3]:
for fifth_inner in lict[4]:
for sixth_inner in lict[5]:
for seventh_inner in lict[6]:
for eighth_inner in lict[7]:
for ninth_inner in lict[8]:
for tenth_inner in lict[9]:
for eleventh_inner in lict[10]:
for twelfth_inner in lict[11]:
for thirteenth_inner in lict[12]:
for fourteenth_inner in lict[13]:
for fifteenth_inner in lict[14]:
for sixteenth_inner in lict[15]:
term = first_inner + second_inner + third_inner + fourth_inner + fifth_inner + sixth_inner + seventh_inner + eighth_inner + ninth_inner + tenth_inner + eleventh_inner + twelfth_inner + thirteenth_inner + fourteenth_inner + fifteenth_inner + sixteenth_inner
termal_lict.append(term)
return termal_lict
def user_input_handling_function_second(dictionary):
print()
user_input = input('Enter: ')
print()
good_to_go = 'no'
errors = []
lict = []
while good_to_go == 'no':
for key in dictionary:
lict.append(key)
for element in user_input:
if element not in lict:
print('The form can only contain a combination of the characters that represent the lists of characters.')
errors.append('yes')
break
if len(user_input) < 2:
print("The form is too short. It can't be less than two-characters long.")
errors.append('yes')
if len(user_input) > 8:
print("The form is too long. It can't be more than eight-characters long.")
errors.append('yes')
if 'yes' in errors:
good_to_go = 'no'
errors = []
print()
user_input = input('Re-enter: ')
print()
else:
good_to_go = 'yes'
return user_input
def user_input_handling_function_third():
print()
user_input = input('Enter: ')
print()
good_to_go = 'no'
errors = []
yes_or_no = ['yes', 'no']
while good_to_go == 'no':
if user_input not in yes_or_no:
print('You have to answer yes or no.')
errors.append('yes')
if 'yes' in errors:
good_to_go = 'no'
errors = []
print()
user_input = input('Re-enter: ')
print()
else:
good_to_go = 'yes'
return user_input
def user_input_handling_function_fourth(dictionary):
print()
user_input = input('Enter: ')
print()
good_to_go = 'no'
errors = []
while good_to_go == 'no':
if user_input not in dictionary:
print('The form you entered does not match one of the forms in your termal_dictionary. Each form in your')
print('termal_dictionary is a name (key) that has an associated definition (value) that is a list of terms')
print('that all have the same form as the name (key).')
errors.append('yes')
if 'yes' in errors:
good_to_go = 'no'
errors = []
print()
user_input = input('Re-enter: ')
print()
else:
good_to_go = 'yes'
return user_input
def user_input_handling_function_eighth():
print()
user_input = input('Enter: ')
print()
good_to_go = 'no'
errors = []
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-']
while good_to_go == 'no':
if user_input == 'None':
user_input = None
return user_input
else:
for inner in user_input:
if inner not in digits:
print('The number must be an integer that consists of digits. For example: 1, -2, etc. or the keyword:')
print('None.')
errors.append('yes')
break
if 'yes' in errors:
good_to_go = 'no'
errors = []
print()
user_input = input('Re-enter: ')
print()
else:
good_to_go = 'yes'
return int(user_input)
def user_input_handling_function_ninth():
""" a parser """
print()
user_input = input('Enter: ')
print()
term = ''
lict = []
for element in user_input:
if element != ' ':
term = term + element
else:
lict.append(term)
term = ''
lict.append(term)
return lict
def user_input_handling_function_tenth(dictionary):
""" a dictionary checker """
user_input = user_input_handling_function_ninth()
good_to_go = 'no'
errors = []
while good_to_go == 'no':
string = ''
lict = []
for element in user_input:
string = string + element
for key in dictionary:
for element in dictionary[key]:
lict.append(element)
for element in string:
if element not in lict:
print('One of your unwanted characters or combination of characters does not match the characters you')
print('entered earlier.')
errors.append('yes')
break
if 'yes' in errors:
print()
user_input = input('Re-enter: ')
print()
good_to_go = 'no'
errors = []
else:
good_to_go = 'yes'
return user_input
def print_vertical_lict(lict):
for element in lict:
print(element)
def print_horizontal_lict(lict):
string = ''
for element in lict:
string = string + str(element) + ', '
print(string)
print()
def write_vertical_lict(file_name, lict):
file = open(file_name, 'w')
for element in lict:
element = str(element) + '\n'
file.write(element)
file.close()
def write_horizontal_lict(file_name, lict):
if '.txt' not in file_name:
file_name = file_name + '.txt'
row = ''
for index in range(len(lict)):
lict[index] = str(lict[index]) + ', '
if len(row + lict[index]) > 100:
lict[index - 1] = lict[index - 1] + '\n'
row = lict[index]
else:
row = row + lict[index]
file = open(file_name, 'w')
for term in lict:
file.write(term)
file.close() |
# ------------------------------
# 331. Verify Preorder Serialization of a Binary Tree
#
# Description:
# One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.
#
# _9_
# / \
# 3 2
# / \ / \
# 4 1 # 6
# / \ / \ / \
# # # # # # #
# For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node.
#
# Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.
# Each comma separated value in the string must be either an integer or a character '#' representing null pointer.
# You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".
#
# Example 1:
# Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
# Output: true
#
# Example 2:
# Input: "1,#"
# Output: false
#
# Example 3:
# Input: "9,#,#,1"
# Output: false
#
# Version: 1.0
# 09/27/19 by Jianfa
# ------------------------------
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
nodes = preorder.split(",")
# diff = outdegree - indegree
diff = 1
for n in nodes:
diff -= 1 # every node bring 1 indegree
if diff < 0:
return False
if n != "#": # if not null, it brings 2 outdegree
diff += 2
return diff == 0
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Math solution idea from: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/78551/7-lines-Easy-Java-Solution
# Consider null as leaves, then
# - all non-null node provides 2 outdegree and 1 indegree (2 children and 1 parent), except root
# - all null node provides 0 outdegree and 1 indegree (0 child and 1 parent).
# During building, we record the difference between out degree and in degree diff = outdegree - indegree.
# When the next node comes, we then decrease diff by 1, because the node provides an in degree. If the node is not null, we increase diff by 2, because it provides two out degrees.
# If a serialization is correct, diff should never be negative and diff will be zero when finished.
#
# Stack solution: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/78560/Simple-Python-solution-using-stack.-With-Explanation.
# When you see two consecutive "#" characters on stack, pop both of them and replace the topmost element on the stack with "#". For example,
# preorder = 1,2,3,#,#,#,#
# Pass 1: stack = [1]
# Pass 2: stack = [1,2]
# Pass 3: stack = [1,2,3]
# Pass 4: stack = [1,2,3,#]
# Pass 5: stack = [1,2,3,#,#] -> two #s on top so pop them and replace top with #. -> stack = [1,2,#]
# Pass 6: stack = [1,2,#,#] -> two #s on top so pop them and replace top with #. -> stack = [1,#]
# Pass 7: stack = [1,#,#] -> two #s on top so pop them and replace top with #. -> stack = [#]
#
# If there is only one # on stack at the end of the string then return True else return False.
| class Solution:
def is_valid_serialization(self, preorder: str) -> bool:
nodes = preorder.split(',')
diff = 1
for n in nodes:
diff -= 1
if diff < 0:
return False
if n != '#':
diff += 2
return diff == 0
if __name__ == '__main__':
test = solution() |
class HsvFilter:
def __init__(self, hMin=None, sMin=None, vMin=None, hMax=None, sMax=None, vMax=None,
sAdd=None, sSub=None, vAdd=None, vSub=None):
self.hMin = hMin
self.sMin = sMin
self.vMin = vMin
self.hMax = hMax
self.sMax = sMax
self.vMax = vMax
self.sAdd = sAdd
self.sSub = sSub
self.vAdd = vAdd
self.vSub = vSub
| class Hsvfilter:
def __init__(self, hMin=None, sMin=None, vMin=None, hMax=None, sMax=None, vMax=None, sAdd=None, sSub=None, vAdd=None, vSub=None):
self.hMin = hMin
self.sMin = sMin
self.vMin = vMin
self.hMax = hMax
self.sMax = sMax
self.vMax = vMax
self.sAdd = sAdd
self.sSub = sSub
self.vAdd = vAdd
self.vSub = vSub |
class Solution:
def isHappy(self, n: int) -> bool:
def squaredSum(n: int) -> bool:
sum = 0
while n:
sum += pow(n % 10, 2)
n //= 10
return sum
slow = squaredSum(n)
fast = squaredSum(squaredSum(n))
while slow != fast:
slow = squaredSum(slow)
fast = squaredSum(squaredSum(fast))
return slow == 1
| class Solution:
def is_happy(self, n: int) -> bool:
def squared_sum(n: int) -> bool:
sum = 0
while n:
sum += pow(n % 10, 2)
n //= 10
return sum
slow = squared_sum(n)
fast = squared_sum(squared_sum(n))
while slow != fast:
slow = squared_sum(slow)
fast = squared_sum(squared_sum(fast))
return slow == 1 |
def safeDict(elem, array_of_keys, default=""):
try:
for key in array_of_keys:
elem = elem[key]
return elem
except Exception as e:
return default | def safe_dict(elem, array_of_keys, default=''):
try:
for key in array_of_keys:
elem = elem[key]
return elem
except Exception as e:
return default |
# Those constants are used from the library only
BASE_PAL_URL = "https://pal-{}.adyen.com/pal/servlet"
PAL_LIVE_ENDPOINT_URL_TEMPLATE = "https://{}-pal-live" \
".adyenpayments.com/pal/servlet"
BASE_HPP_URL = "https://{}.adyen.com/hpp"
ENDPOINT_CHECKOUT_TEST = "https://checkout-test.adyen.com"
ENDPOINT_CHECKOUT_LIVE_SUFFIX = "https://{}-checkout-live" \
".adyenpayments.com/checkout"
API_BIN_LOOKUP_VERSION = "v50"
API_CHECKOUT_VERSION = "v67"
API_CHECKOUT_UTILITY_VERSION = "v1"
API_RECURRING_VERSION = "v49"
API_PAYMENT_VERSION = "v64"
API_PAYOUT_VERSION = "v64"
LIB_VERSION = "5.1.0"
LIB_NAME = "adyen-python-api-library"
| base_pal_url = 'https://pal-{}.adyen.com/pal/servlet'
pal_live_endpoint_url_template = 'https://{}-pal-live.adyenpayments.com/pal/servlet'
base_hpp_url = 'https://{}.adyen.com/hpp'
endpoint_checkout_test = 'https://checkout-test.adyen.com'
endpoint_checkout_live_suffix = 'https://{}-checkout-live.adyenpayments.com/checkout'
api_bin_lookup_version = 'v50'
api_checkout_version = 'v67'
api_checkout_utility_version = 'v1'
api_recurring_version = 'v49'
api_payment_version = 'v64'
api_payout_version = 'v64'
lib_version = '5.1.0'
lib_name = 'adyen-python-api-library' |
__all__ = ['VERSION']
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
VIDEO = 'youtube#video'
YOUTUBE_VIDEO_URL = 'https://www.youtube.com/watch?v='
VERSION = '4.0.0'
| __all__ = ['VERSION']
youtube_api_service_name = 'youtube'
youtube_api_version = 'v3'
video = 'youtube#video'
youtube_video_url = 'https://www.youtube.com/watch?v='
version = '4.0.0' |
# mailbox_or_url_parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'mailbox_or_urlFWSP AT DOT COMMA SEMICOLON LANGLE RANGLE ATOM DOT_ATOM LBRACKET RBRACKET DTEXT DQUOTE QTEXT QPAIR LPAREN RPAREN CTEXT URLmailbox_or_url_list : mailbox_or_url_list delim mailbox_or_url\n | mailbox_or_url_list delim\n | mailbox_or_urldelim : delim fwsp COMMA\n | delim fwsp SEMICOLON\n | COMMA\n | SEMICOLONmailbox_or_url : mailbox\n | urlurl : ofwsp URL ofwspmailbox : addr_spec\n | angle_addr\n | name_addrname_addr : ofwsp phrase angle_addrangle_addr : ofwsp LANGLE addr_spec RANGLE ofwspaddr_spec : ofwsp local_part AT domain ofwsplocal_part : DOT_ATOM\n | ATOM\n | quoted_stringdomain : DOT_ATOM\n | ATOM\n | domain_literalquoted_string : DQUOTE quoted_string_text DQUOTE\n | DQUOTE DQUOTEquoted_string_text : quoted_string_text QTEXT\n | quoted_string_text QPAIR\n | quoted_string_text fwsp\n | QTEXT\n | QPAIR\n | fwspdomain_literal : LBRACKET domain_literal_text RBRACKET\n | LBRACKET RBRACKETdomain_literal_text : domain_literal_text DTEXT\n | domain_literal_text fwsp\n | DTEXT\n | fwspcomment : LPAREN comment_text RPAREN\n | LPAREN RPARENcomment_text : comment_text CTEXT\n | comment_text fwsp\n | CTEXT\n | fwspphrase : phrase fwsp ATOM\n | phrase fwsp DOT_ATOM\n | phrase fwsp DOT\n | phrase fwsp quoted_string\n | phrase ATOM\n | phrase DOT_ATOM\n | phrase DOT\n | phrase quoted_string\n | ATOM\n | DOT_ATOM\n | DOT\n | quoted_stringofwsp : fwsp comment fwsp\n | fwsp comment\n | comment fwsp\n | comment\n | fwsp\n |fwsp : FWSP'
_lr_action_items = {'FWSP':([0,2,7,11,12,14,15,17,18,19,20,21,22,23,24,25,26,32,33,34,35,36,40,41,42,43,44,45,46,50,51,52,53,54,55,56,57,58,59,60,61,62,63,66,67,68,69,70,71,72,],[7,7,-61,7,7,7,7,-51,7,-52,7,-54,-53,-42,7,-38,-41,-30,-29,-28,-24,7,-48,-47,-50,-49,-40,-37,-39,7,7,7,-20,-21,-22,-27,-26,-25,-23,-44,-43,-46,-45,-36,-35,7,-32,-34,-33,-31,]),'LANGLE':([0,1,2,4,7,12,13,17,19,20,21,22,25,27,35,37,38,40,41,42,43,45,59,60,61,62,63,],[-60,-59,-58,14,-61,-56,-57,-51,-52,-60,-54,-53,-38,-55,-24,-59,14,-48,-47,-50,-49,-37,-23,-44,-43,-46,-45,]),'QPAIR':([7,18,32,33,34,36,56,57,58,],[-61,33,-30,-29,-28,57,-27,-26,-25,]),'URL':([0,1,2,4,7,12,13,25,27,45,],[-60,-59,-58,15,-61,-56,-57,-38,-55,-37,]),'QTEXT':([7,18,32,33,34,36,56,57,58,],[-61,34,-30,-29,-28,58,-27,-26,-25,]),'DTEXT':([7,52,66,67,68,70,71,],[-61,67,-36,-35,71,-34,-33,]),'DQUOTE':([0,1,2,4,7,12,13,14,17,18,19,20,21,22,25,27,28,32,33,34,35,36,37,40,41,42,43,45,56,57,58,59,60,61,62,63,],[-60,-59,-58,18,-61,-56,-57,-60,-51,35,-52,18,-54,-53,-38,-55,18,-30,-29,-28,-24,59,18,-48,-47,-50,-49,-37,-27,-26,-25,-23,-44,-43,-46,-45,]),'LBRACKET':([31,],[52,]),'DOT_ATOM':([0,1,2,4,7,12,13,14,17,19,20,21,22,25,27,28,31,35,37,40,41,42,43,45,59,60,61,62,63,],[-60,-59,-58,19,-61,-56,-57,-60,-51,-52,40,-54,-53,-38,-55,47,53,-24,60,-48,-47,-50,-49,-37,-23,-44,-43,-46,-45,]),'RPAREN':([7,11,23,24,26,44,46,],[-61,25,-42,45,-41,-40,-39,]),'AT':([16,17,19,21,35,47,48,49,59,],[31,-18,-17,-19,-24,-17,-18,-19,-23,]),'LPAREN':([0,1,7,14,15,17,19,20,21,22,35,37,40,41,42,43,50,51,53,54,55,59,60,61,62,63,69,72,],[11,11,-61,11,11,-51,-52,11,-54,-53,-24,11,-48,-47,-50,-49,11,11,-20,-21,-22,-23,-44,-43,-46,-45,-32,-31,]),'ATOM':([0,1,2,4,7,12,13,14,17,19,20,21,22,25,27,28,31,35,37,40,41,42,43,45,59,60,61,62,63,],[-60,-59,-58,17,-61,-56,-57,-60,-51,-52,41,-54,-53,-38,-55,48,54,-24,61,-48,-47,-50,-49,-37,-23,-44,-43,-46,-45,]),'RANGLE':([1,2,7,12,13,25,27,29,45,51,53,54,55,65,69,72,],[-59,-58,-61,-56,-57,-38,-55,50,-37,-60,-20,-21,-22,-16,-32,-31,]),'RBRACKET':([7,52,66,67,68,70,71,],[-61,69,-36,-35,72,-34,-33,]),'CTEXT':([7,11,23,24,26,44,46,],[-61,26,-42,46,-41,-40,-39,]),'DOT':([0,1,2,4,7,12,13,17,19,20,21,22,25,27,35,37,40,41,42,43,45,59,60,61,62,63,],[-60,-59,-58,22,-61,-56,-57,-51,-52,43,-54,-53,-38,-55,-24,63,-48,-47,-50,-49,-37,-23,-44,-43,-46,-45,]),'$end':([1,2,3,5,6,7,8,9,10,12,13,15,25,27,30,39,45,50,51,53,54,55,64,65,69,72,],[-59,-58,-13,-12,0,-61,-8,-9,-11,-56,-57,-60,-38,-55,-10,-14,-37,-60,-60,-20,-21,-22,-15,-16,-32,-31,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'fwsp':([0,2,11,12,14,15,18,20,24,36,50,51,52,68,],[1,13,23,27,1,1,32,37,44,56,1,1,66,70,]),'comment':([0,1,14,15,20,37,50,51,],[2,12,2,2,2,12,2,2,]),'domain':([31,],[51,]),'comment_text':([11,],[24,]),'name_addr':([0,],[3,]),'ofwsp':([0,14,15,20,50,51,],[4,28,30,38,64,65,]),'angle_addr':([0,20,],[5,39,]),'mailbox_or_url':([0,],[6,]),'local_part':([4,28,],[16,16,]),'domain_literal_text':([52,],[68,]),'mailbox':([0,],[8,]),'quoted_string_text':([18,],[36,]),'url':([0,],[9,]),'addr_spec':([0,14,],[10,29,]),'phrase':([4,],[20,]),'quoted_string':([4,20,28,37,],[21,42,49,62,]),'domain_literal':([31,],[55,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> mailbox_or_url","S'",1,None,None,None),
('mailbox_or_url_list -> mailbox_or_url_list delim mailbox_or_url','mailbox_or_url_list',3,'p_expression_mailbox_or_url_list','parser.py',19),
('mailbox_or_url_list -> mailbox_or_url_list delim','mailbox_or_url_list',2,'p_expression_mailbox_or_url_list','parser.py',20),
('mailbox_or_url_list -> mailbox_or_url','mailbox_or_url_list',1,'p_expression_mailbox_or_url_list','parser.py',21),
('delim -> delim fwsp COMMA','delim',3,'p_delim','parser.py',30),
('delim -> delim fwsp SEMICOLON','delim',3,'p_delim','parser.py',31),
('delim -> COMMA','delim',1,'p_delim','parser.py',32),
('delim -> SEMICOLON','delim',1,'p_delim','parser.py',33),
('mailbox_or_url -> mailbox','mailbox_or_url',1,'p_expression_mailbox_or_url','parser.py',36),
('mailbox_or_url -> url','mailbox_or_url',1,'p_expression_mailbox_or_url','parser.py',37),
('url -> ofwsp URL ofwsp','url',3,'p_expression_url','parser.py',41),
('mailbox -> addr_spec','mailbox',1,'p_expression_mailbox','parser.py',45),
('mailbox -> angle_addr','mailbox',1,'p_expression_mailbox','parser.py',46),
('mailbox -> name_addr','mailbox',1,'p_expression_mailbox','parser.py',47),
('name_addr -> ofwsp phrase angle_addr','name_addr',3,'p_expression_name_addr','parser.py',51),
('angle_addr -> ofwsp LANGLE addr_spec RANGLE ofwsp','angle_addr',5,'p_expression_angle_addr','parser.py',55),
('addr_spec -> ofwsp local_part AT domain ofwsp','addr_spec',5,'p_expression_addr_spec','parser.py',59),
('local_part -> DOT_ATOM','local_part',1,'p_expression_local_part','parser.py',63),
('local_part -> ATOM','local_part',1,'p_expression_local_part','parser.py',64),
('local_part -> quoted_string','local_part',1,'p_expression_local_part','parser.py',65),
('domain -> DOT_ATOM','domain',1,'p_expression_domain','parser.py',69),
('domain -> ATOM','domain',1,'p_expression_domain','parser.py',70),
('domain -> domain_literal','domain',1,'p_expression_domain','parser.py',71),
('quoted_string -> DQUOTE quoted_string_text DQUOTE','quoted_string',3,'p_expression_quoted_string','parser.py',75),
('quoted_string -> DQUOTE DQUOTE','quoted_string',2,'p_expression_quoted_string','parser.py',76),
('quoted_string_text -> quoted_string_text QTEXT','quoted_string_text',2,'p_expression_quoted_string_text','parser.py',83),
('quoted_string_text -> quoted_string_text QPAIR','quoted_string_text',2,'p_expression_quoted_string_text','parser.py',84),
('quoted_string_text -> quoted_string_text fwsp','quoted_string_text',2,'p_expression_quoted_string_text','parser.py',85),
('quoted_string_text -> QTEXT','quoted_string_text',1,'p_expression_quoted_string_text','parser.py',86),
('quoted_string_text -> QPAIR','quoted_string_text',1,'p_expression_quoted_string_text','parser.py',87),
('quoted_string_text -> fwsp','quoted_string_text',1,'p_expression_quoted_string_text','parser.py',88),
('domain_literal -> LBRACKET domain_literal_text RBRACKET','domain_literal',3,'p_expression_domain_literal','parser.py',92),
('domain_literal -> LBRACKET RBRACKET','domain_literal',2,'p_expression_domain_literal','parser.py',93),
('domain_literal_text -> domain_literal_text DTEXT','domain_literal_text',2,'p_expression_domain_literal_text','parser.py',100),
('domain_literal_text -> domain_literal_text fwsp','domain_literal_text',2,'p_expression_domain_literal_text','parser.py',101),
('domain_literal_text -> DTEXT','domain_literal_text',1,'p_expression_domain_literal_text','parser.py',102),
('domain_literal_text -> fwsp','domain_literal_text',1,'p_expression_domain_literal_text','parser.py',103),
('comment -> LPAREN comment_text RPAREN','comment',3,'p_expression_comment','parser.py',107),
('comment -> LPAREN RPAREN','comment',2,'p_expression_comment','parser.py',108),
('comment_text -> comment_text CTEXT','comment_text',2,'p_expression_comment_text','parser.py',112),
('comment_text -> comment_text fwsp','comment_text',2,'p_expression_comment_text','parser.py',113),
('comment_text -> CTEXT','comment_text',1,'p_expression_comment_text','parser.py',114),
('comment_text -> fwsp','comment_text',1,'p_expression_comment_text','parser.py',115),
('phrase -> phrase fwsp ATOM','phrase',3,'p_expression_phrase','parser.py',119),
('phrase -> phrase fwsp DOT_ATOM','phrase',3,'p_expression_phrase','parser.py',120),
('phrase -> phrase fwsp DOT','phrase',3,'p_expression_phrase','parser.py',121),
('phrase -> phrase fwsp quoted_string','phrase',3,'p_expression_phrase','parser.py',122),
('phrase -> phrase ATOM','phrase',2,'p_expression_phrase','parser.py',123),
('phrase -> phrase DOT_ATOM','phrase',2,'p_expression_phrase','parser.py',124),
('phrase -> phrase DOT','phrase',2,'p_expression_phrase','parser.py',125),
('phrase -> phrase quoted_string','phrase',2,'p_expression_phrase','parser.py',126),
('phrase -> ATOM','phrase',1,'p_expression_phrase','parser.py',127),
('phrase -> DOT_ATOM','phrase',1,'p_expression_phrase','parser.py',128),
('phrase -> DOT','phrase',1,'p_expression_phrase','parser.py',129),
('phrase -> quoted_string','phrase',1,'p_expression_phrase','parser.py',130),
('ofwsp -> fwsp comment fwsp','ofwsp',3,'p_expression_ofwsp','parser.py',139),
('ofwsp -> fwsp comment','ofwsp',2,'p_expression_ofwsp','parser.py',140),
('ofwsp -> comment fwsp','ofwsp',2,'p_expression_ofwsp','parser.py',141),
('ofwsp -> comment','ofwsp',1,'p_expression_ofwsp','parser.py',142),
('ofwsp -> fwsp','ofwsp',1,'p_expression_ofwsp','parser.py',143),
('ofwsp -> <empty>','ofwsp',0,'p_expression_ofwsp','parser.py',144),
('fwsp -> FWSP','fwsp',1,'p_expression_fwsp','parser.py',148),
]
| _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'mailbox_or_urlFWSP AT DOT COMMA SEMICOLON LANGLE RANGLE ATOM DOT_ATOM LBRACKET RBRACKET DTEXT DQUOTE QTEXT QPAIR LPAREN RPAREN CTEXT URLmailbox_or_url_list : mailbox_or_url_list delim mailbox_or_url\n | mailbox_or_url_list delim\n | mailbox_or_urldelim : delim fwsp COMMA\n | delim fwsp SEMICOLON\n | COMMA\n | SEMICOLONmailbox_or_url : mailbox\n | urlurl : ofwsp URL ofwspmailbox : addr_spec\n | angle_addr\n | name_addrname_addr : ofwsp phrase angle_addrangle_addr : ofwsp LANGLE addr_spec RANGLE ofwspaddr_spec : ofwsp local_part AT domain ofwsplocal_part : DOT_ATOM\n | ATOM\n | quoted_stringdomain : DOT_ATOM\n | ATOM\n | domain_literalquoted_string : DQUOTE quoted_string_text DQUOTE\n | DQUOTE DQUOTEquoted_string_text : quoted_string_text QTEXT\n | quoted_string_text QPAIR\n | quoted_string_text fwsp\n | QTEXT\n | QPAIR\n | fwspdomain_literal : LBRACKET domain_literal_text RBRACKET\n | LBRACKET RBRACKETdomain_literal_text : domain_literal_text DTEXT\n | domain_literal_text fwsp\n | DTEXT\n | fwspcomment : LPAREN comment_text RPAREN\n | LPAREN RPARENcomment_text : comment_text CTEXT\n | comment_text fwsp\n | CTEXT\n | fwspphrase : phrase fwsp ATOM\n | phrase fwsp DOT_ATOM\n | phrase fwsp DOT\n | phrase fwsp quoted_string\n | phrase ATOM\n | phrase DOT_ATOM\n | phrase DOT\n | phrase quoted_string\n | ATOM\n | DOT_ATOM\n | DOT\n | quoted_stringofwsp : fwsp comment fwsp\n | fwsp comment\n | comment fwsp\n | comment\n | fwsp\n |fwsp : FWSP'
_lr_action_items = {'FWSP': ([0, 2, 7, 11, 12, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 32, 33, 34, 35, 36, 40, 41, 42, 43, 44, 45, 46, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 66, 67, 68, 69, 70, 71, 72], [7, 7, -61, 7, 7, 7, 7, -51, 7, -52, 7, -54, -53, -42, 7, -38, -41, -30, -29, -28, -24, 7, -48, -47, -50, -49, -40, -37, -39, 7, 7, 7, -20, -21, -22, -27, -26, -25, -23, -44, -43, -46, -45, -36, -35, 7, -32, -34, -33, -31]), 'LANGLE': ([0, 1, 2, 4, 7, 12, 13, 17, 19, 20, 21, 22, 25, 27, 35, 37, 38, 40, 41, 42, 43, 45, 59, 60, 61, 62, 63], [-60, -59, -58, 14, -61, -56, -57, -51, -52, -60, -54, -53, -38, -55, -24, -59, 14, -48, -47, -50, -49, -37, -23, -44, -43, -46, -45]), 'QPAIR': ([7, 18, 32, 33, 34, 36, 56, 57, 58], [-61, 33, -30, -29, -28, 57, -27, -26, -25]), 'URL': ([0, 1, 2, 4, 7, 12, 13, 25, 27, 45], [-60, -59, -58, 15, -61, -56, -57, -38, -55, -37]), 'QTEXT': ([7, 18, 32, 33, 34, 36, 56, 57, 58], [-61, 34, -30, -29, -28, 58, -27, -26, -25]), 'DTEXT': ([7, 52, 66, 67, 68, 70, 71], [-61, 67, -36, -35, 71, -34, -33]), 'DQUOTE': ([0, 1, 2, 4, 7, 12, 13, 14, 17, 18, 19, 20, 21, 22, 25, 27, 28, 32, 33, 34, 35, 36, 37, 40, 41, 42, 43, 45, 56, 57, 58, 59, 60, 61, 62, 63], [-60, -59, -58, 18, -61, -56, -57, -60, -51, 35, -52, 18, -54, -53, -38, -55, 18, -30, -29, -28, -24, 59, 18, -48, -47, -50, -49, -37, -27, -26, -25, -23, -44, -43, -46, -45]), 'LBRACKET': ([31], [52]), 'DOT_ATOM': ([0, 1, 2, 4, 7, 12, 13, 14, 17, 19, 20, 21, 22, 25, 27, 28, 31, 35, 37, 40, 41, 42, 43, 45, 59, 60, 61, 62, 63], [-60, -59, -58, 19, -61, -56, -57, -60, -51, -52, 40, -54, -53, -38, -55, 47, 53, -24, 60, -48, -47, -50, -49, -37, -23, -44, -43, -46, -45]), 'RPAREN': ([7, 11, 23, 24, 26, 44, 46], [-61, 25, -42, 45, -41, -40, -39]), 'AT': ([16, 17, 19, 21, 35, 47, 48, 49, 59], [31, -18, -17, -19, -24, -17, -18, -19, -23]), 'LPAREN': ([0, 1, 7, 14, 15, 17, 19, 20, 21, 22, 35, 37, 40, 41, 42, 43, 50, 51, 53, 54, 55, 59, 60, 61, 62, 63, 69, 72], [11, 11, -61, 11, 11, -51, -52, 11, -54, -53, -24, 11, -48, -47, -50, -49, 11, 11, -20, -21, -22, -23, -44, -43, -46, -45, -32, -31]), 'ATOM': ([0, 1, 2, 4, 7, 12, 13, 14, 17, 19, 20, 21, 22, 25, 27, 28, 31, 35, 37, 40, 41, 42, 43, 45, 59, 60, 61, 62, 63], [-60, -59, -58, 17, -61, -56, -57, -60, -51, -52, 41, -54, -53, -38, -55, 48, 54, -24, 61, -48, -47, -50, -49, -37, -23, -44, -43, -46, -45]), 'RANGLE': ([1, 2, 7, 12, 13, 25, 27, 29, 45, 51, 53, 54, 55, 65, 69, 72], [-59, -58, -61, -56, -57, -38, -55, 50, -37, -60, -20, -21, -22, -16, -32, -31]), 'RBRACKET': ([7, 52, 66, 67, 68, 70, 71], [-61, 69, -36, -35, 72, -34, -33]), 'CTEXT': ([7, 11, 23, 24, 26, 44, 46], [-61, 26, -42, 46, -41, -40, -39]), 'DOT': ([0, 1, 2, 4, 7, 12, 13, 17, 19, 20, 21, 22, 25, 27, 35, 37, 40, 41, 42, 43, 45, 59, 60, 61, 62, 63], [-60, -59, -58, 22, -61, -56, -57, -51, -52, 43, -54, -53, -38, -55, -24, 63, -48, -47, -50, -49, -37, -23, -44, -43, -46, -45]), '$end': ([1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 13, 15, 25, 27, 30, 39, 45, 50, 51, 53, 54, 55, 64, 65, 69, 72], [-59, -58, -13, -12, 0, -61, -8, -9, -11, -56, -57, -60, -38, -55, -10, -14, -37, -60, -60, -20, -21, -22, -15, -16, -32, -31])}
_lr_action = {}
for (_k, _v) in _lr_action_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_action:
_lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'fwsp': ([0, 2, 11, 12, 14, 15, 18, 20, 24, 36, 50, 51, 52, 68], [1, 13, 23, 27, 1, 1, 32, 37, 44, 56, 1, 1, 66, 70]), 'comment': ([0, 1, 14, 15, 20, 37, 50, 51], [2, 12, 2, 2, 2, 12, 2, 2]), 'domain': ([31], [51]), 'comment_text': ([11], [24]), 'name_addr': ([0], [3]), 'ofwsp': ([0, 14, 15, 20, 50, 51], [4, 28, 30, 38, 64, 65]), 'angle_addr': ([0, 20], [5, 39]), 'mailbox_or_url': ([0], [6]), 'local_part': ([4, 28], [16, 16]), 'domain_literal_text': ([52], [68]), 'mailbox': ([0], [8]), 'quoted_string_text': ([18], [36]), 'url': ([0], [9]), 'addr_spec': ([0, 14], [10, 29]), 'phrase': ([4], [20]), 'quoted_string': ([4, 20, 28, 37], [21, 42, 49, 62]), 'domain_literal': ([31], [55])}
_lr_goto = {}
for (_k, _v) in _lr_goto_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_goto:
_lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [("S' -> mailbox_or_url", "S'", 1, None, None, None), ('mailbox_or_url_list -> mailbox_or_url_list delim mailbox_or_url', 'mailbox_or_url_list', 3, 'p_expression_mailbox_or_url_list', 'parser.py', 19), ('mailbox_or_url_list -> mailbox_or_url_list delim', 'mailbox_or_url_list', 2, 'p_expression_mailbox_or_url_list', 'parser.py', 20), ('mailbox_or_url_list -> mailbox_or_url', 'mailbox_or_url_list', 1, 'p_expression_mailbox_or_url_list', 'parser.py', 21), ('delim -> delim fwsp COMMA', 'delim', 3, 'p_delim', 'parser.py', 30), ('delim -> delim fwsp SEMICOLON', 'delim', 3, 'p_delim', 'parser.py', 31), ('delim -> COMMA', 'delim', 1, 'p_delim', 'parser.py', 32), ('delim -> SEMICOLON', 'delim', 1, 'p_delim', 'parser.py', 33), ('mailbox_or_url -> mailbox', 'mailbox_or_url', 1, 'p_expression_mailbox_or_url', 'parser.py', 36), ('mailbox_or_url -> url', 'mailbox_or_url', 1, 'p_expression_mailbox_or_url', 'parser.py', 37), ('url -> ofwsp URL ofwsp', 'url', 3, 'p_expression_url', 'parser.py', 41), ('mailbox -> addr_spec', 'mailbox', 1, 'p_expression_mailbox', 'parser.py', 45), ('mailbox -> angle_addr', 'mailbox', 1, 'p_expression_mailbox', 'parser.py', 46), ('mailbox -> name_addr', 'mailbox', 1, 'p_expression_mailbox', 'parser.py', 47), ('name_addr -> ofwsp phrase angle_addr', 'name_addr', 3, 'p_expression_name_addr', 'parser.py', 51), ('angle_addr -> ofwsp LANGLE addr_spec RANGLE ofwsp', 'angle_addr', 5, 'p_expression_angle_addr', 'parser.py', 55), ('addr_spec -> ofwsp local_part AT domain ofwsp', 'addr_spec', 5, 'p_expression_addr_spec', 'parser.py', 59), ('local_part -> DOT_ATOM', 'local_part', 1, 'p_expression_local_part', 'parser.py', 63), ('local_part -> ATOM', 'local_part', 1, 'p_expression_local_part', 'parser.py', 64), ('local_part -> quoted_string', 'local_part', 1, 'p_expression_local_part', 'parser.py', 65), ('domain -> DOT_ATOM', 'domain', 1, 'p_expression_domain', 'parser.py', 69), ('domain -> ATOM', 'domain', 1, 'p_expression_domain', 'parser.py', 70), ('domain -> domain_literal', 'domain', 1, 'p_expression_domain', 'parser.py', 71), ('quoted_string -> DQUOTE quoted_string_text DQUOTE', 'quoted_string', 3, 'p_expression_quoted_string', 'parser.py', 75), ('quoted_string -> DQUOTE DQUOTE', 'quoted_string', 2, 'p_expression_quoted_string', 'parser.py', 76), ('quoted_string_text -> quoted_string_text QTEXT', 'quoted_string_text', 2, 'p_expression_quoted_string_text', 'parser.py', 83), ('quoted_string_text -> quoted_string_text QPAIR', 'quoted_string_text', 2, 'p_expression_quoted_string_text', 'parser.py', 84), ('quoted_string_text -> quoted_string_text fwsp', 'quoted_string_text', 2, 'p_expression_quoted_string_text', 'parser.py', 85), ('quoted_string_text -> QTEXT', 'quoted_string_text', 1, 'p_expression_quoted_string_text', 'parser.py', 86), ('quoted_string_text -> QPAIR', 'quoted_string_text', 1, 'p_expression_quoted_string_text', 'parser.py', 87), ('quoted_string_text -> fwsp', 'quoted_string_text', 1, 'p_expression_quoted_string_text', 'parser.py', 88), ('domain_literal -> LBRACKET domain_literal_text RBRACKET', 'domain_literal', 3, 'p_expression_domain_literal', 'parser.py', 92), ('domain_literal -> LBRACKET RBRACKET', 'domain_literal', 2, 'p_expression_domain_literal', 'parser.py', 93), ('domain_literal_text -> domain_literal_text DTEXT', 'domain_literal_text', 2, 'p_expression_domain_literal_text', 'parser.py', 100), ('domain_literal_text -> domain_literal_text fwsp', 'domain_literal_text', 2, 'p_expression_domain_literal_text', 'parser.py', 101), ('domain_literal_text -> DTEXT', 'domain_literal_text', 1, 'p_expression_domain_literal_text', 'parser.py', 102), ('domain_literal_text -> fwsp', 'domain_literal_text', 1, 'p_expression_domain_literal_text', 'parser.py', 103), ('comment -> LPAREN comment_text RPAREN', 'comment', 3, 'p_expression_comment', 'parser.py', 107), ('comment -> LPAREN RPAREN', 'comment', 2, 'p_expression_comment', 'parser.py', 108), ('comment_text -> comment_text CTEXT', 'comment_text', 2, 'p_expression_comment_text', 'parser.py', 112), ('comment_text -> comment_text fwsp', 'comment_text', 2, 'p_expression_comment_text', 'parser.py', 113), ('comment_text -> CTEXT', 'comment_text', 1, 'p_expression_comment_text', 'parser.py', 114), ('comment_text -> fwsp', 'comment_text', 1, 'p_expression_comment_text', 'parser.py', 115), ('phrase -> phrase fwsp ATOM', 'phrase', 3, 'p_expression_phrase', 'parser.py', 119), ('phrase -> phrase fwsp DOT_ATOM', 'phrase', 3, 'p_expression_phrase', 'parser.py', 120), ('phrase -> phrase fwsp DOT', 'phrase', 3, 'p_expression_phrase', 'parser.py', 121), ('phrase -> phrase fwsp quoted_string', 'phrase', 3, 'p_expression_phrase', 'parser.py', 122), ('phrase -> phrase ATOM', 'phrase', 2, 'p_expression_phrase', 'parser.py', 123), ('phrase -> phrase DOT_ATOM', 'phrase', 2, 'p_expression_phrase', 'parser.py', 124), ('phrase -> phrase DOT', 'phrase', 2, 'p_expression_phrase', 'parser.py', 125), ('phrase -> phrase quoted_string', 'phrase', 2, 'p_expression_phrase', 'parser.py', 126), ('phrase -> ATOM', 'phrase', 1, 'p_expression_phrase', 'parser.py', 127), ('phrase -> DOT_ATOM', 'phrase', 1, 'p_expression_phrase', 'parser.py', 128), ('phrase -> DOT', 'phrase', 1, 'p_expression_phrase', 'parser.py', 129), ('phrase -> quoted_string', 'phrase', 1, 'p_expression_phrase', 'parser.py', 130), ('ofwsp -> fwsp comment fwsp', 'ofwsp', 3, 'p_expression_ofwsp', 'parser.py', 139), ('ofwsp -> fwsp comment', 'ofwsp', 2, 'p_expression_ofwsp', 'parser.py', 140), ('ofwsp -> comment fwsp', 'ofwsp', 2, 'p_expression_ofwsp', 'parser.py', 141), ('ofwsp -> comment', 'ofwsp', 1, 'p_expression_ofwsp', 'parser.py', 142), ('ofwsp -> fwsp', 'ofwsp', 1, 'p_expression_ofwsp', 'parser.py', 143), ('ofwsp -> <empty>', 'ofwsp', 0, 'p_expression_ofwsp', 'parser.py', 144), ('fwsp -> FWSP', 'fwsp', 1, 'p_expression_fwsp', 'parser.py', 148)] |
print(add(5, 3))
def add(x, y):
return x+y
| print(add(5, 3))
def add(x, y):
return x + y |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if root:
dfs(root.left)
nums.append(root.val)
dfs(root.right)
nums = []
dfs(root)
return nums[len(nums) - k]
def kthLargest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if self.k and root:
dfs(root.right)
self.k -= 1
if not self.k:
self.rtn = root.val
return
dfs(root.left)
self.k = k
dfs(root)
return self.rtn
| class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kth_largest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if root:
dfs(root.left)
nums.append(root.val)
dfs(root.right)
nums = []
dfs(root)
return nums[len(nums) - k]
def kth_largest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if self.k and root:
dfs(root.right)
self.k -= 1
if not self.k:
self.rtn = root.val
return
dfs(root.left)
self.k = k
dfs(root)
return self.rtn |
class Solution:
# O(n) time | O(1) space - where n is the length of the input list
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
maxDuration, startTime, slowestKey = 0, 0, ''
for i in range(len(releaseTimes)):
pressTime = releaseTimes[i] - startTime
if pressTime > maxDuration:
maxDuration = pressTime
slowestKey = keysPressed[i]
elif pressTime == maxDuration and keysPressed[i] > slowestKey:
slowestKey = keysPressed[i]
startTime = releaseTimes[i]
return slowestKey
| class Solution:
def slowest_key(self, releaseTimes: List[int], keysPressed: str) -> str:
(max_duration, start_time, slowest_key) = (0, 0, '')
for i in range(len(releaseTimes)):
press_time = releaseTimes[i] - startTime
if pressTime > maxDuration:
max_duration = pressTime
slowest_key = keysPressed[i]
elif pressTime == maxDuration and keysPressed[i] > slowestKey:
slowest_key = keysPressed[i]
start_time = releaseTimes[i]
return slowestKey |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"run_params": "000_exp_02_pretrained.ipynb",
"experiment": "000_exp_02_pretrained.ipynb",
"DatasetBuilder": "01_dataset_builder.ipynb",
"StatementClassifier": "02_statement_classifer.ipynb",
"Experiment": "03_experiment.ipynb",
"RunParams": "04_run_parameters.ipynb",
"BasicModel": "05_basic_model.ipynb",
"DataManager": "06_data_manager.ipynb",
"WikiDatabase": "08_database_proxy.ipynb",
"properties": "09_properties.ipynb"}
modules = ["exp_01.py",
"dataset_builder.py",
"statement_classifier.py",
"experiment.py",
"run_params.py",
"basic_model.py",
"data_manager.py",
"database_proxy.py",
"properties.py"]
doc_url = "https://rmorain.github.io/kirby/"
git_url = "https://github.com/rmorain/kirby/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'run_params': '000_exp_02_pretrained.ipynb', 'experiment': '000_exp_02_pretrained.ipynb', 'DatasetBuilder': '01_dataset_builder.ipynb', 'StatementClassifier': '02_statement_classifer.ipynb', 'Experiment': '03_experiment.ipynb', 'RunParams': '04_run_parameters.ipynb', 'BasicModel': '05_basic_model.ipynb', 'DataManager': '06_data_manager.ipynb', 'WikiDatabase': '08_database_proxy.ipynb', 'properties': '09_properties.ipynb'}
modules = ['exp_01.py', 'dataset_builder.py', 'statement_classifier.py', 'experiment.py', 'run_params.py', 'basic_model.py', 'data_manager.py', 'database_proxy.py', 'properties.py']
doc_url = 'https://rmorain.github.io/kirby/'
git_url = 'https://github.com/rmorain/kirby/tree/master/'
def custom_doc_links(name):
return None |
A, B = map(int, input().split())
S = str(input())
flag = True
if not S[:A].isdecimal():
flag = False
elif S[A] != '-':
flag = False
elif not S[-B:].isdecimal():
flag = False
if flag:
print('Yes')
else:
print('No')
| (a, b) = map(int, input().split())
s = str(input())
flag = True
if not S[:A].isdecimal():
flag = False
elif S[A] != '-':
flag = False
elif not S[-B:].isdecimal():
flag = False
if flag:
print('Yes')
else:
print('No') |
def configure_tx_chains(txChains, streamNum, mcsIdx):
txChains = txChains.lower()
RATE_MCS_ANT_A_MSK = 0x04000
RATE_MCS_ANT_B_MSK = 0x08000
RATE_MCS_ANT_C_MSK = 0x10000
RATE_MCS_HT_MSK = 0x00100
mask = 0x0
usedAntNum = 0
if "a" in txChains:
mask |= RATE_MCS_ANT_A_MSK
usedAntNum += 1
if "b" in txChains:
mask |= RATE_MCS_ANT_B_MSK
usedAntNum += 1
if "c" in txChains:
mask |= RATE_MCS_ANT_C_MSK
usedAntNum += 1
mask |= RATE_MCS_HT_MSK
if streamNum > usedAntNum:
print("Cannot use {} streams with {} antennas".format(streamNum, usedAntNum))
print("Set stream num to {}".format(usedAntNum))
streamNum = usedAntNum
mcsMask = mcsIdx
if streamNum == 2:
mcsMask += 8
elif streamNum == 3:
mcsMask += 16
mask |= mcsMask
mask = "0x{:05x}".format(mask)
print("Set TX mask: ", mask)
filePath = "/sys/kernel/debug/iwlwifi/0000:03:00.0/iwldvm/debug/monitor_tx_rate"
f = open(filePath, 'w')
f.write(mask)
f.close()
def configure_rx_chains(rxChains):
rxChains = rxChains.lower()
mask = 0x0
aMask = 0x1
bMask = 0x2
cMask = 0x4
if "a" in rxChains:
mask |= aMask
if "b" in rxChains:
mask |= bMask
if "c" in rxChains:
mask |= cMask
mask = "0x{:01x}".format(mask)
print("Set RX chain mask: ", mask)
filePath = "/sys/kernel/debug/iwlwifi/0000:03:00.0/iwldvm/debug/rx_chains_msk"
f = open(filePath, 'w')
f.write(mask)
f.close() | def configure_tx_chains(txChains, streamNum, mcsIdx):
tx_chains = txChains.lower()
rate_mcs_ant_a_msk = 16384
rate_mcs_ant_b_msk = 32768
rate_mcs_ant_c_msk = 65536
rate_mcs_ht_msk = 256
mask = 0
used_ant_num = 0
if 'a' in txChains:
mask |= RATE_MCS_ANT_A_MSK
used_ant_num += 1
if 'b' in txChains:
mask |= RATE_MCS_ANT_B_MSK
used_ant_num += 1
if 'c' in txChains:
mask |= RATE_MCS_ANT_C_MSK
used_ant_num += 1
mask |= RATE_MCS_HT_MSK
if streamNum > usedAntNum:
print('Cannot use {} streams with {} antennas'.format(streamNum, usedAntNum))
print('Set stream num to {}'.format(usedAntNum))
stream_num = usedAntNum
mcs_mask = mcsIdx
if streamNum == 2:
mcs_mask += 8
elif streamNum == 3:
mcs_mask += 16
mask |= mcsMask
mask = '0x{:05x}'.format(mask)
print('Set TX mask: ', mask)
file_path = '/sys/kernel/debug/iwlwifi/0000:03:00.0/iwldvm/debug/monitor_tx_rate'
f = open(filePath, 'w')
f.write(mask)
f.close()
def configure_rx_chains(rxChains):
rx_chains = rxChains.lower()
mask = 0
a_mask = 1
b_mask = 2
c_mask = 4
if 'a' in rxChains:
mask |= aMask
if 'b' in rxChains:
mask |= bMask
if 'c' in rxChains:
mask |= cMask
mask = '0x{:01x}'.format(mask)
print('Set RX chain mask: ', mask)
file_path = '/sys/kernel/debug/iwlwifi/0000:03:00.0/iwldvm/debug/rx_chains_msk'
f = open(filePath, 'w')
f.write(mask)
f.close() |
# 19. Remove Nth Node From End of List
# Time: O(n)
# Space: O(1)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
slow = head
fast = head
for i in range(n):
fast = fast.next
while fast:
prev = slow
slow = slow.next
fast = fast.next
if slow==head:
head = head.next
else:
prev.next = slow.next
return head
| class Solution:
def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode:
slow = head
fast = head
for i in range(n):
fast = fast.next
while fast:
prev = slow
slow = slow.next
fast = fast.next
if slow == head:
head = head.next
else:
prev.next = slow.next
return head |
'''
URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/
Difficulty: Easy
Description: Find Lucky Integer in an Array
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.
Example 1:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.
Example 2:
Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.
Example 3:
Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.
Example 4:
Input: arr = [5]
Output: -1
Example 5:
Input: arr = [7,7,7,7,7,7,7]
Output: 7
Constraints:
1 <= arr.length <= 500
1 <= arr[i] <= 500
'''
class Solution:
def findLucky(self, arr):
counts = {}
for n in arr:
if n in counts:
counts[n] += 1
else:
counts[n] = 1
max_lucky_num = -1
for n, count in counts.items():
if n == count:
max_lucky_num = max(max_lucky_num, n)
return max_lucky_num
'''
OTHER SLOW SOLUTION
class Solution:
def findLucky(self, arr):
max_lucky_num = -1
for n in arr:
if n == arr.count(n):
max_lucky_num = max(max_lucky_num, n)
return max_lucky_num
'''
| """
URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/
Difficulty: Easy
Description: Find Lucky Integer in an Array
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.
Example 1:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.
Example 2:
Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.
Example 3:
Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.
Example 4:
Input: arr = [5]
Output: -1
Example 5:
Input: arr = [7,7,7,7,7,7,7]
Output: 7
Constraints:
1 <= arr.length <= 500
1 <= arr[i] <= 500
"""
class Solution:
def find_lucky(self, arr):
counts = {}
for n in arr:
if n in counts:
counts[n] += 1
else:
counts[n] = 1
max_lucky_num = -1
for (n, count) in counts.items():
if n == count:
max_lucky_num = max(max_lucky_num, n)
return max_lucky_num
'\nOTHER SLOW SOLUTION\n\nclass Solution:\ndef findLucky(self, arr):\n \n max_lucky_num = -1\n \n for n in arr:\n if n == arr.count(n):\n max_lucky_num = max(max_lucky_num, n)\n \n return max_lucky_num\n \n' |
#string.py
str1 = "Hello"
str2 = 'John'
print(type(str1))
print("\"Good\\Job\"")
greet = "Hello John"
print(greet[1])
print(greet[-4])
print(greet[0:3])
print("bad" + "apple")
print("wt" + "d" * 5)
print(len("pine"))
print(type(str(123))) | str1 = 'Hello'
str2 = 'John'
print(type(str1))
print('"Good\\Job"')
greet = 'Hello John'
print(greet[1])
print(greet[-4])
print(greet[0:3])
print('bad' + 'apple')
print('wt' + 'd' * 5)
print(len('pine'))
print(type(str(123))) |
#!/usr/bin/env python
NAME = 'Reblaze (Reblaze)'
def is_waf(self):
if self.matchcookie(r'^rbzid='):
return True
if self.matchheader(('Server', 'Reblaze Secure Web Gateway')):
return True
# Now going for attack phase
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, page = r
if all(i in page for i in (b'Current session has been terminated', b'do not hesitate to contact us',
b'Access denied (403)')):
return True
return False
| name = 'Reblaze (Reblaze)'
def is_waf(self):
if self.matchcookie('^rbzid='):
return True
if self.matchheader(('Server', 'Reblaze Secure Web Gateway')):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
(_, page) = r
if all((i in page for i in (b'Current session has been terminated', b'do not hesitate to contact us', b'Access denied (403)'))):
return True
return False |
#
# PySNMP MIB module TIME-AGGREGATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIME-AGGREGATE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection")
OwnerString, = mibBuilder.importSymbols("RMON-MIB", "OwnerString")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
MibIdentifier, Integer32, IpAddress, Unsigned32, Bits, Opaque, ObjectIdentity, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, experimental, TimeTicks, NotificationType, Counter64, ModuleIdentity, iso, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Integer32", "IpAddress", "Unsigned32", "Bits", "Opaque", "ObjectIdentity", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "experimental", "TimeTicks", "NotificationType", "Counter64", "ModuleIdentity", "iso", "Counter32")
RowStatus, StorageType, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType", "TextualConvention", "DisplayString")
tAggrMIB = ModuleIdentity((1, 3, 6, 1, 3, 124))
tAggrMIB.setRevisions(('2006-04-27 00:00',))
if mibBuilder.loadTexts: tAggrMIB.setLastUpdated('200604270000Z')
if mibBuilder.loadTexts: tAggrMIB.setOrganization('Cyber Solutions Inc. NetMan Working Group')
class TAggrMOErrorStatus(TextualConvention, Opaque):
status = 'current'
subtypeSpec = Opaque.subtypeSpec + ValueSizeConstraint(0, 1024)
class TimeAggrMOValue(TextualConvention, Opaque):
status = 'current'
subtypeSpec = Opaque.subtypeSpec + ValueSizeConstraint(0, 1024)
class CompressedTimeAggrMOValue(TextualConvention, Opaque):
status = 'current'
subtypeSpec = Opaque.subtypeSpec + ValueSizeConstraint(0, 1024)
tAggrCtlTable = MibTable((1, 3, 6, 1, 3, 124, 1), )
if mibBuilder.loadTexts: tAggrCtlTable.setStatus('current')
tAggrCtlEntry = MibTableRow((1, 3, 6, 1, 3, 124, 1, 1), ).setIndexNames((0, "TIME-AGGREGATE-MIB", "tAggrCtlEntryID"))
if mibBuilder.loadTexts: tAggrCtlEntry.setStatus('current')
tAggrCtlEntryID = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: tAggrCtlEntryID.setStatus('current')
tAggrCtlMOInstance = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlMOInstance.setStatus('current')
tAggrCtlAgMODescr = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlAgMODescr.setStatus('current')
tAggrCtlInterval = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 4), Integer32()).setUnits('micro seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlInterval.setStatus('current')
tAggrCtlSamples = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 5), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlSamples.setStatus('current')
tAggrCtlCompressionAlgorithm = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("deflate", 2))).clone('none')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlCompressionAlgorithm.setStatus('current')
tAggrCtlEntryOwner = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 7), OwnerString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlEntryOwner.setStatus('current')
tAggrCtlEntryStorageType = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 8), StorageType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlEntryStorageType.setStatus('current')
tAggrCtlEntryStatus = MibTableColumn((1, 3, 6, 1, 3, 124, 1, 1, 9), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: tAggrCtlEntryStatus.setStatus('current')
tAggrDataTable = MibTable((1, 3, 6, 1, 3, 124, 2), )
if mibBuilder.loadTexts: tAggrDataTable.setStatus('current')
tAggrDataEntry = MibTableRow((1, 3, 6, 1, 3, 124, 2, 1), ).setIndexNames((0, "TIME-AGGREGATE-MIB", "tAggrCtlEntryID"))
if mibBuilder.loadTexts: tAggrDataEntry.setStatus('current')
tAggrDataRecord = MibTableColumn((1, 3, 6, 1, 3, 124, 2, 1, 1), TimeAggrMOValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tAggrDataRecord.setStatus('current')
tAggrDataRecordCompressed = MibTableColumn((1, 3, 6, 1, 3, 124, 2, 1, 2), CompressedTimeAggrMOValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tAggrDataRecordCompressed.setStatus('current')
tAggrDataErrorRecord = MibTableColumn((1, 3, 6, 1, 3, 124, 2, 1, 3), TAggrMOErrorStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tAggrDataErrorRecord.setStatus('current')
tAggrConformance = MibIdentifier((1, 3, 6, 1, 3, 124, 3))
tAggrGroups = MibIdentifier((1, 3, 6, 1, 3, 124, 3, 1))
tAggrCompliances = MibIdentifier((1, 3, 6, 1, 3, 124, 3, 2))
tAggrMibCompliance = ModuleCompliance((1, 3, 6, 1, 3, 124, 3, 2, 1)).setObjects(("TIME-AGGREGATE-MIB", "tAggrMibBasicGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tAggrMibCompliance = tAggrMibCompliance.setStatus('current')
tAggrMibBasicGroup = ObjectGroup((1, 3, 6, 1, 3, 124, 3, 1, 1)).setObjects(("TIME-AGGREGATE-MIB", "tAggrCtlMOInstance"), ("TIME-AGGREGATE-MIB", "tAggrCtlAgMODescr"), ("TIME-AGGREGATE-MIB", "tAggrCtlInterval"), ("TIME-AGGREGATE-MIB", "tAggrCtlSamples"), ("TIME-AGGREGATE-MIB", "tAggrCtlCompressionAlgorithm"), ("TIME-AGGREGATE-MIB", "tAggrCtlEntryOwner"), ("TIME-AGGREGATE-MIB", "tAggrCtlEntryStorageType"), ("TIME-AGGREGATE-MIB", "tAggrCtlEntryStatus"), ("TIME-AGGREGATE-MIB", "tAggrDataRecord"), ("TIME-AGGREGATE-MIB", "tAggrDataRecordCompressed"), ("TIME-AGGREGATE-MIB", "tAggrDataErrorRecord"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tAggrMibBasicGroup = tAggrMibBasicGroup.setStatus('current')
mibBuilder.exportSymbols("TIME-AGGREGATE-MIB", tAggrCtlInterval=tAggrCtlInterval, tAggrDataEntry=tAggrDataEntry, tAggrDataTable=tAggrDataTable, tAggrCtlTable=tAggrCtlTable, tAggrGroups=tAggrGroups, tAggrDataErrorRecord=tAggrDataErrorRecord, tAggrCompliances=tAggrCompliances, tAggrCtlEntry=tAggrCtlEntry, tAggrConformance=tAggrConformance, tAggrCtlEntryOwner=tAggrCtlEntryOwner, tAggrCtlAgMODescr=tAggrCtlAgMODescr, tAggrCtlEntryStorageType=tAggrCtlEntryStorageType, tAggrCtlSamples=tAggrCtlSamples, tAggrCtlEntryStatus=tAggrCtlEntryStatus, tAggrMibBasicGroup=tAggrMibBasicGroup, tAggrMibCompliance=tAggrMibCompliance, TimeAggrMOValue=TimeAggrMOValue, tAggrMIB=tAggrMIB, PYSNMP_MODULE_ID=tAggrMIB, tAggrCtlEntryID=tAggrCtlEntryID, tAggrDataRecord=tAggrDataRecord, tAggrDataRecordCompressed=tAggrDataRecordCompressed, tAggrCtlCompressionAlgorithm=tAggrCtlCompressionAlgorithm, CompressedTimeAggrMOValue=CompressedTimeAggrMOValue, tAggrCtlMOInstance=tAggrCtlMOInstance, TAggrMOErrorStatus=TAggrMOErrorStatus)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection')
(owner_string,) = mibBuilder.importSymbols('RMON-MIB', 'OwnerString')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup')
(mib_identifier, integer32, ip_address, unsigned32, bits, opaque, object_identity, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, experimental, time_ticks, notification_type, counter64, module_identity, iso, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Integer32', 'IpAddress', 'Unsigned32', 'Bits', 'Opaque', 'ObjectIdentity', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'experimental', 'TimeTicks', 'NotificationType', 'Counter64', 'ModuleIdentity', 'iso', 'Counter32')
(row_status, storage_type, textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'StorageType', 'TextualConvention', 'DisplayString')
t_aggr_mib = module_identity((1, 3, 6, 1, 3, 124))
tAggrMIB.setRevisions(('2006-04-27 00:00',))
if mibBuilder.loadTexts:
tAggrMIB.setLastUpdated('200604270000Z')
if mibBuilder.loadTexts:
tAggrMIB.setOrganization('Cyber Solutions Inc. NetMan Working Group')
class Taggrmoerrorstatus(TextualConvention, Opaque):
status = 'current'
subtype_spec = Opaque.subtypeSpec + value_size_constraint(0, 1024)
class Timeaggrmovalue(TextualConvention, Opaque):
status = 'current'
subtype_spec = Opaque.subtypeSpec + value_size_constraint(0, 1024)
class Compressedtimeaggrmovalue(TextualConvention, Opaque):
status = 'current'
subtype_spec = Opaque.subtypeSpec + value_size_constraint(0, 1024)
t_aggr_ctl_table = mib_table((1, 3, 6, 1, 3, 124, 1))
if mibBuilder.loadTexts:
tAggrCtlTable.setStatus('current')
t_aggr_ctl_entry = mib_table_row((1, 3, 6, 1, 3, 124, 1, 1)).setIndexNames((0, 'TIME-AGGREGATE-MIB', 'tAggrCtlEntryID'))
if mibBuilder.loadTexts:
tAggrCtlEntry.setStatus('current')
t_aggr_ctl_entry_id = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 32)))
if mibBuilder.loadTexts:
tAggrCtlEntryID.setStatus('current')
t_aggr_ctl_mo_instance = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 2), object_identifier()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
tAggrCtlMOInstance.setStatus('current')
t_aggr_ctl_ag_mo_descr = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 3), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
tAggrCtlAgMODescr.setStatus('current')
t_aggr_ctl_interval = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 4), integer32()).setUnits('micro seconds').setMaxAccess('readcreate')
if mibBuilder.loadTexts:
tAggrCtlInterval.setStatus('current')
t_aggr_ctl_samples = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 5), integer32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
tAggrCtlSamples.setStatus('current')
t_aggr_ctl_compression_algorithm = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('none', 1), ('deflate', 2))).clone('none')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
tAggrCtlCompressionAlgorithm.setStatus('current')
t_aggr_ctl_entry_owner = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 7), owner_string()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
tAggrCtlEntryOwner.setStatus('current')
t_aggr_ctl_entry_storage_type = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 8), storage_type()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
tAggrCtlEntryStorageType.setStatus('current')
t_aggr_ctl_entry_status = mib_table_column((1, 3, 6, 1, 3, 124, 1, 1, 9), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
tAggrCtlEntryStatus.setStatus('current')
t_aggr_data_table = mib_table((1, 3, 6, 1, 3, 124, 2))
if mibBuilder.loadTexts:
tAggrDataTable.setStatus('current')
t_aggr_data_entry = mib_table_row((1, 3, 6, 1, 3, 124, 2, 1)).setIndexNames((0, 'TIME-AGGREGATE-MIB', 'tAggrCtlEntryID'))
if mibBuilder.loadTexts:
tAggrDataEntry.setStatus('current')
t_aggr_data_record = mib_table_column((1, 3, 6, 1, 3, 124, 2, 1, 1), time_aggr_mo_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
tAggrDataRecord.setStatus('current')
t_aggr_data_record_compressed = mib_table_column((1, 3, 6, 1, 3, 124, 2, 1, 2), compressed_time_aggr_mo_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
tAggrDataRecordCompressed.setStatus('current')
t_aggr_data_error_record = mib_table_column((1, 3, 6, 1, 3, 124, 2, 1, 3), t_aggr_mo_error_status()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
tAggrDataErrorRecord.setStatus('current')
t_aggr_conformance = mib_identifier((1, 3, 6, 1, 3, 124, 3))
t_aggr_groups = mib_identifier((1, 3, 6, 1, 3, 124, 3, 1))
t_aggr_compliances = mib_identifier((1, 3, 6, 1, 3, 124, 3, 2))
t_aggr_mib_compliance = module_compliance((1, 3, 6, 1, 3, 124, 3, 2, 1)).setObjects(('TIME-AGGREGATE-MIB', 'tAggrMibBasicGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
t_aggr_mib_compliance = tAggrMibCompliance.setStatus('current')
t_aggr_mib_basic_group = object_group((1, 3, 6, 1, 3, 124, 3, 1, 1)).setObjects(('TIME-AGGREGATE-MIB', 'tAggrCtlMOInstance'), ('TIME-AGGREGATE-MIB', 'tAggrCtlAgMODescr'), ('TIME-AGGREGATE-MIB', 'tAggrCtlInterval'), ('TIME-AGGREGATE-MIB', 'tAggrCtlSamples'), ('TIME-AGGREGATE-MIB', 'tAggrCtlCompressionAlgorithm'), ('TIME-AGGREGATE-MIB', 'tAggrCtlEntryOwner'), ('TIME-AGGREGATE-MIB', 'tAggrCtlEntryStorageType'), ('TIME-AGGREGATE-MIB', 'tAggrCtlEntryStatus'), ('TIME-AGGREGATE-MIB', 'tAggrDataRecord'), ('TIME-AGGREGATE-MIB', 'tAggrDataRecordCompressed'), ('TIME-AGGREGATE-MIB', 'tAggrDataErrorRecord'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
t_aggr_mib_basic_group = tAggrMibBasicGroup.setStatus('current')
mibBuilder.exportSymbols('TIME-AGGREGATE-MIB', tAggrCtlInterval=tAggrCtlInterval, tAggrDataEntry=tAggrDataEntry, tAggrDataTable=tAggrDataTable, tAggrCtlTable=tAggrCtlTable, tAggrGroups=tAggrGroups, tAggrDataErrorRecord=tAggrDataErrorRecord, tAggrCompliances=tAggrCompliances, tAggrCtlEntry=tAggrCtlEntry, tAggrConformance=tAggrConformance, tAggrCtlEntryOwner=tAggrCtlEntryOwner, tAggrCtlAgMODescr=tAggrCtlAgMODescr, tAggrCtlEntryStorageType=tAggrCtlEntryStorageType, tAggrCtlSamples=tAggrCtlSamples, tAggrCtlEntryStatus=tAggrCtlEntryStatus, tAggrMibBasicGroup=tAggrMibBasicGroup, tAggrMibCompliance=tAggrMibCompliance, TimeAggrMOValue=TimeAggrMOValue, tAggrMIB=tAggrMIB, PYSNMP_MODULE_ID=tAggrMIB, tAggrCtlEntryID=tAggrCtlEntryID, tAggrDataRecord=tAggrDataRecord, tAggrDataRecordCompressed=tAggrDataRecordCompressed, tAggrCtlCompressionAlgorithm=tAggrCtlCompressionAlgorithm, CompressedTimeAggrMOValue=CompressedTimeAggrMOValue, tAggrCtlMOInstance=tAggrCtlMOInstance, TAggrMOErrorStatus=TAggrMOErrorStatus) |
class ExtendedTextAttributes(object):
def __init__(
self,
text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info
):
self._text = text
self._matched_text = matched_text
self._canonical_url = canonical_url
self._description = description
self._title = title
self._jpeg_thumbnail = jpeg_thumbnail
self._context_info = context_info
def __str__(self):
attrs = []
if self.text is not None:
attrs.append(("text", self.text))
if self.matched_text is not None:
attrs.append(("matched_text", self.matched_text))
if self.canonical_url is not None:
attrs.append(("canonical_url", self.canonical_url))
if self.description is not None:
attrs.append(("description", self.description))
if self.title is not None:
attrs.append(("title", self.title))
if self.jpeg_thumbnail is not None:
attrs.append(("jpeg_thumbnail", "[binary data]"))
if self.context_info is not None:
attrs.append(("context_info", self.context_info))
return "[%s]" % " ".join((map(lambda item: "%s=%s" % item, attrs)))
@property
def text(self):
return self._text
@text.setter
def text(self, value):
self._text = value
@property
def matched_text(self):
return self._matched_text
@matched_text.setter
def matched_text(self, value):
self._matched_text = value
@property
def canonical_url(self):
return self._canonical_url
@canonical_url.setter
def canonical_url(self, value):
self._canonical_url = value
@property
def description(self):
return self._description
@description.setter
def description(self, value):
self._description = value
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = value
@property
def jpeg_thumbnail(self):
return self._jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self._jpeg_thumbnail = value
@property
def context_info(self):
return self._context_info
@context_info.setter
def context_info(self, value):
self._context_info = value
| class Extendedtextattributes(object):
def __init__(self, text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info):
self._text = text
self._matched_text = matched_text
self._canonical_url = canonical_url
self._description = description
self._title = title
self._jpeg_thumbnail = jpeg_thumbnail
self._context_info = context_info
def __str__(self):
attrs = []
if self.text is not None:
attrs.append(('text', self.text))
if self.matched_text is not None:
attrs.append(('matched_text', self.matched_text))
if self.canonical_url is not None:
attrs.append(('canonical_url', self.canonical_url))
if self.description is not None:
attrs.append(('description', self.description))
if self.title is not None:
attrs.append(('title', self.title))
if self.jpeg_thumbnail is not None:
attrs.append(('jpeg_thumbnail', '[binary data]'))
if self.context_info is not None:
attrs.append(('context_info', self.context_info))
return '[%s]' % ' '.join(map(lambda item: '%s=%s' % item, attrs))
@property
def text(self):
return self._text
@text.setter
def text(self, value):
self._text = value
@property
def matched_text(self):
return self._matched_text
@matched_text.setter
def matched_text(self, value):
self._matched_text = value
@property
def canonical_url(self):
return self._canonical_url
@canonical_url.setter
def canonical_url(self, value):
self._canonical_url = value
@property
def description(self):
return self._description
@description.setter
def description(self, value):
self._description = value
@property
def title(self):
return self._title
@title.setter
def title(self, value):
self._title = value
@property
def jpeg_thumbnail(self):
return self._jpeg_thumbnail
@jpeg_thumbnail.setter
def jpeg_thumbnail(self, value):
self._jpeg_thumbnail = value
@property
def context_info(self):
return self._context_info
@context_info.setter
def context_info(self, value):
self._context_info = value |
_V = {}
# Stages: game, rounds
# State: probability, probability of co-operating
# Action:
# V(t,p) gives maximum expected value from starting game t with probability p of cooperating
def V(game, probability):
if game is 10:
return 0, 0
else:
if (game, probability) not in _V:
cooperate = probability * (3 + V(game + 1, min(1, probability + 0.1))[0]) + \
(1 - probability) * (0 + V(game + 1, min(1, probability + 0.1))[0])
defect = probability * (5 + V(game + 1, max(0, probability - 0.2))[0]) + \
(1 - probability) * (1 + V(game + 1, max(0, probability - 0.2))[0])
_V[game, probability] = max((cooperate, 'Co-operate'), (defect, 'Defect'))
return _V[game, probability]
print('---------------------------')
prob = 0.6
# Transitions are deterministic so we can generate sequence of actions
for games in range(10):
payoff, decision = V(games, prob)
print('|Round', games + 1, '\t|\t', decision)
prob = min(1, prob + 0.1) if decision == 'Co-operate' else max(0, prob - 0.2)
| _v = {}
def v(game, probability):
if game is 10:
return (0, 0)
elif (game, probability) not in _V:
cooperate = probability * (3 + v(game + 1, min(1, probability + 0.1))[0]) + (1 - probability) * (0 + v(game + 1, min(1, probability + 0.1))[0])
defect = probability * (5 + v(game + 1, max(0, probability - 0.2))[0]) + (1 - probability) * (1 + v(game + 1, max(0, probability - 0.2))[0])
_V[game, probability] = max((cooperate, 'Co-operate'), (defect, 'Defect'))
return _V[game, probability]
print('---------------------------')
prob = 0.6
for games in range(10):
(payoff, decision) = v(games, prob)
print('|Round', games + 1, '\t|\t', decision)
prob = min(1, prob + 0.1) if decision == 'Co-operate' else max(0, prob - 0.2) |
BASE_DIR = './'
environ = {
'KPK_DATA': '/home/kpk/data',
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
}
KPK_DATA = environ.get('KPK_DATA')
# print(KPK_DATA)
# _KPK_DATA = environ['KPK_DATA']
# print(_KPK_DATA)
# os.environ.get('KPK_DATA') or BASE_DIR
#
# os.environ.get('KPK_DATA') if os.environ.get('KPK_DATA') else BASE_DIR
# ROOT = os.environ.get('KPK_DATA') if os.environ.get('KPK_DATA') else BASE_DIR
pass
if KPK_DATA:
ROOT = KPK_DATA
else:
ROOT = BASE_DIR
print(ROOT)
pass
ROOT = KPK_DATA if KPK_DATA else BASE_DIR
print(ROOT)
pass
ROOT = KPK_DATA or BASE_DIR
print(ROOT)
| base_dir = './'
environ = {'KPK_DATA': '/home/kpk/data', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'}
kpk_data = environ.get('KPK_DATA')
pass
if KPK_DATA:
root = KPK_DATA
else:
root = BASE_DIR
print(ROOT)
pass
root = KPK_DATA if KPK_DATA else BASE_DIR
print(ROOT)
pass
root = KPK_DATA or BASE_DIR
print(ROOT) |
class Reference:
def __init__(self, id, campaign_id, name, details, created, modified):
self.id = id
self.campaign_id = campaign_id
self.name = name
self.details = details
self.created = created
self.modified = modified
| class Reference:
def __init__(self, id, campaign_id, name, details, created, modified):
self.id = id
self.campaign_id = campaign_id
self.name = name
self.details = details
self.created = created
self.modified = modified |
NONE = 0x000000000
# Posting Permissions
CREATE_POST = 0x000000001
EDIT_POST = 0x000000002
DELETE_POST = 0x000000004
# Documents Permissions
UPLOAD_DOCUMENT = 0x000000008
EDIT_DOCUMENT = 0x000000010
DELETE_DOCUMENT = 0x000000020
# User Account Permissions
CREATE_USER = 0x000000040
EDIT_USER = 0x000000080
DELETE_USER = 0x000000100 | none = 0
create_post = 1
edit_post = 2
delete_post = 4
upload_document = 8
edit_document = 16
delete_document = 32
create_user = 64
edit_user = 128
delete_user = 256 |
class Car:
wheels = 4 # Class (Static) Variables before __init__
def __init__(self):
self.com = "BMW" # Instance Variables inside __init__
self.mil = "10"
c1 = Car()
c2 = Car()
Car.wheels = 5 # The value of all the wheels is now 5
# c1.wheels = 10 # For individual changes
# c2.wheels = 15
print(c1.com, c1.mil, c1.wheels) # print(c1.com, c1.mil, Car.wheels)
print(c2.com, c2.mil, c2.wheels) # print(c1.com, c1.mil, Car.wheels) | class Car:
wheels = 4
def __init__(self):
self.com = 'BMW'
self.mil = '10'
c1 = car()
c2 = car()
Car.wheels = 5
print(c1.com, c1.mil, c1.wheels)
print(c2.com, c2.mil, c2.wheels) |
'''
Discuss structure:
Getting input from user
Formatting the input (multiply by 100 then convert to integer)
Getting total amount of change (amount paid minus bill)
Getting dollars of change (divide by 100 then convert to integer)
Getting the amount of change leftover (either change minus dollars times 100 or change modulus 100)
Getting quarters of change (divide by 25 then convert to integer)
Getting the amount of change leftover (either change minus quarters times 25 or change modulus 25)
and so on.
Stress the use of comments to at least segment the project.
Stress the use of print statements to test regularly.
Stress the use of working it out on paper in detail to see the calculations that need to be made.
'''
#EXAMPLE SOLUTION:
#The following is not perfect but would benefit from some rounding.
bill=input("How many dollars is the bill for? ")
pay=input("How many dollars will you give the cashier? ")
change=float(pay)-float(bill)
dollars=int(change/1)
left=(change%1)
quarters=int(left/.25)
left=(left%.25)
dimes=int(left/.1)
left=left%.1
nickles=int(left%.05)
pennies=int(100*(left%.05))
left=left%.01
print("If you don't turn things into ints, you are in danger of getting this: "+str(left)+", instead of zero")
print("The bill is for $" + bill + ". You are giving the cashier $" + pay +". You will recieve $"+str(change) + " in the form of " + str(dollars) +" dollars, "+str(quarters)+" quarters, "+str(dimes)+" dimes, "+str(nickles)+" nickles and "+str(left)+" pennies. Thank you for your business")
| """
Discuss structure:
Getting input from user
Formatting the input (multiply by 100 then convert to integer)
Getting total amount of change (amount paid minus bill)
Getting dollars of change (divide by 100 then convert to integer)
Getting the amount of change leftover (either change minus dollars times 100 or change modulus 100)
Getting quarters of change (divide by 25 then convert to integer)
Getting the amount of change leftover (either change minus quarters times 25 or change modulus 25)
and so on.
Stress the use of comments to at least segment the project.
Stress the use of print statements to test regularly.
Stress the use of working it out on paper in detail to see the calculations that need to be made.
"""
bill = input('How many dollars is the bill for? ')
pay = input('How many dollars will you give the cashier? ')
change = float(pay) - float(bill)
dollars = int(change / 1)
left = change % 1
quarters = int(left / 0.25)
left = left % 0.25
dimes = int(left / 0.1)
left = left % 0.1
nickles = int(left % 0.05)
pennies = int(100 * (left % 0.05))
left = left % 0.01
print("If you don't turn things into ints, you are in danger of getting this: " + str(left) + ', instead of zero')
print('The bill is for $' + bill + '. You are giving the cashier $' + pay + '. You will recieve $' + str(change) + ' in the form of ' + str(dollars) + ' dollars, ' + str(quarters) + ' quarters, ' + str(dimes) + ' dimes, ' + str(nickles) + ' nickles and ' + str(left) + ' pennies. Thank you for your business') |
class AzureCloudProviderResourceModel(object):
def __init__(self):
self.azure_application_id = '' # type: str
self.azure_mgmt_network_d = '' # type: str
self.azure_mgmt_nsg_id = '' # type: str
self.azure_application_key = '' # type: str
self.region = '' # type: str
self.vm_size = '' # type: str
self.keypairs_location = '' # type: str
self.networks_in_use = '' # type: str
self.azure_subscription_id = '' # type: str
self.azure_tenant = '' # type: str
self.storage_type = '' # type: str
self.management_group_name = '' # type: str
self.additional_mgmt_networks = '' # type: str
self.cloud_provider_name = '' # type: str
self.private_ip_allocation_method = '' # type: str
| class Azurecloudproviderresourcemodel(object):
def __init__(self):
self.azure_application_id = ''
self.azure_mgmt_network_d = ''
self.azure_mgmt_nsg_id = ''
self.azure_application_key = ''
self.region = ''
self.vm_size = ''
self.keypairs_location = ''
self.networks_in_use = ''
self.azure_subscription_id = ''
self.azure_tenant = ''
self.storage_type = ''
self.management_group_name = ''
self.additional_mgmt_networks = ''
self.cloud_provider_name = ''
self.private_ip_allocation_method = '' |
# Given a binary matrix representing an image, we want to flip the image horizontally, then invert it.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [0, 1, 1] horizontally results in [1, 1, 0].
# To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
# For example, inverting [1, 1, 0] results in [0, 0, 1].
# Example 1:
# Input: [
# [1,0,1],
# [1,1,1],
# [0,1,1]
# ]
# Output: [
# [0,1,0],
# [0,0,0],
# [0,0,1]
# ]
# Explanation: First reverse each row: [[1,0,1],[1,1,1],[1,1,0]]. Then, invert the image: [[0,1,0],[0,0,0],[0,0,1]]
def flip_invert_image(matrix):
m = len(matrix)
n = len(matrix[0])
for i in range(m):
for j in range((n + 1) // 2):
matrix[i][j], matrix[i][n - j - 1] = matrix[i][n - j - 1] ^ 1, matrix[i][j] ^ 1
return matrix
print(flip_invert_image([
[1,0,1],
[1,1,1],
[0,1,1]
]))
print(flip_invert_image([
[1,1,0,0],
[1,0,0,1],
[0,1,1,1],
[1,0,1,0]
])) | def flip_invert_image(matrix):
m = len(matrix)
n = len(matrix[0])
for i in range(m):
for j in range((n + 1) // 2):
(matrix[i][j], matrix[i][n - j - 1]) = (matrix[i][n - j - 1] ^ 1, matrix[i][j] ^ 1)
return matrix
print(flip_invert_image([[1, 0, 1], [1, 1, 1], [0, 1, 1]]))
print(flip_invert_image([[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]])) |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"availability_zones": "availabilityZones",
"backend_services": "backendServices",
"beanstalk_environment_name": "beanstalkEnvironmentName",
"block_devices_mode": "blockDevicesMode",
"capacity_unit": "capacityUnit",
"cluster_id": "clusterId",
"cluster_zone_name": "clusterZoneName",
"controller_id": "controllerId",
"cpu_credits": "cpuCredits",
"desired_capacity": "desiredCapacity",
"draining_timeout": "drainingTimeout",
"ebs_block_devices": "ebsBlockDevices",
"ebs_optimized": "ebsOptimized",
"elastic_ips": "elasticIps",
"elastic_load_balancers": "elasticLoadBalancers",
"enable_monitoring": "enableMonitoring",
"ephemeral_block_devices": "ephemeralBlockDevices",
"event_type": "eventType",
"fallback_to_ondemand": "fallbackToOndemand",
"health_check": "healthCheck",
"health_check_grace_period": "healthCheckGracePeriod",
"health_check_type": "healthCheckType",
"health_check_unhealthy_duration_before_replacement": "healthCheckUnhealthyDurationBeforeReplacement",
"iam_instance_profile": "iamInstanceProfile",
"image_id": "imageId",
"instance_types_customs": "instanceTypesCustoms",
"instance_types_ondemand": "instanceTypesOndemand",
"instance_types_preemptibles": "instanceTypesPreemptibles",
"instance_types_preferred_spots": "instanceTypesPreferredSpots",
"instance_types_spots": "instanceTypesSpots",
"instance_types_weights": "instanceTypesWeights",
"integration_codedeploy": "integrationCodedeploy",
"integration_docker_swarm": "integrationDockerSwarm",
"integration_ecs": "integrationEcs",
"integration_gitlab": "integrationGitlab",
"integration_kubernetes": "integrationKubernetes",
"integration_mesosphere": "integrationMesosphere",
"integration_multai_runtime": "integrationMultaiRuntime",
"integration_nomad": "integrationNomad",
"integration_rancher": "integrationRancher",
"integration_route53": "integrationRoute53",
"ip_forwarding": "ipForwarding",
"key_name": "keyName",
"lifetime_period": "lifetimePeriod",
"load_balancers": "loadBalancers",
"low_priority_sizes": "lowPrioritySizes",
"max_size": "maxSize",
"min_size": "minSize",
"multai_target_sets": "multaiTargetSets",
"network_interfaces": "networkInterfaces",
"node_image": "nodeImage",
"od_sizes": "odSizes",
"ondemand_count": "ondemandCount",
"persist_block_devices": "persistBlockDevices",
"persist_private_ip": "persistPrivateIp",
"persist_root_device": "persistRootDevice",
"placement_tenancy": "placementTenancy",
"preemptible_percentage": "preemptiblePercentage",
"preferred_availability_zones": "preferredAvailabilityZones",
"private_ips": "privateIps",
"resource_group_name": "resourceGroupName",
"resource_id": "resourceId",
"revert_to_spot": "revertToSpot",
"scaling_down_policies": "scalingDownPolicies",
"scaling_target_policies": "scalingTargetPolicies",
"scaling_up_policies": "scalingUpPolicies",
"scheduled_tasks": "scheduledTasks",
"security_groups": "securityGroups",
"service_account": "serviceAccount",
"shutdown_script": "shutdownScript",
"spot_percentage": "spotPercentage",
"startup_script": "startupScript",
"stateful_deallocation": "statefulDeallocation",
"subnet_ids": "subnetIds",
"target_group_arns": "targetGroupArns",
"update_policy": "updatePolicy",
"user_data": "userData",
"utilize_reserved_instances": "utilizeReservedInstances",
"wait_for_capacity": "waitForCapacity",
"wait_for_capacity_timeout": "waitForCapacityTimeout",
}
_CAMEL_TO_SNAKE_CASE_TABLE = {
"availabilityZones": "availability_zones",
"backendServices": "backend_services",
"beanstalkEnvironmentName": "beanstalk_environment_name",
"blockDevicesMode": "block_devices_mode",
"capacityUnit": "capacity_unit",
"clusterId": "cluster_id",
"clusterZoneName": "cluster_zone_name",
"controllerId": "controller_id",
"cpuCredits": "cpu_credits",
"desiredCapacity": "desired_capacity",
"drainingTimeout": "draining_timeout",
"ebsBlockDevices": "ebs_block_devices",
"ebsOptimized": "ebs_optimized",
"elasticIps": "elastic_ips",
"elasticLoadBalancers": "elastic_load_balancers",
"enableMonitoring": "enable_monitoring",
"ephemeralBlockDevices": "ephemeral_block_devices",
"eventType": "event_type",
"fallbackToOndemand": "fallback_to_ondemand",
"healthCheck": "health_check",
"healthCheckGracePeriod": "health_check_grace_period",
"healthCheckType": "health_check_type",
"healthCheckUnhealthyDurationBeforeReplacement": "health_check_unhealthy_duration_before_replacement",
"iamInstanceProfile": "iam_instance_profile",
"imageId": "image_id",
"instanceTypesCustoms": "instance_types_customs",
"instanceTypesOndemand": "instance_types_ondemand",
"instanceTypesPreemptibles": "instance_types_preemptibles",
"instanceTypesPreferredSpots": "instance_types_preferred_spots",
"instanceTypesSpots": "instance_types_spots",
"instanceTypesWeights": "instance_types_weights",
"integrationCodedeploy": "integration_codedeploy",
"integrationDockerSwarm": "integration_docker_swarm",
"integrationEcs": "integration_ecs",
"integrationGitlab": "integration_gitlab",
"integrationKubernetes": "integration_kubernetes",
"integrationMesosphere": "integration_mesosphere",
"integrationMultaiRuntime": "integration_multai_runtime",
"integrationNomad": "integration_nomad",
"integrationRancher": "integration_rancher",
"integrationRoute53": "integration_route53",
"ipForwarding": "ip_forwarding",
"keyName": "key_name",
"lifetimePeriod": "lifetime_period",
"loadBalancers": "load_balancers",
"lowPrioritySizes": "low_priority_sizes",
"maxSize": "max_size",
"minSize": "min_size",
"multaiTargetSets": "multai_target_sets",
"networkInterfaces": "network_interfaces",
"nodeImage": "node_image",
"odSizes": "od_sizes",
"ondemandCount": "ondemand_count",
"persistBlockDevices": "persist_block_devices",
"persistPrivateIp": "persist_private_ip",
"persistRootDevice": "persist_root_device",
"placementTenancy": "placement_tenancy",
"preemptiblePercentage": "preemptible_percentage",
"preferredAvailabilityZones": "preferred_availability_zones",
"privateIps": "private_ips",
"resourceGroupName": "resource_group_name",
"resourceId": "resource_id",
"revertToSpot": "revert_to_spot",
"scalingDownPolicies": "scaling_down_policies",
"scalingTargetPolicies": "scaling_target_policies",
"scalingUpPolicies": "scaling_up_policies",
"scheduledTasks": "scheduled_tasks",
"securityGroups": "security_groups",
"serviceAccount": "service_account",
"shutdownScript": "shutdown_script",
"spotPercentage": "spot_percentage",
"startupScript": "startup_script",
"statefulDeallocation": "stateful_deallocation",
"subnetIds": "subnet_ids",
"targetGroupArns": "target_group_arns",
"updatePolicy": "update_policy",
"userData": "user_data",
"utilizeReservedInstances": "utilize_reserved_instances",
"waitForCapacity": "wait_for_capacity",
"waitForCapacityTimeout": "wait_for_capacity_timeout",
}
| _snake_to_camel_case_table = {'availability_zones': 'availabilityZones', 'backend_services': 'backendServices', 'beanstalk_environment_name': 'beanstalkEnvironmentName', 'block_devices_mode': 'blockDevicesMode', 'capacity_unit': 'capacityUnit', 'cluster_id': 'clusterId', 'cluster_zone_name': 'clusterZoneName', 'controller_id': 'controllerId', 'cpu_credits': 'cpuCredits', 'desired_capacity': 'desiredCapacity', 'draining_timeout': 'drainingTimeout', 'ebs_block_devices': 'ebsBlockDevices', 'ebs_optimized': 'ebsOptimized', 'elastic_ips': 'elasticIps', 'elastic_load_balancers': 'elasticLoadBalancers', 'enable_monitoring': 'enableMonitoring', 'ephemeral_block_devices': 'ephemeralBlockDevices', 'event_type': 'eventType', 'fallback_to_ondemand': 'fallbackToOndemand', 'health_check': 'healthCheck', 'health_check_grace_period': 'healthCheckGracePeriod', 'health_check_type': 'healthCheckType', 'health_check_unhealthy_duration_before_replacement': 'healthCheckUnhealthyDurationBeforeReplacement', 'iam_instance_profile': 'iamInstanceProfile', 'image_id': 'imageId', 'instance_types_customs': 'instanceTypesCustoms', 'instance_types_ondemand': 'instanceTypesOndemand', 'instance_types_preemptibles': 'instanceTypesPreemptibles', 'instance_types_preferred_spots': 'instanceTypesPreferredSpots', 'instance_types_spots': 'instanceTypesSpots', 'instance_types_weights': 'instanceTypesWeights', 'integration_codedeploy': 'integrationCodedeploy', 'integration_docker_swarm': 'integrationDockerSwarm', 'integration_ecs': 'integrationEcs', 'integration_gitlab': 'integrationGitlab', 'integration_kubernetes': 'integrationKubernetes', 'integration_mesosphere': 'integrationMesosphere', 'integration_multai_runtime': 'integrationMultaiRuntime', 'integration_nomad': 'integrationNomad', 'integration_rancher': 'integrationRancher', 'integration_route53': 'integrationRoute53', 'ip_forwarding': 'ipForwarding', 'key_name': 'keyName', 'lifetime_period': 'lifetimePeriod', 'load_balancers': 'loadBalancers', 'low_priority_sizes': 'lowPrioritySizes', 'max_size': 'maxSize', 'min_size': 'minSize', 'multai_target_sets': 'multaiTargetSets', 'network_interfaces': 'networkInterfaces', 'node_image': 'nodeImage', 'od_sizes': 'odSizes', 'ondemand_count': 'ondemandCount', 'persist_block_devices': 'persistBlockDevices', 'persist_private_ip': 'persistPrivateIp', 'persist_root_device': 'persistRootDevice', 'placement_tenancy': 'placementTenancy', 'preemptible_percentage': 'preemptiblePercentage', 'preferred_availability_zones': 'preferredAvailabilityZones', 'private_ips': 'privateIps', 'resource_group_name': 'resourceGroupName', 'resource_id': 'resourceId', 'revert_to_spot': 'revertToSpot', 'scaling_down_policies': 'scalingDownPolicies', 'scaling_target_policies': 'scalingTargetPolicies', 'scaling_up_policies': 'scalingUpPolicies', 'scheduled_tasks': 'scheduledTasks', 'security_groups': 'securityGroups', 'service_account': 'serviceAccount', 'shutdown_script': 'shutdownScript', 'spot_percentage': 'spotPercentage', 'startup_script': 'startupScript', 'stateful_deallocation': 'statefulDeallocation', 'subnet_ids': 'subnetIds', 'target_group_arns': 'targetGroupArns', 'update_policy': 'updatePolicy', 'user_data': 'userData', 'utilize_reserved_instances': 'utilizeReservedInstances', 'wait_for_capacity': 'waitForCapacity', 'wait_for_capacity_timeout': 'waitForCapacityTimeout'}
_camel_to_snake_case_table = {'availabilityZones': 'availability_zones', 'backendServices': 'backend_services', 'beanstalkEnvironmentName': 'beanstalk_environment_name', 'blockDevicesMode': 'block_devices_mode', 'capacityUnit': 'capacity_unit', 'clusterId': 'cluster_id', 'clusterZoneName': 'cluster_zone_name', 'controllerId': 'controller_id', 'cpuCredits': 'cpu_credits', 'desiredCapacity': 'desired_capacity', 'drainingTimeout': 'draining_timeout', 'ebsBlockDevices': 'ebs_block_devices', 'ebsOptimized': 'ebs_optimized', 'elasticIps': 'elastic_ips', 'elasticLoadBalancers': 'elastic_load_balancers', 'enableMonitoring': 'enable_monitoring', 'ephemeralBlockDevices': 'ephemeral_block_devices', 'eventType': 'event_type', 'fallbackToOndemand': 'fallback_to_ondemand', 'healthCheck': 'health_check', 'healthCheckGracePeriod': 'health_check_grace_period', 'healthCheckType': 'health_check_type', 'healthCheckUnhealthyDurationBeforeReplacement': 'health_check_unhealthy_duration_before_replacement', 'iamInstanceProfile': 'iam_instance_profile', 'imageId': 'image_id', 'instanceTypesCustoms': 'instance_types_customs', 'instanceTypesOndemand': 'instance_types_ondemand', 'instanceTypesPreemptibles': 'instance_types_preemptibles', 'instanceTypesPreferredSpots': 'instance_types_preferred_spots', 'instanceTypesSpots': 'instance_types_spots', 'instanceTypesWeights': 'instance_types_weights', 'integrationCodedeploy': 'integration_codedeploy', 'integrationDockerSwarm': 'integration_docker_swarm', 'integrationEcs': 'integration_ecs', 'integrationGitlab': 'integration_gitlab', 'integrationKubernetes': 'integration_kubernetes', 'integrationMesosphere': 'integration_mesosphere', 'integrationMultaiRuntime': 'integration_multai_runtime', 'integrationNomad': 'integration_nomad', 'integrationRancher': 'integration_rancher', 'integrationRoute53': 'integration_route53', 'ipForwarding': 'ip_forwarding', 'keyName': 'key_name', 'lifetimePeriod': 'lifetime_period', 'loadBalancers': 'load_balancers', 'lowPrioritySizes': 'low_priority_sizes', 'maxSize': 'max_size', 'minSize': 'min_size', 'multaiTargetSets': 'multai_target_sets', 'networkInterfaces': 'network_interfaces', 'nodeImage': 'node_image', 'odSizes': 'od_sizes', 'ondemandCount': 'ondemand_count', 'persistBlockDevices': 'persist_block_devices', 'persistPrivateIp': 'persist_private_ip', 'persistRootDevice': 'persist_root_device', 'placementTenancy': 'placement_tenancy', 'preemptiblePercentage': 'preemptible_percentage', 'preferredAvailabilityZones': 'preferred_availability_zones', 'privateIps': 'private_ips', 'resourceGroupName': 'resource_group_name', 'resourceId': 'resource_id', 'revertToSpot': 'revert_to_spot', 'scalingDownPolicies': 'scaling_down_policies', 'scalingTargetPolicies': 'scaling_target_policies', 'scalingUpPolicies': 'scaling_up_policies', 'scheduledTasks': 'scheduled_tasks', 'securityGroups': 'security_groups', 'serviceAccount': 'service_account', 'shutdownScript': 'shutdown_script', 'spotPercentage': 'spot_percentage', 'startupScript': 'startup_script', 'statefulDeallocation': 'stateful_deallocation', 'subnetIds': 'subnet_ids', 'targetGroupArns': 'target_group_arns', 'updatePolicy': 'update_policy', 'userData': 'user_data', 'utilizeReservedInstances': 'utilize_reserved_instances', 'waitForCapacity': 'wait_for_capacity', 'waitForCapacityTimeout': 'wait_for_capacity_timeout'} |
# guess file size : https://softwareengineering.stackexchange.com/q/204417
# https://stackoverflow.com/a/1094933
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
# def fsize(file_path):
# sizeof_fmt(self.size)
# if self.size > 1000000000:
# print('File is larger than 1 GB')
# else:
# print('File smaller than 1 GB')
| def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return '%3.1f%s%s' % (num, unit, suffix)
num /= 1024.0
return '%.1f%s%s' % (num, 'Yi', suffix) |
# Source : https://leetcode.com/problems/rectangle-overlap/
# Author : foxfromworld
# Date : 07/04/2021
# Second attempt
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec2[0] == rec2[2] or\
rec2[1] == rec2[3] or rec1[1] == rec1[3]:
return False
UpBound = min(rec1[3], rec2[3])
LoBound = max(rec1[1], rec2[1])
RtBound = min(rec1[2], rec2[2])
LtBound = max(rec1[0], rec2[0])
return True if UpBound > LoBound and RtBound > LtBound else False
# Date : 07/04/2021
# First attempt
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec1[1] == rec1[3] or \
rec2[0] == rec2[2] or rec2[1] == rec2[3]:
return False # check if it's a line
return rec2[0] < rec1[2] and rec2[1] < rec1[3] and rec1[0] < rec2[2] and rec1[1] < rec2[3]
| class Solution:
def is_rectangle_overlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec2[0] == rec2[2] or rec2[1] == rec2[3] or (rec1[1] == rec1[3]):
return False
up_bound = min(rec1[3], rec2[3])
lo_bound = max(rec1[1], rec2[1])
rt_bound = min(rec1[2], rec2[2])
lt_bound = max(rec1[0], rec2[0])
return True if UpBound > LoBound and RtBound > LtBound else False
class Solution:
def is_rectangle_overlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec1[1] == rec1[3] or rec2[0] == rec2[2] or (rec2[1] == rec2[3]):
return False
return rec2[0] < rec1[2] and rec2[1] < rec1[3] and (rec1[0] < rec2[2]) and (rec1[1] < rec2[3]) |
class Project():
def __init__(self, id_project, name, session_counter, token):
self.id_project = id_project
self.name = name
self.session_counter = session_counter
self.token = token
class Session():
def __init__(self, id_session, index, dt_start, dt_end, is_active, is_favorite, host, description, id_project):
self.id_session = id_session
self.index = index
self.dt_start = dt_start
self.dt_end = dt_end
self.is_active = is_active
self.is_favorite = is_favorite
self.host = host
self.description = description
self.id_project = id_project
class Epoch():
def __init__(self, id_epoch, index, metrics, time, id_session):
self.id_epoch = id_epoch
self.index = index
self.metrics = metrics
self.time = time
self.id_session = id_session | class Project:
def __init__(self, id_project, name, session_counter, token):
self.id_project = id_project
self.name = name
self.session_counter = session_counter
self.token = token
class Session:
def __init__(self, id_session, index, dt_start, dt_end, is_active, is_favorite, host, description, id_project):
self.id_session = id_session
self.index = index
self.dt_start = dt_start
self.dt_end = dt_end
self.is_active = is_active
self.is_favorite = is_favorite
self.host = host
self.description = description
self.id_project = id_project
class Epoch:
def __init__(self, id_epoch, index, metrics, time, id_session):
self.id_epoch = id_epoch
self.index = index
self.metrics = metrics
self.time = time
self.id_session = id_session |
#=======================================================================
# Author: Isai Damier
# Title: Selection Sort
# Project: geekviewpoint
# Package: algorithm.sorting
#
# Statement:
# Given a disordered list of integers (or any other items),
# rearrange the integers in natural order.
#
# Sample Input: [18,5,3,1,19,6,0,7,4,2,5]
# Sample Output: [0,1,2,3,4,5,5,6,7,18,19]
#
# Time Complexity of Solution:
# Best O(n^2); Average O(n^2); Worst O(n^2).
#
# Approach:
# Selection sort is a step up from insertion sort from a memory
# viewpoint. It only swaps elements that need to be swapped. In terms
# of time complexity, however, insertion sort is better.
#=======================================================================
def selectionsort( aList ):
for i in range( len( aList ) ):
least = i
for k in range( i + 1 , len( aList ) ):
if aList[k] < aList[least]:
least = k
swap( aList, least, i )
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
| def selectionsort(aList):
for i in range(len(aList)):
least = i
for k in range(i + 1, len(aList)):
if aList[k] < aList[least]:
least = k
swap(aList, least, i)
def swap(A, x, y):
tmp = A[x]
A[x] = A[y]
A[y] = tmp |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = 3
if a > 2:
print("H")
else:
print("L") | a = 3
if a > 2:
print('H')
else:
print('L') |
# Enter your code here. Read input from STDIN. Print output to STDOUT
m = float(raw_input());
t = m * input() /100;
x = m * input() /100;
totalCost = round(m + x + t);
print ('The total meal cost is' " " + str(int(totalCost)) + " " 'dollars.') | m = float(raw_input())
t = m * input() / 100
x = m * input() / 100
total_cost = round(m + x + t)
print('The total meal cost is ' + str(int(totalCost)) + ' dollars.') |
# program to match key values in two dictionaries.
x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value))
| x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value)) |
class Number(object):
def __init__(self, value):
if value % 2 != 0:
self.even = self._odds_even
else:
self.even = self._even
def _even(self):
print("even")
return True
def _odds_even(self):
print("not odd")
return False
a = Number(2)
a.even()
b = Number(3)
b.even()
a.even()
| class Number(object):
def __init__(self, value):
if value % 2 != 0:
self.even = self._odds_even
else:
self.even = self._even
def _even(self):
print('even')
return True
def _odds_even(self):
print('not odd')
return False
a = number(2)
a.even()
b = number(3)
b.even()
a.even() |
WIDTH = 87
HEIGHT = 87
FIRST = 0x20
LAST = 0x7f
_font =\
b'\x00\x4a\x5a\x02\x44\x60\x44\x52\x60\x52\x02\x44\x60\x44\x60'\
b'\x60\x44\x02\x52\x52\x52\x3e\x52\x66\x02\x44\x60\x44\x44\x60'\
b'\x60\x02\x44\x60\x44\x52\x60\x52\x02\x46\x5e\x46\x59\x5e\x4b'\
b'\x02\x4b\x59\x4b\x5e\x59\x46\x02\x52\x52\x52\x44\x52\x60\x02'\
b'\x4b\x59\x4b\x46\x59\x5e\x02\x46\x5e\x46\x4b\x5e\x59\x02\x4b'\
b'\x59\x4b\x52\x59\x52\x02\x4d\x57\x4d\x57\x57\x4d\x02\x52\x52'\
b'\x52\x4b\x52\x59\x02\x4d\x57\x4d\x4d\x57\x57\x07\x47\x52\x52'\
b'\x47\x50\x47\x4d\x48\x4a\x4a\x48\x4d\x47\x50\x47\x52\x07\x47'\
b'\x52\x47\x52\x47\x54\x48\x57\x4a\x5a\x4d\x5c\x50\x5d\x52\x5d'\
b'\x07\x52\x5d\x52\x5d\x54\x5d\x57\x5c\x5a\x5a\x5c\x57\x5d\x54'\
b'\x5d\x52\x07\x52\x5d\x5d\x52\x5d\x50\x5c\x4d\x5a\x4a\x57\x48'\
b'\x54\x47\x52\x47\x08\x44\x60\x44\x4f\x47\x51\x4b\x53\x50\x54'\
b'\x54\x54\x59\x53\x5d\x51\x60\x4f\x08\x50\x55\x55\x44\x53\x47'\
b'\x51\x4b\x50\x50\x50\x54\x51\x59\x53\x5d\x55\x60\x08\x4f\x54'\
b'\x4f\x44\x51\x47\x53\x4b\x54\x50\x54\x54\x53\x59\x51\x5d\x4f'\
b'\x60\x08\x44\x60\x44\x55\x47\x53\x4b\x51\x50\x50\x54\x50\x59'\
b'\x51\x5d\x53\x60\x55\x04\x4b\x59\x52\x4a\x59\x4e\x4b\x56\x52'\
b'\x5a\x04\x4a\x5a\x4a\x52\x4e\x4b\x56\x59\x5a\x52\x04\x4b\x59'\
b'\x4b\x56\x4b\x4e\x59\x56\x59\x4e\x04\x4a\x5a\x4c\x58\x4a\x50'\
b'\x5a\x54\x58\x4c\x16\x4a\x5a\x4a\x5d\x4c\x5d\x4f\x5c\x51\x5b'\
b'\x54\x58\x55\x56\x56\x53\x56\x4f\x55\x4c\x54\x4a\x53\x49\x51'\
b'\x49\x50\x4a\x4f\x4c\x4e\x4f\x4e\x53\x4f\x56\x50\x58\x53\x5b'\
b'\x55\x5c\x58\x5d\x5a\x5d\x16\x49\x5d\x5d\x5a\x5d\x58\x5c\x55'\
b'\x5b\x53\x58\x50\x56\x4f\x53\x4e\x4f\x4e\x4c\x4f\x4a\x50\x49'\
b'\x51\x49\x53\x4a\x54\x4c\x55\x4f\x56\x53\x56\x56\x55\x58\x54'\
b'\x5b\x51\x5c\x4f\x5d\x4c\x5d\x4a\x16\x4a\x5a\x5a\x47\x58\x47'\
b'\x55\x48\x53\x49\x50\x4c\x4f\x4e\x4e\x51\x4e\x55\x4f\x58\x50'\
b'\x5a\x51\x5b\x53\x5b\x54\x5a\x55\x58\x56\x55\x56\x51\x55\x4e'\
b'\x54\x4c\x51\x49\x4f\x48\x4c\x47\x4a\x47\x16\x47\x5b\x47\x4a'\
b'\x47\x4c\x48\x4f\x49\x51\x4c\x54\x4e\x55\x51\x56\x55\x56\x58'\
b'\x55\x5a\x54\x5b\x53\x5b\x51\x5a\x50\x58\x4f\x55\x4e\x51\x4e'\
b'\x4e\x4f\x4c\x50\x49\x53\x48\x55\x47\x58\x47\x5a\x14\x45\x5b'\
b'\x45\x50\x46\x52\x48\x54\x4a\x55\x4d\x56\x51\x56\x55\x55\x58'\
b'\x53\x5a\x50\x5b\x4e\x5a\x4c\x57\x4c\x53\x4d\x51\x4e\x4e\x50'\
b'\x4c\x53\x4b\x56\x4b\x59\x4c\x5c\x4d\x5e\x12\x45\x59\x45\x54'\
b'\x48\x56\x4b\x57\x50\x57\x53\x56\x56\x54\x58\x51\x59\x4e\x59'\
b'\x4c\x58\x4b\x56\x4b\x53\x4c\x50\x4e\x4e\x51\x4d\x54\x4d\x59'\
b'\x4e\x5c\x50\x5f\x19\x4f\x55\x51\x4f\x4f\x51\x4f\x53\x51\x55'\
b'\x53\x55\x55\x53\x55\x51\x53\x4f\x51\x4f\x20\x52\x51\x50\x50'\
b'\x51\x50\x53\x51\x54\x53\x54\x54\x53\x54\x51\x53\x50\x51\x50'\
b'\x20\x52\x52\x51\x51\x52\x52\x53\x53\x52\x52\x51\x0a\x52\x57'\
b'\x52\x4d\x53\x4d\x55\x4e\x56\x4f\x57\x51\x57\x53\x56\x55\x55'\
b'\x56\x53\x57\x52\x57\x08\x44\x60\x44\x52\x4a\x52\x20\x52\x4f'\
b'\x52\x55\x52\x20\x52\x5a\x52\x60\x52\x04\x44\x60\x44\x55\x44'\
b'\x4f\x60\x4f\x60\x55\x05\x4a\x5a\x52\x44\x4a\x52\x20\x52\x52'\
b'\x44\x5a\x52\x08\x44\x60\x44\x52\x60\x52\x20\x52\x4a\x59\x5a'\
b'\x59\x20\x52\x50\x60\x54\x60\x08\x44\x60\x44\x52\x60\x52\x20'\
b'\x52\x44\x52\x52\x62\x20\x52\x60\x52\x52\x62\x11\x4b\x59\x51'\
b'\x4b\x4e\x4c\x4c\x4e\x4b\x51\x4b\x53\x4c\x56\x4e\x58\x51\x59'\
b'\x53\x59\x56\x58\x58\x56\x59\x53\x59\x51\x58\x4e\x56\x4c\x53'\
b'\x4b\x51\x4b\x05\x4c\x58\x4c\x4c\x4c\x58\x58\x58\x58\x4c\x4c'\
b'\x4c\x04\x4b\x59\x52\x4a\x4b\x56\x59\x56\x52\x4a\x05\x4c\x58'\
b'\x52\x48\x4c\x52\x52\x5c\x58\x52\x52\x48\x0b\x4a\x5a\x52\x49'\
b'\x50\x4f\x4a\x4f\x4f\x53\x4d\x59\x52\x55\x57\x59\x55\x53\x5a'\
b'\x4f\x54\x4f\x52\x49\x05\x4b\x59\x52\x4b\x52\x59\x20\x52\x4b'\
b'\x52\x59\x52\x05\x4d\x57\x4d\x4d\x57\x57\x20\x52\x57\x4d\x4d'\
b'\x57\x08\x4d\x57\x52\x4c\x52\x58\x20\x52\x4d\x4f\x57\x55\x20'\
b'\x52\x57\x4f\x4d\x55\x22\x4e\x56\x51\x4e\x4f\x4f\x4e\x51\x4e'\
b'\x53\x4f\x55\x51\x56\x53\x56\x55\x55\x56\x53\x56\x51\x55\x4f'\
b'\x53\x4e\x51\x4e\x20\x52\x4f\x51\x4f\x53\x20\x52\x50\x50\x50'\
b'\x54\x20\x52\x51\x4f\x51\x55\x20\x52\x52\x4f\x52\x55\x20\x52'\
b'\x53\x4f\x53\x55\x20\x52\x54\x50\x54\x54\x20\x52\x55\x51\x55'\
b'\x53\x1a\x4e\x56\x4e\x4e\x4e\x56\x56\x56\x56\x4e\x4e\x4e\x20'\
b'\x52\x4f\x4f\x4f\x55\x20\x52\x50\x4f\x50\x55\x20\x52\x51\x4f'\
b'\x51\x55\x20\x52\x52\x4f\x52\x55\x20\x52\x53\x4f\x53\x55\x20'\
b'\x52\x54\x4f\x54\x55\x20\x52\x55\x4f\x55\x55\x10\x4d\x57\x52'\
b'\x4c\x4d\x55\x57\x55\x52\x4c\x20\x52\x52\x4f\x4f\x54\x20\x52'\
b'\x52\x4f\x55\x54\x20\x52\x52\x52\x51\x54\x20\x52\x52\x52\x53'\
b'\x54\x10\x4c\x55\x4c\x52\x55\x57\x55\x4d\x4c\x52\x20\x52\x4f'\
b'\x52\x54\x55\x20\x52\x4f\x52\x54\x4f\x20\x52\x52\x52\x54\x53'\
b'\x20\x52\x52\x52\x54\x51\x10\x4d\x57\x52\x58\x57\x4f\x4d\x4f'\
b'\x52\x58\x20\x52\x52\x55\x55\x50\x20\x52\x52\x55\x4f\x50\x20'\
b'\x52\x52\x52\x53\x50\x20\x52\x52\x52\x51\x50\x10\x4f\x58\x58'\
b'\x52\x4f\x4d\x4f\x57\x58\x52\x20\x52\x55\x52\x50\x4f\x20\x52'\
b'\x55\x52\x50\x55\x20\x52\x52\x52\x50\x51\x20\x52\x52\x52\x50'\
b'\x53\x0a\x52\x59\x52\x4b\x52\x59\x20\x52\x52\x4b\x59\x4e\x52'\
b'\x51\x20\x52\x53\x4d\x56\x4e\x53\x4f\x14\x49\x5b\x52\x47\x52'\
b'\x56\x20\x52\x4d\x4a\x57\x50\x20\x52\x57\x4a\x4d\x50\x20\x52'\
b'\x49\x56\x4c\x5c\x20\x52\x5b\x56\x58\x5c\x20\x52\x49\x56\x5b'\
b'\x56\x20\x52\x4c\x5c\x58\x5c\x0c\x4d\x57\x52\x4c\x52\x58\x20'\
b'\x52\x4f\x4f\x55\x4f\x20\x52\x4d\x55\x4f\x57\x51\x58\x53\x58'\
b'\x55\x57\x57\x55\x0a\x4c\x58\x52\x4c\x52\x58\x20\x52\x4c\x51'\
b'\x4d\x4f\x57\x4f\x58\x51\x20\x52\x50\x57\x54\x57\x0d\x4b\x59'\
b'\x4d\x4e\x57\x58\x20\x52\x57\x4e\x4d\x58\x20\x52\x4f\x4c\x4c'\
b'\x4f\x4b\x51\x20\x52\x55\x4c\x58\x4f\x59\x51\x11\x49\x5b\x4e'\
b'\x49\x49\x5b\x20\x52\x56\x49\x5b\x5b\x20\x52\x4d\x4d\x5b\x5b'\
b'\x20\x52\x57\x4d\x49\x5b\x20\x52\x4e\x49\x56\x49\x20\x52\x4d'\
b'\x4d\x57\x4d\x02\x4b\x59\x4b\x46\x59\x5e\x0a\x47\x5b\x4d\x4a'\
b'\x53\x56\x20\x52\x4b\x50\x53\x4c\x20\x52\x47\x5c\x5b\x5c\x5b'\
b'\x52\x47\x5c\x0d\x4c\x58\x50\x4c\x50\x50\x4c\x50\x4c\x54\x50'\
b'\x54\x50\x58\x54\x58\x54\x54\x58\x54\x58\x50\x54\x50\x54\x4c'\
b'\x50\x4c\x1f\x4b\x59\x59\x50\x58\x4e\x56\x4c\x53\x4b\x51\x4b'\
b'\x4e\x4c\x4c\x4e\x4b\x51\x4b\x53\x4c\x56\x4e\x58\x51\x59\x53'\
b'\x59\x56\x58\x58\x56\x59\x54\x20\x52\x59\x50\x57\x4e\x55\x4d'\
b'\x53\x4d\x51\x4e\x50\x4f\x4f\x51\x4f\x53\x50\x55\x51\x56\x53'\
b'\x57\x55\x57\x57\x56\x59\x54\x09\x4b\x59\x52\x4a\x4b\x56\x59'\
b'\x56\x52\x4a\x20\x52\x52\x5a\x59\x4e\x4b\x4e\x52\x5a\x21\x47'\
b'\x5d\x50\x49\x50\x47\x51\x46\x53\x46\x54\x47\x54\x49\x20\x52'\
b'\x47\x5a\x48\x58\x4a\x56\x4b\x54\x4c\x50\x4c\x4b\x4d\x4a\x4f'\
b'\x49\x55\x49\x57\x4a\x58\x4b\x58\x50\x59\x54\x5a\x56\x5c\x58'\
b'\x5d\x5a\x20\x52\x47\x5a\x5d\x5a\x20\x52\x51\x5a\x50\x5b\x51'\
b'\x5c\x53\x5c\x54\x5b\x53\x5a\x3f\x4a\x5a\x52\x4d\x52\x53\x20'\
b'\x52\x52\x53\x51\x5c\x20\x52\x52\x53\x53\x5c\x20\x52\x51\x5c'\
b'\x53\x5c\x20\x52\x52\x4d\x51\x4a\x50\x48\x4e\x47\x20\x52\x51'\
b'\x4a\x4e\x47\x20\x52\x52\x4d\x53\x4a\x54\x48\x56\x47\x20\x52'\
b'\x53\x4a\x56\x47\x20\x52\x52\x4d\x4e\x4b\x4c\x4b\x4a\x4d\x20'\
b'\x52\x50\x4c\x4c\x4c\x4a\x4d\x20\x52\x52\x4d\x56\x4b\x58\x4b'\
b'\x5a\x4d\x20\x52\x54\x4c\x58\x4c\x5a\x4d\x20\x52\x52\x4d\x50'\
b'\x4e\x4f\x4f\x4f\x52\x20\x52\x52\x4d\x50\x4f\x4f\x52\x20\x52'\
b'\x52\x4d\x54\x4e\x55\x4f\x55\x52\x20\x52\x52\x4d\x54\x4f\x55'\
b'\x52\x5d\x4a\x5a\x52\x49\x52\x4b\x20\x52\x52\x4e\x52\x50\x20'\
b'\x52\x52\x53\x52\x55\x20\x52\x52\x59\x51\x5c\x20\x52\x52\x59'\
b'\x53\x5c\x20\x52\x51\x5c\x53\x5c\x20\x52\x52\x47\x51\x49\x50'\
b'\x4a\x20\x52\x52\x47\x53\x49\x54\x4a\x20\x52\x50\x4a\x52\x49'\
b'\x54\x4a\x20\x52\x52\x4b\x50\x4e\x4e\x4f\x4d\x4e\x20\x52\x52'\
b'\x4b\x54\x4e\x56\x4f\x57\x4e\x20\x52\x4e\x4f\x50\x4f\x52\x4e'\
b'\x54\x4f\x56\x4f\x20\x52\x52\x50\x50\x53\x4e\x54\x4c\x54\x4b'\
b'\x52\x4b\x53\x4c\x54\x20\x52\x52\x50\x54\x53\x56\x54\x58\x54'\
b'\x59\x52\x59\x53\x58\x54\x20\x52\x4e\x54\x50\x54\x52\x53\x54'\
b'\x54\x56\x54\x20\x52\x52\x55\x50\x58\x4f\x59\x4d\x5a\x4c\x5a'\
b'\x4b\x59\x4a\x57\x4a\x59\x4c\x5a\x20\x52\x52\x55\x54\x58\x55'\
b'\x59\x57\x5a\x58\x5a\x59\x59\x5a\x57\x5a\x59\x58\x5a\x20\x52'\
b'\x4d\x5a\x4f\x5a\x52\x59\x55\x5a\x57\x5a\x27\x4a\x5a\x52\x59'\
b'\x51\x5c\x20\x52\x52\x59\x53\x5c\x20\x52\x51\x5c\x53\x5c\x20'\
b'\x52\x52\x59\x55\x5a\x58\x5a\x5a\x58\x5a\x55\x59\x54\x57\x54'\
b'\x59\x52\x5a\x4f\x59\x4d\x57\x4c\x55\x4d\x56\x4a\x55\x48\x53'\
b'\x47\x51\x47\x4f\x48\x4e\x4a\x4f\x4d\x4d\x4c\x4b\x4d\x4a\x4f'\
b'\x4b\x52\x4d\x54\x4b\x54\x4a\x55\x4a\x58\x4c\x5a\x4f\x5a\x52'\
b'\x59\x1f\x4a\x5a\x52\x59\x51\x5c\x20\x52\x52\x59\x53\x5c\x20'\
b'\x52\x51\x5c\x53\x5c\x20\x52\x52\x59\x56\x58\x56\x56\x58\x55'\
b'\x58\x52\x5a\x51\x5a\x4c\x59\x49\x58\x48\x56\x48\x54\x47\x50'\
b'\x47\x4e\x48\x4c\x48\x4b\x49\x4a\x4c\x4a\x51\x4c\x52\x4c\x55'\
b'\x4e\x56\x4e\x58\x52\x59\x0e\x49\x5b\x49\x50\x4b\x52\x20\x52'\
b'\x4c\x4b\x4e\x50\x20\x52\x52\x47\x52\x4f\x20\x52\x58\x4b\x56'\
b'\x50\x20\x52\x5b\x50\x59\x52\x1b\x47\x5d\x49\x49\x4a\x4b\x4b'\
b'\x4f\x4b\x55\x4a\x59\x49\x5b\x20\x52\x5b\x49\x5a\x4b\x59\x4f'\
b'\x59\x55\x5a\x59\x5b\x5b\x20\x52\x49\x49\x4b\x4a\x4f\x4b\x55'\
b'\x4b\x59\x4a\x5b\x49\x20\x52\x49\x5b\x4b\x5a\x4f\x59\x55\x59'\
b'\x59\x5a\x5b\x5b\x36\x46\x5e\x52\x52\x52\x5b\x51\x5c\x20\x52'\
b'\x52\x56\x51\x5c\x20\x52\x52\x49\x51\x48\x4f\x48\x4e\x49\x4e'\
b'\x4b\x4f\x4e\x52\x52\x20\x52\x52\x49\x53\x48\x55\x48\x56\x49'\
b'\x56\x4b\x55\x4e\x52\x52\x20\x52\x52\x52\x4e\x4f\x4c\x4e\x4a'\
b'\x4e\x49\x4f\x49\x51\x4a\x52\x20\x52\x52\x52\x56\x4f\x58\x4e'\
b'\x5a\x4e\x5b\x4f\x5b\x51\x5a\x52\x20\x52\x52\x52\x4e\x55\x4c'\
b'\x56\x4a\x56\x49\x55\x49\x53\x4a\x52\x20\x52\x52\x52\x56\x55'\
b'\x58\x56\x5a\x56\x5b\x55\x5b\x53\x5a\x52\x2d\x4a\x5a\x55\x49'\
b'\x54\x4a\x55\x4b\x56\x4a\x56\x49\x55\x47\x53\x46\x51\x46\x4f'\
b'\x47\x4e\x49\x4e\x4b\x4f\x4d\x51\x4f\x56\x52\x20\x52\x4f\x4d'\
b'\x54\x50\x56\x52\x57\x54\x57\x56\x56\x58\x54\x5a\x20\x52\x50'\
b'\x4e\x4e\x50\x4d\x52\x4d\x54\x4e\x56\x50\x58\x55\x5b\x20\x52'\
b'\x4e\x56\x53\x59\x55\x5b\x56\x5d\x56\x5f\x55\x61\x53\x62\x51'\
b'\x62\x4f\x61\x4e\x5f\x4e\x5e\x4f\x5d\x50\x5e\x4f\x5f\x1d\x4a'\
b'\x5a\x52\x46\x51\x48\x52\x4a\x53\x48\x52\x46\x20\x52\x52\x46'\
b'\x52\x62\x20\x52\x52\x51\x51\x54\x52\x62\x53\x54\x52\x51\x20'\
b'\x52\x4c\x4d\x4e\x4e\x50\x4d\x4e\x4c\x4c\x4d\x20\x52\x4c\x4d'\
b'\x58\x4d\x20\x52\x54\x4d\x56\x4e\x58\x4d\x56\x4c\x54\x4d\x37'\
b'\x4a\x5a\x52\x46\x51\x48\x52\x4a\x53\x48\x52\x46\x20\x52\x52'\
b'\x46\x52\x54\x20\x52\x52\x50\x51\x52\x53\x56\x52\x58\x51\x56'\
b'\x53\x52\x52\x50\x20\x52\x52\x54\x52\x62\x20\x52\x52\x5e\x51'\
b'\x60\x52\x62\x53\x60\x52\x5e\x20\x52\x4c\x4d\x4e\x4e\x50\x4d'\
b'\x4e\x4c\x4c\x4d\x20\x52\x4c\x4d\x58\x4d\x20\x52\x54\x4d\x56'\
b'\x4e\x58\x4d\x56\x4c\x54\x4d\x20\x52\x4c\x5b\x4e\x5c\x50\x5b'\
b'\x4e\x5a\x4c\x5b\x20\x52\x4c\x5b\x58\x5b\x20\x52\x54\x5b\x56'\
b'\x5c\x58\x5b\x56\x5a\x54\x5b\x11\x45\x5f\x52\x49\x51\x4a\x52'\
b'\x4b\x53\x4a\x52\x49\x20\x52\x49\x59\x48\x5a\x49\x5b\x4a\x5a'\
b'\x49\x59\x20\x52\x5b\x59\x5a\x5a\x5b\x5b\x5c\x5a\x5b\x59\x20'\
b'\x46\x5e\x52\x48\x4e\x4c\x4b\x50\x4a\x53\x4a\x55\x4b\x57\x4d'\
b'\x58\x4f\x58\x51\x57\x52\x55\x20\x52\x52\x48\x56\x4c\x59\x50'\
b'\x5a\x53\x5a\x55\x59\x57\x57\x58\x55\x58\x53\x57\x52\x55\x20'\
b'\x52\x52\x55\x51\x59\x50\x5c\x20\x52\x52\x55\x53\x59\x54\x5c'\
b'\x20\x52\x50\x5c\x54\x5c\x19\x46\x5e\x52\x4e\x51\x4b\x50\x49'\
b'\x4e\x48\x4d\x48\x4b\x49\x4a\x4b\x4a\x4f\x4b\x52\x4c\x54\x4e'\
b'\x57\x52\x5c\x20\x52\x52\x4e\x53\x4b\x54\x49\x56\x48\x57\x48'\
b'\x59\x49\x5a\x4b\x5a\x4f\x59\x52\x58\x54\x56\x57\x52\x5c\x13'\
b'\x46\x5e\x52\x47\x50\x4a\x4c\x4f\x49\x52\x20\x52\x52\x47\x54'\
b'\x4a\x58\x4f\x5b\x52\x20\x52\x49\x52\x4c\x55\x50\x5a\x52\x5d'\
b'\x20\x52\x5b\x52\x58\x55\x54\x5a\x52\x5d\x2f\x46\x5e\x52\x54'\
b'\x54\x57\x56\x58\x58\x58\x5a\x57\x5b\x55\x5b\x53\x5a\x51\x58'\
b'\x50\x56\x50\x53\x51\x20\x52\x53\x51\x55\x4f\x56\x4d\x56\x4b'\
b'\x55\x49\x53\x48\x51\x48\x4f\x49\x4e\x4b\x4e\x4d\x4f\x4f\x51'\
b'\x51\x20\x52\x51\x51\x4e\x50\x4c\x50\x4a\x51\x49\x53\x49\x55'\
b'\x4a\x57\x4c\x58\x4e\x58\x50\x57\x52\x54\x20\x52\x52\x54\x51'\
b'\x59\x50\x5c\x20\x52\x52\x54\x53\x59\x54\x5c\x20\x52\x50\x5c'\
b'\x54\x5c\x2f\x49\x5b\x56\x2b\x53\x2d\x51\x2f\x50\x31\x4f\x34'\
b'\x4f\x38\x50\x3c\x54\x44\x55\x47\x55\x4a\x54\x4d\x52\x50\x20'\
b'\x52\x53\x2d\x51\x30\x50\x34\x50\x38\x51\x3b\x55\x43\x56\x47'\
b'\x56\x4a\x55\x4d\x52\x50\x4e\x52\x52\x54\x55\x57\x56\x5a\x56'\
b'\x5d\x55\x61\x51\x69\x50\x6c\x50\x70\x51\x74\x53\x77\x20\x52'\
b'\x52\x54\x54\x57\x55\x5a\x55\x5d\x54\x60\x50\x68\x4f\x6c\x4f'\
b'\x70\x50\x73\x51\x75\x53\x77\x56\x79\x2f\x49\x5b\x4e\x2b\x51'\
b'\x2d\x53\x2f\x54\x31\x55\x34\x55\x38\x54\x3c\x50\x44\x4f\x47'\
b'\x4f\x4a\x50\x4d\x52\x50\x20\x52\x51\x2d\x53\x30\x54\x34\x54'\
b'\x38\x53\x3b\x4f\x43\x4e\x47\x4e\x4a\x4f\x4d\x52\x50\x56\x52'\
b'\x52\x54\x4f\x57\x4e\x5a\x4e\x5d\x4f\x61\x53\x69\x54\x6c\x54'\
b'\x70\x53\x74\x51\x77\x20\x52\x52\x54\x50\x57\x4f\x5a\x4f\x5d'\
b'\x50\x60\x54\x68\x55\x6c\x55\x70\x54\x73\x53\x75\x51\x77\x4e'\
b'\x79\x1f\x49\x5b\x56\x2e\x53\x31\x51\x34\x4f\x38\x4e\x3d\x4e'\
b'\x43\x4f\x49\x50\x4d\x53\x58\x54\x5c\x55\x62\x55\x67\x54\x6c'\
b'\x53\x6f\x51\x73\x20\x52\x53\x31\x51\x35\x50\x38\x4f\x3d\x4f'\
b'\x42\x50\x48\x51\x4c\x54\x57\x55\x5b\x56\x61\x56\x67\x55\x6c'\
b'\x53\x70\x51\x73\x4e\x76\x1f\x49\x5b\x4e\x2e\x51\x31\x53\x34'\
b'\x55\x38\x56\x3d\x56\x43\x55\x49\x54\x4d\x51\x58\x50\x5c\x4f'\
b'\x62\x4f\x67\x50\x6c\x51\x6f\x53\x73\x20\x52\x51\x31\x53\x35'\
b'\x54\x38\x55\x3d\x55\x42\x54\x48\x53\x4c\x50\x57\x4f\x5b\x4e'\
b'\x61\x4e\x67\x4f\x6c\x51\x70\x53\x73\x56\x76\x0d\x37\x5a\x3a'\
b'\x52\x41\x52\x52\x6f\x20\x52\x40\x52\x51\x6f\x20\x52\x3f\x52'\
b'\x52\x72\x20\x52\x5a\x22\x56\x4a\x52\x72\x1a\x49\x5b\x54\x4d'\
b'\x56\x4e\x58\x50\x58\x4f\x57\x4e\x54\x4d\x51\x4d\x4e\x4e\x4d'\
b'\x4f\x4c\x51\x4c\x53\x4d\x55\x4f\x57\x53\x5a\x20\x52\x51\x4d'\
b'\x4f\x4e\x4e\x4f\x4d\x51\x4d\x53\x4e\x55\x53\x5a\x54\x5c\x54'\
b'\x5e\x53\x5f\x51\x5f\x2c\x47\x5d\x4c\x4d\x4b\x4e\x4a\x50\x4a'\
b'\x52\x4b\x55\x4f\x59\x50\x5b\x20\x52\x4a\x52\x4b\x54\x4f\x58'\
b'\x50\x5b\x50\x5d\x4f\x60\x4d\x62\x4c\x62\x4b\x61\x4a\x5f\x4a'\
b'\x5c\x4b\x58\x4d\x54\x4f\x51\x52\x4e\x54\x4d\x56\x4d\x59\x4e'\
b'\x5a\x50\x5a\x54\x59\x58\x57\x5a\x55\x5b\x54\x5b\x53\x5a\x53'\
b'\x58\x54\x57\x55\x58\x54\x59\x20\x52\x56\x4d\x58\x4e\x59\x50'\
b'\x59\x54\x58\x58\x57\x5a\x44\x45\x5f\x59\x47\x58\x48\x59\x49'\
b'\x5a\x48\x59\x47\x57\x46\x54\x46\x51\x47\x4f\x49\x4e\x4b\x4d'\
b'\x4e\x4c\x52\x4a\x5b\x49\x5f\x48\x61\x20\x52\x54\x46\x52\x47'\
b'\x50\x49\x4f\x4b\x4e\x4e\x4c\x57\x4b\x5b\x4a\x5e\x49\x60\x48'\
b'\x61\x46\x62\x44\x62\x43\x61\x43\x60\x44\x5f\x45\x60\x44\x61'\
b'\x20\x52\x5f\x47\x5e\x48\x5f\x49\x60\x48\x60\x47\x5f\x46\x5d'\
b'\x46\x5b\x47\x5a\x48\x59\x4a\x58\x4d\x55\x5b\x54\x5f\x53\x61'\
b'\x20\x52\x5d\x46\x5b\x48\x5a\x4a\x59\x4e\x57\x57\x56\x5b\x55'\
b'\x5e\x54\x60\x53\x61\x51\x62\x4f\x62\x4e\x61\x4e\x60\x4f\x5f'\
b'\x50\x60\x4f\x61\x20\x52\x49\x4d\x5e\x4d\x33\x46\x5e\x5b\x47'\
b'\x5a\x48\x5b\x49\x5c\x48\x5b\x47\x58\x46\x55\x46\x52\x47\x50'\
b'\x49\x4f\x4b\x4e\x4e\x4d\x52\x4b\x5b\x4a\x5f\x49\x61\x20\x52'\
b'\x55\x46\x53\x47\x51\x49\x50\x4b\x4f\x4e\x4d\x57\x4c\x5b\x4b'\
b'\x5e\x4a\x60\x49\x61\x47\x62\x45\x62\x44\x61\x44\x60\x45\x5f'\
b'\x46\x60\x45\x61\x20\x52\x59\x4d\x57\x54\x56\x58\x56\x5a\x57'\
b'\x5b\x5a\x5b\x5c\x59\x5d\x57\x20\x52\x5a\x4d\x58\x54\x57\x58'\
b'\x57\x5a\x58\x5b\x20\x52\x4a\x4d\x5a\x4d\x35\x46\x5e\x59\x47'\
b'\x58\x48\x59\x49\x5a\x48\x5a\x47\x58\x46\x20\x52\x5c\x46\x55'\
b'\x46\x52\x47\x50\x49\x4f\x4b\x4e\x4e\x4d\x52\x4b\x5b\x4a\x5f'\
b'\x49\x61\x20\x52\x55\x46\x53\x47\x51\x49\x50\x4b\x4f\x4e\x4d'\
b'\x57\x4c\x5b\x4b\x5e\x4a\x60\x49\x61\x47\x62\x45\x62\x44\x61'\
b'\x44\x60\x45\x5f\x46\x60\x45\x61\x20\x52\x5b\x46\x57\x54\x56'\
b'\x58\x56\x5a\x57\x5b\x5a\x5b\x5c\x59\x5d\x57\x20\x52\x5c\x46'\
b'\x58\x54\x57\x58\x57\x5a\x58\x5b\x20\x52\x4a\x4d\x59\x4d\x55'\
b'\x40\x63\x54\x47\x53\x48\x54\x49\x55\x48\x54\x47\x52\x46\x4f'\
b'\x46\x4c\x47\x4a\x49\x49\x4b\x48\x4e\x47\x52\x45\x5b\x44\x5f'\
b'\x43\x61\x20\x52\x4f\x46\x4d\x47\x4b\x49\x4a\x4b\x49\x4e\x47'\
b'\x57\x46\x5b\x45\x5e\x44\x60\x43\x61\x41\x62\x3f\x62\x3e\x61'\
b'\x3e\x60\x3f\x5f\x40\x60\x3f\x61\x20\x52\x60\x47\x5f\x48\x60'\
b'\x49\x61\x48\x60\x47\x5d\x46\x5a\x46\x57\x47\x55\x49\x54\x4b'\
b'\x53\x4e\x52\x52\x50\x5b\x4f\x5f\x4e\x61\x20\x52\x5a\x46\x58'\
b'\x47\x56\x49\x55\x4b\x54\x4e\x52\x57\x51\x5b\x50\x5e\x4f\x60'\
b'\x4e\x61\x4c\x62\x4a\x62\x49\x61\x49\x60\x4a\x5f\x4b\x60\x4a'\
b'\x61\x20\x52\x5e\x4d\x5c\x54\x5b\x58\x5b\x5a\x5c\x5b\x5f\x5b'\
b'\x61\x59\x62\x57\x20\x52\x5f\x4d\x5d\x54\x5c\x58\x5c\x5a\x5d'\
b'\x5b\x20\x52\x44\x4d\x5f\x4d\x57\x40\x63\x54\x47\x53\x48\x54'\
b'\x49\x55\x48\x54\x47\x52\x46\x4f\x46\x4c\x47\x4a\x49\x49\x4b'\
b'\x48\x4e\x47\x52\x45\x5b\x44\x5f\x43\x61\x20\x52\x4f\x46\x4d'\
b'\x47\x4b\x49\x4a\x4b\x49\x4e\x47\x57\x46\x5b\x45\x5e\x44\x60'\
b'\x43\x61\x41\x62\x3f\x62\x3e\x61\x3e\x60\x3f\x5f\x40\x60\x3f'\
b'\x61\x20\x52\x5e\x47\x5d\x48\x5e\x49\x5f\x48\x5f\x47\x5d\x46'\
b'\x20\x52\x61\x46\x5a\x46\x57\x47\x55\x49\x54\x4b\x53\x4e\x52'\
b'\x52\x50\x5b\x4f\x5f\x4e\x61\x20\x52\x5a\x46\x58\x47\x56\x49'\
b'\x55\x4b\x54\x4e\x52\x57\x51\x5b\x50\x5e\x4f\x60\x4e\x61\x4c'\
b'\x62\x4a\x62\x49\x61\x49\x60\x4a\x5f\x4b\x60\x4a\x61\x20\x52'\
b'\x60\x46\x5c\x54\x5b\x58\x5b\x5a\x5c\x5b\x5f\x5b\x61\x59\x62'\
b'\x57\x20\x52\x61\x46\x5d\x54\x5c\x58\x5c\x5a\x5d\x5b\x20\x52'\
b'\x44\x4d\x5e\x4d\x13\x4c\x59\x4d\x51\x4e\x4f\x50\x4d\x53\x4d'\
b'\x54\x4e\x54\x51\x52\x57\x52\x5a\x53\x5b\x20\x52\x52\x4d\x53'\
b'\x4e\x53\x51\x51\x57\x51\x5a\x52\x5b\x55\x5b\x57\x59\x58\x57'\
b'\x15\x4c\x58\x52\x4c\x4e\x57\x58\x50\x4c\x50\x56\x57\x52\x4c'\
b'\x20\x52\x52\x52\x52\x4c\x20\x52\x52\x52\x4c\x50\x20\x52\x52'\
b'\x52\x4e\x57\x20\x52\x52\x52\x56\x57\x20\x52\x52\x52\x58\x50'\
b'\x17\x46\x5e\x49\x55\x49\x53\x4a\x50\x4c\x4f\x4e\x4f\x50\x50'\
b'\x54\x53\x56\x54\x58\x54\x5a\x53\x5b\x51\x20\x52\x49\x53\x4a'\
b'\x51\x4c\x50\x4e\x50\x50\x51\x54\x54\x56\x55\x58\x55\x5a\x54'\
b'\x5b\x51\x5b\x4f'
_index =\
b'\x00\x00\x03\x00\x0a\x00\x11\x00\x18\x00\x1f\x00\x26\x00\x2d'\
b'\x00\x34\x00\x3b\x00\x42\x00\x49\x00\x50\x00\x57\x00\x5e\x00'\
b'\x65\x00\x76\x00\x87\x00\x98\x00\xa9\x00\xbc\x00\xcf\x00\xe2'\
b'\x00\xf5\x00\x00\x01\x0b\x01\x16\x01\x21\x01\x50\x01\x7f\x01'\
b'\xae\x01\xdd\x01\x08\x02\x2f\x02\x64\x02\x7b\x02\x8e\x02\x99'\
b'\x02\xa6\x02\xb9\x02\xcc\x02\xf1\x02\xfe\x02\x09\x03\x16\x03'\
b'\x2f\x03\x3c\x03\x49\x03\x5c\x03\xa3\x03\xda\x03\xfd\x03\x20'\
b'\x04\x43\x04\x66\x04\x7d\x04\xa8\x04\xc3\x04\xda\x04\xf7\x04'\
b'\x1c\x05\x23\x05\x3a\x05\x57\x05\x98\x05\xad\x05\xf2\x05\x73'\
b'\x06\x30\x07\x81\x07\xc2\x07\xe1\x07\x1a\x08\x89\x08\xe6\x08'\
b'\x23\x09\x94\x09\xb9\x09\xfc\x09\x31\x0a\x5a\x0a\xbb\x0a\x1c'\
b'\x0b\x7d\x0b\xbe\x0b\xff\x0b\x1c\x0c\x53\x0c\xae\x0c\x39\x0d'\
b'\xa2\x0d\x0f\x0e\xbc\x0e\x6d\x0f\x96\x0f\xc3\x0f'
INDEX = memoryview(_index)
FONT = memoryview(_font)
| width = 87
height = 87
first = 32
last = 127
_font = b'\x00JZ\x02D`DR`R\x02D`D``D\x02RRR>Rf\x02D`DD``\x02D`DR`R\x02F^FY^K\x02KYK^YF\x02RRRDR`\x02KYKFY^\x02F^FK^Y\x02KYKRYR\x02MWMWWM\x02RRRKRY\x02MWMMWW\x07GRRGPGMHJJHMGPGR\x07GRGRGTHWJZM\\P]R]\x07R]R]T]W\\ZZ\\W]T]R\x07R]]R]P\\MZJWHTGRG\x08D`DOGQKSPTTTYS]Q`O\x08PUUDSGQKPPPTQYS]U`\x08OTODQGSKTPTTSYQ]O`\x08D`DUGSKQPPTPYQ]S`U\x04KYRJYNKVRZ\x04JZJRNKVYZR\x04KYKVKNYVYN\x04JZLXJPZTXL\x16JZJ]L]O\\Q[TXUVVSVOULTJSIQIPJOLNONSOVPXS[U\\X]Z]\x16I]]Z]X\\U[SXPVOSNONLOJPIQISJTLUOVSVVUXT[Q\\O]L]J\x16JZZGXGUHSIPLONNQNUOXPZQ[S[TZUXVUVQUNTLQIOHLGJG\x16G[GJGLHOIQLTNUQVUVXUZT[S[QZPXOUNQNNOLPISHUGXGZ\x14E[EPFRHTJUMVQVUUXSZP[NZLWLSMQNNPLSKVKYL\\M^\x12EYETHVKWPWSVVTXQYNYLXKVKSLPNNQMTMYN\\P_\x19OUQOOQOSQUSUUSUQSOQO RQPPQPSQTSTTSTQSPQP RRQQRRSSRRQ\nRWRMSMUNVOWQWSVUUVSWRW\x08D`DRJR RORUR RZR`R\x04D`DUDO`O`U\x05JZRDJR RRDZR\x08D`DR`R RJYZY RP`T`\x08D`DR`R RDRRb R`RRb\x11KYQKNLLNKQKSLVNXQYSYVXXVYSYQXNVLSKQK\x05LXLLLXXXXLLL\x04KYRJKVYVRJ\x05LXRHLRR\\XRRH\x0bJZRIPOJOOSMYRUWYUSZOTORI\x05KYRKRY RKRYR\x05MWMMWW RWMMW\x08MWRLRX RMOWU RWOMU"NVQNOONQNSOUQVSVUUVSVQUOSNQN ROQOS RPPPT RQOQU RRORU RSOSU RTPTT RUQUS\x1aNVNNNVVVVNNN ROOOU RPOPU RQOQU RRORU RSOSU RTOTU RUOUU\x10MWRLMUWURL RROOT RROUT RRRQT RRRST\x10LULRUWUMLR RORTU RORTO RRRTS RRRTQ\x10MWRXWOMORX RRUUP RRUOP RRRSP RRRQP\x10OXXROMOWXR RURPO RURPU RRRPQ RRRPS\nRYRKRY RRKYNRQ RSMVNSO\x14I[RGRV RMJWP RWJMP RIVL\\ R[VX\\ RIV[V RL\\X\\\x0cMWRLRX ROOUO RMUOWQXSXUWWU\nLXRLRX RLQMOWOXQ RPWTW\rKYMNWX RWNMX ROLLOKQ RULXOYQ\x11I[NII[ RVI[[ RMM[[ RWMI[ RNIVI RMMWM\x02KYKFY^\nG[MJSV RKPSL RG\\[\\[RG\\\rLXPLPPLPLTPTPXTXTTXTXPTPTLPL\x1fKYYPXNVLSKQKNLLNKQKSLVNXQYSYVXXVYT RYPWNUMSMQNPOOQOSPUQVSWUWWVYT\tKYRJKVYVRJ RRZYNKNRZ!G]PIPGQFSFTGTI RGZHXJVKTLPLKMJOIUIWJXKXPYTZV\\X]Z RGZ]Z RQZP[Q\\S\\T[SZ?JZRMRS RRSQ\\ RRSS\\ RQ\\S\\ RRMQJPHNG RQJNG RRMSJTHVG RSJVG RRMNKLKJM RPLLLJM RRMVKXKZM RTLXLZM RRMPNOOOR RRMPOOR RRMTNUOUR RRMTOUR]JZRIRK RRNRP RRSRU RRYQ\\ RRYS\\ RQ\\S\\ RRGQIPJ RRGSITJ RPJRITJ RRKPNNOMN RRKTNVOWN RNOPORNTOVO RRPPSNTLTKRKSLT RRPTSVTXTYRYSXT RNTPTRSTTVT RRUPXOYMZLZKYJWJYLZ RRUTXUYWZXZYYZWZYXZ RMZOZRYUZWZ\'JZRYQ\\ RRYS\\ RQ\\S\\ RRYUZXZZXZUYTWTYRZOYMWLUMVJUHSGQGOHNJOMMLKMJOKRMTKTJUJXLZOZRY\x1fJZRYQ\\ RRYS\\ RQ\\S\\ RRYVXVVXUXRZQZLYIXHVHTGPGNHLHKIJLJQLRLUNVNXRY\x0eI[IPKR RLKNP RRGRO RXKVP R[PYR\x1bG]IIJKKOKUJYI[ R[IZKYOYUZY[[ RIIKJOKUKYJ[I RI[KZOYUYYZ[[6F^RRR[Q\\ RRVQ\\ RRIQHOHNINKONRR RRISHUHVIVKUNRR RRRNOLNJNIOIQJR RRRVOXNZN[O[QZR RRRNULVJVIUISJR RRRVUXVZV[U[SZR-JZUITJUKVJVIUGSFQFOGNINKOMQOVR ROMTPVRWTWVVXTZ RPNNPMRMTNVPXU[ RNVSYU[V]V_UaSbQbOaN_N^O]P^O_\x1dJZRFQHRJSHRF RRFRb RRQQTRbSTRQ RLMNNPMNLLM RLMXM RTMVNXMVLTM7JZRFQHRJSHRF RRFRT RRPQRSVRXQVSRRP RRTRb RR^Q`RbS`R^ RLMNNPMNLLM RLMXM RTMVNXMVLTM RL[N\\P[NZL[ RL[X[ RT[V\\X[VZT[\x11E_RIQJRKSJRI RIYHZI[JZIY R[YZZ[[\\Z[Y F^RHNLKPJSJUKWMXOXQWRU RRHVLYPZSZUYWWXUXSWRU RRUQYP\\ RRUSYT\\ RP\\T\\\x19F^RNQKPINHMHKIJKJOKRLTNWR\\ RRNSKTIVHWHYIZKZOYRXTVWR\\\x13F^RGPJLOIR RRGTJXO[R RIRLUPZR] R[RXUTZR]/F^RTTWVXXXZW[U[SZQXPVPSQ RSQUOVMVKUISHQHOINKNMOOQQ RQQNPLPJQISIUJWLXNXPWRT RRTQYP\\ RRTSYT\\ RP\\T\\/I[V+S-Q/P1O4O8P<TDUGUJTMRP RS-Q0P4P8Q;UCVGVJUMRPNRRTUWVZV]UaQiPlPpQtSw RRTTWUZU]T`PhOlOpPsQuSwVy/I[N+Q-S/T1U4U8T<PDOGOJPMRP RQ-S0T4T8S;OCNGNJOMRPVRRTOWNZN]OaSiTlTpStQw RRTPWOZO]P`ThUlUpTsSuQwNy\x1fI[V.S1Q4O8N=NCOIPMSXT\\UbUgTlSoQs RS1Q5P8O=OBPHQLTWU[VaVgUlSpQsNv\x1fI[N.Q1S4U8V=VCUITMQXP\\ObOgPlQoSs RQ1S5T8U=UBTHSLPWO[NaNgOlQpSsVv\r7Z:RARRo R@RQo R?RRr RZ"VJRr\x1aI[TMVNXPXOWNTMQMNNMOLQLSMUOWSZ RQMONNOMQMSNUSZT\\T^S_Q_,G]LMKNJPJRKUOYP[ RJRKTOXP[P]O`MbLbKaJ_J\\KXMTOQRNTMVMYNZPZTYXWZU[T[SZSXTWUXTY RVMXNYPYTXXWZDE_YGXHYIZHYGWFTFQGOINKMNLRJ[I_Ha RTFRGPIOKNNLWK[J^I`HaFbDbCaC`D_E`Da R_G^H_I`H`G_F]F[GZHYJXMU[T_Sa R]F[HZJYNWWV[U^T`SaQbObNaN`O_P`Oa RIM^M3F^[GZH[I\\H[GXFUFRGPIOKNNMRK[J_Ia RUFSGQIPKONMWL[K^J`IaGbEbDaD`E_F`Ea RYMWTVXVZW[Z[\\Y]W RZMXTWXWZX[ RJMZM5F^YGXHYIZHZGXF R\\FUFRGPIOKNNMRK[J_Ia RUFSGQIPKONMWL[K^J`IaGbEbDaD`E_F`Ea R[FWTVXVZW[Z[\\Y]W R\\FXTWXWZX[ RJMYMU@cTGSHTIUHTGRFOFLGJIIKHNGRE[D_Ca ROFMGKIJKINGWF[E^D`CaAb?b>a>`?_@`?a R`G_H`IaH`G]FZFWGUITKSNRRP[O_Na RZFXGVIUKTNRWQ[P^O`NaLbJbIaI`J_K`Ja R^M\\T[X[Z\\[_[aYbW R_M]T\\X\\Z][ RDM_MW@cTGSHTIUHTGRFOFLGJIIKHNGRE[D_Ca ROFMGKIJKINGWF[E^D`CaAb?b>a>`?_@`?a R^G]H^I_H_G]F RaFZFWGUITKSNRRP[O_Na RZFXGVIUKTNRWQ[P^O`NaLbJbIaI`J_K`Ja R`F\\T[X[Z\\[_[aYbW RaF]T\\X\\Z][ RDM^M\x13LYMQNOPMSMTNTQRWRZS[ RRMSNSQQWQZR[U[WYXW\x15LXRLNWXPLPVWRL RRRRL RRRLP RRRNW RRRVW RRRXP\x17F^IUISJPLONOPPTSVTXTZS[Q RISJQLPNPPQTTVUXUZT[Q[O'
_index = b'\x00\x00\x03\x00\n\x00\x11\x00\x18\x00\x1f\x00&\x00-\x004\x00;\x00B\x00I\x00P\x00W\x00^\x00e\x00v\x00\x87\x00\x98\x00\xa9\x00\xbc\x00\xcf\x00\xe2\x00\xf5\x00\x00\x01\x0b\x01\x16\x01!\x01P\x01\x7f\x01\xae\x01\xdd\x01\x08\x02/\x02d\x02{\x02\x8e\x02\x99\x02\xa6\x02\xb9\x02\xcc\x02\xf1\x02\xfe\x02\t\x03\x16\x03/\x03<\x03I\x03\\\x03\xa3\x03\xda\x03\xfd\x03 \x04C\x04f\x04}\x04\xa8\x04\xc3\x04\xda\x04\xf7\x04\x1c\x05#\x05:\x05W\x05\x98\x05\xad\x05\xf2\x05s\x060\x07\x81\x07\xc2\x07\xe1\x07\x1a\x08\x89\x08\xe6\x08#\t\x94\t\xb9\t\xfc\t1\nZ\n\xbb\n\x1c\x0b}\x0b\xbe\x0b\xff\x0b\x1c\x0cS\x0c\xae\x0c9\r\xa2\r\x0f\x0e\xbc\x0em\x0f\x96\x0f\xc3\x0f'
index = memoryview(_index)
font = memoryview(_font) |
#!/usr/bin/python
## Ejercicio 1 reverse Polish Notation
## Autor: Fabiola Tapara Quispe
## Description: Mediante el siguiente metodo recibe un string con datos y signos con operaciones basicas (+, -, *, /) usando una Pila como estructura.
## * Date: 15/11/21
def sum (a, b):
return a + b
def resta (a, b):
return a - b
def multipli (a, b):
return a * b
def division (a, b):
return a // b
## Funcion Notacion
def polishReverse(input):
operadores = "+-*/"
string = []
listado = input.split(" ")
for i in listado:
if (i in operadores):
num2 = string.pop()
num1 = string.pop()
if (i == "+"):
string.append(sum(num1, num2))
elif (i == "-"):
string.append(resta(num1, num2))
elif (i == "*"):
string.append(multipli(num1, num2))
else:
string.append(division(num1, num2))
else:
string.append(int(i))
continue
return string[0]
## Casos de prueba vistos en clase
input = "2 1 + 3 *"
print("Primer Input : " + input)
print(polishReverse(input))
input = "4 13 5 / +"
print("Segundo Input : " + input)
print(polishReverse(input))
input = "10 6 9 3 + -11 * / * 17 + 5 +"
print("Tercer Input : " + input)
print(polishReverse(input))
| def sum(a, b):
return a + b
def resta(a, b):
return a - b
def multipli(a, b):
return a * b
def division(a, b):
return a // b
def polish_reverse(input):
operadores = '+-*/'
string = []
listado = input.split(' ')
for i in listado:
if i in operadores:
num2 = string.pop()
num1 = string.pop()
if i == '+':
string.append(sum(num1, num2))
elif i == '-':
string.append(resta(num1, num2))
elif i == '*':
string.append(multipli(num1, num2))
else:
string.append(division(num1, num2))
else:
string.append(int(i))
continue
return string[0]
input = '2 1 + 3 *'
print('Primer Input : ' + input)
print(polish_reverse(input))
input = '4 13 5 / +'
print('Segundo Input : ' + input)
print(polish_reverse(input))
input = '10 6 9 3 + -11 * / * 17 + 5 +'
print('Tercer Input : ' + input)
print(polish_reverse(input)) |
def return_category_with_more_spending(transactions):
category_transactions = transactions.groupby(by=["column_category"])[
"column_installment_value"
].sum()
return category_transactions.idxmax(), category_transactions.max()
| def return_category_with_more_spending(transactions):
category_transactions = transactions.groupby(by=['column_category'])['column_installment_value'].sum()
return (category_transactions.idxmax(), category_transactions.max()) |
def is_palindrome(n: int) -> bool:
s = str(n)
h = int(len(s) / 2)
s1 = s[:h]
s2 = s[h:][::-1]
is_palindrome = True
for i in range(h):
if s1[i] != s2[i]:
is_palindrome = False
return is_palindrome
def solution() -> int:
largest_palindrome = 0
for i in range(100, 1000):
for j in range(100, 1000):
n = i * j
if is_palindrome(n) and n > largest_palindrome:
largest_palindrome = n
return largest_palindrome
if __name__ == "__main__":
print(solution())
| def is_palindrome(n: int) -> bool:
s = str(n)
h = int(len(s) / 2)
s1 = s[:h]
s2 = s[h:][::-1]
is_palindrome = True
for i in range(h):
if s1[i] != s2[i]:
is_palindrome = False
return is_palindrome
def solution() -> int:
largest_palindrome = 0
for i in range(100, 1000):
for j in range(100, 1000):
n = i * j
if is_palindrome(n) and n > largest_palindrome:
largest_palindrome = n
return largest_palindrome
if __name__ == '__main__':
print(solution()) |
''' Check valid age
Write a program that takes age fro the user and then decide whether the age is between 18 to 24. If so, then it will display the message "You can apply for youth festival program". Otherwise, display the message "Sorry, you cannot apply".
If age >= 18 and age <= 24 # Not correct
If age = 18 and age < 24 # correct solution
'''
age = int(input("Please enter the age: "))
if age >= 18 and age <= 24:
print("You can apply for Youth Festival program")
else:
print("Sorry, you cannot apply") # Please enter the age: 20
# You can apply for Youth Festival program
# Please enter the age: 30
# Sorry, you cannot apply
| """ Check valid age
Write a program that takes age fro the user and then decide whether the age is between 18 to 24. If so, then it will display the message "You can apply for youth festival program". Otherwise, display the message "Sorry, you cannot apply".
If age >= 18 and age <= 24 # Not correct
If age = 18 and age < 24 # correct solution
"""
age = int(input('Please enter the age: '))
if age >= 18 and age <= 24:
print('You can apply for Youth Festival program')
else:
print('Sorry, you cannot apply') |
#Algorithm Case Study
def naive(a,b):
x=a; y=b
z =0
while(x > 0):
z = z+y
x = x-1
return z
def testnaive():
i=0
while(i < 10):
j=0
while(j < 10):
print(i,j)
print(naive(i,j))
j += 1
i += 1
if __name__ == "__main__":
testnaive()
| def naive(a, b):
x = a
y = b
z = 0
while x > 0:
z = z + y
x = x - 1
return z
def testnaive():
i = 0
while i < 10:
j = 0
while j < 10:
print(i, j)
print(naive(i, j))
j += 1
i += 1
if __name__ == '__main__':
testnaive() |
capacity = int(input())
income = 0
command = input()
while command != "Movie time!":
group_count = int(command)
if group_count > capacity:
print("The cinema is full.")
print(f"Cinema income - {income} lv.")
exit()
capacity -= group_count
group_tax = group_count * 5
if group_count % 3 == 0:
group_tax -= 5
income += group_tax
command = input()
print(f"There are {capacity} seats left in the cinema.")
print(f"Cinema income - {income} lv.")
| capacity = int(input())
income = 0
command = input()
while command != 'Movie time!':
group_count = int(command)
if group_count > capacity:
print('The cinema is full.')
print(f'Cinema income - {income} lv.')
exit()
capacity -= group_count
group_tax = group_count * 5
if group_count % 3 == 0:
group_tax -= 5
income += group_tax
command = input()
print(f'There are {capacity} seats left in the cinema.')
print(f'Cinema income - {income} lv.') |
#pretty print method
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
| def indent(elem, level=0):
i = '\n' + level * ' '
j = '\n' + (level - 1) * ' '
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + ' '
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
elif level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem |
# -*- coding: utf-8 -*-
# This work is licensed under the MIT License.
# To view a copy of this license, visit https://www.gnu.org/licenses/
# Written by Taher Abbasi
# Email: [email protected]
class WrongSide(Exception):
pass | class Wrongside(Exception):
pass |
skywater_metal1 = {"layer": 68, "datatype": 20 }
skywater_metal2 = {"layer": 69, "datatype": 20 }
skywater_metal3 = {"layer": 70, "datatype": 20 }
skywater_metal4 = {"layer": 71, "datatype": 20 }
skywater_metal5 = {"layer": 72, "datatype": 20 }
| skywater_metal1 = {'layer': 68, 'datatype': 20}
skywater_metal2 = {'layer': 69, 'datatype': 20}
skywater_metal3 = {'layer': 70, 'datatype': 20}
skywater_metal4 = {'layer': 71, 'datatype': 20}
skywater_metal5 = {'layer': 72, 'datatype': 20} |
rc = 0
def setup():
size(600, 600)
smooth()
background(0)
font = loadFont("Gadugi-Bold-48.vlw")
textFont(font, 48)
def draw():
global rc
translate(width/2, height/2)
pushMatrix()
rotate(rc)
fill(255)
text("Black", mouseX - width/4, mouseY - height/4)
popMatrix()
pushMatrix()
rotate(-rc * 1.5)
fill(0)
text("White", width/4 - mouseX, height/4 - mouseY)
popMatrix()
rc += 0.05
| rc = 0
def setup():
size(600, 600)
smooth()
background(0)
font = load_font('Gadugi-Bold-48.vlw')
text_font(font, 48)
def draw():
global rc
translate(width / 2, height / 2)
push_matrix()
rotate(rc)
fill(255)
text('Black', mouseX - width / 4, mouseY - height / 4)
pop_matrix()
push_matrix()
rotate(-rc * 1.5)
fill(0)
text('White', width / 4 - mouseX, height / 4 - mouseY)
pop_matrix()
rc += 0.05 |
class MessagesSerializer:
fields = ['id', 'topic', 'payload', 'attributes', 'bulk']
def serialize(self, messages):
return [self._serialize_fields(message) for message in messages]
def _serialize_fields(self, message):
return {field: getattr(message, field, None) for field in self.fields}
| class Messagesserializer:
fields = ['id', 'topic', 'payload', 'attributes', 'bulk']
def serialize(self, messages):
return [self._serialize_fields(message) for message in messages]
def _serialize_fields(self, message):
return {field: getattr(message, field, None) for field in self.fields} |
# -*- coding: utf-8 -*-
# @Author: Anderson
# @Date: 2018-09-01 22:04:38
# @Last Modified by: Anderson
# @Last Modified time: 2018-09-14 15:55:53
class DS(object):
def __init__(self, N):
self.__id = list(range(0, N))
def is_connected(self, parent, child):
pid = ord(parent) - ord('A')
cid = ord(child) - ord('A')
connected = False
generation_count = 0
while not connected:
generation_count += 1
pid = self.__id[pid]
if pid == cid:
connected = True
elif pid == self.__id[pid]:
break
if connected:
result = 'child'
if generation_count > 1:
result = 'grandchild'
if generation_count > 2:
for _ in range(2, generation_count):
result = 'great-' + result
return result
else:
return '-'
def connect(self, parent, child):
if parent != '-':
self.__id[ord(parent)-ord('A')] = ord(child)-ord('A')
s = input()
n, m = s.split(' ')
n = int(n)
m = int(m)
ds = DS(26)
for _ in range(n):
child, father, mother = input()
ds.connect(father, child)
ds.connect(mother, child)
for _ in range(m):
a, b = input()
if a == b:
print('-')
else:
result = ds.is_connected(b, a)
if result == '-':
result = ds.is_connected(a, b)
result = result.replace('child', 'parent')
print(result)
| class Ds(object):
def __init__(self, N):
self.__id = list(range(0, N))
def is_connected(self, parent, child):
pid = ord(parent) - ord('A')
cid = ord(child) - ord('A')
connected = False
generation_count = 0
while not connected:
generation_count += 1
pid = self.__id[pid]
if pid == cid:
connected = True
elif pid == self.__id[pid]:
break
if connected:
result = 'child'
if generation_count > 1:
result = 'grandchild'
if generation_count > 2:
for _ in range(2, generation_count):
result = 'great-' + result
return result
else:
return '-'
def connect(self, parent, child):
if parent != '-':
self.__id[ord(parent) - ord('A')] = ord(child) - ord('A')
s = input()
(n, m) = s.split(' ')
n = int(n)
m = int(m)
ds = ds(26)
for _ in range(n):
(child, father, mother) = input()
ds.connect(father, child)
ds.connect(mother, child)
for _ in range(m):
(a, b) = input()
if a == b:
print('-')
else:
result = ds.is_connected(b, a)
if result == '-':
result = ds.is_connected(a, b)
result = result.replace('child', 'parent')
print(result) |
#
# PySNMP MIB module Juniper-IPV6-PROFILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-IPV6-PROFILE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:03:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
InetAddressIPv6, = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressIPv6")
Ipv6AddressPrefix, = mibBuilder.importSymbols("IPV6-TC", "Ipv6AddressPrefix")
juniMibs, = mibBuilder.importSymbols("Juniper-MIBs", "juniMibs")
JuniName, JuniSetMap, JuniEnable = mibBuilder.importSymbols("Juniper-TC", "JuniName", "JuniSetMap", "JuniEnable")
NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance")
Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Counter64, ModuleIdentity, Unsigned32, Counter32, NotificationType, Bits, ObjectIdentity, Gauge32, TimeTicks, IpAddress, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Counter64", "ModuleIdentity", "Unsigned32", "Counter32", "NotificationType", "Bits", "ObjectIdentity", "Gauge32", "TimeTicks", "IpAddress", "iso")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
juniIpv6ProfileMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68))
juniIpv6ProfileMIB.setRevisions(('2007-07-19 18:19', '2003-09-29 17:58',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setRevisionsDescriptions(('Added ND support on dynamic interface.', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setLastUpdated('200707191819Z')
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setOrganization('Juniper Networks')
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setContactInfo(' Juniper Networks, Inc. Postal: 10 Technology Park Drive Westford MA 01886-3146 USA Tel: +1 978 589 5800 Email: [email protected]')
if mibBuilder.loadTexts: juniIpv6ProfileMIB.setDescription('The IPv6 Profile MIB for the Juniper Networks enterprise.')
juniIpv6ProfileObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1))
juniIpv6Profile = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1))
juniIpv6ProfileTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1), )
if mibBuilder.loadTexts: juniIpv6ProfileTable.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileTable.setDescription('The entries in this table describe profiles for configuring IP interfaces. Entries in this table are created/deleted as a side-effect of corresponding operations to the juniProfileNameTable in the Juniper-PROFILE-MIB.')
juniIpv6ProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1), ).setIndexNames((0, "Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileId"))
if mibBuilder.loadTexts: juniIpv6ProfileEntry.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileEntry.setDescription('A profile describing configuration of an IPv6 interface.')
juniIpv6ProfileId = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 1), Unsigned32())
if mibBuilder.loadTexts: juniIpv6ProfileId.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileId.setDescription('The integer identifier associated with this profile. A value for this identifier is determined by locating or creating a profile name in the juniProfileNameTable.')
juniIpv6ProfileSetMap = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 2), JuniSetMap()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileSetMap.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileSetMap.setDescription("A bitmap representing which objects in this entry have been explicitly configured. See the definition of the JuniSetMap TEXTUAL-CONVENTION for details of use. The INDEX object(s) and this object are excluded from representation (i.e. their bits are never set). When a SET request does not explicitly configure JuniSetMap, bits in JuniSetMap are set as a side-effect of configuring other profile attributes in the same entry. If, however, a SET request explicitly configures JuniSetMap, the explicitly configured value overrides 1) any previous bit settings, and 2) any simultaneous 'side-effect' settings that would otherwise occur. Once set, bits can only be cleared by explicitly configuring JuniSetMap.")
juniIpv6ProfileRouterName = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 3), JuniName()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileRouterName.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileRouterName.setDescription('The virtual router to which an IPv6 interface configured by this profile will be assigned, if other mechanisms do not otherwise specify a virtual router assignment.')
juniIpv6ProfileIpv6Addr = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 4), InetAddressIPv6().clone(hexValue="00000000000000000000000000000000")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileIpv6Addr.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileIpv6Addr.setDescription('An IPv6 address to be used by an IPv6 interface configured by this profile. This object will have a value of 0::0 for an unnumbered interface.')
juniIpv6ProfileIpv6MaskLen = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 128))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileIpv6MaskLen.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileIpv6MaskLen.setDescription('An IPv6 address mask length to be used by an IPv6 interface configured by this profile. This object will have a value of 0 for an unnumbered interface.')
juniIpv6ProfileMtu = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1280, 10240), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileMtu.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileMtu.setDescription('The configured MTU size for this IPv6 network interface. If set to zero, the default MTU size, as determined by the underlying network media, is used.')
juniIpv6ProfileSrcAddrValidEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 7), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileSrcAddrValidEnable.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileSrcAddrValidEnable.setDescription('Enable/disable whether source addresses in received IPv6 packets are validated. Validation is performed by looking up the source IPv6 address in the routing database and determining whether the packet arrived on the expected interface; if not, the packet is discarded.')
juniIpv6ProfileInheritNumString = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileInheritNumString.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileInheritNumString.setDescription("The text identifier of the numbered interface, associated with the specified virtual router, whose IPv6 address is used as the source address when transmitting IPv6 packets on unnumbered remote access user links. Types/formats/examples for this string include: Loopback loopback <id> 'loopback 0' ATM Virtual Circuit atm <slot>/<port>.<distinguisher> 'atm 3/1.100' Ethernet { fastEthernet | gigabitEthernet } <slot>/<port> 'fastEthernet 3/0' 'gigabitEthernet 3/0' Ethernet VLAN { fastEthernet | gigabitEthernet } <slot>/<port>:<vlanID> 'fastEthernet 3/0:1000' 'gigabitEthernet 3/0:1000' Channelized Serial serial <slot>/<port>:<channelSpecifier>[/<channelSpecifier>]* 'serial 3/0:4' (T1/E1) 'serial 3/0:2/4' (T3/E3) 'serial 3/0:2/1/1/4' (OC3/OC12 - channelized DS3) 'serial 3/0:2/1/1/1/4' (OC3/OC12 - virtual tributaries) Other formats may be supported over time. An empty string indicates the referenced interface is unspecified, e.g., when this IPv6 interface is numbered.")
juniIpv6ProfileNdEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 9), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdEnabled.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdEnabled.setDescription('Enable/disable ND for this IPv6 network interface.')
juniIpv6ProfileNdManagedConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 10), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdManagedConfig.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdManagedConfig.setDescription('Enable/disable ND managed config for this IPv6 network interface.')
juniIpv6ProfileNdOtherConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 11), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdOtherConfig.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdOtherConfig.setDescription('Enable/disable ND other config for this IPv6 network interface.')
juniIpv6ProfileNdSuppressRa = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 12), JuniEnable().clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdSuppressRa.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdSuppressRa.setDescription('Enable/disable ND suppress RA for this IPv6 network interface.')
juniIpv6ProfileNdRaInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(3, 1800)).clone(200)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdRaInterval.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdRaInterval.setDescription('The configured interval between IPv6 RA transmissions on the interface.')
juniIpv6ProfileNdRaLifeTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1800)).clone(1800)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdRaLifeTime.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdRaLifeTime.setDescription('The configured RA lifetime for this IPv6 network interface.')
juniIpv6ProfileNdReachableTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 15), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdReachableTime.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdReachableTime.setDescription('The configured RA reachable time for this IPv6 network interface.')
juniIpv6ProfileNdPrefix = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 16), Ipv6AddressPrefix()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefix.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefix.setDescription('The prefix associated with the this interface.')
juniIpv6ProfileNdPrefixLength = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixLength.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixLength.setDescription('The length of the prefix (in bits).')
juniIpv6ProfileNdPrefixOnLinkFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 18), JuniEnable().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixOnLinkFlag.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixOnLinkFlag.setDescription("This object has the value 'true(1)', if this prefix can be used for on-link determination and the value 'false(2)' otherwise.")
juniIpv6ProfileNdPrefixAutonomousFlag = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 19), JuniEnable().clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixAutonomousFlag.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixAutonomousFlag.setDescription('Autonomous address configuration flag. When true(1), indicates that this prefix can be used for autonomous address configuration (i.e. can be used to form a local interface address). If false(2), it is not used to autoconfigure a local interface address.')
juniIpv6ProfileNdPrefixPreferredLifetime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 20), Integer32().clone(604800)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixPreferredLifetime.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixPreferredLifetime.setDescription('It is the length of time in seconds that this prefix will remain preferred, i.e. time until deprecation. A value of 4,294,967,295 represents infinity. The address generated from a deprecated prefix should no longer be used as a source address in new communications, but packets received on such an interface are processed as expected.')
juniIpv6ProfileNdPrefixValidLifetime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 21), Integer32().clone(2592000)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixValidLifetime.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileNdPrefixValidLifetime.setDescription('It is the length of time in seconds that this prefix will remain valid, i.e. time until invalidation. A value of 4,294,967,295 represents infinity. The address generated from an invalidated prefix should not appear as the destination or source address of a packet.')
juniIpv6ProfileMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4))
juniIpv6ProfileMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1))
juniIpv6ProfileMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2))
juniIpv6ProfileCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1, 1)).setObjects(("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniIpv6ProfileCompliance = juniIpv6ProfileCompliance.setStatus('obsolete')
if mibBuilder.loadTexts: juniIpv6ProfileCompliance.setDescription('Obsolete Compliance statement for systems supporting IPv6 configuration profiles. This statement became obsolete when added ND support.')
juniIpv6ProfileCompliance1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1, 2)).setObjects(("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileGroup1"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniIpv6ProfileCompliance1 = juniIpv6ProfileCompliance1.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileCompliance1.setDescription('Compliance statement for systems supporting IPv6 configuration profiles, incorporating support of ND on dynamical interface.')
juniIpv6ProfileGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2, 1)).setObjects(("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileSetMap"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileRouterName"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileIpv6Addr"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileIpv6MaskLen"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileMtu"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileSrcAddrValidEnable"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileInheritNumString"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniIpv6ProfileGroup = juniIpv6ProfileGroup.setStatus('obsolete')
if mibBuilder.loadTexts: juniIpv6ProfileGroup.setDescription('An obsolete collection of objects providing management of IPv6 Profile functionality in a Juniper product. This statement became obsolete when added ND support.')
juniIpv6ProfileGroup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2, 2)).setObjects(("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileSetMap"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileRouterName"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileIpv6Addr"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileIpv6MaskLen"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileMtu"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileSrcAddrValidEnable"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileInheritNumString"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdEnabled"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdManagedConfig"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdOtherConfig"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdSuppressRa"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdRaInterval"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdRaLifeTime"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdReachableTime"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefix"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixLength"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixOnLinkFlag"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixAutonomousFlag"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixPreferredLifetime"), ("Juniper-IPV6-PROFILE-MIB", "juniIpv6ProfileNdPrefixValidLifetime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniIpv6ProfileGroup1 = juniIpv6ProfileGroup1.setStatus('current')
if mibBuilder.loadTexts: juniIpv6ProfileGroup1.setDescription('The basic collection of objects providing management of IPv6 Profile functionality in a Juniper product.')
mibBuilder.exportSymbols("Juniper-IPV6-PROFILE-MIB", juniIpv6Profile=juniIpv6Profile, juniIpv6ProfileSrcAddrValidEnable=juniIpv6ProfileSrcAddrValidEnable, juniIpv6ProfileGroup=juniIpv6ProfileGroup, juniIpv6ProfileNdSuppressRa=juniIpv6ProfileNdSuppressRa, juniIpv6ProfileIpv6MaskLen=juniIpv6ProfileIpv6MaskLen, juniIpv6ProfileObjects=juniIpv6ProfileObjects, juniIpv6ProfileNdPrefixPreferredLifetime=juniIpv6ProfileNdPrefixPreferredLifetime, juniIpv6ProfileCompliance1=juniIpv6ProfileCompliance1, juniIpv6ProfileNdPrefixValidLifetime=juniIpv6ProfileNdPrefixValidLifetime, juniIpv6ProfileNdPrefixLength=juniIpv6ProfileNdPrefixLength, juniIpv6ProfileMIB=juniIpv6ProfileMIB, juniIpv6ProfileNdPrefix=juniIpv6ProfileNdPrefix, juniIpv6ProfileGroup1=juniIpv6ProfileGroup1, juniIpv6ProfileIpv6Addr=juniIpv6ProfileIpv6Addr, juniIpv6ProfileNdRaLifeTime=juniIpv6ProfileNdRaLifeTime, juniIpv6ProfileTable=juniIpv6ProfileTable, juniIpv6ProfileNdOtherConfig=juniIpv6ProfileNdOtherConfig, juniIpv6ProfileNdPrefixOnLinkFlag=juniIpv6ProfileNdPrefixOnLinkFlag, juniIpv6ProfileMtu=juniIpv6ProfileMtu, juniIpv6ProfileMIBCompliances=juniIpv6ProfileMIBCompliances, juniIpv6ProfileNdEnabled=juniIpv6ProfileNdEnabled, juniIpv6ProfileMIBConformance=juniIpv6ProfileMIBConformance, juniIpv6ProfileInheritNumString=juniIpv6ProfileInheritNumString, juniIpv6ProfileNdPrefixAutonomousFlag=juniIpv6ProfileNdPrefixAutonomousFlag, juniIpv6ProfileMIBGroups=juniIpv6ProfileMIBGroups, juniIpv6ProfileCompliance=juniIpv6ProfileCompliance, juniIpv6ProfileSetMap=juniIpv6ProfileSetMap, juniIpv6ProfileNdReachableTime=juniIpv6ProfileNdReachableTime, juniIpv6ProfileId=juniIpv6ProfileId, juniIpv6ProfileNdRaInterval=juniIpv6ProfileNdRaInterval, PYSNMP_MODULE_ID=juniIpv6ProfileMIB, juniIpv6ProfileRouterName=juniIpv6ProfileRouterName, juniIpv6ProfileEntry=juniIpv6ProfileEntry, juniIpv6ProfileNdManagedConfig=juniIpv6ProfileNdManagedConfig)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint')
(inet_address_i_pv6,) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressIPv6')
(ipv6_address_prefix,) = mibBuilder.importSymbols('IPV6-TC', 'Ipv6AddressPrefix')
(juni_mibs,) = mibBuilder.importSymbols('Juniper-MIBs', 'juniMibs')
(juni_name, juni_set_map, juni_enable) = mibBuilder.importSymbols('Juniper-TC', 'JuniName', 'JuniSetMap', 'JuniEnable')
(notification_group, object_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ObjectGroup', 'ModuleCompliance')
(integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, counter64, module_identity, unsigned32, counter32, notification_type, bits, object_identity, gauge32, time_ticks, ip_address, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'Counter64', 'ModuleIdentity', 'Unsigned32', 'Counter32', 'NotificationType', 'Bits', 'ObjectIdentity', 'Gauge32', 'TimeTicks', 'IpAddress', 'iso')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
juni_ipv6_profile_mib = module_identity((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68))
juniIpv6ProfileMIB.setRevisions(('2007-07-19 18:19', '2003-09-29 17:58'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
juniIpv6ProfileMIB.setRevisionsDescriptions(('Added ND support on dynamic interface.', 'Initial version of this MIB module.'))
if mibBuilder.loadTexts:
juniIpv6ProfileMIB.setLastUpdated('200707191819Z')
if mibBuilder.loadTexts:
juniIpv6ProfileMIB.setOrganization('Juniper Networks')
if mibBuilder.loadTexts:
juniIpv6ProfileMIB.setContactInfo(' Juniper Networks, Inc. Postal: 10 Technology Park Drive Westford MA 01886-3146 USA Tel: +1 978 589 5800 Email: [email protected]')
if mibBuilder.loadTexts:
juniIpv6ProfileMIB.setDescription('The IPv6 Profile MIB for the Juniper Networks enterprise.')
juni_ipv6_profile_objects = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1))
juni_ipv6_profile = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1))
juni_ipv6_profile_table = mib_table((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1))
if mibBuilder.loadTexts:
juniIpv6ProfileTable.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileTable.setDescription('The entries in this table describe profiles for configuring IP interfaces. Entries in this table are created/deleted as a side-effect of corresponding operations to the juniProfileNameTable in the Juniper-PROFILE-MIB.')
juni_ipv6_profile_entry = mib_table_row((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1)).setIndexNames((0, 'Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileId'))
if mibBuilder.loadTexts:
juniIpv6ProfileEntry.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileEntry.setDescription('A profile describing configuration of an IPv6 interface.')
juni_ipv6_profile_id = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 1), unsigned32())
if mibBuilder.loadTexts:
juniIpv6ProfileId.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileId.setDescription('The integer identifier associated with this profile. A value for this identifier is determined by locating or creating a profile name in the juniProfileNameTable.')
juni_ipv6_profile_set_map = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 2), juni_set_map()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileSetMap.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileSetMap.setDescription("A bitmap representing which objects in this entry have been explicitly configured. See the definition of the JuniSetMap TEXTUAL-CONVENTION for details of use. The INDEX object(s) and this object are excluded from representation (i.e. their bits are never set). When a SET request does not explicitly configure JuniSetMap, bits in JuniSetMap are set as a side-effect of configuring other profile attributes in the same entry. If, however, a SET request explicitly configures JuniSetMap, the explicitly configured value overrides 1) any previous bit settings, and 2) any simultaneous 'side-effect' settings that would otherwise occur. Once set, bits can only be cleared by explicitly configuring JuniSetMap.")
juni_ipv6_profile_router_name = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 3), juni_name()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileRouterName.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileRouterName.setDescription('The virtual router to which an IPv6 interface configured by this profile will be assigned, if other mechanisms do not otherwise specify a virtual router assignment.')
juni_ipv6_profile_ipv6_addr = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 4), inet_address_i_pv6().clone(hexValue='00000000000000000000000000000000')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileIpv6Addr.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileIpv6Addr.setDescription('An IPv6 address to be used by an IPv6 interface configured by this profile. This object will have a value of 0::0 for an unnumbered interface.')
juni_ipv6_profile_ipv6_mask_len = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 128))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileIpv6MaskLen.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileIpv6MaskLen.setDescription('An IPv6 address mask length to be used by an IPv6 interface configured by this profile. This object will have a value of 0 for an unnumbered interface.')
juni_ipv6_profile_mtu = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(1280, 10240)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileMtu.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileMtu.setDescription('The configured MTU size for this IPv6 network interface. If set to zero, the default MTU size, as determined by the underlying network media, is used.')
juni_ipv6_profile_src_addr_valid_enable = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 7), juni_enable().clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileSrcAddrValidEnable.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileSrcAddrValidEnable.setDescription('Enable/disable whether source addresses in received IPv6 packets are validated. Validation is performed by looking up the source IPv6 address in the routing database and determining whether the packet arrived on the expected interface; if not, the packet is discarded.')
juni_ipv6_profile_inherit_num_string = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 80))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileInheritNumString.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileInheritNumString.setDescription("The text identifier of the numbered interface, associated with the specified virtual router, whose IPv6 address is used as the source address when transmitting IPv6 packets on unnumbered remote access user links. Types/formats/examples for this string include: Loopback loopback <id> 'loopback 0' ATM Virtual Circuit atm <slot>/<port>.<distinguisher> 'atm 3/1.100' Ethernet { fastEthernet | gigabitEthernet } <slot>/<port> 'fastEthernet 3/0' 'gigabitEthernet 3/0' Ethernet VLAN { fastEthernet | gigabitEthernet } <slot>/<port>:<vlanID> 'fastEthernet 3/0:1000' 'gigabitEthernet 3/0:1000' Channelized Serial serial <slot>/<port>:<channelSpecifier>[/<channelSpecifier>]* 'serial 3/0:4' (T1/E1) 'serial 3/0:2/4' (T3/E3) 'serial 3/0:2/1/1/4' (OC3/OC12 - channelized DS3) 'serial 3/0:2/1/1/1/4' (OC3/OC12 - virtual tributaries) Other formats may be supported over time. An empty string indicates the referenced interface is unspecified, e.g., when this IPv6 interface is numbered.")
juni_ipv6_profile_nd_enabled = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 9), juni_enable().clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdEnabled.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdEnabled.setDescription('Enable/disable ND for this IPv6 network interface.')
juni_ipv6_profile_nd_managed_config = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 10), juni_enable().clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdManagedConfig.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdManagedConfig.setDescription('Enable/disable ND managed config for this IPv6 network interface.')
juni_ipv6_profile_nd_other_config = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 11), juni_enable().clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdOtherConfig.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdOtherConfig.setDescription('Enable/disable ND other config for this IPv6 network interface.')
juni_ipv6_profile_nd_suppress_ra = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 12), juni_enable().clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdSuppressRa.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdSuppressRa.setDescription('Enable/disable ND suppress RA for this IPv6 network interface.')
juni_ipv6_profile_nd_ra_interval = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 13), integer32().subtype(subtypeSpec=value_range_constraint(3, 1800)).clone(200)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdRaInterval.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdRaInterval.setDescription('The configured interval between IPv6 RA transmissions on the interface.')
juni_ipv6_profile_nd_ra_life_time = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 14), integer32().subtype(subtypeSpec=value_range_constraint(0, 1800)).clone(1800)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdRaLifeTime.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdRaLifeTime.setDescription('The configured RA lifetime for this IPv6 network interface.')
juni_ipv6_profile_nd_reachable_time = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 15), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdReachableTime.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdReachableTime.setDescription('The configured RA reachable time for this IPv6 network interface.')
juni_ipv6_profile_nd_prefix = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 16), ipv6_address_prefix()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefix.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefix.setDescription('The prefix associated with the this interface.')
juni_ipv6_profile_nd_prefix_length = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 17), integer32().subtype(subtypeSpec=value_range_constraint(1, 128))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixLength.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixLength.setDescription('The length of the prefix (in bits).')
juni_ipv6_profile_nd_prefix_on_link_flag = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 18), juni_enable().clone('enable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixOnLinkFlag.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixOnLinkFlag.setDescription("This object has the value 'true(1)', if this prefix can be used for on-link determination and the value 'false(2)' otherwise.")
juni_ipv6_profile_nd_prefix_autonomous_flag = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 19), juni_enable().clone('enable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixAutonomousFlag.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixAutonomousFlag.setDescription('Autonomous address configuration flag. When true(1), indicates that this prefix can be used for autonomous address configuration (i.e. can be used to form a local interface address). If false(2), it is not used to autoconfigure a local interface address.')
juni_ipv6_profile_nd_prefix_preferred_lifetime = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 20), integer32().clone(604800)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixPreferredLifetime.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixPreferredLifetime.setDescription('It is the length of time in seconds that this prefix will remain preferred, i.e. time until deprecation. A value of 4,294,967,295 represents infinity. The address generated from a deprecated prefix should no longer be used as a source address in new communications, but packets received on such an interface are processed as expected.')
juni_ipv6_profile_nd_prefix_valid_lifetime = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 1, 1, 1, 1, 21), integer32().clone(2592000)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixValidLifetime.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileNdPrefixValidLifetime.setDescription('It is the length of time in seconds that this prefix will remain valid, i.e. time until invalidation. A value of 4,294,967,295 represents infinity. The address generated from an invalidated prefix should not appear as the destination or source address of a packet.')
juni_ipv6_profile_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4))
juni_ipv6_profile_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1))
juni_ipv6_profile_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2))
juni_ipv6_profile_compliance = module_compliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1, 1)).setObjects(('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juni_ipv6_profile_compliance = juniIpv6ProfileCompliance.setStatus('obsolete')
if mibBuilder.loadTexts:
juniIpv6ProfileCompliance.setDescription('Obsolete Compliance statement for systems supporting IPv6 configuration profiles. This statement became obsolete when added ND support.')
juni_ipv6_profile_compliance1 = module_compliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 1, 2)).setObjects(('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileGroup1'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juni_ipv6_profile_compliance1 = juniIpv6ProfileCompliance1.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileCompliance1.setDescription('Compliance statement for systems supporting IPv6 configuration profiles, incorporating support of ND on dynamical interface.')
juni_ipv6_profile_group = object_group((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2, 1)).setObjects(('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileSetMap'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileRouterName'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileIpv6Addr'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileIpv6MaskLen'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileMtu'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileSrcAddrValidEnable'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileInheritNumString'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juni_ipv6_profile_group = juniIpv6ProfileGroup.setStatus('obsolete')
if mibBuilder.loadTexts:
juniIpv6ProfileGroup.setDescription('An obsolete collection of objects providing management of IPv6 Profile functionality in a Juniper product. This statement became obsolete when added ND support.')
juni_ipv6_profile_group1 = object_group((1, 3, 6, 1, 4, 1, 4874, 2, 2, 68, 4, 2, 2)).setObjects(('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileSetMap'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileRouterName'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileIpv6Addr'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileIpv6MaskLen'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileMtu'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileSrcAddrValidEnable'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileInheritNumString'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdEnabled'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdManagedConfig'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdOtherConfig'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdSuppressRa'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdRaInterval'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdRaLifeTime'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdReachableTime'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdPrefix'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdPrefixLength'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdPrefixOnLinkFlag'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdPrefixAutonomousFlag'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdPrefixPreferredLifetime'), ('Juniper-IPV6-PROFILE-MIB', 'juniIpv6ProfileNdPrefixValidLifetime'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juni_ipv6_profile_group1 = juniIpv6ProfileGroup1.setStatus('current')
if mibBuilder.loadTexts:
juniIpv6ProfileGroup1.setDescription('The basic collection of objects providing management of IPv6 Profile functionality in a Juniper product.')
mibBuilder.exportSymbols('Juniper-IPV6-PROFILE-MIB', juniIpv6Profile=juniIpv6Profile, juniIpv6ProfileSrcAddrValidEnable=juniIpv6ProfileSrcAddrValidEnable, juniIpv6ProfileGroup=juniIpv6ProfileGroup, juniIpv6ProfileNdSuppressRa=juniIpv6ProfileNdSuppressRa, juniIpv6ProfileIpv6MaskLen=juniIpv6ProfileIpv6MaskLen, juniIpv6ProfileObjects=juniIpv6ProfileObjects, juniIpv6ProfileNdPrefixPreferredLifetime=juniIpv6ProfileNdPrefixPreferredLifetime, juniIpv6ProfileCompliance1=juniIpv6ProfileCompliance1, juniIpv6ProfileNdPrefixValidLifetime=juniIpv6ProfileNdPrefixValidLifetime, juniIpv6ProfileNdPrefixLength=juniIpv6ProfileNdPrefixLength, juniIpv6ProfileMIB=juniIpv6ProfileMIB, juniIpv6ProfileNdPrefix=juniIpv6ProfileNdPrefix, juniIpv6ProfileGroup1=juniIpv6ProfileGroup1, juniIpv6ProfileIpv6Addr=juniIpv6ProfileIpv6Addr, juniIpv6ProfileNdRaLifeTime=juniIpv6ProfileNdRaLifeTime, juniIpv6ProfileTable=juniIpv6ProfileTable, juniIpv6ProfileNdOtherConfig=juniIpv6ProfileNdOtherConfig, juniIpv6ProfileNdPrefixOnLinkFlag=juniIpv6ProfileNdPrefixOnLinkFlag, juniIpv6ProfileMtu=juniIpv6ProfileMtu, juniIpv6ProfileMIBCompliances=juniIpv6ProfileMIBCompliances, juniIpv6ProfileNdEnabled=juniIpv6ProfileNdEnabled, juniIpv6ProfileMIBConformance=juniIpv6ProfileMIBConformance, juniIpv6ProfileInheritNumString=juniIpv6ProfileInheritNumString, juniIpv6ProfileNdPrefixAutonomousFlag=juniIpv6ProfileNdPrefixAutonomousFlag, juniIpv6ProfileMIBGroups=juniIpv6ProfileMIBGroups, juniIpv6ProfileCompliance=juniIpv6ProfileCompliance, juniIpv6ProfileSetMap=juniIpv6ProfileSetMap, juniIpv6ProfileNdReachableTime=juniIpv6ProfileNdReachableTime, juniIpv6ProfileId=juniIpv6ProfileId, juniIpv6ProfileNdRaInterval=juniIpv6ProfileNdRaInterval, PYSNMP_MODULE_ID=juniIpv6ProfileMIB, juniIpv6ProfileRouterName=juniIpv6ProfileRouterName, juniIpv6ProfileEntry=juniIpv6ProfileEntry, juniIpv6ProfileNdManagedConfig=juniIpv6ProfileNdManagedConfig) |
print("My name is Jessica Bonnie Ayomide")
print("JJJJJJJJJJJJJ BBBBBBBBBB A")
print(" J B B A A")
print(" J B B A A")
print(" J B B A A")
print(" J B B A A")
print(" J BBBBBBBBBB AAAAAAAAAA")
print(" J B B A A")
print(" J B B A A")
print("J J B B A A")
print(" J J B B A A")
print(" JJJJJ BBBBBBBBBB A A")
| print('My name is Jessica Bonnie Ayomide')
print('JJJJJJJJJJJJJ BBBBBBBBBB A')
print(' J B B A A')
print(' J B B A A')
print(' J B B A A')
print(' J B B A A')
print(' J BBBBBBBBBB AAAAAAAAAA')
print(' J B B A A')
print(' J B B A A')
print('J J B B A A')
print(' J J B B A A')
print(' JJJJJ BBBBBBBBBB A A') |
#!/usr/bin/env python3
def main():
arr = []
fname = sys.argv[1]
with open(fname, 'r') as f:
for line in f:
arr.append(int(line.rstrip('\r\n')))
quicksort(arr, start=0, end=len(arr)-1)
print('Sorted list is: ', arr)
return
def quicksort(arr, start, end):
if end - start < 1:
return 0
b = start + 1
for i in range(start+1, end):
if arr[i] <= arr[start]:
arr[b], arr[i] = arr[i], arr[b]
b += 1
arr[start], arr[b-1] = arr[b-1], arr[start]
quicksort(arr, start, b-1)
quicksort(arr, b, end)
if __name__ == '__main__':
main()
| def main():
arr = []
fname = sys.argv[1]
with open(fname, 'r') as f:
for line in f:
arr.append(int(line.rstrip('\r\n')))
quicksort(arr, start=0, end=len(arr) - 1)
print('Sorted list is: ', arr)
return
def quicksort(arr, start, end):
if end - start < 1:
return 0
b = start + 1
for i in range(start + 1, end):
if arr[i] <= arr[start]:
(arr[b], arr[i]) = (arr[i], arr[b])
b += 1
(arr[start], arr[b - 1]) = (arr[b - 1], arr[start])
quicksort(arr, start, b - 1)
quicksort(arr, b, end)
if __name__ == '__main__':
main() |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"test_eq": "00_core.ipynb",
"listify": "00_core.ipynb",
"test_in": "00_core.ipynb",
"test_err": "00_core.ipynb",
"configure_logging": "00_core.ipynb",
"setup_dataframe_copy_logging": "00_core.ipynb",
"n_total_series": "00_core.ipynb",
"n_days_total": "00_core.ipynb",
"raw_dir": "00_core.ipynb",
"read_series_sample": "00_core.ipynb",
"melt_sales_series": "00_core.ipynb",
"extract_day_ids": "00_core.ipynb",
"join_w_calendar": "00_core.ipynb",
"join_w_prices": "00_core.ipynb",
"to_parquet": "00_core.ipynb",
"extract_id_columns": "00_core.ipynb",
"get_submission_template_melt": "00_core.ipynb",
"ParquetIterableDataset": "01_petastorm.ipynb",
"prepare_data_on_disk": "02_pipeline.ipynb"}
modules = ["core.py",
"petastorm.py",
"pipeline.py"]
doc_url = "https://cluePrints.github.io/kaggle-m5-nbdev/"
git_url = "https://github.com/cluePrints/kaggle-m5-nbdev/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'test_eq': '00_core.ipynb', 'listify': '00_core.ipynb', 'test_in': '00_core.ipynb', 'test_err': '00_core.ipynb', 'configure_logging': '00_core.ipynb', 'setup_dataframe_copy_logging': '00_core.ipynb', 'n_total_series': '00_core.ipynb', 'n_days_total': '00_core.ipynb', 'raw_dir': '00_core.ipynb', 'read_series_sample': '00_core.ipynb', 'melt_sales_series': '00_core.ipynb', 'extract_day_ids': '00_core.ipynb', 'join_w_calendar': '00_core.ipynb', 'join_w_prices': '00_core.ipynb', 'to_parquet': '00_core.ipynb', 'extract_id_columns': '00_core.ipynb', 'get_submission_template_melt': '00_core.ipynb', 'ParquetIterableDataset': '01_petastorm.ipynb', 'prepare_data_on_disk': '02_pipeline.ipynb'}
modules = ['core.py', 'petastorm.py', 'pipeline.py']
doc_url = 'https://cluePrints.github.io/kaggle-m5-nbdev/'
git_url = 'https://github.com/cluePrints/kaggle-m5-nbdev/tree/master/'
def custom_doc_links(name):
return None |
# code
'''python'''
class Solution(object):
def lengthOfLastWord(self, s):
self.s=s
string = self.s.strip().split(' ')[-1]
return len(string)
| """python"""
class Solution(object):
def length_of_last_word(self, s):
self.s = s
string = self.s.strip().split(' ')[-1]
return len(string) |
def clean_sentence(output, data_loader):
start_word = data_loader.dataset.vocab.start_word
end_word = data_loader.dataset.vocab.end_word
unk_word = data_loader.dataset.vocab.unk_word
words = []
for i in range(len(output)):
word_idx = output[i]
word = data_loader.dataset.vocab.idx2word.get(word_idx)
if word == end_word:
break
#elif word != start_word and word != unk_word:
elif word != unk_word:
words.append(word)
return " ".join(words)
| def clean_sentence(output, data_loader):
start_word = data_loader.dataset.vocab.start_word
end_word = data_loader.dataset.vocab.end_word
unk_word = data_loader.dataset.vocab.unk_word
words = []
for i in range(len(output)):
word_idx = output[i]
word = data_loader.dataset.vocab.idx2word.get(word_idx)
if word == end_word:
break
elif word != unk_word:
words.append(word)
return ' '.join(words) |
#
# PySNMP MIB module TPLINK-SSH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-SSH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:25:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Counter64, ModuleIdentity, iso, Gauge32, Unsigned32, IpAddress, Bits, Counter32, NotificationType, ObjectIdentity, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Counter64", "ModuleIdentity", "iso", "Gauge32", "Unsigned32", "IpAddress", "Bits", "Counter32", "NotificationType", "ObjectIdentity", "TimeTicks", "Integer32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
tplinkMgmt, = mibBuilder.importSymbols("TPLINK-MIB", "tplinkMgmt")
tplinkSshMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 11863, 6, 5))
tplinkSshMIB.setRevisions(('2012-12-13 09:30',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: tplinkSshMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: tplinkSshMIB.setLastUpdated('201212130930Z')
if mibBuilder.loadTexts: tplinkSshMIB.setOrganization('TPLINK')
if mibBuilder.loadTexts: tplinkSshMIB.setContactInfo('www.tplink.com.cn')
if mibBuilder.loadTexts: tplinkSshMIB.setDescription('Private MIB for SSH configuration.')
tplinkSshMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1))
tplinkSshNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 5, 2))
tpSshEnable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEnable.setStatus('current')
if mibBuilder.loadTexts: tpSshEnable.setDescription('0. disable 1. enable')
tpSshProtocolV1Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshProtocolV1Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshProtocolV1Enable.setDescription('0. disable 1. enable')
tpSshProtocolV2Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshProtocolV2Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshProtocolV2Enable.setDescription('0. disable 1. enable')
tpSshQuietPeriod = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 120))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshQuietPeriod.setStatus('current')
if mibBuilder.loadTexts: tpSshQuietPeriod.setDescription('quiet period(1-120 second)')
tpSshMaxConnections = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshMaxConnections.setStatus('current')
if mibBuilder.loadTexts: tpSshMaxConnections.setDescription('max connection(1-5)')
tpSshEncryptAlgAES128Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgAES128Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgAES128Enable.setDescription('0. disable 1. enable')
tpSshEncryptAlgAES192Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgAES192Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgAES192Enable.setDescription('0. disable 1. enable')
tpSshEncryptAlgAES256Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgAES256Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgAES256Enable.setDescription('0. disable 1. enable')
tpSshEncryptAlgBlowfishEnable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgBlowfishEnable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgBlowfishEnable.setDescription('0. disable 1. enable')
tpSshEncryptAlgCast128Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlgCast128Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlgCast128Enable.setDescription('0. disable 1. enable')
tpSshEncryptAlg3DESEnable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshEncryptAlg3DESEnable.setStatus('current')
if mibBuilder.loadTexts: tpSshEncryptAlg3DESEnable.setDescription('0. disable 1. enable')
tpSshInteAlgSHA1Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshInteAlgSHA1Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshInteAlgSHA1Enable.setDescription('0. disable 1. enable')
tpSshInteAlgMD5Enable = MibScalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpSshInteAlgMD5Enable.setStatus('current')
if mibBuilder.loadTexts: tpSshInteAlgMD5Enable.setDescription('0. disable 1. enable')
mibBuilder.exportSymbols("TPLINK-SSH-MIB", tpSshEncryptAlgCast128Enable=tpSshEncryptAlgCast128Enable, tplinkSshMIBObjects=tplinkSshMIBObjects, tpSshEncryptAlgBlowfishEnable=tpSshEncryptAlgBlowfishEnable, tpSshEncryptAlgAES128Enable=tpSshEncryptAlgAES128Enable, tpSshProtocolV2Enable=tpSshProtocolV2Enable, tpSshMaxConnections=tpSshMaxConnections, tpSshInteAlgMD5Enable=tpSshInteAlgMD5Enable, tpSshProtocolV1Enable=tpSshProtocolV1Enable, tpSshEncryptAlg3DESEnable=tpSshEncryptAlg3DESEnable, PYSNMP_MODULE_ID=tplinkSshMIB, tplinkSshNotifications=tplinkSshNotifications, tpSshInteAlgSHA1Enable=tpSshInteAlgSHA1Enable, tplinkSshMIB=tplinkSshMIB, tpSshEncryptAlgAES192Enable=tpSshEncryptAlgAES192Enable, tpSshEncryptAlgAES256Enable=tpSshEncryptAlgAES256Enable, tpSshEnable=tpSshEnable, tpSshQuietPeriod=tpSshQuietPeriod)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, counter64, module_identity, iso, gauge32, unsigned32, ip_address, bits, counter32, notification_type, object_identity, time_ticks, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'Counter64', 'ModuleIdentity', 'iso', 'Gauge32', 'Unsigned32', 'IpAddress', 'Bits', 'Counter32', 'NotificationType', 'ObjectIdentity', 'TimeTicks', 'Integer32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
(tplink_mgmt,) = mibBuilder.importSymbols('TPLINK-MIB', 'tplinkMgmt')
tplink_ssh_mib = module_identity((1, 3, 6, 1, 4, 1, 11863, 6, 5))
tplinkSshMIB.setRevisions(('2012-12-13 09:30',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
tplinkSshMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts:
tplinkSshMIB.setLastUpdated('201212130930Z')
if mibBuilder.loadTexts:
tplinkSshMIB.setOrganization('TPLINK')
if mibBuilder.loadTexts:
tplinkSshMIB.setContactInfo('www.tplink.com.cn')
if mibBuilder.loadTexts:
tplinkSshMIB.setDescription('Private MIB for SSH configuration.')
tplink_ssh_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1))
tplink_ssh_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 11863, 6, 5, 2))
tp_ssh_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshEnable.setStatus('current')
if mibBuilder.loadTexts:
tpSshEnable.setDescription('0. disable 1. enable')
tp_ssh_protocol_v1_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshProtocolV1Enable.setStatus('current')
if mibBuilder.loadTexts:
tpSshProtocolV1Enable.setDescription('0. disable 1. enable')
tp_ssh_protocol_v2_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshProtocolV2Enable.setStatus('current')
if mibBuilder.loadTexts:
tpSshProtocolV2Enable.setDescription('0. disable 1. enable')
tp_ssh_quiet_period = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(1, 120))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshQuietPeriod.setStatus('current')
if mibBuilder.loadTexts:
tpSshQuietPeriod.setDescription('quiet period(1-120 second)')
tp_ssh_max_connections = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 5))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshMaxConnections.setStatus('current')
if mibBuilder.loadTexts:
tpSshMaxConnections.setDescription('max connection(1-5)')
tp_ssh_encrypt_alg_aes128_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshEncryptAlgAES128Enable.setStatus('current')
if mibBuilder.loadTexts:
tpSshEncryptAlgAES128Enable.setDescription('0. disable 1. enable')
tp_ssh_encrypt_alg_aes192_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshEncryptAlgAES192Enable.setStatus('current')
if mibBuilder.loadTexts:
tpSshEncryptAlgAES192Enable.setDescription('0. disable 1. enable')
tp_ssh_encrypt_alg_aes256_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshEncryptAlgAES256Enable.setStatus('current')
if mibBuilder.loadTexts:
tpSshEncryptAlgAES256Enable.setDescription('0. disable 1. enable')
tp_ssh_encrypt_alg_blowfish_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshEncryptAlgBlowfishEnable.setStatus('current')
if mibBuilder.loadTexts:
tpSshEncryptAlgBlowfishEnable.setDescription('0. disable 1. enable')
tp_ssh_encrypt_alg_cast128_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshEncryptAlgCast128Enable.setStatus('current')
if mibBuilder.loadTexts:
tpSshEncryptAlgCast128Enable.setDescription('0. disable 1. enable')
tp_ssh_encrypt_alg3_des_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshEncryptAlg3DESEnable.setStatus('current')
if mibBuilder.loadTexts:
tpSshEncryptAlg3DESEnable.setDescription('0. disable 1. enable')
tp_ssh_inte_alg_sha1_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshInteAlgSHA1Enable.setStatus('current')
if mibBuilder.loadTexts:
tpSshInteAlgSHA1Enable.setDescription('0. disable 1. enable')
tp_ssh_inte_alg_md5_enable = mib_scalar((1, 3, 6, 1, 4, 1, 11863, 6, 5, 1, 13), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tpSshInteAlgMD5Enable.setStatus('current')
if mibBuilder.loadTexts:
tpSshInteAlgMD5Enable.setDescription('0. disable 1. enable')
mibBuilder.exportSymbols('TPLINK-SSH-MIB', tpSshEncryptAlgCast128Enable=tpSshEncryptAlgCast128Enable, tplinkSshMIBObjects=tplinkSshMIBObjects, tpSshEncryptAlgBlowfishEnable=tpSshEncryptAlgBlowfishEnable, tpSshEncryptAlgAES128Enable=tpSshEncryptAlgAES128Enable, tpSshProtocolV2Enable=tpSshProtocolV2Enable, tpSshMaxConnections=tpSshMaxConnections, tpSshInteAlgMD5Enable=tpSshInteAlgMD5Enable, tpSshProtocolV1Enable=tpSshProtocolV1Enable, tpSshEncryptAlg3DESEnable=tpSshEncryptAlg3DESEnable, PYSNMP_MODULE_ID=tplinkSshMIB, tplinkSshNotifications=tplinkSshNotifications, tpSshInteAlgSHA1Enable=tpSshInteAlgSHA1Enable, tplinkSshMIB=tplinkSshMIB, tpSshEncryptAlgAES192Enable=tpSshEncryptAlgAES192Enable, tpSshEncryptAlgAES256Enable=tpSshEncryptAlgAES256Enable, tpSshEnable=tpSshEnable, tpSshQuietPeriod=tpSshQuietPeriod) |
REGULAR_MARGIN_REQUIREMENT = 0.25
LEVERAGED_MARGIN_REQUIREMENT = 0.75
def max_margin(leveraged_value, regular_value, percentage_of_leveraged_drop,
percentage_of_regular_drop, current_loan):
leveraged_value_after_drop = leveraged_value * (1 - percentage_of_leveraged_drop)
regular_value_after_drop = regular_value * (1 - percentage_of_regular_drop)
leveraged_margin_impact = (1 - LEVERAGED_MARGIN_REQUIREMENT) * leveraged_value_after_drop
regular_margin_impact = (1 - REGULAR_MARGIN_REQUIREMENT) * regular_value_after_drop
return (leveraged_margin_impact + regular_margin_impact -
current_loan) / (1 - (1 - REGULAR_MARGIN_REQUIREMENT) *
(1 - percentage_of_regular_drop))
def main():
return max_margin(20000, 10000, 0.6, 0.5, 0)
if __name__ == '__main__':
print(main())
| regular_margin_requirement = 0.25
leveraged_margin_requirement = 0.75
def max_margin(leveraged_value, regular_value, percentage_of_leveraged_drop, percentage_of_regular_drop, current_loan):
leveraged_value_after_drop = leveraged_value * (1 - percentage_of_leveraged_drop)
regular_value_after_drop = regular_value * (1 - percentage_of_regular_drop)
leveraged_margin_impact = (1 - LEVERAGED_MARGIN_REQUIREMENT) * leveraged_value_after_drop
regular_margin_impact = (1 - REGULAR_MARGIN_REQUIREMENT) * regular_value_after_drop
return (leveraged_margin_impact + regular_margin_impact - current_loan) / (1 - (1 - REGULAR_MARGIN_REQUIREMENT) * (1 - percentage_of_regular_drop))
def main():
return max_margin(20000, 10000, 0.6, 0.5, 0)
if __name__ == '__main__':
print(main()) |
class Solution:
def __init__(self):
pass
# o(mn)
def print_lcs(self, str1, str2):
m = len(str1)
n = len(str2)
if n == 0 or m == 0:
return 0
# declare an two dimension array store calculated dp value of lcs(str1[i]
R = [[None] * (n + 1) for i in xrange(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
R[i][j] = 0
elif str1[i - 1] == str2[j - 1]:
R[i][j] = 1 + R[i - 1][j - 1]
else:
R[i][j] = max(R[i - 1][j], R[i][j - 1])
lcs = []
i = m
j = n
while i > 0 and j > 0:
if str1[i - 1] == str2[j - 1]:
lcs.insert(0, str1[i - 1])
i -= 1
j -= 1
elif R[i - 1][j] > R[i][j - 1]:
i -= 1
else:
j -= 1
return lcs
str1 = 'AGGTAB';
str2 = 'GXTXAYB';
# print(Solution().longest_sub_sequence(str1, str2, len(str1), len(str2)));
print(Solution().print_lcs(str1, str2))
| class Solution:
def __init__(self):
pass
def print_lcs(self, str1, str2):
m = len(str1)
n = len(str2)
if n == 0 or m == 0:
return 0
r = [[None] * (n + 1) for i in xrange(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
R[i][j] = 0
elif str1[i - 1] == str2[j - 1]:
R[i][j] = 1 + R[i - 1][j - 1]
else:
R[i][j] = max(R[i - 1][j], R[i][j - 1])
lcs = []
i = m
j = n
while i > 0 and j > 0:
if str1[i - 1] == str2[j - 1]:
lcs.insert(0, str1[i - 1])
i -= 1
j -= 1
elif R[i - 1][j] > R[i][j - 1]:
i -= 1
else:
j -= 1
return lcs
str1 = 'AGGTAB'
str2 = 'GXTXAYB'
print(solution().print_lcs(str1, str2)) |
lines = None
with open('day07/input.txt') as f:
lines = f.readlines()
line = lines[0]
arr = list(map(lambda s: int(s), line.split(",")))
cost = []
prev = 0
q = 0
for i in range(2000):
cost.append(prev + q)
prev = prev + q
q += 1
min = 99999999999999
for pos in range(1500):
sum = 0
for x in arr:
sum += cost[abs(x - pos)]
if sum < min: min = sum
print(min)
| lines = None
with open('day07/input.txt') as f:
lines = f.readlines()
line = lines[0]
arr = list(map(lambda s: int(s), line.split(',')))
cost = []
prev = 0
q = 0
for i in range(2000):
cost.append(prev + q)
prev = prev + q
q += 1
min = 99999999999999
for pos in range(1500):
sum = 0
for x in arr:
sum += cost[abs(x - pos)]
if sum < min:
min = sum
print(min) |
target = "xilinx"
action = "synthesis"
syn_device = "xc7k325t"
syn_grade = "-2"
syn_package = "ffg900"
syn_top = "cm0_busy_wait_top"
syn_project = "cm0_busy_wait_top"
syn_tool = "vivado"
modules = {
"local" : [ "../../../top/kc705_busy_wait/verilog" ],
}
| target = 'xilinx'
action = 'synthesis'
syn_device = 'xc7k325t'
syn_grade = '-2'
syn_package = 'ffg900'
syn_top = 'cm0_busy_wait_top'
syn_project = 'cm0_busy_wait_top'
syn_tool = 'vivado'
modules = {'local': ['../../../top/kc705_busy_wait/verilog']} |
class DataObject:
def __init__(self, read_data=True):
if read_data:
self._run_methods('read')
self._run_methods('parse')
def _run_methods(self, method_type):
for method in [m for m in dir(self) if m.startswith('_{}_'.format(method_type))]:
getattr(self, method)()
def get_data(self):
raise NotImplementedError
| class Dataobject:
def __init__(self, read_data=True):
if read_data:
self._run_methods('read')
self._run_methods('parse')
def _run_methods(self, method_type):
for method in [m for m in dir(self) if m.startswith('_{}_'.format(method_type))]:
getattr(self, method)()
def get_data(self):
raise NotImplementedError |
def sumUpNumbers(inputString):
numbers = []
curr = ""
for i in inputString:
try:
x = int(i)
curr += i
except:
if curr != "":
numbers.append(curr)
curr = ""
if curr != "":
numbers.append(curr)
return sum([int(x) for x in numbers])
| def sum_up_numbers(inputString):
numbers = []
curr = ''
for i in inputString:
try:
x = int(i)
curr += i
except:
if curr != '':
numbers.append(curr)
curr = ''
if curr != '':
numbers.append(curr)
return sum([int(x) for x in numbers]) |
#!/usr/bin/python3
def recsum(n): return n if n<=1 else n+recsum(n-1)
n = int(input("Enter your number\t"))
if n < 0:
print("Enter a positive number")
else:
print("The sum is",recsum(n)) | def recsum(n):
return n if n <= 1 else n + recsum(n - 1)
n = int(input('Enter your number\t'))
if n < 0:
print('Enter a positive number')
else:
print('The sum is', recsum(n)) |
raio = float(input())
pi = 3.14159
VOLUME = (4 / 3) * pi * (raio**3)
print("VOLUME = {:.3f}".format(VOLUME))
| raio = float(input())
pi = 3.14159
volume = 4 / 3 * pi * raio ** 3
print('VOLUME = {:.3f}'.format(VOLUME)) |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: proto
class AuthMethod(object):
ANONYMOUS = 0
COOKIE = 1
TLS = 2
TICKET = 3
CRA = 4
SCRAM = 5
CRYPTOSIGN = 6
| class Authmethod(object):
anonymous = 0
cookie = 1
tls = 2
ticket = 3
cra = 4
scram = 5
cryptosign = 6 |
def for_e():
for row in range(6):
for col in range(4):
if row==2 or row==1 and col%3!=0 or row==4 and col>0 or col==0 and row==3:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_e():
row=0
while row<6:
col=0
while col<4:
if row==2 or row==1 and col%3!=0 or row==4 and col>0 or col==0 and row==3:
print("*",end=" ")
else:
print(" ",end=" ")
col+=1
row+=1
print()
| def for_e():
for row in range(6):
for col in range(4):
if row == 2 or (row == 1 and col % 3 != 0) or (row == 4 and col > 0) or (col == 0 and row == 3):
print('*', end=' ')
else:
print(' ', end=' ')
print()
def while_e():
row = 0
while row < 6:
col = 0
while col < 4:
if row == 2 or (row == 1 and col % 3 != 0) or (row == 4 and col > 0) or (col == 0 and row == 3):
print('*', end=' ')
else:
print(' ', end=' ')
col += 1
row += 1
print() |
def selection_sort(elements):
for i in range(len(elements) - 1):
min_index = i
for j in range(i + 1, len(elements)):
if elements[min_index] > elements[j]:
min_index = j
elements[i], elements[min_index] = elements[min_index], elements[i]
return elements
ele = [23, 35, 6, 42, 1, 4, 6, 97, 10]
print(selection_sort(ele))
| def selection_sort(elements):
for i in range(len(elements) - 1):
min_index = i
for j in range(i + 1, len(elements)):
if elements[min_index] > elements[j]:
min_index = j
(elements[i], elements[min_index]) = (elements[min_index], elements[i])
return elements
ele = [23, 35, 6, 42, 1, 4, 6, 97, 10]
print(selection_sort(ele)) |
tab = 1
while tab <= 10:
print("Tabuada do", tab, ":", end="\t")
i = 1
while i <= 10:
print(tab*i, end = "\t")
i = i + 1
print()
tab = tab + 1 | tab = 1
while tab <= 10:
print('Tabuada do', tab, ':', end='\t')
i = 1
while i <= 10:
print(tab * i, end='\t')
i = i + 1
print()
tab = tab + 1 |
def chk_p5m(n):
if n%5==0: return 0
elif n==1: return n
for i in range(2,n):
if n%i==0:
return n
return 0
def fab(n):
f=[0,1]
return [chk_p5m((f:=[f[-1],f[-1]+f[-2]])[0]) for i in range(n)]
#i know it's little confusing most won't understand... but tried to do something unique
print(*fab(int(input())))
| def chk_p5m(n):
if n % 5 == 0:
return 0
elif n == 1:
return n
for i in range(2, n):
if n % i == 0:
return n
return 0
def fab(n):
f = [0, 1]
return [chk_p5m((f := [f[-1], f[-1] + f[-2]])[0]) for i in range(n)]
print(*fab(int(input()))) |
class Solution:
def largestValsFromLabels(self, values, labels, num_wanted, use_limit):
zipped = list(zip(values, labels))
_dict = {x: 0 for x in set(labels)}
ans = 0
for v, l in reversed(sorted(zipped)):
if num_wanted == 0:
return ans
if _dict[l] + 1 <= use_limit:
ans += v
num_wanted -= 1
_dict[l] += 1
return ans
| class Solution:
def largest_vals_from_labels(self, values, labels, num_wanted, use_limit):
zipped = list(zip(values, labels))
_dict = {x: 0 for x in set(labels)}
ans = 0
for (v, l) in reversed(sorted(zipped)):
if num_wanted == 0:
return ans
if _dict[l] + 1 <= use_limit:
ans += v
num_wanted -= 1
_dict[l] += 1
return ans |
class Human():
sum = 0
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
print(self.name)
def do_homework(self):
print('parent method') | class Human:
sum = 0
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
print(self.name)
def do_homework(self):
print('parent method') |
d = {
"no": "yes"
}
class CustomError:
def __init__(self, fun):
self.fun = fun
def __call__(self, *args, **kwargs):
try:
return self.fun(*args, **kwargs)
except Exception as e:
print(e)
raise Exception(d.get(str(e)))
@CustomError
def a():
raise Exception("no")
| d = {'no': 'yes'}
class Customerror:
def __init__(self, fun):
self.fun = fun
def __call__(self, *args, **kwargs):
try:
return self.fun(*args, **kwargs)
except Exception as e:
print(e)
raise exception(d.get(str(e)))
@CustomError
def a():
raise exception('no') |
# Databricks notebook source
# MAGIC %md
# MAGIC <img src="https://github.com/billkellett/flight-school-resources/blob/master/images/databricks icon.png?raw=true" width=100/>
# MAGIC <img src="/files/flight/Megacorp.png?raw=true" width=200/>
# MAGIC # Democratizing MegaCorp's Data
# MAGIC
# MAGIC ## MegaCorp's current challenges
# MAGIC <ul>
# MAGIC <li/>Hard to manage and scale infrastructure
# MAGIC <li/>Multiple sources of truth because of siloed data
# MAGIC <li/>Data Management and Data quality issues
# MAGIC <li/>Sub-optimal performance
# MAGIC <li/>Limited collaboration between teams
# MAGIC </ul>
# COMMAND ----------
# MAGIC %md
# MAGIC ##Databricks can help!
# MAGIC ####A unified Simple, Open, Collaborative Platform for your BI to AI needs
# MAGIC
# MAGIC <img src="https://databricks.com/wp-content/uploads/2021/10/Databricks-lakehouse-platform-2.png" width=600>
# MAGIC <img src="https://databricks.com/wp-content/uploads/2021/09/Platform-image-4.svg">
# COMMAND ----------
# This creates the "team_name" field displayed at the top of the notebook.
dbutils.widgets.text("team_name", "Enter your team's name")
# COMMAND ----------
# Note that we have factored out the setup processing into a different notebook, which we call here.
# As a flight school student, you will probably want to look at the setup notebook.
# Even though you'll want to look at it, we separated it out in order to demonstrate a best practice...
# ... you can use this technique to keep your demos shorter, and avoid boring your audience with housekeeping.
# In addition, you can save demo time by running this initial setup command before you begin your demo.
# This cell should run in a few minutes or less
team_name = dbutils.widgets.get("team_name")
setup_responses = dbutils.notebook.run("./includes/flight_school_assignment_1_setup", 0, {"team_name": team_name}).split()
local_data_path = setup_responses[0]
dbfs_data_path = setup_responses[1]
database_name = setup_responses[2]
print(f"Path to be used for Local Files: {local_data_path}")
print(f"Path to be used for DBFS Files: {dbfs_data_path}")
print(f"Database Name: {database_name}")
# COMMAND ----------
# Let's set the default database name so we don't have to specify it on every query
spark.sql(f"USE {database_name}")
# COMMAND ----------
# MAGIC %md
# MAGIC
# MAGIC #### Let's talk Databricks' Delta Lake
# MAGIC
# MAGIC #####Delta lake is an open-source project that enables building a Lakehouse Architecture on top of existing storage systems such as S3, ADLS, GCS, and HDFS.
# MAGIC
# MAGIC Delta Lake brings __*Performance*__ and __*Reliability*__ to Data Lakes
# MAGIC
# MAGIC Why did Delta Lake have to be invented? Let's take a look...
# MAGIC
# MAGIC <img src="https://github.com/billkellett/flight-school-resources/blob/master/images/projects_failing.png?raw=true" width=1000/>
# MAGIC
# MAGIC As the graphic above shows, Big Data Lake projects have a very high failure rate. In fact, Gartner Group estimates that 85% of these projects fail (see https://www.infoworld.com/article/3393467/4-reasons-big-data-projects-failand-4-ways-to-succeed.html ). *Why* is the failure rate so high?
# MAGIC
# MAGIC <img src="https://github.com/billkellett/flight-school-resources/blob/master/images/projects_failing_reasons.png?raw=true" width=1000/>
# MAGIC
# MAGIC The graphic above shows the main __*reliability*__ issues with data lakes. Unlike relational databases, typical data lakes are not capable of transactional (ACID) behavior. This leads to a number of reliability issues:
# MAGIC
# MAGIC - When a job fails, incomplete work is not rolled back, as it would be in a relational database. Data may be left in an inconsistent state. This issue is extremely difficult to deal with in production.
# MAGIC
# MAGIC - Data lakes typically cannot enforce schema. This is often touted as a "feature" called "schema-on-read," because it allows flexibility at data ingest time. However, when downstream jobs fail trying to read corrupt data, we have a very difficult recovery problem. It is often difficult just to find the source application that caused the problem... which makes fixing the problem even harder!
# MAGIC
# MAGIC - Relational databases allow multiple concurrent users, and ensure that each user gets a consistent view of data. Half-completed transactions never show up in the result sets of other concurrent users. This is not true in a typical data lake. Therefore, it is almost impossible to have a concurrent mix of read jobs and write jobs. This becomes an even bigger problem with streaming data, because streams typically don't pause to let other jobs run!
# MAGIC
# MAGIC Next, let's look at the key __*performance issues*__ with data lakes...
# MAGIC
# MAGIC <img src="https://github.com/billkellett/flight-school-resources/blob/master/images/projects_failing_reasons_1.png?raw=true" width=1000/>
# MAGIC
# MAGIC - We have already noted that data lakes cannot provide a consistent view of data to concurrent users. This is a reliability problem, but it is also a __*performance*__ problem because if we must run jobs one at a time, our production time window becomes extremely limited.
# MAGIC
# MAGIC - Most data lake engineers have come face-to-face with the "small-file problem." Data is typically ingested into a data lake in batches. Each batch typically becomes a separate physical file in a directory that defines a table in the lake. Over time, the number of physical files can grow to be very large. When this happens, performance suffers because opening and closing these files is a time-consuming operation.
# MAGIC
# MAGIC - Experienced relational database architects may be surprised to learn that Big Data usually cannot be indexed in the same way as relational databases. The indexes become too large to be manageable and performant. Instead, we "partition" data by putting it into sub-directories. Each partition can represent a column (or a composite set of columns) in the table. This lets us avoid scanning the entire data set... *if* our queries are based on the partition column. However, in the real world, analysts are running a wide range of queries which may or may not be based on the partition column. In these scenarios, there is no benefit to partitioning. In addition, partitioning breaks down if we choose a partition column with extremely high cardinality.
# MAGIC
# MAGIC - Data lakes typically live in cloud storage (e.g., S3 on AWS, ADLS on Azure), and these storage devices are quite slow compared to SSD disk drives. Most data lakes have no capability to cache data on faster devices, and this fact has a major impact on performance.
# MAGIC
# MAGIC __*Delta Lake was built to solve these reliability and performance problems.*__ First, let's consider how Delta Lake addresses *reliability* issues...
# MAGIC
# MAGIC <img src="https://github.com/billkellett/flight-school-resources/blob/master/images/delta_reliability.png?raw=true" width=1000/>
# MAGIC
# MAGIC Note the Key Features in the graphic above. We'll be diving into all of these capabilities as we go through the Workshop:
# MAGIC
# MAGIC - __ACID Transactions:__ Delta Lake ACID compliance ensures that half-completed transactions are never persisted in the Lake, and concurrent users never see other users' in-flight transactions.
# MAGIC
# MAGIC - __Mutations:__ Experienced relational database architects may be surprised to learn that most data lakes do not support updates and deletes. These lakes concern themselves only with data ingest, which makes error correction and backfill very difficult. In contrast, Delta Lake provides full support for Inserts, Updates, and Deletes.
# MAGIC
# MAGIC - __Schema Enforcement:__ Delta Lake provides full support for schema enforcement at write time, greatly increasing data reliability.
# MAGIC
# MAGIC - __Unified Batch and Streaming:__ Streaming data is becoming an essential capability for all enterprises. We'll see how Delta Lake supports both batch and streaming modes, and in fact blurs the line between them, enabling architects to design systems that use both batch and streaming capabilities simultaneously.
# MAGIC
# MAGIC - __Time Travel:__ unlike most data lakes, Delta Lake enables queries of data *as it existed* at a specific point in time. This has important ramifications for reliability, error recovery, and synchronization with other systems, as we shall see later in this Workshop.
# MAGIC
# MAGIC We have seen how Delta Lake enhances reliability. Next, let's see how Delta Lake optimizes __*performance*__...
# MAGIC
# MAGIC <img src="https://github.com/billkellett/flight-school-resources/blob/master/images/delta_performance.png?raw=true" width=1000/>
# MAGIC
# MAGIC Again, we'll be diving into all these capabilities throughout the Workshop. We'll be concentrating especially on features that are only available in Databricks' distribution of Delta Lake...
# MAGIC
# MAGIC - __Compaction:__ Delta Lake provides sophisticated capabilities to solve the "small-file problem" by compacting small files into larger units.
# MAGIC
# MAGIC - __Caching:__ Delta Lake transparently caches data on the SSD drives of worker nodes in a Spark cluster, greatly improving performance.
# MAGIC
# MAGIC - __Data Skipping:__ this Delta Lake feature goes far beyond the limits of mere partitioning.
# MAGIC
# MAGIC - __Z-Ordering:__ this is a brilliant alternative to traditional indexing, and further enhances Delta Lake performance.
# COMMAND ----------
# MAGIC %md
# MAGIC <img src="/files/flight/Proposed_Architecture.png?raw=true" width=1200/>
# COMMAND ----------
# Read the downloaded historical data into a dataframe
# This is MegaCorp data regarding power plant device performance. It pre-dates our new IOT effort, but we want to save this data and use it in queries.
dataPath = f"dbfs:/FileStore/flight/{team_name}/assignment_1_ingest.csv"
df = spark.read.option("header","true").option("inferSchema","true").csv(dataPath)
#display(df)
# Read the downloaded backfill data into a dataframe
# This is some backfill data that we'll need to merge into the main historical data.
backfillDataPath = f"dbfs:/FileStore/flight/{team_name}/assignment_1_backfill.csv"
df_backfill = spark.read.option("header","true").option("inferSchema","true").csv(backfillDataPath)
#display(df_backfill)
# Create a temporary view on the dataframes to enable SQL
df.createOrReplaceTempView("historical_bronze_vw")
df_backfill.createOrReplaceTempView("historical_bronze_backfill_vw")
# COMMAND ----------
# MAGIC %sql
# MAGIC
# MAGIC -- Create a Delta Lake table for the main bronze table
# MAGIC
# MAGIC DROP TABLE IF EXISTS sensor_readings_historical_bronze;
# MAGIC
# MAGIC CREATE TABLE sensor_readings_historical_bronze
# MAGIC AS SELECT * FROM historical_bronze_vw;
# COMMAND ----------
# MAGIC %sql
# MAGIC
# MAGIC -- Let's take a peek at our new bronze table
# MAGIC
# MAGIC SELECT * FROM sensor_readings_historical_bronze
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's count the records in the Bronze table
# MAGIC
# MAGIC SELECT COUNT(*) FROM sensor_readings_historical_bronze
# COMMAND ----------
# MAGIC %sql
# MAGIC
# MAGIC -- Analysing data? No problem! Let's take a look
# MAGIC
# MAGIC SELECT
# MAGIC count(*) as count, device_operational_status
# MAGIC FROM sensor_readings_historical_bronze
# MAGIC GROUP BY device_operational_status
# MAGIC ORDER BY count asc;
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Now let's make a query that accepts run-time parameters.
# MAGIC -- NOTE that we have set default values so that a default query will return results on this data
# MAGIC
# MAGIC CREATE WIDGET DROPDOWN PARAM_END_SECOND
# MAGIC DEFAULT '57'
# MAGIC CHOICES SELECT DISTINCT SECOND(reading_time) AS end_second FROM sensor_readings_historical_bronze ORDER BY end_second ASC;
# MAGIC CREATE WIDGET DROPDOWN PARAM_START_SECOND
# MAGIC DEFAULT '54'
# MAGIC CHOICES SELECT DISTINCT SECOND(reading_time) AS start_second FROM sensor_readings_historical_bronze ORDER BY start_second ASC;
# MAGIC CREATE WIDGET DROPDOWN PARAM_MINUTE
# MAGIC DEFAULT '18'
# MAGIC CHOICES SELECT DISTINCT MINUTE(reading_time) AS minute FROM sensor_readings_historical_bronze ORDER BY minute ASC;
# MAGIC CREATE WIDGET DROPDOWN PARAM_HOUR
# MAGIC DEFAULT '10'
# MAGIC CHOICES SELECT DISTINCT HOUR(reading_time) AS hour FROM sensor_readings_historical_bronze ORDER BY hour ASC;
# MAGIC CREATE WIDGET DROPDOWN PARAM_DAY
# MAGIC DEFAULT '23'
# MAGIC CHOICES SELECT DISTINCT DAY(reading_time) AS day FROM sensor_readings_historical_bronze ORDER BY day ASC;
# MAGIC CREATE WIDGET DROPDOWN PARAM_MONTH
# MAGIC DEFAULT '2'
# MAGIC CHOICES SELECT DISTINCT MONTH(reading_time) AS month FROM sensor_readings_historical_bronze ORDER BY month ASC;
# MAGIC CREATE WIDGET DROPDOWN PARAM_YEAR
# MAGIC DEFAULT '2015'
# MAGIC CHOICES SELECT DISTINCT YEAR(reading_time) AS year FROM sensor_readings_historical_bronze ORDER BY year ASC;
# MAGIC CREATE WIDGET DROPDOWN PARAM_DEVICE_ID
# MAGIC DEFAULT '7G007R'
# MAGIC CHOICES SELECT DISTINCT device_id FROM sensor_readings_historical_bronze ORDER BY device_id ASC;
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's make a query that shows another meaningful graphical view of the table
# MAGIC -- We'll parameterize this query so a Business Analyst can examine fine-grained device performance issues
# MAGIC -- Experiment with different graphical views
# MAGIC
# MAGIC SELECT
# MAGIC reading_time,
# MAGIC reading_1,
# MAGIC reading_2,
# MAGIC reading_3
# MAGIC FROM sensor_readings_historical_bronze
# MAGIC WHERE
# MAGIC device_id = getArgument("PARAM_DEVICE_ID")
# MAGIC AND
# MAGIC YEAR(reading_time) = getArgument("PARAM_YEAR")
# MAGIC AND
# MAGIC MONTH(reading_time) = getArgument("PARAM_MONTH")
# MAGIC AND
# MAGIC DAY(reading_time) = getArgument("PARAM_DAY")
# MAGIC AND
# MAGIC HOUR(reading_time) = getArgument("PARAM_HOUR")
# MAGIC AND
# MAGIC MINUTE(reading_time) = getArgument("PARAM_MINUTE")
# MAGIC AND
# MAGIC SECOND(reading_time) BETWEEN getArgument("PARAM_START_SECOND")
# MAGIC AND getArgument("PARAM_END_SECOND")
# MAGIC ORDER BY reading_time ASC
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's clean up that messy collection of widgets!
# MAGIC
# MAGIC REMOVE WIDGET PARAM_DEVICE_ID;
# MAGIC REMOVE WIDGET PARAM_YEAR;
# MAGIC REMOVE WIDGET PARAM_MONTH;
# MAGIC REMOVE WIDGET PARAM_DAY;
# MAGIC REMOVE WIDGET PARAM_HOUR;
# MAGIC REMOVE WIDGET PARAM_MINUTE;
# MAGIC REMOVE WIDGET PARAM_START_SECOND;
# MAGIC REMOVE WIDGET PARAM_END_SECOND;
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's take a peek at the backfill data
# MAGIC
# MAGIC SELECT * FROM historical_bronze_backfill_vw
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's count the records in the backfill data
# MAGIC
# MAGIC SELECT COUNT(*) FROM historical_bronze_backfill_vw
# COMMAND ----------
# MAGIC %md
# MAGIC <img src="https://docs.delta.io/latest/_static/delta-lake-logo.png" width=300>
# MAGIC
# MAGIC ## Let's talk Medallion Architecture an how it can help ensuring data quality
# MAGIC <img src="https://databricks.com/wp-content/uploads/2021/05/Bronze-Silver-Gold-Tables.png" width=600>
# MAGIC
# MAGIC
# MAGIC
# MAGIC MegaCorp has informed us that the Bronze historical data has a few issues. Let's deal with them and create a clean Silver table.
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's create a Silver table. We'll start with the Bronze data, then make several improvements
# MAGIC
# MAGIC DROP TABLE IF EXISTS sensor_readings_historical_silver;
# MAGIC
# MAGIC CREATE TABLE sensor_readings_historical_silver
# MAGIC AS SELECT * FROM historical_bronze_vw;
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's take a peek at our new Silver table
# MAGIC
# MAGIC SELECT * FROM sensor_readings_historical_silver
# MAGIC ORDER BY reading_time ASC
# COMMAND ----------
# MAGIC %md
# MAGIC #### Let's rectify the bad sensor readings in our data
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's merge in the Bronze backfill data
# MAGIC -- MERGE INTO is one of the most important differentiators for Delta Lake
# MAGIC -- The entire backfill batch will be treated as an atomic transaction,
# MAGIC -- and we can do both inserts and updates within a single batch.
# MAGIC
# MAGIC MERGE INTO sensor_readings_historical_silver AS h
# MAGIC USING historical_bronze_backfill_vw AS b
# MAGIC ON
# MAGIC h.id = b.id
# MAGIC WHEN MATCHED THEN UPDATE SET *
# MAGIC WHEN NOT MATCHED THEN INSERT *;
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Verify that the upserts worked correctly.
# MAGIC -- Newly inserted records have dates of 2015-02-21 (and id value beginning with 'ZZZ')
# MAGIC -- Updated records have id's in the backfill data that do NOT begin with 'ZZZ'.
# MAGIC -- Check a few of these, and make sure that a tiny value was added to reading_1.
# MAGIC -- In order to check, you might try something similar to...
# MAGIC -- %sql
# MAGIC select a.id, a.reading_1 as reading_1_silver, b.reading_1 as reading_1_bronze
# MAGIC from sensor_readings_historical_silver a
# MAGIC inner join sensor_readings_historical_bronze b
# MAGIC on a.id = b.id
# MAGIC where a.reading_1 <> b.reading_1
# COMMAND ----------
# MAGIC %sql
# MAGIC -- MegaCorp just informed us of some dirty data. Occasionally they would receive garbled data.
# MAGIC -- In those cases, they would put 999.99 in the readings.
# MAGIC -- Let's find these records
# MAGIC
# MAGIC SELECT *
# MAGIC FROM sensor_readings_historical_silver
# MAGIC WHERE reading_1 = 999.99
# COMMAND ----------
# MAGIC %sql
# MAGIC -- We want to fix these bogus readings. Here's the idea...
# MAGIC -- - Use a SQL window function to order the readings by time within each device
# MAGIC -- - Whenever there is a 999.99 reading, replace it with the AVERAGE of the PREVIOUS and FOLLOWING readings.
# MAGIC -- HINTS:
# MAGIC -- Window functions use an "OVER" clause... OVER (PARTITION BY ... ORDER BY )
# MAGIC -- Look up the doc for SQL functions LAG() and LEAD()
# MAGIC
# MAGIC -- We'll create a table of these interpolated readings, then later we'll merge it into the Silver table.
# MAGIC
# MAGIC DROP TABLE IF EXISTS sensor_readings_historical_interpolations;
# MAGIC
# MAGIC CREATE TABLE sensor_readings_historical_interpolations AS (
# MAGIC WITH lags_and_leads AS (
# MAGIC SELECT
# MAGIC id,
# MAGIC reading_time,
# MAGIC device_type,
# MAGIC device_id,
# MAGIC device_operational_status,
# MAGIC reading_1,
# MAGIC LAG(reading_1, 1, 0) OVER (PARTITION BY device_id ORDER BY reading_time ASC, id ASC) AS reading_1_lag,
# MAGIC LEAD(reading_1, 1, 0) OVER (PARTITION BY device_id ORDER BY reading_time ASC, id ASC) AS reading_1_lead,
# MAGIC reading_2,
# MAGIC LAG(reading_2, 1, 0) OVER (PARTITION BY device_id ORDER BY reading_time ASC, id ASC) AS reading_2_lag,
# MAGIC LEAD(reading_2, 1, 0) OVER (PARTITION BY device_id ORDER BY reading_time ASC, id ASC) AS reading_2_lead,
# MAGIC reading_3,
# MAGIC LAG(reading_3, 1, 0) OVER (PARTITION BY device_id ORDER BY reading_time ASC, id ASC) AS reading_3_lag,
# MAGIC LEAD(reading_3, 1, 0) OVER (PARTITION BY device_id ORDER BY reading_time ASC, id ASC) AS reading_3_lead
# MAGIC FROM sensor_readings_historical_silver
# MAGIC )
# MAGIC SELECT
# MAGIC id,
# MAGIC reading_time,
# MAGIC device_type,
# MAGIC device_id,
# MAGIC device_operational_status,
# MAGIC ((reading_1_lag + reading_1_lead) / 2) AS reading_1,
# MAGIC ((reading_2_lag + reading_2_lead) / 2) AS reading_2,
# MAGIC ((reading_3_lag + reading_3_lead) / 2) AS reading_3
# MAGIC FROM lags_and_leads
# MAGIC WHERE reading_1 = 999.99
# MAGIC ORDER BY id ASC
# MAGIC )
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's see how many interpolations we have. There should be 367 rows.
# MAGIC
# MAGIC SELECT COUNT(*) FROM sensor_readings_historical_interpolations
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Now use MERGE INTO to update the historical table
# MAGIC MERGE INTO sensor_readings_historical_silver AS s
# MAGIC USING sensor_readings_historical_interpolations AS i
# MAGIC ON
# MAGIC s.id = i.id
# MAGIC WHEN MATCHED THEN UPDATE SET *
# MAGIC WHEN NOT MATCHED THEN INSERT *;
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Now make sure we got rid of all the bogus readings.
# MAGIC -- Gee, this is fast. Why? What feature in Delta Lake is making this so speedy?
# MAGIC
# MAGIC SELECT count(*)
# MAGIC FROM sensor_readings_historical_silver
# MAGIC WHERE reading_1 = 999.99
# COMMAND ----------
# MAGIC %md
# MAGIC <img src="https://docs.delta.io/latest/_static/delta-lake-logo.png" width=300>
# MAGIC ####Time Travel - Go back to the last known stable state of your data
# COMMAND ----------
# MAGIC %sql
# MAGIC -- List all the versions of the table that are available to us
# MAGIC
# MAGIC DESCRIBE HISTORY sensor_readings_historical_silver
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Ah, version 1 should have the 999.99 values
# MAGIC
# MAGIC SELECT
# MAGIC *
# MAGIC FROM
# MAGIC sensor_readings_historical_silver
# MAGIC VERSION
# MAGIC AS OF 1
# MAGIC WHERE
# MAGIC reading_1 = 999.99;
# COMMAND ----------
dbutils.fs.help()
# COMMAND ----------
dbutils.fs.head(f"dbfs:/FileStore/flight/{team_name}/assignment_1_ingest.csv")
# COMMAND ----------
# MAGIC %md
# MAGIC <img src="https://docs.delta.io/latest/_static/delta-lake-logo.png" width=300>
# MAGIC ###Handling Schema Evolution
# COMMAND ----------
# Read the downloaded historical data into a dataframe
# This is MegaCorp data regarding power plant device performance. It pre-dates our new IOT effort, but we want to save this data and use it in queries.
dataPath = f"dbfs:/FileStore/flight/{team_name}/sensor_new_schema.csv"
df = spark.read.option("header","true").option("inferSchema","true").csv(dataPath)
display(df)
# Create a temporary view on the dataframes to enable SQL
df.createOrReplaceTempView("new_schema_bronze_vw")
# COMMAND ----------
# MAGIC %sql
# MAGIC INSERT INTO sensor_readings_historical_bronze
# MAGIC SELECT
# MAGIC *
# MAGIC FROM
# MAGIC new_schema_bronze_vw;
# COMMAND ----------
# MAGIC %sql
# MAGIC set spark.databricks.delta.schema.autoMerge.enabled=true;
# MAGIC
# MAGIC INSERT INTO sensor_readings_historical_bronze
# MAGIC SELECT
# MAGIC *
# MAGIC FROM
# MAGIC new_schema_bronze_vw;
# COMMAND ----------
# MAGIC %sql
# MAGIC SELECT
# MAGIC *
# MAGIC FROM
# MAGIC sensor_readings_historical_bronze
# MAGIC WHERE
# MAGIC reading_4 IS NOT NULL;
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Here is an example of a Gold table
# MAGIC DROP TABLE IF EXISTS sensor_readings_historical_gold_stats;
# MAGIC
# MAGIC CREATE TABLE sensor_readings_historical_gold_stats AS
# MAGIC SELECT
# MAGIC device_id
# MAGIC , avg(reading_1) as avg_1
# MAGIC , avg(reading_2) as avg_2
# MAGIC , avg(reading_3) as avg_3
# MAGIC , min(reading_1) as min_1
# MAGIC , min(reading_2) as min_2
# MAGIC , min(reading_3) as min_3
# MAGIC , max(reading_1) as max_1
# MAGIC , max(reading_2) as max_2
# MAGIC , max(reading_3) as max_3
# MAGIC FROM
# MAGIC sensor_readings_historical_silver
# MAGIC GROUP BY
# MAGIC device_id
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Range of sensor readings: minimum, maximum, and the average.
# MAGIC SELECT
# MAGIC device_id
# MAGIC , min_1
# MAGIC , max_1
# MAGIC , avg_1
# MAGIC , min_2
# MAGIC , max_2
# MAGIC , avg_2
# MAGIC , min_3
# MAGIC , max_3
# MAGIC , avg_3
# MAGIC FROM
# MAGIC sensor_readings_historical_gold_stats
# COMMAND ----------
# MAGIC %md
# MAGIC <img src="https://databricks.com/wp-content/uploads/2021/08/photon-icon.svg">
# MAGIC ###All that is great! But what about performance??
# MAGIC #### Databricks' Runtime has been consistently benchmarked order of magnitude faster comapred to OSS and other verdors' Spark as well as various other offerings
# MAGIC #### Photon take the performance to next level
# MAGIC
# MAGIC Please see the following link for further details.
# MAGIC https://databricks.com/product/photon
# MAGIC https://databricks.com/blog/2017/07/12/benchmarking-big-data-sql-platforms-in-the-cloud.html
# MAGIC https://databricks.com/blog/2021/11/02/databricks-sets-official-data-warehousing-performance-record.html
# MAGIC https://pages.databricks.com/Benchmarking-Big-Data-Platforms.html
# COMMAND ----------
# MAGIC %md
# MAGIC <img src="https://docs.delta.io/latest/_static/delta-lake-logo.png" width=300>
# MAGIC ####Delta Lake features for enhanced performance
# MAGIC
# MAGIC Let's begin with __*partition*__
# COMMAND ----------
# MAGIC %sql
# MAGIC -- DESCRIBE EXTENDED will give us some partition information, and will also tell us the location of the data
# MAGIC -- Hmmm, looks like we are not partitioned. What does that mean?
# MAGIC
# MAGIC DESCRIBE EXTENDED sensor_readings_historical_silver
# COMMAND ----------
# Let's look at the physical file layout in a non-partitioned table
dbutils.fs.ls(f"dbfs:/user/hive/warehouse/{database_name}.db/sensor_readings_historical_silver")
# As you can see, the data is just broken into a set of files, without regard to the meaning of the data
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's create a Silver table partitioned by Device.
# MAGIC -- Create a new table, so we can compare new and old
# MAGIC
# MAGIC DROP TABLE IF EXISTS sensor_readings_historical_silver_by_device;
# MAGIC
# MAGIC CREATE TABLE sensor_readings_historical_silver_by_device
# MAGIC PARTITIONED BY (device_id)
# MAGIC AS SELECT * FROM sensor_readings_historical_silver
# COMMAND ----------
# MAGIC %sql
# MAGIC -- We can see partition information
# MAGIC
# MAGIC DESCRIBE EXTENDED sensor_readings_historical_silver_by_device
# COMMAND ----------
# Now we have subdirectories for each device, with physical files inside them
# Will that speed up queries?
dbutils.fs.ls(f"dbfs:/user/hive/warehouse/{database_name}.db/sensor_readings_historical_silver_by_device")
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's create a Silver table partitioned by BOTH Date AND Hour.
# MAGIC -- Note that Delta cannot partition by expressions, so I have to explicitly create the partition columns
# MAGIC -- HINT: Use the DATE() function to extract date from a timestamp, and use the HOUR() function to extract hour from a timestamp
# MAGIC
# MAGIC DROP TABLE IF EXISTS sensor_readings_historical_silver_by_hour;
# MAGIC
# MAGIC CREATE TABLE sensor_readings_historical_silver_by_hour
# MAGIC PARTITIONED BY (reading_date, reading_hour)
# MAGIC AS SELECT
# MAGIC *
# MAGIC , DATE(reading_time) as reading_date
# MAGIC , HOUR(reading_time) as reading_hour
# MAGIC FROM
# MAGIC sensor_readings_historical_silver
# COMMAND ----------
# NOTE how the hour directories are nested within the date directories
dbutils.fs.ls(f"dbfs:/user/hive/warehouse/{database_name}.db/sensor_readings_historical_silver_by_hour/reading_date=2015-02-24")
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's create a Silver table partitioned by Date AND Hour AND Minute.
# MAGIC -- Note that Delta cannot partition by expressions, so I have to explicitly create the partition columns
# MAGIC
# MAGIC DROP TABLE IF EXISTS sensor_readings_historical_silver_by_hour_and_minute;
# MAGIC
# MAGIC CREATE TABLE sensor_readings_historical_silver_by_hour_and_minute
# MAGIC PARTITIONED BY (reading_date, reading_hour, reading_minute)
# MAGIC AS
# MAGIC SELECT
# MAGIC *
# MAGIC , DATE(reading_time) as reading_date
# MAGIC , HOUR(reading_time) as reading_hour
# MAGIC , MINUTE(reading_time) as reading_minute
# MAGIC FROM
# MAGIC sensor_readings_historical_silver
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Let's take a peek at our minute-partitioned table
# MAGIC
# MAGIC SELECT
# MAGIC *
# MAGIC FROM
# MAGIC sensor_readings_historical_silver_by_hour_and_minute
# MAGIC LIMIT 100
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Now let's take some timings that compare our partitioned Silver tables against the unpartitioned Silver table
# MAGIC -- Here is an example "baseline" query against the unpartitioned Silver table
# MAGIC -- (run these queries several times to get a rough average)
# MAGIC
# MAGIC SELECT
# MAGIC *
# MAGIC FROM
# MAGIC sensor_readings_historical_silver
# MAGIC WHERE
# MAGIC DATE(reading_time) = '2015-02-24'
# MAGIC AND HOUR(reading_time) = '14'
# MAGIC AND MINUTE(reading_time) = '2'
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Now compare the time for the same query against a partitioned table
# MAGIC -- Think and discuss... Did both data skipping and partitioning play a part here? How could you combine data skipping and partitioning to make queries even more performant?
# MAGIC
# MAGIC SELECT
# MAGIC *
# MAGIC FROM
# MAGIC sensor_readings_historical_silver_by_hour_and_minute
# MAGIC WHERE
# MAGIC reading_date = '2015-02-24'
# MAGIC AND reading_hour = '14'
# MAGIC AND reading_minute = '2'
# COMMAND ----------
# MAGIC %md
# MAGIC
# MAGIC <img src="https://docs.delta.io/latest/_static/delta-lake-logo.png" width=300>
# MAGIC ####Delta Lake Caching
# COMMAND ----------
# MAGIC %sql
# MAGIC CACHE SELECT * FROM sensor_readings_historical_silver
# COMMAND ----------
# MAGIC %md
# MAGIC #Delta Live Tables
# MAGIC ##Reliable data engineering made easy
# MAGIC
# MAGIC Delta Live Tables (DLT) makes it easy to build and manage reliable data pipelines that deliver high quality data on Delta Lake. DLT helps data engineering teams simplify ETL development and management with declarative pipeline development, automatic data testing, and deep visibility for monitoring and recovery.
# MAGIC
# MAGIC Here's what Delta Live Tables do for you.
# MAGIC
# MAGIC ###More easily build and maintain data pipelines</li>
# MAGIC <img src="https://databricks.com/wp-content/uploads/2021/09/Live-Tables-Pipeline.png">
# MAGIC
# MAGIC ---
# MAGIC ###Automatic Testing
# MAGIC <img src="https://databricks.com/wp-content/uploads/2021/05/Bronze-Silver-Gold-Tables.png">
# MAGIC
# MAGIC ---
# MAGIC ###Deep visibility for monitoring and easy recovery
# MAGIC <img src="https://databricks.com/wp-content/uploads/2021/05/Pipeline-Graph.png">
# COMMAND ----------
# MAGIC %md
# MAGIC
# MAGIC <img src="https://docs.delta.io/latest/_static/delta-lake-logo.png" width=300>
# MAGIC Read more about Delta Lake - https://delta.io/
# MAGIC Read more about Delta Live Tables - https://databricks.com/product/delta-live-tables
# MAGIC Read more about Caching - https://docs.databricks.com/delta/optimizations/delta-cache.html
# MAGIC Read more about ZOrdering - https://docs.databricks.com/delta/optimizations/file-mgmt.html
# COMMAND ----------
# MAGIC %sql
# MAGIC drop table if exists dummy1;
# MAGIC create table dummy1 as select * from sensor_readings_historical_bronze limit 5;
# COMMAND ----------
# MAGIC %sql
# MAGIC describe history dummy1
# COMMAND ----------
dbutils.fs.ls(f"dbfs:/user/hive/warehouse/dummy1")
# COMMAND ----------
# MAGIC %sql
# MAGIC select * from dummy1 version as of 17
# COMMAND ----------
# MAGIC %sql
# MAGIC DESCRIBE HISTORY DUMMY1
# COMMAND ----------
# MAGIC %sql
# MAGIC alter table dummy1 set tblproperties(delta.logRetentionDuration="interval 0 hours")
# COMMAND ----------
# MAGIC %sql
# MAGIC show tblproperties dummy1
# COMMAND ----------
# MAGIC %sql
# MAGIC set spark.databricks.delta.retentionDurationCheck.enabled = false;
# MAGIC
# MAGIC VACUUM dummy1 RETAIN 0 HOURS
# COMMAND ----------
# MAGIC %sql
# MAGIC update dummy1 set reading_1=126 where id="34fb2d8a-5829-4036-adea-a08ccc2c260c"
# COMMAND ----------
# MAGIC %sql
# MAGIC select * from dummy1
# COMMAND ----------
# MAGIC %sql
# MAGIC optimize dummy1
# COMMAND ----------
dbutils.fs.ls(f"dbfs:/user/hive/warehouse//dummy1")
# COMMAND ----------
dbutils.fs.ls(f"dbfs:/user/hive/warehouse/dummy1/_delta_log")
# COMMAND ----------
df = spark.read.json("dbfs:/user/hive/warehouse/dummy1/_delta_log/00000000000000000010.json")
# COMMAND ----------
# MAGIC %sql
# MAGIC set spark.databricks.delta.formatCheck.enabled=false
# COMMAND ----------
# MAGIC %scala
# MAGIC
# MAGIC val df = spark.read.parquet("dbfs:/user/hive/warehouse/dummy1/part-00000-7f2a6d7c-1d44-47e1-a37c-da877c15e860-c000.snappy.parquet")
# MAGIC display(df)
# COMMAND ----------
# MAGIC %scala
# MAGIC
# MAGIC val df = spark.read.parquet("dbfs:/user/hive/warehouse/dummy1/_delta_log/00000000000000000020.checkpoint.parquet")
# MAGIC display(df)
# COMMAND ----------
df = spark.read.json("dbfs:/user/hive/warehouse//dummy1/_delta_log/00000000000000000028.json")
display(df)
##Out[59]: [FileInfo(path='dbfs:/user/hive/warehouse/dummy1/_delta_log/', name='_delta_log/', size=0),
## FileInfo(path='dbfs:/user/hive/warehouse/dummy1/part-00000-7d18212c-7240-4194-94d2-a34f56195076-c000.snappy.parquet', name='part-00000-7d18212c-7240-4194-94d2-a34f56195076-c000.snappy.parquet', size=3292),
## FileInfo(path='dbfs:/user/hive/warehouse/dummy1/part-00000-7f2a6d7c-1d44-47e1-a37c-da877c15e860-c000.snappy.parquet', name='part-00000-7f2a6d7c-1d44-47e1-a37c-da877c15e860-c000.snappy.parquet', size=3293),
## FileInfo(path='dbfs:/user/hive/warehouse/dummy1/part-00000-940cde1d-5373-4986-aa73-cd099ae021d7-c000.snappy.parquet', name='part-00000-940cde1d-5373-4986-aa73-cd099ae021d7-c000.snappy.parquet', size=3293)]
# COMMAND ----------
dbutils.fs.rm(f"dbfs:/user/hive/warehouse//dummy1/_delta_log/00000000000000000000.json")
# COMMAND ----------
# MAGIC %sql
# MAGIC describe formatted dummy1
# COMMAND ----------
# MAGIC %sql
# MAGIC VACUUM dummy1 retain 0 hours
# COMMAND ----------
| dbutils.widgets.text('team_name', "Enter your team's name")
team_name = dbutils.widgets.get('team_name')
setup_responses = dbutils.notebook.run('./includes/flight_school_assignment_1_setup', 0, {'team_name': team_name}).split()
local_data_path = setup_responses[0]
dbfs_data_path = setup_responses[1]
database_name = setup_responses[2]
print(f'Path to be used for Local Files: {local_data_path}')
print(f'Path to be used for DBFS Files: {dbfs_data_path}')
print(f'Database Name: {database_name}')
spark.sql(f'USE {database_name}')
data_path = f'dbfs:/FileStore/flight/{team_name}/assignment_1_ingest.csv'
df = spark.read.option('header', 'true').option('inferSchema', 'true').csv(dataPath)
backfill_data_path = f'dbfs:/FileStore/flight/{team_name}/assignment_1_backfill.csv'
df_backfill = spark.read.option('header', 'true').option('inferSchema', 'true').csv(backfillDataPath)
df.createOrReplaceTempView('historical_bronze_vw')
df_backfill.createOrReplaceTempView('historical_bronze_backfill_vw')
dbutils.fs.help()
dbutils.fs.head(f'dbfs:/FileStore/flight/{team_name}/assignment_1_ingest.csv')
data_path = f'dbfs:/FileStore/flight/{team_name}/sensor_new_schema.csv'
df = spark.read.option('header', 'true').option('inferSchema', 'true').csv(dataPath)
display(df)
df.createOrReplaceTempView('new_schema_bronze_vw')
dbutils.fs.ls(f'dbfs:/user/hive/warehouse/{database_name}.db/sensor_readings_historical_silver')
dbutils.fs.ls(f'dbfs:/user/hive/warehouse/{database_name}.db/sensor_readings_historical_silver_by_device')
dbutils.fs.ls(f'dbfs:/user/hive/warehouse/{database_name}.db/sensor_readings_historical_silver_by_hour/reading_date=2015-02-24')
dbutils.fs.ls(f'dbfs:/user/hive/warehouse/dummy1')
dbutils.fs.ls(f'dbfs:/user/hive/warehouse//dummy1')
dbutils.fs.ls(f'dbfs:/user/hive/warehouse/dummy1/_delta_log')
df = spark.read.json('dbfs:/user/hive/warehouse/dummy1/_delta_log/00000000000000000010.json')
df = spark.read.json('dbfs:/user/hive/warehouse//dummy1/_delta_log/00000000000000000028.json')
display(df)
dbutils.fs.rm(f'dbfs:/user/hive/warehouse//dummy1/_delta_log/00000000000000000000.json') |
#Longest Collatz Sequence
#Solving for Project Euler.Net Problem 14.
#Given n -> n/2 (n is even)
# n -> 3n + 1 (n is odd)
#
#Which starting number, under one million, produces the longest chain?
#
#By Alex Murshak
def collatz(n):
count = 0
while n>1:
if n%2==0:
n= n/2
else:
n= 3*n+1
count += 1
return count
C_large = 0
I_large = 0
for i in range(1,1000000,1):
C = collatz(i)
if C> C_large:
C_large = C
I_large = i
print(I_large)
| def collatz(n):
count = 0
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
count += 1
return count
c_large = 0
i_large = 0
for i in range(1, 1000000, 1):
c = collatz(i)
if C > C_large:
c_large = C
i_large = i
print(I_large) |
class Solution:
def romanToInt(self, s: str) -> int:
translations = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
number = 0
s = s.replace("IV", "IIII").replace("IX", "VIIII")
s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
for char in s:number += translations[char]
return number | class Solution:
def roman_to_int(self, s: str) -> int:
translations = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
number = 0
s = s.replace('IV', 'IIII').replace('IX', 'VIIII')
s = s.replace('XL', 'XXXX').replace('XC', 'LXXXX')
s = s.replace('CD', 'CCCC').replace('CM', 'DCCCC')
for char in s:
number += translations[char]
return number |
budget = float(input())
price_1kg_flour = float(input())
colored_eggs = 0
price_1pack_eggs = price_1kg_flour * 0.75
price_250ml_milk = (price_1kg_flour + (price_1kg_flour * 0.25)) / 4
price_1_bread = price_1pack_eggs + price_1kg_flour + price_250ml_milk
count_breads = int(budget // price_1_bread)
for current_bread in range(1, count_breads + 1):
colored_eggs += 3
if current_bread % 3 == 0:
lost_colored_eggs = current_bread - 2
colored_eggs -= lost_colored_eggs
money_left = budget - (count_breads * price_1_bread)
print(f"You made {count_breads} loaves of Easter bread! Now you have {colored_eggs} eggs and {money_left:.2f}BGN left.")
| budget = float(input())
price_1kg_flour = float(input())
colored_eggs = 0
price_1pack_eggs = price_1kg_flour * 0.75
price_250ml_milk = (price_1kg_flour + price_1kg_flour * 0.25) / 4
price_1_bread = price_1pack_eggs + price_1kg_flour + price_250ml_milk
count_breads = int(budget // price_1_bread)
for current_bread in range(1, count_breads + 1):
colored_eggs += 3
if current_bread % 3 == 0:
lost_colored_eggs = current_bread - 2
colored_eggs -= lost_colored_eggs
money_left = budget - count_breads * price_1_bread
print(f'You made {count_breads} loaves of Easter bread! Now you have {colored_eggs} eggs and {money_left:.2f}BGN left.') |
# O(n) time | O(h) space - where n is the number of nodes in the Binary Tree
# and h is the height of the Binary Tree
def nodeDepths(root, depth = 0):
if root is None:
return 0
return depth + nodeDepths(root.left, depth + 1) + nodeDepths(root.right, depth + 1)
# This is the class of the input binary tree.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
| def node_depths(root, depth=0):
if root is None:
return 0
return depth + node_depths(root.left, depth + 1) + node_depths(root.right, depth + 1)
class Binarytree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None |
# Lesson 1 - Hello world and entry points
#
# All languages have an "entry point"
# An entry point is where the program begins execution
# "Main" is a common keyword used to specify the entry point
#
# Common C style entry points:
# int main()
# {
# return 0;
# }
# or
# void main()
# {
# }
# Hello World is a common and simple IO program to test a language
# and teach very basic concepts like console I/O
def helloWorld():
print("Hello World")
if __name__ == '__main__':
helloWorld() | def hello_world():
print('Hello World')
if __name__ == '__main__':
hello_world() |
PASSWD = '12345'
def password_required(func):
def wrapper():
password = input('Cual es el passwd ? ')
if password == PASSWD:
return func()
else:
print('error')
return wrapper
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
def strong_decorate(func):
def func_wrapper(name):
return "<strong>{0}</strong>".format(func(name))
return func_wrapper
def div_decorate(func):
def func_wrapper(name):
return "<div>{0}</div>".format(func(name))
return func_wrapper
def upper_dec(func):
def wrapper(*args,**kwargs):
result = func(*args,**kwargs)
return result.upper()
return wrapper
@upper_dec
def get_my_name(name):
return "My name is {0}".format(name)
@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
a = get_text
@password_required
def needs_password():
print('la contra esta correcta!!')
########################################################
## test general arguments "*args,**kwargs"
def test_valor_kwargs(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print('%s == %s' %(key,value))
print(type(kwargs))
def test_valor_args(n_arg, *args):
print('primer valor normal: ', n_arg)
for arg in args:
print('este es un valor de *args: ',arg)
print(type(args))
def test_valor_kwargs_args(*args, **kwargs):
print(type(kwargs))
print(kwargs)
print('----------')
print(type(args))
print(args)
################################################################################
### example decorators in classes
def p_decorate_cla(func):
def func_wrapper(*args, **kwargs):
return "<p>{0}</p>".format(func(*args, **kwargs))
return func_wrapper
class Person():
def __init__(self):
self.name = "John"
self.family = "Doe"
@p_decorate_cla
def get_fullname(self):
return self.name+" "+self.family
if __name__ == '__main__':
#print(get_my_name('johan'))
print(a('johan'))
#test_valor_kwargs(caricatura='batman')
#test_valor_args('carlos','Karla','Paola','Elena',[1,2,3,5,1])
#test_valor_kwargs_args('flash', 'batman',[1,2,3,5,1], caricatura='batman', empresa = 'dc')
#
#my_person = Person()
#print(my_person.get_fullname())
#needs_password()
#print(get_text('johan'))
| passwd = '12345'
def password_required(func):
def wrapper():
password = input('Cual es el passwd ? ')
if password == PASSWD:
return func()
else:
print('error')
return wrapper
def p_decorate(func):
def func_wrapper(name):
return '<p>{0}</p>'.format(func(name))
return func_wrapper
def strong_decorate(func):
def func_wrapper(name):
return '<strong>{0}</strong>'.format(func(name))
return func_wrapper
def div_decorate(func):
def func_wrapper(name):
return '<div>{0}</div>'.format(func(name))
return func_wrapper
def upper_dec(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@upper_dec
def get_my_name(name):
return 'My name is {0}'.format(name)
@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
return 'lorem ipsum, {0} dolor sit amet'.format(name)
a = get_text
@password_required
def needs_password():
print('la contra esta correcta!!')
def test_valor_kwargs(**kwargs):
if kwargs is not None:
for (key, value) in kwargs.items():
print('%s == %s' % (key, value))
print(type(kwargs))
def test_valor_args(n_arg, *args):
print('primer valor normal: ', n_arg)
for arg in args:
print('este es un valor de *args: ', arg)
print(type(args))
def test_valor_kwargs_args(*args, **kwargs):
print(type(kwargs))
print(kwargs)
print('----------')
print(type(args))
print(args)
def p_decorate_cla(func):
def func_wrapper(*args, **kwargs):
return '<p>{0}</p>'.format(func(*args, **kwargs))
return func_wrapper
class Person:
def __init__(self):
self.name = 'John'
self.family = 'Doe'
@p_decorate_cla
def get_fullname(self):
return self.name + ' ' + self.family
if __name__ == '__main__':
print(a('johan')) |
def euclid(n, m):
if n > m:
r = m
m = n
n = r
r = m % n
while r != 0:
m = n
n = r
r = m % n
return n
| def euclid(n, m):
if n > m:
r = m
m = n
n = r
r = m % n
while r != 0:
m = n
n = r
r = m % n
return n |
def bisection_search(arr: list, n: int) -> bool:
mid = len(arr) // 2
if len(arr) < 2:
if arr[mid] == n:
return True
else:
return False
else:
if arr[mid] == n:
return True
else:
return bisection_search(arr[:mid], n) if arr[mid] > n else bisection_search(arr[mid:], n)
print(bisection_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 11], 12))
| def bisection_search(arr: list, n: int) -> bool:
mid = len(arr) // 2
if len(arr) < 2:
if arr[mid] == n:
return True
else:
return False
elif arr[mid] == n:
return True
else:
return bisection_search(arr[:mid], n) if arr[mid] > n else bisection_search(arr[mid:], n)
print(bisection_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 11], 12)) |
l1 = int(input('Digite o lado 1 '))
l2 = int(input('Digite o lado 2 '))
l3 = int(input('Digite o lado 3 '))
if l1+l2>l3 and l1+l3>l2 and l2+l3>l1:
print(f'O triangulo PODE ser formado')
else:
print(f'O triangulo NAO PODE ser formado') | l1 = int(input('Digite o lado 1 '))
l2 = int(input('Digite o lado 2 '))
l3 = int(input('Digite o lado 3 '))
if l1 + l2 > l3 and l1 + l3 > l2 and (l2 + l3 > l1):
print(f'O triangulo PODE ser formado')
else:
print(f'O triangulo NAO PODE ser formado') |
'''
02 - Creating two-factor
Let's continue looking at the student_data dataset of students
in secondary school. Here, we want to answer the following question:
does a student's first semester grade ("G1") tend to correlate with
their final grade ("G3")?
There are many aspects of a student's life that could result in a higher
or lower final grade in the class. For example, some students receive extra
educational support from their school ("schoolsup") or from their family
("famsup"), which could result in higher grades. Let's try to control for
these two factors by creating subplots based on whether the student received
extra educational support from their school or family.
Seaborn has been imported as sns and matplotlib.pyplot has been imported as plt.
Instructions 1/3
- Use relplot() to create a scatter plot with "G1" on the x-axis and "G3" on the
y-axis, using the student_data DataFrame.
'''
# Create a scatter plot of G1 vs. G3
sns.relplot(x="G1", y="G3",
data=student_data,
kind="scatter",
)
# Show plot
plt.show()
'''
Instructions 2/3
- Create column subplots based on whether the student received support from the
school ("schoolsup"), ordered so that "yes" comes before "no".
'''
# Adjust to add subplots based on school support
sns.relplot(x="G1", y="G3",
data=student_data,
kind="scatter",
col="schoolsup",
col_order=["yes", "no"])
# Show plot
plt.show()
'''
Instructions 3/3
- Add row subplots based on whether the student received support from the family
("famsup"), ordered so that "yes" comes before "no". This will result in subplots
based on two factors.
'''
# Adjust further to add subplots based on family support
sns.relplot(x="G1", y="G3",
data=student_data,
kind="scatter",
col="schoolsup",
col_order=["yes", "no"],
row="famsup",
row_order=["yes", "no"])
# Show plot
plt.show()
| """
02 - Creating two-factor
Let's continue looking at the student_data dataset of students
in secondary school. Here, we want to answer the following question:
does a student's first semester grade ("G1") tend to correlate with
their final grade ("G3")?
There are many aspects of a student's life that could result in a higher
or lower final grade in the class. For example, some students receive extra
educational support from their school ("schoolsup") or from their family
("famsup"), which could result in higher grades. Let's try to control for
these two factors by creating subplots based on whether the student received
extra educational support from their school or family.
Seaborn has been imported as sns and matplotlib.pyplot has been imported as plt.
Instructions 1/3
- Use relplot() to create a scatter plot with "G1" on the x-axis and "G3" on the
y-axis, using the student_data DataFrame.
"""
sns.relplot(x='G1', y='G3', data=student_data, kind='scatter')
plt.show()
'\nInstructions 2/3\n- Create column subplots based on whether the student received support from the \n school ("schoolsup"), ordered so that "yes" comes before "no".\n'
sns.relplot(x='G1', y='G3', data=student_data, kind='scatter', col='schoolsup', col_order=['yes', 'no'])
plt.show()
'\nInstructions 3/3\n\n- Add row subplots based on whether the student received support from the family \n ("famsup"), ordered so that "yes" comes before "no". This will result in subplots \n based on two factors.\n'
sns.relplot(x='G1', y='G3', data=student_data, kind='scatter', col='schoolsup', col_order=['yes', 'no'], row='famsup', row_order=['yes', 'no'])
plt.show() |
#
# PySNMP MIB module CISCO-VOICE-DNIS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-DNIS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:03:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
iso, NotificationType, Integer32, Counter64, Gauge32, Unsigned32, MibIdentifier, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, TimeTicks, ModuleIdentity, Bits, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Integer32", "Counter64", "Gauge32", "Unsigned32", "MibIdentifier", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "TimeTicks", "ModuleIdentity", "Bits", "IpAddress")
DisplayString, TextualConvention, RowStatus, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus", "TruthValue")
ciscoVoiceDnisMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 219))
if mibBuilder.loadTexts: ciscoVoiceDnisMIB.setLastUpdated('200205010000Z')
if mibBuilder.loadTexts: ciscoVoiceDnisMIB.setOrganization('Cisco Systems, Inc.')
class DnisMapname(TextualConvention, OctetString):
status = 'current'
displayHint = '32a'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 32)
class CvE164String(TextualConvention, OctetString):
status = 'current'
displayHint = '32a'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 32)
cvDnisMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 1))
cvDnisMap = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1))
cvDnisMappingTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1), )
if mibBuilder.loadTexts: cvDnisMappingTable.setStatus('current')
cvDnisMappingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1), ).setIndexNames((1, "CISCO-VOICE-DNIS-MIB", "cvDnisMappingName"))
if mibBuilder.loadTexts: cvDnisMappingEntry.setStatus('current')
cvDnisMappingName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 1), DnisMapname().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: cvDnisMappingName.setStatus('current')
cvDnisMappingUrl = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 2), DisplayString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvDnisMappingUrl.setStatus('current')
cvDnisMappingRefresh = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("idle", 1), ("refresh", 2))).clone('idle')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvDnisMappingRefresh.setStatus('current')
cvDnisMappingUrlAccessError = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvDnisMappingUrlAccessError.setStatus('current')
cvDnisMappingStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvDnisMappingStatus.setStatus('current')
cvDnisNodeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2), )
if mibBuilder.loadTexts: cvDnisNodeTable.setStatus('current')
cvDnisNodeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-VOICE-DNIS-MIB", "cvDnisMappingName"), (1, "CISCO-VOICE-DNIS-MIB", "cvDnisNumber"))
if mibBuilder.loadTexts: cvDnisNodeEntry.setStatus('current')
cvDnisNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1, 1), CvE164String())
if mibBuilder.loadTexts: cvDnisNumber.setStatus('current')
cvDnisNodeUrl = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1, 2), DisplayString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvDnisNodeUrl.setStatus('current')
cvDnisNodeModifiable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1, 3), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cvDnisNodeModifiable.setStatus('current')
cvDnisNodeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cvDnisNodeStatus.setStatus('current')
cvDnisMIBNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 2))
cvDnisMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 2, 0))
cvDnisMappingUrlInaccessible = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 219, 2, 0, 1)).setObjects(("CISCO-VOICE-DNIS-MIB", "cvDnisMappingUrl"), ("CISCO-VOICE-DNIS-MIB", "cvDnisMappingUrlAccessError"))
if mibBuilder.loadTexts: cvDnisMappingUrlInaccessible.setStatus('current')
cvDnisMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 3))
cvDnisMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 1))
cvDnisMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 2))
cvDnisMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 1, 1)).setObjects(("CISCO-VOICE-DNIS-MIB", "cvDnisGroup"), ("CISCO-VOICE-DNIS-MIB", "cvDnisNotificationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cvDnisMIBCompliance = cvDnisMIBCompliance.setStatus('current')
cvDnisGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 2, 1)).setObjects(("CISCO-VOICE-DNIS-MIB", "cvDnisMappingUrl"), ("CISCO-VOICE-DNIS-MIB", "cvDnisMappingRefresh"), ("CISCO-VOICE-DNIS-MIB", "cvDnisMappingUrlAccessError"), ("CISCO-VOICE-DNIS-MIB", "cvDnisMappingStatus"), ("CISCO-VOICE-DNIS-MIB", "cvDnisNodeUrl"), ("CISCO-VOICE-DNIS-MIB", "cvDnisNodeModifiable"), ("CISCO-VOICE-DNIS-MIB", "cvDnisNodeStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cvDnisGroup = cvDnisGroup.setStatus('current')
cvDnisNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 2, 2)).setObjects(("CISCO-VOICE-DNIS-MIB", "cvDnisMappingUrlInaccessible"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cvDnisNotificationGroup = cvDnisNotificationGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-VOICE-DNIS-MIB", cvDnisNodeUrl=cvDnisNodeUrl, cvDnisMappingStatus=cvDnisMappingStatus, cvDnisMIBNotificationPrefix=cvDnisMIBNotificationPrefix, cvDnisNumber=cvDnisNumber, cvDnisMappingEntry=cvDnisMappingEntry, cvDnisMIBGroups=cvDnisMIBGroups, cvDnisNodeTable=cvDnisNodeTable, cvDnisGroup=cvDnisGroup, cvDnisMappingTable=cvDnisMappingTable, cvDnisMappingUrlInaccessible=cvDnisMappingUrlInaccessible, cvDnisMIBObjects=cvDnisMIBObjects, cvDnisMappingRefresh=cvDnisMappingRefresh, cvDnisMappingUrl=cvDnisMappingUrl, CvE164String=CvE164String, cvDnisMappingUrlAccessError=cvDnisMappingUrlAccessError, DnisMapname=DnisMapname, ciscoVoiceDnisMIB=ciscoVoiceDnisMIB, cvDnisMap=cvDnisMap, cvDnisMIBConformance=cvDnisMIBConformance, cvDnisMIBCompliances=cvDnisMIBCompliances, cvDnisMIBCompliance=cvDnisMIBCompliance, cvDnisNodeModifiable=cvDnisNodeModifiable, cvDnisNodeStatus=cvDnisNodeStatus, cvDnisMappingName=cvDnisMappingName, cvDnisNotificationGroup=cvDnisNotificationGroup, cvDnisMIBNotifications=cvDnisMIBNotifications, cvDnisNodeEntry=cvDnisNodeEntry, PYSNMP_MODULE_ID=ciscoVoiceDnisMIB)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint')
(cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt')
(object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance')
(iso, notification_type, integer32, counter64, gauge32, unsigned32, mib_identifier, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, time_ticks, module_identity, bits, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'NotificationType', 'Integer32', 'Counter64', 'Gauge32', 'Unsigned32', 'MibIdentifier', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'TimeTicks', 'ModuleIdentity', 'Bits', 'IpAddress')
(display_string, textual_convention, row_status, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'RowStatus', 'TruthValue')
cisco_voice_dnis_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 219))
if mibBuilder.loadTexts:
ciscoVoiceDnisMIB.setLastUpdated('200205010000Z')
if mibBuilder.loadTexts:
ciscoVoiceDnisMIB.setOrganization('Cisco Systems, Inc.')
class Dnismapname(TextualConvention, OctetString):
status = 'current'
display_hint = '32a'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 32)
class Cve164String(TextualConvention, OctetString):
status = 'current'
display_hint = '32a'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(1, 32)
cv_dnis_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 1))
cv_dnis_map = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1))
cv_dnis_mapping_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1))
if mibBuilder.loadTexts:
cvDnisMappingTable.setStatus('current')
cv_dnis_mapping_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1)).setIndexNames((1, 'CISCO-VOICE-DNIS-MIB', 'cvDnisMappingName'))
if mibBuilder.loadTexts:
cvDnisMappingEntry.setStatus('current')
cv_dnis_mapping_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 1), dnis_mapname().subtype(subtypeSpec=value_size_constraint(1, 32)))
if mibBuilder.loadTexts:
cvDnisMappingName.setStatus('current')
cv_dnis_mapping_url = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 2), display_string()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvDnisMappingUrl.setStatus('current')
cv_dnis_mapping_refresh = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('idle', 1), ('refresh', 2))).clone('idle')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvDnisMappingRefresh.setStatus('current')
cv_dnis_mapping_url_access_error = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 4), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cvDnisMappingUrlAccessError.setStatus('current')
cv_dnis_mapping_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 1, 1, 5), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvDnisMappingStatus.setStatus('current')
cv_dnis_node_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2))
if mibBuilder.loadTexts:
cvDnisNodeTable.setStatus('current')
cv_dnis_node_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1)).setIndexNames((0, 'CISCO-VOICE-DNIS-MIB', 'cvDnisMappingName'), (1, 'CISCO-VOICE-DNIS-MIB', 'cvDnisNumber'))
if mibBuilder.loadTexts:
cvDnisNodeEntry.setStatus('current')
cv_dnis_number = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1, 1), cv_e164_string())
if mibBuilder.loadTexts:
cvDnisNumber.setStatus('current')
cv_dnis_node_url = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1, 2), display_string()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvDnisNodeUrl.setStatus('current')
cv_dnis_node_modifiable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1, 3), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cvDnisNodeModifiable.setStatus('current')
cv_dnis_node_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 219, 1, 1, 2, 1, 4), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cvDnisNodeStatus.setStatus('current')
cv_dnis_mib_notification_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 2))
cv_dnis_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 2, 0))
cv_dnis_mapping_url_inaccessible = notification_type((1, 3, 6, 1, 4, 1, 9, 9, 219, 2, 0, 1)).setObjects(('CISCO-VOICE-DNIS-MIB', 'cvDnisMappingUrl'), ('CISCO-VOICE-DNIS-MIB', 'cvDnisMappingUrlAccessError'))
if mibBuilder.loadTexts:
cvDnisMappingUrlInaccessible.setStatus('current')
cv_dnis_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 3))
cv_dnis_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 1))
cv_dnis_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 2))
cv_dnis_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 1, 1)).setObjects(('CISCO-VOICE-DNIS-MIB', 'cvDnisGroup'), ('CISCO-VOICE-DNIS-MIB', 'cvDnisNotificationGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cv_dnis_mib_compliance = cvDnisMIBCompliance.setStatus('current')
cv_dnis_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 2, 1)).setObjects(('CISCO-VOICE-DNIS-MIB', 'cvDnisMappingUrl'), ('CISCO-VOICE-DNIS-MIB', 'cvDnisMappingRefresh'), ('CISCO-VOICE-DNIS-MIB', 'cvDnisMappingUrlAccessError'), ('CISCO-VOICE-DNIS-MIB', 'cvDnisMappingStatus'), ('CISCO-VOICE-DNIS-MIB', 'cvDnisNodeUrl'), ('CISCO-VOICE-DNIS-MIB', 'cvDnisNodeModifiable'), ('CISCO-VOICE-DNIS-MIB', 'cvDnisNodeStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cv_dnis_group = cvDnisGroup.setStatus('current')
cv_dnis_notification_group = notification_group((1, 3, 6, 1, 4, 1, 9, 9, 219, 3, 2, 2)).setObjects(('CISCO-VOICE-DNIS-MIB', 'cvDnisMappingUrlInaccessible'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cv_dnis_notification_group = cvDnisNotificationGroup.setStatus('current')
mibBuilder.exportSymbols('CISCO-VOICE-DNIS-MIB', cvDnisNodeUrl=cvDnisNodeUrl, cvDnisMappingStatus=cvDnisMappingStatus, cvDnisMIBNotificationPrefix=cvDnisMIBNotificationPrefix, cvDnisNumber=cvDnisNumber, cvDnisMappingEntry=cvDnisMappingEntry, cvDnisMIBGroups=cvDnisMIBGroups, cvDnisNodeTable=cvDnisNodeTable, cvDnisGroup=cvDnisGroup, cvDnisMappingTable=cvDnisMappingTable, cvDnisMappingUrlInaccessible=cvDnisMappingUrlInaccessible, cvDnisMIBObjects=cvDnisMIBObjects, cvDnisMappingRefresh=cvDnisMappingRefresh, cvDnisMappingUrl=cvDnisMappingUrl, CvE164String=CvE164String, cvDnisMappingUrlAccessError=cvDnisMappingUrlAccessError, DnisMapname=DnisMapname, ciscoVoiceDnisMIB=ciscoVoiceDnisMIB, cvDnisMap=cvDnisMap, cvDnisMIBConformance=cvDnisMIBConformance, cvDnisMIBCompliances=cvDnisMIBCompliances, cvDnisMIBCompliance=cvDnisMIBCompliance, cvDnisNodeModifiable=cvDnisNodeModifiable, cvDnisNodeStatus=cvDnisNodeStatus, cvDnisMappingName=cvDnisMappingName, cvDnisNotificationGroup=cvDnisNotificationGroup, cvDnisMIBNotifications=cvDnisMIBNotifications, cvDnisNodeEntry=cvDnisNodeEntry, PYSNMP_MODULE_ID=ciscoVoiceDnisMIB) |
# acronymsBuilder.py
# A program to build acronyms from a phrase
# by Tung Nguyen
def main():
# declare program function:
print("This program builds acronyms.")
print()
# prompt user to input the sentence:
sentence = input("Enter a phrase: ")
# split the sentence into a list that contains words
listWord = sentence.split()
# assign a variable that will be used to store each of the first letter of every word in the sentence
acronym = ""
# loop through the list of words in the sentence (listWord) -> pick the first letter of every word -> store it in acronym variable
for x in listWord:
acronym += x[0].upper()
# print out the result
print("The acronym is " + acronym)
main() | def main():
print('This program builds acronyms.')
print()
sentence = input('Enter a phrase: ')
list_word = sentence.split()
acronym = ''
for x in listWord:
acronym += x[0].upper()
print('The acronym is ' + acronym)
main() |
# x y x y
#r1 = [[0, 0], [5, 5]]
r1 = [[-5, -5], [-2, -2]]
r2 = [[7, 1], [1, 8]]
r3 = [[-1.2, 4], [3.7, 1.1]]
def rect_intersection_area(r1, r2, r3):
area = 0
r1_p1, r1_p2 = r1
r2_p1, r2_p2 = r2
r3_p1, r3_p2 = r3
right_x_p = 0
left_x_p = 0
top_y_p = 0
bottom_y_p = 0
# check for x
# max of left
left_x_p = max(min(r2_p1[0], r2_p2[0]), min(r1_p1[0], r1_p2[0]), min(r3_p1[0], r3_p2[0]))
# min of right
right_x_p = min(max(r2_p1[0], r2_p2[0]), max(r1_p1[0], r1_p2[0]), min(r3_p1[0], r3_p2[0]))
# max of left
top_y_p = max(min(r2_p1[1], r2_p2[1]), min(r1_p1[1], r1_p2[1]), min(r3_p1[1], r3_p2[1]))
# min of right
bottom_y_p = min(max(r2_p1[1], r2_p2[1]), max(r1_p1[1], r1_p2[1]), min(r3_p1[1], r3_p2[1]))
print('left_x_p:', left_x_p)
print('right_x_p:', right_x_p)
print('top_y_p:', top_y_p)
print('bottom_y_p:', bottom_y_p)
y_length = max(top_y_p, bottom_y_p) - min(top_y_p, bottom_y_p)
x_length = max(left_x_p, right_x_p) - min(left_x_p, right_x_p)
if right_x_p < left_x_p:
# no overlap
return 0
if bottom_y_p < top_y_p:
# no overlap
return 0
area = y_length * x_length
return area
#def is_within()
print(rect_intersection_area(r1, r2, r3))
| r1 = [[-5, -5], [-2, -2]]
r2 = [[7, 1], [1, 8]]
r3 = [[-1.2, 4], [3.7, 1.1]]
def rect_intersection_area(r1, r2, r3):
area = 0
(r1_p1, r1_p2) = r1
(r2_p1, r2_p2) = r2
(r3_p1, r3_p2) = r3
right_x_p = 0
left_x_p = 0
top_y_p = 0
bottom_y_p = 0
left_x_p = max(min(r2_p1[0], r2_p2[0]), min(r1_p1[0], r1_p2[0]), min(r3_p1[0], r3_p2[0]))
right_x_p = min(max(r2_p1[0], r2_p2[0]), max(r1_p1[0], r1_p2[0]), min(r3_p1[0], r3_p2[0]))
top_y_p = max(min(r2_p1[1], r2_p2[1]), min(r1_p1[1], r1_p2[1]), min(r3_p1[1], r3_p2[1]))
bottom_y_p = min(max(r2_p1[1], r2_p2[1]), max(r1_p1[1], r1_p2[1]), min(r3_p1[1], r3_p2[1]))
print('left_x_p:', left_x_p)
print('right_x_p:', right_x_p)
print('top_y_p:', top_y_p)
print('bottom_y_p:', bottom_y_p)
y_length = max(top_y_p, bottom_y_p) - min(top_y_p, bottom_y_p)
x_length = max(left_x_p, right_x_p) - min(left_x_p, right_x_p)
if right_x_p < left_x_p:
return 0
if bottom_y_p < top_y_p:
return 0
area = y_length * x_length
return area
print(rect_intersection_area(r1, r2, r3)) |
# https://atcoder.jp/contests/abs/tasks/practice_1
def resolve():
a = int(input())
b, c = list(map(int, input().split()))
d = input()
print("{} {}".format(a + b + c, d))
| def resolve():
a = int(input())
(b, c) = list(map(int, input().split()))
d = input()
print('{} {}'.format(a + b + c, d)) |
class IpConfiguration:
options: object
def __init__(self, options):
self.options = options
| class Ipconfiguration:
options: object
def __init__(self, options):
self.options = options |
#!/usr/bin/env python3
# Compares two lexicon files providing several stats
# @author Cristian TG
# @since 2021/04/15
# Please change the value of these variables:
LEXICON_1 = 'lexicon1.txt'
LEXICON_2 = 'lexicon2.txt'
SHOW_DETAILS = True
DISAMBIGUATION_SYMBOL = '#'
###############################################################
###############################################################
#import os
def getLexicon(lexicon, path):
with open(path) as lexi:
for line in lexi:
aux = line.split('\t')
lexicon[aux[0]] = aux[1].replace("\n","").split(" ")
return lexicon
def getWords(lexicon):
words = set()
for word in lexicon:
words.add(word)
return words
def getCharacters(lexicon):
characters = set()
for word in lexicon:
for c in word:
characters.add(c)
return characters
def getPhonemes(lexicon):
phonemes = set()
disambiguation = set()
for word in lexicon:
phones = lexicon[word]
for p in phones:
if DISAMBIGUATION_SYMBOL not in p:
phonemes.add(p)
else:
disambiguation.add(p)
return phonemes, disambiguation
#############################################################
lexicon1 = getLexicon({}, LEXICON_1)
lexicon2 = getLexicon({}, LEXICON_2)
words_l1 = getWords(lexicon1)
words_l2 = getWords(lexicon2)
characters_l1 = getCharacters(lexicon1)
characters_l2 = getCharacters(lexicon2)
phonemes_l1, disambiguation_l1 = getPhonemes(lexicon1)
phonemes_l2, disambiguation_l2 = getPhonemes(lexicon2)
print("\nLEXICON_1", LEXICON_1, "LEXICON_2", LEXICON_2)
print("- Number of words:", len(words_l1),
len(words_l2), len(words_l1)-len(words_l2))
print("\n- Number of common words:", len(words_l1&words_l2))
if SHOW_DETAILS:
print(words_l1 & words_l2)
print("- Number of words included in 1 (not in 2):", len(words_l1 - words_l2))
if SHOW_DETAILS:
print(words_l1 - words_l2)
print("- Number of words included in 2 (not in 1):", len(words_l2 - words_l1))
if SHOW_DETAILS:
print(words_l2 - words_l1)
print("\n- Number of characters:", len(characters_l1),
len(characters_l2), len(characters_l1)-len(characters_l2))
print("- Number of common characters:", len(characters_l1 & characters_l2))
if SHOW_DETAILS:
print(characters_l1 & characters_l2)
print("- Number of characters included in 1 (not in 2):", len(characters_l1 - characters_l2))
if SHOW_DETAILS:
print(characters_l1 - characters_l2)
print("- Number of characters included in 2 (not in 1):",
len(characters_l2 - characters_l1))
if SHOW_DETAILS:
print(characters_l2 - characters_l1)
print("\n- Number of phonemes:", len(phonemes_l1),
len(phonemes_l2), len(phonemes_l1)-len(phonemes_l2))
print("- Number of common phonemes:", len(phonemes_l1 & phonemes_l2))
if SHOW_DETAILS:
print(phonemes_l1 & phonemes_l2)
print("- Number of phonemes included in 1 (not in 2):",
len(phonemes_l1 - phonemes_l2))
if SHOW_DETAILS:
print(phonemes_l1 - phonemes_l2)
print("- Number of phonemes included in 2 (not in 1):",
len(phonemes_l2 - phonemes_l1))
if SHOW_DETAILS:
print(phonemes_l2 - phonemes_l1)
print("\n- Number of disambiguation symbols:", len(disambiguation_l1),
len(disambiguation_l2), len(disambiguation_l1)-len(disambiguation_l2))
print("- Number of common disambiguation symbols:",
len(disambiguation_l1 & disambiguation_l2))
if SHOW_DETAILS:
print(disambiguation_l1 & disambiguation_l2)
print("- Number of disambiguation symbols included in 1 (not in 2):",
len(disambiguation_l1 - disambiguation_l2))
if SHOW_DETAILS:
print(disambiguation_l1 - disambiguation_l2)
print("- Number of disambiguation symbols included in 2 (not in 1):",
len(disambiguation_l2 - disambiguation_l1))
if SHOW_DETAILS:
print(disambiguation_l2 - disambiguation_l1)
| lexicon_1 = 'lexicon1.txt'
lexicon_2 = 'lexicon2.txt'
show_details = True
disambiguation_symbol = '#'
def get_lexicon(lexicon, path):
with open(path) as lexi:
for line in lexi:
aux = line.split('\t')
lexicon[aux[0]] = aux[1].replace('\n', '').split(' ')
return lexicon
def get_words(lexicon):
words = set()
for word in lexicon:
words.add(word)
return words
def get_characters(lexicon):
characters = set()
for word in lexicon:
for c in word:
characters.add(c)
return characters
def get_phonemes(lexicon):
phonemes = set()
disambiguation = set()
for word in lexicon:
phones = lexicon[word]
for p in phones:
if DISAMBIGUATION_SYMBOL not in p:
phonemes.add(p)
else:
disambiguation.add(p)
return (phonemes, disambiguation)
lexicon1 = get_lexicon({}, LEXICON_1)
lexicon2 = get_lexicon({}, LEXICON_2)
words_l1 = get_words(lexicon1)
words_l2 = get_words(lexicon2)
characters_l1 = get_characters(lexicon1)
characters_l2 = get_characters(lexicon2)
(phonemes_l1, disambiguation_l1) = get_phonemes(lexicon1)
(phonemes_l2, disambiguation_l2) = get_phonemes(lexicon2)
print('\nLEXICON_1', LEXICON_1, 'LEXICON_2', LEXICON_2)
print('- Number of words:', len(words_l1), len(words_l2), len(words_l1) - len(words_l2))
print('\n- Number of common words:', len(words_l1 & words_l2))
if SHOW_DETAILS:
print(words_l1 & words_l2)
print('- Number of words included in 1 (not in 2):', len(words_l1 - words_l2))
if SHOW_DETAILS:
print(words_l1 - words_l2)
print('- Number of words included in 2 (not in 1):', len(words_l2 - words_l1))
if SHOW_DETAILS:
print(words_l2 - words_l1)
print('\n- Number of characters:', len(characters_l1), len(characters_l2), len(characters_l1) - len(characters_l2))
print('- Number of common characters:', len(characters_l1 & characters_l2))
if SHOW_DETAILS:
print(characters_l1 & characters_l2)
print('- Number of characters included in 1 (not in 2):', len(characters_l1 - characters_l2))
if SHOW_DETAILS:
print(characters_l1 - characters_l2)
print('- Number of characters included in 2 (not in 1):', len(characters_l2 - characters_l1))
if SHOW_DETAILS:
print(characters_l2 - characters_l1)
print('\n- Number of phonemes:', len(phonemes_l1), len(phonemes_l2), len(phonemes_l1) - len(phonemes_l2))
print('- Number of common phonemes:', len(phonemes_l1 & phonemes_l2))
if SHOW_DETAILS:
print(phonemes_l1 & phonemes_l2)
print('- Number of phonemes included in 1 (not in 2):', len(phonemes_l1 - phonemes_l2))
if SHOW_DETAILS:
print(phonemes_l1 - phonemes_l2)
print('- Number of phonemes included in 2 (not in 1):', len(phonemes_l2 - phonemes_l1))
if SHOW_DETAILS:
print(phonemes_l2 - phonemes_l1)
print('\n- Number of disambiguation symbols:', len(disambiguation_l1), len(disambiguation_l2), len(disambiguation_l1) - len(disambiguation_l2))
print('- Number of common disambiguation symbols:', len(disambiguation_l1 & disambiguation_l2))
if SHOW_DETAILS:
print(disambiguation_l1 & disambiguation_l2)
print('- Number of disambiguation symbols included in 1 (not in 2):', len(disambiguation_l1 - disambiguation_l2))
if SHOW_DETAILS:
print(disambiguation_l1 - disambiguation_l2)
print('- Number of disambiguation symbols included in 2 (not in 1):', len(disambiguation_l2 - disambiguation_l1))
if SHOW_DETAILS:
print(disambiguation_l2 - disambiguation_l1) |
def three_word(a, b, c):
title = a
if title == '\"\"':
title = "\'\'"
else:
title = "\'{0}\'".format(title)
tag = b
if tag == '\"\"':
tag = "\'\'"
else:
tag = "\'{0}\'".format(tag)
description = c
if description == '\"\"':
description = "\'\'"
else:
description = "\'{0}\'".format(description)
return title, tag, description
def format_file(old_file, new_file):
try:
format_file = open(new_file, 'a')
with open(old_file, 'r') as face_file:
for line in face_file:
line = line.split('\n')[0]
title, tag, description = three_word(line.split('\t')[4], line.split('\t')[5], line.split('\t')[6])
face_data = "{0}\t\'{1}\'\t\'{2}\'\t{3}\t{4}\t{5}\t{6}\t" \
"{7}\t{8}\t{9}\t\'{10}\'\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t" \
"{17}\t{18}\t{19}\t{20}\t{21}\t{22}\t{23}\t{24}\t{25}\n" \
.format(line.split('\t')[0],
line.split('\t')[1], line.split('\t')[2],
line.split('\t')[3], title, tag, description,
line.split('\t')[7], line.split('\t')[8],
line.split('\t')[9], line.split('\t')[10],
line.split('\t')[11], line.split('\t')[12],
line.split('\t')[13], line.split('\t')[14],
line.split('\t')[15], line.split('\t')[16],
line.split('\t')[17], line.split('\t')[18],
line.split('\t')[19],
line.split('\t')[20], line.split('\t')[21],
line.split('\t')[22], line.split('\t')[23],
line.split('\t')[24], line.split('\t')[25])
format_file.writelines(face_data)
format_file.close()
except Exception as e:
with open('log.txt', 'a') as log:
log.writelines("{0},{1}".format(new_file, e))
if __name__ == '__main__':
start =1
end = 135
for i in range(start, end):
print(i)
format_file(r'D:\Users\KYH\Desktop\EmotionMap\FlickrEmotionData\4face_all\face{0}.txt'.format(i),
r'D:\Users\KYH\Desktop\EmotionMap\FlickrEmotionData\5face_format\face{0}.txt'.format(i))
| def three_word(a, b, c):
title = a
if title == '""':
title = "''"
else:
title = "'{0}'".format(title)
tag = b
if tag == '""':
tag = "''"
else:
tag = "'{0}'".format(tag)
description = c
if description == '""':
description = "''"
else:
description = "'{0}'".format(description)
return (title, tag, description)
def format_file(old_file, new_file):
try:
format_file = open(new_file, 'a')
with open(old_file, 'r') as face_file:
for line in face_file:
line = line.split('\n')[0]
(title, tag, description) = three_word(line.split('\t')[4], line.split('\t')[5], line.split('\t')[6])
face_data = "{0}\t'{1}'\t'{2}'\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t'{10}'\t{11}\t{12}\t{13}\t{14}\t{15}\t{16}\t{17}\t{18}\t{19}\t{20}\t{21}\t{22}\t{23}\t{24}\t{25}\n".format(line.split('\t')[0], line.split('\t')[1], line.split('\t')[2], line.split('\t')[3], title, tag, description, line.split('\t')[7], line.split('\t')[8], line.split('\t')[9], line.split('\t')[10], line.split('\t')[11], line.split('\t')[12], line.split('\t')[13], line.split('\t')[14], line.split('\t')[15], line.split('\t')[16], line.split('\t')[17], line.split('\t')[18], line.split('\t')[19], line.split('\t')[20], line.split('\t')[21], line.split('\t')[22], line.split('\t')[23], line.split('\t')[24], line.split('\t')[25])
format_file.writelines(face_data)
format_file.close()
except Exception as e:
with open('log.txt', 'a') as log:
log.writelines('{0},{1}'.format(new_file, e))
if __name__ == '__main__':
start = 1
end = 135
for i in range(start, end):
print(i)
format_file('D:\\Users\\KYH\\Desktop\\EmotionMap\\FlickrEmotionData\\4face_all\\face{0}.txt'.format(i), 'D:\\Users\\KYH\\Desktop\\EmotionMap\\FlickrEmotionData\\5face_format\\face{0}.txt'.format(i)) |
# [Skill] Cygnus Constellation (20899)
echo = 10001005
cygnusConstellation = 1142597
cygnus = 1101000
if sm.canHold(cygnusConstellation):
sm.setSpeakerID(cygnus)
sm.sendNext("You have exceeded all our expectations. Please take this as a symbol of your heroism.\r\n"
"#s" + str(echo) + "# #q" + str(echo) + "#\r\n"
"#i" + str(cygnusConstellation) + "# #z" + str(cygnusConstellation) + "#")
sm.completeQuest(parentID)
sm.giveSkill(echo)
sm.giveItem(cygnusConstellation)
else:
sm.setSpeakerID(cygnus)
sm.sendSayOkay("Please make room in your Equip inventory.") | echo = 10001005
cygnus_constellation = 1142597
cygnus = 1101000
if sm.canHold(cygnusConstellation):
sm.setSpeakerID(cygnus)
sm.sendNext('You have exceeded all our expectations. Please take this as a symbol of your heroism.\r\n#s' + str(echo) + '# #q' + str(echo) + '#\r\n#i' + str(cygnusConstellation) + '# #z' + str(cygnusConstellation) + '#')
sm.completeQuest(parentID)
sm.giveSkill(echo)
sm.giveItem(cygnusConstellation)
else:
sm.setSpeakerID(cygnus)
sm.sendSayOkay('Please make room in your Equip inventory.') |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = str(int(self.combine(l1)) + int(self.combine(l2)))
return self.separate(ans, len(ans) - 1)
def combine(self, lst):
if lst.next:
return self.combine(lst.next) + str(lst.val)
else:
return str(lst.val)
def separate(self, string, i):
if i < 1:
return ListNode(int(string[0]), None)
else:
return ListNode(int(string[i]), self.separate(string, i-1))
| class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = str(int(self.combine(l1)) + int(self.combine(l2)))
return self.separate(ans, len(ans) - 1)
def combine(self, lst):
if lst.next:
return self.combine(lst.next) + str(lst.val)
else:
return str(lst.val)
def separate(self, string, i):
if i < 1:
return list_node(int(string[0]), None)
else:
return list_node(int(string[i]), self.separate(string, i - 1)) |
def http_exception(response):
raise HTTPException(response)
class HTTPException(Exception):
def __init__(self, response):
self._response = response
def __str__(self):
return self._response.message
@property
def is_redirect(self):
return self._response.is_redirect
@property
def is_client_error(self):
return self._response.is_client_error
@property
def is_server_error(self):
return self._response.is_server_error
| def http_exception(response):
raise http_exception(response)
class Httpexception(Exception):
def __init__(self, response):
self._response = response
def __str__(self):
return self._response.message
@property
def is_redirect(self):
return self._response.is_redirect
@property
def is_client_error(self):
return self._response.is_client_error
@property
def is_server_error(self):
return self._response.is_server_error |
coins = [
100,
50,
25,
5,
1
]
total = 0
change = 130
for i in range(len(coins)):
numCoins = change // coins[i]
change -= numCoins * coins[i]
total += numCoins
print(total)
'''
numCoins = 75 // 100 = 0
change = change - 0 * 100
change = change
''' | coins = [100, 50, 25, 5, 1]
total = 0
change = 130
for i in range(len(coins)):
num_coins = change // coins[i]
change -= numCoins * coins[i]
total += numCoins
print(total)
'\nnumCoins = 75 // 100 = 0\nchange = change - 0 * 100\nchange = change \n' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
DELIMITER = "\r\n"
def encode(*args):
"Pack a series of arguments into a value Redis command"
result = []
result.append("*")
result.append(str(len(args)))
result.append(DELIMITER)
for arg in args:
result.append("$")
result.append(str(len(arg)))
result.append(DELIMITER)
result.append(arg)
result.append(DELIMITER)
return "".join(result)
def decode(data):
processed, index = 0, data.find(DELIMITER)
if index == -1:
index = len(data)
term = data[processed]
if term == "*":
return parse_multi_chunked(data)
elif term == "$":
return parse_chunked(data)
elif term == "+":
return parse_status(data)
elif term == "-":
return parse_error(data)
elif term == ":":
return parse_integer(data)
def parse_stream(data):
cursor = 0
data_len = len(data)
result = []
while cursor < data_len:
pdata = data[cursor:]
index = pdata.find(DELIMITER)
count = int(pdata[1:index])
cmd = ''
start = index + len(DELIMITER)
for i in range(count):
chunk, length = parse_chunked(pdata, start)
start = length + len(DELIMITER)
cmd += " " + chunk
cursor += start
result.append(cmd.strip())
return result
def parse_multi_chunked(data):
index = data.find(DELIMITER)
count = int(data[1:index])
result = []
start = index + len(DELIMITER)
for i in range(count):
chunk, length = parse_chunked(data, start)
start = length + len(DELIMITER)
result.append(chunk)
return result
def parse_chunked(data, start=0):
index = data.find(DELIMITER, start)
if index == -1:
index = start
length = int(data[start + 1:index])
if length == -1:
if index + len(DELIMITER) == len(data):
return None
else:
return None, index
else:
result = data[index + len(DELIMITER):index + len(DELIMITER) + length]
return result if start == 0 else [result, index + len(DELIMITER) + length]
def parse_status(data):
return [True, data[1:]]
def parse_error(data):
return [False, data[1:]]
def parse_integer(data):
return [int(data[1:])]
if __name__ == '__main__':
print(decode(encode("ping")))
print((encode("set some value")))
print(encode("foobar"))
data = '*3\r\n$3\r\nSET\r\n$15\r\nmemtier-8232902\r\n$2\r\nxx\r\n*3\r\n$3\r\nSET\r\n$15\r\nmemtier-8232902\r\n$2\r\nxx\r\n*3\r\n$3\r\nSET\r\n$15\r\nmemtier-7630684\r\n$3\r\nAAA\r\n'
print(parse_stream(data))
| delimiter = '\r\n'
def encode(*args):
"""Pack a series of arguments into a value Redis command"""
result = []
result.append('*')
result.append(str(len(args)))
result.append(DELIMITER)
for arg in args:
result.append('$')
result.append(str(len(arg)))
result.append(DELIMITER)
result.append(arg)
result.append(DELIMITER)
return ''.join(result)
def decode(data):
(processed, index) = (0, data.find(DELIMITER))
if index == -1:
index = len(data)
term = data[processed]
if term == '*':
return parse_multi_chunked(data)
elif term == '$':
return parse_chunked(data)
elif term == '+':
return parse_status(data)
elif term == '-':
return parse_error(data)
elif term == ':':
return parse_integer(data)
def parse_stream(data):
cursor = 0
data_len = len(data)
result = []
while cursor < data_len:
pdata = data[cursor:]
index = pdata.find(DELIMITER)
count = int(pdata[1:index])
cmd = ''
start = index + len(DELIMITER)
for i in range(count):
(chunk, length) = parse_chunked(pdata, start)
start = length + len(DELIMITER)
cmd += ' ' + chunk
cursor += start
result.append(cmd.strip())
return result
def parse_multi_chunked(data):
index = data.find(DELIMITER)
count = int(data[1:index])
result = []
start = index + len(DELIMITER)
for i in range(count):
(chunk, length) = parse_chunked(data, start)
start = length + len(DELIMITER)
result.append(chunk)
return result
def parse_chunked(data, start=0):
index = data.find(DELIMITER, start)
if index == -1:
index = start
length = int(data[start + 1:index])
if length == -1:
if index + len(DELIMITER) == len(data):
return None
else:
return (None, index)
else:
result = data[index + len(DELIMITER):index + len(DELIMITER) + length]
return result if start == 0 else [result, index + len(DELIMITER) + length]
def parse_status(data):
return [True, data[1:]]
def parse_error(data):
return [False, data[1:]]
def parse_integer(data):
return [int(data[1:])]
if __name__ == '__main__':
print(decode(encode('ping')))
print(encode('set some value'))
print(encode('foobar'))
data = '*3\r\n$3\r\nSET\r\n$15\r\nmemtier-8232902\r\n$2\r\nxx\r\n*3\r\n$3\r\nSET\r\n$15\r\nmemtier-8232902\r\n$2\r\nxx\r\n*3\r\n$3\r\nSET\r\n$15\r\nmemtier-7630684\r\n$3\r\nAAA\r\n'
print(parse_stream(data)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.