content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
def usersagein_Sec():
users_age = int(input("Enter user age in years"))
agein_sec = users_age *12 *365 * 24
print(f"Age in sec is {agein_sec}")
print("Welcome to function project 1 ")
usersagein_Sec()
# Never use same name in anywhere inside a function program. else going to get error.
friends = []
def friend():
friends.append("Ram")
friend()
friend()
friend()
print(friends)
|
def usersagein__sec():
users_age = int(input('Enter user age in years'))
agein_sec = users_age * 12 * 365 * 24
print(f'Age in sec is {agein_sec}')
print('Welcome to function project 1 ')
usersagein__sec()
friends = []
def friend():
friends.append('Ram')
friend()
friend()
friend()
print(friends)
|
def test_non_standard_default_desired_privilege_level(iosxe_conn):
# purpose of this test is to ensure that when a user sets a non-standard default desired priv
# level, that there is nothing in genericdriver/networkdriver that will prevent that from
# actually being set as the default desired priv level
iosxe_conn.close()
iosxe_conn.default_desired_privilege_level = "configuration"
iosxe_conn.open()
current_prompt = iosxe_conn.get_prompt()
assert current_prompt == "csr1000v(config)#"
iosxe_conn.close()
|
def test_non_standard_default_desired_privilege_level(iosxe_conn):
iosxe_conn.close()
iosxe_conn.default_desired_privilege_level = 'configuration'
iosxe_conn.open()
current_prompt = iosxe_conn.get_prompt()
assert current_prompt == 'csr1000v(config)#'
iosxe_conn.close()
|
class Trader(object):
"""An entity buying and/or selling on the market."""
def __init__(self, name, funds=0, units=0):
self.name = name
self.funds = funds
self.units = units
def __repr__(self):
return "[Trader: name={}, funds={}, units={}]".format(self.name, self.funds, self.units)
NO_TRADER = Trader("No Trader", -1, -1)
|
class Trader(object):
"""An entity buying and/or selling on the market."""
def __init__(self, name, funds=0, units=0):
self.name = name
self.funds = funds
self.units = units
def __repr__(self):
return '[Trader: name={}, funds={}, units={}]'.format(self.name, self.funds, self.units)
no_trader = trader('No Trader', -1, -1)
|
fruits = {
"orange" :"a sweet,orange citrus fruit",
"apple" :"good for making cider",
"lemon" :"a sour,yellow citrus fruit",
"grape" :"a small, sweet fruit growing in bunches",
"lime" :"a sour,yellow citrus fruit",
}
def simple_operation():
print("To find the details in Fruits dictionary")
print(fruits)
print()
print('To find description for "lemon" in Fruits dictionary')
print(fruits["lemon"])
print()
print('To add a fruit name "pear" in in Fruits dictionary')
fruits["pear"] = "an odd shaped apple"
print(fruits)
print()
print('To change description of fruit "lime" in in Fruits dictionary')
fruits["lime"] = "great with tequilla"
print(fruits)
print()
print('Deleting a Key "Apple" from fruits')
del(fruits["apple"])
print(fruits)
print()
print("Clearing the fruits dictionary")
fruits.clear()
print(fruits)
def find_description():
print("To Find the description of a fruit")
while True:
dict_key = input("Please Enter Fruit name:\n")
if dict_key == "quit":
break
if dict_key in fruits:
description = fruits.get(dict_key)
print(description)
else:
print("The details of {} doesn't exist".format(dict_key))
if __name__ == "__main__":
print("""Select any one the below options
1. To find the description of fruit
2. To Display simple operation""")
choice = input("Enter Your choice here: ")
if choice == "1":
print("*" * 120)
find_description()
elif choice == "2":
print("*" * 120)
simple_operation()
|
fruits = {'orange': 'a sweet,orange citrus fruit', 'apple': 'good for making cider', 'lemon': 'a sour,yellow citrus fruit', 'grape': 'a small, sweet fruit growing in bunches', 'lime': 'a sour,yellow citrus fruit'}
def simple_operation():
print('To find the details in Fruits dictionary')
print(fruits)
print()
print('To find description for "lemon" in Fruits dictionary')
print(fruits['lemon'])
print()
print('To add a fruit name "pear" in in Fruits dictionary')
fruits['pear'] = 'an odd shaped apple'
print(fruits)
print()
print('To change description of fruit "lime" in in Fruits dictionary')
fruits['lime'] = 'great with tequilla'
print(fruits)
print()
print('Deleting a Key "Apple" from fruits')
del fruits['apple']
print(fruits)
print()
print('Clearing the fruits dictionary')
fruits.clear()
print(fruits)
def find_description():
print('To Find the description of a fruit')
while True:
dict_key = input('Please Enter Fruit name:\n')
if dict_key == 'quit':
break
if dict_key in fruits:
description = fruits.get(dict_key)
print(description)
else:
print("The details of {} doesn't exist".format(dict_key))
if __name__ == '__main__':
print('Select any one the below options\n 1. To find the description of fruit\n 2. To Display simple operation')
choice = input('Enter Your choice here: ')
if choice == '1':
print('*' * 120)
find_description()
elif choice == '2':
print('*' * 120)
simple_operation()
|
# Mac address of authentication server
AUTH_SERVER_MAC = "b8:ae:ed:7a:05:3b"
# IP address of authentication server
AUTH_SERVER_IP = "192.168.1.42"
# Switch port authentication server is facing
AUTH_SERVER_PORT = 3
#CTL_REST_IP = "192.168.1.39"
CTL_REST_IP = "10.0.1.8"
CTL_REST_PORT = "8080"
CTL_MAC = "b8:27:eb:b0:1d:6b"
GATEWAY_MAC = "24:09:95:79:31:7e"
GATEWAY_PORT = 1
# L2 src-dst pairs which are whitelisted and does not need to go through auth
WHITELIST = [
(AUTH_SERVER_MAC, CTL_MAC),
(CTL_MAC, AUTH_SERVER_MAC),
(GATEWAY_MAC, "00:1d:a2:80:60:64"),
("00:1d:a2:80:60:64", GATEWAY_MAC)
# (GATEWAY_MAC, "9c:eb:e8:01:6e:db"),
# ("9c:eb:e8:01:6e:db", GATEWAY_MAC)
]
|
auth_server_mac = 'b8:ae:ed:7a:05:3b'
auth_server_ip = '192.168.1.42'
auth_server_port = 3
ctl_rest_ip = '10.0.1.8'
ctl_rest_port = '8080'
ctl_mac = 'b8:27:eb:b0:1d:6b'
gateway_mac = '24:09:95:79:31:7e'
gateway_port = 1
whitelist = [(AUTH_SERVER_MAC, CTL_MAC), (CTL_MAC, AUTH_SERVER_MAC), (GATEWAY_MAC, '00:1d:a2:80:60:64'), ('00:1d:a2:80:60:64', GATEWAY_MAC)]
|
running = True
# Global Options
SIZES = {'small': [7.58, 0], 'medium': [9.69, 1], 'large': [12.09, 2], 'jumbo': [17.99, 3], 'party': [20.29, 4]} # [Price, ID]
TOPPINGS = {'pepperoni': [0, False], 'bacon': [0, True], 'sausage': [0, False], 'mushroom': [1, False], 'black olive': [1, False], 'green pepper': [1, False]} # [Group, Special]
TOPPING_PRICES = [[1.6, 2.05, 2.35, 3.15, 3.30], [1.95, 2.25, 2.65, 3.49, 3.69]] # 0: No Special - 1: Special [Inc size]
def ask(question, options, show = True):
answer = False
o = "" # Choices to show, only if show = true
if show:
o = " (" + ', '.join([str(lst).title() for lst in options]) + ")"
while True:
a = input(question + o + ": ").lower() # User input
if a.isdigit(): # Allow users to pick via number too
a = int(a) - 1 # Set to an int
if a in range(0, len(options)):
a = options[a] # Set to value so next function completes
if a in options: # Is option valid?
answer = a
break
print("Not a valid option, try again!") # Nope
return answer # Return answer
def splitter():
print("---------------------------------------------------")
# Only do while running, used for confirmation.
while running:
PIZZA = {} # Pizza config
DELIVERY = {} # Delivery config
TOTAL = 0
# Start title
print(" MAKAN PIZZA ")
splitter()
# Delivery or pickup?
DELIVERY['type'] = ask("Type of order", ['delivery', 'pickup'])
while True:
DELIVERY['location'] = input("Location of " + DELIVERY['type'] + ": ") # Need a location
# Did they leave it blank?
if DELIVERY['location']:
break
else:
print("Please enter a valid location!")
# If delivery, ask for special instructions
if DELIVERY['type'] == "delivery":
DELIVERY['special_instructions'] = input("Special instructions (Blank for None): ")
# Do they have special instructions?
if not DELIVERY['special_instructions']:
DELIVERY['special_instructions'] = "None"
splitter()
# Size of the pizza
PIZZA['size'] = ask("Select the size", ['small', 'medium', 'large', 'jumbo', 'party'])
# Dough type
PIZZA['dough'] = ask("Select dough type", ['regular', 'whole wheat', 'carbone'])
# Type of sauce
PIZZA['sauce'] = ask("Type of sauce", ['tomato', 'pesto', 'bbq sauce', 'no sauce'])
# Type of primary cheese
PIZZA['cheese'] = ask("Type of cheese", ['mozzarella', 'cheddar', 'dairy-free', 'no cheese'])
splitter()
# Pick your topping section!
print("Pick your Toppings!", end = "")
count = -1 # Category count
for i in TOPPINGS:
start = "" # Used for the comma
# Check category and print to new line if so.
if TOPPINGS[i][0] != count:
count = TOPPINGS[i][0]
print("\n--> ", end = "")
else:
start = ", " # Split toppings
print(start + i.title(), end = "") # Print topping
# Special topping?
if TOPPINGS[i][1]:
print(" (*)", end = "")
print() # New line
# Extra functions
print("--> Typing in list will show current toppings.")
print("--> Retyping in a topping will remove it.")
print("--> Press enter once you're done!")
# Topping selector
PIZZA['toppings'] = []
while True:
top = input("Pick your topping: ") # Get input
if top == "list": # Want a list of toppings.
if not len(PIZZA['toppings']): # Do they have toppings?
print("You have no toppings!")
else:
for i in PIZZA['toppings']: # Go through and print toppings.
print("--> ", i.title())
elif not top: # Done picking.
break
else: # Picked a topping?
if top.endswith('s'): # If it ends with s, remove and check (sausages -> sausage)
top = top[:-1]
if top in TOPPINGS:
if top in PIZZA['toppings']:
print("Topping", top.title(), "has been removed from your order.")
PIZZA['toppings'].remove(top) # Remove topping
else:
print("Topping", top.title(), "has been added to your order.")
PIZZA['toppings'].append(top) # Add topping
else:
print("That topping does not exist!")
splitter()
print(" MAKAN PIZZA ORDER CONFIRMATION ")
splitter()
# Calculate the price of order and print.
print(PIZZA['size'].title() + " Pizza (CAD$" + str(SIZES[PIZZA['size']][0]) + ")")
TOTAL += SIZES[PIZZA['size']][0] # Price of size
# Free Things
print("--> " + PIZZA['dough'].title() + " (FREE)")
print("--> " + PIZZA['sauce'].title() + " (FREE)")
print("--> " + PIZZA['cheese'].title() + " (FREE)")
# Toppings
if PIZZA['toppings']:
print("--> Toppings:") # If they have any toppings, print title
# Go through all the toppings
for i in PIZZA['toppings']:
if TOPPINGS[i][1]:
tpp = TOPPING_PRICES[1][SIZES[PIZZA['size']][1]] # Special pricing
else:
tpp = TOPPING_PRICES[0][SIZES[PIZZA['size']][1]] # Non-Special pricing
print(" --> " + i.title() + " (CAD$" + format(tpp, '.2f') + ")") # Print the topping name and price
TOTAL += tpp # Add price of topping to total
splitter()
print("Sub-Total: CAD$" + format(TOTAL, '.2f')) # total
# Delivery has delivery fee (Fixed $3.50)
if DELIVERY['type'] == "delivery":
print("Delivery Fee: CAD$3.50")
TOTAL += 3.5
# Calculate and add tax
TAX = round(TOTAL * 0.13, 2)
TOTAL += TAX
print("Tax: CAD$" + format(TAX, '.2f'))
print("Total: CAD$" + format(TOTAL, '.2f'))
splitter()
CONFIRM = ask("Do you wish to confirm this order", ['yes', 'no'])
splitter()
# Done?
if CONFIRM == "yes":
break
# Final order print
print("Your order is on the way, we'll be there in 45 minutes or you get a refund!")
if DELIVERY['type'] == "delivery": # Did they get delivery?
print("Delivery to:", DELIVERY['location'], "(Special Instructions:", DELIVERY['special_instructions'] + ")")
else:
print("Pickup at:", DELIVERY['location'])
splitter()
|
running = True
sizes = {'small': [7.58, 0], 'medium': [9.69, 1], 'large': [12.09, 2], 'jumbo': [17.99, 3], 'party': [20.29, 4]}
toppings = {'pepperoni': [0, False], 'bacon': [0, True], 'sausage': [0, False], 'mushroom': [1, False], 'black olive': [1, False], 'green pepper': [1, False]}
topping_prices = [[1.6, 2.05, 2.35, 3.15, 3.3], [1.95, 2.25, 2.65, 3.49, 3.69]]
def ask(question, options, show=True):
answer = False
o = ''
if show:
o = ' (' + ', '.join([str(lst).title() for lst in options]) + ')'
while True:
a = input(question + o + ': ').lower()
if a.isdigit():
a = int(a) - 1
if a in range(0, len(options)):
a = options[a]
if a in options:
answer = a
break
print('Not a valid option, try again!')
return answer
def splitter():
print('---------------------------------------------------')
while running:
pizza = {}
delivery = {}
total = 0
print(' MAKAN PIZZA ')
splitter()
DELIVERY['type'] = ask('Type of order', ['delivery', 'pickup'])
while True:
DELIVERY['location'] = input('Location of ' + DELIVERY['type'] + ': ')
if DELIVERY['location']:
break
else:
print('Please enter a valid location!')
if DELIVERY['type'] == 'delivery':
DELIVERY['special_instructions'] = input('Special instructions (Blank for None): ')
if not DELIVERY['special_instructions']:
DELIVERY['special_instructions'] = 'None'
splitter()
PIZZA['size'] = ask('Select the size', ['small', 'medium', 'large', 'jumbo', 'party'])
PIZZA['dough'] = ask('Select dough type', ['regular', 'whole wheat', 'carbone'])
PIZZA['sauce'] = ask('Type of sauce', ['tomato', 'pesto', 'bbq sauce', 'no sauce'])
PIZZA['cheese'] = ask('Type of cheese', ['mozzarella', 'cheddar', 'dairy-free', 'no cheese'])
splitter()
print('Pick your Toppings!', end='')
count = -1
for i in TOPPINGS:
start = ''
if TOPPINGS[i][0] != count:
count = TOPPINGS[i][0]
print('\n--> ', end='')
else:
start = ', '
print(start + i.title(), end='')
if TOPPINGS[i][1]:
print(' (*)', end='')
print()
print('--> Typing in list will show current toppings.')
print('--> Retyping in a topping will remove it.')
print("--> Press enter once you're done!")
PIZZA['toppings'] = []
while True:
top = input('Pick your topping: ')
if top == 'list':
if not len(PIZZA['toppings']):
print('You have no toppings!')
else:
for i in PIZZA['toppings']:
print('--> ', i.title())
elif not top:
break
else:
if top.endswith('s'):
top = top[:-1]
if top in TOPPINGS:
if top in PIZZA['toppings']:
print('Topping', top.title(), 'has been removed from your order.')
PIZZA['toppings'].remove(top)
else:
print('Topping', top.title(), 'has been added to your order.')
PIZZA['toppings'].append(top)
else:
print('That topping does not exist!')
splitter()
print(' MAKAN PIZZA ORDER CONFIRMATION ')
splitter()
print(PIZZA['size'].title() + ' Pizza (CAD$' + str(SIZES[PIZZA['size']][0]) + ')')
total += SIZES[PIZZA['size']][0]
print('--> ' + PIZZA['dough'].title() + ' (FREE)')
print('--> ' + PIZZA['sauce'].title() + ' (FREE)')
print('--> ' + PIZZA['cheese'].title() + ' (FREE)')
if PIZZA['toppings']:
print('--> Toppings:')
for i in PIZZA['toppings']:
if TOPPINGS[i][1]:
tpp = TOPPING_PRICES[1][SIZES[PIZZA['size']][1]]
else:
tpp = TOPPING_PRICES[0][SIZES[PIZZA['size']][1]]
print(' --> ' + i.title() + ' (CAD$' + format(tpp, '.2f') + ')')
total += tpp
splitter()
print('Sub-Total: CAD$' + format(TOTAL, '.2f'))
if DELIVERY['type'] == 'delivery':
print('Delivery Fee: CAD$3.50')
total += 3.5
tax = round(TOTAL * 0.13, 2)
total += TAX
print('Tax: CAD$' + format(TAX, '.2f'))
print('Total: CAD$' + format(TOTAL, '.2f'))
splitter()
confirm = ask('Do you wish to confirm this order', ['yes', 'no'])
splitter()
if CONFIRM == 'yes':
break
print("Your order is on the way, we'll be there in 45 minutes or you get a refund!")
if DELIVERY['type'] == 'delivery':
print('Delivery to:', DELIVERY['location'], '(Special Instructions:', DELIVERY['special_instructions'] + ')')
else:
print('Pickup at:', DELIVERY['location'])
splitter()
|
#
# PySNMP MIB module EdgeSwitch-QOS-AUTOVOIP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EdgeSwitch-QOS-AUTOVOIP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:10:44 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")
ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
fastPathQOS, = mibBuilder.importSymbols("EdgeSwitch-QOS-MIB", "fastPathQOS")
InterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
NotificationType, TimeTicks, Counter32, ModuleIdentity, iso, Bits, Unsigned32, MibIdentifier, Counter64, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Gauge32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "TimeTicks", "Counter32", "ModuleIdentity", "iso", "Bits", "Unsigned32", "MibIdentifier", "Counter64", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Gauge32", "Integer32")
DisplayString, RowStatus, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention")
fastPathQOSAUTOVOIP = ModuleIdentity((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4))
fastPathQOSAUTOVOIP.setRevisions(('2012-02-18 00:00', '2011-01-26 00:00', '2007-11-23 00:00', '2007-11-23 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setRevisionsDescriptions(('Added OUI based auto VoIP support.', 'Postal address updated.', 'Ubiquiti branding related changes.', 'Initial revision.',))
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setLastUpdated('201101260000Z')
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setOrganization('Broadcom Inc')
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setContactInfo('')
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setDescription('The MIB definitions for Quality of Service - VoIP Flex package.')
agentAutoVoIPCfgGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1))
agentAutoVoIPVLAN = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPVLAN.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPVLAN.setDescription('The VLAN to which all VoIP traffic is mapped to.')
agentAutoVoIPOUIPriority = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPOUIPriority.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIPriority.setDescription('The priority to which all VoIP traffic with known OUI is mapped to.')
agentAutoVoIPProtocolPriScheme = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("trafficClass", 1), ("remark", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPProtocolPriScheme.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocolPriScheme.setDescription('The priotization scheme which is used to priritize the voice data. ')
agentAutoVoIPProtocolTcOrRemarkValue = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPProtocolTcOrRemarkValue.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocolTcOrRemarkValue.setDescription("If 'agentAutoVoIPProtocolPriScheme' is traffic class, then the object 'agentAutoVoIPProtocolTcOrRemarkValue' is CoS Queue value to which all VoIP traffic is mapped to. if 'agentAutoVoIPProtocolPriScheme' is remark, then the object 'agentAutoVoIPProtocolTcOrRemarkValue' is 802.1p priority to which all VoIP traffic is remarked at the ingress port. This is used by Protocol based Auto VoIP")
agentAutoVoIPTable = MibTable((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5), )
if mibBuilder.loadTexts: agentAutoVoIPTable.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPTable.setDescription('A table providing configuration of Auto VoIP Profile.')
agentAutoVoIPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1), ).setIndexNames((0, "EdgeSwitch-QOS-AUTOVOIP-MIB", "agentAutoVoIPIntfIndex"))
if mibBuilder.loadTexts: agentAutoVoIPEntry.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPEntry.setDescription('Auto VoIP Profile configuration for a port.')
agentAutoVoIPIntfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: agentAutoVoIPIntfIndex.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPIntfIndex.setDescription('This is a unique index for an entry in the agentAutoVoIPTable. A non-zero value indicates the ifIndex for the corresponding interface entry in the ifTable. A value of zero represents global configuration, which in turn causes all interface entries to be updated for a set operation, or reflects the most recent global setting for a get operation.')
agentAutoVoIPProtocolMode = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPProtocolMode.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocolMode.setDescription('Enables / disables AutoVoIP Protocol profile on an interface.')
agentAutoVoIPOUIMode = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPOUIMode.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIMode.setDescription('Enables / disables AutoVoIP OUI profile on an interface.')
agentAutoVoIPProtocolPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPProtocolPortStatus.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocolPortStatus.setDescription('AutoVoIP protocol profile operational status of an interface.')
agentAutoVoIPOUIPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPOUIPortStatus.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIPortStatus.setDescription('AutoVoIP OUI profile operational status of an interface.')
agentAutoVoIPOUITable = MibTable((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6), )
if mibBuilder.loadTexts: agentAutoVoIPOUITable.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUITable.setDescription('A table providing configuration of Auto VoIP Profile.')
agentAutoVoIPOUIEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1), ).setIndexNames((0, "EdgeSwitch-QOS-AUTOVOIP-MIB", "agentAutoVoIPOUIIndex"))
if mibBuilder.loadTexts: agentAutoVoIPOUIEntry.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIEntry.setDescription('Auto VoIP Profile OUI configuration.')
agentAutoVoIPOUIIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPOUIIndex.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIIndex.setDescription('The Auto VoIP OUI table index.')
agentAutoVoIPOUI = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(3, 3)).setFixedLength(3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPOUI.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUI.setDescription('The Organizationally Unique Identifier (OUI), as defined in IEEE std 802-2001, is a 24 bit (three octets) globally unique assigned number referenced by various standards, of the information received from the remote system.')
agentAutoVoIPOUIDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPOUIDesc.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIDesc.setDescription('The Description of the Organizationally Unique Identifier (OUI), as defined in IEEE std 802-2001(up to 32 characters)')
agentAutoVoIPOUIRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: agentAutoVoIPOUIRowStatus.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIRowStatus.setDescription('The row status variable is used according to installation and removal conventions for conceptual rows.')
agentAutoVoIPSessionTable = MibTable((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7), )
if mibBuilder.loadTexts: agentAutoVoIPSessionTable.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSessionTable.setDescription('A table providing configuration of Auto VoIP Profile.')
agentAutoVoIPSessionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1), ).setIndexNames((0, "EdgeSwitch-QOS-AUTOVOIP-MIB", "agentAutoVoIPSessionIndex"))
if mibBuilder.loadTexts: agentAutoVoIPSessionEntry.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSessionEntry.setDescription('Auto VoIP Session Table.')
agentAutoVoIPSessionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 127))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPSessionIndex.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSessionIndex.setDescription('The Auto VoIP session index.')
agentAutoVoIPSourceIP = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPSourceIP.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSourceIP.setDescription('The source IP address of the VoIP session.')
agentAutoVoIPDestinationIP = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 3), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPDestinationIP.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPDestinationIP.setDescription('The destination IP address of the VoIP session.')
agentAutoVoIPSourceL4Port = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPSourceL4Port.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSourceL4Port.setDescription('The source L4 Port of the VoIP session.')
agentAutoVoIPDestinationL4Port = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPDestinationL4Port.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPDestinationL4Port.setDescription('The destination L4 Port of the VoIP session.')
agentAutoVoIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPProtocol.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocol.setDescription('The Protocol of the VoIP session.')
mibBuilder.exportSymbols("EdgeSwitch-QOS-AUTOVOIP-MIB", agentAutoVoIPProtocolMode=agentAutoVoIPProtocolMode, agentAutoVoIPOUIMode=agentAutoVoIPOUIMode, agentAutoVoIPProtocol=agentAutoVoIPProtocol, agentAutoVoIPOUIDesc=agentAutoVoIPOUIDesc, agentAutoVoIPDestinationIP=agentAutoVoIPDestinationIP, agentAutoVoIPOUIEntry=agentAutoVoIPOUIEntry, agentAutoVoIPCfgGroup=agentAutoVoIPCfgGroup, agentAutoVoIPEntry=agentAutoVoIPEntry, fastPathQOSAUTOVOIP=fastPathQOSAUTOVOIP, agentAutoVoIPSessionIndex=agentAutoVoIPSessionIndex, agentAutoVoIPSourceL4Port=agentAutoVoIPSourceL4Port, agentAutoVoIPOUIPriority=agentAutoVoIPOUIPriority, agentAutoVoIPOUIIndex=agentAutoVoIPOUIIndex, agentAutoVoIPDestinationL4Port=agentAutoVoIPDestinationL4Port, agentAutoVoIPOUI=agentAutoVoIPOUI, agentAutoVoIPOUIRowStatus=agentAutoVoIPOUIRowStatus, PYSNMP_MODULE_ID=fastPathQOSAUTOVOIP, agentAutoVoIPSessionEntry=agentAutoVoIPSessionEntry, agentAutoVoIPProtocolTcOrRemarkValue=agentAutoVoIPProtocolTcOrRemarkValue, agentAutoVoIPSourceIP=agentAutoVoIPSourceIP, agentAutoVoIPTable=agentAutoVoIPTable, agentAutoVoIPProtocolPriScheme=agentAutoVoIPProtocolPriScheme, agentAutoVoIPSessionTable=agentAutoVoIPSessionTable, agentAutoVoIPOUIPortStatus=agentAutoVoIPOUIPortStatus, agentAutoVoIPOUITable=agentAutoVoIPOUITable, agentAutoVoIPProtocolPortStatus=agentAutoVoIPProtocolPortStatus, agentAutoVoIPIntfIndex=agentAutoVoIPIntfIndex, agentAutoVoIPVLAN=agentAutoVoIPVLAN)
|
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, constraints_union, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint')
(fast_path_qos,) = mibBuilder.importSymbols('EdgeSwitch-QOS-MIB', 'fastPathQOS')
(interface_index, interface_index_or_zero) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex', 'InterfaceIndexOrZero')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(notification_type, time_ticks, counter32, module_identity, iso, bits, unsigned32, mib_identifier, counter64, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, gauge32, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'TimeTicks', 'Counter32', 'ModuleIdentity', 'iso', 'Bits', 'Unsigned32', 'MibIdentifier', 'Counter64', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Gauge32', 'Integer32')
(display_string, row_status, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'RowStatus', 'TextualConvention')
fast_path_qosautovoip = module_identity((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4))
fastPathQOSAUTOVOIP.setRevisions(('2012-02-18 00:00', '2011-01-26 00:00', '2007-11-23 00:00', '2007-11-23 00:00'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
fastPathQOSAUTOVOIP.setRevisionsDescriptions(('Added OUI based auto VoIP support.', 'Postal address updated.', 'Ubiquiti branding related changes.', 'Initial revision.'))
if mibBuilder.loadTexts:
fastPathQOSAUTOVOIP.setLastUpdated('201101260000Z')
if mibBuilder.loadTexts:
fastPathQOSAUTOVOIP.setOrganization('Broadcom Inc')
if mibBuilder.loadTexts:
fastPathQOSAUTOVOIP.setContactInfo('')
if mibBuilder.loadTexts:
fastPathQOSAUTOVOIP.setDescription('The MIB definitions for Quality of Service - VoIP Flex package.')
agent_auto_vo_ip_cfg_group = mib_identifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1))
agent_auto_vo_ipvlan = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 1), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentAutoVoIPVLAN.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPVLAN.setDescription('The VLAN to which all VoIP traffic is mapped to.')
agent_auto_vo_ipoui_priority = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 2), integer32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentAutoVoIPOUIPriority.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUIPriority.setDescription('The priority to which all VoIP traffic with known OUI is mapped to.')
agent_auto_vo_ip_protocol_pri_scheme = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('trafficClass', 1), ('remark', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentAutoVoIPProtocolPriScheme.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPProtocolPriScheme.setDescription('The priotization scheme which is used to priritize the voice data. ')
agent_auto_vo_ip_protocol_tc_or_remark_value = mib_scalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 4), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 7))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentAutoVoIPProtocolTcOrRemarkValue.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPProtocolTcOrRemarkValue.setDescription("If 'agentAutoVoIPProtocolPriScheme' is traffic class, then the object 'agentAutoVoIPProtocolTcOrRemarkValue' is CoS Queue value to which all VoIP traffic is mapped to. if 'agentAutoVoIPProtocolPriScheme' is remark, then the object 'agentAutoVoIPProtocolTcOrRemarkValue' is 802.1p priority to which all VoIP traffic is remarked at the ingress port. This is used by Protocol based Auto VoIP")
agent_auto_vo_ip_table = mib_table((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5))
if mibBuilder.loadTexts:
agentAutoVoIPTable.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPTable.setDescription('A table providing configuration of Auto VoIP Profile.')
agent_auto_vo_ip_entry = mib_table_row((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1)).setIndexNames((0, 'EdgeSwitch-QOS-AUTOVOIP-MIB', 'agentAutoVoIPIntfIndex'))
if mibBuilder.loadTexts:
agentAutoVoIPEntry.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPEntry.setDescription('Auto VoIP Profile configuration for a port.')
agent_auto_vo_ip_intf_index = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 1), interface_index())
if mibBuilder.loadTexts:
agentAutoVoIPIntfIndex.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPIntfIndex.setDescription('This is a unique index for an entry in the agentAutoVoIPTable. A non-zero value indicates the ifIndex for the corresponding interface entry in the ifTable. A value of zero represents global configuration, which in turn causes all interface entries to be updated for a set operation, or reflects the most recent global setting for a get operation.')
agent_auto_vo_ip_protocol_mode = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone(2)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentAutoVoIPProtocolMode.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPProtocolMode.setDescription('Enables / disables AutoVoIP Protocol profile on an interface.')
agent_auto_vo_ipoui_mode = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone(2)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentAutoVoIPOUIMode.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUIMode.setDescription('Enables / disables AutoVoIP OUI profile on an interface.')
agent_auto_vo_ip_protocol_port_status = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('up', 1), ('down', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPProtocolPortStatus.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPProtocolPortStatus.setDescription('AutoVoIP protocol profile operational status of an interface.')
agent_auto_vo_ipoui_port_status = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('up', 1), ('down', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPOUIPortStatus.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUIPortStatus.setDescription('AutoVoIP OUI profile operational status of an interface.')
agent_auto_vo_ipoui_table = mib_table((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6))
if mibBuilder.loadTexts:
agentAutoVoIPOUITable.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUITable.setDescription('A table providing configuration of Auto VoIP Profile.')
agent_auto_vo_ipoui_entry = mib_table_row((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1)).setIndexNames((0, 'EdgeSwitch-QOS-AUTOVOIP-MIB', 'agentAutoVoIPOUIIndex'))
if mibBuilder.loadTexts:
agentAutoVoIPOUIEntry.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUIEntry.setDescription('Auto VoIP Profile OUI configuration.')
agent_auto_vo_ipoui_index = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 128))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPOUIIndex.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUIIndex.setDescription('The Auto VoIP OUI table index.')
agent_auto_vo_ipoui = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 2), octet_string().subtype(subtypeSpec=value_size_constraint(3, 3)).setFixedLength(3)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentAutoVoIPOUI.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUI.setDescription('The Organizationally Unique Identifier (OUI), as defined in IEEE std 802-2001, is a 24 bit (three octets) globally unique assigned number referenced by various standards, of the information received from the remote system.')
agent_auto_vo_ipoui_desc = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(1, 32))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentAutoVoIPOUIDesc.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUIDesc.setDescription('The Description of the Organizationally Unique Identifier (OUI), as defined in IEEE std 802-2001(up to 32 characters)')
agent_auto_vo_ipoui_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 4), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
agentAutoVoIPOUIRowStatus.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPOUIRowStatus.setDescription('The row status variable is used according to installation and removal conventions for conceptual rows.')
agent_auto_vo_ip_session_table = mib_table((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7))
if mibBuilder.loadTexts:
agentAutoVoIPSessionTable.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPSessionTable.setDescription('A table providing configuration of Auto VoIP Profile.')
agent_auto_vo_ip_session_entry = mib_table_row((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1)).setIndexNames((0, 'EdgeSwitch-QOS-AUTOVOIP-MIB', 'agentAutoVoIPSessionIndex'))
if mibBuilder.loadTexts:
agentAutoVoIPSessionEntry.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPSessionEntry.setDescription('Auto VoIP Session Table.')
agent_auto_vo_ip_session_index = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 127))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPSessionIndex.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPSessionIndex.setDescription('The Auto VoIP session index.')
agent_auto_vo_ip_source_ip = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 2), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPSourceIP.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPSourceIP.setDescription('The source IP address of the VoIP session.')
agent_auto_vo_ip_destination_ip = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 3), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPDestinationIP.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPDestinationIP.setDescription('The destination IP address of the VoIP session.')
agent_auto_vo_ip_source_l4_port = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 4), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPSourceL4Port.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPSourceL4Port.setDescription('The source L4 Port of the VoIP session.')
agent_auto_vo_ip_destination_l4_port = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 5), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPDestinationL4Port.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPDestinationL4Port.setDescription('The destination L4 Port of the VoIP session.')
agent_auto_vo_ip_protocol = mib_table_column((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 6), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentAutoVoIPProtocol.setStatus('current')
if mibBuilder.loadTexts:
agentAutoVoIPProtocol.setDescription('The Protocol of the VoIP session.')
mibBuilder.exportSymbols('EdgeSwitch-QOS-AUTOVOIP-MIB', agentAutoVoIPProtocolMode=agentAutoVoIPProtocolMode, agentAutoVoIPOUIMode=agentAutoVoIPOUIMode, agentAutoVoIPProtocol=agentAutoVoIPProtocol, agentAutoVoIPOUIDesc=agentAutoVoIPOUIDesc, agentAutoVoIPDestinationIP=agentAutoVoIPDestinationIP, agentAutoVoIPOUIEntry=agentAutoVoIPOUIEntry, agentAutoVoIPCfgGroup=agentAutoVoIPCfgGroup, agentAutoVoIPEntry=agentAutoVoIPEntry, fastPathQOSAUTOVOIP=fastPathQOSAUTOVOIP, agentAutoVoIPSessionIndex=agentAutoVoIPSessionIndex, agentAutoVoIPSourceL4Port=agentAutoVoIPSourceL4Port, agentAutoVoIPOUIPriority=agentAutoVoIPOUIPriority, agentAutoVoIPOUIIndex=agentAutoVoIPOUIIndex, agentAutoVoIPDestinationL4Port=agentAutoVoIPDestinationL4Port, agentAutoVoIPOUI=agentAutoVoIPOUI, agentAutoVoIPOUIRowStatus=agentAutoVoIPOUIRowStatus, PYSNMP_MODULE_ID=fastPathQOSAUTOVOIP, agentAutoVoIPSessionEntry=agentAutoVoIPSessionEntry, agentAutoVoIPProtocolTcOrRemarkValue=agentAutoVoIPProtocolTcOrRemarkValue, agentAutoVoIPSourceIP=agentAutoVoIPSourceIP, agentAutoVoIPTable=agentAutoVoIPTable, agentAutoVoIPProtocolPriScheme=agentAutoVoIPProtocolPriScheme, agentAutoVoIPSessionTable=agentAutoVoIPSessionTable, agentAutoVoIPOUIPortStatus=agentAutoVoIPOUIPortStatus, agentAutoVoIPOUITable=agentAutoVoIPOUITable, agentAutoVoIPProtocolPortStatus=agentAutoVoIPProtocolPortStatus, agentAutoVoIPIntfIndex=agentAutoVoIPIntfIndex, agentAutoVoIPVLAN=agentAutoVoIPVLAN)
|
def reverse(my_list):
if type(my_list) != list:
return f"{my_list} is not a list"
elif len(my_list) ==0:
return 'list should not be empty'
reversed_list = my_list[::-1]
return reversed_list
if __name__ == "__main__":
riddle_index = 0
|
def reverse(my_list):
if type(my_list) != list:
return f'{my_list} is not a list'
elif len(my_list) == 0:
return 'list should not be empty'
reversed_list = my_list[::-1]
return reversed_list
if __name__ == '__main__':
riddle_index = 0
|
class _dafny:
def print(value):
if type(value) == bool:
print("true" if value else "false", end="")
elif type(value) == property:
print(value.fget(), end="")
else:
print(value, end="")
|
class _Dafny:
def print(value):
if type(value) == bool:
print('true' if value else 'false', end='')
elif type(value) == property:
print(value.fget(), end='')
else:
print(value, end='')
|
limit=int(input("enter the limit"))
no=int(input("enter the no"))
for i in range(1,limit+1,1):
multi=no*i
print(no,"*",i,"=",multi)
|
limit = int(input('enter the limit'))
no = int(input('enter the no'))
for i in range(1, limit + 1, 1):
multi = no * i
print(no, '*', i, '=', multi)
|
"""Exceptions raised by `e2e.pom` at runtime."""
class PomError(Exception):
"""Base exception from which all `e2e.pom` errors inherit."""
class ElementNotUniqueErrror(PomError):
"""Raised when multiple DOM matches are found for a "unique" model."""
class ElementNotFoundErrror(PomError):
"""Raised when no DOM matches are found for a "unique" model."""
|
"""Exceptions raised by `e2e.pom` at runtime."""
class Pomerror(Exception):
"""Base exception from which all `e2e.pom` errors inherit."""
class Elementnotuniqueerrror(PomError):
"""Raised when multiple DOM matches are found for a "unique" model."""
class Elementnotfounderrror(PomError):
"""Raised when no DOM matches are found for a "unique" model."""
|
class Arithmetic:
def __init__(self, command):
self.text = command
def operation(self):
return self.text.strip()
class MemoryAccess:
def __init__(self, command):
self.op, self.seg, self.idx = tuple(command.split())
def operation(self):
return self.op
def segment(self):
return self.seg
def index(self):
return self.idx
class ProgramFlow:
def __init__(self, command, function):
self.op, self.lb = tuple(command.split())
self.func = function
def operation(self):
return self.op
def label(self):
return f'{self.func}${self.lb}'
class FunctionCall:
def __init__(self, command):
self.cmd = tuple(command.split())
def operation(self):
return self.cmd[0]
def func_name(self):
return self.cmd[1]
def arg_count(self):
return int(self.cmd[2])
|
class Arithmetic:
def __init__(self, command):
self.text = command
def operation(self):
return self.text.strip()
class Memoryaccess:
def __init__(self, command):
(self.op, self.seg, self.idx) = tuple(command.split())
def operation(self):
return self.op
def segment(self):
return self.seg
def index(self):
return self.idx
class Programflow:
def __init__(self, command, function):
(self.op, self.lb) = tuple(command.split())
self.func = function
def operation(self):
return self.op
def label(self):
return f'{self.func}${self.lb}'
class Functioncall:
def __init__(self, command):
self.cmd = tuple(command.split())
def operation(self):
return self.cmd[0]
def func_name(self):
return self.cmd[1]
def arg_count(self):
return int(self.cmd[2])
|
N = int(input())
pokemons = []
while (N != 0):
Name = input()
pokemons.append(Name)
N-= 1
print('Falta(m) {} pomekon(s).'.format(151 - len(set(pokemons))))
|
n = int(input())
pokemons = []
while N != 0:
name = input()
pokemons.append(Name)
n -= 1
print('Falta(m) {} pomekon(s).'.format(151 - len(set(pokemons))))
|
def count_salutes(hallway):
count=hallway.count("<")
total=0
for i in hallway:
count-=i=="<"
if i==">":
total+=count*2
return total
|
def count_salutes(hallway):
count = hallway.count('<')
total = 0
for i in hallway:
count -= i == '<'
if i == '>':
total += count * 2
return total
|
# Python - 3.6.0
Test.assert_equals(catch_sign_change([1, 3, 4, 5]), 0)
Test.assert_equals(catch_sign_change([1, -3, -4, 0, 5]), 2)
Test.assert_equals(catch_sign_change([]), 0)
Test.assert_equals(catch_sign_change([-47, 84, -30, -11, -5, 74, 77]), 3)
|
Test.assert_equals(catch_sign_change([1, 3, 4, 5]), 0)
Test.assert_equals(catch_sign_change([1, -3, -4, 0, 5]), 2)
Test.assert_equals(catch_sign_change([]), 0)
Test.assert_equals(catch_sign_change([-47, 84, -30, -11, -5, 74, 77]), 3)
|
{
'targets': [
{
'target_name': 'murmurhash3',
'sources': ['src/MurmurHash3.cpp', 'src/node_murmurhash3.cc'],
'cflags': ['-fexceptions'],
'cflags_cc': ['-fexceptions'],
'cflags!': ['-fno-exceptions'],
'cflags_cc!': ['-fno-exception'],
"include_dirs" : [
"<!(node -e \"require('nan')\")"
],
'conditions': [
['OS=="win"', {
'msvs_settings': {
'VCCLCompilerTool': {
'AdditionalOptions': [ '/EHsc' ]
}
}
}
],
['OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'
}
}
]
]
}
]
}
|
{'targets': [{'target_name': 'murmurhash3', 'sources': ['src/MurmurHash3.cpp', 'src/node_murmurhash3.cc'], 'cflags': ['-fexceptions'], 'cflags_cc': ['-fexceptions'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exception'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'conditions': [['OS=="win"', {'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': ['/EHsc']}}}], ['OS=="mac"', {'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'}}]]}]}
|
def create_desktop_file_KDE():
path="/usr/share/applications/klusta_process_manager.desktop"
text=["[Desktop Entry]",
"Version=0.1",
"Name=klusta_process_manager",
"Comment=GUI",
"Exec=klusta_process_manager",
"Icon=eyes",
"Terminal=False",
"Type=Application",
"Categories=Applications;"]
with open(path,"w") as f:
f.write("\n".join(text))
if __name__=="__main__":
print("Create a .desktop file in /usr/share/application")
print("Only tested with Linux OpenSuse KDE")
print("--------------")
try:
create_desktop_file_KDE()
print("Shortcut created !")
except PermissionError:
print("Needs admin rights: try 'sudo python create_shortcut.py'")
|
def create_desktop_file_kde():
path = '/usr/share/applications/klusta_process_manager.desktop'
text = ['[Desktop Entry]', 'Version=0.1', 'Name=klusta_process_manager', 'Comment=GUI', 'Exec=klusta_process_manager', 'Icon=eyes', 'Terminal=False', 'Type=Application', 'Categories=Applications;']
with open(path, 'w') as f:
f.write('\n'.join(text))
if __name__ == '__main__':
print('Create a .desktop file in /usr/share/application')
print('Only tested with Linux OpenSuse KDE')
print('--------------')
try:
create_desktop_file_kde()
print('Shortcut created !')
except PermissionError:
print("Needs admin rights: try 'sudo python create_shortcut.py'")
|
class BinarySearchTreeNode:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def add_child(self,data):
if data == self.data:
return
if data <self.data:
#add on the left side of the subtree
if self.left:
self.left.add_child(data)
else:
self.left = BinarySearchTreeNode(data)
else:
#add on the right side of the subtree
if self.right:
self.right.add_child(data)
else:
self.right = BinarySearchTreeNode(data)
def in_order_traversal(self):
elements=[]
#visits left tree
if self.left:
elements+=self.left.in_order_traversal()
#visits root node
elements.append(self.data)
#visits right tree
if self.right:
elements+=self.right.in_order_traversal()
return elements
def post_traversal(self):
elements=[]
#visits left tree
if self.left:
elements+=self.left.post_traversal()
#vists right tree
if self.right:
elements+=self.right.post_traversal()
#vists root
elements.append(self.data)
def pre_traversal(self):
elements=[self.data]
#visits left tree
if self.left:
elements+=self.left.append.pre_traversal()
#visits right tree
if self.right:
elements+=self.right.append.pre_traversal()
def find_max(self):
if self.right is None:
return self.data
return self.right.find_max()
def find_min(self):
if self.left is None:
return self.data
return self.left.find_min()
def calculate_sum(self):
left_sum = self.left.calculate_sum() if self.left else 0
right_sum = self.right.calculate_sum() if self.right else 0
return self.data + left_sum + right_sum
def build_tree(elements):
root=BinarySearchTreeNode(elements[0])
for i in range(1,len(elements)):
root.add_child(elements[i])
return root
if __name__ == '__main__':
numbers = [17, 4, 1, 20, 9, 23, 18, 34]
numbers = [15,12,7,14,27,20,23,88 ]
numbers_tree = build_tree(numbers)
print("Input numbers:",numbers)
print("Min:",numbers_tree.find_min())
print("Max:",numbers_tree.find_max())
print("Sum:", numbers_tree.calculate_sum())
print("In order traversal:", numbers_tree.in_order_traversal())
print("Pre order traversal:", numbers_tree.pre_traversal())
print("Post order traversal:", numbers_tree.post_traversal())
|
class Binarysearchtreenode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def add_child(self, data):
if data == self.data:
return
if data < self.data:
if self.left:
self.left.add_child(data)
else:
self.left = binary_search_tree_node(data)
elif self.right:
self.right.add_child(data)
else:
self.right = binary_search_tree_node(data)
def in_order_traversal(self):
elements = []
if self.left:
elements += self.left.in_order_traversal()
elements.append(self.data)
if self.right:
elements += self.right.in_order_traversal()
return elements
def post_traversal(self):
elements = []
if self.left:
elements += self.left.post_traversal()
if self.right:
elements += self.right.post_traversal()
elements.append(self.data)
def pre_traversal(self):
elements = [self.data]
if self.left:
elements += self.left.append.pre_traversal()
if self.right:
elements += self.right.append.pre_traversal()
def find_max(self):
if self.right is None:
return self.data
return self.right.find_max()
def find_min(self):
if self.left is None:
return self.data
return self.left.find_min()
def calculate_sum(self):
left_sum = self.left.calculate_sum() if self.left else 0
right_sum = self.right.calculate_sum() if self.right else 0
return self.data + left_sum + right_sum
def build_tree(elements):
root = binary_search_tree_node(elements[0])
for i in range(1, len(elements)):
root.add_child(elements[i])
return root
if __name__ == '__main__':
numbers = [17, 4, 1, 20, 9, 23, 18, 34]
numbers = [15, 12, 7, 14, 27, 20, 23, 88]
numbers_tree = build_tree(numbers)
print('Input numbers:', numbers)
print('Min:', numbers_tree.find_min())
print('Max:', numbers_tree.find_max())
print('Sum:', numbers_tree.calculate_sum())
print('In order traversal:', numbers_tree.in_order_traversal())
print('Pre order traversal:', numbers_tree.pre_traversal())
print('Post order traversal:', numbers_tree.post_traversal())
|
# -*- coding: utf-8 -*-
# Scrapy settings for cosme project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'cosme'
SPIDER_MODULES = ['cosme.spiders']
NEWSPIDER_MODULE = 'cosme.spiders'
DOWNLOAD_DELAY = 1.5
COOKIES_ENABLES = False
ITEM_PIPELINES = {
# 'cosme.pipelines.CosmePipeline': 1,
# 'cosme.pipelines.ProductPipeline': 1,
'cosme.pipelines.ProductDetailPipeline': 1,
}
#---mysql config---
HOST, DB, USER, PWD = '127.0.0.1', 'cosme', 'root', '123456'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'cosme (+http://www.yourdomain.com)'
|
bot_name = 'cosme'
spider_modules = ['cosme.spiders']
newspider_module = 'cosme.spiders'
download_delay = 1.5
cookies_enables = False
item_pipelines = {'cosme.pipelines.ProductDetailPipeline': 1}
(host, db, user, pwd) = ('127.0.0.1', 'cosme', 'root', '123456')
|
# Time: O(n)
# Space: O(h), h is height of binary tree
# 129
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
#
# An example is the root-to-leaf path 1->2->3 which represents the number 123.
#
# Find the total sum of all root-to-leaf numbers.
#
# For example,
#
# 1
# / \
# 2 3
# The root-to-leaf path 1->2 represents the number 12.
# The root-to-leaf path 1->3 represents the number 13.
#
# Return the sum = 12 + 13 = 25.
#
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def sumNumbers(self, root: TreeNode) -> int: # USE THIS
ans = 0
stack = [(root, 0)]
while stack:
node, v = stack.pop()
if node:
if not node.left and not node.right:
ans += v*10 + node.val
else:
stack.append((node.right, v*10+node.val))
stack.append((node.left, v*10+node.val))
return ans
def sumNumbers_rec1(self, root):
return self.recu(root, 0)
def recu(self, root, num):
if root is None:
return 0
if root.left is None and root.right is None:
return num * 10 + root.val
return self.recu(root.left, num * 10 + root.val) + self.recu(root.right, num * 10 + root.val)
# the following recursion is not very good (use global var, don't leverage return value)
def sumNumbers_rec2(self, root: TreeNode) -> int:
def dfs(node, v):
if node:
if not (node.left or node.right):
self.ans += v*10 + node.val
return
dfs(node.left, v*10+node.val)
dfs(node.right, v*10+node.val)
self.ans = 0
dfs(root, 0)
return self.ans
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
print(Solution().sumNumbers(root)) # 137
|
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sum_numbers(self, root: TreeNode) -> int:
ans = 0
stack = [(root, 0)]
while stack:
(node, v) = stack.pop()
if node:
if not node.left and (not node.right):
ans += v * 10 + node.val
else:
stack.append((node.right, v * 10 + node.val))
stack.append((node.left, v * 10 + node.val))
return ans
def sum_numbers_rec1(self, root):
return self.recu(root, 0)
def recu(self, root, num):
if root is None:
return 0
if root.left is None and root.right is None:
return num * 10 + root.val
return self.recu(root.left, num * 10 + root.val) + self.recu(root.right, num * 10 + root.val)
def sum_numbers_rec2(self, root: TreeNode) -> int:
def dfs(node, v):
if node:
if not (node.left or node.right):
self.ans += v * 10 + node.val
return
dfs(node.left, v * 10 + node.val)
dfs(node.right, v * 10 + node.val)
self.ans = 0
dfs(root, 0)
return self.ans
if __name__ == '__main__':
root = tree_node(1)
root.left = tree_node(2)
root.right = tree_node(3)
root.left.left = tree_node(4)
print(solution().sumNumbers(root))
|
"""
Georgia Institute of Technology - CS1301
HW04 - Strings, Indexing and Lists
"""
#########################################
"""
Function Name: findMax()
Parameters: a caption list of numbers (list), start index (int), stop index (int)
Returns: highest number (int)
"""
def findMax(theNumbersMason, theStart, theEnd):
highscore = theNumbersMason[theStart]
for x in theNumbersMason[theStart:theEnd+1]:
if x > highscore:
highscore = x
return highscore
#########################################
"""
Function Name: fruitPie()
Parameters: list of fruits (list), minimum quantity (int)
Returns: list of fruits (list)
"""
def fruitPie(theFruit, theMin):
acceptableFruit = []
for x in range(0, len(theFruit)):
if x % 2 != 0 and theFruit[x] >= theMin:
acceptableFruit.append(theFruit[x-1])
return acceptableFruit
#########################################
"""
Function Name: replaceWord()
Parameters: initial sentence (str), replacement word (str)
Returns: corrected sentence (str)
"""
def replaceWord(sentence, word):
segments = sentence.split()
sentence = ""
for x in segments:
if len(x) >= 5:
sentence = sentence + word + " "
else:
sentence = sentence + x + " "
return sentence[0:len(sentence) - 1]
#########################################
"""
Function Name: highestSum()
Parameters: list of strings (strings)
Returns: index of string with the highest sum (int)
"""
def highestSum(theStrings):
high = [0, 0] # index, score
for x in range(0, len(theStrings)):
sum = 0
for y in theStrings[x]:
if y.isdigit():
sum = sum + int(y)
if sum > high[1]:
high = [x, sum]
return high[0]
#########################################
"""
Function: sublist()
Parameters: alist (list), blist (list)
Returns: True or False (`boolean`)
"""
def sublist(aList, bList):
bLength = len(bList)
if bLength == 0:
return True
for x in aList:
if x == bList[0]:
if len(bList) == 1:
return True
bList = bList[1:len(bList)]
else:
if bLength != len(bList):
return False
return False
|
"""
Georgia Institute of Technology - CS1301
HW04 - Strings, Indexing and Lists
"""
'\nFunction Name: findMax()\nParameters: a caption list of numbers (list), start index (int), stop index (int)\nReturns: highest number (int)\n'
def find_max(theNumbersMason, theStart, theEnd):
highscore = theNumbersMason[theStart]
for x in theNumbersMason[theStart:theEnd + 1]:
if x > highscore:
highscore = x
return highscore
'\nFunction Name: fruitPie()\nParameters: list of fruits (list), minimum quantity (int)\nReturns: list of fruits (list)\n'
def fruit_pie(theFruit, theMin):
acceptable_fruit = []
for x in range(0, len(theFruit)):
if x % 2 != 0 and theFruit[x] >= theMin:
acceptableFruit.append(theFruit[x - 1])
return acceptableFruit
'\nFunction Name: replaceWord()\nParameters: initial sentence (str), replacement word (str)\nReturns: corrected sentence (str)\n'
def replace_word(sentence, word):
segments = sentence.split()
sentence = ''
for x in segments:
if len(x) >= 5:
sentence = sentence + word + ' '
else:
sentence = sentence + x + ' '
return sentence[0:len(sentence) - 1]
'\nFunction Name: highestSum()\nParameters: list of strings (strings)\nReturns: index of string with the highest sum (int)\n'
def highest_sum(theStrings):
high = [0, 0]
for x in range(0, len(theStrings)):
sum = 0
for y in theStrings[x]:
if y.isdigit():
sum = sum + int(y)
if sum > high[1]:
high = [x, sum]
return high[0]
'\nFunction: sublist()\nParameters: alist (list), blist (list)\nReturns: True or False (`boolean`)\n'
def sublist(aList, bList):
b_length = len(bList)
if bLength == 0:
return True
for x in aList:
if x == bList[0]:
if len(bList) == 1:
return True
b_list = bList[1:len(bList)]
elif bLength != len(bList):
return False
return False
|
"""
Midi pitch values:
A0 has value 21
C8 has value 108
"""
NAME_TO_VAL = {
"C": 0,
"D": 2,
"E": 4,
"F": 5,
"G": 7,
"A": 9,
"B": 11,
}
def name_to_val(name):
name = name.upper()
note = name[0]
mod = None
octave = None
offset = 12
if name[1] in ("#", "B"):
mod = name[1]
octave = int(name[2:])
else:
octave = int(name[1:])
val = NAME_TO_VAL[note]
if mod == "#":
val += 1
elif mod == "B":
val -= 1
val += octave * 12
val += offset
return val
|
"""
Midi pitch values:
A0 has value 21
C8 has value 108
"""
name_to_val = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
def name_to_val(name):
name = name.upper()
note = name[0]
mod = None
octave = None
offset = 12
if name[1] in ('#', 'B'):
mod = name[1]
octave = int(name[2:])
else:
octave = int(name[1:])
val = NAME_TO_VAL[note]
if mod == '#':
val += 1
elif mod == 'B':
val -= 1
val += octave * 12
val += offset
return val
|
task = int(input())
points = int(input())
course = input()
if task == 1:
if course == 'Basics':
points = points * 0.08 - (0.2 * (points * 0.08))
elif course == 'Fundamentals':
points = points * 0.11
elif course == 'Advanced':
points = points * 0.14 + (0.2 * (points * 0.14))
elif task == 2:
if course == 'Basics':
points = points * 0.09
elif course == 'Fundamentals':
points = points * 0.11
elif course == 'Advanced':
points = points * 0.14 + (0.2 * (points * 0.14))
elif task == 3:
if course == 'Basics':
points = points * 0.09
elif course == 'Fundamentals':
points = points * 0.12
elif course == 'Advanced':
points = points * 0.15 + (0.2 * (points * 0.15))
elif task == 4:
if course == 'Basics':
points = points * 0.10
elif course == 'Fundamentals':
points = points * 0.13
elif course == 'Advanced':
points = points * 0.16 + (0.2 * (points * 0.16))
print(f'Total points: {points:.2f}')
|
task = int(input())
points = int(input())
course = input()
if task == 1:
if course == 'Basics':
points = points * 0.08 - 0.2 * (points * 0.08)
elif course == 'Fundamentals':
points = points * 0.11
elif course == 'Advanced':
points = points * 0.14 + 0.2 * (points * 0.14)
elif task == 2:
if course == 'Basics':
points = points * 0.09
elif course == 'Fundamentals':
points = points * 0.11
elif course == 'Advanced':
points = points * 0.14 + 0.2 * (points * 0.14)
elif task == 3:
if course == 'Basics':
points = points * 0.09
elif course == 'Fundamentals':
points = points * 0.12
elif course == 'Advanced':
points = points * 0.15 + 0.2 * (points * 0.15)
elif task == 4:
if course == 'Basics':
points = points * 0.1
elif course == 'Fundamentals':
points = points * 0.13
elif course == 'Advanced':
points = points * 0.16 + 0.2 * (points * 0.16)
print(f'Total points: {points:.2f}')
|
# Given a number N, print the odd digits in the number(space seperated) or print -1 if there is no odd digit in the given number.
number = int(input(''))
array = list(str(number))
flag = 0
for digit in range(0, len(array)-1):
if(int(array[digit]) % 2 == 0):
print(' ', end='')
else:
print(array[digit], end='')
flag = flag+1
if(int(array[len(array)-1]) % 2 == 0):
print('', end='')
else:
print(int(array[len(array)-1]), end='')
if(flag == 0):
print(-1)
|
number = int(input(''))
array = list(str(number))
flag = 0
for digit in range(0, len(array) - 1):
if int(array[digit]) % 2 == 0:
print(' ', end='')
else:
print(array[digit], end='')
flag = flag + 1
if int(array[len(array) - 1]) % 2 == 0:
print('', end='')
else:
print(int(array[len(array) - 1]), end='')
if flag == 0:
print(-1)
|
"""A function to reverse a string.
By Ted Silbernagel
"""
def reverse_string(input_word: str) -> str:
return_word = ''
for _ in input_word:
return_word += input_word[-1:]
input_word = input_word[:-1]
return return_word
if __name__ == '__main__':
user_string = input('Please enter a word/string to reverse: ')
result = reverse_string(user_string)
print(result)
|
"""A function to reverse a string.
By Ted Silbernagel
"""
def reverse_string(input_word: str) -> str:
return_word = ''
for _ in input_word:
return_word += input_word[-1:]
input_word = input_word[:-1]
return return_word
if __name__ == '__main__':
user_string = input('Please enter a word/string to reverse: ')
result = reverse_string(user_string)
print(result)
|
"""
File: forestfire.py
----------------
This program highlights fires in an image by identifying
pixels who red intensity is more than INTENSITY_THRESHOLD times
the average of the red, green, and blue values at a pixel.
Those "sufficiently red" pixels are then highlighted in the
image and the rest of the image is turned grey, by setting the
pixels red, green, and blue values all to be the same average
value.
"""
def main():
# write a program to ask user their height in METERS
# it will be a float!
# evaluate if their height is too short or too tall or ok to ride
# print response depending on evaluation
# precondition: we don't know if they can ride
# postcondition: we know if they can ride and tell them.
# what is their height in meters?
rider_height = float(input("Enter height in meters: "))
if (rider_height < 1 or rider_height > 2):
print("You can't ride the roller coaster.")
else:
print("You can ride the roller coaster.")
if __name__ == '__main__':
main()
|
"""
File: forestfire.py
----------------
This program highlights fires in an image by identifying
pixels who red intensity is more than INTENSITY_THRESHOLD times
the average of the red, green, and blue values at a pixel.
Those "sufficiently red" pixels are then highlighted in the
image and the rest of the image is turned grey, by setting the
pixels red, green, and blue values all to be the same average
value.
"""
def main():
rider_height = float(input('Enter height in meters: '))
if rider_height < 1 or rider_height > 2:
print("You can't ride the roller coaster.")
else:
print('You can ride the roller coaster.')
if __name__ == '__main__':
main()
|
t5_generation_config = {
"do_sample": True,
"num_beams": 2,
"repetition_penalty": 5.0,
"length_penalty": 1.0,
"num_return_sequences": 1,
}
GPT2_generation_config = {
"do_sample": True,
"num_beams": 2,
"repetition_penalty": 5.0,
"length_penalty": 1.0,
}
|
t5_generation_config = {'do_sample': True, 'num_beams': 2, 'repetition_penalty': 5.0, 'length_penalty': 1.0, 'num_return_sequences': 1}
gpt2_generation_config = {'do_sample': True, 'num_beams': 2, 'repetition_penalty': 5.0, 'length_penalty': 1.0}
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 12:11:09 2019
@author: DiPu
"""
A1=int(input())
A2=int(input())
A3=int(input())
E1=int(input())
E2=int(input())
weighted_score=((A1+A2+A3)*0.1)+((E1+E2)*0.35 )
print("weightrd score is",weighted_score)
|
"""
Created on Tue May 7 12:11:09 2019
@author: DiPu
"""
a1 = int(input())
a2 = int(input())
a3 = int(input())
e1 = int(input())
e2 = int(input())
weighted_score = (A1 + A2 + A3) * 0.1 + (E1 + E2) * 0.35
print('weightrd score is', weighted_score)
|
# Pyomniar
# Copyright 2011 Chris Kelly
# See LICENSE for details.
class OmniarError(Exception):
"""Omniar exception"""
def __init__(self, reason, response=None):
self.reason = unicode(reason)
self.response = response
def __str__(self):
return self.reason
|
class Omniarerror(Exception):
"""Omniar exception"""
def __init__(self, reason, response=None):
self.reason = unicode(reason)
self.response = response
def __str__(self):
return self.reason
|
while True:
number = int(input('Enter a number: '))
while number != 1:
if number % 2 == 0:
number //= 2
else:
number = number * 3 + 1
print(number)
print()
|
while True:
number = int(input('Enter a number: '))
while number != 1:
if number % 2 == 0:
number //= 2
else:
number = number * 3 + 1
print(number)
print()
|
# ------------------------------
# 276. Paint Fence
#
# Description:
# There is a fence with n posts, each post can be painted with one of the k colors.
# You have to paint all the posts such that no more than two adjacent fence posts have the same color.
#
# Return the total number of ways you can paint the fence.
#
# Note:
# n and k are non-negative integers.
#
# Version: 1.0
# 12/11/17 by Jianfa
# ------------------------------
class Solution(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0:
return 0
if n == 1:
return k
same, diff = k, k * (k-1)
for i in range(3, n + 1): # Note it's n + 1 here, not n
same, diff = diff, (same + diff) * (k-1)
return same + diff
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get the idea from "Python solution with explanation" in discuss section
# If n == 1, there would be k-ways to paint.
#
# if n == 2, there would be two situations:
#
# 2.1 You paint same color with the previous post: k*1 ways to paint, named it as same
# 2.2 You paint differently with the previous post: k*(k-1) ways to paint this way, named it as dif
# So, you can think, if n >= 3, you can always maintain these two situations,
# You either paint the same color with the previous one, or differently.
#
# Since there is a rule: "no more than two adjacent fence posts have the same color."
#
# We can further analyze:
#
# from 2.1, since previous two are in the same color, next one you could only paint differently, and it would
# form one part of "paint differently" case in the n == 3 level, and the number of ways to paint this way
# would equal to same*(k-1).
# from 2.2, since previous two are not the same, you can either paint the same color this time (dif*1) ways
# to do so, or stick to paint differently (dif*(k-1)) times.
# Here you can conclude, when seeing back from the next level, ways to paint the same, or variable same would
# equal to dif*1 = dif, and ways to paint differently, variable dif, would equal to same*(k-1)+dif*(k-1) = (same + dif)*(k-1)
|
class Solution(object):
def num_ways(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0:
return 0
if n == 1:
return k
(same, diff) = (k, k * (k - 1))
for i in range(3, n + 1):
(same, diff) = (diff, (same + diff) * (k - 1))
return same + diff
if __name__ == '__main__':
test = solution()
|
#Conditional if
x = 22
y = 100
if y < x:
print("This is True, y is not greater than x!")
elif y == x:
print("This is True, y is greater than x!")
else:
print("Anything else!")
print("Completed")
|
x = 22
y = 100
if y < x:
print('This is True, y is not greater than x!')
elif y == x:
print('This is True, y is greater than x!')
else:
print('Anything else!')
print('Completed')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
models
----------------------------------
Models store record state during parsing and serialisation to other formats.
"""
class InventoryItem(object):
""" Inventory Item Model """
def __init__(self, id=None, price=None, description=None, cost=None, price_type=None,
quantity_on_hand=None, modifiers=[]):
self._id = id
self._price = price
self._description = description
self._cost = cost
self._price_type = price_type
self._quantity_on_hand = quantity_on_hand
self._modifiers = modifiers
@property
def id(self):
""" get id property """
return self._id
@id.setter
def id(self, id):
""" set id property """
self._id = id
@property
def price(self):
""" get price property """
return self._price
@price.setter
def price(self, price):
""" set price property """
self._price = price
@property
def description(self):
""" get description property """
return self._description
@description.setter
def description(self, _description):
""" set description property """
self._description = _description
@property
def cost(self):
""" set cost property """
return self._cost
@cost.setter
def cost(self, cost):
""" get cost property """
self._cost = cost
@property
def price_type(self):
""" get price_type property """
return self._price_type
@price_type.setter
def price_type(self, price_type):
""" set price_type property """
self._price_type = price_type
@property
def quantity_on_hand(self):
""" set quantity_on_hand property """
return self._quantity_on_hand
@quantity_on_hand.setter
def quantity_on_hand(self, quantity_on_hand):
""" get quantity_on_hand property """
self._quantity_on_hand = quantity_on_hand
@property
def modifiers(self):
""" get modifiers property """
return self._modifiers
@modifiers.setter
def modifiers(self, modifiers):
""" set modifiers property """
self._modifiers = modifiers
|
"""
models
----------------------------------
Models store record state during parsing and serialisation to other formats.
"""
class Inventoryitem(object):
""" Inventory Item Model """
def __init__(self, id=None, price=None, description=None, cost=None, price_type=None, quantity_on_hand=None, modifiers=[]):
self._id = id
self._price = price
self._description = description
self._cost = cost
self._price_type = price_type
self._quantity_on_hand = quantity_on_hand
self._modifiers = modifiers
@property
def id(self):
""" get id property """
return self._id
@id.setter
def id(self, id):
""" set id property """
self._id = id
@property
def price(self):
""" get price property """
return self._price
@price.setter
def price(self, price):
""" set price property """
self._price = price
@property
def description(self):
""" get description property """
return self._description
@description.setter
def description(self, _description):
""" set description property """
self._description = _description
@property
def cost(self):
""" set cost property """
return self._cost
@cost.setter
def cost(self, cost):
""" get cost property """
self._cost = cost
@property
def price_type(self):
""" get price_type property """
return self._price_type
@price_type.setter
def price_type(self, price_type):
""" set price_type property """
self._price_type = price_type
@property
def quantity_on_hand(self):
""" set quantity_on_hand property """
return self._quantity_on_hand
@quantity_on_hand.setter
def quantity_on_hand(self, quantity_on_hand):
""" get quantity_on_hand property """
self._quantity_on_hand = quantity_on_hand
@property
def modifiers(self):
""" get modifiers property """
return self._modifiers
@modifiers.setter
def modifiers(self, modifiers):
""" set modifiers property """
self._modifiers = modifiers
|
""""""
_TEST_TEMPLATE = """#!/bin/bash
# Unset TEST_SRCDIR since we're trying to test the non-test behavior
unset TEST_SRCDIR
# --- begin runfiles.bash initialization v2 ---
# Copy-pasted from the Bazel Bash runfiles library v2.
set -uo pipefail; f=bazel_tools/tools/bash/runfiles/runfiles.bash
source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \
source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \
source "$0.runfiles/$f" 2>/dev/null || \
source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
{ echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e
# --- end runfiles.bash initialization v2 ---
runfiles_export_envvars
$(rlocation {nested_tool})
"""
def _runfiles_path(ctx, file):
if file.short_path.startswith("../"):
return file.short_path[3:]
else:
return ctx.workspace_name + "/" + file.short_path
def _impl(ctx):
runfiles = ctx.runfiles()
runfiles = runfiles.merge(ctx.attr._bash_runfiles.default_runfiles)
runfiles = runfiles.merge(ctx.attr.nested_tool.default_runfiles)
script = ctx.actions.declare_file(ctx.label.name)
ctx.actions.write(
script,
_TEST_TEMPLATE.replace("{nested_tool}", _runfiles_path(ctx, ctx.executable.nested_tool)),
is_executable = True
)
return [
DefaultInfo(
executable = script,
runfiles = runfiles,
),
]
nested_tool_test = rule(
implementation = _impl,
test = True,
# executable = True,
attrs = {
"nested_tool": attr.label(
executable = True,
mandatory = True,
cfg = "target",
),
"_bash_runfiles": attr.label(
allow_files = True,
default = Label("@bazel_tools//tools/bash/runfiles"),
),
},
)
|
""""""
_test_template = '#!/bin/bash\n# Unset TEST_SRCDIR since we\'re trying to test the non-test behavior\nunset TEST_SRCDIR\n\n# --- begin runfiles.bash initialization v2 ---\n# Copy-pasted from the Bazel Bash runfiles library v2.\nset -uo pipefail; f=bazel_tools/tools/bash/runfiles/runfiles.bash\nsource "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d\' \')" 2>/dev/null || source "$0.runfiles/$f" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d\' \')" 2>/dev/null || source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d\' \')" 2>/dev/null || { echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e\n# --- end runfiles.bash initialization v2 ---\nrunfiles_export_envvars\n$(rlocation {nested_tool})\n'
def _runfiles_path(ctx, file):
if file.short_path.startswith('../'):
return file.short_path[3:]
else:
return ctx.workspace_name + '/' + file.short_path
def _impl(ctx):
runfiles = ctx.runfiles()
runfiles = runfiles.merge(ctx.attr._bash_runfiles.default_runfiles)
runfiles = runfiles.merge(ctx.attr.nested_tool.default_runfiles)
script = ctx.actions.declare_file(ctx.label.name)
ctx.actions.write(script, _TEST_TEMPLATE.replace('{nested_tool}', _runfiles_path(ctx, ctx.executable.nested_tool)), is_executable=True)
return [default_info(executable=script, runfiles=runfiles)]
nested_tool_test = rule(implementation=_impl, test=True, attrs={'nested_tool': attr.label(executable=True, mandatory=True, cfg='target'), '_bash_runfiles': attr.label(allow_files=True, default=label('@bazel_tools//tools/bash/runfiles'))})
|
#!/usr/bin/env python
# encoding: utf-8
"""
constants.py
Useful constants; the ones embedded in classes can be thought of as Enums.
Created by Niall Richard Murphy on 2011-05-25.
"""
_DNS_SEPARATOR = "." # What do we use to join hostname to domain name
_FIRST_ONE_ONLY = 0 # If we only want the first match back from an array
class Types(object):
"""Types of router configuration."""
UNKNOWN=0
DEFAULT_CISCO=1
DEFAULT_JUNIPER=2
class Regex(object):
"""These regular expressions use named capturing groups; most of them
are gross simplifications."""
V4_ADDR = '((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)'
V6_ADDR = '::'
ANY_ADDR = '\S+'
ANY_MASK = '\S+'
INTERFACE = '[a-zA-Z-]+\d+(/\d+)?'
ANY_METRIC = '\d+'
SNMP_VERSION = '\d|\dc'
SSH_VERSION = '1|2'
SINGLE_STRING = '\S+'
GREEDY_STRING = '.*'
DIGITS = '\d+'
STANDARD_ACL_DIGITS = '\d{1,2}'
EXTENDED_ACL_DIGITS = '\d{3}'
ACL_DIRECTION = 'in|out'
ACCESS_GROUP = DIGITS
CISCO_WILDCARD = '(\d+)\.(\d+)\.(\d+)\.(\d+)'
ETHER_SPEED = 'nonegotiate|auto|\d+'
ETHER_DUPLEX = 'full|half|auto'
SHUTDOWN_STATE = 'shutdown'
NO_IP_STATE = 'no ip address'
VTY_COMPRESS = '(\d+)\s+(\d+)'
ACL_PROTO = 'ip|tcp|udp'
ACL_ACTION = 'permit|deny'
ACL_SOURCE = '\S+'
INTERFACE_PROPERTIES = "ip address (?P<addr1>%s) (?P<mask1>%s)|" \
"ipv6 address (?P<addr2>%s)|" \
"speed (?P<speed>%s)|" \
"duplex (?P<duplex>%s)|" \
"ip access-group (?P<aclin>%s) in|" \
"ip access-group (?P<aclout>%s) out|" \
"(?P<shutdown>%s)|" \
"(?P<noip>%s)|" \
"description (?P<descr>%s)" % (
SINGLE_STRING, # ip address
ANY_MASK, # mask
SINGLE_STRING, # ip address
ETHER_SPEED, # ethernet speed
ETHER_DUPLEX, # ethernet duplicity
ACCESS_GROUP, # access group
ACCESS_GROUP, # access group
SHUTDOWN_STATE, # shutdown state
NO_IP_STATE, # no ip address
GREEDY_STRING) # description
CON_CONFIG = "transport preferred (?P<tpref>%s)|transport output (?P<tout>%s)|" \
"exec-timeout (?P<timeo>%s\ +\d+)|stopbits (?P<stopb>%s)|" \
"password (?P<encrlevel>%s) (?P<passw>%s)" % (
SINGLE_STRING, # tpref
SINGLE_STRING, # tout
SINGLE_STRING, # timeo
DIGITS, # stopb
DIGITS, # encrlevel
SINGLE_STRING) # passwd
VTY_CONFIG = CON_CONFIG + "|transport input (?P<inputm>%s)" \
"|access-class (?P<acl>%s) (?P<acldir>%s)" \
"|ipv6 access-class (?P<aclv6>%s) (?P<dirv6>%s)" % (
GREEDY_STRING, # inputm - could be multiple inputs supported
SINGLE_STRING, # v4 acl
SINGLE_STRING, # v4 direction
SINGLE_STRING, # v6 acl
SINGLE_STRING) # v6 direction
STANDARD_ACL = "^access-list (?P<id>%s) (?P<action>%s) (?P<netw>%s) (?P<netm>%s)$" % (
STANDARD_ACL_DIGITS, # id
ACL_ACTION, # permit
SINGLE_STRING, # 127.0.0.1
SINGLE_STRING) # 0.0.0.255
EXTENDED_ACL = "(?P<action1>%s) (?P<netw1>%s) (?P<netm1>%s)|" \
"(?P<action2>%s) (?P<proto>%s) (?P<netw2>%s) (?P<netm2>%s) (.*$)" % (
ACL_ACTION, # permit
ANY_ADDR, # 127.0.0.1
SINGLE_STRING, # 0.0.0.255
ACL_ACTION, # permit
ACL_PROTO, # tcp
ANY_ADDR, # 8.8.8.0
SINGLE_STRING) # 0.0.0.255
AAA_NEWMODEL = "^aaa new-model"
TACACS_SERVERS = "tacacs-server host (?P<host>%s)" % (ANY_ADDR)
TACACS_KEY = "tacacs-server key 7 (?P<key>%s)" % (SINGLE_STRING)
class UserClasses(object):
CORE_ROUTER = 0
ACCESS_ROUTER = 1
DISTRIBUTION_ROUTER = 2
class NetworkConstants(object):
SLASH_32 = '255.255.255.255'
|
"""
constants.py
Useful constants; the ones embedded in classes can be thought of as Enums.
Created by Niall Richard Murphy on 2011-05-25.
"""
_dns_separator = '.'
_first_one_only = 0
class Types(object):
"""Types of router configuration."""
unknown = 0
default_cisco = 1
default_juniper = 2
class Regex(object):
"""These regular expressions use named capturing groups; most of them
are gross simplifications."""
v4_addr = '((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)'
v6_addr = '::'
any_addr = '\\S+'
any_mask = '\\S+'
interface = '[a-zA-Z-]+\\d+(/\\d+)?'
any_metric = '\\d+'
snmp_version = '\\d|\\dc'
ssh_version = '1|2'
single_string = '\\S+'
greedy_string = '.*'
digits = '\\d+'
standard_acl_digits = '\\d{1,2}'
extended_acl_digits = '\\d{3}'
acl_direction = 'in|out'
access_group = DIGITS
cisco_wildcard = '(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)'
ether_speed = 'nonegotiate|auto|\\d+'
ether_duplex = 'full|half|auto'
shutdown_state = 'shutdown'
no_ip_state = 'no ip address'
vty_compress = '(\\d+)\\s+(\\d+)'
acl_proto = 'ip|tcp|udp'
acl_action = 'permit|deny'
acl_source = '\\S+'
interface_properties = 'ip address (?P<addr1>%s) (?P<mask1>%s)|ipv6 address (?P<addr2>%s)|speed (?P<speed>%s)|duplex (?P<duplex>%s)|ip access-group (?P<aclin>%s) in|ip access-group (?P<aclout>%s) out|(?P<shutdown>%s)|(?P<noip>%s)|description (?P<descr>%s)' % (SINGLE_STRING, ANY_MASK, SINGLE_STRING, ETHER_SPEED, ETHER_DUPLEX, ACCESS_GROUP, ACCESS_GROUP, SHUTDOWN_STATE, NO_IP_STATE, GREEDY_STRING)
con_config = 'transport preferred (?P<tpref>%s)|transport output (?P<tout>%s)|exec-timeout (?P<timeo>%s\\ +\\d+)|stopbits (?P<stopb>%s)|password (?P<encrlevel>%s) (?P<passw>%s)' % (SINGLE_STRING, SINGLE_STRING, SINGLE_STRING, DIGITS, DIGITS, SINGLE_STRING)
vty_config = CON_CONFIG + '|transport input (?P<inputm>%s)|access-class (?P<acl>%s) (?P<acldir>%s)|ipv6 access-class (?P<aclv6>%s) (?P<dirv6>%s)' % (GREEDY_STRING, SINGLE_STRING, SINGLE_STRING, SINGLE_STRING, SINGLE_STRING)
standard_acl = '^access-list (?P<id>%s) (?P<action>%s) (?P<netw>%s) (?P<netm>%s)$' % (STANDARD_ACL_DIGITS, ACL_ACTION, SINGLE_STRING, SINGLE_STRING)
extended_acl = '(?P<action1>%s) (?P<netw1>%s) (?P<netm1>%s)|(?P<action2>%s) (?P<proto>%s) (?P<netw2>%s) (?P<netm2>%s) (.*$)' % (ACL_ACTION, ANY_ADDR, SINGLE_STRING, ACL_ACTION, ACL_PROTO, ANY_ADDR, SINGLE_STRING)
aaa_newmodel = '^aaa new-model'
tacacs_servers = 'tacacs-server host (?P<host>%s)' % ANY_ADDR
tacacs_key = 'tacacs-server key 7 (?P<key>%s)' % SINGLE_STRING
class Userclasses(object):
core_router = 0
access_router = 1
distribution_router = 2
class Networkconstants(object):
slash_32 = '255.255.255.255'
|
"""
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
"""
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if root is None:
return False
if root.left is None and root.right is None: # Found a leaf
if sum == root.val:
return True
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
# Need to note, a leaf is a node has no left chind and no right child
|
"""
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ 4 8
/ / 11 13 4
/ \\ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
"""
class Solution:
def has_path_sum(self, root, sum):
if root is None:
return False
if root.left is None and root.right is None:
if sum == root.val:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
|
#import sys
#sys.stdin = open('rectangles.in', 'r')
#sys.stdout = open('rectangles.out', 'w')
n, m, k = map(int, input().split())
a = [[100000, 0, 100000, 0] for i in range(k)]
field = []
for i in range(n):
field.append(list(map(int, input().split())))
field.reverse()
for i in range(n):
for j in range(m):
if field[i][j] > 0:
v = field[i][j] - 1
a[v][0] = min(a[v][0], j)
a[v][1] = max(a[v][1], j)
a[v][2] = min(a[v][2], i)
a[v][3] = max(a[v][3], i)
for i in range(k):
print(a[i][0], a[i][2], a[i][1] + 1, a[i][3] + 1)
|
(n, m, k) = map(int, input().split())
a = [[100000, 0, 100000, 0] for i in range(k)]
field = []
for i in range(n):
field.append(list(map(int, input().split())))
field.reverse()
for i in range(n):
for j in range(m):
if field[i][j] > 0:
v = field[i][j] - 1
a[v][0] = min(a[v][0], j)
a[v][1] = max(a[v][1], j)
a[v][2] = min(a[v][2], i)
a[v][3] = max(a[v][3], i)
for i in range(k):
print(a[i][0], a[i][2], a[i][1] + 1, a[i][3] + 1)
|
def _cc_injected_toolchain_header_library_impl(ctx):
hdrs = ctx.files.hdrs
transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps]
compilation_ctx = cc_common.create_compilation_context(headers = depset(hdrs))
info = cc_common.merge_cc_infos(
cc_infos = transitive_cc_infos + [CcInfo(compilation_context = compilation_ctx)],
)
return [info, DefaultInfo(files = depset(hdrs))]
cc_injected_toolchain_header_library = rule(
_cc_injected_toolchain_header_library_impl,
attrs = {
"hdrs": attr.label_list(
doc = "A list of headers to be included into a toolchain implicitly using -include",
allow_files = True,
),
"deps": attr.label_list(
doc = "list of injected header libraries that this target depends on",
providers = [CcInfo],
),
},
provides = [CcInfo],
)
def _cc_toolchain_header_polyfill_library_impl(ctx):
hdrs = ctx.files.hdrs
system_includes = [ctx.label.package + "/" + inc for inc in ctx.attr.system_includes] + [ctx.label.workspace_root]
transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps]
compilation_ctx = cc_common.create_compilation_context(headers = depset(hdrs), system_includes = depset(system_includes))
info = cc_common.merge_cc_infos(cc_infos = transitive_cc_infos + [CcInfo(compilation_context = compilation_ctx)])
return [info, DefaultInfo(files = depset(hdrs, transitive = [info.compilation_context.headers]))]
cc_polyfill_toolchain_library = rule(
_cc_toolchain_header_polyfill_library_impl,
attrs = {
"hdrs": attr.label_list(
doc = "A list of headers to be included into the toolchains system libraries",
allow_files = True,
),
"system_includes": attr.string_list(
doc = "A list of directories to be included when the toolchain searches for headers",
),
"deps": attr.label_list(
doc = "list of injected header libraries that this target depends on",
providers = [CcInfo],
),
},
)
|
def _cc_injected_toolchain_header_library_impl(ctx):
hdrs = ctx.files.hdrs
transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps]
compilation_ctx = cc_common.create_compilation_context(headers=depset(hdrs))
info = cc_common.merge_cc_infos(cc_infos=transitive_cc_infos + [cc_info(compilation_context=compilation_ctx)])
return [info, default_info(files=depset(hdrs))]
cc_injected_toolchain_header_library = rule(_cc_injected_toolchain_header_library_impl, attrs={'hdrs': attr.label_list(doc='A list of headers to be included into a toolchain implicitly using -include', allow_files=True), 'deps': attr.label_list(doc='list of injected header libraries that this target depends on', providers=[CcInfo])}, provides=[CcInfo])
def _cc_toolchain_header_polyfill_library_impl(ctx):
hdrs = ctx.files.hdrs
system_includes = [ctx.label.package + '/' + inc for inc in ctx.attr.system_includes] + [ctx.label.workspace_root]
transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps]
compilation_ctx = cc_common.create_compilation_context(headers=depset(hdrs), system_includes=depset(system_includes))
info = cc_common.merge_cc_infos(cc_infos=transitive_cc_infos + [cc_info(compilation_context=compilation_ctx)])
return [info, default_info(files=depset(hdrs, transitive=[info.compilation_context.headers]))]
cc_polyfill_toolchain_library = rule(_cc_toolchain_header_polyfill_library_impl, attrs={'hdrs': attr.label_list(doc='A list of headers to be included into the toolchains system libraries', allow_files=True), 'system_includes': attr.string_list(doc='A list of directories to be included when the toolchain searches for headers'), 'deps': attr.label_list(doc='list of injected header libraries that this target depends on', providers=[CcInfo])})
|
"""
Given two integers n and k, return all possible combinations of k numbers out
of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
"""
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
a = range(1, n + 1)
return self.combine_aux(a, k)
def combine_aux(self, a, k):
if k == 0:
return [[]]
else:
res = []
for i, e in enumerate(a):
rest_comb = self.combine_aux(a[i + 1:], k - 1)
for comb in rest_comb:
comb.insert(0, e)
res += rest_comb
return res
|
"""
Given two integers n and k, return all possible combinations of k numbers out
of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
"""
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
a = range(1, n + 1)
return self.combine_aux(a, k)
def combine_aux(self, a, k):
if k == 0:
return [[]]
else:
res = []
for (i, e) in enumerate(a):
rest_comb = self.combine_aux(a[i + 1:], k - 1)
for comb in rest_comb:
comb.insert(0, e)
res += rest_comb
return res
|
#
# PySNMP MIB module TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Unsigned32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Counter32, Counter64, Gauge32, MibIdentifier, IpAddress, TimeTicks, ObjectIdentity, NotificationType, Bits, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Counter32", "Counter64", "Gauge32", "MibIdentifier", "IpAddress", "TimeTicks", "ObjectIdentity", "NotificationType", "Bits", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
trpzRegistration, = mibBuilder.importSymbols("TRAPEZE-NETWORKS-ROOT-MIB", "trpzRegistration")
trpzRegistrationDevicesMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 14525, 3, 6))
trpzRegistrationDevicesMib.setRevisions(('2011-08-09 00:32', '2011-03-08 00:22', '2010-12-02 00:11', '2009-12-18 00:10', '2007-11-30 00:01', '2007-08-22 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setRevisionsDescriptions(('v1.4.2: added switch models WLC8, WLC2, WLC800R, WLC2800. (This was first published in 7.3 MR4 release.)', 'v1.3.2: added switch model WLC880R (This will be published in 7.5 release.)', 'v1.2.1: Revision history correction for v1.2: switch model MX-800 was introduced in 7.3 release.', 'v1.2: added switch model MX-800.', 'v1.1: added switch model MX-2800 (This will be published in 7.0 release.)', 'v1.0: initial version, published in 6.2 release',))
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setLastUpdated('201108090032Z')
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setOrganization('Trapeze Networks')
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setContactInfo('Trapeze Networks Technical Support www.trapezenetworks.com US: 866.TRPZ.TAC International: 925.474.2400 [email protected]')
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setDescription("The MIB module for Trapeze Networks wireless device OID registrations. Copyright 2007-2011 Trapeze Networks, Inc. All rights reserved. This Trapeze Networks SNMP Management Information Base Specification (Specification) embodies Trapeze Networks' confidential and proprietary intellectual property. Trapeze Networks retains all title and ownership in the Specification, including any revisions. This Specification is supplied 'AS IS' and Trapeze Networks makes no warranty, either express or implied, as to the use, operation, condition, or performance of the Specification.")
mobilityExchange = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1))
mobilityExchange20 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 1))
mobilityExchange8 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 2))
mobilityExchange400 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 3))
mobilityExchangeR2 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 4))
mobilityExchange216 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 6))
mobilityExchange200 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 7))
mobilityExchange2800 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 12))
mobilityExchange800 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 13))
mobilityPoint = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2))
mobilityPoint101 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 1))
mobilityPoint122 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 2))
mobilityPoint241 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 3))
mobilityPoint252 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 4))
wirelessLANController = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3))
wirelessLANController880R = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 1))
wirelessLANController8 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 2))
wirelessLANController2 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 3))
wirelessLANController800r = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 4))
wirelessLANController2800 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 5))
mibBuilder.exportSymbols("TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB", mobilityExchange2800=mobilityExchange2800, mobilityExchange8=mobilityExchange8, wirelessLANController880R=wirelessLANController880R, wirelessLANController800r=wirelessLANController800r, mobilityPoint101=mobilityPoint101, wirelessLANController2800=wirelessLANController2800, mobilityPoint241=mobilityPoint241, mobilityExchange20=mobilityExchange20, wirelessLANController2=wirelessLANController2, mobilityPoint122=mobilityPoint122, mobilityExchange800=mobilityExchange800, mobilityExchange400=mobilityExchange400, mobilityPoint252=mobilityPoint252, mobilityExchange=mobilityExchange, mobilityPoint=mobilityPoint, mobilityExchange216=mobilityExchange216, mobilityExchangeR2=mobilityExchangeR2, PYSNMP_MODULE_ID=trpzRegistrationDevicesMib, mobilityExchange200=mobilityExchange200, wirelessLANController8=wirelessLANController8, wirelessLANController=wirelessLANController, trpzRegistrationDevicesMib=trpzRegistrationDevicesMib)
|
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, constraints_union, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(unsigned32, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, counter32, counter64, gauge32, mib_identifier, ip_address, time_ticks, object_identity, notification_type, bits, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Counter32', 'Counter64', 'Gauge32', 'MibIdentifier', 'IpAddress', 'TimeTicks', 'ObjectIdentity', 'NotificationType', 'Bits', 'Integer32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
(trpz_registration,) = mibBuilder.importSymbols('TRAPEZE-NETWORKS-ROOT-MIB', 'trpzRegistration')
trpz_registration_devices_mib = module_identity((1, 3, 6, 1, 4, 1, 14525, 3, 6))
trpzRegistrationDevicesMib.setRevisions(('2011-08-09 00:32', '2011-03-08 00:22', '2010-12-02 00:11', '2009-12-18 00:10', '2007-11-30 00:01', '2007-08-22 00:00'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
trpzRegistrationDevicesMib.setRevisionsDescriptions(('v1.4.2: added switch models WLC8, WLC2, WLC800R, WLC2800. (This was first published in 7.3 MR4 release.)', 'v1.3.2: added switch model WLC880R (This will be published in 7.5 release.)', 'v1.2.1: Revision history correction for v1.2: switch model MX-800 was introduced in 7.3 release.', 'v1.2: added switch model MX-800.', 'v1.1: added switch model MX-2800 (This will be published in 7.0 release.)', 'v1.0: initial version, published in 6.2 release'))
if mibBuilder.loadTexts:
trpzRegistrationDevicesMib.setLastUpdated('201108090032Z')
if mibBuilder.loadTexts:
trpzRegistrationDevicesMib.setOrganization('Trapeze Networks')
if mibBuilder.loadTexts:
trpzRegistrationDevicesMib.setContactInfo('Trapeze Networks Technical Support www.trapezenetworks.com US: 866.TRPZ.TAC International: 925.474.2400 [email protected]')
if mibBuilder.loadTexts:
trpzRegistrationDevicesMib.setDescription("The MIB module for Trapeze Networks wireless device OID registrations. Copyright 2007-2011 Trapeze Networks, Inc. All rights reserved. This Trapeze Networks SNMP Management Information Base Specification (Specification) embodies Trapeze Networks' confidential and proprietary intellectual property. Trapeze Networks retains all title and ownership in the Specification, including any revisions. This Specification is supplied 'AS IS' and Trapeze Networks makes no warranty, either express or implied, as to the use, operation, condition, or performance of the Specification.")
mobility_exchange = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1))
mobility_exchange20 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 1))
mobility_exchange8 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 2))
mobility_exchange400 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 3))
mobility_exchange_r2 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 4))
mobility_exchange216 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 6))
mobility_exchange200 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 7))
mobility_exchange2800 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 12))
mobility_exchange800 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 13))
mobility_point = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 2))
mobility_point101 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 1))
mobility_point122 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 2))
mobility_point241 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 3))
mobility_point252 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 4))
wireless_lan_controller = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 3))
wireless_lan_controller880_r = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 1))
wireless_lan_controller8 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 2))
wireless_lan_controller2 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 3))
wireless_lan_controller800r = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 4))
wireless_lan_controller2800 = mib_identifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 5))
mibBuilder.exportSymbols('TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB', mobilityExchange2800=mobilityExchange2800, mobilityExchange8=mobilityExchange8, wirelessLANController880R=wirelessLANController880R, wirelessLANController800r=wirelessLANController800r, mobilityPoint101=mobilityPoint101, wirelessLANController2800=wirelessLANController2800, mobilityPoint241=mobilityPoint241, mobilityExchange20=mobilityExchange20, wirelessLANController2=wirelessLANController2, mobilityPoint122=mobilityPoint122, mobilityExchange800=mobilityExchange800, mobilityExchange400=mobilityExchange400, mobilityPoint252=mobilityPoint252, mobilityExchange=mobilityExchange, mobilityPoint=mobilityPoint, mobilityExchange216=mobilityExchange216, mobilityExchangeR2=mobilityExchangeR2, PYSNMP_MODULE_ID=trpzRegistrationDevicesMib, mobilityExchange200=mobilityExchange200, wirelessLANController8=wirelessLANController8, wirelessLANController=wirelessLANController, trpzRegistrationDevicesMib=trpzRegistrationDevicesMib)
|
class Solution:
def searchMatrix(self, matrix, target):
i = 0
m = len(matrix)
while i < m and matrix[i][0] <= target:
i = i + 1
i = i - 1
return target in matrix[i]
if __name__ == '__main__':
matrix = [[1]]
target = 1
ans = Solution().searchMatrix(matrix, target)
print(ans)
|
class Solution:
def search_matrix(self, matrix, target):
i = 0
m = len(matrix)
while i < m and matrix[i][0] <= target:
i = i + 1
i = i - 1
return target in matrix[i]
if __name__ == '__main__':
matrix = [[1]]
target = 1
ans = solution().searchMatrix(matrix, target)
print(ans)
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def _download_binary(ctx):
ctx.download(
url = [
ctx.attr.uri,
],
output = ctx.attr.binary_name,
executable = True,
)
ctx.file(
"BUILD.bazel",
content = 'exports_files(glob(["*"]))',
)
download_binary = repository_rule(
_download_binary,
doc = """Downloads a single binary that is not tarballed.
Example:
download_binary(
name = "jq_macos_amd64",
binary_name = "jq",
uri = "https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64",
)
""",
attrs = {
"binary_name": attr.string(
mandatory = True,
),
"uri": attr.string(
mandatory = True,
),
},
)
def _declare_binary(ctx):
out = ctx.actions.declare_file(ctx.attr.binary_name)
ctx.actions.symlink(
output = out,
target_file = ctx.files.binary[0],
)
return DefaultInfo(executable = out)
declare_binary = rule(
_declare_binary,
doc = """Declares a single binary, used as a wrapper around a select() statement
Example:
declare_binary(
name = "jq",
binary = select({
"@platforms//os:linux": "@jq_linux_amd64//:jq",
"@platforms//os:osx": "@jq_macos_amd64//:jq",
}),
binary_name = "jq",
visibility = ["//visibility:public"],
)
""",
attrs = {
"binary_name": attr.string(
mandatory = True,
),
"binary": attr.label(
mandatory = True,
executable = True,
cfg = "exec",
allow_files = True,
),
},
)
|
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def _download_binary(ctx):
ctx.download(url=[ctx.attr.uri], output=ctx.attr.binary_name, executable=True)
ctx.file('BUILD.bazel', content='exports_files(glob(["*"]))')
download_binary = repository_rule(_download_binary, doc='Downloads a single binary that is not tarballed.\n\n Example:\n download_binary(\n name = "jq_macos_amd64",\n binary_name = "jq",\n uri = "https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64",\n )\n ', attrs={'binary_name': attr.string(mandatory=True), 'uri': attr.string(mandatory=True)})
def _declare_binary(ctx):
out = ctx.actions.declare_file(ctx.attr.binary_name)
ctx.actions.symlink(output=out, target_file=ctx.files.binary[0])
return default_info(executable=out)
declare_binary = rule(_declare_binary, doc='Declares a single binary, used as a wrapper around a select() statement\n\n Example:\n declare_binary(\n name = "jq",\n binary = select({\n "@platforms//os:linux": "@jq_linux_amd64//:jq",\n "@platforms//os:osx": "@jq_macos_amd64//:jq",\n }),\n binary_name = "jq",\n visibility = ["//visibility:public"],\n )\n\n ', attrs={'binary_name': attr.string(mandatory=True), 'binary': attr.label(mandatory=True, executable=True, cfg='exec', allow_files=True)})
|
# Basic type checking: no types necessary
x = 3
x + 'a'
def return_type() -> float:
return 'a'
return_type(9)
def argument_type(x: float):
return
argument_type()
|
x = 3
x + 'a'
def return_type() -> float:
return 'a'
return_type(9)
def argument_type(x: float):
return
argument_type()
|
def sudoku(board, rows, columns):
return helper(board, 0, 0, columns, rows)
def helper(board, r, c, rows, columns):
def inbound(r, c):
return (0 <= r < rows) and (0 <= c < columns)
# Out of bounds:
# We filled all blank cells and, thus, a valid solution
if not inbound(r, c):
return True
nr, nc = next_pos(r, c, rows, columns)
if board[r][c] != 0:
# This is a pre-filled cell, so skip
# for the next one
return helper(board, nr, nc, rows, columns)
for i in range(1, 10):
if valid_placement(board, r, c, rows, columns, i):
# "i" can be place in the cell without breaking
# the sudoku rules. So, it's a canditate for solution.
# Mark the cell with the value and try to solve
# recursively for the remaining blank cells
board[r][c] = i
if helper(board, nr, nc, rows, columns):
return True
else:
# No solution found for the search branch:
# reset the cell for the future attemps
board[r][c] = 0
return False
def next_pos(r, c, rows, columns):
if c + 1 == columns:
return (r + 1, 0)
else:
return (r, c + 1)
def valid_placement(board, r, c, rows, columns, v):
# Check conflict with row
if v in board[r]:
return False
# Check conflict with column
for i in range(0, rows):
if v == board[i][c]:
return False
# Check conflict with the subgrid
row_offset = r - r % 3
col_offset = c - c % 3
for i in range(3):
for j in range(3):
if board[i + row_offset][j + col_offset] == v:
return False
return True
|
def sudoku(board, rows, columns):
return helper(board, 0, 0, columns, rows)
def helper(board, r, c, rows, columns):
def inbound(r, c):
return 0 <= r < rows and 0 <= c < columns
if not inbound(r, c):
return True
(nr, nc) = next_pos(r, c, rows, columns)
if board[r][c] != 0:
return helper(board, nr, nc, rows, columns)
for i in range(1, 10):
if valid_placement(board, r, c, rows, columns, i):
board[r][c] = i
if helper(board, nr, nc, rows, columns):
return True
else:
board[r][c] = 0
return False
def next_pos(r, c, rows, columns):
if c + 1 == columns:
return (r + 1, 0)
else:
return (r, c + 1)
def valid_placement(board, r, c, rows, columns, v):
if v in board[r]:
return False
for i in range(0, rows):
if v == board[i][c]:
return False
row_offset = r - r % 3
col_offset = c - c % 3
for i in range(3):
for j in range(3):
if board[i + row_offset][j + col_offset] == v:
return False
return True
|
"""
Configuration file
"""
URL = 'localhost'
PORT = 1883
KEEPALIVE = 60
UDP_URL = 'localhost'
UDP_PORT = 1885
|
"""
Configuration file
"""
url = 'localhost'
port = 1883
keepalive = 60
udp_url = 'localhost'
udp_port = 1885
|
'''Print multiplication table of given number'''
n=int(input("Enter the no:"))
print("Multiplication table is:")
for i in range(1,11):
print(i*n)
|
"""Print multiplication table of given number"""
n = int(input('Enter the no:'))
print('Multiplication table is:')
for i in range(1, 11):
print(i * n)
|
# CONVERT DB_DATA TO STRING FOR SELF-MESSAGE
def format_to_writeable_db_data(db_data: list) -> str:
writeable_data = ""
for user in db_data:
listed_mangoes = ""
for manga in user['mangoes']:
listed_mangoes += f"{manga}>(u*u)>"
writeable_data = f"{writeable_data}{user['name']}:{listed_mangoes}\n"
return writeable_data
# ADD OR REMOVE SUBSCRIPTION BASED ON MESSAGE
def update(db_data: list, messages: list, conf: dict) -> list:
for message in messages:
if message.subject.lower() == conf['UNSUB_MESSAGE_SUBJECT']:
db_data = _update_unsubscribe(db_data, message)
elif message.subject.lower() == conf['SUB_MESSAGE_SUBJECT']:
db_data = _update_subscribe(db_data, message)
db_data = _remove_users_with_no_subscriptions(db_data)
return db_data
# DONT KEEP TRACK OF USERS WHEN THEY HAVE 0 SUBSCRIPTIONS
def _remove_users_with_no_subscriptions(db_data: list) -> list:
remove_users = []
for user in db_data:
if user['mangoes'] is None or len(user['mangoes']) == 0:
remove_users.append(user)
db_data = [x for x in db_data if x not in remove_users]
return db_data
# ADD NEWLY SUBSCRIBED MANGA TO USER OR NEW USER
def _update_subscribe(db_data: list, message: dict) -> list:
lines = message.body.splitlines()
for user in db_data:
if user['name'] == message.author.name:
for line in lines:
if line not in user['mangoes']:
user['mangoes'].append(line)
return db_data
db_data.append({'name': message.author.name, 'mangoes': lines})
return db_data
# REMOVE NEWLY UNSUBSCRIBED MANGA FROM USER
def _update_unsubscribe(db_data: list, message: dict) -> list:
print("unsubscribing")
for user in db_data:
if user['name'] == message.author.name:
lines = message.body.splitlines()
user['mangoes'] = [x for x in user['mangoes'] if x not in lines ]
break
return db_data
# INIT DB_DATA BASED ON SELF-MESSAGE
def init_db(message: str) -> list:
db_data = []
lines = message.splitlines()
for line in lines:
var_break = line.find(':')
db_data.append({'name': line[:var_break], 'mangoes': line[var_break+1:].split('>(u*u)>')[:-1]})
return db_data
|
def format_to_writeable_db_data(db_data: list) -> str:
writeable_data = ''
for user in db_data:
listed_mangoes = ''
for manga in user['mangoes']:
listed_mangoes += f'{manga}>(u*u)>'
writeable_data = f"{writeable_data}{user['name']}:{listed_mangoes}\n"
return writeable_data
def update(db_data: list, messages: list, conf: dict) -> list:
for message in messages:
if message.subject.lower() == conf['UNSUB_MESSAGE_SUBJECT']:
db_data = _update_unsubscribe(db_data, message)
elif message.subject.lower() == conf['SUB_MESSAGE_SUBJECT']:
db_data = _update_subscribe(db_data, message)
db_data = _remove_users_with_no_subscriptions(db_data)
return db_data
def _remove_users_with_no_subscriptions(db_data: list) -> list:
remove_users = []
for user in db_data:
if user['mangoes'] is None or len(user['mangoes']) == 0:
remove_users.append(user)
db_data = [x for x in db_data if x not in remove_users]
return db_data
def _update_subscribe(db_data: list, message: dict) -> list:
lines = message.body.splitlines()
for user in db_data:
if user['name'] == message.author.name:
for line in lines:
if line not in user['mangoes']:
user['mangoes'].append(line)
return db_data
db_data.append({'name': message.author.name, 'mangoes': lines})
return db_data
def _update_unsubscribe(db_data: list, message: dict) -> list:
print('unsubscribing')
for user in db_data:
if user['name'] == message.author.name:
lines = message.body.splitlines()
user['mangoes'] = [x for x in user['mangoes'] if x not in lines]
break
return db_data
def init_db(message: str) -> list:
db_data = []
lines = message.splitlines()
for line in lines:
var_break = line.find(':')
db_data.append({'name': line[:var_break], 'mangoes': line[var_break + 1:].split('>(u*u)>')[:-1]})
return db_data
|
class SuperList(list):
def __len__(self):
return 1000
super_list1 = SuperList()
print((len(super_list1)))
super_list1.append(5)
print(super_list1[0])
print(issubclass(SuperList, list)) # true
print(issubclass(list, object))
|
class Superlist(list):
def __len__(self):
return 1000
super_list1 = super_list()
print(len(super_list1))
super_list1.append(5)
print(super_list1[0])
print(issubclass(SuperList, list))
print(issubclass(list, object))
|
def reverse(SA):
reverse = [0] * len(SA)
for i in range(len(SA)):
reverse[SA[i] - 1] = i + 1
return reverse
def prefix_doubling(text, n):
'''Computes suffix array using Karp-Miller-Rosenberg algorithm'''
text += '$'
mapping = {v: i + 1 for i, v in enumerate(sorted(set(text[1:])))}
R, k = [mapping[v] for v in text[1:]], 1
while k < 2 * n:
pairs = [(R[i], R[i + k] if i + k < len(R) else 0) for i in range(len(R))]
mapping = {v: i + 1 for i, v in enumerate(sorted(set(pairs)))}
R, k = [mapping[pair] for pair in pairs], 2 * k
return reverse(R)
|
def reverse(SA):
reverse = [0] * len(SA)
for i in range(len(SA)):
reverse[SA[i] - 1] = i + 1
return reverse
def prefix_doubling(text, n):
"""Computes suffix array using Karp-Miller-Rosenberg algorithm"""
text += '$'
mapping = {v: i + 1 for (i, v) in enumerate(sorted(set(text[1:])))}
(r, k) = ([mapping[v] for v in text[1:]], 1)
while k < 2 * n:
pairs = [(R[i], R[i + k] if i + k < len(R) else 0) for i in range(len(R))]
mapping = {v: i + 1 for (i, v) in enumerate(sorted(set(pairs)))}
(r, k) = ([mapping[pair] for pair in pairs], 2 * k)
return reverse(R)
|
N, M = map(int, input().split())
case = [i for i in range(1, N+1)]
disk = []
for _ in range(M):
disk.append(int(input()))
now = 0
for d in disk:
if d == now:
continue
i = case.index(d)
tmp = case[i]
case[i] = now
now = tmp
for c in case:
print(c)
|
(n, m) = map(int, input().split())
case = [i for i in range(1, N + 1)]
disk = []
for _ in range(M):
disk.append(int(input()))
now = 0
for d in disk:
if d == now:
continue
i = case.index(d)
tmp = case[i]
case[i] = now
now = tmp
for c in case:
print(c)
|
def maximum():
A = input('Enter the 1st number:')
B = input('Enter the 2nd number:')
if A > B:
print("%d The highest num than %d"%(A,B))
else:
print('The highest num is:' ,B)
print("Optised max",max(A,B))
def minimum():
A1 = input('Enter the 1st number:')
B1 = input('Enter the 2nd number:')
C1 = input('Enter the 3rd number:')
print("Optimised min " ,min(A1,B1,C1))
if(A1<B1) and (A1<C1):
print("Smallest number is",A1)
else :
if(B1 <C1):
print("Smallest number is ",B1)
else :
print("Smallest number is ", C1)
def main():
print("Enter your choice")
print("1.Max of 2 numbers")
print("2.Min of 3 numbers")
choice=input("Enter your choice")
if(choice == 1):
maximum()
else :
minimum()
main()
|
def maximum():
a = input('Enter the 1st number:')
b = input('Enter the 2nd number:')
if A > B:
print('%d The highest num than %d' % (A, B))
else:
print('The highest num is:', B)
print('Optised max', max(A, B))
def minimum():
a1 = input('Enter the 1st number:')
b1 = input('Enter the 2nd number:')
c1 = input('Enter the 3rd number:')
print('Optimised min ', min(A1, B1, C1))
if A1 < B1 and A1 < C1:
print('Smallest number is', A1)
elif B1 < C1:
print('Smallest number is ', B1)
else:
print('Smallest number is ', C1)
def main():
print('Enter your choice')
print('1.Max of 2 numbers')
print('2.Min of 3 numbers')
choice = input('Enter your choice')
if choice == 1:
maximum()
else:
minimum()
main()
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
shelters = [0] * (n + 1)
for _ in range(n - 1):
x, y = map(int, input().strip().split())
shelters[x] += 1
shelters[y] += 1
max_seen = max(shelters)
good_shelters = [i for i, v in enumerate(shelters) if i != 0 and v == max_seen]
print(len(good_shelters))
print(' '.join(map(str, good_shelters)))
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
n = int(input())
shelters = [0] * (n + 1)
for _ in range(n - 1):
(x, y) = map(int, input().strip().split())
shelters[x] += 1
shelters[y] += 1
max_seen = max(shelters)
good_shelters = [i for (i, v) in enumerate(shelters) if i != 0 and v == max_seen]
print(len(good_shelters))
print(' '.join(map(str, good_shelters)))
|
__author__ = 'varx'
class BaseRenderer(object):
"""
Base renderer that all renders should inherit from
"""
def can_render(self, path):
raise NotImplementedError()
def render(self, path):
raise NotImplementedError()
|
__author__ = 'varx'
class Baserenderer(object):
"""
Base renderer that all renders should inherit from
"""
def can_render(self, path):
raise not_implemented_error()
def render(self, path):
raise not_implemented_error()
|
stores = []
command = input()
while command != 'END':
tokens = command.split('->')
store_name = tokens[1]
if tokens[0] == 'Add':
items = tokens[2].split(',')
if len([x for x in stores if x[0] == store_name]) > 0:
idx = stores.index([x for x in stores if x[0] == store_name][0])
stores[idx][1].extend(items)
else:
stores.append([store_name, items])
elif tokens[0] == 'Remove':
if len([x for x in stores if x[0] == store_name]) > 0:
idx = stores.index([x for x in stores if x[0] == store_name][0])
del stores[idx]
command = input()
sorted_stores = sorted(stores, key=lambda x: (len(x[1]), x[0]), reverse=True)
print('Stores list:')
for store in sorted_stores:
store_name = store[0]
items = store[1]
print(store_name)
for item in items:
print(f'<<{item}>>')
|
stores = []
command = input()
while command != 'END':
tokens = command.split('->')
store_name = tokens[1]
if tokens[0] == 'Add':
items = tokens[2].split(',')
if len([x for x in stores if x[0] == store_name]) > 0:
idx = stores.index([x for x in stores if x[0] == store_name][0])
stores[idx][1].extend(items)
else:
stores.append([store_name, items])
elif tokens[0] == 'Remove':
if len([x for x in stores if x[0] == store_name]) > 0:
idx = stores.index([x for x in stores if x[0] == store_name][0])
del stores[idx]
command = input()
sorted_stores = sorted(stores, key=lambda x: (len(x[1]), x[0]), reverse=True)
print('Stores list:')
for store in sorted_stores:
store_name = store[0]
items = store[1]
print(store_name)
for item in items:
print(f'<<{item}>>')
|
# This is a great place to put your bot's version number.
__version__ = "0.1.0"
# You'll want to change this.
GUILD_ID = 845688627265536010
|
__version__ = '0.1.0'
guild_id = 845688627265536010
|
#dictionary and for statements with values method
linguagens = {
'lea': 'python',
'sara': 'c',
'eddie': 'java',
'phil': 'python',
}
for linguagem in linguagens.values(): #values method shows us the values of a dictionary
print(linguagem.title())
|
linguagens = {'lea': 'python', 'sara': 'c', 'eddie': 'java', 'phil': 'python'}
for linguagem in linguagens.values():
print(linguagem.title())
|
class EmitterTypeError(Exception):
pass
class EmitterValidationError(Exception):
pass
|
class Emittertypeerror(Exception):
pass
class Emittervalidationerror(Exception):
pass
|
class BSTNode():
def __init__(self, Key, Value=None):
self.key = Key
self.Value = Value
self.left = None
self.right = None
self.parent = None
@staticmethod
def remove_none(lst):
return [x for x in lst if x is not None]
def check_BSTNode(self):
if self is None:
return True, None, None
is_BSTNode_l, max_l, min_l = BSTNode.check_BSTNode(self.left)
is_BSTNode_r, max_r, min_r = BSTNode.check_BSTNode(self.right)
is_BSTNode = (is_BSTNode_l and is_BSTNode_r and (max_l is None or max_l < self.key) and (
min_l is None or min_r > self.key))
min_key = min(BSTNode.remove_none([min_l, self.key, min_r]))
max_key = max(BSTNode.remove_none([max_l, self.key, max_r]))
return is_BSTNode, max_key, min_key
def display(self, lvl=0):
if self is None:
return
if self.right is None and self.left is None:
print("\t" * lvl + str(self.key))
return
BSTNode.display(self.right, lvl + 1)
print("\t" * lvl + str(self.key))
BSTNode.display(self.left, lvl + 1)
@staticmethod
def parse(data):
if isinstance(data, tuple) and len(data) == 3:
node = BSTNode(data[1])
node.left = BSTNode.parse(data[0])
node.right = BSTNode.parse(data[2])
node.left.parent = node
node.right.parent = node
elif data is None:
node = None
else:
node = BSTNode(data)
return node
def insert(self, key, value=None):
if self is None:
self = BSTNode(key, value)
elif self.key > key:
self.left = BSTNode.insert(self.left, key, value)
self.left.parent = self
elif self.key < key:
self.right = BSTNode.insert(self.right, key, value)
self.right.parent = self
return self
def find(self, key):
if self is None:
return False
elif self.key == key:
return True
elif self.key<key:
return BSTNode.find(self.right, key)
else:
return BSTNode.find(self.left, key)
if __name__ == "__main__":
print(f"Input Range :")
k = BSTNode.insert(None, 7)
k.insert(1)
k.insert(9)
k.insert(4)
k.insert(10)
k.insert(8)
k.display()
print(f"\n\n Find- { k.find(0) }")
|
class Bstnode:
def __init__(self, Key, Value=None):
self.key = Key
self.Value = Value
self.left = None
self.right = None
self.parent = None
@staticmethod
def remove_none(lst):
return [x for x in lst if x is not None]
def check_bst_node(self):
if self is None:
return (True, None, None)
(is_bst_node_l, max_l, min_l) = BSTNode.check_BSTNode(self.left)
(is_bst_node_r, max_r, min_r) = BSTNode.check_BSTNode(self.right)
is_bst_node = is_BSTNode_l and is_BSTNode_r and (max_l is None or max_l < self.key) and (min_l is None or min_r > self.key)
min_key = min(BSTNode.remove_none([min_l, self.key, min_r]))
max_key = max(BSTNode.remove_none([max_l, self.key, max_r]))
return (is_BSTNode, max_key, min_key)
def display(self, lvl=0):
if self is None:
return
if self.right is None and self.left is None:
print('\t' * lvl + str(self.key))
return
BSTNode.display(self.right, lvl + 1)
print('\t' * lvl + str(self.key))
BSTNode.display(self.left, lvl + 1)
@staticmethod
def parse(data):
if isinstance(data, tuple) and len(data) == 3:
node = bst_node(data[1])
node.left = BSTNode.parse(data[0])
node.right = BSTNode.parse(data[2])
node.left.parent = node
node.right.parent = node
elif data is None:
node = None
else:
node = bst_node(data)
return node
def insert(self, key, value=None):
if self is None:
self = bst_node(key, value)
elif self.key > key:
self.left = BSTNode.insert(self.left, key, value)
self.left.parent = self
elif self.key < key:
self.right = BSTNode.insert(self.right, key, value)
self.right.parent = self
return self
def find(self, key):
if self is None:
return False
elif self.key == key:
return True
elif self.key < key:
return BSTNode.find(self.right, key)
else:
return BSTNode.find(self.left, key)
if __name__ == '__main__':
print(f'Input Range :')
k = BSTNode.insert(None, 7)
k.insert(1)
k.insert(9)
k.insert(4)
k.insert(10)
k.insert(8)
k.display()
print(f'\n\n Find- {k.find(0)}')
|
LSM9DS1_MAG_ADDRESS = 0x1C #Would be 0x1E if SDO_M is HIGH
LSM9DS1_ACC_ADDRESS = 0x6A
LSM9DS1_GYR_ADDRESS = 0x6A #Would be 0x6B if SDO_AG is HIGH
#/////////////////////////////////////////
#// LSM9DS1 Accel/Gyro (XL/G) Registers //
#/////////////////////////////////////////
LSM9DS1_ACT_THS = 0x04
LSM9DS1_ACT_DUR = 0x05
LSM9DS1_INT_GEN_CFG_XL = 0x06
LSM9DS1_INT_GEN_THS_X_XL = 0x07
LSM9DS1_INT_GEN_THS_Y_XL = 0x08
LSM9DS1_INT_GEN_THS_Z_XL = 0x09
LSM9DS1_INT_GEN_DUR_XL = 0x0A
LSM9DS1_REFERENCE_G = 0x0B
LSM9DS1_INT1_CTRL = 0x0C
LSM9DS1_INT2_CTRL = 0x0D
LSM9DS1_WHO_AM_I_XG = 0x0F
LSM9DS1_CTRL_REG1_G = 0x10
LSM9DS1_CTRL_REG2_G = 0x11
LSM9DS1_CTRL_REG3_G = 0x12
LSM9DS1_ORIENT_CFG_G = 0x13
LSM9DS1_INT_GEN_SRC_G = 0x14
LSM9DS1_OUT_TEMP_L = 0x15
LSM9DS1_OUT_TEMP_H = 0x16
LSM9DS1_STATUS_REG_0 = 0x17
LSM9DS1_OUT_X_L_G = 0x18
LSM9DS1_OUT_X_H_G = 0x19
LSM9DS1_OUT_Y_L_G = 0x1A
LSM9DS1_OUT_Y_H_G = 0x1B
LSM9DS1_OUT_Z_L_G = 0x1C
LSM9DS1_OUT_Z_H_G = 0x1D
LSM9DS1_CTRL_REG4 = 0x1E
LSM9DS1_CTRL_REG5_XL = 0x1F
LSM9DS1_CTRL_REG6_XL = 0x20
LSM9DS1_CTRL_REG7_XL = 0x21
LSM9DS1_CTRL_REG8 = 0x22
LSM9DS1_CTRL_REG9 = 0x23
LSM9DS1_CTRL_REG10 = 0x24
LSM9DS1_INT_GEN_SRC_XL = 0x26
LSM9DS1_STATUS_REG_1 = 0x27
LSM9DS1_OUT_X_L_XL = 0x28
LSM9DS1_OUT_X_H_XL = 0x29
LSM9DS1_OUT_Y_L_XL = 0x2A
LSM9DS1_OUT_Y_H_XL = 0x2B
LSM9DS1_OUT_Z_L_XL = 0x2C
LSM9DS1_OUT_Z_H_XL = 0x2D
LSM9DS1_FIFO_CTRL = 0x2E
LSM9DS1_FIFO_SRC = 0x2F
LSM9DS1_INT_GEN_CFG_G = 0x30
LSM9DS1_INT_GEN_THS_XH_G = 0x31
LSM9DS1_INT_GEN_THS_XL_G = 0x32
LSM9DS1_INT_GEN_THS_YH_G = 0x33
LSM9DS1_INT_GEN_THS_YL_G = 0x34
LSM9DS1_INT_GEN_THS_ZH_G = 0x35
LSM9DS1_INT_GEN_THS_ZL_G = 0x36
LSM9DS1_INT_GEN_DUR_G = 0x37
#///////////////////////////////
#// LSM9DS1 Magneto Registers //
#///////////////////////////////
LSM9DS1_OFFSET_X_REG_L_M = 0x05
LSM9DS1_OFFSET_X_REG_H_M = 0x06
LSM9DS1_OFFSET_Y_REG_L_M = 0x07
LSM9DS1_OFFSET_Y_REG_H_M = 0x08
LSM9DS1_OFFSET_Z_REG_L_M = 0x09
LSM9DS1_OFFSET_Z_REG_H_M = 0x0A
LSM9DS1_WHO_AM_I_M = 0x0F
LSM9DS1_CTRL_REG1_M = 0x20
LSM9DS1_CTRL_REG2_M = 0x21
LSM9DS1_CTRL_REG3_M = 0x22
LSM9DS1_CTRL_REG4_M = 0x23
LSM9DS1_CTRL_REG5_M = 0x24
LSM9DS1_STATUS_REG_M = 0x27
LSM9DS1_OUT_X_L_M = 0x28
LSM9DS1_OUT_X_H_M = 0x29
LSM9DS1_OUT_Y_L_M = 0x2A
LSM9DS1_OUT_Y_H_M = 0x2B
LSM9DS1_OUT_Z_L_M = 0x2C
LSM9DS1_OUT_Z_H_M = 0x2D
LSM9DS1_INT_CFG_M = 0x30
LSM9DS1_INT_SRC_M = 0x30
LSM9DS1_INT_THS_L_M = 0x32
LSM9DS1_INT_THS_H_M = 0x33
#////////////////////////////////
#// LSM9DS1 WHO_AM_I Responses //
#////////////////////////////////
LSM9DS1_WHO_AM_I_AG_RSP = 0x68
LSM9DS1_WHO_AM_I_M_RSP = 0x3D
|
lsm9_ds1_mag_address = 28
lsm9_ds1_acc_address = 106
lsm9_ds1_gyr_address = 106
lsm9_ds1_act_ths = 4
lsm9_ds1_act_dur = 5
lsm9_ds1_int_gen_cfg_xl = 6
lsm9_ds1_int_gen_ths_x_xl = 7
lsm9_ds1_int_gen_ths_y_xl = 8
lsm9_ds1_int_gen_ths_z_xl = 9
lsm9_ds1_int_gen_dur_xl = 10
lsm9_ds1_reference_g = 11
lsm9_ds1_int1_ctrl = 12
lsm9_ds1_int2_ctrl = 13
lsm9_ds1_who_am_i_xg = 15
lsm9_ds1_ctrl_reg1_g = 16
lsm9_ds1_ctrl_reg2_g = 17
lsm9_ds1_ctrl_reg3_g = 18
lsm9_ds1_orient_cfg_g = 19
lsm9_ds1_int_gen_src_g = 20
lsm9_ds1_out_temp_l = 21
lsm9_ds1_out_temp_h = 22
lsm9_ds1_status_reg_0 = 23
lsm9_ds1_out_x_l_g = 24
lsm9_ds1_out_x_h_g = 25
lsm9_ds1_out_y_l_g = 26
lsm9_ds1_out_y_h_g = 27
lsm9_ds1_out_z_l_g = 28
lsm9_ds1_out_z_h_g = 29
lsm9_ds1_ctrl_reg4 = 30
lsm9_ds1_ctrl_reg5_xl = 31
lsm9_ds1_ctrl_reg6_xl = 32
lsm9_ds1_ctrl_reg7_xl = 33
lsm9_ds1_ctrl_reg8 = 34
lsm9_ds1_ctrl_reg9 = 35
lsm9_ds1_ctrl_reg10 = 36
lsm9_ds1_int_gen_src_xl = 38
lsm9_ds1_status_reg_1 = 39
lsm9_ds1_out_x_l_xl = 40
lsm9_ds1_out_x_h_xl = 41
lsm9_ds1_out_y_l_xl = 42
lsm9_ds1_out_y_h_xl = 43
lsm9_ds1_out_z_l_xl = 44
lsm9_ds1_out_z_h_xl = 45
lsm9_ds1_fifo_ctrl = 46
lsm9_ds1_fifo_src = 47
lsm9_ds1_int_gen_cfg_g = 48
lsm9_ds1_int_gen_ths_xh_g = 49
lsm9_ds1_int_gen_ths_xl_g = 50
lsm9_ds1_int_gen_ths_yh_g = 51
lsm9_ds1_int_gen_ths_yl_g = 52
lsm9_ds1_int_gen_ths_zh_g = 53
lsm9_ds1_int_gen_ths_zl_g = 54
lsm9_ds1_int_gen_dur_g = 55
lsm9_ds1_offset_x_reg_l_m = 5
lsm9_ds1_offset_x_reg_h_m = 6
lsm9_ds1_offset_y_reg_l_m = 7
lsm9_ds1_offset_y_reg_h_m = 8
lsm9_ds1_offset_z_reg_l_m = 9
lsm9_ds1_offset_z_reg_h_m = 10
lsm9_ds1_who_am_i_m = 15
lsm9_ds1_ctrl_reg1_m = 32
lsm9_ds1_ctrl_reg2_m = 33
lsm9_ds1_ctrl_reg3_m = 34
lsm9_ds1_ctrl_reg4_m = 35
lsm9_ds1_ctrl_reg5_m = 36
lsm9_ds1_status_reg_m = 39
lsm9_ds1_out_x_l_m = 40
lsm9_ds1_out_x_h_m = 41
lsm9_ds1_out_y_l_m = 42
lsm9_ds1_out_y_h_m = 43
lsm9_ds1_out_z_l_m = 44
lsm9_ds1_out_z_h_m = 45
lsm9_ds1_int_cfg_m = 48
lsm9_ds1_int_src_m = 48
lsm9_ds1_int_ths_l_m = 50
lsm9_ds1_int_ths_h_m = 51
lsm9_ds1_who_am_i_ag_rsp = 104
lsm9_ds1_who_am_i_m_rsp = 61
|
def handle(event, context):
"""handle a request to the function
Args:
event (dict): request params
context (dict): function call metadata
"""
return {
"message": "Hello From Python3 runtime on Serverless Framework and Scaleway Functions"
}
|
def handle(event, context):
"""handle a request to the function
Args:
event (dict): request params
context (dict): function call metadata
"""
return {'message': 'Hello From Python3 runtime on Serverless Framework and Scaleway Functions'}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 15:19:36 2020
@author: krishan
"""
class Book:
def __init__(self, pages):
self.pages = pages
def __add__(self, other):
total = self.pages + other.pages
b = Book(total)
return b
def __mul__(self, other):
total = self.pages * other.pages
b = Book(total)
return b
def __str__(self):
return str(self.pages)
b1 = Book(100)
b2 = Book(200)
b3 = Book(300)
b4 = Book(400)
b5 = Book(500)
print(b1 + b2 + b3 + b4 + b5)
print(b1 * b2 + b3 + b4 * b5)
|
"""
Created on Mon Aug 10 15:19:36 2020
@author: krishan
"""
class Book:
def __init__(self, pages):
self.pages = pages
def __add__(self, other):
total = self.pages + other.pages
b = book(total)
return b
def __mul__(self, other):
total = self.pages * other.pages
b = book(total)
return b
def __str__(self):
return str(self.pages)
b1 = book(100)
b2 = book(200)
b3 = book(300)
b4 = book(400)
b5 = book(500)
print(b1 + b2 + b3 + b4 + b5)
print(b1 * b2 + b3 + b4 * b5)
|
n = int(input('digite um numero: '))
n2 = int(input('digite um numero: '))
def soma ():
s = n + n2
print(soma)
|
n = int(input('digite um numero: '))
n2 = int(input('digite um numero: '))
def soma():
s = n + n2
print(soma)
|
# noinspection PyUnusedLocal
# skus = unicode string
def checkout(skus):
sd = dict()
for sku in skus:
if sku in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if sku in sd:
sd[sku] += 1
else:
sd[sku] = 1
else:
return -1
na = sd.get('A', 0)
p = int(na/5) * 200
na %= 5
p += int(na/3) * 130 + (na%3) * 50
p += 20 * sd.get('C', 0)
p += 15 * sd.get('D', 0)
ne = sd.get('E', 0)
p += 40 * ne
nb = max(0, sd.get('B', 0)-int(ne/2))
p += int(nb / 2) * 45 + (nb % 2) * 30
ff = int(sd.get('F', 0) / 3)
nf = max(0, sd.get('F', 0)-ff)
p += 10 * nf
p += 20 * sd.get('G', 0)
nh = sd.get('H', 0)
p += int(nh/10) * 80
nh %= 10
p += int(nh/5) * 45
nh %= 5
p += nh * 10
p += sd.get('I', 0) * 35
p += sd.get('J', 0) * 60
nk = sd.get('K', 0)
p += int(nk/2) * 120
nk %= 2
p += nk * 70
p += sd.get('L', 0) * 90
nn = sd.get('N', 0)
p += 40 * nn
nm = max(0, sd.get('M', 0)-int(nn/3))
p += nm * 15
p += sd.get('O', 0) * 10
np = sd.get('P', 0)
p += int(np/5) * 200
np %= 5
p += np * 50
nr = sd.get('R', 0)
p += nr * 50
fq = int(nr/3)
nq = max(0, sd.get('Q', 0)-fq)
p += int(nq/3) * 80
p += (nq%3) * 30
fu = int(sd.get('U', 0) / 4)
nu = max(0, sd.get('U', 0)-fu)
p += 40 * nu
nv = sd.get('V', 0)
p += int(nv/3) * 130
nv %= 3
p += int(nv/2) * 90
nv %= 2
p += nv * 50
p += 20 * sd.get('W', 0)
ns = sd.get('S', 0)
nt = sd.get('T', 0)
nx = sd.get('X', 0)
ny = sd.get('Y', 0)
nz = sd.get('Z', 0)
# it was cut highest priced first then others (ZSTYX)
# actually I could not get the exact criteria from the specs :(
ngrp = ns + nt + nx + ny + nz
p += int(ngrp/3) * 45
fgrp = ngrp % 3
while fgrp > 0:
if nx > 0:
p += 17
nx -= 1
elif ny > 0:
p += 20
ny -= 1
elif nt > 0:
p += 20
nt -= 1
elif ns > 0:
p += 20
ns -= 1
elif nz > 0:
p += 21
nz -= 1
fgrp -= 1
return int(p)
|
def checkout(skus):
sd = dict()
for sku in skus:
if sku in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if sku in sd:
sd[sku] += 1
else:
sd[sku] = 1
else:
return -1
na = sd.get('A', 0)
p = int(na / 5) * 200
na %= 5
p += int(na / 3) * 130 + na % 3 * 50
p += 20 * sd.get('C', 0)
p += 15 * sd.get('D', 0)
ne = sd.get('E', 0)
p += 40 * ne
nb = max(0, sd.get('B', 0) - int(ne / 2))
p += int(nb / 2) * 45 + nb % 2 * 30
ff = int(sd.get('F', 0) / 3)
nf = max(0, sd.get('F', 0) - ff)
p += 10 * nf
p += 20 * sd.get('G', 0)
nh = sd.get('H', 0)
p += int(nh / 10) * 80
nh %= 10
p += int(nh / 5) * 45
nh %= 5
p += nh * 10
p += sd.get('I', 0) * 35
p += sd.get('J', 0) * 60
nk = sd.get('K', 0)
p += int(nk / 2) * 120
nk %= 2
p += nk * 70
p += sd.get('L', 0) * 90
nn = sd.get('N', 0)
p += 40 * nn
nm = max(0, sd.get('M', 0) - int(nn / 3))
p += nm * 15
p += sd.get('O', 0) * 10
np = sd.get('P', 0)
p += int(np / 5) * 200
np %= 5
p += np * 50
nr = sd.get('R', 0)
p += nr * 50
fq = int(nr / 3)
nq = max(0, sd.get('Q', 0) - fq)
p += int(nq / 3) * 80
p += nq % 3 * 30
fu = int(sd.get('U', 0) / 4)
nu = max(0, sd.get('U', 0) - fu)
p += 40 * nu
nv = sd.get('V', 0)
p += int(nv / 3) * 130
nv %= 3
p += int(nv / 2) * 90
nv %= 2
p += nv * 50
p += 20 * sd.get('W', 0)
ns = sd.get('S', 0)
nt = sd.get('T', 0)
nx = sd.get('X', 0)
ny = sd.get('Y', 0)
nz = sd.get('Z', 0)
ngrp = ns + nt + nx + ny + nz
p += int(ngrp / 3) * 45
fgrp = ngrp % 3
while fgrp > 0:
if nx > 0:
p += 17
nx -= 1
elif ny > 0:
p += 20
ny -= 1
elif nt > 0:
p += 20
nt -= 1
elif ns > 0:
p += 20
ns -= 1
elif nz > 0:
p += 21
nz -= 1
fgrp -= 1
return int(p)
|
def test_upgrade_atac_alignment_enrichment_quality_metric_1_2(
upgrader, atac_alignment_enrichment_quality_metric_1
):
value = upgrader.upgrade(
'atac_alignment_enrichment_quality_metric',
atac_alignment_enrichment_quality_metric_1,
current_version='1',
target_version='2',
)
assert value['schema_version'] == '2'
assert 'fri_blacklist' not in value
assert value['fri_exclusion_list'] == 0.0013046877081284722
|
def test_upgrade_atac_alignment_enrichment_quality_metric_1_2(upgrader, atac_alignment_enrichment_quality_metric_1):
value = upgrader.upgrade('atac_alignment_enrichment_quality_metric', atac_alignment_enrichment_quality_metric_1, current_version='1', target_version='2')
assert value['schema_version'] == '2'
assert 'fri_blacklist' not in value
assert value['fri_exclusion_list'] == 0.0013046877081284722
|
PREVIEW_CHOICES = [
('slider', 'Slider'),
('pre-order', 'Pre-order'),
('new', 'New'),
('offer', 'Offer'),
('hidden', 'Hidden'),
]
CATEGORY_CHOICES = [
('accesory', 'Accesory'),
('bottom', 'Bottoms'),
('hoodie', 'Hoodies'),
('outerwear', 'Outerwears'),
('sneaker', 'Sneakers'),
('t-shirt', 'T-Shirts'),
]
|
preview_choices = [('slider', 'Slider'), ('pre-order', 'Pre-order'), ('new', 'New'), ('offer', 'Offer'), ('hidden', 'Hidden')]
category_choices = [('accesory', 'Accesory'), ('bottom', 'Bottoms'), ('hoodie', 'Hoodies'), ('outerwear', 'Outerwears'), ('sneaker', 'Sneakers'), ('t-shirt', 'T-Shirts')]
|
# SPDX-License-Identifier: BSD-2-Clause
"""osdk-manager about details.
Manage osdk and opm binary installation, and help to scaffold, release, and
version Operator SDK-based Kubernetes operators.
This file contains some basic variables used for setup.
"""
__title__ = "osdk-manager"
__name__ = __title__
__summary__ = "A script for managing Operator SDK-based operators."
__uri__ = "https://github.com/jharmison-redhat/osdk-manager"
__version__ = "0.3.0"
__release__ = "1"
__status__ = "Development"
__author__ = "James Harmison"
__email__ = "[email protected]"
__license__ = "BSD-2-Clause"
__copyright__ = "2020 %s" % __author__
__requires__ = [
'requests',
'click',
'lastversion',
'python-gnupg',
'PyYAML'
]
|
"""osdk-manager about details.
Manage osdk and opm binary installation, and help to scaffold, release, and
version Operator SDK-based Kubernetes operators.
This file contains some basic variables used for setup.
"""
__title__ = 'osdk-manager'
__name__ = __title__
__summary__ = 'A script for managing Operator SDK-based operators.'
__uri__ = 'https://github.com/jharmison-redhat/osdk-manager'
__version__ = '0.3.0'
__release__ = '1'
__status__ = 'Development'
__author__ = 'James Harmison'
__email__ = '[email protected]'
__license__ = 'BSD-2-Clause'
__copyright__ = '2020 %s' % __author__
__requires__ = ['requests', 'click', 'lastversion', 'python-gnupg', 'PyYAML']
|
print("Let's practice everything")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs.')
poem="""
\tThe lovely world
with logic so firmly planted
cannnot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print("---------------")
print(poem)
print("---------------")
five=10-2+3-6
print(f"This should be five:{five}")
def secret_formula(started):
jelly_beans=started*500
jars=jelly_beans / 1000
crates=jars /100
return jelly_beans,jars,crates
start_point=10000
beans,jars,crates=secret_formula(start_point)
print("With a starting point of :{}".format(start_point))
print(f"We'd have {beans} beans,{jars} jars, and {crates}crates.")
start_point=start_point /10
print("We can also do that this way:")
formula=secret_formula(start_point)
print("We'd have {} beans,{} jars,{} crates.".format(*formula))
|
print("Let's practice everything")
print("You'd need to know 'bout escapes with \\ that do:")
print('\n newlines and \t tabs.')
poem = '\n\tThe lovely world\nwith logic so firmly planted\ncannnot discern \n the needs of love\nnor comprehend passion from intuition\nand requires an explanation\n\n\t\twhere there is none.\n'
print('---------------')
print(poem)
print('---------------')
five = 10 - 2 + 3 - 6
print(f'This should be five:{five}')
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return (jelly_beans, jars, crates)
start_point = 10000
(beans, jars, crates) = secret_formula(start_point)
print('With a starting point of :{}'.format(start_point))
print(f"We'd have {beans} beans,{jars} jars, and {crates}crates.")
start_point = start_point / 10
print('We can also do that this way:')
formula = secret_formula(start_point)
print("We'd have {} beans,{} jars,{} crates.".format(*formula))
|
class Estereo:
def __init__(self, marca) -> None:
self.marca = marca
self.estado = 'apagado'
|
class Estereo:
def __init__(self, marca) -> None:
self.marca = marca
self.estado = 'apagado'
|
list = [2, 4, 6, 8]
sum = 0
for num in list:
sum = sum + num
print("The sum is:", sum)
|
list = [2, 4, 6, 8]
sum = 0
for num in list:
sum = sum + num
print('The sum is:', sum)
|
class RDBMSHost:
def __init__(self, host: str, port: int, db_name: str, db_schema: str, db_user: str, db_password: str):
self.host: str = host
self.port: int = port
self.db_name: str = db_name
self.db_schema: str = db_schema
self.db_user: str = db_user
self.db_password: str = db_password
|
class Rdbmshost:
def __init__(self, host: str, port: int, db_name: str, db_schema: str, db_user: str, db_password: str):
self.host: str = host
self.port: int = port
self.db_name: str = db_name
self.db_schema: str = db_schema
self.db_user: str = db_user
self.db_password: str = db_password
|
grid = [input() for _ in range(323)]
width = len(grid[0])
height = len(grid)
trees = 0
i, j = 0, 0
while (i := i + 1) < height:
j = (j + 3) % width
if grid[i][j] == '#':
trees += 1
print(trees)
|
grid = [input() for _ in range(323)]
width = len(grid[0])
height = len(grid)
trees = 0
(i, j) = (0, 0)
while (i := (i + 1)) < height:
j = (j + 3) % width
if grid[i][j] == '#':
trees += 1
print(trees)
|
def test_root_redirect(client):
r_root = client.get("/")
assert r_root.status_code == 302
assert r_root.headers["Location"].endswith("/overview/")
|
def test_root_redirect(client):
r_root = client.get('/')
assert r_root.status_code == 302
assert r_root.headers['Location'].endswith('/overview/')
|
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
size = len(prices)
bought = False
profit = 0
price = 0
for i in range(0, size - 1):
if not bought:
if prices[i] < prices[i + 1]:
bought = True
price = prices[i]
else:
if prices[i] > prices[i + 1]:
bought = False
profit += prices[i] - price
price = 0
if bought:
profit += prices[i + 1] - price
return profit
|
class Solution:
def max_profit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
size = len(prices)
bought = False
profit = 0
price = 0
for i in range(0, size - 1):
if not bought:
if prices[i] < prices[i + 1]:
bought = True
price = prices[i]
elif prices[i] > prices[i + 1]:
bought = False
profit += prices[i] - price
price = 0
if bought:
profit += prices[i + 1] - price
return profit
|
'''8. Write a Python program to split a given list into two parts where the length of the first part of the list is given.
Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
Length of the first part of the list: 3
Splited the said list into two parts:
([1, 1, 2], [3, 4, 4, 5, 1]) '''
def split_two_parts(n_list, L):
return n_list[:L], n_list[L:]
n_list = [1,1,2,3,4,4,5, 1]
print("Original list:")
print(n_list)
first_list_length = 3
print("\nLength of the first part of the list:",first_list_length)
print("\nSplited the said list into two parts:")
print(split_two_parts(n_list, first_list_length))
|
"""8. Write a Python program to split a given list into two parts where the length of the first part of the list is given.
Original list:
[1, 1, 2, 3, 4, 4, 5, 1]
Length of the first part of the list: 3
Splited the said list into two parts:
([1, 1, 2], [3, 4, 4, 5, 1]) """
def split_two_parts(n_list, L):
return (n_list[:L], n_list[L:])
n_list = [1, 1, 2, 3, 4, 4, 5, 1]
print('Original list:')
print(n_list)
first_list_length = 3
print('\nLength of the first part of the list:', first_list_length)
print('\nSplited the said list into two parts:')
print(split_two_parts(n_list, first_list_length))
|
n = int(input())
for i in range(n):
row, base, number = map(int, input().split())
remains = list()
while number > 0:
remain = number % base
number = number // base
remains.append(remain)
sumOfRemains = 0
for i in range(len(remains)):
remains[i] = remains[i] ** 2
sumOfRemains += remains[i]
print(f'{row} {sumOfRemains}')
|
n = int(input())
for i in range(n):
(row, base, number) = map(int, input().split())
remains = list()
while number > 0:
remain = number % base
number = number // base
remains.append(remain)
sum_of_remains = 0
for i in range(len(remains)):
remains[i] = remains[i] ** 2
sum_of_remains += remains[i]
print(f'{row} {sumOfRemains}')
|
with open("110000.dat","r") as fi:
with open("110000num.dat","w") as fo:
i=1
for l in fi.readlines():
if i%100 == 0:
fo.write(l.strip()+" #"+str(i)+"\n")
else:
fo.write(l)
i = i+1
|
with open('110000.dat', 'r') as fi:
with open('110000num.dat', 'w') as fo:
i = 1
for l in fi.readlines():
if i % 100 == 0:
fo.write(l.strip() + ' #' + str(i) + '\n')
else:
fo.write(l)
i = i + 1
|
class Person(object):
# This definition hasn't changed from part 1!
def __init__(self, fn, ln, em, age, occ):
self.firstName = fn
self.lastName = ln
self.email = em
self.age = age
self.occupation = occ
class Occupation(object):
def __init__(self, name, location):
self.name = name
self.location = location
if __name__ == "__main__":
stringOcc = "Lawyer"
person1 = Person(
"Michael",
"Smith",
"[email protected]",
27,
stringOcc)
classOcc = Occupation("Software Engineer", "San Francisco")
# Still works!
person2 = Person(
"Katie",
"Johnson",
"[email protected]",
26,
classOcc)
people = [person1, person2]
for p in people:
# This works. Both types of occupations are printable.
print(p.occupation)
# This won't work. Our "Occupation" class
# doesn't work with "len"
# print(len(p.occupation))
|
class Person(object):
def __init__(self, fn, ln, em, age, occ):
self.firstName = fn
self.lastName = ln
self.email = em
self.age = age
self.occupation = occ
class Occupation(object):
def __init__(self, name, location):
self.name = name
self.location = location
if __name__ == '__main__':
string_occ = 'Lawyer'
person1 = person('Michael', 'Smith', '[email protected]', 27, stringOcc)
class_occ = occupation('Software Engineer', 'San Francisco')
person2 = person('Katie', 'Johnson', '[email protected]', 26, classOcc)
people = [person1, person2]
for p in people:
print(p.occupation)
|
#!/usr/bin/python3
class Face(object):
def __init__(self, bbox, aligned_face_img, confidence, key_points):
self._bbox = bbox # [x_min, y_min, x_max, y_max]
self._aligned_face_img = aligned_face_img
self._confidence = confidence
self._key_points = key_points
@property
def bbox(self):
return self._bbox
@property
def confidence(self):
return self._confidence
@property
def key_points(self):
return self._key_points
@property
def aligned_face_img(self):
return self._aligned_face_img
|
class Face(object):
def __init__(self, bbox, aligned_face_img, confidence, key_points):
self._bbox = bbox
self._aligned_face_img = aligned_face_img
self._confidence = confidence
self._key_points = key_points
@property
def bbox(self):
return self._bbox
@property
def confidence(self):
return self._confidence
@property
def key_points(self):
return self._key_points
@property
def aligned_face_img(self):
return self._aligned_face_img
|
start_house, end_house = map(int, input().split())
left_tree, right_tree = map(int, input().split())
number_of_apples, number_of_oranges = map(int, input().split())
apple_distances = map(int, input().split())
orange_distances = map(int, input().split())
apple_count = 0
orange_count = 0
for distance in apple_distances:
if start_house <= left_tree + distance <= end_house:
apple_count += 1
for distance in orange_distances:
if start_house <= right_tree + distance <= end_house:
orange_count += 1
print(apple_count)
print(orange_count)
|
(start_house, end_house) = map(int, input().split())
(left_tree, right_tree) = map(int, input().split())
(number_of_apples, number_of_oranges) = map(int, input().split())
apple_distances = map(int, input().split())
orange_distances = map(int, input().split())
apple_count = 0
orange_count = 0
for distance in apple_distances:
if start_house <= left_tree + distance <= end_house:
apple_count += 1
for distance in orange_distances:
if start_house <= right_tree + distance <= end_house:
orange_count += 1
print(apple_count)
print(orange_count)
|
def countInversions(nums):
#Our recursive base case, if our list is of size 1 we know there's no inversion and that it's already sorted
if len(nums) == 1: return nums, 0
#We run our function recursively on it's left and right halves
left, leftInversions = countInversions(nums[:len(nums) // 2])
right, rightInversions = countInversions(nums[len(nums) // 2:])
#Initialize our inversions variable to be the number of inversions in each half
inversions = leftInversions + rightInversions
#Initialize a list to hold our sorted result list
sortedNums = []
i = j = 0
#Here we count the inversions that exist between the two halves -- while sorting them at the same time
while i < len(left) and j < len(right):
if left[i] < right[j]:
sortedNums += [left[i]]; i += 1
else:
sortedNums += [right[j]]; j += 1
#Since we know that 'left' is sorted, once we reach an item in 'left' thats bigger than something in right that item and everything to it's right-hand side must be an inversion!
#This line right here is exactly what shrinks the time of this algorithm from n^2 to nlogn as it means we don't need to compare every single pair
inversions += len(left) - i
#Once we've exhausted either left or right, we can just add the other one onto our sortedNums list
sortedNums += left[i:] + right[j:]
return sortedNums, inversions
def main():
nums = [1, 5, 4, 8, 10, 2, 6, 9]
print(countInversions(nums))
main()
|
def count_inversions(nums):
if len(nums) == 1:
return (nums, 0)
(left, left_inversions) = count_inversions(nums[:len(nums) // 2])
(right, right_inversions) = count_inversions(nums[len(nums) // 2:])
inversions = leftInversions + rightInversions
sorted_nums = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_nums += [left[i]]
i += 1
else:
sorted_nums += [right[j]]
j += 1
inversions += len(left) - i
sorted_nums += left[i:] + right[j:]
return (sortedNums, inversions)
def main():
nums = [1, 5, 4, 8, 10, 2, 6, 9]
print(count_inversions(nums))
main()
|
# find highest grade of an assignment
def highest_SRQs_grade(queryset):
queryset = queryset.order_by('-assignment', 'SRQs_grade')
dict_q = {}
for each in queryset:
dict_q[each.assignment] = each
result = []
for assignment in dict_q.values():
result.append(assignment)
return result
|
def highest_sr_qs_grade(queryset):
queryset = queryset.order_by('-assignment', 'SRQs_grade')
dict_q = {}
for each in queryset:
dict_q[each.assignment] = each
result = []
for assignment in dict_q.values():
result.append(assignment)
return result
|
def f(x):
if x:
return
if x:
return
elif y:
return
if x:
return
else:
return
if x:
return
elif y:
return
else:
return
if x:
return
elif y:
return
elif z:
return
else:
return
return None
|
def f(x):
if x:
return
if x:
return
elif y:
return
if x:
return
else:
return
if x:
return
elif y:
return
else:
return
if x:
return
elif y:
return
elif z:
return
else:
return
return None
|
# Iterative approach using stack
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if root1 == None:
return root2
stack = []
stack.append([root1, root2])
while stack:
node = stack.pop()
# possible when tree2 node was None
if node[0]==None or node[1]==None:
continue
node[0].val += node[1].val
# merging tree2's left subtree with tree1's left subtree
if node[0].left == None:
node[0].left = node[1].left
else:
stack.append([node[0].left, node[1].left])
# merging tree2's right subtree with tree1's right subtree
if node[0].right == None:
node[0].right = node[1].right
else:
stack.append([node[0].right, node[1].right])
return root1
|
class Solution:
def merge_trees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if root1 == None:
return root2
stack = []
stack.append([root1, root2])
while stack:
node = stack.pop()
if node[0] == None or node[1] == None:
continue
node[0].val += node[1].val
if node[0].left == None:
node[0].left = node[1].left
else:
stack.append([node[0].left, node[1].left])
if node[0].right == None:
node[0].right = node[1].right
else:
stack.append([node[0].right, node[1].right])
return root1
|
class point:
"K-D POINT CLASS"
def __init__(self,coordinate, name=None, dim=None):
""" name, dimension and coordinates """
self.name = name
if type(dim) == type(None):
self.dim = len(coordinate)
else:
self.dim = dim
if len(coordinate) == self.dim:
self.coordinate = coordinate
else:
raise Exception("INVALID DIMENSIONAL INFORMATION WHILE CREATING A POINT")
def getx(self):
if self.dim >= 1:
return self.coordinate[0]
else:
return None
def gety(self):
if self.dim >= 2:
return self.coordinate[1]
else:
return None
def getz(self):
if self.dim >= 3:
return self.coordinate[2]
else:
return None
def get(self,k):
if self.dim >= k:
return self.coordinate[k]
else:
return None
def print(self):
print("Name:",self.name,"Dim:",self.dim,"Coordinates:",self.coordinate)
return
def __eq__(self, other):
if (type(self) != type(None) and type(other) == type(None)) or (type(self) == type(None) and type(other) != type(None)):
return False
if self.dim == other.dim and self.coordinate == other.coordinate:
return True
return False
def __ne__(self, other):
if (type(self) != type(None) and type(other) == type(None)) or (type(self) == type(None) and type(other) != type(None)):
return False
if self.dim != other.dim or self.coordinate != other.coordinate:
return True
return False
def __lt__(self, other):
'''overload lesser than operator mainly for heapq'''
t = self.coordinate < other.coordinate
return t
def __gt__(self, other):
'''overload greater than operator mainly for heapq'''
t = self.coordinate > other.coordinate
return t
def copy(self):
k = point(self.coordinate, self.name, self.dim)
return k
def distance(self, other):
if self.dim != other.dim:
return None
dist = 0
for i in range(self.dim):
dist += (self.coordinate[i] - other.coordinate[i])**2
dist = dist**0.5
return dist
def in_range(self, bounds):
"""return true if a point lies within given bounds"""
if len(bounds) != self.dim:
raise Exception("DIMENSIONAL INCONSISTENCY WHILE CALLING IN_RANGE")
for i in range(self.dim):
if(not(bounds[i][0] <= self.coordinate[i] <= bounds[i][1])):
return False
return True
|
class Point:
"""K-D POINT CLASS"""
def __init__(self, coordinate, name=None, dim=None):
""" name, dimension and coordinates """
self.name = name
if type(dim) == type(None):
self.dim = len(coordinate)
else:
self.dim = dim
if len(coordinate) == self.dim:
self.coordinate = coordinate
else:
raise exception('INVALID DIMENSIONAL INFORMATION WHILE CREATING A POINT')
def getx(self):
if self.dim >= 1:
return self.coordinate[0]
else:
return None
def gety(self):
if self.dim >= 2:
return self.coordinate[1]
else:
return None
def getz(self):
if self.dim >= 3:
return self.coordinate[2]
else:
return None
def get(self, k):
if self.dim >= k:
return self.coordinate[k]
else:
return None
def print(self):
print('Name:', self.name, 'Dim:', self.dim, 'Coordinates:', self.coordinate)
return
def __eq__(self, other):
if type(self) != type(None) and type(other) == type(None) or (type(self) == type(None) and type(other) != type(None)):
return False
if self.dim == other.dim and self.coordinate == other.coordinate:
return True
return False
def __ne__(self, other):
if type(self) != type(None) and type(other) == type(None) or (type(self) == type(None) and type(other) != type(None)):
return False
if self.dim != other.dim or self.coordinate != other.coordinate:
return True
return False
def __lt__(self, other):
"""overload lesser than operator mainly for heapq"""
t = self.coordinate < other.coordinate
return t
def __gt__(self, other):
"""overload greater than operator mainly for heapq"""
t = self.coordinate > other.coordinate
return t
def copy(self):
k = point(self.coordinate, self.name, self.dim)
return k
def distance(self, other):
if self.dim != other.dim:
return None
dist = 0
for i in range(self.dim):
dist += (self.coordinate[i] - other.coordinate[i]) ** 2
dist = dist ** 0.5
return dist
def in_range(self, bounds):
"""return true if a point lies within given bounds"""
if len(bounds) != self.dim:
raise exception('DIMENSIONAL INCONSISTENCY WHILE CALLING IN_RANGE')
for i in range(self.dim):
if not bounds[i][0] <= self.coordinate[i] <= bounds[i][1]:
return False
return True
|
# 26.05.2019
# Working with BitwiseOperators and different kind of String Outputs.
print(f"Working with Bitwise Operators and different kind of String Outputs.")
var1 = 13 # 13 in Binary: 1101
var2 = 5 # 5 in Binary: 0101
# AND Operator with format String
# 1101 13
# 0101 5
# ---- AND: 1,0 = 0; 1,1 = 1; 0,0 = 0
# 0101 -> 5
print("AND & Operator {}".format(var1 & var2))
# OR Operator with f-String
# 1101 13
# 0101 5
# ---- OR: 1,0 = 1; 1,1 = 1; 0,0 = 0
# 1101 -> 13
print(f"OR | operator {var1 | var2}")
# XOR Operator with String-formatting
# 1101 13
# 0101 5
# ---- XOR: 1,0 = 1; 1,1 = 0; 0,0 = 0
# 1000 -> 8
print("XOR ^ operator %d" %(var1 ^ var2))
# Left Shift Operator with String .format
# 1101 13
# ---- Left Shift: var << 1
# 11010 -> 26
print("Left Shift << operator {}".format(var1 << 1))
# Right Shift Operator with f-String
# 1101 13
# ---- Right Shift: var >> 1
# 0110 -> 6
print(f"Right Shift >> operator {var1 >> 1}")
|
print(f'Working with Bitwise Operators and different kind of String Outputs.')
var1 = 13
var2 = 5
print('AND & Operator {}'.format(var1 & var2))
print(f'OR | operator {var1 | var2}')
print('XOR ^ operator %d' % (var1 ^ var2))
print('Left Shift << operator {}'.format(var1 << 1))
print(f'Right Shift >> operator {var1 >> 1}')
|
"""
Given a non negative integer number num. For every numbers i in the range 0 <= i <= num calculate the number of 1's in
their binary representation and return them as an array.
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /
possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other
language.
"""
__author__ = 'Daniel'
class Solution(object):
def countBits(self, num):
"""
Dynamic programming: make use of what you have produced already
0 => 0
1 => 1
10 => 1+0
11 => 1+1
100 => 1+0
101 => 1+1
110 => 1+1
111 => 1+2
:type num: int
:rtype: List[int]
"""
ret = [0]
i = 0
hi = len(ret)
while len(ret) < num + 1:
if i == hi:
i = 0
hi = len(ret)
ret.append(1+ret[i])
i += 1
return ret
|
"""
Given a non negative integer number num. For every numbers i in the range 0 <= i <= num calculate the number of 1's in
their binary representation and return them as an array.
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /
possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other
language.
"""
__author__ = 'Daniel'
class Solution(object):
def count_bits(self, num):
"""
Dynamic programming: make use of what you have produced already
0 => 0
1 => 1
10 => 1+0
11 => 1+1
100 => 1+0
101 => 1+1
110 => 1+1
111 => 1+2
:type num: int
:rtype: List[int]
"""
ret = [0]
i = 0
hi = len(ret)
while len(ret) < num + 1:
if i == hi:
i = 0
hi = len(ret)
ret.append(1 + ret[i])
i += 1
return ret
|
"""
Conf file for product catagory and payment gateway
"""
#Products
product_sunscreens_category = ['SPF-50','SPF-30']
product_moisturizers_category = ['Aloe','Almond']
|
"""
Conf file for product catagory and payment gateway
"""
product_sunscreens_category = ['SPF-50', 'SPF-30']
product_moisturizers_category = ['Aloe', 'Almond']
|
class Solution:
def numTilings(self, n: int) -> int:
MOD = 1000000007
if n <= 2:
return n
previous = 1
result = 2
current = 1
for k in range(3, n + 1):
tmp = result
result = (result + previous + 2 * current) % MOD
current = (current + previous) % MOD
previous = tmp
return result
s = Solution()
print(s.numTilings(3))
print(s.numTilings(1))
|
class Solution:
def num_tilings(self, n: int) -> int:
mod = 1000000007
if n <= 2:
return n
previous = 1
result = 2
current = 1
for k in range(3, n + 1):
tmp = result
result = (result + previous + 2 * current) % MOD
current = (current + previous) % MOD
previous = tmp
return result
s = solution()
print(s.numTilings(3))
print(s.numTilings(1))
|
# 4. Caesar Cipher
# Write a program that returns an encrypted version of the same text.
# Encrypt the text by shifting each character with three positions forward.
# For example A would be replaced by D, B would become E, and so on. Print the encrypted text.
text = input()
encrypted_text = [chr(ord(character) + 3) for character in text]
print("".join(encrypted_text))
|
text = input()
encrypted_text = [chr(ord(character) + 3) for character in text]
print(''.join(encrypted_text))
|
ies = []
ies.append({ "ie_type" : "Node ID", "ie_value" : "Node ID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier of the sending Node."})
ies.append({ "ie_type" : "F-SEID", "ie_value" : "CP F-SEID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier allocated by the CP function identifying the session."})
ies.append({ "ie_type" : "Create PDR", "ie_value" : "Create PDR", "presence" : "O", "instance" : "0", "comment" : "This IE shall be present for at least one PDR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple PDRs.See Table 7.5.2.2-1."})
ies.append({ "ie_type" : "Create PDR", "ie_value" : "Create PDR", "presence" : "M", "instance" : "1", "comment" : "This IE shall be present for at least one PDR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple PDRs.See Table 7.5.2.2-1."})
ies.append({ "ie_type" : "Create FAR", "ie_value" : "Create FAR", "presence" : "O", "instance" : "0", "comment" : "This IE shall be present for at least one FAR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple FARs.See Table 7.5.2.3-1."})
ies.append({ "ie_type" : "Create FAR", "ie_value" : "Create FAR", "presence" : "M", "instance" : "1", "comment" : "This IE shall be present for at least one FAR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple FARs.See Table 7.5.2.3-1."})
ies.append({ "ie_type" : "Create URR", "ie_value" : "Create URR", "presence" : "C", "instance" : "0", "comment" : "This IE shall be present if a measurement action shall be applied to packets matching one or more PDR(s) of this PFCP session. Several IEs within the same IE type may be present to represent multiple URRs.See Table 7.5.2.4-1."})
ies.append({ "ie_type" : "Create QER", "ie_value" : "Create QER", "presence" : "C", "instance" : "0", "comment" : "This IE shall be present if a QoS enforcement action shall be applied to packets matching one or more PDR(s) of this PFCP session.Several IEs within the same IE type may be present to represent multiple QERs.See Table 7.5.2.5-1."})
ies.append({ "ie_type" : "Create BAR", "ie_value" : "Create BAR", "presence" : "O", "instance" : "0", "comment" : "When present, this IE shall contain the buffering instructions to be applied by the UP function to any FAR of this PFCP session set with the Apply Action requesting the packets to be buffered and with a BAR ID IE referring to this BAR. See table 7.5.2.6-1."})
ies.append({ "ie_type" : "PDN Typep", "ie_value" : "PDN Type", "presence" : "C", "instance" : "0", "comment" : "This IE shall be present if the PFCP session is setup for an individual PDN connection or PDU session (see subclause 5.2.1). When present, this IE shall indicate whether this is an IP or non-IP PDN connection/PDU session. "})
ies.append({ "ie_type" : "FQ-CSIDp", "ie_value" : "SGW-C FQ-CSID", "presence" : "C", "instance" : "0", "comment" : "This IE shall be included according to the requirements in clause23 of 3GPPTS 23.007[24]."})
ies.append({ "ie_type" : "User Plane Inactivity Timer", "ie_value" : "User Plane Inactivity Timer", "presence" : "O", "instance" : "0", "comment" : "This IE may be present to request the UP function to send a User Plane Inactivity Report when no user plane packets are received for this PFCP session for a duration exceeding the User Plane Inactivity Timer. When present, it shall contain the duration of the inactivity period after which a User Plane Inactivity Report shall be generated."})
msg_list[key]["ies"] = ies
|
ies = []
ies.append({'ie_type': 'Node ID', 'ie_value': 'Node ID', 'presence': 'M', 'instance': '0', 'comment': 'This IE shall contain the unique identifier of the sending Node.'})
ies.append({'ie_type': 'F-SEID', 'ie_value': 'CP F-SEID', 'presence': 'M', 'instance': '0', 'comment': 'This IE shall contain the unique identifier allocated by the CP function identifying the session.'})
ies.append({'ie_type': 'Create PDR', 'ie_value': 'Create PDR', 'presence': 'O', 'instance': '0', 'comment': 'This IE shall be present for at least one PDR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple PDRs.See Table 7.5.2.2-1.'})
ies.append({'ie_type': 'Create PDR', 'ie_value': 'Create PDR', 'presence': 'M', 'instance': '1', 'comment': 'This IE shall be present for at least one PDR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple PDRs.See Table 7.5.2.2-1.'})
ies.append({'ie_type': 'Create FAR', 'ie_value': 'Create FAR', 'presence': 'O', 'instance': '0', 'comment': 'This IE shall be present for at least one FAR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple FARs.See Table 7.5.2.3-1.'})
ies.append({'ie_type': 'Create FAR', 'ie_value': 'Create FAR', 'presence': 'M', 'instance': '1', 'comment': 'This IE shall be present for at least one FAR to be associated to the PFCP session.Several IEs with the same IE type may be present to represent multiple FARs.See Table 7.5.2.3-1.'})
ies.append({'ie_type': 'Create URR', 'ie_value': 'Create URR', 'presence': 'C', 'instance': '0', 'comment': 'This IE shall be present if a measurement action shall be applied to packets matching one or more PDR(s) of this PFCP session. Several IEs within the same IE type may be present to represent multiple URRs.See Table 7.5.2.4-1.'})
ies.append({'ie_type': 'Create QER', 'ie_value': 'Create QER', 'presence': 'C', 'instance': '0', 'comment': 'This IE shall be present if a QoS enforcement action shall be applied to packets matching one or more PDR(s) of this PFCP session.Several IEs within the same IE type may be present to represent multiple QERs.See Table 7.5.2.5-1.'})
ies.append({'ie_type': 'Create BAR', 'ie_value': 'Create BAR', 'presence': 'O', 'instance': '0', 'comment': 'When present, this IE shall contain the buffering instructions to be applied by the UP function to any FAR of this PFCP session set with the Apply Action requesting the packets to be buffered and with a BAR ID IE referring to this BAR. See table 7.5.2.6-1.'})
ies.append({'ie_type': 'PDN Typep', 'ie_value': 'PDN Type', 'presence': 'C', 'instance': '0', 'comment': 'This IE shall be present if the PFCP session is setup for an individual PDN connection or PDU session (see subclause 5.2.1). When present, this IE shall indicate whether this is an IP or non-IP PDN connection/PDU session. '})
ies.append({'ie_type': 'FQ-CSIDp', 'ie_value': 'SGW-C FQ-CSID', 'presence': 'C', 'instance': '0', 'comment': 'This IE shall be included according to the requirements in clause23 of 3GPPTS 23.007[24].'})
ies.append({'ie_type': 'User Plane Inactivity Timer', 'ie_value': 'User Plane Inactivity Timer', 'presence': 'O', 'instance': '0', 'comment': 'This IE may be present to request the UP function to send a User Plane Inactivity Report when no user plane packets are received for this PFCP session for a duration exceeding the User Plane Inactivity Timer. When present, it shall contain the duration of the inactivity period after which a User Plane Inactivity Report shall be generated.'})
msg_list[key]['ies'] = ies
|
code = """
400 0078 Clear Display
402 21C0 V1 = 0C0h (Pattern #)
404 2200 V2 = 10h (Cell#)
406 2301 V3 = 01 (Centre)
408 B600 B = 600 Set B to point to $600
40A 1422 CALL 422 Call 422 for C0,C5,CA,CA,BC,B5
40C 21C5 V1 = C5 Print PUZZLE.
40E 1422 CALL 422
410 21CA V1 = CA
412 1422 CALL 422
414 21CA V1 = CA
416 1422 CALL 422
418 21BC V1 = BC
41A 1422 CALL 422
41C 21B5 V1 = B5
41E 1422 CALL 422
420 F430 GOTO 430 Skip over 422 code.
422 7134 V1->LSB of (B) So B is now (say) $6C5
424 7121 Read $6C5 into V1
426 8234 Says V2 + V3 -> V2 which makes more sense.
428 9125 Write graphic V1 and position V2. 5 high.
42A 026E Return.
42C E47A Keyboard on, wait for key to V4.
42E F438 Goto 438
430 0078 Clear Screen
432 F42C Goto 42C
438 0078 Clear Screen
43A 2700 V7 = 0 (timer)
43C 21F0 V1 = F0
43E 2200 V2 = 0
440 1450 Call 450
442 7121 Read Mem(B) to V1.
444 2201 V2 = 1
446 1450 Call 450
448 21F1 V1 = F1
44A 2208 V2 = 8
44C 1450 Call 450
44E F458 Goto 458
;
; Read [$0600+V1] and display pattern at V2
;
450 7134 B = 6[V1]
452 7121 V1 = M[B]
454 912B 8x8 Pattern address in V1, Cell in V2.
456 026E Return
458 025C TV On
45A 21F5 V1 = F5
45C 220E V2 = 0E
45E 1450 Call 450
460 21F3 V1 = F3
462 2215 V2 = 15
464 1450 Call 450
466 7448 Delay V4
468 E480 Get Key Skip if None
46A 1490 Key goto 1490
"""
|
code = '\n400\t\t0078 \tClear Display\n402\t\t21C0 \tV1 = 0C0h \t\t\t(Pattern #)\n404\t\t2200\tV2 = 10h \t\t\t(Cell#)\n406 \t2301 \tV3 = 01 \t\t\t(Centre)\n\n408 \tB600 \tB = 600 \t\t\tSet B to point to $600\n40A \t1422 \tCALL 422 \t\t\tCall 422 for C0,C5,CA,CA,BC,B5\n40C \t21C5 \tV1 = C5 \t\t\tPrint PUZZLE.\n40E \t1422 \tCALL 422\n410 \t21CA \tV1 = CA\n412 \t1422 \tCALL 422\n414 \t21CA \tV1 = CA\n416 \t1422 \tCALL 422\n418 \t21BC \tV1 = BC\n41A \t1422 \tCALL 422\n41C \t21B5 \tV1 = B5\n41E \t1422 \tCALL 422\n420 \tF430 \tGOTO 430 \t\tSkip over 422 code.\n\n\n422 \t7134 \tV1->LSB of (B)\tSo B is now (say) $6C5\n424\t\t7121 \tRead $6C5 into V1\n426 \t8234 \tSays V2 + V3 -> V2 which makes more sense.\n428 \t9125 \tWrite graphic V1 and position V2. 5 high.\n42A \t026E \tReturn.\n\n42C \tE47A \tKeyboard on, wait for key to V4.\n42E \tF438 \tGoto 438\n\n430 \t0078 \tClear Screen\n432\t\tF42C \tGoto 42C\n\n438 \t0078 \tClear Screen\n43A \t2700 \tV7 = 0 (timer)\n\n43C \t21F0 \tV1 = F0\n43E \t2200\tV2 = 0\n440 \t1450\tCall 450\n\n442 \t7121 \tRead Mem(B) to V1.\n444 \t2201\tV2 = 1\n446 \t1450 \tCall 450\n\n448 \t21F1 \tV1 = F1\n44A \t2208\tV2 = 8\n44C \t1450 \tCall 450\n\n44E \tF458 \tGoto 458\n;\n;\tRead [$0600+V1] and display pattern at V2\n;\n450 \t7134 \tB = 6[V1]\n452 \t7121 \tV1 = M[B]\n454 \t912B \t8x8 Pattern address in V1, Cell in V2.\n456 \t026E \tReturn\n\n458 \t025C \tTV On\n45A \t21F5 \tV1 = F5\n45C\t\t220E \tV2 = 0E\n45E \t1450 \tCall 450\n\n460 \t21F3 \tV1 = F3\n462 \t2215 \tV2 = 15\n464 \t1450 \tCall 450\n\n466\t\t7448 \tDelay V4\n468 \tE480\tGet Key Skip if None\n46A \t1490\tKey goto 1490\n\n\n'
|
# https://www.codechef.com/problems/MISSP
for T in range(int(input())):
a=[]
for n in range(int(input())):
k=int(input())
if(k not in a): a.append(k)
else: a.remove(k)
print(a[0])
|
for t in range(int(input())):
a = []
for n in range(int(input())):
k = int(input())
if k not in a:
a.append(k)
else:
a.remove(k)
print(a[0])
|
"""
1. Clarification
2. Possible solutions
- Naive Approach
- String Concatenation
- Hash
3. Coding
4. Tests
"""
# T=O(n), S=O(1)
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for num in range(1, n + 1):
divisible_by_3 = (num % 3 == 0)
divisible_by_5 = (num % 5 == 0)
if divisible_by_3 and divisible_by_5:
ans.append("FizzBuzz")
elif divisible_by_3:
ans.append("Fizz")
elif divisible_by_5:
ans.append("Buzz")
else:
ans.append(str(num))
return ans
# T=O(n), S=O(1)
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for num in range(1, n + 1):
divisible_by_3 = (num % 3 == 0)
divisible_by_5 = (num % 5 == 0)
num_ans_str = ""
if divisible_by_3:
num_ans_str += "Fizz"
if divisible_by_5:
num_ans_str += "Buzz"
if not num_ans_str:
num_ans_str = str(num)
ans.append(num_ans_str)
return ans
# T=O(n), S=O(1)
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
fizz_buzz_dict = {3: "Fizz", 5: "Buzz"}
for num in range(1, n + 1):
num_ans_str = ""
for key in fizz_buzz_dict.keys():
if num % key == 0:
num_ans_str += fizz_buzz_dict[key]
if not num_ans_str:
num_ans_str = str(num)
ans.append(num_ans_str)
return ans
|
"""
1. Clarification
2. Possible solutions
- Naive Approach
- String Concatenation
- Hash
3. Coding
4. Tests
"""
class Solution:
def fizz_buzz(self, n: int) -> List[str]:
ans = []
for num in range(1, n + 1):
divisible_by_3 = num % 3 == 0
divisible_by_5 = num % 5 == 0
if divisible_by_3 and divisible_by_5:
ans.append('FizzBuzz')
elif divisible_by_3:
ans.append('Fizz')
elif divisible_by_5:
ans.append('Buzz')
else:
ans.append(str(num))
return ans
class Solution:
def fizz_buzz(self, n: int) -> List[str]:
ans = []
for num in range(1, n + 1):
divisible_by_3 = num % 3 == 0
divisible_by_5 = num % 5 == 0
num_ans_str = ''
if divisible_by_3:
num_ans_str += 'Fizz'
if divisible_by_5:
num_ans_str += 'Buzz'
if not num_ans_str:
num_ans_str = str(num)
ans.append(num_ans_str)
return ans
class Solution:
def fizz_buzz(self, n: int) -> List[str]:
ans = []
fizz_buzz_dict = {3: 'Fizz', 5: 'Buzz'}
for num in range(1, n + 1):
num_ans_str = ''
for key in fizz_buzz_dict.keys():
if num % key == 0:
num_ans_str += fizz_buzz_dict[key]
if not num_ans_str:
num_ans_str = str(num)
ans.append(num_ans_str)
return ans
|
def check_subtree(t2, t1):
if t1 is None or t2 is None:
return False
if t1.val == t2.val: # potential subtree
if subtree_equality(t2, t1):
return True
return check_subtree(t2, t1.left) or check_subtree(t2, t1.right)
def subtree_equality(t2, t1):
if t2 is None and t1 is None:
return True
if t1 is None or t2 is None:
return False
if t2.val == t1.val:
return subtree_equality(t2.left, t1.left) and subtree_equality(t2.right, t1.right)
return False
|
def check_subtree(t2, t1):
if t1 is None or t2 is None:
return False
if t1.val == t2.val:
if subtree_equality(t2, t1):
return True
return check_subtree(t2, t1.left) or check_subtree(t2, t1.right)
def subtree_equality(t2, t1):
if t2 is None and t1 is None:
return True
if t1 is None or t2 is None:
return False
if t2.val == t1.val:
return subtree_equality(t2.left, t1.left) and subtree_equality(t2.right, t1.right)
return False
|
# Sky Jewel box (2002016) | Treasure Room of Queen (926000010)
eleska = 3935
skyJewel = 4031574
reactor.incHitCount()
if reactor.getHitCount() >= 3:
if sm.hasQuest(eleska) and not sm.hasItem(skyJewel):
sm.dropItem(skyJewel, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY())
sm.removeReactor()
|
eleska = 3935
sky_jewel = 4031574
reactor.incHitCount()
if reactor.getHitCount() >= 3:
if sm.hasQuest(eleska) and (not sm.hasItem(skyJewel)):
sm.dropItem(skyJewel, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY())
sm.removeReactor()
|
a[-1]
a[-2:]
a[:-2]
a[::-1]
a[1::-1]
a[:-3:-1]
a[-3::-1]
point_coords = coords[i, :]
main(sys.argv[1:])
|
a[-1]
a[-2:]
a[:-2]
a[::-1]
a[1::-1]
a[:-3:-1]
a[-3::-1]
point_coords = coords[i, :]
main(sys.argv[1:])
|
'''
for a in range(3,1000):
for b in range(a+1,999):
csquared= a**2+b**2
c=csquared**0.5
if a+b+c==1000:
product= a*b*c
print(product)
print(c)
break
'''
def compute():
PERIMETER = 1000
for a in range(1, PERIMETER + 1):
for b in range(a + 1, PERIMETER + 1):
c = PERIMETER - a - b
if a * a + b * b == c * c:
# It is now implied that b < c, because we have a > 0
return str(a * b * c)
if __name__ == "__main__":
print(compute())
|
"""
for a in range(3,1000):
for b in range(a+1,999):
csquared= a**2+b**2
c=csquared**0.5
if a+b+c==1000:
product= a*b*c
print(product)
print(c)
break
"""
def compute():
perimeter = 1000
for a in range(1, PERIMETER + 1):
for b in range(a + 1, PERIMETER + 1):
c = PERIMETER - a - b
if a * a + b * b == c * c:
return str(a * b * c)
if __name__ == '__main__':
print(compute())
|
# Language: Python
# Level: 8kyu
# Name of Problem: DNA to RNA Conversion
# Instructions: Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems.
# It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T').
# Ribonucleic acid, RNA, is the primary messenger molecule in cells.
# RNA differs slightly from DNA its chemical structure and contains no Thymine.
# In RNA Thymine is replaced by another nucleic acid Uracil ('U').
# Create a function which translates a given DNA string into RNA.
# The input string can be of arbitrary length - in particular, it may be empty.
# All input is guaranteed to be valid, i.e. each input string will only ever consist of 'G', 'C', 'A' and/or 'T'.
# Example:
# DNAtoRNA("GCAT") returns ("GCAU")
# Solution 1:
def DNAtoRNA(dna):
return dna.replace('T', 'U')
# Sample Tests Passed:
# test.assert_equals(DNAtoRNA("TTTT"), "UUUU")
# test.assert_equals(DNAtoRNA("GCAT"), "GCAU")
# test.assert_equals(DNAtoRNA("GACCGCCGCC"), "GACCGCCGCC")
|
def dn_ato_rna(dna):
return dna.replace('T', 'U')
|
data = (
'Kay ', # 0x00
'Kayng ', # 0x01
'Ke ', # 0x02
'Ko ', # 0x03
'Kol ', # 0x04
'Koc ', # 0x05
'Kwi ', # 0x06
'Kwi ', # 0x07
'Kyun ', # 0x08
'Kul ', # 0x09
'Kum ', # 0x0a
'Na ', # 0x0b
'Na ', # 0x0c
'Na ', # 0x0d
'La ', # 0x0e
'Na ', # 0x0f
'Na ', # 0x10
'Na ', # 0x11
'Na ', # 0x12
'Na ', # 0x13
'Nak ', # 0x14
'Nak ', # 0x15
'Nak ', # 0x16
'Nak ', # 0x17
'Nak ', # 0x18
'Nak ', # 0x19
'Nak ', # 0x1a
'Nan ', # 0x1b
'Nan ', # 0x1c
'Nan ', # 0x1d
'Nan ', # 0x1e
'Nan ', # 0x1f
'Nan ', # 0x20
'Nam ', # 0x21
'Nam ', # 0x22
'Nam ', # 0x23
'Nam ', # 0x24
'Nap ', # 0x25
'Nap ', # 0x26
'Nap ', # 0x27
'Nang ', # 0x28
'Nang ', # 0x29
'Nang ', # 0x2a
'Nang ', # 0x2b
'Nang ', # 0x2c
'Nay ', # 0x2d
'Nayng ', # 0x2e
'No ', # 0x2f
'No ', # 0x30
'No ', # 0x31
'No ', # 0x32
'No ', # 0x33
'No ', # 0x34
'No ', # 0x35
'No ', # 0x36
'No ', # 0x37
'No ', # 0x38
'No ', # 0x39
'No ', # 0x3a
'Nok ', # 0x3b
'Nok ', # 0x3c
'Nok ', # 0x3d
'Nok ', # 0x3e
'Nok ', # 0x3f
'Nok ', # 0x40
'Non ', # 0x41
'Nong ', # 0x42
'Nong ', # 0x43
'Nong ', # 0x44
'Nong ', # 0x45
'Noy ', # 0x46
'Noy ', # 0x47
'Noy ', # 0x48
'Noy ', # 0x49
'Nwu ', # 0x4a
'Nwu ', # 0x4b
'Nwu ', # 0x4c
'Nwu ', # 0x4d
'Nwu ', # 0x4e
'Nwu ', # 0x4f
'Nwu ', # 0x50
'Nwu ', # 0x51
'Nuk ', # 0x52
'Nuk ', # 0x53
'Num ', # 0x54
'Nung ', # 0x55
'Nung ', # 0x56
'Nung ', # 0x57
'Nung ', # 0x58
'Nung ', # 0x59
'Twu ', # 0x5a
'La ', # 0x5b
'Lak ', # 0x5c
'Lak ', # 0x5d
'Lan ', # 0x5e
'Lyeng ', # 0x5f
'Lo ', # 0x60
'Lyul ', # 0x61
'Li ', # 0x62
'Pey ', # 0x63
'Pen ', # 0x64
'Pyen ', # 0x65
'Pwu ', # 0x66
'Pwul ', # 0x67
'Pi ', # 0x68
'Sak ', # 0x69
'Sak ', # 0x6a
'Sam ', # 0x6b
'Sayk ', # 0x6c
'Sayng ', # 0x6d
'Sep ', # 0x6e
'Sey ', # 0x6f
'Sway ', # 0x70
'Sin ', # 0x71
'Sim ', # 0x72
'Sip ', # 0x73
'Ya ', # 0x74
'Yak ', # 0x75
'Yak ', # 0x76
'Yang ', # 0x77
'Yang ', # 0x78
'Yang ', # 0x79
'Yang ', # 0x7a
'Yang ', # 0x7b
'Yang ', # 0x7c
'Yang ', # 0x7d
'Yang ', # 0x7e
'Ye ', # 0x7f
'Ye ', # 0x80
'Ye ', # 0x81
'Ye ', # 0x82
'Ye ', # 0x83
'Ye ', # 0x84
'Ye ', # 0x85
'Ye ', # 0x86
'Ye ', # 0x87
'Ye ', # 0x88
'Ye ', # 0x89
'Yek ', # 0x8a
'Yek ', # 0x8b
'Yek ', # 0x8c
'Yek ', # 0x8d
'Yen ', # 0x8e
'Yen ', # 0x8f
'Yen ', # 0x90
'Yen ', # 0x91
'Yen ', # 0x92
'Yen ', # 0x93
'Yen ', # 0x94
'Yen ', # 0x95
'Yen ', # 0x96
'Yen ', # 0x97
'Yen ', # 0x98
'Yen ', # 0x99
'Yen ', # 0x9a
'Yen ', # 0x9b
'Yel ', # 0x9c
'Yel ', # 0x9d
'Yel ', # 0x9e
'Yel ', # 0x9f
'Yel ', # 0xa0
'Yel ', # 0xa1
'Yem ', # 0xa2
'Yem ', # 0xa3
'Yem ', # 0xa4
'Yem ', # 0xa5
'Yem ', # 0xa6
'Yep ', # 0xa7
'Yeng ', # 0xa8
'Yeng ', # 0xa9
'Yeng ', # 0xaa
'Yeng ', # 0xab
'Yeng ', # 0xac
'Yeng ', # 0xad
'Yeng ', # 0xae
'Yeng ', # 0xaf
'Yeng ', # 0xb0
'Yeng ', # 0xb1
'Yeng ', # 0xb2
'Yeng ', # 0xb3
'Yeng ', # 0xb4
'Yey ', # 0xb5
'Yey ', # 0xb6
'Yey ', # 0xb7
'Yey ', # 0xb8
'O ', # 0xb9
'Yo ', # 0xba
'Yo ', # 0xbb
'Yo ', # 0xbc
'Yo ', # 0xbd
'Yo ', # 0xbe
'Yo ', # 0xbf
'Yo ', # 0xc0
'Yo ', # 0xc1
'Yo ', # 0xc2
'Yo ', # 0xc3
'Yong ', # 0xc4
'Wun ', # 0xc5
'Wen ', # 0xc6
'Yu ', # 0xc7
'Yu ', # 0xc8
'Yu ', # 0xc9
'Yu ', # 0xca
'Yu ', # 0xcb
'Yu ', # 0xcc
'Yu ', # 0xcd
'Yu ', # 0xce
'Yu ', # 0xcf
'Yu ', # 0xd0
'Yuk ', # 0xd1
'Yuk ', # 0xd2
'Yuk ', # 0xd3
'Yun ', # 0xd4
'Yun ', # 0xd5
'Yun ', # 0xd6
'Yun ', # 0xd7
'Yul ', # 0xd8
'Yul ', # 0xd9
'Yul ', # 0xda
'Yul ', # 0xdb
'Yung ', # 0xdc
'I ', # 0xdd
'I ', # 0xde
'I ', # 0xdf
'I ', # 0xe0
'I ', # 0xe1
'I ', # 0xe2
'I ', # 0xe3
'I ', # 0xe4
'I ', # 0xe5
'I ', # 0xe6
'I ', # 0xe7
'I ', # 0xe8
'I ', # 0xe9
'I ', # 0xea
'Ik ', # 0xeb
'Ik ', # 0xec
'In ', # 0xed
'In ', # 0xee
'In ', # 0xef
'In ', # 0xf0
'In ', # 0xf1
'In ', # 0xf2
'In ', # 0xf3
'Im ', # 0xf4
'Im ', # 0xf5
'Im ', # 0xf6
'Ip ', # 0xf7
'Ip ', # 0xf8
'Ip ', # 0xf9
'Cang ', # 0xfa
'Cek ', # 0xfb
'Ci ', # 0xfc
'Cip ', # 0xfd
'Cha ', # 0xfe
'Chek ', # 0xff
)
|
data = ('Kay ', 'Kayng ', 'Ke ', 'Ko ', 'Kol ', 'Koc ', 'Kwi ', 'Kwi ', 'Kyun ', 'Kul ', 'Kum ', 'Na ', 'Na ', 'Na ', 'La ', 'Na ', 'Na ', 'Na ', 'Na ', 'Na ', 'Nak ', 'Nak ', 'Nak ', 'Nak ', 'Nak ', 'Nak ', 'Nak ', 'Nan ', 'Nan ', 'Nan ', 'Nan ', 'Nan ', 'Nan ', 'Nam ', 'Nam ', 'Nam ', 'Nam ', 'Nap ', 'Nap ', 'Nap ', 'Nang ', 'Nang ', 'Nang ', 'Nang ', 'Nang ', 'Nay ', 'Nayng ', 'No ', 'No ', 'No ', 'No ', 'No ', 'No ', 'No ', 'No ', 'No ', 'No ', 'No ', 'No ', 'Nok ', 'Nok ', 'Nok ', 'Nok ', 'Nok ', 'Nok ', 'Non ', 'Nong ', 'Nong ', 'Nong ', 'Nong ', 'Noy ', 'Noy ', 'Noy ', 'Noy ', 'Nwu ', 'Nwu ', 'Nwu ', 'Nwu ', 'Nwu ', 'Nwu ', 'Nwu ', 'Nwu ', 'Nuk ', 'Nuk ', 'Num ', 'Nung ', 'Nung ', 'Nung ', 'Nung ', 'Nung ', 'Twu ', 'La ', 'Lak ', 'Lak ', 'Lan ', 'Lyeng ', 'Lo ', 'Lyul ', 'Li ', 'Pey ', 'Pen ', 'Pyen ', 'Pwu ', 'Pwul ', 'Pi ', 'Sak ', 'Sak ', 'Sam ', 'Sayk ', 'Sayng ', 'Sep ', 'Sey ', 'Sway ', 'Sin ', 'Sim ', 'Sip ', 'Ya ', 'Yak ', 'Yak ', 'Yang ', 'Yang ', 'Yang ', 'Yang ', 'Yang ', 'Yang ', 'Yang ', 'Yang ', 'Ye ', 'Ye ', 'Ye ', 'Ye ', 'Ye ', 'Ye ', 'Ye ', 'Ye ', 'Ye ', 'Ye ', 'Ye ', 'Yek ', 'Yek ', 'Yek ', 'Yek ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yen ', 'Yel ', 'Yel ', 'Yel ', 'Yel ', 'Yel ', 'Yel ', 'Yem ', 'Yem ', 'Yem ', 'Yem ', 'Yem ', 'Yep ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yeng ', 'Yey ', 'Yey ', 'Yey ', 'Yey ', 'O ', 'Yo ', 'Yo ', 'Yo ', 'Yo ', 'Yo ', 'Yo ', 'Yo ', 'Yo ', 'Yo ', 'Yo ', 'Yong ', 'Wun ', 'Wen ', 'Yu ', 'Yu ', 'Yu ', 'Yu ', 'Yu ', 'Yu ', 'Yu ', 'Yu ', 'Yu ', 'Yu ', 'Yuk ', 'Yuk ', 'Yuk ', 'Yun ', 'Yun ', 'Yun ', 'Yun ', 'Yul ', 'Yul ', 'Yul ', 'Yul ', 'Yung ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'I ', 'Ik ', 'Ik ', 'In ', 'In ', 'In ', 'In ', 'In ', 'In ', 'In ', 'Im ', 'Im ', 'Im ', 'Ip ', 'Ip ', 'Ip ', 'Cang ', 'Cek ', 'Ci ', 'Cip ', 'Cha ', 'Chek ')
|
class Sol(object):
def __init__(self):
self.suc = None
def in_order(self, head, num):
if not head:
return None
int = []
def helper(head):
nonlocal int
if head:
self.helper(head.left)
int.append(head.val)
self.helper(head.right)
helper(head)
if num in int:
return int[int.index(num)+1]
|
class Sol(object):
def __init__(self):
self.suc = None
def in_order(self, head, num):
if not head:
return None
int = []
def helper(head):
nonlocal int
if head:
self.helper(head.left)
int.append(head.val)
self.helper(head.right)
helper(head)
if num in int:
return int[int.index(num) + 1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.