content
stringlengths
7
1.05M
def jogar(): print("################################") print("###Bem Vindo ao jogo da forca###") print("################################") palavra_secreta = "luna" enforcou = False acertou = False while(not enforcou and not acertou): #Enquanto (nao enforcou e nao acertou) chute = input("Qual é a letra") print("Continue jogando...") if(__name__ == "__main__"): jogar()
result = '' for line in DATA: result += line + '\n'
# -*- coding: utf-8 -*- """ Model object specification and validation. """
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: dp = [[0] * len(matrix[0]) for i in range(len(matrix))] for row_i, row in enumerate(matrix): for col_i, col in enumerate(row): if col == "0": dp[row_i][col_i] = 0 else: dp[row_i][col_i] = self.find(col_i, row) mx = 0 print(dp) for i in range(len(dp)): for j in range(len(dp[i])): mx = max(mx, self.search(dp, i, j)) return mx def search(self, dp, start_row, start_col): start, up, down = dp[start_row][start_col], 0, 0 if start_row > 0: for i in range(start_row - 1, -1, -1): if start <= dp[i][start_col]: up += 1 else: break if start_row < len(dp) - 1: for i in range(start_row + 1, len(dp)): if start <= dp[i][start_col]: down += 1 else: break return start * (up + down + 1) def find(self, index, row): count = 0 for i in range(index, len(row)): if row[i] == "0": break count += 1 return count
# variables 4 a = "abc" b = 1 c = 1.5 d = True e = 3 + 5j print("a:", type(a), "b", type(b), "c:", type(c), "d:", type(d), "e:", type(e))
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold(x1, y1, x2, y2, r1, r2): distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) radSumSq = (r1 + r2) * (r1 + r2) if (distSq == radSumSq): return 1 elif (distSq > radSumSq): return - 1 else: return 0 #TOFILL if __name__ == '__main__': param = [ (11, 36, 62, 64, 50, 4,), (87, 1, 62, 64, 54, 41,), (51, 1, 47, 90, 14, 71,), (89, 67, 9, 52, 94, 21,), (64, 10, 79, 45, 67, 78,), (57, 86, 99, 43, 83, 63,), (65, 90, 42, 82, 77, 32,), (32, 23, 28, 26, 60, 45,), (73, 61, 63, 77, 92, 76,), (3, 99, 6, 19, 21, 28,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print("#Results: %i, %i" % (n_success, len(param)))
#!/usr/bin/env python # Task 1 instructions = list() with open("./dec_2/dec2_input.txt") as f: instructions = [x for x in f.read().split('\n')] start_position = [0, 0] for direction in instructions: info = direction.split(' ') vector, length = info[0], int(info[1]) if vector == "forward": start_position[0] += length elif vector == "up": start_position[1] -= length elif vector == "down": start_position[1] += length print(start_position[0] * start_position[1]) # Task 2 start_position = [0, 0, 0] for direction in instructions: info = direction.split(' ') vector, length = info[0], int(info[1]) if vector == "forward": start_position[0] += length start_position[1] += length * start_position[2] elif vector == "up": start_position[2] -= length elif vector == "down": start_position[2] += length print(info, start_position) print(start_position[0] * start_position[1])
a = input() s = [int(x) for x in input().split()] buff = 0 load = False for num in s: if num - buff < 0: load = True if num - buff >= 30: print(buff+30) break else: if load: buff += 5 load = False else: buff = num + 5 else: print(buff+30)
"""File IO.""" def re_readable_read(file): """Read file and reset cursor/pointer to allow fast, simple re-read. Side Effects: Mutates file stream object passed as argument by moving cursor/pointer from from position at start of function call and setting it to position '0'. If file stream has not been read before calling this function, there will be no effective change. Returns: str: Contents of read file. """ file_contents = file.read() file.seek(0) return file_contents def open_and_read(file): """Alias: read_contents""" read_contents(file) def read_contents(file): """Open file and read it. Returns: str: File contents. """ # with open(file, 'r') as stream: # return re_readable_read(stream) # return re_readable_read(open(file, 'r')) return open(file, 'r').read()
class OmnipyConfiguration(object): def __init__(self): self.mqtt_host = "" self.mqtt_port = 1883 self.mqtt_clientid = "" self.mqtt_command_topic = "" self.mqtt_response_topic = "" self.mqtt_rate_topic = ""
def solution(N): num = bin(N)[2:].split('1') if len(num[1:-1]) == 0: return 0 return len(max(num[1:-1], key=lambda x: len(x)))
a = int(input()) b = int ( input ( ) ) a = int(input())
class Solution(object): def shuffle(self, nums, n): """ :type nums: List[int] :type n: int :rtype: List[int] """ shuffled_array = [] for i in range(0, n): shuffled_array.append(nums[i]) shuffled_array.append(nums[i+n]) return shuffled_array s = Solution() print("Solution 1 :", s.shuffle([2, 5, 1, 3, 4, 7], 3)) print("Solution 2 :", s.shuffle([1, 2, 3, 4, 4, 3, 2, 1], 4)) print("Solution 1 :", s.shuffle([1, 1, 2, 2], 2))
word = 'Python' word[0] = 'M'
#Operator Name Example # > Greater than x > y x = 5 y = 3 print(x > y) # true
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( x , y , z ) : c = 0 while ( x and y and z ) : x = x - 1 y = y - 1 z = z - 1 c = c + 1 return c #TOFILL if __name__ == '__main__': param = [ (23,98,25,), (87,55,94,), (35,90,29,), (25,9,41,), (93,22,39,), (52,42,96,), (95,88,26,), (91,64,51,), (75,1,6,), (96,44,76,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
# Voting with delegation. # Information about voters voters: public({ # weight is accumulated by delegation weight: num, # if true, that person already voted voted: bool, # person delegated to delegate: address, # index of the voted proposal vote: num }[address]) # This is a type for a list of proposals. proposals: public({ # short name (up to 32 bytes) name: bytes32, # number of accumulated votes vote_count: num }[num]) voter_count: public(num) chairperson: public(address) # Setup global variables def __init__(_proposalNames: bytes32[5]): self.chairperson = msg.sender self.voter_count = 0 for i in range(5): self.proposals[i] = { name: _proposalNames[i], vote_count: 0 } # Give `voter` the right to vote on this ballot. # May only be called by `chairperson`. def give_right_to_vote(voter: address): # Throws if sender is not chairpers assert msg.sender == self.chairperson # Throws if voter has already voted assert not self.voters[voter].voted # Throws if voters voting weight isn't 0 assert self.voters[voter].weight == 0 self.voters[voter].weight = 1 self.voter_count += 1 # Delegate your vote to the voter `to`. def delegate(_to: address): to = _to # Throws if sender has already voted assert not self.voters[msg.sender].voted # Throws if sender tries to delegate their vote to themselves assert not msg.sender == to # loop can delegate votes up to the current voter count for i in range(self.voter_count, self.voter_count+1): if self.voters[to].delegate: # Because there are not while loops, use recursion to forward the delegation # self.delegate(self.voters[to].delegate) assert self.voters[to].delegate != msg.sender to = self.voters[to].delegate self.voters[msg.sender].voted = True self.voters[msg.sender].delegate = to if self.voters[to].voted: # If the delegate already voted, # directly add to the number of votes self.proposals[self.voters[to].vote].vote_count += self.voters[msg.sender].weight else: # If the delegate did not vote yet, # add to her weight. self.voters[to].weight += self.voters[msg.sender].weight # Give your vote (including votes delegated to you) # to proposal `proposals[proposal].name`. def vote(proposal: num): assert not self.voters[msg.sender].voted self.voters[msg.sender].voted = True self.voters[msg.sender].vote = proposal # If `proposal` is out of the range of the array, # this will throw automatically and revert all # changes. self.proposals[proposal].vote_count += self.voters[msg.sender].weight # Computes the winning proposal taking all # previous votes into account. @constant def winning_proposal() -> num: winning_vote_count = 0 for i in range(5): if self.proposals[i].vote_count > winning_vote_count: winning_vote_count = self.proposals[i].vote_count winning_proposal = i return winning_proposal # Calls winning_proposal() function to get the index # of the winner contained in the proposals array and then # returns the name of the winner @constant def winner_name() -> bytes32: return self.proposals[self.winning_proposal()].name
load( "@com_googlesource_gerrit_bazlets//tools:junit.bzl", "junit_tests", ) def tests(tests): for src in tests: name = src[len("tst/"):len(src) - len(".java")].replace("/", "_") labels = [] timeout = "moderate" if name.startswith("org_eclipse_jgit_"): package = name[len("org.eclipse.jgit_"):] if package.startswith("internal_storage_"): package = package[len("internal.storage_"):] index = package.find("_") if index > 0: labels.append(package[:index]) else: labels.append(index) if "lib" not in labels: labels.append("lib") # TODO(http://eclip.se/534285): Make this test pass reliably # and remove the flaky attribute. flaky = src.endswith("CrissCrossMergeTest.java") additional_deps = [] if src.endswith("RootLocaleTest.java"): additional_deps = [ "//org.eclipse.jgit.pgm:pgm", "//org.eclipse.jgit.ui:ui", ] if src.endswith("WalkEncryptionTest.java"): additional_deps = [ "//org.eclipse.jgit:insecure_cipher_factory", ] if src.endswith("OpenSshConfigTest.java"): additional_deps = [ "//lib:jsch", ] if src.endswith("JschConfigSessionFactoryTest.java"): additional_deps = [ "//lib:jsch", ] if src.endswith("ArchiveCommandTest.java"): additional_deps = [ "//lib:commons-compress", "//lib:xz", "//org.eclipse.jgit.archive:jgit-archive", ] heap_size = "-Xmx256m" if src.endswith("HugeCommitMessageTest.java"): heap_size = "-Xmx512m" if src.endswith("EolRepositoryTest.java") or src.endswith("GcCommitSelectionTest.java"): timeout = "long" junit_tests( name = name, tags = labels, srcs = [src], deps = additional_deps + [ ":helpers", ":tst_rsrc", "//lib:javaewah", "//lib:junit", "//lib:slf4j-api", "//org.eclipse.jgit:jgit", "//org.eclipse.jgit.junit:junit", "//org.eclipse.jgit.lfs:jgit-lfs", ], flaky = flaky, jvm_flags = [heap_size, "-Dfile.encoding=UTF-8"], timeout = timeout, )
class Hero: """ kahramanların tanımlanabileceği bir yapı oluşturun parametre olarak adi,guc,saglik darbe,vurma adında iki fonksiyon ile secilen karakterin güçleri ölçüsünde diğer karakterin sağlığında eksiltmesini sağlayalım istenildiğinde tek bir fonksiyon ile karakterin durumunu görebilelim """ def __init__(self, name, power, health): self.name = name self.power = power self.health = health def __repr__(self): return self.name + "Health" + str(self.health) def darbe(self): self.health -= self.power * 0.2 def vurma(self): self.health -= self.power * 0.1
#Exam def solution(N): if (N > 0) and (N < 1000): #Assume that N is an integer within 1 to 1000 list_of_coded_numbers = [] #List will contain the coded numbers in descending order while N > 0: if (N % 2 == 0) and (N % 3 == 0) and (N % 5 == 0): list_of_coded_numbers.append("CodilityTestCoders") elif (N % 3 == 0) and (N % 5 == 0): list_of_coded_numbers.append("TestCoders") elif (N % 2 == 0) and (N % 5 == 0): list_of_coded_numbers.append("CodilityCoders") elif (N % 2 == 0) and (N % 3 == 0): list_of_coded_numbers.append("CodilityTest") elif (N % 5 == 0): list_of_coded_numbers.append("Coders") elif (N % 3 == 0): list_of_coded_numbers.append("Test") elif (N % 2 == 0): list_of_coded_numbers.append("Codility") else: list_of_coded_numbers.append(N) N -= 1 list_of_coded_numbers.reverse() #Arrange the coded numbers in ascending order for coded_number in list_of_coded_numbers:# Print the coded numbers in each line print(coded_number) if __name__ == '__main__': solution(110)
# # This file is part of stac2odc # Copyright (C) 2020 INPE. # # stac2odc is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # __version__ = '0.0.1'
""" LINK: https://leetcode.com/problems/power-of-three/ Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x. Example 1: Input: n = 27 Output: true Example 2: Input: n = 0 Output: false Example 3: Input: n = 9 Output: true Example 4: Input: n = 45 Output: false Constraints: -231 <= n <= 231 - 1 Follow up: Could you do it without using any loop / recursion? """ def isPowerOfThree(n): if not n: return False while not n%3: n /= 3 return n==1 def isPowerOfThree_recursive(n): if not n: return False elif n==1: return True elif not n%3: return isPowerOfThree_recursive(n/3) return False
str = 'X-DSPAM-Confidence:0.8475' print(str) colon = str.find(":") fnum = float(str[colon+1:]) print("Number from string equals:", fnum)
# Python > Strings > String Validators # Identify the presence of alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters in a string. # # https://www.hackerrank.com/challenges/string-validators/problem # if __name__ == '__main__': s = input() # any alphanumeric characters print(any(c.isalnum() for c in s)) # any alphabetical characters print(any(c.isalpha() for c in s)) # any digits print(any(c.isdigit() for c in s)) # any lowercase characters print(any(c.islower() for c in s)) # any uppercase characters print(any(c.isupper() for c in s))
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ a=input() print(a[0].upper()+a[1:])
DOMAIN = "airthings" KEY_API = "api" PLATFORMS = ("sensor",) ERROR_LOGIN_FAILED = "login_failed"
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' def associate_customer_gateway(CustomerGatewayArn=None, GlobalNetworkId=None, DeviceId=None, LinkId=None): """ Associates a customer gateway with a device and optionally, with a link. If you specify a link, it must be associated with the specified device. You can only associate customer gateways that are connected to a VPN attachment on a transit gateway. The transit gateway must be registered in your global network. When you register a transit gateway, customer gateways that are connected to the transit gateway are automatically included in the global network. To list customer gateways that are connected to a transit gateway, use the DescribeVpnConnections EC2 API and filter by transit-gateway-id . You cannot associate a customer gateway with more than one device and link. See also: AWS API Documentation Exceptions :example: response = client.associate_customer_gateway( CustomerGatewayArn='string', GlobalNetworkId='string', DeviceId='string', LinkId='string' ) :type CustomerGatewayArn: string :param CustomerGatewayArn: [REQUIRED]\nThe Amazon Resource Name (ARN) of the customer gateway. For more information, see Resources Defined by Amazon EC2 .\n :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type DeviceId: string :param DeviceId: [REQUIRED]\nThe ID of the device.\n :type LinkId: string :param LinkId: The ID of the link. :rtype: dict ReturnsResponse Syntax { 'CustomerGatewayAssociation': { 'CustomerGatewayArn': 'string', 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' } } Response Structure (dict) -- CustomerGatewayAssociation (dict) -- The customer gateway association. CustomerGatewayArn (string) -- The Amazon Resource Name (ARN) of the customer gateway. GlobalNetworkId (string) -- The ID of the global network. DeviceId (string) -- The ID of the device. LinkId (string) -- The ID of the link. State (string) -- The association state. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'CustomerGatewayAssociation': { 'CustomerGatewayArn': 'string', 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def associate_link(GlobalNetworkId=None, DeviceId=None, LinkId=None): """ Associates a link to a device. A device can be associated to multiple links and a link can be associated to multiple devices. The device and link must be in the same global network and the same site. See also: AWS API Documentation Exceptions :example: response = client.associate_link( GlobalNetworkId='string', DeviceId='string', LinkId='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type DeviceId: string :param DeviceId: [REQUIRED]\nThe ID of the device.\n :type LinkId: string :param LinkId: [REQUIRED]\nThe ID of the link.\n :rtype: dict ReturnsResponse Syntax { 'LinkAssociation': { 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'LinkAssociationState': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' } } Response Structure (dict) -- LinkAssociation (dict) -- The link association. GlobalNetworkId (string) -- The ID of the global network. DeviceId (string) -- The device ID for the link association. LinkId (string) -- The ID of the link. LinkAssociationState (string) -- The state of the association. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'LinkAssociation': { 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'LinkAssociationState': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def can_paginate(operation_name=None): """ Check if an operation can be paginated. :type operation_name: string :param operation_name: The operation name. This is the same name\nas the method name on the client. For example, if the\nmethod name is create_foo, and you\'d normally invoke the\noperation as client.create_foo(**kwargs), if the\ncreate_foo operation can be paginated, you can use the\ncall client.get_paginator('create_foo'). """ pass def create_device(GlobalNetworkId=None, Description=None, Type=None, Vendor=None, Model=None, SerialNumber=None, Location=None, SiteId=None, Tags=None): """ Creates a new device in a global network. If you specify both a site ID and a location, the location of the site is used for visualization in the Network Manager console. See also: AWS API Documentation Exceptions :example: response = client.create_device( GlobalNetworkId='string', Description='string', Type='string', Vendor='string', Model='string', SerialNumber='string', Location={ 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, SiteId='string', Tags=[ { 'Key': 'string', 'Value': 'string' }, ] ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type Description: string :param Description: A description of the device.\nLength Constraints: Maximum length of 256 characters.\n :type Type: string :param Type: The type of the device. :type Vendor: string :param Vendor: The vendor of the device.\nLength Constraints: Maximum length of 128 characters.\n :type Model: string :param Model: The model of the device.\nLength Constraints: Maximum length of 128 characters.\n :type SerialNumber: string :param SerialNumber: The serial number of the device.\nLength Constraints: Maximum length of 128 characters.\n :type Location: dict :param Location: The location of the device.\n\nAddress (string) --The physical address.\n\nLatitude (string) --The latitude.\n\nLongitude (string) --The longitude.\n\n\n :type SiteId: string :param SiteId: The ID of the site. :type Tags: list :param Tags: The tags to apply to the resource during creation.\n\n(dict) --Describes a tag.\n\nKey (string) --The tag key.\nLength Constraints: Maximum length of 128 characters.\n\nValue (string) --The tag value.\nLength Constraints: Maximum length of 256 characters.\n\n\n\n\n :rtype: dict ReturnsResponse Syntax { 'Device': { 'DeviceId': 'string', 'DeviceArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Type': 'string', 'Vendor': 'string', 'Model': 'string', 'SerialNumber': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'SiteId': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Device (dict) -- Information about the device. DeviceId (string) -- The ID of the device. DeviceArn (string) -- The Amazon Resource Name (ARN) of the device. GlobalNetworkId (string) -- The ID of the global network. Description (string) -- The description of the device. Type (string) -- The device type. Vendor (string) -- The device vendor. Model (string) -- The device model. SerialNumber (string) -- The device serial number. Location (dict) -- The site location. Address (string) -- The physical address. Latitude (string) -- The latitude. Longitude (string) -- The longitude. SiteId (string) -- The site ID. CreatedAt (datetime) -- The date and time that the site was created. State (string) -- The device state. Tags (list) -- The tags for the device. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Device': { 'DeviceId': 'string', 'DeviceArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Type': 'string', 'Vendor': 'string', 'Model': 'string', 'SerialNumber': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'SiteId': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def create_global_network(Description=None, Tags=None): """ Creates a new, empty global network. See also: AWS API Documentation Exceptions :example: response = client.create_global_network( Description='string', Tags=[ { 'Key': 'string', 'Value': 'string' }, ] ) :type Description: string :param Description: A description of the global network.\nLength Constraints: Maximum length of 256 characters.\n :type Tags: list :param Tags: The tags to apply to the resource during creation.\n\n(dict) --Describes a tag.\n\nKey (string) --The tag key.\nLength Constraints: Maximum length of 128 characters.\n\nValue (string) --The tag value.\nLength Constraints: Maximum length of 256 characters.\n\n\n\n\n :rtype: dict ReturnsResponse Syntax { 'GlobalNetwork': { 'GlobalNetworkId': 'string', 'GlobalNetworkArn': 'string', 'Description': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- GlobalNetwork (dict) -- Information about the global network object. GlobalNetworkId (string) -- The ID of the global network. GlobalNetworkArn (string) -- The Amazon Resource Name (ARN) of the global network. Description (string) -- The description of the global network. CreatedAt (datetime) -- The date and time that the global network was created. State (string) -- The state of the global network. Tags (list) -- The tags for the global network. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'GlobalNetwork': { 'GlobalNetworkId': 'string', 'GlobalNetworkArn': 'string', 'Description': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def create_link(GlobalNetworkId=None, Description=None, Type=None, Bandwidth=None, Provider=None, SiteId=None, Tags=None): """ Creates a new link for a specified site. See also: AWS API Documentation Exceptions :example: response = client.create_link( GlobalNetworkId='string', Description='string', Type='string', Bandwidth={ 'UploadSpeed': 123, 'DownloadSpeed': 123 }, Provider='string', SiteId='string', Tags=[ { 'Key': 'string', 'Value': 'string' }, ] ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type Description: string :param Description: A description of the link.\nLength Constraints: Maximum length of 256 characters.\n :type Type: string :param Type: The type of the link.\nConstraints: Cannot include the following characters: | ^\nLength Constraints: Maximum length of 128 characters.\n :type Bandwidth: dict :param Bandwidth: [REQUIRED]\nThe upload speed and download speed in Mbps.\n\nUploadSpeed (integer) --Upload speed in Mbps.\n\nDownloadSpeed (integer) --Download speed in Mbps.\n\n\n :type Provider: string :param Provider: The provider of the link.\nConstraints: Cannot include the following characters: | ^\nLength Constraints: Maximum length of 128 characters.\n :type SiteId: string :param SiteId: [REQUIRED]\nThe ID of the site.\n :type Tags: list :param Tags: The tags to apply to the resource during creation.\n\n(dict) --Describes a tag.\n\nKey (string) --The tag key.\nLength Constraints: Maximum length of 128 characters.\n\nValue (string) --The tag value.\nLength Constraints: Maximum length of 256 characters.\n\n\n\n\n :rtype: dict ReturnsResponse Syntax { 'Link': { 'LinkId': 'string', 'LinkArn': 'string', 'GlobalNetworkId': 'string', 'SiteId': 'string', 'Description': 'string', 'Type': 'string', 'Bandwidth': { 'UploadSpeed': 123, 'DownloadSpeed': 123 }, 'Provider': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Link (dict) -- Information about the link. LinkId (string) -- The ID of the link. LinkArn (string) -- The Amazon Resource Name (ARN) of the link. GlobalNetworkId (string) -- The ID of the global network. SiteId (string) -- The ID of the site. Description (string) -- The description of the link. Type (string) -- The type of the link. Bandwidth (dict) -- The bandwidth for the link. UploadSpeed (integer) -- Upload speed in Mbps. DownloadSpeed (integer) -- Download speed in Mbps. Provider (string) -- The provider of the link. CreatedAt (datetime) -- The date and time that the link was created. State (string) -- The state of the link. Tags (list) -- The tags for the link. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Link': { 'LinkId': 'string', 'LinkArn': 'string', 'GlobalNetworkId': 'string', 'SiteId': 'string', 'Description': 'string', 'Type': 'string', 'Bandwidth': { 'UploadSpeed': 123, 'DownloadSpeed': 123 }, 'Provider': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def create_site(GlobalNetworkId=None, Description=None, Location=None, Tags=None): """ Creates a new site in a global network. See also: AWS API Documentation Exceptions :example: response = client.create_site( GlobalNetworkId='string', Description='string', Location={ 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, Tags=[ { 'Key': 'string', 'Value': 'string' }, ] ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type Description: string :param Description: A description of your site.\nLength Constraints: Maximum length of 256 characters.\n :type Location: dict :param Location: The site location. This information is used for visualization in the Network Manager console. If you specify the address, the latitude and longitude are automatically calculated.\n\nAddress : The physical address of the site.\nLatitude : The latitude of the site.\nLongitude : The longitude of the site.\n\n\nAddress (string) --The physical address.\n\nLatitude (string) --The latitude.\n\nLongitude (string) --The longitude.\n\n\n :type Tags: list :param Tags: The tags to apply to the resource during creation.\n\n(dict) --Describes a tag.\n\nKey (string) --The tag key.\nLength Constraints: Maximum length of 128 characters.\n\nValue (string) --The tag value.\nLength Constraints: Maximum length of 256 characters.\n\n\n\n\n :rtype: dict ReturnsResponse Syntax { 'Site': { 'SiteId': 'string', 'SiteArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Site (dict) -- Information about the site. SiteId (string) -- The ID of the site. SiteArn (string) -- The Amazon Resource Name (ARN) of the site. GlobalNetworkId (string) -- The ID of the global network. Description (string) -- The description of the site. Location (dict) -- The location of the site. Address (string) -- The physical address. Latitude (string) -- The latitude. Longitude (string) -- The longitude. CreatedAt (datetime) -- The date and time that the site was created. State (string) -- The state of the site. Tags (list) -- The tags for the site. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Site': { 'SiteId': 'string', 'SiteArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def delete_device(GlobalNetworkId=None, DeviceId=None): """ Deletes an existing device. You must first disassociate the device from any links and customer gateways. See also: AWS API Documentation Exceptions :example: response = client.delete_device( GlobalNetworkId='string', DeviceId='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type DeviceId: string :param DeviceId: [REQUIRED]\nThe ID of the device.\n :rtype: dict ReturnsResponse Syntax { 'Device': { 'DeviceId': 'string', 'DeviceArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Type': 'string', 'Vendor': 'string', 'Model': 'string', 'SerialNumber': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'SiteId': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Device (dict) -- Information about the device. DeviceId (string) -- The ID of the device. DeviceArn (string) -- The Amazon Resource Name (ARN) of the device. GlobalNetworkId (string) -- The ID of the global network. Description (string) -- The description of the device. Type (string) -- The device type. Vendor (string) -- The device vendor. Model (string) -- The device model. SerialNumber (string) -- The device serial number. Location (dict) -- The site location. Address (string) -- The physical address. Latitude (string) -- The latitude. Longitude (string) -- The longitude. SiteId (string) -- The site ID. CreatedAt (datetime) -- The date and time that the site was created. State (string) -- The device state. Tags (list) -- The tags for the device. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Device': { 'DeviceId': 'string', 'DeviceArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Type': 'string', 'Vendor': 'string', 'Model': 'string', 'SerialNumber': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'SiteId': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def delete_global_network(GlobalNetworkId=None): """ Deletes an existing global network. You must first delete all global network objects (devices, links, and sites) and deregister all transit gateways. See also: AWS API Documentation Exceptions :example: response = client.delete_global_network( GlobalNetworkId='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :rtype: dict ReturnsResponse Syntax{ 'GlobalNetwork': { 'GlobalNetworkId': 'string', 'GlobalNetworkArn': 'string', 'Description': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- GlobalNetwork (dict) --Information about the global network. GlobalNetworkId (string) --The ID of the global network. GlobalNetworkArn (string) --The Amazon Resource Name (ARN) of the global network. Description (string) --The description of the global network. CreatedAt (datetime) --The date and time that the global network was created. State (string) --The state of the global network. Tags (list) --The tags for the global network. (dict) --Describes a tag. Key (string) --The tag key. Length Constraints: Maximum length of 128 characters. Value (string) --The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'GlobalNetwork': { 'GlobalNetworkId': 'string', 'GlobalNetworkArn': 'string', 'Description': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } """ pass def delete_link(GlobalNetworkId=None, LinkId=None): """ Deletes an existing link. You must first disassociate the link from any devices and customer gateways. See also: AWS API Documentation Exceptions :example: response = client.delete_link( GlobalNetworkId='string', LinkId='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type LinkId: string :param LinkId: [REQUIRED]\nThe ID of the link.\n :rtype: dict ReturnsResponse Syntax { 'Link': { 'LinkId': 'string', 'LinkArn': 'string', 'GlobalNetworkId': 'string', 'SiteId': 'string', 'Description': 'string', 'Type': 'string', 'Bandwidth': { 'UploadSpeed': 123, 'DownloadSpeed': 123 }, 'Provider': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Link (dict) -- Information about the link. LinkId (string) -- The ID of the link. LinkArn (string) -- The Amazon Resource Name (ARN) of the link. GlobalNetworkId (string) -- The ID of the global network. SiteId (string) -- The ID of the site. Description (string) -- The description of the link. Type (string) -- The type of the link. Bandwidth (dict) -- The bandwidth for the link. UploadSpeed (integer) -- Upload speed in Mbps. DownloadSpeed (integer) -- Download speed in Mbps. Provider (string) -- The provider of the link. CreatedAt (datetime) -- The date and time that the link was created. State (string) -- The state of the link. Tags (list) -- The tags for the link. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Link': { 'LinkId': 'string', 'LinkArn': 'string', 'GlobalNetworkId': 'string', 'SiteId': 'string', 'Description': 'string', 'Type': 'string', 'Bandwidth': { 'UploadSpeed': 123, 'DownloadSpeed': 123 }, 'Provider': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def delete_site(GlobalNetworkId=None, SiteId=None): """ Deletes an existing site. The site cannot be associated with any device or link. See also: AWS API Documentation Exceptions :example: response = client.delete_site( GlobalNetworkId='string', SiteId='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type SiteId: string :param SiteId: [REQUIRED]\nThe ID of the site.\n :rtype: dict ReturnsResponse Syntax { 'Site': { 'SiteId': 'string', 'SiteArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Site (dict) -- Information about the site. SiteId (string) -- The ID of the site. SiteArn (string) -- The Amazon Resource Name (ARN) of the site. GlobalNetworkId (string) -- The ID of the global network. Description (string) -- The description of the site. Location (dict) -- The location of the site. Address (string) -- The physical address. Latitude (string) -- The latitude. Longitude (string) -- The longitude. CreatedAt (datetime) -- The date and time that the site was created. State (string) -- The state of the site. Tags (list) -- The tags for the site. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Site': { 'SiteId': 'string', 'SiteArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def deregister_transit_gateway(GlobalNetworkId=None, TransitGatewayArn=None): """ Deregisters a transit gateway from your global network. This action does not delete your transit gateway, or modify any of its attachments. This action removes any customer gateway associations. See also: AWS API Documentation Exceptions :example: response = client.deregister_transit_gateway( GlobalNetworkId='string', TransitGatewayArn='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type TransitGatewayArn: string :param TransitGatewayArn: [REQUIRED]\nThe Amazon Resource Name (ARN) of the transit gateway.\n :rtype: dict ReturnsResponse Syntax { 'TransitGatewayRegistration': { 'GlobalNetworkId': 'string', 'TransitGatewayArn': 'string', 'State': { 'Code': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'|'FAILED', 'Message': 'string' } } } Response Structure (dict) -- TransitGatewayRegistration (dict) -- The transit gateway registration information. GlobalNetworkId (string) -- The ID of the global network. TransitGatewayArn (string) -- The Amazon Resource Name (ARN) of the transit gateway. State (dict) -- The state of the transit gateway registration. Code (string) -- The code for the state reason. Message (string) -- The message for the state reason. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'TransitGatewayRegistration': { 'GlobalNetworkId': 'string', 'TransitGatewayArn': 'string', 'State': { 'Code': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'|'FAILED', 'Message': 'string' } } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def describe_global_networks(GlobalNetworkIds=None, MaxResults=None, NextToken=None): """ Describes one or more global networks. By default, all global networks are described. To describe the objects in your global network, you must use the appropriate Get* action. For example, to list the transit gateways in your global network, use GetTransitGatewayRegistrations . See also: AWS API Documentation Exceptions :example: response = client.describe_global_networks( GlobalNetworkIds=[ 'string', ], MaxResults=123, NextToken='string' ) :type GlobalNetworkIds: list :param GlobalNetworkIds: The IDs of one or more global networks. The maximum is 10.\n\n(string) --\n\n :type MaxResults: integer :param MaxResults: The maximum number of results to return. :type NextToken: string :param NextToken: The token for the next page of results. :rtype: dict ReturnsResponse Syntax { 'GlobalNetworks': [ { 'GlobalNetworkId': 'string', 'GlobalNetworkArn': 'string', 'Description': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ], 'NextToken': 'string' } Response Structure (dict) -- GlobalNetworks (list) -- Information about the global networks. (dict) -- Describes a global network. GlobalNetworkId (string) -- The ID of the global network. GlobalNetworkArn (string) -- The Amazon Resource Name (ARN) of the global network. Description (string) -- The description of the global network. CreatedAt (datetime) -- The date and time that the global network was created. State (string) -- The state of the global network. Tags (list) -- The tags for the global network. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. NextToken (string) -- The token for the next page of results. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'GlobalNetworks': [ { 'GlobalNetworkId': 'string', 'GlobalNetworkArn': 'string', 'Description': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ], 'NextToken': 'string' } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def disassociate_customer_gateway(GlobalNetworkId=None, CustomerGatewayArn=None): """ Disassociates a customer gateway from a device and a link. See also: AWS API Documentation Exceptions :example: response = client.disassociate_customer_gateway( GlobalNetworkId='string', CustomerGatewayArn='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type CustomerGatewayArn: string :param CustomerGatewayArn: [REQUIRED]\nThe Amazon Resource Name (ARN) of the customer gateway. For more information, see Resources Defined by Amazon EC2 .\n :rtype: dict ReturnsResponse Syntax { 'CustomerGatewayAssociation': { 'CustomerGatewayArn': 'string', 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' } } Response Structure (dict) -- CustomerGatewayAssociation (dict) -- Information about the customer gateway association. CustomerGatewayArn (string) -- The Amazon Resource Name (ARN) of the customer gateway. GlobalNetworkId (string) -- The ID of the global network. DeviceId (string) -- The ID of the device. LinkId (string) -- The ID of the link. State (string) -- The association state. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'CustomerGatewayAssociation': { 'CustomerGatewayArn': 'string', 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def disassociate_link(GlobalNetworkId=None, DeviceId=None, LinkId=None): """ Disassociates an existing device from a link. You must first disassociate any customer gateways that are associated with the link. See also: AWS API Documentation Exceptions :example: response = client.disassociate_link( GlobalNetworkId='string', DeviceId='string', LinkId='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type DeviceId: string :param DeviceId: [REQUIRED]\nThe ID of the device.\n :type LinkId: string :param LinkId: [REQUIRED]\nThe ID of the link.\n :rtype: dict ReturnsResponse Syntax { 'LinkAssociation': { 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'LinkAssociationState': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' } } Response Structure (dict) -- LinkAssociation (dict) -- Information about the link association. GlobalNetworkId (string) -- The ID of the global network. DeviceId (string) -- The device ID for the link association. LinkId (string) -- The ID of the link. LinkAssociationState (string) -- The state of the association. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'LinkAssociation': { 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'LinkAssociationState': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None, HttpMethod=None): """ Generate a presigned url given a client, its method, and arguments :type ClientMethod: string :param ClientMethod: The client method to presign for :type Params: dict :param Params: The parameters normally passed to\nClientMethod. :type ExpiresIn: int :param ExpiresIn: The number of seconds the presigned url is valid\nfor. By default it expires in an hour (3600 seconds) :type HttpMethod: string :param HttpMethod: The http method to use on the generated url. By\ndefault, the http method is whatever is used in the method\'s model. """ pass def get_customer_gateway_associations(GlobalNetworkId=None, CustomerGatewayArns=None, MaxResults=None, NextToken=None): """ Gets the association information for customer gateways that are associated with devices and links in your global network. See also: AWS API Documentation Exceptions :example: response = client.get_customer_gateway_associations( GlobalNetworkId='string', CustomerGatewayArns=[ 'string', ], MaxResults=123, NextToken='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type CustomerGatewayArns: list :param CustomerGatewayArns: One or more customer gateway Amazon Resource Names (ARNs). For more information, see Resources Defined by Amazon EC2 . The maximum is 10.\n\n(string) --\n\n :type MaxResults: integer :param MaxResults: The maximum number of results to return. :type NextToken: string :param NextToken: The token for the next page of results. :rtype: dict ReturnsResponse Syntax { 'CustomerGatewayAssociations': [ { 'CustomerGatewayArn': 'string', 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' }, ], 'NextToken': 'string' } Response Structure (dict) -- CustomerGatewayAssociations (list) -- The customer gateway associations. (dict) -- Describes the association between a customer gateway, a device, and a link. CustomerGatewayArn (string) -- The Amazon Resource Name (ARN) of the customer gateway. GlobalNetworkId (string) -- The ID of the global network. DeviceId (string) -- The ID of the device. LinkId (string) -- The ID of the link. State (string) -- The association state. NextToken (string) -- The token for the next page of results. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'CustomerGatewayAssociations': [ { 'CustomerGatewayArn': 'string', 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' }, ], 'NextToken': 'string' } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def get_devices(GlobalNetworkId=None, DeviceIds=None, SiteId=None, MaxResults=None, NextToken=None): """ Gets information about one or more of your devices in a global network. See also: AWS API Documentation Exceptions :example: response = client.get_devices( GlobalNetworkId='string', DeviceIds=[ 'string', ], SiteId='string', MaxResults=123, NextToken='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type DeviceIds: list :param DeviceIds: One or more device IDs. The maximum is 10.\n\n(string) --\n\n :type SiteId: string :param SiteId: The ID of the site. :type MaxResults: integer :param MaxResults: The maximum number of results to return. :type NextToken: string :param NextToken: The token for the next page of results. :rtype: dict ReturnsResponse Syntax { 'Devices': [ { 'DeviceId': 'string', 'DeviceArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Type': 'string', 'Vendor': 'string', 'Model': 'string', 'SerialNumber': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'SiteId': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ], 'NextToken': 'string' } Response Structure (dict) -- Devices (list) -- The devices. (dict) -- Describes a device. DeviceId (string) -- The ID of the device. DeviceArn (string) -- The Amazon Resource Name (ARN) of the device. GlobalNetworkId (string) -- The ID of the global network. Description (string) -- The description of the device. Type (string) -- The device type. Vendor (string) -- The device vendor. Model (string) -- The device model. SerialNumber (string) -- The device serial number. Location (dict) -- The site location. Address (string) -- The physical address. Latitude (string) -- The latitude. Longitude (string) -- The longitude. SiteId (string) -- The site ID. CreatedAt (datetime) -- The date and time that the site was created. State (string) -- The device state. Tags (list) -- The tags for the device. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. NextToken (string) -- The token for the next page of results. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Devices': [ { 'DeviceId': 'string', 'DeviceArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Type': 'string', 'Vendor': 'string', 'Model': 'string', 'SerialNumber': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'SiteId': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ], 'NextToken': 'string' } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def get_link_associations(GlobalNetworkId=None, DeviceId=None, LinkId=None, MaxResults=None, NextToken=None): """ Gets the link associations for a device or a link. Either the device ID or the link ID must be specified. See also: AWS API Documentation Exceptions :example: response = client.get_link_associations( GlobalNetworkId='string', DeviceId='string', LinkId='string', MaxResults=123, NextToken='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type DeviceId: string :param DeviceId: The ID of the device. :type LinkId: string :param LinkId: The ID of the link. :type MaxResults: integer :param MaxResults: The maximum number of results to return. :type NextToken: string :param NextToken: The token for the next page of results. :rtype: dict ReturnsResponse Syntax { 'LinkAssociations': [ { 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'LinkAssociationState': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' }, ], 'NextToken': 'string' } Response Structure (dict) -- LinkAssociations (list) -- The link associations. (dict) -- Describes the association between a device and a link. GlobalNetworkId (string) -- The ID of the global network. DeviceId (string) -- The device ID for the link association. LinkId (string) -- The ID of the link. LinkAssociationState (string) -- The state of the association. NextToken (string) -- The token for the next page of results. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'LinkAssociations': [ { 'GlobalNetworkId': 'string', 'DeviceId': 'string', 'LinkId': 'string', 'LinkAssociationState': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED' }, ], 'NextToken': 'string' } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def get_links(GlobalNetworkId=None, LinkIds=None, SiteId=None, Type=None, Provider=None, MaxResults=None, NextToken=None): """ Gets information about one or more links in a specified global network. If you specify the site ID, you cannot specify the type or provider in the same request. You can specify the type and provider in the same request. See also: AWS API Documentation Exceptions :example: response = client.get_links( GlobalNetworkId='string', LinkIds=[ 'string', ], SiteId='string', Type='string', Provider='string', MaxResults=123, NextToken='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type LinkIds: list :param LinkIds: One or more link IDs. The maximum is 10.\n\n(string) --\n\n :type SiteId: string :param SiteId: The ID of the site. :type Type: string :param Type: The link type. :type Provider: string :param Provider: The link provider. :type MaxResults: integer :param MaxResults: The maximum number of results to return. :type NextToken: string :param NextToken: The token for the next page of results. :rtype: dict ReturnsResponse Syntax { 'Links': [ { 'LinkId': 'string', 'LinkArn': 'string', 'GlobalNetworkId': 'string', 'SiteId': 'string', 'Description': 'string', 'Type': 'string', 'Bandwidth': { 'UploadSpeed': 123, 'DownloadSpeed': 123 }, 'Provider': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ], 'NextToken': 'string' } Response Structure (dict) -- Links (list) -- The links. (dict) -- Describes a link. LinkId (string) -- The ID of the link. LinkArn (string) -- The Amazon Resource Name (ARN) of the link. GlobalNetworkId (string) -- The ID of the global network. SiteId (string) -- The ID of the site. Description (string) -- The description of the link. Type (string) -- The type of the link. Bandwidth (dict) -- The bandwidth for the link. UploadSpeed (integer) -- Upload speed in Mbps. DownloadSpeed (integer) -- Download speed in Mbps. Provider (string) -- The provider of the link. CreatedAt (datetime) -- The date and time that the link was created. State (string) -- The state of the link. Tags (list) -- The tags for the link. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. NextToken (string) -- The token for the next page of results. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Links': [ { 'LinkId': 'string', 'LinkArn': 'string', 'GlobalNetworkId': 'string', 'SiteId': 'string', 'Description': 'string', 'Type': 'string', 'Bandwidth': { 'UploadSpeed': 123, 'DownloadSpeed': 123 }, 'Provider': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ], 'NextToken': 'string' } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def get_paginator(operation_name=None): """ Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name\nas the method name on the client. For example, if the\nmethod name is create_foo, and you\'d normally invoke the\noperation as client.create_foo(**kwargs), if the\ncreate_foo operation can be paginated, you can use the\ncall client.get_paginator('create_foo'). :rtype: L{botocore.paginate.Paginator} ReturnsA paginator object. """ pass def get_sites(GlobalNetworkId=None, SiteIds=None, MaxResults=None, NextToken=None): """ Gets information about one or more of your sites in a global network. See also: AWS API Documentation Exceptions :example: response = client.get_sites( GlobalNetworkId='string', SiteIds=[ 'string', ], MaxResults=123, NextToken='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type SiteIds: list :param SiteIds: One or more site IDs. The maximum is 10.\n\n(string) --\n\n :type MaxResults: integer :param MaxResults: The maximum number of results to return. :type NextToken: string :param NextToken: The token for the next page of results. :rtype: dict ReturnsResponse Syntax { 'Sites': [ { 'SiteId': 'string', 'SiteArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ], 'NextToken': 'string' } Response Structure (dict) -- Sites (list) -- The sites. (dict) -- Describes a site. SiteId (string) -- The ID of the site. SiteArn (string) -- The Amazon Resource Name (ARN) of the site. GlobalNetworkId (string) -- The ID of the global network. Description (string) -- The description of the site. Location (dict) -- The location of the site. Address (string) -- The physical address. Latitude (string) -- The latitude. Longitude (string) -- The longitude. CreatedAt (datetime) -- The date and time that the site was created. State (string) -- The state of the site. Tags (list) -- The tags for the site. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. NextToken (string) -- The token for the next page of results. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Sites': [ { 'SiteId': 'string', 'SiteArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ], 'NextToken': 'string' } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def get_transit_gateway_registrations(GlobalNetworkId=None, TransitGatewayArns=None, MaxResults=None, NextToken=None): """ Gets information about the transit gateway registrations in a specified global network. See also: AWS API Documentation Exceptions :example: response = client.get_transit_gateway_registrations( GlobalNetworkId='string', TransitGatewayArns=[ 'string', ], MaxResults=123, NextToken='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type TransitGatewayArns: list :param TransitGatewayArns: The Amazon Resource Names (ARNs) of one or more transit gateways. The maximum is 10.\n\n(string) --\n\n :type MaxResults: integer :param MaxResults: The maximum number of results to return. :type NextToken: string :param NextToken: The token for the next page of results. :rtype: dict ReturnsResponse Syntax { 'TransitGatewayRegistrations': [ { 'GlobalNetworkId': 'string', 'TransitGatewayArn': 'string', 'State': { 'Code': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'|'FAILED', 'Message': 'string' } }, ], 'NextToken': 'string' } Response Structure (dict) -- TransitGatewayRegistrations (list) -- The transit gateway registrations. (dict) -- Describes the registration of a transit gateway to a global network. GlobalNetworkId (string) -- The ID of the global network. TransitGatewayArn (string) -- The Amazon Resource Name (ARN) of the transit gateway. State (dict) -- The state of the transit gateway registration. Code (string) -- The code for the state reason. Message (string) -- The message for the state reason. NextToken (string) -- The token for the next page of results. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'TransitGatewayRegistrations': [ { 'GlobalNetworkId': 'string', 'TransitGatewayArn': 'string', 'State': { 'Code': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'|'FAILED', 'Message': 'string' } }, ], 'NextToken': 'string' } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def get_waiter(waiter_name=None): """ Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters\nsection of the service docs for a list of available waiters. :rtype: botocore.waiter.Waiter """ pass def list_tags_for_resource(ResourceArn=None): """ Lists the tags for a specified resource. See also: AWS API Documentation Exceptions :example: response = client.list_tags_for_resource( ResourceArn='string' ) :type ResourceArn: string :param ResourceArn: [REQUIRED]\nThe Amazon Resource Name (ARN) of the resource.\n :rtype: dict ReturnsResponse Syntax{ 'TagList': [ { 'Key': 'string', 'Value': 'string' }, ] } Response Structure (dict) -- TagList (list) --The list of tags. (dict) --Describes a tag. Key (string) --The tag key. Length Constraints: Maximum length of 128 characters. Value (string) --The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'TagList': [ { 'Key': 'string', 'Value': 'string' }, ] } """ pass def register_transit_gateway(GlobalNetworkId=None, TransitGatewayArn=None): """ Registers a transit gateway in your global network. The transit gateway can be in any AWS Region, but it must be owned by the same AWS account that owns the global network. You cannot register a transit gateway in more than one global network. See also: AWS API Documentation Exceptions :example: response = client.register_transit_gateway( GlobalNetworkId='string', TransitGatewayArn='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type TransitGatewayArn: string :param TransitGatewayArn: [REQUIRED]\nThe Amazon Resource Name (ARN) of the transit gateway. For more information, see Resources Defined by Amazon EC2 .\n :rtype: dict ReturnsResponse Syntax { 'TransitGatewayRegistration': { 'GlobalNetworkId': 'string', 'TransitGatewayArn': 'string', 'State': { 'Code': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'|'FAILED', 'Message': 'string' } } } Response Structure (dict) -- TransitGatewayRegistration (dict) -- Information about the transit gateway registration. GlobalNetworkId (string) -- The ID of the global network. TransitGatewayArn (string) -- The Amazon Resource Name (ARN) of the transit gateway. State (dict) -- The state of the transit gateway registration. Code (string) -- The code for the state reason. Message (string) -- The message for the state reason. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'TransitGatewayRegistration': { 'GlobalNetworkId': 'string', 'TransitGatewayArn': 'string', 'State': { 'Code': 'PENDING'|'AVAILABLE'|'DELETING'|'DELETED'|'FAILED', 'Message': 'string' } } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def tag_resource(ResourceArn=None, Tags=None): """ Tags a specified resource. See also: AWS API Documentation Exceptions :example: response = client.tag_resource( ResourceArn='string', Tags=[ { 'Key': 'string', 'Value': 'string' }, ] ) :type ResourceArn: string :param ResourceArn: [REQUIRED]\nThe Amazon Resource Name (ARN) of the resource.\n :type Tags: list :param Tags: [REQUIRED]\nThe tags to apply to the specified resource.\n\n(dict) --Describes a tag.\n\nKey (string) --The tag key.\nLength Constraints: Maximum length of 128 characters.\n\nValue (string) --The tag value.\nLength Constraints: Maximum length of 256 characters.\n\n\n\n\n :rtype: dict ReturnsResponse Syntax {} Response Structure (dict) -- Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: {} :returns: (dict) -- """ pass def untag_resource(ResourceArn=None, TagKeys=None): """ Removes tags from a specified resource. See also: AWS API Documentation Exceptions :example: response = client.untag_resource( ResourceArn='string', TagKeys=[ 'string', ] ) :type ResourceArn: string :param ResourceArn: [REQUIRED]\nThe Amazon Resource Name (ARN) of the resource.\n :type TagKeys: list :param TagKeys: [REQUIRED]\nThe tag keys to remove from the specified resource.\n\n(string) --\n\n :rtype: dict ReturnsResponse Syntax {} Response Structure (dict) -- Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: {} :returns: (dict) -- """ pass def update_device(GlobalNetworkId=None, DeviceId=None, Description=None, Type=None, Vendor=None, Model=None, SerialNumber=None, Location=None, SiteId=None): """ Updates the details for an existing device. To remove information for any of the parameters, specify an empty string. See also: AWS API Documentation Exceptions :example: response = client.update_device( GlobalNetworkId='string', DeviceId='string', Description='string', Type='string', Vendor='string', Model='string', SerialNumber='string', Location={ 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, SiteId='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type DeviceId: string :param DeviceId: [REQUIRED]\nThe ID of the device.\n :type Description: string :param Description: A description of the device.\nLength Constraints: Maximum length of 256 characters.\n :type Type: string :param Type: The type of the device. :type Vendor: string :param Vendor: The vendor of the device.\nLength Constraints: Maximum length of 128 characters.\n :type Model: string :param Model: The model of the device.\nLength Constraints: Maximum length of 128 characters.\n :type SerialNumber: string :param SerialNumber: The serial number of the device.\nLength Constraints: Maximum length of 128 characters.\n :type Location: dict :param Location: Describes a location.\n\nAddress (string) --The physical address.\n\nLatitude (string) --The latitude.\n\nLongitude (string) --The longitude.\n\n\n :type SiteId: string :param SiteId: The ID of the site. :rtype: dict ReturnsResponse Syntax { 'Device': { 'DeviceId': 'string', 'DeviceArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Type': 'string', 'Vendor': 'string', 'Model': 'string', 'SerialNumber': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'SiteId': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Device (dict) -- Information about the device. DeviceId (string) -- The ID of the device. DeviceArn (string) -- The Amazon Resource Name (ARN) of the device. GlobalNetworkId (string) -- The ID of the global network. Description (string) -- The description of the device. Type (string) -- The device type. Vendor (string) -- The device vendor. Model (string) -- The device model. SerialNumber (string) -- The device serial number. Location (dict) -- The site location. Address (string) -- The physical address. Latitude (string) -- The latitude. Longitude (string) -- The longitude. SiteId (string) -- The site ID. CreatedAt (datetime) -- The date and time that the site was created. State (string) -- The device state. Tags (list) -- The tags for the device. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Device': { 'DeviceId': 'string', 'DeviceArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Type': 'string', 'Vendor': 'string', 'Model': 'string', 'SerialNumber': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'SiteId': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def update_global_network(GlobalNetworkId=None, Description=None): """ Updates an existing global network. To remove information for any of the parameters, specify an empty string. See also: AWS API Documentation Exceptions :example: response = client.update_global_network( GlobalNetworkId='string', Description='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of your global network.\n :type Description: string :param Description: A description of the global network.\nLength Constraints: Maximum length of 256 characters.\n :rtype: dict ReturnsResponse Syntax { 'GlobalNetwork': { 'GlobalNetworkId': 'string', 'GlobalNetworkArn': 'string', 'Description': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- GlobalNetwork (dict) -- Information about the global network object. GlobalNetworkId (string) -- The ID of the global network. GlobalNetworkArn (string) -- The Amazon Resource Name (ARN) of the global network. Description (string) -- The description of the global network. CreatedAt (datetime) -- The date and time that the global network was created. State (string) -- The state of the global network. Tags (list) -- The tags for the global network. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'GlobalNetwork': { 'GlobalNetworkId': 'string', 'GlobalNetworkArn': 'string', 'Description': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def update_link(GlobalNetworkId=None, LinkId=None, Description=None, Type=None, Bandwidth=None, Provider=None): """ Updates the details for an existing link. To remove information for any of the parameters, specify an empty string. See also: AWS API Documentation Exceptions :example: response = client.update_link( GlobalNetworkId='string', LinkId='string', Description='string', Type='string', Bandwidth={ 'UploadSpeed': 123, 'DownloadSpeed': 123 }, Provider='string' ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type LinkId: string :param LinkId: [REQUIRED]\nThe ID of the link.\n :type Description: string :param Description: A description of the link.\nLength Constraints: Maximum length of 256 characters.\n :type Type: string :param Type: The type of the link.\nLength Constraints: Maximum length of 128 characters.\n :type Bandwidth: dict :param Bandwidth: The upload and download speed in Mbps.\n\nUploadSpeed (integer) --Upload speed in Mbps.\n\nDownloadSpeed (integer) --Download speed in Mbps.\n\n\n :type Provider: string :param Provider: The provider of the link.\nLength Constraints: Maximum length of 128 characters.\n :rtype: dict ReturnsResponse Syntax { 'Link': { 'LinkId': 'string', 'LinkArn': 'string', 'GlobalNetworkId': 'string', 'SiteId': 'string', 'Description': 'string', 'Type': 'string', 'Bandwidth': { 'UploadSpeed': 123, 'DownloadSpeed': 123 }, 'Provider': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Link (dict) -- Information about the link. LinkId (string) -- The ID of the link. LinkArn (string) -- The Amazon Resource Name (ARN) of the link. GlobalNetworkId (string) -- The ID of the global network. SiteId (string) -- The ID of the site. Description (string) -- The description of the link. Type (string) -- The type of the link. Bandwidth (dict) -- The bandwidth for the link. UploadSpeed (integer) -- Upload speed in Mbps. DownloadSpeed (integer) -- Download speed in Mbps. Provider (string) -- The provider of the link. CreatedAt (datetime) -- The date and time that the link was created. State (string) -- The state of the link. Tags (list) -- The tags for the link. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Link': { 'LinkId': 'string', 'LinkArn': 'string', 'GlobalNetworkId': 'string', 'SiteId': 'string', 'Description': 'string', 'Type': 'string', 'Bandwidth': { 'UploadSpeed': 123, 'DownloadSpeed': 123 }, 'Provider': 'string', 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.ServiceQuotaExceededException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass def update_site(GlobalNetworkId=None, SiteId=None, Description=None, Location=None): """ Updates the information for an existing site. To remove information for any of the parameters, specify an empty string. See also: AWS API Documentation Exceptions :example: response = client.update_site( GlobalNetworkId='string', SiteId='string', Description='string', Location={ 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' } ) :type GlobalNetworkId: string :param GlobalNetworkId: [REQUIRED]\nThe ID of the global network.\n :type SiteId: string :param SiteId: [REQUIRED]\nThe ID of your site.\n :type Description: string :param Description: A description of your site.\nLength Constraints: Maximum length of 256 characters.\n :type Location: dict :param Location: The site location:\n\nAddress : The physical address of the site.\nLatitude : The latitude of the site.\nLongitude : The longitude of the site.\n\n\nAddress (string) --The physical address.\n\nLatitude (string) --The latitude.\n\nLongitude (string) --The longitude.\n\n\n :rtype: dict ReturnsResponse Syntax { 'Site': { 'SiteId': 'string', 'SiteArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } Response Structure (dict) -- Site (dict) -- Information about the site. SiteId (string) -- The ID of the site. SiteArn (string) -- The Amazon Resource Name (ARN) of the site. GlobalNetworkId (string) -- The ID of the global network. Description (string) -- The description of the site. Location (dict) -- The location of the site. Address (string) -- The physical address. Latitude (string) -- The latitude. Longitude (string) -- The longitude. CreatedAt (datetime) -- The date and time that the site was created. State (string) -- The state of the site. Tags (list) -- The tags for the site. (dict) -- Describes a tag. Key (string) -- The tag key. Length Constraints: Maximum length of 128 characters. Value (string) -- The tag value. Length Constraints: Maximum length of 256 characters. Exceptions NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException :return: { 'Site': { 'SiteId': 'string', 'SiteArn': 'string', 'GlobalNetworkId': 'string', 'Description': 'string', 'Location': { 'Address': 'string', 'Latitude': 'string', 'Longitude': 'string' }, 'CreatedAt': datetime(2015, 1, 1), 'State': 'PENDING'|'AVAILABLE'|'DELETING'|'UPDATING', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] } } :returns: NetworkManager.Client.exceptions.ValidationException NetworkManager.Client.exceptions.AccessDeniedException NetworkManager.Client.exceptions.ResourceNotFoundException NetworkManager.Client.exceptions.ConflictException NetworkManager.Client.exceptions.ThrottlingException NetworkManager.Client.exceptions.InternalServerException """ pass
def updatePars(): if not parent().par.Lockbuffermenu: return op('output_table_path').cook(force=True) dat = op('output_table') if dat.numRows < 2: return p = parent().par.Outputbuffer p.menuNames = dat.col('name')[1:] p.menuLabels = dat.col('label')[1:] def onTableChange(dat): updatePars() def onValueChange(*_): updatePars()
def test(name): print("from method", name) test("hello") def printinfo(name, age=18): print(name, age) printinfo("cgy") # 单个*号参数以数组传入 def uncertainLength(name, *args): for x in args: print(x, end=",") print(name, len(args)) uncertainLength("cgy", 10, 20, 30) # ** 2个星号参数以dict传入 def uncertDict(name, **argdict): print(argdict['a']) print(name, argdict) uncertDict("cgy", a=1, b=2) # 单个*后的参数必须用关键词传入 def f(a, b, *, c): return a + b + c # 这样写会报错f(1,2,3) print(f(1,2,c=3)) def f1(*,a,b,c): return a + b+ c print(f1(a=1,b=2,c=3)) # lambda 表达式,好搓 sum = lambda a,b:a+b sum(1,2)
def error_Check(inputX, inputY, nSamples, initVector, minCost, alpha, training_epochs, silent, overlap, objFunc, keepPercent, batchSize, batching): acceptedObjFuncs = ["", "QUAD"] if inputX.shape[0] != inputY.shape[0]: print("Must have the same number of labels and training samples") return -1 if type(nSamples) != int: print("nSamples must be an integer") return -1 if len(initVector) <= 1: print("init vector is too short, must be at least 2 layers") return -1 if type(minCost) not in [int, float]: print("minCost must be float or integer") return -1 if type(alpha) not in [int, float]: print("alpha must be float or integer") return -1 if type(training_epochs) != int: print("training_epochs must be an integer") return -1 if type(silent) != bool: print("silent must be either True or False") return -1 if type(overlap) != bool: print("silent must be either True or False") return -1 if type(keepPercent) not in [float, int]: print("keepPercent must be an int or float") return -1 if keepPercent > 1 or keepPercent < 0: print("keepPercent must be between 0 and 1") return -1 if objFunc not in acceptedObjFuncs: print("objFunc can only take on values: ", end='') for func in acceptedObjFuncs[:-1]: if func == '': print("Empty string", end=', ') else: print(func, end=", ") print(acceptedObjFuncs[-1] + '.') return -1 if type(batchSize) != int: print("batchSize must be int") return -1 if batching not in [True, False]: print("batching must be boolean") return -1 #passed all tests return 0
n1 = int(input('Um valor: ')) n2 = int(input('Outro valor: ')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 e = n1 ** n2 su = n1 - n2 print('A soma é {}, produto é {} e a divisão {:.2f}.'.format(s, m, d), end='>>>')#exemplo -> end='' => continua na mesma linha print('Divisão inteira é {}, a potencia é {:.2f} e a divisão {:.2f}'.format(di, e, su)) #print('A soma vale {:w^20}.'.format(n1+n2)) exemplo
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 25 14:06:56 2020 Class to handle coordinates in Hive according to how they are used in the entomology Hive position editor. cf. https://entomology.appspot.com/hive.html?bg=0&board=:w***@bA**@bB***@bG*@bL*@bM*@bP*@bQ**@bS***@wA**@wB***@wG*@wL*@wM*@wP*@wQ**@wS&grid=1 @author: epenjos """ class Position: def __init__(self, aA, aB): self.a = aA self.b = aB def importBSCoords(self, coordinates): #handle the conversion to numerical coordinates from the format #used at BoardSpace # a,b are non-orhogonal coordinates of the hex-grid # N 13 = ( 0, 0) # N 12 = ( 0, 1) # O 13 = ( 1, 0) # M 11 = (-1, 2) # O 14 = ( 1,-1) # M 12 = (-1, 1) coords = coordinates.split() self.a = ord(coords[0]) - 78 #coords[1] the letter coordinate self.b = 13 - int(coords[1]) #coords[2] is the numerical coordinate return self #Overloading the '+' operator def __add__(self, other): newA = self.a + other.a newB = self.b + other.b return Position(newA,newB) def __sub__(self, other): newA = self.a - other.a newB = self.b - other.b return Position(newA,newB) #The scalar product for vectors implemented def __mul__(self, other): return self.a * other.a + self.b * other.b def __neg__(self): return Position(-self.a, -self.b) def __eq__(self, other): return (self.a == other.a) & (self.b == other.b) def __ne__(self, other): return not self.__eq__(other) #60 degrees rotation counter-clockwise transformation # e1 -> e1 - e2 # e2 -> e1 # [ 1 1 ] [a] # [-1 0 ] [b] def rot60CCW(self): newA = Position( 1, 1)*self newB = Position(-1, 0)*self return Position(newA, newB) def rot120CCW(self): newA = Position( 0, 1)*self newB = Position(-1,-1)*self return Position(newA, newB) def rot180CCW(self): newA = Position(-1, 0)*self newB = Position( 0,-1)*self return Position(newA, newB) def rot60CW(self): newA = Position( 0,-1)*self newB = Position( 1, 1)*self return Position(newA, newB) def rot120CW(self): newA = Position(-1,-1)*self newB = Position( 1, 0)*self return Position(newA, newB) def reflXaxis(self): newA = Position( 1, 1)*self newB = Position( 0,-1)*self return Position(newA, newB) def __repr__(self): return "(%s,%s)" % (self.a, self.b) def testPositionClass(): inpStr = ["N 13", "N 12", "O 13", "M 11", "O 14", "M 12"] expRes = ["(0,0)", "(0,1)", "(1,0)", "(-1,2)", "(1,-1)", "(-1,1)"] for i, val in enumerate(inpStr): if str(Position(0,0).importBSCoords(val)) != expRes[i]: print("Position conversion error:" + val + "=>" + str(Position(0,0).importBSCoords(val))) assert Position(2,1).reflXaxis() == Position(3,-1) assert Position(-4,2).reflXaxis() == Position(-2,-2) assert Position(2,1).rot60CCW() == Position(3,-2) assert Position(4,-1).rot60CCW() == Position(3,-4) assert Position(2,1).rot60CW() == Position(-1,3) assert Position(7,-4).rot60CW() == Position(4,3) assert Position(2,1).rot120CW() == Position(-3,2) assert Position(-2,-2).rot120CW() == Position(4,-2)
''' Kattis - oddgnome theres probably a smarter way, but i really can't be bothered Time: O(n^2 log n), Space: O(n) ''' num_tc = int(input()) for _ in range(num_tc): arr = list(map(int, input().split())) n = arr.pop(0) for i in range(1, n): new_arr = arr[:i] + arr[i+1:] if new_arr == sorted(new_arr): print(i+1) break
def force_bytes(value): if isinstance(value, bytes): return value return str(value).encode('utf-8')
""" ## Questions : EASY ### 1844. [Replace All Digits with Characters](https://leetcode.com/problems/replace-all-digits-with-characters/) You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices. There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c. For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'. For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]). Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'. Example 1: Input: s = "a1c1e1" Output: "abcdef" Explanation: The digits are replaced as follows: - s[1] -> shift('a',1) = 'b' - s[3] -> shift('c',1) = 'd' - s[5] -> shift('e',1) = 'f' Example 2: Input: s = "a1b2c3d4e" Output: "abbdcfdhe" Explanation: The digits are replaced as follows: - s[1] -> shift('a',1) = 'b' - s[3] -> shift('b',2) = 'd' - s[5] -> shift('c',3) = 'f' - s[7] -> shift('d',4) = 'h' Constraints: 1 <= s.length <= 100 s consists only of lowercase English letters and digits. shift(s[i-1], s[i]) <= 'z' for all odd indices i. """ # Solutions class Solution: def replaceDigits(self, s: str) -> str: chars = 'abcdefghijklmnopqrstuvwxyz' res = '' n = len(s) i = 0 while i < n: if i & 1: new_char = chars[(int(s[i]) + chars.index(s[i - 1])) % 26] res += new_char else: res += s[i] i += 1 return res # Runtime : 28 ms, faster than 91.58% of Python3 online submissions # Memory Usage : 14.2 MB, less than 44.97% of Python3 online submissions
""" Event dispatcher for non-browser Events which occur on Widget state changes. """ class EventDispatcher(object): """ Base class for event notifier. """ def __init__(self, name): super(EventDispatcher, self).__init__() self.queue = [] self.name = name def _genTargetFuncName(self): """ Returns the name of the function called on the receiving object """ return "on%s" % (self.name[0].upper() + self.name[1:]) def register(self, cb, reset=False): """ Append "cb" to the list of objects to inform of the given Event. Does nothing if cb has already subscribed. :param cb: the object to register :type cb: object """ assert self._genTargetFuncName() in dir(cb), "cb must provide a %s method" % self._genTargetFuncName() if reset: self.queue = [] if cb not in self.queue: self.queue.append(cb) def unregister(self, cb): """ Remove "cb" from the list of objects to inform of the given Event. Does nothing if cb is not in that list. :param cb: the object to remove :type cb: object """ if cb in self.queue: self.queue.remove(cb) def fire(self, *args, **kwargs): """ Fires the event. Informs all subscribed listeners. All parameters passed to the receiving function. """ for cb in self.queue: getattr(cb, self._genTargetFuncName())(*args, **kwargs)
# 自定义数组结构 class Array(object): """自定义数组类""" def __init__(self, len, default=None): """ 数组初始化 :param len: 数组的长度 :param default: 数组的默认值 """ self._item = list() for i in range(len): self._item.append(default) def __str__(self): """使用打印输出的时候的返回值""" return self._item.__str__() def __len__(self): """调用len(obj)时的返回值""" return len(self._item) def __iter__(self): """调用迭代环境时返回迭代器""" return iter(self._item) def __getitem__(self, item): """通过索引取值时的返回值""" return self._item[item] def __setitem__(self, key, value): """通过索引设置值""" self._item[key] = value if __name__ == "__main__": a = Array(10) print(a)
""" Pagamento exigido pelo total de metros cúbicos de água ao encher uma piscina. """ preco_m3 = float(input("Informe o custo (R$) por metro cúbico de agua:")) print("Informe as dimensões da piscina:") Lar = float(input("Largura [metros]:")) Comp = float(input("Comprimento [metros]:")) Alt = float(input("Altura [metros]:")) vol = Lar * Comp * Alt print("As dimensoes da piscina são Largura x Comprimento x Altura: ") print(str(Lar) + "x" + str(Comp) + "x" + str(Alt) + ' m3' + '\n') print("Volume de agua " + str(vol) + " m3") print("Valor a pagar R$/" + str(preco_m3 * vol) + "\n")
coords = [] for ry in range(-2, 3): for rx in range(2, -3, -1): x = rx / 4 y = ry / 4 coords.append((x,y)) for p in range(16): y, x = divmod(p, 4) top_right = coords[(y+1)*5 + x] top_left = coords[(y+1)*5 + x + 1] bottom_left = coords[y*5 + x + 1] bottom_right = coords[y*5 + x] line = '{{{{ {} }}}},'.format(', '.join('{: .2f}f' for _ in range(12))) line = line.format( top_right[0], top_right[1], top_left[0], top_left[1], bottom_left[0], bottom_left[1], top_right[0], top_right[1], bottom_left[0], bottom_left[1], bottom_right[0], bottom_right[1], ) print(line)
"""df[{}] = df[{}].astype({})""" def run(dfs: dict, settings: dict) -> dict: """df[{}] = df[{}].astype({})""" if 'columns' not in settings: raise Exception('Missing columns param') dfs[settings['df']] = dfs[settings['df']].astype(settings['columns']) return dfs
# -*- coding: utf-8 -*- __author__ = 'Bruno Paes' __email__ = 'brunopaes05@gmail.com' __github__ = 'https://www.github.com/Brunopaes' __status__ = 'Finalised' class Viginere(object): @staticmethod def encrypt(plaintext, key): key_length = len(key) key_as_int = [ord(i) for i in key] plaintext_int = [ord(i) for i in plaintext] ciphertext = '' for i in range(len(plaintext_int)): value = (plaintext_int[i] + key_as_int[i % key_length]) % 26 ciphertext += chr(value + 65) return ciphertext @staticmethod def decrypt(ciphertext, key): key_length = len(key) key_as_int = [ord(i) for i in key] ciphertext_int = [ord(i) for i in ciphertext] plaintext = '' for i in range(len(ciphertext_int)): value = (ciphertext_int[i] - key_as_int[i % key_length]) % 26 plaintext += chr(value + 65) return plaintext if __name__ == '__main__': c = Viginere() print(c.decrypt('efsdsetpe', 'espm'))
""" Hash tables :: Day 1 Notes: Arrays An array: * Stores a sequence of elements * Each element must be the same data type * Occupies a contiguous block of memory * Can access data in constant time with this equation: `memory_address = starting_address + index * data_size` """ class DynamicArray: def __init__(self, capacity=1): self.count = 0 # Number of elements in the array self.capacity = capacity # Total amount of storage in array self.storage = [None] * capacity def insert(self, index, value): """Inserts a value into list at index. Complexity: O(n)""" # Check if we have enough capacity if self.count >= self.capacity: # If not, make more room self.resize() # Shift every item after index to right by 1 for i in range(self.count, index, -1): self.storage[i] = self.storage[i - 1] # Add new value at the index self.storage[index] = value # Increment count self.count += 1 def append(self, value): """Appends a value to the end of array. Complexity: O(1)""" # Check if array has enough capacity if self.count >= self.capacity: # If not, resize up self.resize() # Add value to the index of count self.storage[self.count] = value # Increment count self.count += 1 def resize(self): """Doubles the capacity of array.""" self.capacity *= 2 # Allocate a new storage array with double capacity new_storage = [None] * self.capacity # Copy all ements from old storage to new for i in range(self.count): new_storage[i] = self.storage[i] self.storage = new_storage a = DynamicArray(2) a.insert(0, 19) a.insert(0, 14) print(a.storage) a.append(9) a.append(8) print(a.storage) a.append(7) print(a.storage)
predictor_url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2' predictor_file = '../weights/shape_predictor_68_face_landmarks.dat' p2v_model_gdrive_id = '1op5_zyH4CWm_JFDdCUPZM4X-A045ETex' sample_image = '../examples/sample.jpg'
def main(request, response): name = request.GET.first(b"name") value = request.GET.first(b"value") source_origin = request.headers.get(b"origin", None) response_headers = [(b"Set-Cookie", name + b"=" + value), (b"Access-Control-Allow-Origin", source_origin), (b"Access-Control-Allow-Credentials", b"true")] return (200, response_headers, u"")
# Leetcode 435. Non-overlapping Intervals # # Link: https://leetcode.com/problems/non-overlapping-intervals/ # Difficulty: Medium # Solution using sorting. # Complexity: # O(NlogN) time | where N represent the number of intervals # O(1) space class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key = lambda pair : pair[0]) result = 0 prevEnd = intervals[0][1] for start, end in intervals[1:]: if start >= prevEnd: # Not overlapping if prevEnd < start prevEnd = end else: # Overlapping if prevEnd > start # Remove the longest one result += 1 prevEnd = min(prevEnd, end) return result
BOARD_TILE_SIZE = 56 # the size of each board tile BOARD_PLAYER_SIZE = 20 # the size of each player icon BOARD_MARGIN = (10, 0) # margins, in pixels (for player icons) PLAYER_ICON_IMAGE_SIZE = 32 # the size of the image to download, should a power of 2 and higher than BOARD_PLAYER_SIZE MAX_PLAYERS = 4 # depends on the board size/quality, 4 is for the default board # board definition (from, to) BOARD = { # ladders 2: 38, 7: 14, 8: 31, 15: 26, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 78: 98, 87: 94, # snakes 99: 80, 95: 75, 92: 88, 89: 68, 74: 53, 64: 60, 62: 19, 49: 11, 46: 25, 16: 6 }
def truncate(string, length): "Ensure a string is no longer than a given length." if len(string) <= length: return string else: return string[:length]
print(':-:' * 10) print('{:^30}'.format('Cálculo de IMC')) print(':-:' * 10) peso = float(input('Seu peso: ')) altura = float(input('Sua altura em metros: ')) IMC = peso / pow(altura, 2) situacao = ''; if IMC < 18.5: situacao = 'Magreza' elif IMC <= 24.9: situacao = 'Normal' elif IMC <= 29.9: situacao = 'Sobrepeso' elif IMC <= 39.9: situacao = 'Obesidade' else: situacao = 'Obesidade Grave' print('Seu IMC resultou em {:.2f}! Caracterizado como {}.'.format(IMC, situacao))
def insertionSort(arr, size): for i in range(1, size): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr def shakerSort(arr, size): left = 0 right = size - 1 lastSwap = 0 while left < right: for i in range(left, right): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] lastSwap = i right = lastSwap for i in range(right, left, -1): if arr[i - 1] > arr[i]: arr[i], arr[i - 1] = arr[i - 1], arr[i] lastSwap = i left = lastSwap return arr def selectionSort(arr, size): for i in range(size - 1): minIndex = i for j in range(i + 1, size): if arr[minIndex] > arr[j]: minIndex = j arr[minIndex], arr[i] = arr[i], arr[minIndex] return arr if __name__ == '__main__': a = [1, 2, 3, 4, 5] b = [5, 4, 3, 2, 1] c = [4, 2 ,3, 5, 1] print(insertionSort(a, 5)) print(shakerSort(a, 5)) print(selectionSort(a, 5)) print(insertionSort(b, 5)) print(shakerSort(b, 5)) print(selectionSort(b, 5)) print(insertionSort(c, 5)) print(shakerSort(c, 5)) print(selectionSort(c, 5)) print(insertionSort([1], 1)) print(shakerSort([1], 1)) print(selectionSort([1], 1)) print(insertionSort([], 0)) print(shakerSort([], 0)) print(selectionSort([], 0)) print(insertionSort(["ab", "make", "draw"], 3)) print(insertionSort([2, 1, 3, 4, 5], 5))
def mergeOverlappingIntervals(intervals): sortedIntervals = sorted(intervals, key=lambda x: x[0]) overlappingIntervals = [] left = sortedIntervals[0][0] right = sortedIntervals[0][1] for i in range(1, len(sortedIntervals)): if right >= sortedIntervals[i][0]: right = max(right, sortedIntervals[i][1]) else: overlappingIntervals.append([left, right]) left, right = sortedIntervals[i][0], sortedIntervals[i][1] overlappingIntervals.append([left, right]) return overlappingIntervals
# hash class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ count_map = {} res = [] for num in nums1: count_map[num] = count_map.get(num, 0) + 1 for num in nums2: if count_map.get(num, 0) > 0: res.append(num) count_map[num] -= 1 return res # tow-pointers class Solution2(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums1.sort() nums2.sort() left = 0 right = 0 res = [] while(left < len(nums1) and right < len(nums2)): if nums1[left] > nums2[right]: right += 1 elif nums1[left] < nums2[right]: left += 1 else: res.append(nums1[left]) left += 1 right += 1 return res
class Pessoa: olhos = 2 def __init__(self, *filhos,nome=None, idade = 35): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f" Olá {id(self)}" @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return f"{cls} = olhos {cls.olhos}" if __name__ == '__main__': ataide = Pessoa(nome = "Ataíde") luciano = Pessoa(ataide, nome = "Luciano") print(Pessoa.cumprimentar(luciano)) print(id(luciano)) print(luciano.cumprimentar()) print(luciano.nome) print(luciano.idade) for filho in luciano.filhos: print(filho.nome) luciano.sobrenome = "Ramalho" print(luciano.sobrenome) del luciano.filhos print(luciano.__dict__) print(ataide.__dict__) print(Pessoa.olhos) print(luciano.olhos) print(ataide.olhos) print(id(Pessoa.olhos), id(luciano.olhos), id(ataide)) print(Pessoa.metodo_estatico(), luciano.metodo_estatico(), ataide.metodo_estatico()) print(Pessoa.nome_e_atributos_de_classe(),luciano.metodo_estatico())
class GameLogic: def __int__(self): self def add_lander(self, lander): self.lander = lander def update(self, delta_time): self.lander.update_lander(delta_time)
data = [] with open("data.txt") as file: data = [int(x) for x in file.read().split(",")] def part_one(data, noun, verb): opcode = 0 data_c = data[:] data_c[1] = noun data_c[2] = verb while True: if data_c[opcode] == 1: data_c[data_c[opcode + 3]] = data_c[data_c[opcode + 1]] + data_c[data_c[opcode + 2]] elif data_c[opcode] == 2: data_c[data_c[opcode + 3]] = data_c[data_c[opcode + 1]] * data_c[data_c[opcode + 2]] elif data_c[opcode] == 99: break else: print("It failed!") opcode += 4 return data_c[0] def part_two(data): for noun in range(100): for verb in range(100): if part_one(data, noun, verb) == 19690720: return 100 * noun + verb print(part_two(data))
# coding=utf8 """ Prolog Grammar of ATIS """ GRAMMAR_DICTIONARY = {} ROOT_RULE = 'statement -> [answer]' GRAMMAR_DICTIONARY['statement'] = ['(answer ws)'] GRAMMAR_DICTIONARY['answer'] = [ '("answer_1(" var "," goal ")")', '("answer_2(" var "," var "," goal ")")', '("answer_3(" var "," var "," var "," goal ")")', '("answer_4(" var "," var "," var "," var "," goal ")")', ] # Goal GRAMMAR_DICTIONARY['goal'] = [ '(declaration)', '(unit_relation)', '(binary_relation)', '(triplet_relation)', '(meta)', '("(" goal conjunction ")")', '("or(" goal conjunction ")")', '("not(" goal conjunction ")")' ] GRAMMAR_DICTIONARY['conjunction'] = [ '("," goal conjunction)', '""' ] # Variable GRAMMAR_DICTIONARY['var'] = ['"%s"' % chr(97+i) for i in range(26)] # Declaration GRAMMAR_DICTIONARY['declaration'] = [ '("const(" var "," object ")")'] # Object GRAMMAR_DICTIONARY['object'] = [ '(fare_basis_code)', '(meal_code)', '(airport_code)', '(airline_code)', '(aircraft_code_object)', '(city_name)', '(time)', '(flight_number_object)', '(class_description)', '(day_period)', '(state_name)', '(day_number)', '(month)', '(day)', '(dollar)', '(meal_description)', '("hour(9)")', '(integer)', '(basis_type)', '(year)', '("days_code(sa)")', '("manufacturer(boeing)")' ] GRAMMAR_DICTIONARY['fare_basis_code'] = ['("fare_basis_code(" fare_basis_code_value ")")'] GRAMMAR_DICTIONARY['fare_basis_code_value'] = ['"_qx"', '"_qw"', '"_qo"', '"_fn"', '"_yn"', '"_bh"', '"_k"', '"_b"', '"_h"', '"_f"', '"_q"', '"_c"', '"_y"', '"_m"',] GRAMMAR_DICTIONARY['meal_code'] = ['("meal_code(" meal_code_value ")")'] GRAMMAR_DICTIONARY['meal_code_value'] = ['"ap_58"', '"ap_57"', '"d_s"', '"b"', '"ap_55"', '"s_"', '"sd_d"', '"ls"', '"ap_68"', '"ap_80"', '"ap"', '"s"', ] GRAMMAR_DICTIONARY['airline_code'] = ['("airline_code(" airline_code_value ")")'] GRAMMAR_DICTIONARY['airline_code_value'] = ['"usair"', '"co"', '"ua"', '"delta"', '"as"', '"ff"', '"canadian_airlines_international"', '"us"', '"nx"', '"hp"', '"aa"', '"kw"', '"ml"', '"nw"', '"ac"', '"tw"', '"yx"', '"ea"', '"dl"', '"wn"', '"lh"', '"cp"'] GRAMMAR_DICTIONARY['airport_code'] = ['("airport_code(" airport_code_value ")")'] GRAMMAR_DICTIONARY['airport_code_value'] = ['"dallas"', '"ont"', '"stapelton"', '"bna"', '"bwi"', '"iad"', '"sfo"', '"phl"', '"pit"', '"slc"', '"phx"', '"lax"', '"bur"', '"ind"', '"iah"', '"dtw"', '"las"', '"dal"', '"den"', '"atl"', '"ewr"', '"bos"', '"tpa"', '"jfk"', '"mke"', '"oak"', '"yyz"', '"dfw"', '"cvg"', '"hou"', '"lga"', '"ord"', '"mia"', '"mco"'] GRAMMAR_DICTIONARY['aircraft_code_object'] = ['("aircraft_code(" aircraft_code_value ")")'] GRAMMAR_DICTIONARY['aircraft_code_value'] = ['"m80"', '"dc10"', '"727"', '"d9s"', '"f28"', '"j31"', '"767"', '"734"', '"73s"', '"747"', '"737"', '"733"', '"d10"', '"100"', '"757"', '"72s"'] GRAMMAR_DICTIONARY['city_name'] = ['("city_name(" city_name_value ")")'] GRAMMAR_DICTIONARY['city_name_value'] = ['"cleveland"', '"milwaukee"', '"detroit"', '"los_angeles"', '"miami"', '"salt_lake_city"', '"ontario"', '"tacoma"', '"memphis"', '"denver"', '"san_francisco"', '"new_york"', '"tampa"', '"washington"', '"westchester_county"', '"boston"', '"newark"', '"pittsburgh"', '"charlotte"', '"columbus"', '"atlanta"', '"oakland"', '"kansas_city"', '"st_louis"', '"nashville"', '"chicago"', '"fort_worth"', '"san_jose"', '"dallas"', '"philadelphia"', '"st_petersburg"', '"baltimore"', '"san_diego"', '"cincinnati"', '"long_beach"', '"phoenix"', '"indianapolis"', '"burbank"', '"montreal"', '"seattle"', '"st_paul"', '"minneapolis"', '"houston"', '"orlando"', '"toronto"', '"las_vegas"'] GRAMMAR_DICTIONARY['time'] = ['("time(" time_value ")")'] GRAMMAR_DICTIONARY['time_value'] = [ '"1850"', '"1110"', '"2000"', '"1815"', '"1024"', '"1500"', '"1900"', '"1600"', '"1300"', '"1800"', '"1200"', '"1628"', '"1830"', '"823"', '"1245"', '"1524"', '"200"', '"1615"', '"1230"', '"705"', '"1045"', '"1700"', '"1115"', '"1645"', '"1730"', '"815"', '"0"', '"500"', '"1205"', '"1940"', '"1400"', '"1130"', '"2200"', '"645"', '"718"', '"2220"', '"600"', '"630"', '"800"', '"838"', '"1330"', '"845"', '"1630"', '"1715"', '"2010"', '"1000"', '"1619"', '"2100"', '"1505"', '"2400"', '"1923"', '"100"', '"1145"', '"2300"', '"1620"', '"2023"', '"2358"', '"1425"', '"720"', '"1310"', '"700"', '"650"', '"1410"', '"1030"', '"1900"', '"1017"', '"1430"', '"900"', '"1930"', '"1133"', '"1220"', '"2226"', '"1100"', '"819"', '"755"', '"2134"', '"555"', '"1"', ] GRAMMAR_DICTIONARY['flight_number_object'] = ['("flight_number(" flight_number_value ")")'] GRAMMAR_DICTIONARY['flight_number_value'] = [ '"1291"', '"345"', '"813"', '"71"', '"1059"', '"212"', '"1209"', '"281"', '"201"', '"324"', '"19"', '"352"', '"137338"', '"4400"', '"323"', '"505"', '"825"', '"82"', '"279"', '"1055"', '"296"', '"315"', '"1765"', '"405"', '"771"', '"106"', '"2153"', '"257"', '"402"', '"343"', '"98"', '"1039"', '"217"', '"539"', '"459"', '"417"', '"1083"', '"3357"', '"311"', '"210"', '"139"', '"852"', '"838"', '"415"', '"3724"', '"21"', '"928"', '"269"', '"270"', '"297"', '"746"', '"1222"', '"271"' ] GRAMMAR_DICTIONARY['class_description'] = ['("class_description(" class_description_value ")")'] GRAMMAR_DICTIONARY['class_description_value'] = ['"thrift"', '"coach"', '"first"', '"business"'] GRAMMAR_DICTIONARY['day_period'] = ['("day_period(" day_period_value ")")'] GRAMMAR_DICTIONARY['day_period_value'] = ['"early"', '"afternoon"', '"late_evening"', '"late_night"', '"mealtime"', '"evening"', '"pm"', '"daytime"', '"breakfast"', '"morning"', '"late"'] GRAMMAR_DICTIONARY['state_name'] = ['("state_name(" state_name_value ")")'] GRAMMAR_DICTIONARY['state_name_value'] = ['"minnesota"', '"florida"', '"arizona"', '"nevada"', '"california"'] GRAMMAR_DICTIONARY['day_number'] = ['("day_number(" day_number_value ")")'] GRAMMAR_DICTIONARY['day_number_value'] = ['"13"', '"29"', '"28"', '"22"', '"21"', '"16"', '"30"', '"12"', '"18"', '"19"', '"31"', '"20"', '"27"', '"6"', '"26"', '"17"', '"11"', '"10"', '"15"', '"23"', '"24"', '"25"', '"14"', '"1"', '"3"', '"8"', '"5"', '"2"', '"9"', '"4"', '"7"'] GRAMMAR_DICTIONARY['month'] = ['("month(" month_value ")")'] GRAMMAR_DICTIONARY['month_value'] = ['"april"', '"august"', '"may"', '"october"', '"june"', '"november"', '"september"', '"february"', '"december"', '"march"', '"july"', '"january"'] GRAMMAR_DICTIONARY['day'] = ['("day(" day_value ")")'] GRAMMAR_DICTIONARY['day_value'] = ['"monday"', '"wednesday"', '"thursday"', '"tuesday"', '"saturday"', '"friday"', '"sunday"'] GRAMMAR_DICTIONARY['dollar'] = ['("dollar(" dollar_value ")")'] GRAMMAR_DICTIONARY['dollar_value'] = ['"1000"', '"1500"', '"466"', '"1288"', '"300"', '"329"', '"416"', '"124"', '"932"', '"1100"', '"200"', '"500"', '"100"', '"415"', '"150"', '"400"'] GRAMMAR_DICTIONARY['meal_description'] = ['("meal_description(" meal_description_value ")")'] GRAMMAR_DICTIONARY['meal_description_value'] = ['"snack"', '"breakfast"', '"lunch"', '"dinner"'] GRAMMAR_DICTIONARY['integer'] = ['("integer(" integer_value ")")'] GRAMMAR_DICTIONARY['integer_value'] = ['"2"', '"1"', '"3"'] GRAMMAR_DICTIONARY['basis_type'] = ['("basis_type(" basis_type_value ")")'] GRAMMAR_DICTIONARY['basis_type_value'] = ['"737"', '"767"'] GRAMMAR_DICTIONARY['year'] = ['("year(" year_value ")")'] GRAMMAR_DICTIONARY['year_value'] = ['"1991"', '"1993"', '"1992"'] # Unit Relation GRAMMAR_DICTIONARY['unit_relation'] = [ # Flight '(is_flight)', '(is_oneway)', '(is_round_trip)', '(is_daily_flight)', '(is_flight_has_stop)', '(is_non_stop_flight)', '(is_flight_economy)', '(is_flight_has_meal)', '(is_economy)', '(is_discounted_flight)', '(is_flight_overnight)', '(is_connecting_flight)', # Meal '(is_meal)', '(is_meal_code)', # Airline '(is_airline)', # Transport way '(is_rapid_transit)', '(is_taxi)', '(is_air_taxi_operation)', '(is_ground_transport_on_weekday)', '(is_ground_transport)', '(is_limousine)', '(is_rental_car)', # Aircraft '(is_flight_turboprop)', '(is_turboprop)', '(aircraft_code)', '(is_aircraft)', '(is_flight_jet)', # Time '(is_day_after_tomorrow_flight)', '(is_flight_tonight)', '(is_today_flight)', '(is_tomorrow_flight)', '(is_flight_on_weekday)', '(is_tomorrow_arrival_flight)', # Other '(is_time_zone_code)', '(is_class_of_service)', '(is_city)', '(is_airport)', '(is_fare_basis_code)', '(is_booking_class_t)', ] GRAMMAR_DICTIONARY['is_discounted_flight'] = ['("is_discounted_flight(" var ")")'] GRAMMAR_DICTIONARY['is_taxi'] = ['("is_taxi(" var ")")'] GRAMMAR_DICTIONARY['is_economy'] = ['("is_economy(" var ")")'] GRAMMAR_DICTIONARY['is_flight_on_weekday'] = ['("is_flight_on_weekday(" var ")")'] GRAMMAR_DICTIONARY['is_time_zone_code'] = ['("is_time_zone_code(" var ")")'] GRAMMAR_DICTIONARY['is_air_taxi_operation'] = ['("is_air_taxi_operation(" var ")")'] GRAMMAR_DICTIONARY['is_fare_basis_code'] = ['("is_fare_basis_code(" var ")")'] GRAMMAR_DICTIONARY['is_meal_code'] = ['("is_meal_code(" var ")")'] GRAMMAR_DICTIONARY['is_limousine'] = ['("is_limousine(" var ")")'] GRAMMAR_DICTIONARY['is_flight_tonight'] = ['("is_flight_tonight(" var ")")'] GRAMMAR_DICTIONARY['is_tomorrow_arrival_flight'] = ['("is_tomorrow_arrival_flight(" var ")")'] GRAMMAR_DICTIONARY['is_tomorrow_flight'] = ['("is_tomorrow_flight(" var ")")'] GRAMMAR_DICTIONARY['is_daily_flight'] = ['("is_daily_flight(" var ")")'] GRAMMAR_DICTIONARY['_minutes_distant'] = ['("_minutes_distant(" var ")")'] GRAMMAR_DICTIONARY['is_flight'] = ['("is_flight(" var ")")'] GRAMMAR_DICTIONARY['is_city'] = ['("is_city(" var ")")'] GRAMMAR_DICTIONARY['is_booking_class_t'] = ['("is_booking_class_t(" var ")")'] GRAMMAR_DICTIONARY['is_rapid_transit'] = ['("is_rapid_transit(" var ")")'] GRAMMAR_DICTIONARY['is_oneway'] = ['("is_oneway(" var ")")'] GRAMMAR_DICTIONARY['is_airport'] = ['("is_airport(" var ")")'] GRAMMAR_DICTIONARY['is_flight_has_stop'] = ['("is_flight_has_stop(" var ")")'] GRAMMAR_DICTIONARY['aircraft_code'] = ['("aircraft_code(" var ")")'] GRAMMAR_DICTIONARY['is_day_after_tomorrow_flight'] = ['("is_day_after_tomorrow_flight(" var ")")'] GRAMMAR_DICTIONARY['is_airline'] = ['("is_airline(" var ")")'] GRAMMAR_DICTIONARY['is_flight_economy'] = ['("is_flight_economy(" var ")")'] GRAMMAR_DICTIONARY['is_class_of_service'] = ['("is_class_of_service(" var ")")'] GRAMMAR_DICTIONARY['is_aircraft'] = ['("is_aircraft(" var ")")'] GRAMMAR_DICTIONARY['is_today_flight'] = ['("is_today_flight(" var ")")'] GRAMMAR_DICTIONARY['is_flight_has_meal'] = ['("is_flight_has_meal(" var ")")'] GRAMMAR_DICTIONARY['is_ground_transport'] = ['("is_ground_transport(" var ")")'] GRAMMAR_DICTIONARY['is_non_stop_flight'] = ['("is_non_stop_flight(" var ")")'] GRAMMAR_DICTIONARY['is_flight_turboprop'] = ['("is_flight_turboprop(" var ")")'] GRAMMAR_DICTIONARY['is_meal'] = ['("is_meal(" var ")")'] GRAMMAR_DICTIONARY['is_round_trip'] = ['("is_round_trip(" var ")")'] GRAMMAR_DICTIONARY['is_ground_transport_on_weekday'] = ['("is_ground_transport_on_weekday(" var ")")'] GRAMMAR_DICTIONARY['is_turboprop'] = ['("is_turboprop(" var ")")'] GRAMMAR_DICTIONARY['is_rental_car'] = ['("is_rental_car(" var ")")'] GRAMMAR_DICTIONARY['is_connecting_flight'] = ['("is_connecting_flight(" var ")")'] GRAMMAR_DICTIONARY['is_flight_jet'] = ['("is_flight_jet(" var ")")'] GRAMMAR_DICTIONARY['is_flight_overnight'] = ['("is_flight_overnight(" var ")")'] # Binary Predicate GRAMMAR_DICTIONARY['binary_relation'] = [ # General '(_named)', # Flight property '(is_flight_has_specific_fare_basis_code)', '(is_flight_has_booking_class)', '(is_flight_stop_at_city)', '(is_flight_on_year)', '(is_flight_during_day)', '(is_flight_stops_specify_number_of_times)', '(is_flight_meal_code)', '(is_from)', '(is_flight_day_return)', '(is_flight_day_number_return)', '(is_flight_departure_time)', '(is_flight_month_return)', '(is_flight_month_arrival)', '(is_flight_approx_return_time)', '(is_flight_before_day)', '(is_flight_approx_arrival_time)', '(is_flight_day_number_arrival)', '(is_flight_arrival_time)', '(is_flight_with_specific_aircraft)', '(is_flight_on_day_number)', '(is_flight_on_day)', '(is_flight_manufacturer)', '(is_flight_aircraft)', '(is_flight_stop_at_airport)', '(is_flight_during_day_arrival)', '(is_flight_days_from_today)', '(is_fare_basis_code_class_type)', '(is_flight_after_day)', '(is_flight_day_arrival)', '(is_flight_approx_departure_time)', '(is_flight_has_specific_meal)', '(is_next_days_flight)', '(is_flight_has_class_type)', '(is_to)', '(is_flight_airline)', '(p_flight_fare)', '(is_flight_number)', # Airport '(is_airport_of_city)', '(is_airline_services)', '(is_services)', '(is_from_airports_of_city)', # Ground Transport '(is_from_airport)', '(is_to_city)', '(is_loc_t_state)', # Aircraft '(is_mf)', '(is_loc_t)', '(is_aircraft_basis_type)', '(is_aircraft_airline)', # Other '(is_flight_cost_fare)', '(is_loc_t_city_time_zone)', '(is_airline_provide_meal)', '(is_airline_has_booking_class)', # Entity '(minimum_connection_time)', '(p_flight_stop_arrival_time)', '(p_ground_fare)', '(p_booking_class_fare)', '(airline_name)', '(abbrev)', '(capacity)', '(minutes_distant)', '(is_time_elapsed)', '(p_flight_restriction_code)' ] GRAMMAR_DICTIONARY['airline_name'] = ['("airline_name(" var "," var ")")'] GRAMMAR_DICTIONARY['_named'] = ['("_named(" var "," var ")")'] GRAMMAR_DICTIONARY['is_time_elapsed'] = ['("is_time_elapsed(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_has_specific_fare_basis_code'] = ['("is_flight_has_specific_fare_basis_code(" var "," var ")")'] GRAMMAR_DICTIONARY['abbrev'] = ['("abbrev(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_during_day'] = ['("is_flight_during_day(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_has_booking_class'] = ['("is_flight_has_booking_class(" var "," var ")")'] GRAMMAR_DICTIONARY['is_airline_has_booking_class'] = ['("is_airline_has_booking_class(" var "," var ")")'] GRAMMAR_DICTIONARY['capacity'] = ['("capacity(" var "," var ")")'] GRAMMAR_DICTIONARY['get_flight_airline_code'] = ['("get_flight_airline_code(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_stop_at_city'] = ['("is_flight_stop_at_city(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_on_year'] = ['("is_flight_on_year(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_stops_specify_number_of_times'] = ['("is_flight_stops_specify_number_of_times(" var "," var ")")'] GRAMMAR_DICTIONARY['is_from_airport'] = ['("is_from_airport(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_meal_code'] = ['("is_flight_meal_code(" var "," var ")")'] GRAMMAR_DICTIONARY['p_flight_airline_code'] = ['("p_flight_airline_code(" var "," var ")")'] GRAMMAR_DICTIONARY['is_from'] = ['("is_from(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_day_return'] = ['("is_flight_day_return(" var "," var ")")'] GRAMMAR_DICTIONARY['get_flight_fare'] = ['("get_flight_fare(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_day_number_return'] = ['("is_flight_day_number_return(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_departure_time'] = ['("is_flight_departure_time(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_month_return'] = ['("is_flight_month_return(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_month_arrival'] = ['("is_flight_month_arrival(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_number'] = ['("is_flight_number(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_cost_fare'] = ['("is_flight_cost_fare(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_approx_return_time'] = ['("is_flight_approx_return_time(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_before_day'] = ['("is_flight_before_day(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_approx_arrival_time'] = ['("is_flight_approx_arrival_time(" var "," var ")")'] GRAMMAR_DICTIONARY['is_airport_of_city'] = ['("is_airport_of_city(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_day_number_arrival'] = ['("is_flight_day_number_arrival(" var "," var ")")'] GRAMMAR_DICTIONARY['is_airline_services'] = ['("is_airline_services(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_airline'] = ['("is_flight_airline(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_arrival_time'] = ['("is_flight_arrival_time(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_with_specific_aircraft'] = ['("is_flight_with_specific_aircraft(" var "," var ")")'] GRAMMAR_DICTIONARY['is_mf'] = ['("is_mf(" var "," var ")")'] GRAMMAR_DICTIONARY['get_flight_aircraft_code'] = ['("get_flight_aircraft_code(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_on_day_number'] = ['("is_flight_on_day_number(" var "," var ")")'] GRAMMAR_DICTIONARY['is_loc_t'] = ['("is_loc_t(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_on_day'] = ['("is_flight_on_day(" var "," var ")")'] GRAMMAR_DICTIONARY['get_flight_restriction_code'] = ['("get_flight_restriction_code(" var "," var ")")'] GRAMMAR_DICTIONARY['is_to_city'] = ['("is_to_city(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_manufacturer'] = ['("is_flight_manufacturer(" var "," var ")")'] GRAMMAR_DICTIONARY['minutes_distant'] = ['("minutes_distant(" var "," var ")")'] GRAMMAR_DICTIONARY['is_services'] = ['("is_services(" var "," var ")")'] GRAMMAR_DICTIONARY['p_booking_class_fare'] = ['("p_booking_class_fare(" var "," var ")")'] GRAMMAR_DICTIONARY['p_flight_aircraft_code'] = ['("p_flight_aircraft_code(" var "," var ")")'] GRAMMAR_DICTIONARY['p_flight_restriction_code'] = ['("p_flight_restriction_code(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_aircraft'] = ['("is_flight_aircraft(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_stop_at_airport'] = ['("is_flight_stop_at_airport(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_during_day_arrival'] = ['("is_flight_during_day_arrival(" var "," var ")")'] GRAMMAR_DICTIONARY['departure_time'] = ['("departure_time(" var "," var ")")'] GRAMMAR_DICTIONARY['arrival_time'] = ['("arrival_time(" var "," var ")")'] GRAMMAR_DICTIONARY['is_fare_basis_code_class_type'] = ['("is_fare_basis_code_class_type(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_after_day'] = ['("is_flight_after_day(" var "," var ")")'] GRAMMAR_DICTIONARY['p_flight_booking_class'] = ['("p_flight_booking_class(" var "," var ")")'] GRAMMAR_DICTIONARY['get_number_of_stops'] = ['("get_number_of_stops(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_days_from_today'] = ['("is_flight_days_from_today(" var "," var ")")'] GRAMMAR_DICTIONARY['minimum_connection_time'] = ['("minimum_connection_time(" var "," var ")")'] GRAMMAR_DICTIONARY['is_aircraft_basis_type'] = ['("is_aircraft_basis_type(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_day_arrival'] = ['("is_flight_day_arrival(" var "," var ")")'] GRAMMAR_DICTIONARY['is_loc_t_state'] = ['("is_loc_t_state(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_approx_departure_time'] = ['("is_flight_approx_departure_time(" var "," var ")")'] GRAMMAR_DICTIONARY['is_from_airports_of_city'] = ['("is_from_airports_of_city(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_has_specific_meal'] = ['("is_flight_has_specific_meal(" var "," var ")")'] GRAMMAR_DICTIONARY['p_flight_fare'] = ['("p_flight_fare(" var "," var ")")'] GRAMMAR_DICTIONARY['is_next_days_flight'] = ['("is_next_days_flight(" var "," var ")")'] GRAMMAR_DICTIONARY['is_flight_has_class_type'] = ['("is_flight_has_class_type(" var "," var ")")'] GRAMMAR_DICTIONARY['time_elapsed'] = ['("time_elapsed(" var "," var ")")'] GRAMMAR_DICTIONARY['is_to'] = ['("is_to(" var "," var ")")'] GRAMMAR_DICTIONARY['is_loc_t_city_time_zone'] = ['("is_loc_t_city_time_zone(" var "," var ")")'] GRAMMAR_DICTIONARY['is_aircraft_airline'] = ['("is_aircraft_airline(" var "," var ")")'] GRAMMAR_DICTIONARY['p_ground_fare'] = ['("p_ground_fare(" var "," var ")")'] GRAMMAR_DICTIONARY['is_airline_provide_meal'] = ['("is_airline_provide_meal(" var "," var ")")'] GRAMMAR_DICTIONARY['p_flight_meal'] = ['("p_flight_meal(" var "," var ")")'] GRAMMAR_DICTIONARY['p_flight_stop_arrival_time'] = ['("p_flight_stop_arrival_time(" var "," var ")")'] # Triplet Relations GRAMMAR_DICTIONARY['triplet_relation'] = ['(miles_distant_between_city)', '(miles_distant)'] GRAMMAR_DICTIONARY['miles_distant_between_city'] = ['("miles_distant_between_city(" var "," var "," var ")")'] GRAMMAR_DICTIONARY['miles_distant'] = ['("miles_distant(" var "," var "," var ")")'] # Meta Predicates GRAMMAR_DICTIONARY['meta'] = [ '(equals)', '(equals_arrival_time)', '(larger_than_arrival_time)', '(larger_than_capacity)', '(larger_than_departure_time)', '(larger_than_number_of_stops)', '(less_than_flight_cost)', '(less_than_departure_time)', '(less_than_flight_fare)', '(less_than_arrival_time)', '(count)', '(argmax_capacity)', '(argmax_arrival_time)', '(argmax_departure_time)', '(argmax_get_number_of_stops)', '(argmax_get_flight_fare)', '(argmax_count)', '(argmin_time_elapsed)', '(argmin_get_number_of_stops)', '(argmin_time_elapsed)', '(argmin_arrival_time)', '(argmin_capacity)', '(argmin_departure_time)', '(argmin_get_flight_fare)', '(argmin_miles_distant)', '(max)', '(min)', '(sum_capacity)', '(sum_get_number_of_stops)' ] GRAMMAR_DICTIONARY['equals'] = ['("equals(" var "," var ")")'] GRAMMAR_DICTIONARY['equals_arrival_time'] = ['("equals_arrival_time(" var "," var ")")'] GRAMMAR_DICTIONARY['larger_than_arrival_time'] = ['("larger_than_arrival_time(" var "," var ")")'] GRAMMAR_DICTIONARY['larger_than_capacity'] = ['("larger_than_capacity(" var "," var ")")'] GRAMMAR_DICTIONARY['larger_than_departure_time'] = ['("larger_than_departure_time(" var "," var ")")'] GRAMMAR_DICTIONARY['larger_than_number_of_stops'] = ['("larger_than_number_of_stops(" var "," var ")")'] GRAMMAR_DICTIONARY['less_than_flight_cost'] = ['("less_than_flight_cost(" var "," var ")")'] GRAMMAR_DICTIONARY['less_than_departure_time'] = ['("less_than_departure_time(" var "," var ")")'] GRAMMAR_DICTIONARY['less_than_flight_fare'] = ['("less_than_flight_fare(" var "," var ")")'] GRAMMAR_DICTIONARY['less_than_arrival_time'] = ['("less_than_arrival_time(" var "," var ")")'] GRAMMAR_DICTIONARY['count'] = ['("count(" var "," goal "," var ")")'] GRAMMAR_DICTIONARY['max'] = ['("_max(" var "," goal ")")'] GRAMMAR_DICTIONARY['min'] = ['("_min(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmax_capacity'] = ['("argmax_capacity(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmax_arrival_time'] = ['("argmax_arrival_time(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmax_departure_time'] = ['("argmax_departure_time(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmax_get_number_of_stops'] = ['("argmax_get_number_of_stops(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmax_get_flight_fare'] = ['("argmax_get_flight_fare(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmax_count'] = ['("argmax_count(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmin_arrival_time'] = ['("argmin_arrival_time(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmin_capacity'] = ['("argmin_capacity(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmin_departure_time'] = ['("argmin_departure_time(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmin_get_number_of_stops'] = ['("argmin_get_number_of_stops(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmin_get_flight_fare'] = ['("argmin_get_flight_fare(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmin_miles_distant'] = ['("argmin_miles_distant(" var "," goal ")")'] GRAMMAR_DICTIONARY['argmin_time_elapsed'] = ['("argmin_time_elapsed(" var "," goal ")")'] GRAMMAR_DICTIONARY['sum_capacity'] = ['("sum_capacity(" var "," goal "," var ")")'] GRAMMAR_DICTIONARY['sum_get_number_of_stops'] = ['("sum_get_number_of_stops(" var "," goal "," var ")")'] GRAMMAR_DICTIONARY["ws"] = ['~"\s*"i'] GRAMMAR_DICTIONARY["wsp"] = ['~"\s+"i'] COPY_TERMINAL_SET = { 'fare_basis_code_value', 'meal_code_value', 'airport_code_value', 'airline_code_value', 'aircraft_code_value', 'city_name_value', 'time_value', 'flight_number_value', 'class_description_value', 'day_period_value', 'state_name_value', 'day_number_value', 'month_value', 'day_value', 'dollar_value', 'meal_description_value', 'integer_value', 'basis_type_value', 'year_value', }
var = 'foo' def ex2(): var = 'bar' print ('inside the function var is ', var) ex2() def ex3(): global var var = 'bar' print ('inside the function var is ', var) ex3() print ('outside the function var is ', var)
''' Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2. Note: - Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For this problem, assume that your function returns 2^31 − 1 when the division result overflows. Example: Input: dividend = 10, divisor = 3 Output: 3 Explanation: 10/3 = truncate(3.33333..) = 3. Example: Input: dividend = 7, divisor = -3 Output: -2 Explanation: 7/-3 = truncate(-2.33333..) = -2. Example: Input: dividend = 0, divisor = 1 Output: 0 Example: Input: dividend = 1, divisor = 1 Output: 1 Constraints: - -2^31 <= dividend, divisor <= 2^31 - 1 - divisor != 0 ''' #Difficulty: Medium #989 / 989 test cases passed. #Runtime: 28 ms #Memory Usage: 14.3 MB #Runtime: 28 ms, faster than 92.03% of Python3 online submissions for Divide Two Integers. #Memory Usage: 14.3 MB, less than 58.58% of Python3 online submissions for Divide Two Integers. class Solution: def divide(self, dividend: int, divisor: int) -> int: min_number = -2**31 max_number = 2**31 - 1 result = abs(dividend) // abs(divisor) if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0): return min(result, max_number) else: return max(-result, min_number)
code = bytearray([ 0xa9, 0xff, 0x8d, 0x02, 0x60, 0xa9, 0x55, # lda #$55 0x8d, 0x00, 0x60, #sta $6000 0xa9, 0x00, # lda #00 0x8d, 0x00, 0x60, #sta $6000 0x4c, 0x05, 0x80 #jmp 8005 (#lda $55) ]) rom = code + bytearray([0xea] * (32768 - len(code)) ) rom[0x7ffc] = 0x00 rom[0x7ffd] = 0x80 with open("rom.bin", "wb") as out_file: out_file.write(rom);
_sampler = None def get_sampler(): return _sampler def set_sampler(sampler): global _sampler _sampler = sampler
class Node: def __init__(self,id,parent,val): self.id=id self.parent=parent self.ch1,self.ch2=0,0 self.val=val self.leaf=True n=int(input()) orix=[*map(int,input().split())] x=sorted(orix) node=dict() node[1]=Node(1,0,-1) cnt=1 li=[] for i in x: li2=[] root=node[1] for j in range(i): if root.ch1==0: cnt+=1 node[cnt]=Node(cnt,root.id,0) root.ch1=cnt root.leaf=False root=node[cnt] li2.append("0") elif root.ch2==0: cnt+=1 node[cnt]=Node(cnt,root.id,1) root.ch2=cnt if j==i-1: while root.id!=1: if node[root.ch1].leaf and node[root.ch2].leaf: root.leaf=True root=node[root.parent] else: break else: root=node[cnt] li2.append("1") elif not node[root.ch1].leaf: root=node[root.ch1] li2.append("0") elif not node[root.ch2].leaf: root=node[root.ch2] li2.append("1") else: print(-1) exit(0) li.append("".join(li2)) print(1) for i in li: for j in range(n): if orix[j]==len(i): break orix[j]=i for i in orix: print(i)
''' Check-for-balanced-parentheses Problem Statement : Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. For example, the function should return 'true' for exp = “[()]{}{[()()]()}” and 'false' for exp = “[(])”. Input : Enter list of parentheses. Output : Print True if it is balanced or else False. Time Complexity : O(n) Space Complexity : O(n) ''' def Check(brackets): stack = [] # Traversing the Expression for i in brackets: if i in ["(", "{", "["]: # Push the element in the stack stack.append(i) else: # IF current character is not opening # bracket, then it must be closing. if not stack: return False char = stack.pop() if char == '(': if i != ")": return False if char == '{': if i != "}": return False if char == '[': if i != "]": return False # Check Empty Stack if stack: return False return True # -----------------------Driver Code----------------------- # INPUT # Enter the list of the brackets brackets = input("Enter the brackets: ") # OUTPUT if(Check(brackets)): print("The parentheses are balnced") else: print("The parentheses are not balnced") ''' SAMPLE INPUT/OUTPUT: INPUT Enter the brackets: {{[[[()]]]}}{(())} OUTPUT The parentheses are balnced '''
print('Progressão aritmética') print(10*'_*_') termo = int(input('Digite o primeiro Termo ')) razao = int(input('Digite a razão de uma P.A ')) print('Os 10 primeiros termos da progressão aritmética são:') for c in range(1,11): print(f'{termo}') termo = termo + razao print('Acabou')
#!/usr/bin/env python # coding=utf-8 ''' @Author: John @Email: johnjim0816@gmail.com @Date: 2019-11-15 13:46:12 @LastEditor: John @LastEditTime: 2020-07-29 22:43:12 @Discription: @Environment: ''' class Solution: def singleNumber(self, nums: List[int]) -> int: seen_once = seen_twice = 0 for num in nums: seen_once = ~seen_twice & (seen_once ^ num) seen_twice = ~seen_once & (seen_twice ^ num) return seen_once
res = 0 i = 0 nb = int(input()) if nb == -1: while i != 'F': i = input() if i != 'F': res += int(i) else: for x in range(nb): i = int(input()) res += i print(res)
def tema(str): print(str) print('-'*20) tema('CONTROLE DE TERRENOS') comprimento = float(input('LARGURA (m): ')) largura = float(input('COMPRIMENTO (m): ')) def área(largura, comprimento): calculo = comprimento * largura print(f'A área do terreno [{largura} x {comprimento}] é {calculo}m²') área(comprimento, largura)
# # Example file for working with conditional statements # def main(): x, y = 10, 100 # conditional flow uses if, elif, else if x < y: print("x is smaller than y") elif x == y: print("x has same value as y") else: print("x is larger than y") # conditional statements let you use "a if C else b" result = "x is less than y" if x < y else "x is same as or larger than y" print(result) if __name__ == "__main__": main()
class AreaLight: def __init__(self, shape_id, intensity, two_sided = False): assert(intensity.device.type == 'cpu') self.shape_id = shape_id self.intensity = intensity self.two_sided = two_sided def state_dict(self): return { 'shape_id': self.shape_id, 'intensity': self.intensity, 'two_sided': self.two_sided } @classmethod def load_state_dict(cls, state_dict): return cls( state_dict['shape_id'], state_dict['intensity'], state_dict['two_sided'])
""" Scaling functions that take PCB and modbus register version numbers, and convert raw register values into real values. """ def scale_5v(value, reverse=False, pcb_version=0): """ Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw value to a voltage (if reverse=False), or convert a value in Volts to raw (if reverse=True). For now, raw values are hundredths of a volt, positive only. :param value: raw register contents as a value from 0-65535, or a voltage in Volts :param reverse: Boolean, True to perform physical->raw conversion instead of raw->physical :param pcb_version: integer PCB version number, 0-65535 :return: output_value in Volts """ if reverse: return int(value * 100) & 0xFFFF else: return value / 100.0 def scale_48v(value, reverse=False, pcb_version=0): """ Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw value to a voltage (if reverse=False), or convert a value in Volts to raw (if reverse=True). For now, raw values are hundredths of a volt, positive only. :param value: raw register contents as a value from 0-65535, or a voltage in Volts :param reverse: Boolean, True to perform physical->raw conversion instead of raw->physical :param pcb_version: integer PCB version number, 0-65535 :return: output_value in Volts """ if reverse: return int(value * 100) & 0xFFFF else: return value / 100.0 def scale_temp(value, reverse=False, pcb_version=0): """ Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw value to deg C (if reverse=False), or convert a value in deg C to raw (if reverse=True). For now, raw values are hundredths of a deg C, as a signed 16-bit integer value :param value: raw register contents as a value from 0-65535, or a floating point temperature in degrees :param reverse: Boolean, True to perform physical->raw conversion instead of raw->physical :param pcb_version: integer PCB version number, 0-65535 :return: value in deg C (if reverse=False), or raw value as an unsigned 16 bit integer """ if reverse: if value < 0: return (int(value * 100) + 65536) & 0xFFFF else: return int(value * 100) & 0xFFFF else: if value >= 32768: value -= 65536 return value / 100.0 # raw_value is a signed 16-bit integer containing temp in 1/100th of a degree # TODO - fix all the uses (and simulated ports in sim_smartbox) to use no conversion, raw ADU values def scale_FEMcurrent(value, reverse=False, pcb_version=0): """ Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw value to mA. Note that for now, this returns the value unchanged, in both directions, until we settle on a final representation. :param value: raw register contents as a value from 0-65535, or crude estimate of the current in Amps :param reverse: Boolean, True to perform physical->raw conversion instead of raw->physical :param pcb_version: integer PCB version number, 0-65535 :return: output_value in mA """ return value def scale_48vcurrent(value, reverse=False, pcb_version=0): """ Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw value to Amps (if reverse=False), or convert a value in Amps to raw (if reverse=True). For now, raw values are hundredths of an Amp, positive only. :param value: raw register contents as a value from 0-65535, or current in Amps :param reverse: Boolean, True to perform physical->raw conversion instead of raw->physical :param pcb_version: integer PCB version number, 0-65535 :return: output_value in Amps """ if reverse: return int(value * 100) & 0xFFFF else: return value / 100.0
# # PySNMP MIB module CISCO-VOICE-CAS-MODULE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-CAS-MODULE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:02:23 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") EntPhysicalIndexOrZero, = mibBuilder.importSymbols("CISCO-TC", "EntPhysicalIndexOrZero") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") IpAddress, Counter32, TimeTicks, Gauge32, Unsigned32, MibIdentifier, Bits, iso, ObjectIdentity, Counter64, ModuleIdentity, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Counter32", "TimeTicks", "Gauge32", "Unsigned32", "MibIdentifier", "Bits", "iso", "ObjectIdentity", "Counter64", "ModuleIdentity", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32") TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus") ciscoVoiceCasModuleMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 389)) ciscoVoiceCasModuleMIB.setRevisions(('2004-03-15 00:00',)) if mibBuilder.loadTexts: ciscoVoiceCasModuleMIB.setLastUpdated('200403150000Z') if mibBuilder.loadTexts: ciscoVoiceCasModuleMIB.setOrganization('Cisco Systems, Inc.') ciscoVoiceCasModuleNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 0)) ciscoVoiceCasModuleObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 1)) cvcmCasConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1)) class CvcmCasPatternBitPosition(TextualConvention, Bits): status = 'current' namedValues = NamedValues(("dBit", 0), ("cBit", 1), ("bBit", 2), ("aBit", 3)) class CvcmCasBitAction(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) namedValues = NamedValues(("casBitNoAction", 1), ("casBitSetToZero", 2), ("casBitSetToOne", 3), ("casBitInvertBit", 4), ("casBitInvertABit", 5), ("casBitInvertBBit", 6), ("casBitInvertCBit", 7), ("casBitInvertDBit", 8), ("casBitABit", 9), ("casBitBBit", 10), ("casBitCBit", 11), ("casBitDBit", 12)) cvcmABCDBitTemplateConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1), ) if mibBuilder.loadTexts: cvcmABCDBitTemplateConfigTable.setStatus('current') cvcmABCDBitTemplateConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-VOICE-CAS-MODULE-MIB", "cvcmModuleIndex"), (0, "CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasTemplateIndex"), (0, "CISCO-VOICE-CAS-MODULE-MIB", "cvcmABCDPatternIndex")) if mibBuilder.loadTexts: cvcmABCDBitTemplateConfigEntry.setStatus('current') cvcmModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: cvcmModuleIndex.setStatus('current') cvcmCasTemplateIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: cvcmCasTemplateIndex.setStatus('current') cvcmABCDPatternIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))) if mibBuilder.loadTexts: cvcmABCDPatternIndex.setStatus('current') cvcmModulePhysicalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 4), EntPhysicalIndexOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: cvcmModulePhysicalIndex.setStatus('current') cvcmCasTemplateName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 5), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasTemplateName.setStatus('current') cvcmABCDIncomingPattern = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 6), CvcmCasPatternBitPosition()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmABCDIncomingPattern.setStatus('current') cvcmABCDOutgoingPattern = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 7), CvcmCasPatternBitPosition()).setMaxAccess("readonly") if mibBuilder.loadTexts: cvcmABCDOutgoingPattern.setStatus('current') cvcmCasABitAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 8), CvcmCasBitAction().clone('casBitABit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasABitAction.setStatus('current') cvcmCasBBitAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 9), CvcmCasBitAction().clone('casBitBBit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasBBitAction.setStatus('current') cvcmCasCBitAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 10), CvcmCasBitAction().clone('casBitCBit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasCBitAction.setStatus('current') cvcmCasDBitAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 11), CvcmCasBitAction().clone('casBitDBit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasDBitAction.setStatus('current') cvcmCasBitRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 12), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasBitRowStatus.setStatus('current') cvcmMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2)) cvcmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 1)) cvcmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 2)) ciscoVoiceCasModuleMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 2, 1)).setObjects(("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasBitGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVoiceCasModuleMIBCompliance = ciscoVoiceCasModuleMIBCompliance.setStatus('current') cvcmCasBitGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 1, 1)).setObjects(("CISCO-VOICE-CAS-MODULE-MIB", "cvcmModulePhysicalIndex"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasTemplateName"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmABCDIncomingPattern"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmABCDOutgoingPattern"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasABitAction"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasBBitAction"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasCBitAction"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasDBitAction"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasBitRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cvcmCasBitGroup = cvcmCasBitGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-VOICE-CAS-MODULE-MIB", cvcmModulePhysicalIndex=cvcmModulePhysicalIndex, ciscoVoiceCasModuleMIB=ciscoVoiceCasModuleMIB, cvcmModuleIndex=cvcmModuleIndex, CvcmCasBitAction=CvcmCasBitAction, cvcmMIBCompliances=cvcmMIBCompliances, PYSNMP_MODULE_ID=ciscoVoiceCasModuleMIB, cvcmABCDOutgoingPattern=cvcmABCDOutgoingPattern, cvcmCasTemplateName=cvcmCasTemplateName, cvcmABCDIncomingPattern=cvcmABCDIncomingPattern, cvcmCasABitAction=cvcmCasABitAction, cvcmCasCBitAction=cvcmCasCBitAction, cvcmCasTemplateIndex=cvcmCasTemplateIndex, cvcmABCDPatternIndex=cvcmABCDPatternIndex, ciscoVoiceCasModuleMIBCompliance=ciscoVoiceCasModuleMIBCompliance, cvcmABCDBitTemplateConfigEntry=cvcmABCDBitTemplateConfigEntry, cvcmCasBitGroup=cvcmCasBitGroup, ciscoVoiceCasModuleNotifs=ciscoVoiceCasModuleNotifs, cvcmCasConfig=cvcmCasConfig, cvcmMIBConformance=cvcmMIBConformance, cvcmCasBitRowStatus=cvcmCasBitRowStatus, ciscoVoiceCasModuleObjects=ciscoVoiceCasModuleObjects, CvcmCasPatternBitPosition=CvcmCasPatternBitPosition, cvcmCasBBitAction=cvcmCasBBitAction, cvcmABCDBitTemplateConfigTable=cvcmABCDBitTemplateConfigTable, cvcmMIBGroups=cvcmMIBGroups, cvcmCasDBitAction=cvcmCasDBitAction)
# # PySNMP MIB module CISCOSB-rlInterfaces (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-rlInterfaces # Produced by pysmi-0.3.4 at Wed May 1 12:24:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") rlIfInterfaces, switch001 = mibBuilder.importSymbols("CISCOSB-MIB", "rlIfInterfaces", "switch001") InterfaceIndexOrZero, ifIndex, InterfaceIndex = mibBuilder.importSymbols("IF-MIB", "InterfaceIndexOrZero", "ifIndex", "InterfaceIndex") PortList, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "PortList") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter32, Gauge32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Bits, iso, ObjectIdentity, TimeTicks, IpAddress, ModuleIdentity, MibIdentifier, NotificationType, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Gauge32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Bits", "iso", "ObjectIdentity", "TimeTicks", "IpAddress", "ModuleIdentity", "MibIdentifier", "NotificationType", "Integer32") RowStatus, DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TruthValue", "TextualConvention") swInterfaces = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43)) swInterfaces.setRevisions(('2013-04-01 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: swInterfaces.setRevisionsDescriptions(('Added MODULE-IDENTITY',)) if mibBuilder.loadTexts: swInterfaces.setLastUpdated('201304010000Z') if mibBuilder.loadTexts: swInterfaces.setOrganization('Cisco Small Business') if mibBuilder.loadTexts: swInterfaces.setContactInfo('Postal: 170 West Tasman Drive San Jose , CA 95134-1706 USA Website: Cisco Small Business Home http://www.cisco.com/smb>;, Cisco Small Business Support Community <http://www.cisco.com/go/smallbizsupport>') if mibBuilder.loadTexts: swInterfaces.setDescription('The private MIB module definition for Switch Interfaces.') class AutoNegCapabilitiesBits(TextualConvention, Bits): description = 'Auto negotiation capabilities bits.' status = 'current' namedValues = NamedValues(("default", 0), ("unknown", 1), ("tenHalf", 2), ("tenFull", 3), ("fastHalf", 4), ("fastFull", 5), ("gigaHalf", 6), ("gigaFull", 7), ("tenGigaFull", 8)) swIfTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1), ) if mibBuilder.loadTexts: swIfTable.setStatus('current') if mibBuilder.loadTexts: swIfTable.setDescription('Switch media specific information and configuration of the device interfaces.') swIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1), ).setIndexNames((0, "CISCOSB-rlInterfaces", "swIfIndex")) if mibBuilder.loadTexts: swIfEntry.setStatus('current') if mibBuilder.loadTexts: swIfEntry.setDescription('Defines the contents of each line in the swIfTable table.') swIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfIndex.setStatus('current') if mibBuilder.loadTexts: swIfIndex.setDescription('Index to the swIfTable. The interface defined by a particular value of this index is the same interface as identified by the same value of ifIndex (MIB II).') swIfPhysAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("default", 1), ("reserve", 2))).clone('default')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPhysAddressType.setStatus('obsolete') if mibBuilder.loadTexts: swIfPhysAddressType.setDescription(' This variable indicates whether the physical address assigned to this interface should be the default one or be chosen from the set of reserved physical addresses of the device.') swIfDuplexAdminMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("half", 2), ("full", 3))).clone('none')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfDuplexAdminMode.setStatus('current') if mibBuilder.loadTexts: swIfDuplexAdminMode.setDescription("This variable specifies whether this interface should operate in half duplex or full duplex mode. This specification will take effect only if swIfSpeedDuplexAutoNegotiation is disabled. A value of 'none' is returned if a value of the variable hasn't been set.") swIfDuplexOperMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("half", 1), ("full", 2), ("hybrid", 3), ("unknown", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfDuplexOperMode.setStatus('current') if mibBuilder.loadTexts: swIfDuplexOperMode.setDescription(' This variable indicates whether this interface operates in half duplex or full duplex mode. This variable can have the values hybrid or unknown only for a trunk. unknown - only if trunk operative status is not present.') swIfBackPressureMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfBackPressureMode.setStatus('current') if mibBuilder.loadTexts: swIfBackPressureMode.setDescription('This variable indicates whether this interface activates back pressure when congested.') swIfTaggedMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfTaggedMode.setStatus('current') if mibBuilder.loadTexts: swIfTaggedMode.setDescription('If enable, this interface operates in tagged mode, i.e all frames sent out through this interface will have the 802.1Q header. If disabled the frames will not be tagged.') swIfTransceiverType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("regular", 1), ("fiberOptics", 2), ("comboRegular", 3), ("comboFiberOptics", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfTransceiverType.setStatus('current') if mibBuilder.loadTexts: swIfTransceiverType.setDescription(' This variable indicates the transceiver type of this interface.') swIfLockAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2))).clone('unlocked')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfLockAdminStatus.setStatus('current') if mibBuilder.loadTexts: swIfLockAdminStatus.setDescription('This variable indicates whether this interface should operate in locked or unlocked mode. In unlocked mode the device learns all MAC addresses from this port and forwards all frames arrived at this port. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') swIfLockOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfLockOperStatus.setStatus('current') if mibBuilder.loadTexts: swIfLockOperStatus.setDescription('This variable defines whether this interface operates in locked or unlocked mode. It is locked in each of the following two cases: 1) if swLockAdminStatus is set to locked 2) no IP/IPX interface is defined over this interface and no VLAN contains this interface. In unlocked mode the device learns all MAC addresses from this port and forwards all frames arrived at this port. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') swIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("eth10M", 1), ("eth100M", 2), ("eth1000M", 3), ("eth10G", 4), ("unknown", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfType.setStatus('current') if mibBuilder.loadTexts: swIfType.setDescription(' This variable specifies the type of interface.') swIfDefaultTag = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfDefaultTag.setStatus('current') if mibBuilder.loadTexts: swIfDefaultTag.setDescription('This variable specifies the default VLAN tag which will be attached to outgoing frames if swIfTaggedMode for this interface is enabled.') swIfDefaultPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfDefaultPriority.setStatus('current') if mibBuilder.loadTexts: swIfDefaultPriority.setDescription(' This variable specifies the default port priority.') swIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 13), RowStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfStatus.setStatus('current') if mibBuilder.loadTexts: swIfStatus.setDescription('The status of a table entry. It is used to delete an entry from this table.') swIfFlowControlMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("on", 1), ("off", 2), ("autoNegotiation", 3), ("enabledRx", 4), ("enabledTx", 5)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfFlowControlMode.setStatus('current') if mibBuilder.loadTexts: swIfFlowControlMode.setDescription("on - Flow control will be enabled on this interface according to the IEEE 802.3x standard. off - Flow control is disabled. autoNegotiation - Flow control will be enabled or disabled on this interface. If enabled, it will operate as specified by the IEEE 802.3x standard. enabledRx - Flow control will be enabled on this interface for recieved frames. enabledTx - Flow control will be enabled on this interface for transmitted frames. An attempt to set this object to 'enabledRx(4)' or 'enabledTx(5)' will fail on interfaces that do not support operation at greater than 100 Mb/s. In any case, flow control can work only if swIfDuplexOperMode is full.") swIfSpeedAdminMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 15), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSpeedAdminMode.setStatus('current') if mibBuilder.loadTexts: swIfSpeedAdminMode.setDescription("This variable specifies the required speed of this interface in bits per second. This specification will take effect only if swIfSpeedDuplexAutoNegotiation is disabled. A value of 10 is returned for 10G. A value of 0 is returned if the value of the variable hasn't been set.") swIfSpeedDuplexAutoNegotiation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSpeedDuplexAutoNegotiation.setStatus('current') if mibBuilder.loadTexts: swIfSpeedDuplexAutoNegotiation.setDescription('If enabled the speed and duplex mode will be set by the device through the autonegotiation process. Otherwise these characteristics will be set according to the values of swIfSpeedAdminMode and swIfSpeedDuplexAutoNegotiation.') swIfOperFlowControlMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("on", 1), ("off", 2), ("enabledRx", 3), ("enabledTx", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperFlowControlMode.setStatus('current') if mibBuilder.loadTexts: swIfOperFlowControlMode.setDescription('on - Flow control is enabled on this interface according to the IEEE 802.3x standard. off - Flow control is disabled. enabledRx - Flow control is enabled on this interface for recieved frames. enabledTx - Flow control is enabled on this interface for transmitted frames.') swIfOperSpeedDuplexAutoNegotiation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ("hybrid", 3), ("unknown", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiation.setStatus('current') if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiation.setDescription('If enabled the speed and duplex are determined by the device through the autonegotiation process. If disabled these characteristics are determined according to the values of swIfSpeedAdminMode and swIfDuplexAdminMode. hybrid - only for a trunk. unknown - only for ports that there operative status is not present.') swIfOperBackPressureMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2), ("hybrid", 3), ("unknown", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperBackPressureMode.setStatus('current') if mibBuilder.loadTexts: swIfOperBackPressureMode.setDescription('This variable indicates the operative back pressure mode of this interface.') swIfAdminLockAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminLockAction.setStatus('current') if mibBuilder.loadTexts: swIfAdminLockAction.setDescription('This variable indicates which action this interface should be taken in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') swIfOperLockAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperLockAction.setStatus('current') if mibBuilder.loadTexts: swIfOperLockAction.setDescription('This variable indicates which action this interface actually takes in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') swIfAdminLockTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 22), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminLockTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfAdminLockTrapEnable.setDescription('This variable indicates whether to create a SNMP trap in the locked mode.') swIfOperLockTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 23), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperLockTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfOperLockTrapEnable.setDescription('This variable indicates whether a SNMP trap can be created in the locked mode.') swIfOperSuspendedStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 24), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperSuspendedStatus.setStatus('current') if mibBuilder.loadTexts: swIfOperSuspendedStatus.setDescription('This variable indicates whether the port is suspended or not due to some feature. After reboot this value is false') swIfLockOperTrapCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 25), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfLockOperTrapCount.setStatus('current') if mibBuilder.loadTexts: swIfLockOperTrapCount.setDescription("This variable indicates the trap counter status per ifIndex (i.e. number of received packets since the last trap sent due to a packet which was received on this ifIndex). It's relevant only in locked mode while trap is enabled.") swIfLockAdminTrapFrequency = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfLockAdminTrapFrequency.setStatus('current') if mibBuilder.loadTexts: swIfLockAdminTrapFrequency.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap per ifIndex. It's relevant only in locked mode and in trap enabled.") swIfReActivate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 27), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfReActivate.setStatus('current') if mibBuilder.loadTexts: swIfReActivate.setDescription('This variable reactivates (enables) an ifIndex (which was suspended)') swIfAdminMdix = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("cross", 1), ("normal", 2), ("auto", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminMdix.setStatus('current') if mibBuilder.loadTexts: swIfAdminMdix.setDescription('The configuration is on a physical port, not include trunks. cross - The interface should force crossover. normal - The interface should not force crossover. auto - Auto mdix is enabled on the interface.') swIfOperMdix = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("cross", 1), ("normal", 2), ("unknown", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperMdix.setStatus('current') if mibBuilder.loadTexts: swIfOperMdix.setDescription('cross - The interface is in crossover mode. normal - The interface is not in crossover mode. unknown - Only for port that its operative status is not present or down.') swIfHostMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("single", 1), ("multiple", 2), ("multiple-auth", 3))).clone('single')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfHostMode.setStatus('current') if mibBuilder.loadTexts: swIfHostMode.setDescription("This variable indicates the 802.1X host mode of a port. Relevant when the port's 802.1X control is auto. In addtion multiple-auth was added.") swIfSingleHostViolationAdminAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3))).clone('discard')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSingleHostViolationAdminAction.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminAction.setDescription('This variable indicates which action this interface should take in single authorized. Possible actions: discard - every packet is dropped. forwardNormal - every packet is forwarded according to the DST address. discardDisable - drops the first packet and suspends the port.') swIfSingleHostViolationOperAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3))).clone('discard')).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfSingleHostViolationOperAction.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperAction.setDescription('This variable indicates which action this interface actually takes in single authorized. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') swIfSingleHostViolationAdminTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 33), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapEnable.setDescription('This variable indicates whether to create a SNMP trap in single authorized.') swIfSingleHostViolationOperTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 34), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapEnable.setDescription('This variable indicates whether a SNMP trap can be created in the single authorized.') swIfSingleHostViolationOperTrapCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 35), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapCount.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapCount.setDescription("This variable indicates the trap counter status per ifIndex (i.e. number of received packets since the last trap sent due to a packet which was received on this ifIndex). It's relevant only in single authorized while trap is enabled.") swIfSingleHostViolationAdminTrapFrequency = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 36), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1000000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapFrequency.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapFrequency.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap per ifIndex. It's relevant only in single authorized and in trap enabled. A value of 0 means that trap is disabled.") swIfLockLimitationMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("disabled", 1), ("dynamic", 2), ("secure-permanent", 3), ("secure-delete-on-reset", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfLockLimitationMode.setStatus('current') if mibBuilder.loadTexts: swIfLockLimitationMode.setDescription("This variable indicates what is the learning limitation on the locked interface. Possible values: disabled - learning is stopped. The dynamic addresses associated with the port are not aged out or relearned on other port as long as the port is locked. dynamic - dynamic addresses can be learned up to the maximum dynamic addresses allowed on the port. Relearning and aging of the dynamic addresses are enabled. The learned addresses aren't kept after reset. secure-permanent - secure addresses can be learned up to the maximum addresses allowed on the port. Relearning and aging of addresses are disabled. The learned addresses are kept after reset. secure-delete-on-reset - secure addresses can be learned up to the maximum addresses allowed on the port. Relearning and aging of addresses are disabled. The learned addresses are not kept after reset.") swIfLockMaxMacAddresses = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 38), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfLockMaxMacAddresses.setStatus('current') if mibBuilder.loadTexts: swIfLockMaxMacAddresses.setDescription("This variable defines the maximum number of dynamic addresses that can be asscoiated with the locked interface. It isn't relevant in disabled limitation mode.") swIfLockMacAddressesCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 39), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfLockMacAddressesCount.setStatus('current') if mibBuilder.loadTexts: swIfLockMacAddressesCount.setDescription("This variable indicates the actual number of dynamic addresses that can be asscoiated with the locked interface. It isn't relevant in disabled limitation mode.") swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 40), AutoNegCapabilitiesBits().clone(namedValues=NamedValues(("default", 0)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities.setDescription("Administrative auto negotiation capabilities of the interface that can be advertised when swIfSpeedDuplexAutoNegotiation is enabled. default bit means advertise all the port's capabilities according to its type.") swIfOperSpeedDuplexAutoNegotiationLocalCapabilities = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 41), AutoNegCapabilitiesBits()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiationLocalCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiationLocalCapabilities.setDescription('Operative auto negotiation capabilities of the remote link. unknown bit means that port operative status is not up.') swIfSpeedDuplexNegotiationRemoteCapabilities = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 42), AutoNegCapabilitiesBits()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfSpeedDuplexNegotiationRemoteCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfSpeedDuplexNegotiationRemoteCapabilities.setDescription('Operative auto negotiation capabilities of the remote link. unknown bit means that port operative status is not up, or auto negotiation process not complete, or remote link is not auto negotiation able.') swIfAdminComboMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 43), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("force-fiber", 1), ("force-copper", 2), ("prefer-fiber", 3), ("prefer-copper", 4))).clone('prefer-fiber')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminComboMode.setStatus('current') if mibBuilder.loadTexts: swIfAdminComboMode.setDescription('This variable specifies the administrative mode of a combo Ethernet interface.') swIfOperComboMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 44), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("fiber", 1), ("copper", 2), ("unknown", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperComboMode.setStatus('current') if mibBuilder.loadTexts: swIfOperComboMode.setDescription('This variable specifies the operative mode of a combo Ethernet interface.') swIfAutoNegotiationMasterSlavePreference = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 45), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("preferMaster", 1), ("preferSlave", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAutoNegotiationMasterSlavePreference.setStatus('current') if mibBuilder.loadTexts: swIfAutoNegotiationMasterSlavePreference.setDescription('This variable specifies the administrative mode of the Maste-Slave preference in auto negotiation.') swIfMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfMibVersion.setStatus('current') if mibBuilder.loadTexts: swIfMibVersion.setDescription("The swIfTable Mib's version, the current version is 3.") swIfPortLockSupport = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("supported", 1), ("notSupported", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfPortLockSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockSupport.setDescription('indicates if the locked port package is supported.') swIfPortLockActionSupport = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfPortLockActionSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockActionSupport.setDescription('indicates which port lock actions are supported: (bit 0 is the most significant bit) bit 0 - discard bit 1 - forwardNormal bit 2 - discardDisable') swIfPortLockTrapSupport = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfPortLockTrapSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockTrapSupport.setDescription('indicates with which port lock actions the trap option is supported (e.g. discard indicates that trap is supported only when the portlock action is discard): (bit 0 is the most significant bit) bit 0 - discard bit 1 - forwardNormal bit 2 - discardDisable') swIfPortLockIfRangeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6), ) if mibBuilder.loadTexts: swIfPortLockIfRangeTable.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTable.setDescription('Port lock interfaces range configuration') swIfPortLockIfRangeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1), ).setIndexNames((0, "CISCOSB-rlInterfaces", "swIfPortLockIfRangeIndex")) if mibBuilder.loadTexts: swIfPortLockIfRangeEntry.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeEntry.setDescription('Defines the contents of each line in the swIfPortLockIfRangeTable table.') swIfPortLockIfRangeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfPortLockIfRangeIndex.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeIndex.setDescription('Index to the swIfPortLockIfRangeTable.') swIfPortLockIfRange = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 2), PortList()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRange.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRange.setDescription('The set of interfaces to which the port lock parameters should be configured') swIfPortLockIfRangeLockStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2))).clone('unlocked')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRangeLockStatus.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeLockStatus.setDescription('This variable indicates whether the interfaces range should operate in locked or unlocked mode. In unlocked mode the device learns all MAC addresses from these interfaces and forwards all frames arrived at these interfaces. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') swIfPortLockIfRangeAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRangeAction.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeAction.setDescription('This variable indicates which action for these interfaces should be take in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') swIfPortLockIfRangeTrapEn = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 5), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRangeTrapEn.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTrapEn.setDescription('This variable indicates whether to create a SNMP trap in the locked mode.') swIfPortLockIfRangeTrapFreq = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRangeTrapFreq.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTrapFreq.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap for these interfaces. It's relevant only in locked mode and in trap enabled.") swIfExtTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7), ) if mibBuilder.loadTexts: swIfExtTable.setStatus('current') if mibBuilder.loadTexts: swIfExtTable.setDescription('Display information and configuration of the device interfaces.') swIfExtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: swIfExtEntry.setStatus('current') if mibBuilder.loadTexts: swIfExtEntry.setDescription('Defines the contents of each row in the swIfExtTable.') swIfExtSFPSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("default", 1), ("eth100M", 2), ("eth1G", 3))).clone('default')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfExtSFPSpeed.setStatus('current') if mibBuilder.loadTexts: swIfExtSFPSpeed.setDescription('Configure speed of an SFP Ethernet interface.') rlIfMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfMibVersion.setStatus('current') if mibBuilder.loadTexts: rlIfMibVersion.setDescription("MIB's version, the current version is 1.") rlIfNumOfPhPorts = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfNumOfPhPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfPhPorts.setDescription('Total number of physical ports on this device (including all stack units)') rlIfMapOfOnPhPorts = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 3), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfMapOfOnPhPorts.setStatus('current') if mibBuilder.loadTexts: rlIfMapOfOnPhPorts.setDescription("Each bit in this octet string indicates that the correspondig port's ifOperStatus is ON if set. The mapping of port number to bits in this octet string is as follows: The port with the L2 interface number 1 is mapped to the least significant bit of the 1st octet, the port with L2 ifNumber 2 to the next significant bit in the 1st octet, port 8 to the most-significant bit of the in the 1st octet, port 9 to the least significant bit of the 2nd octet, etc. and in general, port n to bit corresponding to 2**((n mod 8) -1) in byte n/8 + 1") rlIfClearPortMibCounters = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 4), PortList()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfClearPortMibCounters.setStatus('current') if mibBuilder.loadTexts: rlIfClearPortMibCounters.setDescription('Each bit that is set in this portList represent a port that its mib counters should be reset.') rlIfNumOfUserDefinedPorts = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfNumOfUserDefinedPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfUserDefinedPorts.setDescription('The number of user defined ports on this device.') rlIfFirstOutOfBandIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfFirstOutOfBandIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfFirstOutOfBandIfIndex.setDescription('First ifIndex of out-of-band port. This scalar exists only the device has out of band ports.') rlIfNumOfLoopbackPorts = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfNumOfLoopbackPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfLoopbackPorts.setDescription('The number of loopback ports on this device.') rlIfFirstLoopbackIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfFirstLoopbackIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfFirstLoopbackIfIndex.setDescription('First ifIndex of loopback port. This scalar will exists only if rlIfNumOfLoopbackPorts is different from 0.') rlIfExistingPortList = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 9), PortList()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfExistingPortList.setStatus('current') if mibBuilder.loadTexts: rlIfExistingPortList.setDescription("Indicates which ports/trunks exist in the system. It doesn't indicate which are present.") rlIfBaseMACAddressPerIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 10), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfBaseMACAddressPerIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfBaseMACAddressPerIfIndex.setDescription('Indicates if the system will assign a unique MAC per Ethernet port or not.') rlFlowControlCascadeMode = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlFlowControlCascadeMode.setStatus('current') if mibBuilder.loadTexts: rlFlowControlCascadeMode.setDescription('enable disable flow control on cascade ports') rlFlowControlCascadeType = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("internalonly", 1), ("internalexternal", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlFlowControlCascadeType.setStatus('current') if mibBuilder.loadTexts: rlFlowControlCascadeType.setDescription('define which type of ports will be affected by flow control on cascade ports') rlFlowControlRxPerSystem = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 13), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlFlowControlRxPerSystem.setStatus('current') if mibBuilder.loadTexts: rlFlowControlRxPerSystem.setDescription('define if flow control RX is supported per system.') rlCascadePortProtectionAction = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 14), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlCascadePortProtectionAction.setStatus('current') if mibBuilder.loadTexts: rlCascadePortProtectionAction.setDescription('As a result of this set all of the local cascade ports will stop being consider unstable and will be force up.') rlManagementIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 15), InterfaceIndex()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlManagementIfIndex.setStatus('current') if mibBuilder.loadTexts: rlManagementIfIndex.setDescription('Specify L2 bound management interface index in a single IP address system when configurable management interface is supported.') rlIfClearStackPortsCounters = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 16), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfClearStackPortsCounters.setStatus('current') if mibBuilder.loadTexts: rlIfClearStackPortsCounters.setDescription('As a result of this set all counters of all external cascade ports will be cleared.') rlIfClearPortMacAddresses = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 17), InterfaceIndexOrZero()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfClearPortMacAddresses.setStatus('current') if mibBuilder.loadTexts: rlIfClearPortMacAddresses.setDescription('if port is non secure, its all dynamic MAC addresses are cleared. if port is secure, its all secure MAC addresses which have learned or configured are cleared.') rlIfCutThroughPacketLength = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(257, 16383)).clone(1522)).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutThroughPacketLength.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughPacketLength.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode.') rlIfCutPriorityZero = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 19), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityZero.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityZero.setDescription('Enable or disable cut-Through for priority 0.') rlIfCutPriorityOne = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 20), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityOne.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityOne.setDescription('Enable or disable cut-Through for priority 1.') rlIfCutPriorityTwo = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 21), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityTwo.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityTwo.setDescription('Enable or disable cut-Through for priority 2.') rlIfCutPriorityThree = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 22), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityThree.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityThree.setDescription('Enable or disable cut-Through for priority 3.') rlIfCutPriorityFour = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 23), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityFour.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityFour.setDescription('Enable or disable cut-Through for priority 4.') rlIfCutPriorityFive = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 24), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityFive.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityFive.setDescription('Enable or disable cut-Through for priority 5.') rlIfCutPrioritySix = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 25), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPrioritySix.setStatus('current') if mibBuilder.loadTexts: rlIfCutPrioritySix.setDescription('Enable or disable cut-Through for priority 6.') rlIfCutPrioritySeven = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 26), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPrioritySeven.setStatus('current') if mibBuilder.loadTexts: rlIfCutPrioritySeven.setDescription('Enable or disable cut-Through for priority 7.') rlIfCutThroughTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27), ) if mibBuilder.loadTexts: rlIfCutThroughTable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughTable.setDescription('Information and configuration of cut-through feature.') rlIfCutThroughEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1), ).setIndexNames((0, "CISCOSB-rlInterfaces", "swIfIndex")) if mibBuilder.loadTexts: rlIfCutThroughEntry.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughEntry.setDescription('Defines the contents of each line in the swIfTable table.') rlIfCutThroughPriorityEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutThroughPriorityEnable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughPriorityEnable.setDescription('Enable or disable cut-through for a priority for an interface.') rlIfCutThroughUntaggedEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutThroughUntaggedEnable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughUntaggedEnable.setDescription('Enable or disable cut-through for untagged packets for an interface.') rlIfCutThroughOperMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 3), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfCutThroughOperMode.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughOperMode.setDescription('Operational mode of spesific cut-through interface.') rlCutThroughPacketLength = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 28), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlCutThroughPacketLength.setStatus('current') if mibBuilder.loadTexts: rlCutThroughPacketLength.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode.') rlCutThroughPacketLengthAfterReset = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 29), Integer32().subtype(subtypeSpec=ValueRangeConstraint(257, 16383)).clone(1522)).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlCutThroughPacketLengthAfterReset.setStatus('current') if mibBuilder.loadTexts: rlCutThroughPacketLengthAfterReset.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode after reset.') rlCutThroughEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 30), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlCutThroughEnable.setStatus('current') if mibBuilder.loadTexts: rlCutThroughEnable.setDescription('Cut-Through global enable mode.') rlCutThroughEnableAfterReset = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 31), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlCutThroughEnableAfterReset.setStatus('current') if mibBuilder.loadTexts: rlCutThroughEnableAfterReset.setDescription('Cut-Through global enable mode after reset.') rlFlowControlMode = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("send-receive", 1), ("receive-only", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlFlowControlMode.setStatus('current') if mibBuilder.loadTexts: rlFlowControlMode.setDescription('Define which mode will be enabled on flow control enabled ports. The interfaces with enabled flow control will receive pause frames, but will not send flow control pause frames Send-receive: The interfaces with enabled flow control will receive and send pause frames. Receive-only: The interfaces with enabled flow control will receive pause frames, but will not send flow control pause frames.') mibBuilder.exportSymbols("CISCOSB-rlInterfaces", rlFlowControlCascadeType=rlFlowControlCascadeType, rlIfNumOfPhPorts=rlIfNumOfPhPorts, rlIfFirstLoopbackIfIndex=rlIfFirstLoopbackIfIndex, rlIfNumOfLoopbackPorts=rlIfNumOfLoopbackPorts, swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities=swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities, PYSNMP_MODULE_ID=swInterfaces, swIfMibVersion=swIfMibVersion, rlIfClearPortMacAddresses=rlIfClearPortMacAddresses, swIfStatus=swIfStatus, swIfOperSpeedDuplexAutoNegotiation=swIfOperSpeedDuplexAutoNegotiation, swIfSingleHostViolationOperTrapCount=swIfSingleHostViolationOperTrapCount, rlIfClearPortMibCounters=rlIfClearPortMibCounters, swIfOperFlowControlMode=swIfOperFlowControlMode, swIfAdminMdix=swIfAdminMdix, swIfDuplexAdminMode=swIfDuplexAdminMode, swIfPortLockTrapSupport=swIfPortLockTrapSupport, swIfPortLockIfRangeIndex=swIfPortLockIfRangeIndex, rlIfClearStackPortsCounters=rlIfClearStackPortsCounters, swIfTransceiverType=swIfTransceiverType, swInterfaces=swInterfaces, swIfPortLockSupport=swIfPortLockSupport, swIfDefaultTag=swIfDefaultTag, swIfSingleHostViolationAdminTrapEnable=swIfSingleHostViolationAdminTrapEnable, swIfTable=swIfTable, rlIfCutPriorityThree=rlIfCutPriorityThree, swIfOperLockTrapEnable=swIfOperLockTrapEnable, rlCascadePortProtectionAction=rlCascadePortProtectionAction, rlFlowControlRxPerSystem=rlFlowControlRxPerSystem, swIfType=swIfType, rlIfCutThroughPriorityEnable=rlIfCutThroughPriorityEnable, rlIfCutPriorityTwo=rlIfCutPriorityTwo, swIfHostMode=swIfHostMode, rlIfCutPriorityFour=rlIfCutPriorityFour, rlCutThroughPacketLengthAfterReset=rlCutThroughPacketLengthAfterReset, rlIfMibVersion=rlIfMibVersion, swIfDuplexOperMode=swIfDuplexOperMode, rlIfCutPrioritySix=rlIfCutPrioritySix, AutoNegCapabilitiesBits=AutoNegCapabilitiesBits, rlIfNumOfUserDefinedPorts=rlIfNumOfUserDefinedPorts, rlIfCutPriorityOne=rlIfCutPriorityOne, swIfPortLockActionSupport=swIfPortLockActionSupport, swIfSpeedAdminMode=swIfSpeedAdminMode, rlIfMapOfOnPhPorts=rlIfMapOfOnPhPorts, swIfSingleHostViolationOperTrapEnable=swIfSingleHostViolationOperTrapEnable, swIfOperLockAction=swIfOperLockAction, rlIfCutPrioritySeven=rlIfCutPrioritySeven, rlFlowControlMode=rlFlowControlMode, rlIfExistingPortList=rlIfExistingPortList, rlManagementIfIndex=rlManagementIfIndex, rlIfCutThroughTable=rlIfCutThroughTable, swIfLockOperStatus=swIfLockOperStatus, swIfAdminLockAction=swIfAdminLockAction, swIfOperComboMode=swIfOperComboMode, swIfBackPressureMode=swIfBackPressureMode, rlCutThroughPacketLength=rlCutThroughPacketLength, swIfDefaultPriority=swIfDefaultPriority, swIfOperBackPressureMode=swIfOperBackPressureMode, rlIfCutThroughPacketLength=rlIfCutThroughPacketLength, swIfOperMdix=swIfOperMdix, rlIfFirstOutOfBandIfIndex=rlIfFirstOutOfBandIfIndex, rlIfCutThroughOperMode=rlIfCutThroughOperMode, swIfOperSpeedDuplexAutoNegotiationLocalCapabilities=swIfOperSpeedDuplexAutoNegotiationLocalCapabilities, rlCutThroughEnable=rlCutThroughEnable, swIfOperSuspendedStatus=swIfOperSuspendedStatus, rlCutThroughEnableAfterReset=rlCutThroughEnableAfterReset, swIfSingleHostViolationAdminTrapFrequency=swIfSingleHostViolationAdminTrapFrequency, swIfAdminLockTrapEnable=swIfAdminLockTrapEnable, swIfPhysAddressType=swIfPhysAddressType, swIfSingleHostViolationOperAction=swIfSingleHostViolationOperAction, swIfExtTable=swIfExtTable, swIfPortLockIfRangeTrapEn=swIfPortLockIfRangeTrapEn, swIfPortLockIfRange=swIfPortLockIfRange, swIfPortLockIfRangeLockStatus=swIfPortLockIfRangeLockStatus, swIfLockAdminStatus=swIfLockAdminStatus, swIfReActivate=swIfReActivate, swIfPortLockIfRangeEntry=swIfPortLockIfRangeEntry, swIfLockMacAddressesCount=swIfLockMacAddressesCount, swIfLockAdminTrapFrequency=swIfLockAdminTrapFrequency, rlIfCutThroughUntaggedEnable=rlIfCutThroughUntaggedEnable, rlIfCutPriorityFive=rlIfCutPriorityFive, swIfAdminComboMode=swIfAdminComboMode, swIfIndex=swIfIndex, swIfPortLockIfRangeAction=swIfPortLockIfRangeAction, swIfFlowControlMode=swIfFlowControlMode, rlIfBaseMACAddressPerIfIndex=rlIfBaseMACAddressPerIfIndex, swIfPortLockIfRangeTrapFreq=swIfPortLockIfRangeTrapFreq, swIfEntry=swIfEntry, swIfSingleHostViolationAdminAction=swIfSingleHostViolationAdminAction, swIfExtSFPSpeed=swIfExtSFPSpeed, swIfPortLockIfRangeTable=swIfPortLockIfRangeTable, rlFlowControlCascadeMode=rlFlowControlCascadeMode, rlIfCutThroughEntry=rlIfCutThroughEntry, swIfTaggedMode=swIfTaggedMode, swIfAutoNegotiationMasterSlavePreference=swIfAutoNegotiationMasterSlavePreference, swIfSpeedDuplexAutoNegotiation=swIfSpeedDuplexAutoNegotiation, swIfLockOperTrapCount=swIfLockOperTrapCount, swIfSpeedDuplexNegotiationRemoteCapabilities=swIfSpeedDuplexNegotiationRemoteCapabilities, swIfExtEntry=swIfExtEntry, swIfLockLimitationMode=swIfLockLimitationMode, swIfLockMaxMacAddresses=swIfLockMaxMacAddresses, rlIfCutPriorityZero=rlIfCutPriorityZero)
def solveQuestion(inputPath): fileP = open(inputPath, 'r') fileLines = fileP.readlines() fileP.close() newPosition = [] numRows = len(fileLines) numCols = len(fileLines[0].strip('\n')) for line in fileLines: currentLine = [] for grid in line.strip('\n'): currentLine.append(grid) newPosition.append(currentLine) lastPosition = [] counter = 0 while lastPosition != newPosition: lastPosition = list(newPosition) newPosition =[] counter += 1 for row in range(numRows): currentLine = [] for col in range(numCols): if lastPosition[row][col] == '.': currentLine.append('.') continue numNeighbors = getNeighbors(lastPosition, row, col, numRows, numCols) if numNeighbors == 0 and lastPosition[row][col] == 'L': currentLine.append('#') elif numNeighbors >= 4 and lastPosition[row][col] == '#': currentLine.append('L') else: currentLine.append(lastPosition[row][col]) newPosition.append(currentLine) totalOccupied = 0 for position in newPosition: totalOccupied += ''.join(position).count('#') return totalOccupied def getNeighbors(lastPosition, row, col, maxRow, maxCol): indexMove = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] counter = 0 for index in indexMove: rowActual = row + index[0] colActual = col + index[1] if rowActual < 0 or colActual < 0: continue if rowActual == maxRow: continue if colActual == maxCol: continue if lastPosition[rowActual][colActual] == '#': counter += 1 return counter print(solveQuestion('InputD11Q1.txt'))
""" The trick here is that I am using the new_ls parameter as a list to append. Since this list is created on first call to the function it is the same object that I append to. """ def rc(ls, new_ls=[]): for x in ls: if isinstance(x, list): rc(x, new_ls) else: new_ls.append(x) return new_ls
n = int(input()) if n%2 != 0: print('Weird') else: if n in range(2, 6): print('Not Weird') if n in range(6, 21): print('Weird') if n > 20: print('Not Weird')
def add_numbers(start, end): total=0 for i in range(start,end+1): total=total+i return total test1 = add_numbers(333, 777) print(test1)
MOD = 10 ** 9 + 7 n, k = map(int, input().split()) dp = [0] * (k + 1) ans = 0 for x in range(k, 0, -1): dp[x] = pow(k // x, n, MOD) for i in range(2 * x, k + 1, x): dp[x] -= dp[i] ans += dp[x] * x ans %= MOD print(ans)
# Bidirectional BFS class Solution(object): def minKnightMoves(self, x, y): offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)] q1 = collections.deque([(0, 0)]) q2 = collections.deque([(x, y)]) steps1 = {(0, 0): 0} #steps needed starting from (0, 0) steps2 = {(x, y): 0} #steps needed starting from (x,y) while q1 and q2: i1, j1 = q1.popleft() if (i1, j1) in steps2: return steps1[(i1, j1)]+steps2[(i1, j1)] i2, j2 = q2.popleft() if (i2, j2) in steps1: return steps1[(i2, j2)]+steps2[(i2, j2)] for ox, oy in offsets: nextI1 = i1+ox nextJ1 = j1+oy if (nextI1, nextJ1) not in steps1: q1.append((nextI1, nextJ1)) steps1[(nextI1, nextJ1)] = steps1[(i1, j1)]+1 nextI2 = i2+ox nextJ2 = j2+oy if (nextI2, nextJ2) not in steps2: q2.append((nextI2, nextJ2)) steps2[(nextI2, nextJ2)] = steps2[(i2, j2)]+1 return float('inf')
class School: def __init__(self): self.list_students = list() self.list_data = list() def add_student(self, name, grade): self.list_students.append({"name": name, "grade": grade}) def roster(self): return self.sort_student_list_by_name_and_grade() def grade(self, grade_number): return self.expect_grade_number_and_return_list_ordered(grade_number) def sort_student_list_by_name_and_grade(self): sorted_list = sorted(self.list_students, key=lambda k: (k['grade'], k['name'])) return self.add_to_a_new_list_student_list(sorted_list) def add_to_a_new_list_student_list(self, list_name): for names_students in list_name: self.list_data.append(names_students["name"]) return self.list_data def expect_grade_number_and_return_list_ordered(self, grade_number): for names_students in self.list_students: if names_students["grade"] == grade_number: self.list_data.append(names_students["name"]) return sorted(self.list_data)
#!/usr/bin/python3 # * Copyright (c) 2020-2021, Happiest Minds Technologies Limited Intellectual Property. All rights reserved. # * # * SPDX-License-Identifier: LGPL-2.1-only PE1_binding_chk = 'ipv4 PE1ID/32 P1ID imp-null' P1_binding_chk1 = 'ipv4 P1ID/32 PE1ID imp-null' P1_binding_chk2 = 'ipv4 P1ID/32 PE2ID imp-null' PE2_binding_chk = 'ipv4 PE2ID/32 P1ID imp-null'
# Url source: # https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list numbers = list(range(1, 50)) for i in numbers: if i < 20: numbers.remove(i) print(numbers)
class Solution: def shortestPathLength(self, graph): def dp(node, mask): state = (node, mask) if state in cache: return cache[state] if mask & (mask - 1) == 0: # Base case - mask only has a single "1", which means # that only one node has been visited (the current node) return 0 cache[state] = float("inf") # Avoid infinite loop in recursion for neighbor in graph[node]: if mask & (1 << neighbor): already_visited = 1 + dp(neighbor, mask) not_visited = 1 + dp(neighbor, mask ^ (1 << node)) cache[state] = min(cache[state], already_visited, not_visited) return cache[state] n = len(graph) ending_mask = (1 << n) - 1 cache = {} return min(dp(node, ending_mask) for node in range(n))
# Em uma competição de salto em distância cada atleta tem direito a cinco saltos. # O resultado do atleta será determinado pela média dos cinco valores restantes. # Você deve fazer um programa que receba o nome e as cinco distâncias alcançadas pelo atleta em seus saltos e depois informe o nome, os saltos e a média dos saltos. # O programa deve ser encerrado quando não for informado o nome do atleta. A saída do programa deve ser conforme o exemplo abaixo: # Atleta: Rodrigo Curvêllo # Primeiro Salto: 6.5 m # Segundo Salto: 6.1 m # Terceiro Salto: 6.2 m # Quarto Salto: 5.4 m # Quinto Salto: 5.3 m # Resultado final: # Atleta: Rodrigo Curvêllo # Saltos: 6.5 - 6.1 - 6.2 - 5.4 - 5.3 # Média dos saltos: 5.9 m dados_gerais = [] while True: nome_atleta = input("Digite o nome do atleta ou nada para continuar: ") if not nome_atleta: break saltos = [] for numero in range(1,6): saltos.append(float(input(f"Digite o valor do salto {numero}: "))) dados_atleta = [] dados_atleta.append(nome_atleta) dados_atleta.append(saltos) dados_gerais.append(dados_atleta) for nome, saltos in dados_gerais: print() print(f"Atleta: {nome}") print() print(f"Primeiro salto: {saltos[0]} m") print(f"Segundo salto: {saltos[1]} m") print(f"Terceiro salto: {saltos[2]} m") print(f"Quarto salto: {saltos[3]} m") print(f"Quinto salto: {saltos[4]} m") # Resultado final: # Atleta: Rodrigo Curvêllo # Saltos: 6.5 - 6.1 - 6.2 - 5.4 - 5.3 # Média dos saltos: 5.9 m print() print("Resultado final: ") print(f"Atleta: {nome} ") print(f"Saltos: {saltos[0]} - {saltos[1]} - {saltos[2]} - {saltos[3]} - {saltos[4]}") print(f"Média dos saltos: {sum(saltos) / len(saltos):.2f} m")
""" 复制的次数等分解质因数的次数,分解质因数的计算,主要有两个,递归和质数求解。 这里要使用 while 进行循环,而不能使用 for 因为 n 的次数会变。 """ class Solution: def minSteps(self, n: int) -> int: res = 0 if n == 1: return res d = 2 while n > 1: while (n % d == 0): res += d n //= d d += 1 return res """ 递归方式求解 如果能整除就调用方法本身,直到返回 0 的时候。 """ class Solution: def minSteps(self, n: int) -> int: res = 0 if n == 1: return res for i in range(2, n): if n % i == 0: return self.minSteps(n // i) + i return n
def format_dict(data, sep_item=", ", sep_key_value="=", brackets=True): output = "" delim = "" for key, value in data.items(): output += f"{delim}{key}{sep_key_value}{value}" delim = f"{sep_item}" return f"{{{output}}}" if brackets else f"{output}" def powerdict(data): # https://stackoverflow.com/a/1482320 n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield {key: data[key] for mask, key in zip(masks, data) if i & mask} def powerset(data): # https://stackoverflow.com/a/1482320 n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield {element for mask, element in zip(masks, data) if i & mask} def powerlist(data): # https://stackoverflow.com/a/1482320 n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield [element for mask, element in zip(masks, data) if i & mask] def issubdict(a, b): return all(key in b for key in a.keys()) and all(b[key] == value for key, value in a.items())
#!/usr/bin/env python3 # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # These are the snippets shown during the demo videos in C2M2 # Each snippet is followed by the corresponding output when executed in the # Python interpreter. # >>> file = open("spider.txt") # >>> print(file.readline()) # The itsy bitsy spider climbed up the waterspout. # # >>> print(file.readline()) # Down came the rain # # >>> print(file.read()) # and washed the spider out. # Out came the sun # and dried up all the rain # and the itsy bitsy spider climbed up the spout again. # # >>> file.close() # # >>> with open("spider.txt") as file: # ... print(file.readline()) # ... # The itsy bitsy spider climbed up the waterspout. # # >>> with open("spider.txt") as file: # ... for line in file: # ... print(line.upper()) # ... # # THE ITSY BITSY SPIDER CLIMBED UP THE WATERSPOUT. # # DOWN CAME THE RAIN # # AND WASHED THE SPIDER OUT. # # OUT CAME THE SUN # # AND DRIED UP ALL THE RAIN # # AND THE ITSY BITSY SPIDER CLIMBED UP THE SPOUT AGAIN. # # # >>> with open("spider.txt") as file: # ... for line in file: # ... print(line.strip().upper()) # ... # THE ITSY BITSY SPIDER CLIMBED UP THE WATERSPOUT. # DOWN CAME THE RAIN # AND WASHED THE SPIDER OUT. # OUT CAME THE SUN # AND DRIED UP ALL THE RAIN # AND THE ITSY BITSY SPIDER CLIMBED UP THE SPOUT AGAIN. # # >>> file = open("spider.txt") # >>> lines = file.readlines() # >>> file.close() # >>> lines.sort() # >>> print(lines) # ['Down came the rain\n', 'Out came the sun\n', 'The itsy bitsy spider climbed up the waterspout.\n', 'and dried up all the rain\n', 'and the itsy bitsy spider climbed up the spout again.\n', 'and washed the spider out.\n'] # # >>> with open("novel.txt", "w") as file: # ... file.write("It was a dark and stormy night") # ... # 30 # # >>> import os # >>> os.remove("novel.txt") # >>> # # >>> os.remove("novel.txt") # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # FileNotFoundError: [Errno 2] No such file or directory: 'novel.txt' # # >>> os.rename("first_draft.txt", "finished_masterpiece.txt") # >>> # # # >>> os.path.exists("finished_masterpiece.txt") # True # >>> os.path.exists("userlist.txt") # False # # >>> os.path.getsize("spider.txt") # 192 # # >>> os.path.getmtime("spider.txt") # 1556990746.582071 # # >>> import datetime # >>> timestamp = os.path.getmtime("spider.txt") # >>> datetime.datetime.fromtimestamp(timestamp) # datetime.datetime(2019, 5, 4, 19, 25, 46, 582071) # # >>> os.path.abspath("spider.txt") # '/home/user/spider.txt' # # >>> print(os.getcwd()) # /home/user # # # >>> os.mkdir("new_dir") # >>> os.chdir("new_dir") # # >>> os.getcwd() # '/home/user/new_dir' # # >>> os.mkdir("newer_dir") # >>> os.rmdir("newer_dir") # # >>> import os # >>> os.listdir("website") # ['index.html', 'images', 'favicon.ico'] # dir = "website" for name in os.listdir(dir): fullname = os.path.join(dir, name) if os.path.isdir(fullname): print("{} is a directory".format(fullname)) else: print("{} is a file".format(fullname)) # >>> dir = "website" # >>> for name in os.listdir(dir): # ... fullname = os.path.join(dir, name) # ... if os.path.isdir(fullname): # ... print("{} is a directory".format(fullname)) # ... else: # ... print("{} is a file".format(fullname)) # ... # website/index.html is a file # website/images is a directory # website/favicon.ico is a file # # # CSV files # # --------- # # >>> import csv # >>> f = open("csv_file.txt") # >>> csv_f = csv.reader(f) # >>> for row in csv_f: # ... name, phone, role = row # ... print("Name: {}, Phone: {}, Role: {}".format(name, phone, role)) # ... # Name: Sabrina Green, Phone: 802-867-5309, Role: System Administrator # Name: Eli Jones, Phone: 684-3481127, Role: IT specialist # Name: Melody Daniels, Phone: 846-687-7436, Role: Programmer # Name: Charlie Rivera, Phone: 698-746-3357, Role: Web Developer # # >>> f.close() # # >>> hosts = [["workstation.local", "192.168.25.46"],["webserver.cloud", "10.2.5.6"]] # >>> with open('hosts.csv', 'w') as hosts_csv: # ... writer = csv.writer(hosts_csv) # ... writer.writerows(hosts) # ... # with open('software.csv') as software: reader = csv.DictReader(software) for row in reader: print(("{} has {} users").format(row["name"], row["users"])) # >>> with open('software.csv') as software: # ... reader = csv.DictReader(software) # ... for row in reader: # ... print(("{} has {} users").format(row["name"], row["users"])) # ... # MailTree has 324 users # CalDoor has 22 users # Chatty Chicken has 4 users # # # users = [ {"name": "Sol Mansi", "username": "solm", "department": "IT infrastructure"}, # {"name": "Lio Nelson", "username": "lion", "department": "User Experience Research"}, # {"name": "Charlie Grey", "username": "greyc", "department": "Development"}] # keys = ["name", "username", "department"] # with open('by_department.csv', 'w') as by_department: # writer = csv.DictWriter(by_department, fieldnames=keys) # writer.writeheader() # writer.writerows(users)
class Auxiliar:#Ira auxiliar as buscas #--------------------------Auxilia nas Buscas sem informação----------------------------------- def expande(self, no, problema, tipo): #Expandira o nó Conjfilhos = [] #Conjunto de Filhos possibilidades = problema.acoes(no, tipo) #Possibilidades de filhos if(possibilidades !=[]): for acoes in range(len(possibilidades)): #Caminhos possiveis nofilho = No() nofilho._init_(possibilidades[acoes],no,no.custo + problema.custo_do_passo, no.profundidade + 1) Conjfilhos.append(nofilho) #Adicionando o filhos return Conjfilhos estado_inicial = [] # gerar matriz inicial indice = 8 for l in range(indice): linha = [] for c in range(indice): linha.append("'x'") estado_inicial.append(linha) def matrizprint(self,matriz): #Printar a matriz for i in range(len(matriz)): for j in range(len(matriz)): print(matriz[i][j], end="") print() print("\n") def caminhos(self, no): #Mostrar o caminho, caso necessario caminho = [] while(no!=None): caminho.append(no) no = no.pai return caminho def detectaQs(self, auxMatriz, linha, coluna): #Funcao para detectar se tem ataques cont = 0 for l in range(len(auxMatriz)): if(auxMatriz[l][coluna] == auxMatriz[linha][coluna]): cont+=1 for c in range(len(auxMatriz)): if(linha == l): if(auxMatriz[linha][c] == auxMatriz[linha][coluna]): cont+=1 #Principal #For seguindo c=coluna for l in range(linha,len(auxMatriz), 1): if(c!=len(auxMatriz)): if(auxMatriz[linha][coluna] == auxMatriz[l][c]): cont+=1 c+=1 #For voltando c = coluna for l in range(linha, -1, -1): if(c!=-1): if(auxMatriz[linha][coluna] == auxMatriz[l][c]): cont+=1 c-=1 #Secundaria #For voltando c= coluna for l in range(linha, len(auxMatriz), 1): if(c!=-1): if(auxMatriz[linha][coluna] == auxMatriz[l][c]): cont+=1 c-=1 #For seguindo c = coluna for l in range(linha, -1, -1): if(c!=len(auxMatriz)): if(auxMatriz[linha][coluna] == auxMatriz[l][c]): cont+=1 c+=1 return cont-6 #--------------------------Auxilia nas Buscas Locais----------------------------------- def achaQ(self, matriz, col): #Funcao para achar a linha da rainha for linha in range(len(matriz)): if (matriz[linha][col]=="'Q'"): return linha def ColunaX(self, matriz, coluna): #Funcao para deletar uma coluna for linha in range(len(matriz)): matriz[linha][coluna]= "'x'" return matriz def conflitos(self,tabuleiro): #Achar os conflitos indiretos e diretos conflitos = copy.deepcopy(tabuleiro) for col in range(len(conflitos)): #Coluna por linha matriz = copy.deepcopy(tabuleiro) matriz = Auxiliar.ColunaX(self,matriz, col)#zera a coluna for lin in range(len(conflitos)): matriz[lin][col] = "'Q'"#Testar Q's Batidas = Auxiliar.detectaQs(self,matriz,lin, col)#Contando as batidas (direta) matriz = Auxiliar.ColunaX(self,matriz, col) #Zerar colunas aux = copy.deepcopy(matriz) #Matriz auxiliar for proxcol in range(len(conflitos)):#Contar as batidas das proximas colunas(indireta) if (proxcol !=col):#Pra ele pular a coluna em que ele está linha = Auxiliar.achaQ(self,aux,proxcol) #Achar o Q da linha Batidas = Batidas + Auxiliar.detectaQs(self,aux,linha, proxcol) aux = Auxiliar.ColunaX(self,aux, proxcol)#Zera a coluna conflitos[lin][col] = Batidas#Matriz de batidas Batidas=0 return conflitos def melhorfilho(self,matriz):#Colocar os melhores filhos na lista menor = 100 for i in range(len(matriz)): for j in range(len(matriz)): if(menor>matriz[i][j]): menor=matriz[i][j] liMenor=[] for i in range(len(matriz)): for j in range(len(matriz)): if(matriz[i][j]==menor): liMenor.append(matriz[i][j]) return liMenor, menor def gerarCusto(self,conflitos, matriz): return conflitos[Auxiliar.achaQ(self,matriz,0)][0] def vizinhos(self, matriz): vizinhos =[] for i in range(len(matriz)): for j in range(len(matriz)): if(matriz[i][j]!="'Q'"): aux = copy.deepcopy(matriz) aux = Auxiliar.ColunaX(self,aux,j) aux[i][j]="'Q'" vizinhos.append(aux) return vizinhos Batidas = [] visitados = [] def expandelocal(self, no): aux = copy.deepcopy(no.estado) liMenor, menor = Auxiliar.melhorfilho(self,Auxiliar.Batidas)#Melhor filho select = randrange(0,len(liMenor))#Selecionar um dos melhores filhos contador = -1 for i in range(len(aux)): for j in range(len(aux)): if(menor == Auxiliar.Batidas[i][j]):#Procurar o melhor filho selecionado contador+=1 #Depende da quantiadade de melhores filhos if(contador==select):#Achou linha = Auxiliar.achaQ(self,aux,j)#Pega linha em que a rainha está aux[linha][j] = "'x'" #Faz a troca aux[i][j] = "'Q'" Auxiliar.Batidas = Auxiliar.conflitos(self,aux) nofilho = No() nofilho._init_(aux,no,Auxiliar.gerarCusto(self, Auxiliar.Batidas, aux), no.profundidade + 1) return nofilho def Peturbar(self, no): vizinhos = Auxiliar.vizinhos(self,no.estado) while(True): select = randrange(0,len(vizinhos)) if(not vizinhos[select] in Auxiliar.visitados): Auxiliar.visitados.append(vizinhos[select]) break Proximo = No() Proximo._init_(vizinhos[select],no,Auxiliar.gerarCusto(self, Auxiliar.conflitos(self,vizinhos[select]),vizinhos[select]),no.profundidade + 1) return Proximo def selectMask(self): a = randrange(0,2) if(a==0): return [0,0,0,0,1,1,1,1] if(a==1): return [1,1,1,0,0,0,0,0] if(a==2): return [1,1,0,0,0,0,1,1]
class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: if grid[0][0] == 1: return -1 def neighbor8(i, j): n = len(grid) for di in (-1, 0, 1): for dj in (-1, 0, 1): if di == dj == 0: continue newi, newj = i + di, j + dj if 0 <= newi < n and 0 <= newj < n and grid[newi][newj] == 0: yield (newi, newj) n = len(grid) ds = [[math.inf] * n for _ in range(n)] queue = collections.deque([(0, 0)]) ds[0][0] = 1 while queue: i, j = queue.popleft() if i == j == n - 1: return ds[n - 1][n - 1] for newi, newj in neighbor8(i, j): if ds[i][j] + 1 < ds[newi][newj]: ds[newi][newj] = ds[i][j] + 1 queue.append((newi, newj)) return -1
# x_4_5 # # 「text」を逆さ読みで表示されるように修正してください number = 0 text = 'ももからうまれた桃太郎' while number < 11: print(text[number]) number += 1
first = "Aditya" last = "Mhambrey" full = first+" "+last print(full) full = f"{first} {last} {2+2} {len(first)}" print(full) course = " Python Programming" print(course.upper()) print(course.lower()) print(course.title()) # First Letter of every Word is capital print(course.strip()) # Getting rid of white space print(course.rstrip()) # Getting rid of white space from right similar for Left print(course.find("Pro")) # Same as JS, -1 for wrong case print(course.replace("P", "-")) print("Programming" in course) print("Programming" not in course)
def ler_numero(minimo, maximo): while True: try: n = int(input(f'Digite um número entre {minimo} e {maximo}: ')) if minimo <= n <= maximo: return n else: print(f'O número deve estar entre entre {minimo} e {maximo}') except ValueError: print('Você não digitou um número') n = ler_numero(10000, 30000) x = n total = 0 for peso in range(6, 1, -1): x, digito = divmod(x, 10) total += digito * peso print('resultado:') dv = total % 7 print(f'{n}-{dv}')
""" @author: acfromspace """ # Time complexity: O(n^2) # Space complexity: O(n) def bubble_sort_1(data): for i in range(len(data)-1, 0, -1): for j in range(i): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] return data def bubble_sort_2(data): # %last_index% is here to keep check of amount of passes, not needed for bubble sort. last_index = len(data) - 1 # Checks last step to see if it was the last needed step. is_sorted = False while last_index > 0 and not is_sorted: for i in range(last_index): if data[i] > data[i + 1]: data[i], data[i + 1] = data[i + 1], data[i] is_sorted = False else: is_sorted = True last_index -= 1 print("Early Exit: ", is_sorted, " | ", len(data) - last_index, " Passes") def bubble_sort_3(data): is_sorted = False while not is_sorted: is_sorted = True for i in range(len(data)-1): if data[i] > data[i+1]: data[i], data[i+1] = data[i+1], data[i] is_sorted = False return data test_list = [9, 5, 1, 3, 6, -2, -8] print(test_list) bubble_sort_1(test_list) print(test_list, "\n") test_list = [9, 5, 1, 3, 6, -2, -8] print(test_list) bubble_sort_2(test_list) print(test_list, "\n") test_list = [9, 5, 1, 3, 6, -2, -8] print(test_list) bubble_sort_3(test_list) print(test_list) """ Output: [9, 5, 1, 3, 6, -2, -8] [-8, -2, 1, 3, 5, 6, 9] [9, 5, 1, 3, 6, -2, -8] Early Exit: False | 7 Passes [-8, -2, 1, 3, 5, 6, 9] [9, 5, 1, 3, 6, -2, -8] [-8, -2, 1, 3, 5, 6, 9] """
__author__ = 'วรรณพงษ์' #import re print("Text") a = input("Text") if a.find("+"): s = a.split("+") in1 = int(s[0]) in2 = int(s[1]) cal = in1 + in2 elif a.find("-"): s = a.split("-") in1 = int(s[0]) in2 = int(s[1]) cal = in1 - in2 elif a.find("*"): s = a.split("*") in1 = int(s[0]) in2 = int(s[1]) cal = in1 * in2 elif a.find("//"): s = a.split("//") in1 = int(s[0]) in2 = int(s[1]) cal = in1 // in2 else: cal = "error"; print(cal)
class Node: def __init__(self, value, next=None): self.value = value self.next = next def has_cycle(head): slow, fast = head, head while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if slow == fast: return True # found the cycle return False
#Sort an array of 0s, 1s and 2s #It is a problem from geeksforgeeks and can be solved using python code #Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order. # Here t is the number of test cases, # i is an iterative variable, # n is the number of elements in list, # x is the list in which elements are to be entered # and sort() is a python in-built function which will sort the list of elements in ascending order t = int(input()) for i in range(t): n = int(input()) x = list(map(int, input().split())) x.sort() for i in x: print(i, end=" ") print() #This code is contributed by Akhil
# list(map(int, input().split())) # int(input()) def main(): X = int(input()) if X >= 30: print('Yes') else: print('No') if __name__ == '__main__': main()
class ManageCards: cards = {} cards["154-98-11-133-118"] = "1" cards["64-91-169-137-59"] = "2" cards["46-245-168-137-250"] = "3" cards["198-241-168-137-22"] = "4" cards["127-72-227-41-253"] = "5" cards["78-4-170-137-105"] = "6" cards["119-174-226-41-18"] = "7" cards["98-155-250-41-42"] = "8" cards["1-112-169-137-81"] = "9" cards["26-171-169-137-145"] = "10" cards["167-132-229-41-239"] = "11" cards["150-234-168-137-93"] = "12" def getCardFromUID(self, uid): try: return self.cards[uid] except KeyError: return None
# Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generates configuration for a single NAT gateway """ def GenerateConfig(context): """Generates config.""" prefix = context.env['name'] zone = context.properties['zone'] resources = [] #reserve a static IP address ip_name = prefix + '-ip' resources.append({ 'name': ip_name, 'type': 'compute.v1.address', 'properties': { 'region': context.properties['region'] } }) # create an instance template that points to a reserved static IP address template_name = prefix + '-it' runtime_var_name = prefix + '/0' resources.append({ 'name': template_name, 'type': 'compute.v1.instanceTemplate', 'properties': { 'properties': { 'disks': [{ 'deviceName': 'boot', 'type': 'PERSISTENT', 'mode': 'READ_WRITE', 'boot': True, 'autoDelete': True, 'initializeParams': { 'sourceImage': context.properties['image'], 'diskType': context.properties['diskType'], 'diskSizeGb': context.properties['diskSizeGb'] } }], 'tags': { 'items': [context.properties['nat-gw-tag']] }, 'machineType': context.properties['machineType'], 'metadata': { 'items': [{ 'key': 'startup-script', 'value': context.properties['startupScript'] }, { 'key': 'runtime-variable', 'value': runtime_var_name }, { 'key': 'runtime-config', 'value': context.properties['runtimeConfigName'] }, ] }, 'serviceAccounts': [{ 'email': 'default', 'scopes': [ # The following scope allows an instance to create runtime variable resources. 'https://www.googleapis.com/auth/cloudruntimeconfig' ] }], 'canIpForward': True, 'networkInterfaces': [{ 'network': context.properties['network'], 'subnetwork': context.properties['subnetwork'], 'accessConfigs': [{ 'name': 'External-IP', 'type': 'ONE_TO_ONE_NAT', 'natIP': '$(ref.' + ip_name + '.address)' }] }] } } }) # create an instance greoup manager of size 1 with autohealing enabled # it will make sure that the NAT gateway VM is always up igm_name = prefix + '-igm' resources.append({ 'name': igm_name, 'type': 'compute.beta.instanceGroupManager', 'properties': { 'baseInstanceName': prefix + '-vm', 'instanceTemplate': '$(ref.' + template_name + '.selfLink)', 'targetSize': 1, 'zone': zone, 'autoHealingPolicies': [{ 'initialDelaySec': 120, 'healthCheck': context.properties['healthCheck'] }] } }) # Wait until a GCE VM is created by the instance group manager. waiter_name = prefix + '-waiter' resources.append({ 'name': waiter_name, 'type': 'runtimeconfig.v1beta1.waiter', 'properties': { 'parent': context.properties['runtimeConfig'], 'waiter': waiter_name, 'timeout': '120s', 'success': { 'cardinality': { 'path': prefix, 'number': 1 } } }, 'metadata': { 'dependsOn': [igm_name] } }) # Find a name of the GCE VM created by the instance group manager get_mig_instances = prefix + '-get-mig-instances' resources.append({ 'name': get_mig_instances, 'action': 'gcp-types/compute-v1:compute.instanceGroupManagers.listManagedInstances', 'properties': { 'instanceGroupManager': igm_name, 'project': context.properties['projectId'], 'zone': zone, }, 'metadata': { 'dependsOn': [waiter_name] } }) #create a route that will allow to use the NAT gateway VM as a next hop route_name = prefix + 'route' resources.append({ 'name': route_name, 'type': 'compute.v1.route', 'properties': { 'network': context.properties['network'], 'tags': [context.properties['nated-vm-tag']], 'destRange': '0.0.0.0/0', 'priority': context.properties['routePriority'], 'nextHopInstance': '$(ref.' + get_mig_instances + '.managedInstances[0].instance)' } }) return {'resources': resources}
'''An e-commerce website wishes to find the lucky customer who will be eligible for full value cash back. For this purpose,a number N is fed to the system. It will return another number that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each number n the sum of the preceding numbers. initially the sequence will have two 1's in it. The System will return the Nth number from the generated sequence which is treated as the order ID. The lucky customer will be one who has placed that order. Write an alorithm to help the website find the lucky customer. Input Format an integer value from the user Constraints no constraints Output Format print order ID as an integer Sample Input 0 8 Sample Output 0 21 Sample Input 1 5 Sample Output 1 5''' #solution def lucky(num): n1 = 1 n2 = 1 summ = 0 for i in range(2,num): summ = n1+n2 n1 = n2 n2 = summ return summ print(lucky(int(input())))
class CommonsShared: # period, step, and episode counter periods_counter = 1 steps_counter = 1 episode_number = 0 # number of periods considered for calculating short and long term sustainabilities n_steps_short_term = 1 n_steps_long_term = 4 # number of agents n_agents = 5 # max periods per episode max_episode_periods = 10 # rounds played by each agent in a period agents_loop_steps = 20 # resources growing rate and environment carrying capacity growing_rate = 0.3 # Ghorbani uses 0.25 - 0.35 carrying_capacity = 50000 # Ghorbani uses 10000 - 20000 # probability of being caught wrong-doing punishment_probability = 1 # max replenishment (dependent on growth function) max_replenishment = carrying_capacity * growing_rate * 0.5 ** 2 # max consumption, penalty, and increases in consumption and penalty max_penalty_multiplier = 3 max_penalty_multiplier_increase = 0.5 max_limit_exploit = max_replenishment * 2 / n_agents # two times max replenishment max_limit_exploit_increase = 1000 #consumption and replenishment buffers consumed_buffer = [] consumed = [] replenished_buffer = [] replenished = []
"""Top-level package for CY Quant Components.""" try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__) __author__ = """Gatro CY""" __email__ = 'cragodn@gmail.com' __version__ = '0.3.14'
def test_ci_placeholder(): # This empty test is used within the CI to # setup the tox venv without running the test suite # if we simply skip all test with pytest -k=wrong_pattern # pytest command would return with exit_code=5 (i.e "no tests run") # making travis fail # this empty test is the recommended way to handle this # as described in https://github.com/pytest-dev/pytest/issues/2393 pass