content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class DISPPARAMS(object): """ Use System.Runtime.InteropServices.ComTypes.DISPPARAMS instead. """ cArgs = None cNamedArgs = None rgdispidNamedArgs = None rgvarg = None
class Dispparams(object): """ Use System.Runtime.InteropServices.ComTypes.DISPPARAMS instead. """ c_args = None c_named_args = None rgdispid_named_args = None rgvarg = None
course = 'Python "Programming"' print(course) course = "Python \"Programming\"" # use this to be maintain consistency course = "Python \\Programming\"" # Python \Programming" print(course)
course = 'Python "Programming"' print(course) course = 'Python "Programming"' course = 'Python \\Programming"' print(course)
n = int(input()) prev_dst = prev_t = 0 for _ in range(n): t, x, y = map(int, input().split()) dst = x + y ddst = abs(dst - prev_dst) dt = t - prev_t if t % 2 != dst % 2 or ddst > dt: print('No') exit() prev_t, prev_dst = t, dst print('Yes')
n = int(input()) prev_dst = prev_t = 0 for _ in range(n): (t, x, y) = map(int, input().split()) dst = x + y ddst = abs(dst - prev_dst) dt = t - prev_t if t % 2 != dst % 2 or ddst > dt: print('No') exit() (prev_t, prev_dst) = (t, dst) print('Yes')
class Customer: def __init__(self): self.id = "", self.name = "", self.phone = "", self.email = "", self.username = "", self.address_line_1 = "", self.address_line_2 = "", self.city = "", self.country = ""
class Customer: def __init__(self): self.id = ('',) self.name = ('',) self.phone = ('',) self.email = ('',) self.username = ('',) self.address_line_1 = ('',) self.address_line_2 = ('',) self.city = ('',) self.country = ''
counter = 0; with open("./Resources/01. Odd Lines/Input.txt", 'r') as lines: read_line = None while read_line != "": read_line = lines.readline() counter += 1 if counter % 2 == 0: with open("./Resources/01. Odd Lines/Output.txt", 'a') as odd_lines: odd_lines.write(read_line) print(odd_lines)
counter = 0 with open('./Resources/01. Odd Lines/Input.txt', 'r') as lines: read_line = None while read_line != '': read_line = lines.readline() counter += 1 if counter % 2 == 0: with open('./Resources/01. Odd Lines/Output.txt', 'a') as odd_lines: odd_lines.write(read_line) print(odd_lines)
def func(i): if i % 2 == 0: i = i+1 return i else: x = func(i-1) print('Value of X is ',x) return func(x) func(399)
def func(i): if i % 2 == 0: i = i + 1 return i else: x = func(i - 1) print('Value of X is ', x) return func(x) func(399)
# key is age, chance is contents def getdeathchance(agent): deathchance = 0.0 if agent.taxon == "savannah": if agent.sex == 'm': deathchance = SavannahLifeTable.male_death_chance[agent.age] else: deathchance = SavannahLifeTable.female_death_chance[agent.age] if agent.taxon == "hamadryas": if agent.sex == 'm': deathchance = HamadryasLifeTable.male_death_chance[agent.age] else: deathchance = HamadryasLifeTable.female_death_chance[agent.age] # print deathchance return deathchance def getbirthchance(agent): birthchance = 0.0 if agent.taxon == "savannah": birthchance = SavannahLifeTable.birth_chance[agent.age] if agent.taxon == "hamadryas": birthchance = HamadryasLifeTable.birth_chance[agent.age] return birthchance class SavannahLifeTable: male_death_chance = { 0: 0, 0.5: 0.10875, 1: 0.10875, 1.5: 0.0439, 2: 0.0439, 2.5: 0.03315, 3: 0.03315, 3.5: 0.04165, 4: 0.04165, 4.5: 0.0206, 5: 0.0206, 5.5: 0.02865, 6: 0.02865, 6.5: 0.0346375, 7: 0.0346375, 7.5: 0.0346375, 8: 0.0346375, 8.5: 0.0346375, 9: 0.0346375, 9.5: 0.0346375, 10: 0.0346375, 10.5: 0.0685625, 11: 0.0685625, 11.5: 0.0685625, 12: 0.0685625, 12.5: 0.0685625, 13: 0.0685625, 13.5: 0.0685625, 14: 0.0685625, 14.5: 0.140825, 15: 0.140825, 15.5: 0.140825, 16: 0.140825, 16.5: 0.140825, 17: 0.140825, 17.5: 0.140825, 18: 0.140825, 18.5: 0.125, 19: 0.125, 19.5: 0.335, 20: 0.335, 20.5: 1, 21: 1 } female_death_chance = { 0: 0, 0.5: 0.1031, 1: 0.1031, 1.5: 0.0558, 2: 0.0558, 2.5: 0.0317, 3: 0.0317, 3.5: 0.0156, 4: 0.0156, 4.5: 0.02355, 5: 0.02355, 5.5: 0.027125, 6: 0.027125, 6.5: 0.027125, 7: 0.027125, 7.5: 0.027125, 8: 0.027125, 8.5: 0.027125, 9: 0.027125, 9.5: 0.0436875, 10: 0.0436875, 10.5: 0.0436875, 11: 0.0436875, 11.5: 0.0436875, 12: 0.0436875, 12.5: 0.0436875, 13: 0.0436875, 13.5: 0.0691, 14: 0.0691, 14.5: 0.0691, 15: 0.0691, 15.5: 0.0691, 16: 0.0691, 16.5: 0.0691, 17: 0.0691, 17.5: 0.141125, 18: 0.141125, 18.5: 0.141125, 19: 0.141125, 19.5: 0.141125, 20: 0.141125, 20.5: 0.141125, 21: 0.141125, 21.5: 0.2552875, 22: 0.2552875, 22.5: 0.2552875, 23: 0.2552875, 23.5: 0.2552875, 24: 0.2552875, 24.5: 0.2552875, 25: 1, 25.5: 1 } birth_chance = { 0: 0, 0.5: 0, 1: 0, 1.5: 0, 2: 0, 2.5: 0, 3: 0, 3.5: 0, 4: 0, 4.5: 0, 5: 0.85, 5.5: 0.85, 6: 0.85, 6.5: 0.85, 7: 0.85, 7.5: 0.9, 8: 0.9, 8.5: 0.9, 9: 0.9, 9.5: 0.9, 10: 0.9, 10.5: 0.85, 11: 0.85, 11.5: 0.85, 12: 0.85, 12.5: 0.8, 13: 0.8, 13.5: 0.8, 14: 0.8, 14.5: 0.8, 15: 0.8, 15.5: 0.75, 16: 0.75, 16.5: 0.75, 17: 0.75, 17.5: 0.75, 18: 0.75, 18.5: 0.75, 19: 0.75, 19.5: 0.75, 20: 0.75, 20.5: 0.6, 21: 0.6, 21.5: 0.6, 22: 0.6, 22.5: 0.6, 23: 0.6, 23.5: 0.6, 24: 0.6, 24.5: 0.6, 25: 0 } class HamadryasLifeTable: male_death_chance = { 0: 0, 0.5: 0.10875, 1: 0.10875, 1.5: 0.0439, 2: 0.0439, 2.5: 0.03315, 3: 0.03315, 3.5: 0.04165, 4: 0.04165, 4.5: 0.0206, 5: 0.0206, 5.5: 0.02865, 6: 0.02865, 6.5: 0.0346375, 7: 0.0346375, 7.5: 0.0346375, 8: 0.0346375, 8.5: 0.0346375, 9: 0.0346375, 9.5: 0.0346375, 10: 0.0346375, 10.5: 0.0685625, 11: 0.0685625, 11.5: 0.0685625, 12: 0.0685625, 12.5: 0.0685625, 13: 0.0685625, 13.5: 0.0685625, 14: 0.0685625, 14.5: 0.140825, 15: 0.140825, 15.5: 0.140825, 16: 0.140825, 16.5: 0.140825, 17: 0.140825, 17.5: 0.140825, 18: 0.140825, 18.5: 0.125, 19: 0.125, 19.5: 0.335, 20: 0.335, 20.5: 1 } female_death_chance = { 0: 0, 0.5: 0.1031, 1: 0.1031, 1.5: 0.0558, 2: 0.0558, 2.5: 0.0317, 3: 0.0317, 3.5: 0.0156, 4: 0.0156, 4.5: 0.02355, 5: 0.02355, 5.5: 0.027125, 6: 0.027125, 6.5: 0.027125, 7: 0.027125, 7.5: 0.027125, 8: 0.027125, 8.5: 0.027125, 9: 0.027125, 9.5: 0.0436875, 10: 0.0436875, 10.5: 0.0436875, 11: 0.0436875, 11.5: 0.0436875, 12: 0.0436875, 12.5: 0.0436875, 13: 0.0436875, 13.5: 0.0691, 14: 0.0691, 14.5: 0.0691, 15: 0.0691, 15.5: 0.0691, 16: 0.0691, 16.5: 0.0691, 17: 0.0691, 17.5: 0.141125, 18: 0.141125, 18.5: 0.141125, 19: 0.141125, 19.5: 0.141125, 20: 0.141125, 20.5: 0.141125, 21: 0.141125, 21.5: 0.2552875, 22: 0.2552875, 22.5: 0.2552875, 23: 0.2552875, 23.5: 0.2552875, 24: 0.2552875, 24.5: 0.2552875, 25: 1 } birth_chance = { 0: 0, 0.5: 0, 1: 0, 1.5: 0, 2: 0, 2.5: 0, 3: 0, 3.5: 0, 4: 0, 4.5: 0, 5: 0.85, 5.5: 0.85, 6: 0.85, 6.5: 0.85, 7: 0.85, 7.5: 0.9, 8: 0.9, 8.5: 0.9, 9: 0.9, 9.5: 0.9, 10: 0.9, 10.5: 0.85, 11: 0.85, 11.5: 0.85, 12: 0.85, 12.5: 0.8, 13: 0.8, 13.5: 0.8, 14: 0.8, 14.5: 0.8, 15: 0.8, 15.5: 0.75, 16: 0.75, 16.5: 0.75, 17: 0.75, 17.5: 0.75, 18: 0.75, 18.5: 0.75, 19: 0.75, 19.5: 0.75, 20: 0.75, 20.5: 0.6, 21: 0.6, 21.5: 0.6, 22: 0.6, 22.5: 0.6, 23: 0.6, 23.5: 0.6, 24: 0.6, 24.5: 0.6, 25: 0 }
def getdeathchance(agent): deathchance = 0.0 if agent.taxon == 'savannah': if agent.sex == 'm': deathchance = SavannahLifeTable.male_death_chance[agent.age] else: deathchance = SavannahLifeTable.female_death_chance[agent.age] if agent.taxon == 'hamadryas': if agent.sex == 'm': deathchance = HamadryasLifeTable.male_death_chance[agent.age] else: deathchance = HamadryasLifeTable.female_death_chance[agent.age] return deathchance def getbirthchance(agent): birthchance = 0.0 if agent.taxon == 'savannah': birthchance = SavannahLifeTable.birth_chance[agent.age] if agent.taxon == 'hamadryas': birthchance = HamadryasLifeTable.birth_chance[agent.age] return birthchance class Savannahlifetable: male_death_chance = {0: 0, 0.5: 0.10875, 1: 0.10875, 1.5: 0.0439, 2: 0.0439, 2.5: 0.03315, 3: 0.03315, 3.5: 0.04165, 4: 0.04165, 4.5: 0.0206, 5: 0.0206, 5.5: 0.02865, 6: 0.02865, 6.5: 0.0346375, 7: 0.0346375, 7.5: 0.0346375, 8: 0.0346375, 8.5: 0.0346375, 9: 0.0346375, 9.5: 0.0346375, 10: 0.0346375, 10.5: 0.0685625, 11: 0.0685625, 11.5: 0.0685625, 12: 0.0685625, 12.5: 0.0685625, 13: 0.0685625, 13.5: 0.0685625, 14: 0.0685625, 14.5: 0.140825, 15: 0.140825, 15.5: 0.140825, 16: 0.140825, 16.5: 0.140825, 17: 0.140825, 17.5: 0.140825, 18: 0.140825, 18.5: 0.125, 19: 0.125, 19.5: 0.335, 20: 0.335, 20.5: 1, 21: 1} female_death_chance = {0: 0, 0.5: 0.1031, 1: 0.1031, 1.5: 0.0558, 2: 0.0558, 2.5: 0.0317, 3: 0.0317, 3.5: 0.0156, 4: 0.0156, 4.5: 0.02355, 5: 0.02355, 5.5: 0.027125, 6: 0.027125, 6.5: 0.027125, 7: 0.027125, 7.5: 0.027125, 8: 0.027125, 8.5: 0.027125, 9: 0.027125, 9.5: 0.0436875, 10: 0.0436875, 10.5: 0.0436875, 11: 0.0436875, 11.5: 0.0436875, 12: 0.0436875, 12.5: 0.0436875, 13: 0.0436875, 13.5: 0.0691, 14: 0.0691, 14.5: 0.0691, 15: 0.0691, 15.5: 0.0691, 16: 0.0691, 16.5: 0.0691, 17: 0.0691, 17.5: 0.141125, 18: 0.141125, 18.5: 0.141125, 19: 0.141125, 19.5: 0.141125, 20: 0.141125, 20.5: 0.141125, 21: 0.141125, 21.5: 0.2552875, 22: 0.2552875, 22.5: 0.2552875, 23: 0.2552875, 23.5: 0.2552875, 24: 0.2552875, 24.5: 0.2552875, 25: 1, 25.5: 1} birth_chance = {0: 0, 0.5: 0, 1: 0, 1.5: 0, 2: 0, 2.5: 0, 3: 0, 3.5: 0, 4: 0, 4.5: 0, 5: 0.85, 5.5: 0.85, 6: 0.85, 6.5: 0.85, 7: 0.85, 7.5: 0.9, 8: 0.9, 8.5: 0.9, 9: 0.9, 9.5: 0.9, 10: 0.9, 10.5: 0.85, 11: 0.85, 11.5: 0.85, 12: 0.85, 12.5: 0.8, 13: 0.8, 13.5: 0.8, 14: 0.8, 14.5: 0.8, 15: 0.8, 15.5: 0.75, 16: 0.75, 16.5: 0.75, 17: 0.75, 17.5: 0.75, 18: 0.75, 18.5: 0.75, 19: 0.75, 19.5: 0.75, 20: 0.75, 20.5: 0.6, 21: 0.6, 21.5: 0.6, 22: 0.6, 22.5: 0.6, 23: 0.6, 23.5: 0.6, 24: 0.6, 24.5: 0.6, 25: 0} class Hamadryaslifetable: male_death_chance = {0: 0, 0.5: 0.10875, 1: 0.10875, 1.5: 0.0439, 2: 0.0439, 2.5: 0.03315, 3: 0.03315, 3.5: 0.04165, 4: 0.04165, 4.5: 0.0206, 5: 0.0206, 5.5: 0.02865, 6: 0.02865, 6.5: 0.0346375, 7: 0.0346375, 7.5: 0.0346375, 8: 0.0346375, 8.5: 0.0346375, 9: 0.0346375, 9.5: 0.0346375, 10: 0.0346375, 10.5: 0.0685625, 11: 0.0685625, 11.5: 0.0685625, 12: 0.0685625, 12.5: 0.0685625, 13: 0.0685625, 13.5: 0.0685625, 14: 0.0685625, 14.5: 0.140825, 15: 0.140825, 15.5: 0.140825, 16: 0.140825, 16.5: 0.140825, 17: 0.140825, 17.5: 0.140825, 18: 0.140825, 18.5: 0.125, 19: 0.125, 19.5: 0.335, 20: 0.335, 20.5: 1} female_death_chance = {0: 0, 0.5: 0.1031, 1: 0.1031, 1.5: 0.0558, 2: 0.0558, 2.5: 0.0317, 3: 0.0317, 3.5: 0.0156, 4: 0.0156, 4.5: 0.02355, 5: 0.02355, 5.5: 0.027125, 6: 0.027125, 6.5: 0.027125, 7: 0.027125, 7.5: 0.027125, 8: 0.027125, 8.5: 0.027125, 9: 0.027125, 9.5: 0.0436875, 10: 0.0436875, 10.5: 0.0436875, 11: 0.0436875, 11.5: 0.0436875, 12: 0.0436875, 12.5: 0.0436875, 13: 0.0436875, 13.5: 0.0691, 14: 0.0691, 14.5: 0.0691, 15: 0.0691, 15.5: 0.0691, 16: 0.0691, 16.5: 0.0691, 17: 0.0691, 17.5: 0.141125, 18: 0.141125, 18.5: 0.141125, 19: 0.141125, 19.5: 0.141125, 20: 0.141125, 20.5: 0.141125, 21: 0.141125, 21.5: 0.2552875, 22: 0.2552875, 22.5: 0.2552875, 23: 0.2552875, 23.5: 0.2552875, 24: 0.2552875, 24.5: 0.2552875, 25: 1} birth_chance = {0: 0, 0.5: 0, 1: 0, 1.5: 0, 2: 0, 2.5: 0, 3: 0, 3.5: 0, 4: 0, 4.5: 0, 5: 0.85, 5.5: 0.85, 6: 0.85, 6.5: 0.85, 7: 0.85, 7.5: 0.9, 8: 0.9, 8.5: 0.9, 9: 0.9, 9.5: 0.9, 10: 0.9, 10.5: 0.85, 11: 0.85, 11.5: 0.85, 12: 0.85, 12.5: 0.8, 13: 0.8, 13.5: 0.8, 14: 0.8, 14.5: 0.8, 15: 0.8, 15.5: 0.75, 16: 0.75, 16.5: 0.75, 17: 0.75, 17.5: 0.75, 18: 0.75, 18.5: 0.75, 19: 0.75, 19.5: 0.75, 20: 0.75, 20.5: 0.6, 21: 0.6, 21.5: 0.6, 22: 0.6, 22.5: 0.6, 23: 0.6, 23.5: 0.6, 24: 0.6, 24.5: 0.6, 25: 0}
"""Azure Provisioning Device Internal This package provides internal classes for use within the Azure Provisioning Device SDK. """
"""Azure Provisioning Device Internal This package provides internal classes for use within the Azure Provisioning Device SDK. """
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # 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. ''' BSD 3-Clause License Copyright (c) Soumith Chintala 2016, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://spdx.org/licenses/BSD-3-Clause.html # # 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. '''
""" BSD 3-Clause License Copyright (c) Soumith Chintala 2016, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://spdx.org/licenses/BSD-3-Clause.html # # 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. """
grocery = ["Harpic", "Vim bar", "deo", "Bhindi", "Lollypop",56] #print(grocery[5]) #numbers = [2,7,5,11,3] #print(numbers[2]) #print(numbers.sort()) sorting done #print(numbers[1:4]) #slicing returning list but will not change original list. #print(numbers) #print(numbers[::3]) #print(numbers[::-1]) #don't take more than -1(-2,-3...) grocery.pop["Harpic"]
grocery = ['Harpic', 'Vim bar', 'deo', 'Bhindi', 'Lollypop', 56] grocery.pop['Harpic']
def get_pic_upload_to(instance, filename): return "static/profile/{}/pic/{}".format(instance.user, filename) def get_aadhar_upload_to(instance, filename): instance.filename = filename return "static/profile/{}/aadhar/{}".format(instance.user, filename) def get_passbook_upload_to(instance, filename): instance.filename = filename return "static/profile/{}/passbook/{}".format(instance.user, filename)
def get_pic_upload_to(instance, filename): return 'static/profile/{}/pic/{}'.format(instance.user, filename) def get_aadhar_upload_to(instance, filename): instance.filename = filename return 'static/profile/{}/aadhar/{}'.format(instance.user, filename) def get_passbook_upload_to(instance, filename): instance.filename = filename return 'static/profile/{}/passbook/{}'.format(instance.user, filename)
# -*- coding: UTF-8 -*- class DSException(Exception): pass class DSRequestException(DSException): pass class DSCommandFailedException(DSException): pass
class Dsexception(Exception): pass class Dsrequestexception(DSException): pass class Dscommandfailedexception(DSException): pass
def pluralize(s): last_char = s[-1] if last_char == 'y': pluralized = s[:-1] + 'ies' elif last_char == 's': pluralized = s else: pluralized = s + 's' return pluralized
def pluralize(s): last_char = s[-1] if last_char == 'y': pluralized = s[:-1] + 'ies' elif last_char == 's': pluralized = s else: pluralized = s + 's' return pluralized
# # PySNMP MIB module SWAPCOM-SCC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SWAPCOM-SCC # Produced by pysmi-0.3.4 at Wed May 1 15:12:56 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Integer32, ObjectIdentity, Counter32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Counter64, NotificationType, MibIdentifier, iso, ModuleIdentity, enterprises, Unsigned32, Bits, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "ObjectIdentity", "Counter32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Counter64", "NotificationType", "MibIdentifier", "iso", "ModuleIdentity", "enterprises", "Unsigned32", "Bits", "TimeTicks") MacAddress, TimeInterval, TextualConvention, DateAndTime, DisplayString, TruthValue, StorageType, TestAndIncr, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "MacAddress", "TimeInterval", "TextualConvention", "DateAndTime", "DisplayString", "TruthValue", "StorageType", "TestAndIncr", "RowStatus") swapcom = ModuleIdentity((1, 3, 6, 1, 4, 1, 11308)) swapcom.setRevisions(('1970-01-01 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: swapcom.setRevisionsDescriptions(('Revision Description',)) if mibBuilder.loadTexts: swapcom.setLastUpdated('2007381648Z') if mibBuilder.loadTexts: swapcom.setOrganization('Organization name') if mibBuilder.loadTexts: swapcom.setContactInfo('Contact information') if mibBuilder.loadTexts: swapcom.setDescription('Description') org = MibIdentifier((1, 3)) dod = MibIdentifier((1, 3, 6)) internet = MibIdentifier((1, 3, 6, 1)) private = MibIdentifier((1, 3, 6, 1, 4)) enterprises = MibIdentifier((1, 3, 6, 1, 4, 1)) scc = MibIdentifier((1, 3, 6, 1, 4, 1, 11308, 3)) platform = MibIdentifier((1, 3, 6, 1, 4, 1, 11308, 3, 1)) platformPlatformId = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 1, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: platformPlatformId.setStatus('current') if mibBuilder.loadTexts: platformPlatformId.setDescription('Identifier of the local platform') platformPlatformStatus = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: platformPlatformStatus.setStatus('current') if mibBuilder.loadTexts: platformPlatformStatus.setDescription('Status of local platform (0=Initializing / 1=Platform initialized / 2=Domains initialized / 3=Platform started and ready') versionTable = MibTable((1, 3, 6, 1, 4, 1, 11308, 3, 2), ) if mibBuilder.loadTexts: versionTable.setStatus('current') if mibBuilder.loadTexts: versionTable.setDescription('Components version') versionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1), ).setIndexNames((0, "SWAPCOM-SCC", "versionProductName")) if mibBuilder.loadTexts: versionEntry.setStatus('current') if mibBuilder.loadTexts: versionEntry.setDescription('The entry for versionTable') versionProductName = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: versionProductName.setStatus('current') if mibBuilder.loadTexts: versionProductName.setDescription('Name of the component') versionProductVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: versionProductVersion.setStatus('current') if mibBuilder.loadTexts: versionProductVersion.setDescription('Version of the component, follows the standard SWAPCOM versioning') versionBuildNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: versionBuildNumber.setStatus('current') if mibBuilder.loadTexts: versionBuildNumber.setDescription('Component build number') versionBuildDate = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: versionBuildDate.setStatus('current') if mibBuilder.loadTexts: versionBuildDate.setDescription('Component build date') transactionManager = MibIdentifier((1, 3, 6, 1, 4, 1, 11308, 3, 3)) transactionManagerLongTransactionThreshold = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerLongTransactionThreshold.setStatus('current') if mibBuilder.loadTexts: transactionManagerLongTransactionThreshold.setDescription('Threshold duration for long transaction detection') transactionManagerActiveTransactionCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerActiveTransactionCurrentCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerActiveTransactionCurrentCount.setDescription('Number of current active transaction') transactionManagerActiveTransactionMinCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerActiveTransactionMinCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerActiveTransactionMinCount.setDescription('Minimum number of active transaction') transactionManagerActiveTransactionMaxCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerActiveTransactionMaxCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerActiveTransactionMaxCount.setDescription('Maximum number of active transaction') transactionManagerCommittedTransactionCumulativeCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerCommittedTransactionCumulativeCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerCommittedTransactionCumulativeCount.setDescription('Number of transaction committed') transactionManagerRolledbackTransactionCumulativeCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerRolledbackTransactionCumulativeCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerRolledbackTransactionCumulativeCount.setDescription('Number of transaction rollbacked') transactionManagerTransactionCumulativeTime = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 7), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerTransactionCumulativeTime.setStatus('current') if mibBuilder.loadTexts: transactionManagerTransactionCumulativeTime.setDescription('Cumulative transaction time') transactionManagerTransactionMinTime = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 8), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerTransactionMinTime.setStatus('current') if mibBuilder.loadTexts: transactionManagerTransactionMinTime.setDescription('Minimum transaction duration time') transactionManagerTransactionMaxTime = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 9), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerTransactionMaxTime.setStatus('current') if mibBuilder.loadTexts: transactionManagerTransactionMaxTime.setDescription('Maximum transaction duration time') transactionManagerTransactionManagerLastError = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 10), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: transactionManagerTransactionManagerLastError.setStatus('current') if mibBuilder.loadTexts: transactionManagerTransactionManagerLastError.setDescription('Last error message that occured in the transaction manager') lockManager = MibIdentifier((1, 3, 6, 1, 4, 1, 11308, 3, 4)) lockManagerLockedItemCumulativeCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerLockedItemCumulativeCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockedItemCumulativeCount.setDescription('Number of lock acquired') lockManagerLockedItemCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerLockedItemCurrentCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockedItemCurrentCount.setDescription('Number of currenty locked objects') lockManagerLockedItemMinCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerLockedItemMinCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockedItemMinCount.setDescription('Minimum number of locked objects') lockManagerLockedItemMaxCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerLockedItemMaxCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockedItemMaxCount.setDescription('Maximum number of locked objects') lockManagerLockRejectedOnDeadlockCumulativeCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerLockRejectedOnDeadlockCumulativeCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockRejectedOnDeadlockCumulativeCount.setDescription('Number of lock rejected on deadlock') lockManagerLockRejectedOnTimeoutCumulativeCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerLockRejectedOnTimeoutCumulativeCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockRejectedOnTimeoutCumulativeCount.setDescription('Number of lock rejected on timeout') lockManagerBlockedTransactionCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerBlockedTransactionCurrentCount.setStatus('current') if mibBuilder.loadTexts: lockManagerBlockedTransactionCurrentCount.setDescription('Number of currently blocked transaction in lockmanager') lockManagerBlockedTransactionMinCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerBlockedTransactionMinCount.setStatus('current') if mibBuilder.loadTexts: lockManagerBlockedTransactionMinCount.setDescription('Minimum number of blocked transaction in lockmanager') lockManagerBlockedTransactionMaxCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lockManagerBlockedTransactionMaxCount.setStatus('current') if mibBuilder.loadTexts: lockManagerBlockedTransactionMaxCount.setDescription('Maximum number of blocked transaction in lockmanager') schedulerTaskTable = MibTable((1, 3, 6, 1, 4, 1, 11308, 3, 5), ) if mibBuilder.loadTexts: schedulerTaskTable.setStatus('current') if mibBuilder.loadTexts: schedulerTaskTable.setDescription('Status of tasks registered in the scheduler') schedulerTaskEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1), ).setIndexNames((0, "SWAPCOM-SCC", "schedulerTaskName")) if mibBuilder.loadTexts: schedulerTaskEntry.setStatus('current') if mibBuilder.loadTexts: schedulerTaskEntry.setDescription('The entry for schedulerTaskTable') schedulerTaskName = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: schedulerTaskName.setStatus('current') if mibBuilder.loadTexts: schedulerTaskName.setDescription('Name of the task') schedulerTaskRunning = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 2), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: schedulerTaskRunning.setStatus('current') if mibBuilder.loadTexts: schedulerTaskRunning.setDescription('Indicate if the task is currenlty being executed') schedulerTaskExecutionCumulativeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: schedulerTaskExecutionCumulativeCount.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionCumulativeCount.setDescription('Number of executions succesfully done') schedulerTaskExecutionCumulativeTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: schedulerTaskExecutionCumulativeTime.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionCumulativeTime.setDescription('Cumulative processing time (success and failure)') schedulerTaskExecutionMinTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: schedulerTaskExecutionMinTime.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionMinTime.setDescription('Minimum processing time of the task') schedulerTaskExecutionMaxTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 6), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: schedulerTaskExecutionMaxTime.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionMaxTime.setDescription('Maximum processing time of the task') schedulerTaskExecutionRetryCurrentCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: schedulerTaskExecutionRetryCurrentCount.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionRetryCurrentCount.setDescription('Number of execution failure') schedulerTaskExecutionLastError = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: schedulerTaskExecutionLastError.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionLastError.setDescription('Message of the last execution failure') alarmProbeTable = MibTable((1, 3, 6, 1, 4, 1, 11308, 3, 12), ) if mibBuilder.loadTexts: alarmProbeTable.setStatus('current') if mibBuilder.loadTexts: alarmProbeTable.setDescription('Alarm probes status of the platform') alarmProbeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1), ).setIndexNames((0, "SWAPCOM-SCC", "alarmProbeAlertType"), (0, "SWAPCOM-SCC", "alarmProbeAlertSource")) if mibBuilder.loadTexts: alarmProbeEntry.setStatus('current') if mibBuilder.loadTexts: alarmProbeEntry.setDescription('The entry for alarmProbeTable') alarmProbeAlertType = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: alarmProbeAlertType.setStatus('current') if mibBuilder.loadTexts: alarmProbeAlertType.setDescription('Type of the probe alarm') alarmProbeAlertSource = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: alarmProbeAlertSource.setStatus('current') if mibBuilder.loadTexts: alarmProbeAlertSource.setDescription('Source of the probe alarm') alarmProbeSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: alarmProbeSeverity.setStatus('current') if mibBuilder.loadTexts: alarmProbeSeverity.setDescription('Current severity of the probe') alarmProbeLastSeverityChange = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: alarmProbeLastSeverityChange.setStatus('current') if mibBuilder.loadTexts: alarmProbeLastSeverityChange.setDescription('Date of the last severity value change') remotePlatformTable = MibTable((1, 3, 6, 1, 4, 1, 11308, 3, 21), ) if mibBuilder.loadTexts: remotePlatformTable.setStatus('current') if mibBuilder.loadTexts: remotePlatformTable.setDescription('Remote platform connected to this one') remotePlatformEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11308, 3, 21, 1), ).setIndexNames((0, "SWAPCOM-SCC", "remotePlatformPlatformId")) if mibBuilder.loadTexts: remotePlatformEntry.setStatus('current') if mibBuilder.loadTexts: remotePlatformEntry.setDescription('The entry for remotePlatformTable') remotePlatformPlatformId = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 21, 1, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: remotePlatformPlatformId.setStatus('current') if mibBuilder.loadTexts: remotePlatformPlatformId.setDescription('Identifier of the remote platform') remotePlatformPlatformProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 21, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: remotePlatformPlatformProtocol.setStatus('current') if mibBuilder.loadTexts: remotePlatformPlatformProtocol.setDescription('Protocol used to communicate with the remote platform') remotePlatformRemotePlatformStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 21, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: remotePlatformRemotePlatformStatus.setStatus('current') if mibBuilder.loadTexts: remotePlatformRemotePlatformStatus.setDescription('Status of the remote platform connection (-2=unknown / -1=down / 3=up)') asynchronousEventQueueTable = MibTable((1, 3, 6, 1, 4, 1, 11308, 3, 22), ) if mibBuilder.loadTexts: asynchronousEventQueueTable.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueTable.setDescription('Asynchronous event queues status') asynchronousEventQueueEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1), ).setIndexNames((0, "SWAPCOM-SCC", "asynchronousEventQueuePlatformId")) if mibBuilder.loadTexts: asynchronousEventQueueEntry.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueEntry.setDescription('The entry for asynchronousEventQueueTable') asynchronousEventQueuePlatformId = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueuePlatformId.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueuePlatformId.setDescription('Identifier of the platform events queue') asynchronousEventQueueInsertedEventCumulativeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueInsertedEventCumulativeCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueInsertedEventCumulativeCount.setDescription('Number of generated asynchronous events') asynchronousEventQueueWaitingEventCurrentCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventCurrentCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventCurrentCount.setDescription('Number of events that are pending in the send queue') asynchronousEventQueueWaitingEventMinCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventMinCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventMinCount.setDescription('Minimum number of events pending in the send queue') asynchronousEventQueueWaitingEventMaxCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventMaxCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventMaxCount.setDescription('Maximum number of events pending in the send queue') asynchronousEventQueueProcessedEventCumulativeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueProcessedEventCumulativeCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueProcessedEventCumulativeCount.setDescription('Number of successfully sent asynchronous events') asynchronousEventQueueEventProcessingCumulativeTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 7), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingCumulativeTime.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingCumulativeTime.setDescription('Cumulated time of event processing') asynchronousEventQueueEventProcessingMinTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 8), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingMinTime.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingMinTime.setDescription('Minimum event processing time') asynchronousEventQueueEventProcessingMaxTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 9), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingMaxTime.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingMaxTime.setDescription('Maximum event processing time') asynchronousEventQueueFailedEventCumulativeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueFailedEventCumulativeCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueFailedEventCumulativeCount.setDescription("Number of asynchronous events in the 'failed' queue") asynchronousEventQueueFailedEventLastError = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 11), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: asynchronousEventQueueFailedEventLastError.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueFailedEventLastError.setDescription('Last error message of events process failure') slsConnection = MibIdentifier((1, 3, 6, 1, 4, 1, 11308, 3, 23)) slsConnectionConnected = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 23, 1), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: slsConnectionConnected.setStatus('current') if mibBuilder.loadTexts: slsConnectionConnected.setDescription('Indicate if the platform is connected to the SLS') slsConnectionLicenseCheckSuccessCumulativeCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 23, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slsConnectionLicenseCheckSuccessCumulativeCount.setStatus('current') if mibBuilder.loadTexts: slsConnectionLicenseCheckSuccessCumulativeCount.setDescription('Number of successfull license check') slsConnectionLicenseCheckFailedCumulativeCount = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 23, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slsConnectionLicenseCheckFailedCumulativeCount.setStatus('current') if mibBuilder.loadTexts: slsConnectionLicenseCheckFailedCumulativeCount.setDescription('Number of failed license check') slsConnectionLicenseCheckLastError = MibScalar((1, 3, 6, 1, 4, 1, 11308, 3, 23, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: slsConnectionLicenseCheckLastError.setStatus('current') if mibBuilder.loadTexts: slsConnectionLicenseCheckLastError.setDescription('Last error message that occured in the SLS connection') sqlPoolXATable = MibTable((1, 3, 6, 1, 4, 1, 11308, 3, 24), ) if mibBuilder.loadTexts: sqlPoolXATable.setStatus('current') if mibBuilder.loadTexts: sqlPoolXATable.setDescription('SQLPool status and properties') sqlPoolXAEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1), ).setIndexNames((0, "SWAPCOM-SCC", "sqlPoolXAName")) if mibBuilder.loadTexts: sqlPoolXAEntry.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAEntry.setDescription('The entry for sqlPoolXATable') sqlPoolXAName = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXAName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAName.setDescription('Name of the connection pool') sqlPoolXASqlPlatformName = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXASqlPlatformName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXASqlPlatformName.setDescription('Detected database type') sqlPoolXADatabaseName = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 3), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXADatabaseName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXADatabaseName.setDescription('Raw database name') sqlPoolXADriverName = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 4), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXADriverName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXADriverName.setDescription('Name of the JDBC driver') sqlPoolXADriverClassName = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 5), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXADriverClassName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXADriverClassName.setDescription('Name of the JDBC driver class') sqlPoolXAMaximumSize = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXAMaximumSize.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAMaximumSize.setDescription('Maximum size of connection pool') sqlPoolXAMaximumIdleTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 7), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXAMaximumIdleTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAMaximumIdleTime.setDescription('Maximum life duration of a connection in the pool') sqlPoolXAMaximumWaitTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 8), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXAMaximumWaitTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAMaximumWaitTime.setDescription('Maximum waiting time for getting a connection when the pool is exhausted') sqlPoolXACheckIsClosedInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 9), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckIsClosedInterval.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckIsClosedInterval.setDescription('Minimum time between two connection checking') sqlPoolXACreateConnectionSuccessCumulativeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACreateConnectionSuccessCumulativeCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACreateConnectionSuccessCumulativeCount.setDescription('Number of connections succesfully created') sqlPoolXACreateConnectionFailureCumulativeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACreateConnectionFailureCumulativeCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACreateConnectionFailureCumulativeCount.setDescription('Number of connection creation failure') sqlPoolXACreateConnectionLastError = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 12), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACreateConnectionLastError.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACreateConnectionLastError.setDescription('Last exception message during checkout failure') sqlPoolXAConnectionCurrentCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXAConnectionCurrentCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAConnectionCurrentCount.setDescription('Current size of the connection pool') sqlPoolXAConnectionMinCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 14), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXAConnectionMinCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAConnectionMinCount.setDescription('Minimum size reached by the connection pool') sqlPoolXAConnectionMaxCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 15), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXAConnectionMaxCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAConnectionMaxCount.setDescription('Maximum size reached by the connection pool') sqlPoolXACheckedOutConnectionCurrentCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 16), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCurrentCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCurrentCount.setDescription('Current number of connection that are checked out from the pool') sqlPoolXACheckedOutConnectionMinCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 17), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMinCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMinCount.setDescription('Minimum number of simultaneous checked out connections reached by the pool') sqlPoolXACheckedOutConnectionMaxCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 18), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMaxCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMaxCount.setDescription('Maximum number of simultaneous checked out connections reached by the pool') sqlPoolXACheckedOutConnectionCumulativeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 19), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCumulativeCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCumulativeCount.setDescription('Number of checkout performed from pool') sqlPoolXACheckedOutConnectionCumulativeTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 20), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCumulativeTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCumulativeTime.setDescription('Cumulation of time that the connections are checked out from the pool') sqlPoolXACheckedOutConnectionMinTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 21), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMinTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMinTime.setDescription('Minimum time that a connection has been checked out from the pool') sqlPoolXACheckedOutConnectionMaxTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 22), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMaxTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMaxTime.setDescription('Maximum time that a connection has been checked out from the pool') sqlPoolXACheckedOutConnectionAverageTime = MibTableColumn((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 23), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionAverageTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionAverageTime.setDescription('Connection checkedout average time (equals to CheckedOutConnectionCumulativeTime divided by CheckedOutConnectionCumulativeCount') mibBuilder.exportSymbols("SWAPCOM-SCC", lockManagerLockRejectedOnTimeoutCumulativeCount=lockManagerLockRejectedOnTimeoutCumulativeCount, versionProductName=versionProductName, transactionManagerTransactionCumulativeTime=transactionManagerTransactionCumulativeTime, sqlPoolXAConnectionMaxCount=sqlPoolXAConnectionMaxCount, lockManagerLockRejectedOnDeadlockCumulativeCount=lockManagerLockRejectedOnDeadlockCumulativeCount, org=org, asynchronousEventQueueFailedEventLastError=asynchronousEventQueueFailedEventLastError, lockManagerLockedItemMinCount=lockManagerLockedItemMinCount, sqlPoolXAConnectionMinCount=sqlPoolXAConnectionMinCount, lockManagerLockedItemMaxCount=lockManagerLockedItemMaxCount, schedulerTaskEntry=schedulerTaskEntry, asynchronousEventQueueFailedEventCumulativeCount=asynchronousEventQueueFailedEventCumulativeCount, sqlPoolXAMaximumWaitTime=sqlPoolXAMaximumWaitTime, alarmProbeAlertType=alarmProbeAlertType, internet=internet, sqlPoolXADatabaseName=sqlPoolXADatabaseName, dod=dod, sqlPoolXACheckedOutConnectionCurrentCount=sqlPoolXACheckedOutConnectionCurrentCount, sqlPoolXADriverClassName=sqlPoolXADriverClassName, schedulerTaskExecutionCumulativeCount=schedulerTaskExecutionCumulativeCount, transactionManagerActiveTransactionCurrentCount=transactionManagerActiveTransactionCurrentCount, sqlPoolXACreateConnectionFailureCumulativeCount=sqlPoolXACreateConnectionFailureCumulativeCount, platformPlatformId=platformPlatformId, remotePlatformPlatformProtocol=remotePlatformPlatformProtocol, schedulerTaskExecutionLastError=schedulerTaskExecutionLastError, transactionManagerRolledbackTransactionCumulativeCount=transactionManagerRolledbackTransactionCumulativeCount, sqlPoolXASqlPlatformName=sqlPoolXASqlPlatformName, lockManagerBlockedTransactionCurrentCount=lockManagerBlockedTransactionCurrentCount, remotePlatformPlatformId=remotePlatformPlatformId, alarmProbeAlertSource=alarmProbeAlertSource, schedulerTaskExecutionMaxTime=schedulerTaskExecutionMaxTime, slsConnectionConnected=slsConnectionConnected, transactionManagerTransactionManagerLastError=transactionManagerTransactionManagerLastError, versionBuildDate=versionBuildDate, asynchronousEventQueueWaitingEventMaxCount=asynchronousEventQueueWaitingEventMaxCount, swapcom=swapcom, alarmProbeLastSeverityChange=alarmProbeLastSeverityChange, sqlPoolXACheckIsClosedInterval=sqlPoolXACheckIsClosedInterval, asynchronousEventQueueEventProcessingCumulativeTime=asynchronousEventQueueEventProcessingCumulativeTime, PYSNMP_MODULE_ID=swapcom, slsConnectionLicenseCheckLastError=slsConnectionLicenseCheckLastError, private=private, lockManager=lockManager, remotePlatformTable=remotePlatformTable, sqlPoolXACheckedOutConnectionAverageTime=sqlPoolXACheckedOutConnectionAverageTime, sqlPoolXACheckedOutConnectionCumulativeTime=sqlPoolXACheckedOutConnectionCumulativeTime, sqlPoolXACheckedOutConnectionMaxTime=sqlPoolXACheckedOutConnectionMaxTime, lockManagerBlockedTransactionMinCount=lockManagerBlockedTransactionMinCount, asynchronousEventQueueWaitingEventMinCount=asynchronousEventQueueWaitingEventMinCount, lockManagerBlockedTransactionMaxCount=lockManagerBlockedTransactionMaxCount, schedulerTaskTable=schedulerTaskTable, sqlPoolXAConnectionCurrentCount=sqlPoolXAConnectionCurrentCount, transactionManager=transactionManager, schedulerTaskName=schedulerTaskName, sqlPoolXAEntry=sqlPoolXAEntry, remotePlatformRemotePlatformStatus=remotePlatformRemotePlatformStatus, alarmProbeEntry=alarmProbeEntry, sqlPoolXACreateConnectionLastError=sqlPoolXACreateConnectionLastError, sqlPoolXACheckedOutConnectionMinCount=sqlPoolXACheckedOutConnectionMinCount, slsConnection=slsConnection, sqlPoolXAName=sqlPoolXAName, sqlPoolXAMaximumIdleTime=sqlPoolXAMaximumIdleTime, transactionManagerTransactionMinTime=transactionManagerTransactionMinTime, sqlPoolXACreateConnectionSuccessCumulativeCount=sqlPoolXACreateConnectionSuccessCumulativeCount, versionProductVersion=versionProductVersion, alarmProbeTable=alarmProbeTable, asynchronousEventQueueWaitingEventCurrentCount=asynchronousEventQueueWaitingEventCurrentCount, asynchronousEventQueueEntry=asynchronousEventQueueEntry, remotePlatformEntry=remotePlatformEntry, asynchronousEventQueuePlatformId=asynchronousEventQueuePlatformId, sqlPoolXACheckedOutConnectionMaxCount=sqlPoolXACheckedOutConnectionMaxCount, schedulerTaskRunning=schedulerTaskRunning, asynchronousEventQueueTable=asynchronousEventQueueTable, transactionManagerActiveTransactionMaxCount=transactionManagerActiveTransactionMaxCount, alarmProbeSeverity=alarmProbeSeverity, versionTable=versionTable, versionEntry=versionEntry, sqlPoolXAMaximumSize=sqlPoolXAMaximumSize, schedulerTaskExecutionMinTime=schedulerTaskExecutionMinTime, asynchronousEventQueueInsertedEventCumulativeCount=asynchronousEventQueueInsertedEventCumulativeCount, schedulerTaskExecutionRetryCurrentCount=schedulerTaskExecutionRetryCurrentCount, schedulerTaskExecutionCumulativeTime=schedulerTaskExecutionCumulativeTime, lockManagerLockedItemCumulativeCount=lockManagerLockedItemCumulativeCount, sqlPoolXACheckedOutConnectionMinTime=sqlPoolXACheckedOutConnectionMinTime, slsConnectionLicenseCheckFailedCumulativeCount=slsConnectionLicenseCheckFailedCumulativeCount, transactionManagerLongTransactionThreshold=transactionManagerLongTransactionThreshold, versionBuildNumber=versionBuildNumber, enterprises=enterprises, sqlPoolXADriverName=sqlPoolXADriverName, scc=scc, transactionManagerCommittedTransactionCumulativeCount=transactionManagerCommittedTransactionCumulativeCount, platform=platform, platformPlatformStatus=platformPlatformStatus, asynchronousEventQueueEventProcessingMinTime=asynchronousEventQueueEventProcessingMinTime, transactionManagerActiveTransactionMinCount=transactionManagerActiveTransactionMinCount, lockManagerLockedItemCurrentCount=lockManagerLockedItemCurrentCount, asynchronousEventQueueEventProcessingMaxTime=asynchronousEventQueueEventProcessingMaxTime, slsConnectionLicenseCheckSuccessCumulativeCount=slsConnectionLicenseCheckSuccessCumulativeCount, sqlPoolXACheckedOutConnectionCumulativeCount=sqlPoolXACheckedOutConnectionCumulativeCount, transactionManagerTransactionMaxTime=transactionManagerTransactionMaxTime, asynchronousEventQueueProcessedEventCumulativeCount=asynchronousEventQueueProcessedEventCumulativeCount, sqlPoolXATable=sqlPoolXATable)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (integer32, object_identity, counter32, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, counter64, notification_type, mib_identifier, iso, module_identity, enterprises, unsigned32, bits, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'ObjectIdentity', 'Counter32', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Counter64', 'NotificationType', 'MibIdentifier', 'iso', 'ModuleIdentity', 'enterprises', 'Unsigned32', 'Bits', 'TimeTicks') (mac_address, time_interval, textual_convention, date_and_time, display_string, truth_value, storage_type, test_and_incr, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'MacAddress', 'TimeInterval', 'TextualConvention', 'DateAndTime', 'DisplayString', 'TruthValue', 'StorageType', 'TestAndIncr', 'RowStatus') swapcom = module_identity((1, 3, 6, 1, 4, 1, 11308)) swapcom.setRevisions(('1970-01-01 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: swapcom.setRevisionsDescriptions(('Revision Description',)) if mibBuilder.loadTexts: swapcom.setLastUpdated('2007381648Z') if mibBuilder.loadTexts: swapcom.setOrganization('Organization name') if mibBuilder.loadTexts: swapcom.setContactInfo('Contact information') if mibBuilder.loadTexts: swapcom.setDescription('Description') org = mib_identifier((1, 3)) dod = mib_identifier((1, 3, 6)) internet = mib_identifier((1, 3, 6, 1)) private = mib_identifier((1, 3, 6, 1, 4)) enterprises = mib_identifier((1, 3, 6, 1, 4, 1)) scc = mib_identifier((1, 3, 6, 1, 4, 1, 11308, 3)) platform = mib_identifier((1, 3, 6, 1, 4, 1, 11308, 3, 1)) platform_platform_id = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 1, 1), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: platformPlatformId.setStatus('current') if mibBuilder.loadTexts: platformPlatformId.setDescription('Identifier of the local platform') platform_platform_status = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: platformPlatformStatus.setStatus('current') if mibBuilder.loadTexts: platformPlatformStatus.setDescription('Status of local platform (0=Initializing / 1=Platform initialized / 2=Domains initialized / 3=Platform started and ready') version_table = mib_table((1, 3, 6, 1, 4, 1, 11308, 3, 2)) if mibBuilder.loadTexts: versionTable.setStatus('current') if mibBuilder.loadTexts: versionTable.setDescription('Components version') version_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1)).setIndexNames((0, 'SWAPCOM-SCC', 'versionProductName')) if mibBuilder.loadTexts: versionEntry.setStatus('current') if mibBuilder.loadTexts: versionEntry.setDescription('The entry for versionTable') version_product_name = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1, 1), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: versionProductName.setStatus('current') if mibBuilder.loadTexts: versionProductName.setDescription('Name of the component') version_product_version = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1, 2), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: versionProductVersion.setStatus('current') if mibBuilder.loadTexts: versionProductVersion.setDescription('Version of the component, follows the standard SWAPCOM versioning') version_build_number = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: versionBuildNumber.setStatus('current') if mibBuilder.loadTexts: versionBuildNumber.setDescription('Component build number') version_build_date = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 2, 1, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: versionBuildDate.setStatus('current') if mibBuilder.loadTexts: versionBuildDate.setDescription('Component build date') transaction_manager = mib_identifier((1, 3, 6, 1, 4, 1, 11308, 3, 3)) transaction_manager_long_transaction_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 1), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerLongTransactionThreshold.setStatus('current') if mibBuilder.loadTexts: transactionManagerLongTransactionThreshold.setDescription('Threshold duration for long transaction detection') transaction_manager_active_transaction_current_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerActiveTransactionCurrentCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerActiveTransactionCurrentCount.setDescription('Number of current active transaction') transaction_manager_active_transaction_min_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerActiveTransactionMinCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerActiveTransactionMinCount.setDescription('Minimum number of active transaction') transaction_manager_active_transaction_max_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerActiveTransactionMaxCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerActiveTransactionMaxCount.setDescription('Maximum number of active transaction') transaction_manager_committed_transaction_cumulative_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerCommittedTransactionCumulativeCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerCommittedTransactionCumulativeCount.setDescription('Number of transaction committed') transaction_manager_rolledback_transaction_cumulative_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerRolledbackTransactionCumulativeCount.setStatus('current') if mibBuilder.loadTexts: transactionManagerRolledbackTransactionCumulativeCount.setDescription('Number of transaction rollbacked') transaction_manager_transaction_cumulative_time = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 7), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerTransactionCumulativeTime.setStatus('current') if mibBuilder.loadTexts: transactionManagerTransactionCumulativeTime.setDescription('Cumulative transaction time') transaction_manager_transaction_min_time = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 8), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerTransactionMinTime.setStatus('current') if mibBuilder.loadTexts: transactionManagerTransactionMinTime.setDescription('Minimum transaction duration time') transaction_manager_transaction_max_time = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 9), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerTransactionMaxTime.setStatus('current') if mibBuilder.loadTexts: transactionManagerTransactionMaxTime.setDescription('Maximum transaction duration time') transaction_manager_transaction_manager_last_error = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 3, 10), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: transactionManagerTransactionManagerLastError.setStatus('current') if mibBuilder.loadTexts: transactionManagerTransactionManagerLastError.setDescription('Last error message that occured in the transaction manager') lock_manager = mib_identifier((1, 3, 6, 1, 4, 1, 11308, 3, 4)) lock_manager_locked_item_cumulative_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerLockedItemCumulativeCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockedItemCumulativeCount.setDescription('Number of lock acquired') lock_manager_locked_item_current_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerLockedItemCurrentCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockedItemCurrentCount.setDescription('Number of currenty locked objects') lock_manager_locked_item_min_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerLockedItemMinCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockedItemMinCount.setDescription('Minimum number of locked objects') lock_manager_locked_item_max_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerLockedItemMaxCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockedItemMaxCount.setDescription('Maximum number of locked objects') lock_manager_lock_rejected_on_deadlock_cumulative_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerLockRejectedOnDeadlockCumulativeCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockRejectedOnDeadlockCumulativeCount.setDescription('Number of lock rejected on deadlock') lock_manager_lock_rejected_on_timeout_cumulative_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerLockRejectedOnTimeoutCumulativeCount.setStatus('current') if mibBuilder.loadTexts: lockManagerLockRejectedOnTimeoutCumulativeCount.setDescription('Number of lock rejected on timeout') lock_manager_blocked_transaction_current_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerBlockedTransactionCurrentCount.setStatus('current') if mibBuilder.loadTexts: lockManagerBlockedTransactionCurrentCount.setDescription('Number of currently blocked transaction in lockmanager') lock_manager_blocked_transaction_min_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 8), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerBlockedTransactionMinCount.setStatus('current') if mibBuilder.loadTexts: lockManagerBlockedTransactionMinCount.setDescription('Minimum number of blocked transaction in lockmanager') lock_manager_blocked_transaction_max_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 4, 9), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lockManagerBlockedTransactionMaxCount.setStatus('current') if mibBuilder.loadTexts: lockManagerBlockedTransactionMaxCount.setDescription('Maximum number of blocked transaction in lockmanager') scheduler_task_table = mib_table((1, 3, 6, 1, 4, 1, 11308, 3, 5)) if mibBuilder.loadTexts: schedulerTaskTable.setStatus('current') if mibBuilder.loadTexts: schedulerTaskTable.setDescription('Status of tasks registered in the scheduler') scheduler_task_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1)).setIndexNames((0, 'SWAPCOM-SCC', 'schedulerTaskName')) if mibBuilder.loadTexts: schedulerTaskEntry.setStatus('current') if mibBuilder.loadTexts: schedulerTaskEntry.setDescription('The entry for schedulerTaskTable') scheduler_task_name = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 1), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: schedulerTaskName.setStatus('current') if mibBuilder.loadTexts: schedulerTaskName.setDescription('Name of the task') scheduler_task_running = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 2), truth_value()).setMaxAccess('readonly') if mibBuilder.loadTexts: schedulerTaskRunning.setStatus('current') if mibBuilder.loadTexts: schedulerTaskRunning.setDescription('Indicate if the task is currenlty being executed') scheduler_task_execution_cumulative_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: schedulerTaskExecutionCumulativeCount.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionCumulativeCount.setDescription('Number of executions succesfully done') scheduler_task_execution_cumulative_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 4), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: schedulerTaskExecutionCumulativeTime.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionCumulativeTime.setDescription('Cumulative processing time (success and failure)') scheduler_task_execution_min_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 5), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: schedulerTaskExecutionMinTime.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionMinTime.setDescription('Minimum processing time of the task') scheduler_task_execution_max_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 6), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: schedulerTaskExecutionMaxTime.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionMaxTime.setDescription('Maximum processing time of the task') scheduler_task_execution_retry_current_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: schedulerTaskExecutionRetryCurrentCount.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionRetryCurrentCount.setDescription('Number of execution failure') scheduler_task_execution_last_error = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 5, 1, 8), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: schedulerTaskExecutionLastError.setStatus('current') if mibBuilder.loadTexts: schedulerTaskExecutionLastError.setDescription('Message of the last execution failure') alarm_probe_table = mib_table((1, 3, 6, 1, 4, 1, 11308, 3, 12)) if mibBuilder.loadTexts: alarmProbeTable.setStatus('current') if mibBuilder.loadTexts: alarmProbeTable.setDescription('Alarm probes status of the platform') alarm_probe_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1)).setIndexNames((0, 'SWAPCOM-SCC', 'alarmProbeAlertType'), (0, 'SWAPCOM-SCC', 'alarmProbeAlertSource')) if mibBuilder.loadTexts: alarmProbeEntry.setStatus('current') if mibBuilder.loadTexts: alarmProbeEntry.setDescription('The entry for alarmProbeTable') alarm_probe_alert_type = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1, 1), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: alarmProbeAlertType.setStatus('current') if mibBuilder.loadTexts: alarmProbeAlertType.setDescription('Type of the probe alarm') alarm_probe_alert_source = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1, 2), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: alarmProbeAlertSource.setStatus('current') if mibBuilder.loadTexts: alarmProbeAlertSource.setDescription('Source of the probe alarm') alarm_probe_severity = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: alarmProbeSeverity.setStatus('current') if mibBuilder.loadTexts: alarmProbeSeverity.setDescription('Current severity of the probe') alarm_probe_last_severity_change = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 12, 1, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: alarmProbeLastSeverityChange.setStatus('current') if mibBuilder.loadTexts: alarmProbeLastSeverityChange.setDescription('Date of the last severity value change') remote_platform_table = mib_table((1, 3, 6, 1, 4, 1, 11308, 3, 21)) if mibBuilder.loadTexts: remotePlatformTable.setStatus('current') if mibBuilder.loadTexts: remotePlatformTable.setDescription('Remote platform connected to this one') remote_platform_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11308, 3, 21, 1)).setIndexNames((0, 'SWAPCOM-SCC', 'remotePlatformPlatformId')) if mibBuilder.loadTexts: remotePlatformEntry.setStatus('current') if mibBuilder.loadTexts: remotePlatformEntry.setDescription('The entry for remotePlatformTable') remote_platform_platform_id = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 21, 1, 1), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: remotePlatformPlatformId.setStatus('current') if mibBuilder.loadTexts: remotePlatformPlatformId.setDescription('Identifier of the remote platform') remote_platform_platform_protocol = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 21, 1, 2), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: remotePlatformPlatformProtocol.setStatus('current') if mibBuilder.loadTexts: remotePlatformPlatformProtocol.setDescription('Protocol used to communicate with the remote platform') remote_platform_remote_platform_status = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 21, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: remotePlatformRemotePlatformStatus.setStatus('current') if mibBuilder.loadTexts: remotePlatformRemotePlatformStatus.setDescription('Status of the remote platform connection (-2=unknown / -1=down / 3=up)') asynchronous_event_queue_table = mib_table((1, 3, 6, 1, 4, 1, 11308, 3, 22)) if mibBuilder.loadTexts: asynchronousEventQueueTable.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueTable.setDescription('Asynchronous event queues status') asynchronous_event_queue_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1)).setIndexNames((0, 'SWAPCOM-SCC', 'asynchronousEventQueuePlatformId')) if mibBuilder.loadTexts: asynchronousEventQueueEntry.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueEntry.setDescription('The entry for asynchronousEventQueueTable') asynchronous_event_queue_platform_id = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 1), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueuePlatformId.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueuePlatformId.setDescription('Identifier of the platform events queue') asynchronous_event_queue_inserted_event_cumulative_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueInsertedEventCumulativeCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueInsertedEventCumulativeCount.setDescription('Number of generated asynchronous events') asynchronous_event_queue_waiting_event_current_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventCurrentCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventCurrentCount.setDescription('Number of events that are pending in the send queue') asynchronous_event_queue_waiting_event_min_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventMinCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventMinCount.setDescription('Minimum number of events pending in the send queue') asynchronous_event_queue_waiting_event_max_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventMaxCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueWaitingEventMaxCount.setDescription('Maximum number of events pending in the send queue') asynchronous_event_queue_processed_event_cumulative_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueProcessedEventCumulativeCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueProcessedEventCumulativeCount.setDescription('Number of successfully sent asynchronous events') asynchronous_event_queue_event_processing_cumulative_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 7), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingCumulativeTime.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingCumulativeTime.setDescription('Cumulated time of event processing') asynchronous_event_queue_event_processing_min_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 8), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingMinTime.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingMinTime.setDescription('Minimum event processing time') asynchronous_event_queue_event_processing_max_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 9), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingMaxTime.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueEventProcessingMaxTime.setDescription('Maximum event processing time') asynchronous_event_queue_failed_event_cumulative_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 10), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueFailedEventCumulativeCount.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueFailedEventCumulativeCount.setDescription("Number of asynchronous events in the 'failed' queue") asynchronous_event_queue_failed_event_last_error = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 22, 1, 11), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: asynchronousEventQueueFailedEventLastError.setStatus('current') if mibBuilder.loadTexts: asynchronousEventQueueFailedEventLastError.setDescription('Last error message of events process failure') sls_connection = mib_identifier((1, 3, 6, 1, 4, 1, 11308, 3, 23)) sls_connection_connected = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 23, 1), truth_value()).setMaxAccess('readonly') if mibBuilder.loadTexts: slsConnectionConnected.setStatus('current') if mibBuilder.loadTexts: slsConnectionConnected.setDescription('Indicate if the platform is connected to the SLS') sls_connection_license_check_success_cumulative_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 23, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slsConnectionLicenseCheckSuccessCumulativeCount.setStatus('current') if mibBuilder.loadTexts: slsConnectionLicenseCheckSuccessCumulativeCount.setDescription('Number of successfull license check') sls_connection_license_check_failed_cumulative_count = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 23, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slsConnectionLicenseCheckFailedCumulativeCount.setStatus('current') if mibBuilder.loadTexts: slsConnectionLicenseCheckFailedCumulativeCount.setDescription('Number of failed license check') sls_connection_license_check_last_error = mib_scalar((1, 3, 6, 1, 4, 1, 11308, 3, 23, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: slsConnectionLicenseCheckLastError.setStatus('current') if mibBuilder.loadTexts: slsConnectionLicenseCheckLastError.setDescription('Last error message that occured in the SLS connection') sql_pool_xa_table = mib_table((1, 3, 6, 1, 4, 1, 11308, 3, 24)) if mibBuilder.loadTexts: sqlPoolXATable.setStatus('current') if mibBuilder.loadTexts: sqlPoolXATable.setDescription('SQLPool status and properties') sql_pool_xa_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1)).setIndexNames((0, 'SWAPCOM-SCC', 'sqlPoolXAName')) if mibBuilder.loadTexts: sqlPoolXAEntry.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAEntry.setDescription('The entry for sqlPoolXATable') sql_pool_xa_name = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 1), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXAName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAName.setDescription('Name of the connection pool') sql_pool_xa_sql_platform_name = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 2), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXASqlPlatformName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXASqlPlatformName.setDescription('Detected database type') sql_pool_xa_database_name = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 3), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXADatabaseName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXADatabaseName.setDescription('Raw database name') sql_pool_xa_driver_name = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 4), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXADriverName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXADriverName.setDescription('Name of the JDBC driver') sql_pool_xa_driver_class_name = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 5), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXADriverClassName.setStatus('current') if mibBuilder.loadTexts: sqlPoolXADriverClassName.setDescription('Name of the JDBC driver class') sql_pool_xa_maximum_size = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXAMaximumSize.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAMaximumSize.setDescription('Maximum size of connection pool') sql_pool_xa_maximum_idle_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 7), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXAMaximumIdleTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAMaximumIdleTime.setDescription('Maximum life duration of a connection in the pool') sql_pool_xa_maximum_wait_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 8), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXAMaximumWaitTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAMaximumWaitTime.setDescription('Maximum waiting time for getting a connection when the pool is exhausted') sql_pool_xa_check_is_closed_interval = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 9), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckIsClosedInterval.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckIsClosedInterval.setDescription('Minimum time between two connection checking') sql_pool_xa_create_connection_success_cumulative_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 10), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACreateConnectionSuccessCumulativeCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACreateConnectionSuccessCumulativeCount.setDescription('Number of connections succesfully created') sql_pool_xa_create_connection_failure_cumulative_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 11), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACreateConnectionFailureCumulativeCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACreateConnectionFailureCumulativeCount.setDescription('Number of connection creation failure') sql_pool_xa_create_connection_last_error = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 12), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACreateConnectionLastError.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACreateConnectionLastError.setDescription('Last exception message during checkout failure') sql_pool_xa_connection_current_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 13), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXAConnectionCurrentCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAConnectionCurrentCount.setDescription('Current size of the connection pool') sql_pool_xa_connection_min_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 14), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXAConnectionMinCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAConnectionMinCount.setDescription('Minimum size reached by the connection pool') sql_pool_xa_connection_max_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 15), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXAConnectionMaxCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXAConnectionMaxCount.setDescription('Maximum size reached by the connection pool') sql_pool_xa_checked_out_connection_current_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 16), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCurrentCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCurrentCount.setDescription('Current number of connection that are checked out from the pool') sql_pool_xa_checked_out_connection_min_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 17), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMinCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMinCount.setDescription('Minimum number of simultaneous checked out connections reached by the pool') sql_pool_xa_checked_out_connection_max_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 18), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMaxCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMaxCount.setDescription('Maximum number of simultaneous checked out connections reached by the pool') sql_pool_xa_checked_out_connection_cumulative_count = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 19), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCumulativeCount.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCumulativeCount.setDescription('Number of checkout performed from pool') sql_pool_xa_checked_out_connection_cumulative_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 20), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCumulativeTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionCumulativeTime.setDescription('Cumulation of time that the connections are checked out from the pool') sql_pool_xa_checked_out_connection_min_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 21), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMinTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMinTime.setDescription('Minimum time that a connection has been checked out from the pool') sql_pool_xa_checked_out_connection_max_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 22), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMaxTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionMaxTime.setDescription('Maximum time that a connection has been checked out from the pool') sql_pool_xa_checked_out_connection_average_time = mib_table_column((1, 3, 6, 1, 4, 1, 11308, 3, 24, 1, 23), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionAverageTime.setStatus('current') if mibBuilder.loadTexts: sqlPoolXACheckedOutConnectionAverageTime.setDescription('Connection checkedout average time (equals to CheckedOutConnectionCumulativeTime divided by CheckedOutConnectionCumulativeCount') mibBuilder.exportSymbols('SWAPCOM-SCC', lockManagerLockRejectedOnTimeoutCumulativeCount=lockManagerLockRejectedOnTimeoutCumulativeCount, versionProductName=versionProductName, transactionManagerTransactionCumulativeTime=transactionManagerTransactionCumulativeTime, sqlPoolXAConnectionMaxCount=sqlPoolXAConnectionMaxCount, lockManagerLockRejectedOnDeadlockCumulativeCount=lockManagerLockRejectedOnDeadlockCumulativeCount, org=org, asynchronousEventQueueFailedEventLastError=asynchronousEventQueueFailedEventLastError, lockManagerLockedItemMinCount=lockManagerLockedItemMinCount, sqlPoolXAConnectionMinCount=sqlPoolXAConnectionMinCount, lockManagerLockedItemMaxCount=lockManagerLockedItemMaxCount, schedulerTaskEntry=schedulerTaskEntry, asynchronousEventQueueFailedEventCumulativeCount=asynchronousEventQueueFailedEventCumulativeCount, sqlPoolXAMaximumWaitTime=sqlPoolXAMaximumWaitTime, alarmProbeAlertType=alarmProbeAlertType, internet=internet, sqlPoolXADatabaseName=sqlPoolXADatabaseName, dod=dod, sqlPoolXACheckedOutConnectionCurrentCount=sqlPoolXACheckedOutConnectionCurrentCount, sqlPoolXADriverClassName=sqlPoolXADriverClassName, schedulerTaskExecutionCumulativeCount=schedulerTaskExecutionCumulativeCount, transactionManagerActiveTransactionCurrentCount=transactionManagerActiveTransactionCurrentCount, sqlPoolXACreateConnectionFailureCumulativeCount=sqlPoolXACreateConnectionFailureCumulativeCount, platformPlatformId=platformPlatformId, remotePlatformPlatformProtocol=remotePlatformPlatformProtocol, schedulerTaskExecutionLastError=schedulerTaskExecutionLastError, transactionManagerRolledbackTransactionCumulativeCount=transactionManagerRolledbackTransactionCumulativeCount, sqlPoolXASqlPlatformName=sqlPoolXASqlPlatformName, lockManagerBlockedTransactionCurrentCount=lockManagerBlockedTransactionCurrentCount, remotePlatformPlatformId=remotePlatformPlatformId, alarmProbeAlertSource=alarmProbeAlertSource, schedulerTaskExecutionMaxTime=schedulerTaskExecutionMaxTime, slsConnectionConnected=slsConnectionConnected, transactionManagerTransactionManagerLastError=transactionManagerTransactionManagerLastError, versionBuildDate=versionBuildDate, asynchronousEventQueueWaitingEventMaxCount=asynchronousEventQueueWaitingEventMaxCount, swapcom=swapcom, alarmProbeLastSeverityChange=alarmProbeLastSeverityChange, sqlPoolXACheckIsClosedInterval=sqlPoolXACheckIsClosedInterval, asynchronousEventQueueEventProcessingCumulativeTime=asynchronousEventQueueEventProcessingCumulativeTime, PYSNMP_MODULE_ID=swapcom, slsConnectionLicenseCheckLastError=slsConnectionLicenseCheckLastError, private=private, lockManager=lockManager, remotePlatformTable=remotePlatformTable, sqlPoolXACheckedOutConnectionAverageTime=sqlPoolXACheckedOutConnectionAverageTime, sqlPoolXACheckedOutConnectionCumulativeTime=sqlPoolXACheckedOutConnectionCumulativeTime, sqlPoolXACheckedOutConnectionMaxTime=sqlPoolXACheckedOutConnectionMaxTime, lockManagerBlockedTransactionMinCount=lockManagerBlockedTransactionMinCount, asynchronousEventQueueWaitingEventMinCount=asynchronousEventQueueWaitingEventMinCount, lockManagerBlockedTransactionMaxCount=lockManagerBlockedTransactionMaxCount, schedulerTaskTable=schedulerTaskTable, sqlPoolXAConnectionCurrentCount=sqlPoolXAConnectionCurrentCount, transactionManager=transactionManager, schedulerTaskName=schedulerTaskName, sqlPoolXAEntry=sqlPoolXAEntry, remotePlatformRemotePlatformStatus=remotePlatformRemotePlatformStatus, alarmProbeEntry=alarmProbeEntry, sqlPoolXACreateConnectionLastError=sqlPoolXACreateConnectionLastError, sqlPoolXACheckedOutConnectionMinCount=sqlPoolXACheckedOutConnectionMinCount, slsConnection=slsConnection, sqlPoolXAName=sqlPoolXAName, sqlPoolXAMaximumIdleTime=sqlPoolXAMaximumIdleTime, transactionManagerTransactionMinTime=transactionManagerTransactionMinTime, sqlPoolXACreateConnectionSuccessCumulativeCount=sqlPoolXACreateConnectionSuccessCumulativeCount, versionProductVersion=versionProductVersion, alarmProbeTable=alarmProbeTable, asynchronousEventQueueWaitingEventCurrentCount=asynchronousEventQueueWaitingEventCurrentCount, asynchronousEventQueueEntry=asynchronousEventQueueEntry, remotePlatformEntry=remotePlatformEntry, asynchronousEventQueuePlatformId=asynchronousEventQueuePlatformId, sqlPoolXACheckedOutConnectionMaxCount=sqlPoolXACheckedOutConnectionMaxCount, schedulerTaskRunning=schedulerTaskRunning, asynchronousEventQueueTable=asynchronousEventQueueTable, transactionManagerActiveTransactionMaxCount=transactionManagerActiveTransactionMaxCount, alarmProbeSeverity=alarmProbeSeverity, versionTable=versionTable, versionEntry=versionEntry, sqlPoolXAMaximumSize=sqlPoolXAMaximumSize, schedulerTaskExecutionMinTime=schedulerTaskExecutionMinTime, asynchronousEventQueueInsertedEventCumulativeCount=asynchronousEventQueueInsertedEventCumulativeCount, schedulerTaskExecutionRetryCurrentCount=schedulerTaskExecutionRetryCurrentCount, schedulerTaskExecutionCumulativeTime=schedulerTaskExecutionCumulativeTime, lockManagerLockedItemCumulativeCount=lockManagerLockedItemCumulativeCount, sqlPoolXACheckedOutConnectionMinTime=sqlPoolXACheckedOutConnectionMinTime, slsConnectionLicenseCheckFailedCumulativeCount=slsConnectionLicenseCheckFailedCumulativeCount, transactionManagerLongTransactionThreshold=transactionManagerLongTransactionThreshold, versionBuildNumber=versionBuildNumber, enterprises=enterprises, sqlPoolXADriverName=sqlPoolXADriverName, scc=scc, transactionManagerCommittedTransactionCumulativeCount=transactionManagerCommittedTransactionCumulativeCount, platform=platform, platformPlatformStatus=platformPlatformStatus, asynchronousEventQueueEventProcessingMinTime=asynchronousEventQueueEventProcessingMinTime, transactionManagerActiveTransactionMinCount=transactionManagerActiveTransactionMinCount, lockManagerLockedItemCurrentCount=lockManagerLockedItemCurrentCount, asynchronousEventQueueEventProcessingMaxTime=asynchronousEventQueueEventProcessingMaxTime, slsConnectionLicenseCheckSuccessCumulativeCount=slsConnectionLicenseCheckSuccessCumulativeCount, sqlPoolXACheckedOutConnectionCumulativeCount=sqlPoolXACheckedOutConnectionCumulativeCount, transactionManagerTransactionMaxTime=transactionManagerTransactionMaxTime, asynchronousEventQueueProcessedEventCumulativeCount=asynchronousEventQueueProcessedEventCumulativeCount, sqlPoolXATable=sqlPoolXATable)
#!/usr/bin/env python #------------------------------------------------------------------------------- # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ # We know a linkedList has a cycle if and only if it encounters an element again if head is not None: slow = head fast = head while fast and fast.next: slow, fast = slow.next, fast.next.next if slow is fast: return True return False #------------------------------------------------------------------------------- # Testing
class Solution(object): def has_cycle(self, head): """ :type head: ListNode :rtype: bool """ if head is not None: slow = head fast = head while fast and fast.next: (slow, fast) = (slow.next, fast.next.next) if slow is fast: return True return False
DISCRETE = 0 CONTINUOUS = 1 INITIAL = 0 INTERMEDIATE = 1 FINAL = 2
discrete = 0 continuous = 1 initial = 0 intermediate = 1 final = 2
# python3 def read_input(): return (input().rstrip(), input().rstrip()) def print_occurrences(output): print(' '.join(map(str, output))) def PolyHash(s, prime, multiplier): hash = 0 for c in reversed(s): hash = (hash * multiplier + ord(c)) % prime return hash def PrecomputeHashes(text, len_pattern, prime, multiplier): H = [None] * (len(text) - len_pattern + 1) S = text[len(text) - len_pattern:] H[len(text) - len_pattern] = PolyHash(S, prime, multiplier) y = 1 for i in range(len_pattern): y = (y * multiplier) % prime for i in range(len(text) - len_pattern - 1, -1, -1): H[i] = (multiplier * H[i + 1] + ord(text[i]) - y * ord(text[i + len_pattern])) % prime return H def get_occurrences(pattern, text): result = [] prime = 1610612741 multiplier = 263 p_hash = PolyHash(pattern, prime, multiplier) H = PrecomputeHashes(text, len(pattern), prime, multiplier) for i in range(len(text) - len(pattern) + 1): if (p_hash == H[i]) and (text[i:i + len(pattern)] == pattern): result.append(i) return result if __name__ == '__main__': print_occurrences(get_occurrences(*read_input()))
def read_input(): return (input().rstrip(), input().rstrip()) def print_occurrences(output): print(' '.join(map(str, output))) def poly_hash(s, prime, multiplier): hash = 0 for c in reversed(s): hash = (hash * multiplier + ord(c)) % prime return hash def precompute_hashes(text, len_pattern, prime, multiplier): h = [None] * (len(text) - len_pattern + 1) s = text[len(text) - len_pattern:] H[len(text) - len_pattern] = poly_hash(S, prime, multiplier) y = 1 for i in range(len_pattern): y = y * multiplier % prime for i in range(len(text) - len_pattern - 1, -1, -1): H[i] = (multiplier * H[i + 1] + ord(text[i]) - y * ord(text[i + len_pattern])) % prime return H def get_occurrences(pattern, text): result = [] prime = 1610612741 multiplier = 263 p_hash = poly_hash(pattern, prime, multiplier) h = precompute_hashes(text, len(pattern), prime, multiplier) for i in range(len(text) - len(pattern) + 1): if p_hash == H[i] and text[i:i + len(pattern)] == pattern: result.append(i) return result if __name__ == '__main__': print_occurrences(get_occurrences(*read_input()))
#!/usr/bin/env python ''' Copyright (C) 2020, WAFW00F Developers. See the LICENSE file for copying permission. ''' NAME = 'LiteSpeed (LiteSpeed Technologies)' def is_waf(self): schema1 = [ self.matchHeader(('Server', 'LiteSpeed')), self.matchStatus(403) ] schema2 = [ self.matchContent(r'Proudly powered by litespeed web server'), self.matchContent(r'www\.litespeedtech\.com/error\-page') ] if all(i for i in schema1): return True if any(i for i in schema2): return True return False
""" Copyright (C) 2020, WAFW00F Developers. See the LICENSE file for copying permission. """ name = 'LiteSpeed (LiteSpeed Technologies)' def is_waf(self): schema1 = [self.matchHeader(('Server', 'LiteSpeed')), self.matchStatus(403)] schema2 = [self.matchContent('Proudly powered by litespeed web server'), self.matchContent('www\\.litespeedtech\\.com/error\\-page')] if all((i for i in schema1)): return True if any((i for i in schema2)): return True return False
# -*- coding: utf-8 -*- """ Created on Fri Jan 28 16:26:55 2022 @author: leoda """ precedence = { '+': 1, '-': 1, '*': 2, '/': 2, '^': 3, None: 0 } symbols = ['+', '-', '*', '/', '^'] all_allowed = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.', ')', '('] all_allowed.extend(symbols) # evaluates a simple expression def evaluate_simple(x, y, symbol): value = None if symbol == '+': value = x + y elif symbol == '-': value = x - y elif symbol == '*': value = x * y elif symbol == '/': value = x / y elif symbol == '^': value = x ** y return value # evaluates the equation in polish notation by recursion, equation is an array def evaluate_in_polish(equation): # can't have even length or length 0 as there is one more number than symbol if equation is None or len(equation) % 2 == 0: return None # works by replacing elements by result until there is one left, the answer while len(equation) > 1: # find the first symbol element counter = 2 while equation[counter] not in symbols: counter += 1 # once found first symbol, evaluate its expression result = evaluate_simple(equation[counter - 2], equation[counter - 1], equation[counter]) # replaces operands and operator with answer equation.pop(counter - 2) equation.pop(counter - 2) equation[counter - 2] = result return equation[0] # allows either the use of integers or floating point numbers def to_polish(equation, type_number): # initialising data, in_polish is list in RPN, lower is used to extract numbers # stack_symbols is all symbols of lower precedence, i is used to iterate in_polish = [] lower = 0 stack_symbols = [] i = 0 end_bracket = False while i < len(equation) - 1: if equation[i] == '(': # lower is first place after the bracket i += 1 lower = i # finds opening bracket corresponding to opening bracket,end just after it brackets = 0 while brackets < 1: # hasn't found a second bracket, returns nothing if i >= len(equation): print('Index out of range, wasnt correct bracketing!') return None if equation[i] == '(': brackets -= 1 if equation[i] == ')': brackets += 1 i += 1 # Show what was in the brackets # print('bracket encountered: '+equation[lower:i-1]) # adds the stuff in the brackets in RPN in right order and reinitialises lower in_polish.extend(to_polish(equation[lower:i - 1], type_number)) lower = i # last encountered was bracketed end_bracket = True elif equation[i] in symbols: # find number and makes sure it is correct # add number to the list if last wasn't bracket if not end_bracket: try: number = type_number(equation[lower:i]) in_polish.append(number) except ValueError: print('Not a correct number between symbols before end!') return None # reinitialise end_bracket and calculate precedence of symbol end_bracket = False precede = precedence[equation[i]] # for all symbols which are already if they have same precedence or higher # they need to be added to the list for j in range(len(stack_symbols)): if precedence[stack_symbols[len(stack_symbols) - j - 1]] >= precede: in_polish.append(stack_symbols.pop()) else: break # add the symbol next at the top of the stack of symbols so popped first stack_symbols.append(equation[i]) # adjust i and lower i += 1 lower = i else: i += 1 # print(in_polish) # if last symbol wasn't a bracket add the number if not end_bracket: try: number = type_number(equation[lower:]) in_polish.append(number) except: print('Not a correct number between symbols in end!') return None # adds the rest of the symbols which were on the stack fo lower precedence for j in range(len(stack_symbols)): in_polish.append(stack_symbols.pop()) return in_polish def evaluate(equation, type_number): for j in equation: if j not in all_allowed: print('Symbols used not allowed') return None return evaluate_in_polish(to_polish(equation, type_number)) def evaluate_int(equation): return evaluate(equation, int) def evaluate_float(equation): return evaluate(equation, float) def main(): equation2 = '3*(9-6)^2' # print(evaluate_int(equation2)) answer = None in_polish = None while answer == None: equation2 = input('What is your equation: ') in_polish = to_polish(equation2, int) print(in_polish) answer = evaluate_in_polish(in_polish) print('Evaluated ' + equation2 + ' gives: ' + str(answer)) main()
""" Created on Fri Jan 28 16:26:55 2022 @author: leoda """ precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3, None: 0} symbols = ['+', '-', '*', '/', '^'] all_allowed = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.', ')', '('] all_allowed.extend(symbols) def evaluate_simple(x, y, symbol): value = None if symbol == '+': value = x + y elif symbol == '-': value = x - y elif symbol == '*': value = x * y elif symbol == '/': value = x / y elif symbol == '^': value = x ** y return value def evaluate_in_polish(equation): if equation is None or len(equation) % 2 == 0: return None while len(equation) > 1: counter = 2 while equation[counter] not in symbols: counter += 1 result = evaluate_simple(equation[counter - 2], equation[counter - 1], equation[counter]) equation.pop(counter - 2) equation.pop(counter - 2) equation[counter - 2] = result return equation[0] def to_polish(equation, type_number): in_polish = [] lower = 0 stack_symbols = [] i = 0 end_bracket = False while i < len(equation) - 1: if equation[i] == '(': i += 1 lower = i brackets = 0 while brackets < 1: if i >= len(equation): print('Index out of range, wasnt correct bracketing!') return None if equation[i] == '(': brackets -= 1 if equation[i] == ')': brackets += 1 i += 1 in_polish.extend(to_polish(equation[lower:i - 1], type_number)) lower = i end_bracket = True elif equation[i] in symbols: if not end_bracket: try: number = type_number(equation[lower:i]) in_polish.append(number) except ValueError: print('Not a correct number between symbols before end!') return None end_bracket = False precede = precedence[equation[i]] for j in range(len(stack_symbols)): if precedence[stack_symbols[len(stack_symbols) - j - 1]] >= precede: in_polish.append(stack_symbols.pop()) else: break stack_symbols.append(equation[i]) i += 1 lower = i else: i += 1 if not end_bracket: try: number = type_number(equation[lower:]) in_polish.append(number) except: print('Not a correct number between symbols in end!') return None for j in range(len(stack_symbols)): in_polish.append(stack_symbols.pop()) return in_polish def evaluate(equation, type_number): for j in equation: if j not in all_allowed: print('Symbols used not allowed') return None return evaluate_in_polish(to_polish(equation, type_number)) def evaluate_int(equation): return evaluate(equation, int) def evaluate_float(equation): return evaluate(equation, float) def main(): equation2 = '3*(9-6)^2' answer = None in_polish = None while answer == None: equation2 = input('What is your equation: ') in_polish = to_polish(equation2, int) print(in_polish) answer = evaluate_in_polish(in_polish) print('Evaluated ' + equation2 + ' gives: ' + str(answer)) main()
#!/usr/bin/env python3 """ global user-defined variables """ data_folder: str = 'data' raw_data_folder: str = f'{data_folder}/raw_data' clean_data_folder: str = f'{data_folder}/clean_data' models_folder = f'{data_folder}/models' text_vectorization_folder = f'{models_folder}/vectorization' output_folder: str = 'output' rnn_folder = f'{models_folder}/rnn' rnn_file_name = 'cp.ckpt' sentences_key: str = 'sentences' random_state: int = 0 unknown_token: str = '[UNK]'
""" global user-defined variables """ data_folder: str = 'data' raw_data_folder: str = f'{data_folder}/raw_data' clean_data_folder: str = f'{data_folder}/clean_data' models_folder = f'{data_folder}/models' text_vectorization_folder = f'{models_folder}/vectorization' output_folder: str = 'output' rnn_folder = f'{models_folder}/rnn' rnn_file_name = 'cp.ckpt' sentences_key: str = 'sentences' random_state: int = 0 unknown_token: str = '[UNK]'
'''(Binary Search Special Trick Unknown length [M]): Given a sorted array whose length is not known, perform binary search for a target T. Do the search in O(log(n)) time.''' def binarySearchOverRange(arr, T, low, high): while low <= high: mid = low + (high - low) // 2 if arr[mid] == T: return mid elif arr[mid] < T: low = mid + 1 else: high = mid - 1 return -1 def binarySearchForLastIndex(arr, low, high): while low <= high: mid = low + (high - low) // 2 try: temp = arr[mid] except Exception as e: # mid is out of bounds, go to lower half high = mid - 1 continue try: temp = arr[mid + 1] except Exception as e: # mid + 1 is out of bounds, mid is last index return mid # both mid and mid + 1 are inside array, mid is not last index low = mid + 1 # this does not have end of the array return -1 def findWithUnknownLength(arr, T): # 1,2,4,8,16,32 high = 1 lastIndex = -1 # consider putting a sanity limit here, don't go more # than index 1 million. while True: try: temp = arr[high] except Exception as e: lastIndex = binarySearchForLastIndex(arr, high // 2, high) break high *= 2 return binarySearchOverRange(arr, T, 0, lastIndex) print(findWithUnknownLength([1,2,5,6,9,10], 5)) # Output: 2 -> lets imagine out input is unknown :) # Time: O(logn) Space: O(1)
"""(Binary Search Special Trick Unknown length [M]): Given a sorted array whose length is not known, perform binary search for a target T. Do the search in O(log(n)) time.""" def binary_search_over_range(arr, T, low, high): while low <= high: mid = low + (high - low) // 2 if arr[mid] == T: return mid elif arr[mid] < T: low = mid + 1 else: high = mid - 1 return -1 def binary_search_for_last_index(arr, low, high): while low <= high: mid = low + (high - low) // 2 try: temp = arr[mid] except Exception as e: high = mid - 1 continue try: temp = arr[mid + 1] except Exception as e: return mid low = mid + 1 return -1 def find_with_unknown_length(arr, T): high = 1 last_index = -1 while True: try: temp = arr[high] except Exception as e: last_index = binary_search_for_last_index(arr, high // 2, high) break high *= 2 return binary_search_over_range(arr, T, 0, lastIndex) print(find_with_unknown_length([1, 2, 5, 6, 9, 10], 5))
def lengthOfLongestSubstring(self, s: str) -> int: valueMap = dict() pointer = 0 maxLen = 0 for i in range(len(s)): char = s[i] if char in valueMap and pointer <= valueMap[char]: pointer = valueMap[char] + 1 valueMap[char] = i diff = i - pointer + 1 maxLen = max(diff, maxLen) return maxLen
def length_of_longest_substring(self, s: str) -> int: value_map = dict() pointer = 0 max_len = 0 for i in range(len(s)): char = s[i] if char in valueMap and pointer <= valueMap[char]: pointer = valueMap[char] + 1 valueMap[char] = i diff = i - pointer + 1 max_len = max(diff, maxLen) return maxLen
# Singly-linked lists are already defined with this interface: class ListNode(object): def __init__(self, x): self.value = x self.next = None def condense_linked_list(node): # Reference the current node's value current = node # List to store the values condensed_list = [] # Loop through the list while current: # If the current value is already in the list if current.value in condensed_list: # Delete it current.value = None # Otherwise, append the current value to the list else: condensed_list.append(current.value) # Move to the next node current = current.next return condensed_list
class Listnode(object): def __init__(self, x): self.value = x self.next = None def condense_linked_list(node): current = node condensed_list = [] while current: if current.value in condensed_list: current.value = None else: condensed_list.append(current.value) current = current.next return condensed_list
print("Anand K S") print("AM.EN.U4CSE19106") print("S1 CSE B") print("Marvel rockz")
print('Anand K S') print('AM.EN.U4CSE19106') print('S1 CSE B') print('Marvel rockz')
ct = "eae4a5b1aad7964ec9f1f0bff0229cf1a11b22b11bfefecc9922aaf4bff0dd3c88" ct = bytes.fromhex(ct) flag = "" initialize = 0 for i in range(len(ct)): for val in range(256): if (initialize ^ (val<<2)^val)&0xff == ct[i]: flag += chr(val) initialize ^= (val<<2)^val initialize >>=8 break print(flag) #batpwn{Ch00se_y0uR_pR3fix_w1selY}
ct = 'eae4a5b1aad7964ec9f1f0bff0229cf1a11b22b11bfefecc9922aaf4bff0dd3c88' ct = bytes.fromhex(ct) flag = '' initialize = 0 for i in range(len(ct)): for val in range(256): if (initialize ^ val << 2 ^ val) & 255 == ct[i]: flag += chr(val) initialize ^= val << 2 ^ val initialize >>= 8 break print(flag)
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Yelp Key ID = "Enter Your Yelp ID Here" ykey = "Enter your Yelp API Key Here"
id = 'Enter Your Yelp ID Here' ykey = 'Enter your Yelp API Key Here'
class Solution: def subtractProductAndSum(self, n: int) -> int: n = str(n) s = 0 p = 1 for c in n: c = int(c) s += c p *= c return p - s
class Solution: def subtract_product_and_sum(self, n: int) -> int: n = str(n) s = 0 p = 1 for c in n: c = int(c) s += c p *= c return p - s
#!/usr/bin/env python3 # Dictionaries map a value to a key, hence a value can be # called using the key. # 1. They ar3333i3ie mutable, ie. they can be changed. # 3. They are surrounded by curly {} brackets. # 3. They are indexed using square [] brackets. # 4. Key and Value pairs are separated by columns ":" # 5. Each pair of key/value pairs are separated by commas ",". # 6. Dicts return values not in any order. # 7. collections.OrderedDict() gives an ordered dictionary. # Create a dict mydict1 = {} # Add values to the dict. mydict1["host1"] = "A.B.C.D" mydict1["host2"] = "E.F.G.H" print(mydict1) # Remove values del mydict1["host2"] print(mydict1) # Check if a key exists in a dict. "host2" in mydict1 "host1" in mydict1 # Add elements to the dictionary mydict1["host3"] = "I.J.K.L" mydict1["host4"] = "M.N.O.P" print(mydict1) # Check the length of the dictionary print(len(mydict1)) print(mydict1.keys()) released = { "IPhone": 2007, "IPhone 3G": 2008, "IPhone 3GS": 2009, "IPhone 4": 2010, "IPhone 4S": 2011, "IPhone 5": 2012, "IPhone 5s": 2013, "IPhone SE": 2016, } for i, j in released.items(): print("{0} was released in {1}".format(i, j)) # Change a value for a specific key print("Changing the value for a key") released["IPhone"] = 2006 released["IPhone"] += 1 print(released["IPhone"]) released["IPhone"] -= 1 print(released["IPhone"])
mydict1 = {} mydict1['host1'] = 'A.B.C.D' mydict1['host2'] = 'E.F.G.H' print(mydict1) del mydict1['host2'] print(mydict1) 'host2' in mydict1 'host1' in mydict1 mydict1['host3'] = 'I.J.K.L' mydict1['host4'] = 'M.N.O.P' print(mydict1) print(len(mydict1)) print(mydict1.keys()) released = {'IPhone': 2007, 'IPhone 3G': 2008, 'IPhone 3GS': 2009, 'IPhone 4': 2010, 'IPhone 4S': 2011, 'IPhone 5': 2012, 'IPhone 5s': 2013, 'IPhone SE': 2016} for (i, j) in released.items(): print('{0} was released in {1}'.format(i, j)) print('Changing the value for a key') released['IPhone'] = 2006 released['IPhone'] += 1 print(released['IPhone']) released['IPhone'] -= 1 print(released['IPhone'])
class RequestError(Exception): def __init__(self, message: str, code: int): super(RequestError, self).__init__(message) self.code = code
class Requesterror(Exception): def __init__(self, message: str, code: int): super(RequestError, self).__init__(message) self.code = code
# this is the default configuration file for cage interfaces # # request_timeout is conceptually the most far reaching parameter # here, it is one of the guarantees for the entire cage - that it # responds within that time, even though the response is a failure # # thread_count limits the number of threads in the cage's main # processing thread pool, thus effectively the number of requests # being processed concurrently, no matter which interface they # arrived from; this behaviour of processing stuff with pools of # worker threads while putting the excessive work on queue is one # of the design principles of Pythomnic3k # # log_level can be changed at runtime to temporarily increase logging # verbosity (set to "DEBUG") to see wtf is going on config = dict \ ( interfaces = ("performance", "rpc", "retry"), # tuple containing names of interfaces to start request_timeout = 10.0, # global request timeout for this cage thread_count = 10, # interfaces worker thread pool size sweep_period = 15.0, # time between scanning all pools for expired objects log_level = "INFO", # one of "ERROR", "WARNING", "LOG", "INFO", "DEBUG", "NOISE" ) # DO NOT TOUCH BELOW THIS LINE __all__ = [ "get", "copy" ] get = lambda key, default = None: pmnc.config.get_(config, {}, key, default) copy = lambda: pmnc.config.copy_(config, {}) # EOF
config = dict(interfaces=('performance', 'rpc', 'retry'), request_timeout=10.0, thread_count=10, sweep_period=15.0, log_level='INFO') __all__ = ['get', 'copy'] get = lambda key, default=None: pmnc.config.get_(config, {}, key, default) copy = lambda : pmnc.config.copy_(config, {})
""" Build targets for default implementations of tf/core/platform libraries. """ # This is a temporary hack to mimic the presence of a BUILD file under # tensorflow/core/platform/default. This is part of a large refactoring # of BUILD rules under tensorflow/core/platform. We will remove this file # and add real BUILD files under tensorflow/core/platform/default and # tensorflow/core/platform/windows after the refactoring is complete. TF_PLATFORM_LIBRARIES = { "context": { "name": "context_impl", "hdrs": ["//tensorflow/core/platform:context.h"], "textual_hdrs": ["//tensorflow/core/platform:default/context.h"], "deps": [ "//tensorflow/core/platform", ], "visibility": ["//visibility:private"], }, "cord": { "name": "cord_impl", "hdrs": ["//tensorflow/core/platform:default/cord.h"], "visibility": ["//visibility:private"], }, } def tf_instantiate_platform_libraries(names = []): for name in names: native.cc_library(**TF_PLATFORM_LIBRARIES[name])
""" Build targets for default implementations of tf/core/platform libraries. """ tf_platform_libraries = {'context': {'name': 'context_impl', 'hdrs': ['//tensorflow/core/platform:context.h'], 'textual_hdrs': ['//tensorflow/core/platform:default/context.h'], 'deps': ['//tensorflow/core/platform'], 'visibility': ['//visibility:private']}, 'cord': {'name': 'cord_impl', 'hdrs': ['//tensorflow/core/platform:default/cord.h'], 'visibility': ['//visibility:private']}} def tf_instantiate_platform_libraries(names=[]): for name in names: native.cc_library(**TF_PLATFORM_LIBRARIES[name])
def cyclical(length=100, relative_min=0.1): '''Also known as triangular, https://arxiv.org/pdf/1506.01186.pdf''' half = length / 2 def _cyclical(step, multiplier): return ( step, multiplier * ( relative_min + (1 - relative_min) * abs( ((step - 1) % length - half) / (half - 1) ) ) ) return _cyclical
def cyclical(length=100, relative_min=0.1): """Also known as triangular, https://arxiv.org/pdf/1506.01186.pdf""" half = length / 2 def _cyclical(step, multiplier): return (step, multiplier * (relative_min + (1 - relative_min) * abs(((step - 1) % length - half) / (half - 1)))) return _cyclical
L = int(input()) C = int(input()) t2 = (((L - 1) + (C - 1)) * 2) t1 = (L * C) + ((L - 1) * (C - 1)) print(f"{t1}\n{t2}")
l = int(input()) c = int(input()) t2 = (L - 1 + (C - 1)) * 2 t1 = L * C + (L - 1) * (C - 1) print(f'{t1}\n{t2}')
class usuario (): "Clase que representa una persona." def __init__(self, dni, nombre, apellido): "Constructor de Persona" self.dni = dni self.nombre = nombre self.apellido = apellido def carritoCompras(self,carrito): self.carrito=carrito return def __str__(self): return f"{self.dni}{self.nombre}{self.apellido}"
class Usuario: """Clase que representa una persona.""" def __init__(self, dni, nombre, apellido): """Constructor de Persona""" self.dni = dni self.nombre = nombre self.apellido = apellido def carrito_compras(self, carrito): self.carrito = carrito return def __str__(self): return f'{self.dni}{self.nombre}{self.apellido}'
class AlreadyInDatabase(Exception): pass class MissingUnit(Exception): pass
class Alreadyindatabase(Exception): pass class Missingunit(Exception): pass
name0_1_0_0_0_0_0 = None name0_1_0_0_0_0_1 = None name0_1_0_0_0_0_2 = None name0_1_0_0_0_0_3 = None name0_1_0_0_0_0_4 = None
name0_1_0_0_0_0_0 = None name0_1_0_0_0_0_1 = None name0_1_0_0_0_0_2 = None name0_1_0_0_0_0_3 = None name0_1_0_0_0_0_4 = None
# # MIT License # # brutemind framework for python # Copyright (C) 2018 Michael Lin, Valeriy Garnaga # # 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. class Data(object): DATA_URL = "http://fremont1.cto911.com/esdoc/data/" def __init__(self, inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, zipPassword=None, refreshData=True): self.inputTrainCsvZipUrl = inputTrainCsvZipUrl self.outputTrainCsvZipUrl = outputTrainCsvZipUrl self.inputTestCsvZipUrl = inputTestCsvZipUrl self.outputTestCsvZipUrl = outputTestCsvZipUrl self.zipPassword = zipPassword self.refreshData = refreshData def load_valuation(refresh_data=True): inputTrainCsvZipUrl = '{}valuation_train_inputs.zip'.format(Data.DATA_URL) outputTrainCsvZipUrl = '{}valuation_train_outputs.zip'.format(Data.DATA_URL) inputTestCsvZipUrl = None outputTestCsvZipUrl = None return Data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_iris(refresh_data=True): inputTrainCsvZipUrl = '{}iris_train_inputs.zip'.format(Data.DATA_URL) outputTrainCsvZipUrl = '{}iris_train_outputs.zip'.format(Data.DATA_URL) inputTestCsvZipUrl = None outputTestCsvZipUrl = None return Data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_diabetes(refresh_data=True): inputTrainCsvZipUrl = '{}diabetes_train_inputs.zip'.format(Data.DATA_URL) outputTrainCsvZipUrl = '{}diabetes_train_outputs.zip'.format(Data.DATA_URL) inputTestCsvZipUrl = None outputTestCsvZipUrl = None return Data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_mnist(refresh_data=True): inputTrainCsvZipUrl = '{}mnist_train_inputs.zip'.format(Data.DATA_URL) outputTrainCsvZipUrl = '{}mnist_train_outputs.zip'.format(Data.DATA_URL) inputTestCsvZipUrl = '{}mnist_test_inputs.zip'.format(Data.DATA_URL) outputTestCsvZipUrl = '{}mnist_test_outputs.zip'.format(Data.DATA_URL) return Data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data)
class Data(object): data_url = 'http://fremont1.cto911.com/esdoc/data/' def __init__(self, inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, zipPassword=None, refreshData=True): self.inputTrainCsvZipUrl = inputTrainCsvZipUrl self.outputTrainCsvZipUrl = outputTrainCsvZipUrl self.inputTestCsvZipUrl = inputTestCsvZipUrl self.outputTestCsvZipUrl = outputTestCsvZipUrl self.zipPassword = zipPassword self.refreshData = refreshData def load_valuation(refresh_data=True): input_train_csv_zip_url = '{}valuation_train_inputs.zip'.format(Data.DATA_URL) output_train_csv_zip_url = '{}valuation_train_outputs.zip'.format(Data.DATA_URL) input_test_csv_zip_url = None output_test_csv_zip_url = None return data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_iris(refresh_data=True): input_train_csv_zip_url = '{}iris_train_inputs.zip'.format(Data.DATA_URL) output_train_csv_zip_url = '{}iris_train_outputs.zip'.format(Data.DATA_URL) input_test_csv_zip_url = None output_test_csv_zip_url = None return data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_diabetes(refresh_data=True): input_train_csv_zip_url = '{}diabetes_train_inputs.zip'.format(Data.DATA_URL) output_train_csv_zip_url = '{}diabetes_train_outputs.zip'.format(Data.DATA_URL) input_test_csv_zip_url = None output_test_csv_zip_url = None return data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data) def load_mnist(refresh_data=True): input_train_csv_zip_url = '{}mnist_train_inputs.zip'.format(Data.DATA_URL) output_train_csv_zip_url = '{}mnist_train_outputs.zip'.format(Data.DATA_URL) input_test_csv_zip_url = '{}mnist_test_inputs.zip'.format(Data.DATA_URL) output_test_csv_zip_url = '{}mnist_test_outputs.zip'.format(Data.DATA_URL) return data(inputTrainCsvZipUrl, outputTrainCsvZipUrl, inputTestCsvZipUrl, outputTestCsvZipUrl, refresh_data)
class BinHeap(object): def __init__(self): self.size = 0 self.heapList = [0] def __str__(self): return '[ ' + ' '.join(str(i) for i in self.heapList[1:]) + ' ]' def _percolateUp(self, i): while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: tmp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = tmp i //= 2 def _percolateDown(self, i): while i * 2 <= self.size: minC_idx = self._getMinChildIndex(i) if self.heapList[i] > self.heapList[minC_idx]: tmp = self.heapList[i] self.heapList[i] = self.heapList[minC_idx] self.heapList[minC_idx] = tmp i = minC_idx def _getMinChildIndex(self, i): if i * 2 == self.size: return i * 2 else: if self.heapList[i * 2] < self.heapList[i * 2 + 1]: return i * 2 else: return i * 2 + 1 def insert(self, value): self.heapList.append(value) self.size += 1 self._percolateUp(self.size) def delMin(self): vmin = self.heapList[1] self.heapList[1] = self.heapList[self.size] self.heapList.pop() self.size -= 1 self._percolateDown(1) return vmin def build_from_list(self, aList): """ One can build a heap by just inserting items one at a time. This process is at O(log_n) ops. Since inserting an item in middle of a list will cause O(n) ops, thus the whole process will finally cost O(n*log_n). However if start building a heap with an entire list, that will end up with O(n) ops. """ i = len(aList) // 2 self.heapList = [0] + aList self.size = len(aList) while i > 0: self._percolateDown(i) i -= 1 if __name__ == '__main__': bh = BinHeap() print(bh) bh.insert(17) bh.insert(14) bh.insert(9) bh.insert(5) print(bh) bh = BinHeap() bh.build_from_list([14, 9, 17, 5, 18, 21, 3]) print(bh) bh.delMin() print('del Min:', bh) bh.delMin() print('del Min:', bh) bh.delMin() print('del Min:', bh)
class Binheap(object): def __init__(self): self.size = 0 self.heapList = [0] def __str__(self): return '[ ' + ' '.join((str(i) for i in self.heapList[1:])) + ' ]' def _percolate_up(self, i): while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: tmp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = tmp i //= 2 def _percolate_down(self, i): while i * 2 <= self.size: min_c_idx = self._getMinChildIndex(i) if self.heapList[i] > self.heapList[minC_idx]: tmp = self.heapList[i] self.heapList[i] = self.heapList[minC_idx] self.heapList[minC_idx] = tmp i = minC_idx def _get_min_child_index(self, i): if i * 2 == self.size: return i * 2 elif self.heapList[i * 2] < self.heapList[i * 2 + 1]: return i * 2 else: return i * 2 + 1 def insert(self, value): self.heapList.append(value) self.size += 1 self._percolateUp(self.size) def del_min(self): vmin = self.heapList[1] self.heapList[1] = self.heapList[self.size] self.heapList.pop() self.size -= 1 self._percolateDown(1) return vmin def build_from_list(self, aList): """ One can build a heap by just inserting items one at a time. This process is at O(log_n) ops. Since inserting an item in middle of a list will cause O(n) ops, thus the whole process will finally cost O(n*log_n). However if start building a heap with an entire list, that will end up with O(n) ops. """ i = len(aList) // 2 self.heapList = [0] + aList self.size = len(aList) while i > 0: self._percolateDown(i) i -= 1 if __name__ == '__main__': bh = bin_heap() print(bh) bh.insert(17) bh.insert(14) bh.insert(9) bh.insert(5) print(bh) bh = bin_heap() bh.build_from_list([14, 9, 17, 5, 18, 21, 3]) print(bh) bh.delMin() print('del Min:', bh) bh.delMin() print('del Min:', bh) bh.delMin() print('del Min:', bh)
class Solution: def arrangeCoins(self, n: int) -> int: res =1 while res*(res+1)<=2*n: res +=1 res-=1 return res
class Solution: def arrange_coins(self, n: int) -> int: res = 1 while res * (res + 1) <= 2 * n: res += 1 res -= 1 return res
# # PySNMP MIB module Unisphere-Data-MPLS-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-MPLS-CONF # Produced by pysmi-0.3.4 at Mon Apr 29 21:24:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint") AgentCapabilities, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "NotificationGroup", "ModuleCompliance") ObjectIdentity, MibIdentifier, Unsigned32, TimeTicks, Counter32, Integer32, Bits, Counter64, NotificationType, ModuleIdentity, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "MibIdentifier", "Unsigned32", "TimeTicks", "Counter32", "Integer32", "Bits", "Counter64", "NotificationType", "ModuleIdentity", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "IpAddress") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") usDataAgents, = mibBuilder.importSymbols("Unisphere-Data-Agents", "usDataAgents") usdMplsMinorLayerConfGroup, usdMplsExplicitPathConfGroup, usdMplsTunnelProfileConfGroup, usdMplsLsrGlobalConfGroup, usdMplsMajorLayerConfGroup = mibBuilder.importSymbols("Unisphere-Data-MPLS-MIB", "usdMplsMinorLayerConfGroup", "usdMplsExplicitPathConfGroup", "usdMplsTunnelProfileConfGroup", "usdMplsLsrGlobalConfGroup", "usdMplsMajorLayerConfGroup") usdMplsAgent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 51)) usdMplsAgent.setRevisions(('2001-12-05 21:41',)) if mibBuilder.loadTexts: usdMplsAgent.setLastUpdated('200112052141Z') if mibBuilder.loadTexts: usdMplsAgent.setOrganization('Unisphere Networks, Inc.') usdMplsAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 51, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdMplsAgentV1 = usdMplsAgentV1.setProductRelease('Version 1 of the MultiProtocol Label Switching (MPLS) component of the\n Unisphere Routing Switch SNMP agent. This version of the MPLS component\n is supported in the Unisphere RX 4.0 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdMplsAgentV1 = usdMplsAgentV1.setStatus('current') mibBuilder.exportSymbols("Unisphere-Data-MPLS-CONF", usdMplsAgentV1=usdMplsAgentV1, PYSNMP_MODULE_ID=usdMplsAgent, usdMplsAgent=usdMplsAgent)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, single_value_constraint, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint') (agent_capabilities, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'AgentCapabilities', 'NotificationGroup', 'ModuleCompliance') (object_identity, mib_identifier, unsigned32, time_ticks, counter32, integer32, bits, counter64, notification_type, module_identity, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'MibIdentifier', 'Unsigned32', 'TimeTicks', 'Counter32', 'Integer32', 'Bits', 'Counter64', 'NotificationType', 'ModuleIdentity', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'IpAddress') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') (us_data_agents,) = mibBuilder.importSymbols('Unisphere-Data-Agents', 'usDataAgents') (usd_mpls_minor_layer_conf_group, usd_mpls_explicit_path_conf_group, usd_mpls_tunnel_profile_conf_group, usd_mpls_lsr_global_conf_group, usd_mpls_major_layer_conf_group) = mibBuilder.importSymbols('Unisphere-Data-MPLS-MIB', 'usdMplsMinorLayerConfGroup', 'usdMplsExplicitPathConfGroup', 'usdMplsTunnelProfileConfGroup', 'usdMplsLsrGlobalConfGroup', 'usdMplsMajorLayerConfGroup') usd_mpls_agent = module_identity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 51)) usdMplsAgent.setRevisions(('2001-12-05 21:41',)) if mibBuilder.loadTexts: usdMplsAgent.setLastUpdated('200112052141Z') if mibBuilder.loadTexts: usdMplsAgent.setOrganization('Unisphere Networks, Inc.') usd_mpls_agent_v1 = agent_capabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 51, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usd_mpls_agent_v1 = usdMplsAgentV1.setProductRelease('Version 1 of the MultiProtocol Label Switching (MPLS) component of the\n Unisphere Routing Switch SNMP agent. This version of the MPLS component\n is supported in the Unisphere RX 4.0 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usd_mpls_agent_v1 = usdMplsAgentV1.setStatus('current') mibBuilder.exportSymbols('Unisphere-Data-MPLS-CONF', usdMplsAgentV1=usdMplsAgentV1, PYSNMP_MODULE_ID=usdMplsAgent, usdMplsAgent=usdMplsAgent)
# coding=utf-8 class App: TESTING = True SQLALCHEMY_DATABASE_URI = 'mysql://lvye_pay:p@55word@127.0.0.1:3306/lvye_pay' SQLALCHEMY_ECHO = True class Biz: VALID_NETLOCS = ['test_pay.lvye.com:5100'] HOST_URL = 'http://test_pay.lvye.com:5100' CHECKOUT_URL = 'http://dev_pay.lvye.com:5102/checkout/{sn}' TEST_CHANNELS = {'zyt_sample'}
class App: testing = True sqlalchemy_database_uri = 'mysql://lvye_pay:p@55word@127.0.0.1:3306/lvye_pay' sqlalchemy_echo = True class Biz: valid_netlocs = ['test_pay.lvye.com:5100'] host_url = 'http://test_pay.lvye.com:5100' checkout_url = 'http://dev_pay.lvye.com:5102/checkout/{sn}' test_channels = {'zyt_sample'}
# 1 grafo = [ { "vertice": 'a', "arestas": ['c', 'd', 'f'] }, { "vertice": 'b', "arestas": ['d', 'e'] }, { "vertice": 'c', "arestas": ['a', 'f'] }, { "vertice": 'd', "arestas": ['a', 'b', 'e', 'f'] }, { "vertice": 'e', "arestas": ['b', 'd'] }, { "vertice": 'f', "arestas": ['a', 'c', 'd'] }, { "vertice": 'g', "arestas": [] } ] for i in grafo: print(i)
grafo = [{'vertice': 'a', 'arestas': ['c', 'd', 'f']}, {'vertice': 'b', 'arestas': ['d', 'e']}, {'vertice': 'c', 'arestas': ['a', 'f']}, {'vertice': 'd', 'arestas': ['a', 'b', 'e', 'f']}, {'vertice': 'e', 'arestas': ['b', 'd']}, {'vertice': 'f', 'arestas': ['a', 'c', 'd']}, {'vertice': 'g', 'arestas': []}] for i in grafo: print(i)
thinkers = ['Plato','PlayDo','Gumby'] while True: try: thinker = thinkers.pop() print(thinker) except IndexError as e: print("We tried to pop too many thinkers") print(e) break
thinkers = ['Plato', 'PlayDo', 'Gumby'] while True: try: thinker = thinkers.pop() print(thinker) except IndexError as e: print('We tried to pop too many thinkers') print(e) break
# Time Complexity : O(n) ; Space Complexity : O(n) # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: nodes = set() while headA: nodes.add(headA) headA = headA.next while headB: if headB in nodes: return headB headB = headB.next return None # Time Complexity : O(2n) ; Space Complexity : O(1) # Constant Space # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lena,lenb = 0,0 tempa,tempb = headA,headB while tempa: lena += 1 tempa = tempa.next while tempb: lenb += 1 tempb = tempb.next if lena>lenb: for i in range(lena-lenb): headA = headA.next elif lena<lenb: for i in range(lenb-lena): headB = headB.next while headA and headB: if headA == headB: return headA headA = headA.next headB = headB.next return None # Time Complexity : O(2n) ; Space Complexity : O(1) ; TRICKY # Constant Space # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lena,lenb = 0,0 if headA == None or headB == None: return None A_pointer = headA B_pointer = headB while A_pointer != B_pointer: A_pointer = headB if A_pointer == None else A_pointer.next B_pointer = headA if B_pointer == None else B_pointer.next return A_pointer
class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: nodes = set() while headA: nodes.add(headA) head_a = headA.next while headB: if headB in nodes: return headB head_b = headB.next return None class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: (lena, lenb) = (0, 0) (tempa, tempb) = (headA, headB) while tempa: lena += 1 tempa = tempa.next while tempb: lenb += 1 tempb = tempb.next if lena > lenb: for i in range(lena - lenb): head_a = headA.next elif lena < lenb: for i in range(lenb - lena): head_b = headB.next while headA and headB: if headA == headB: return headA head_a = headA.next head_b = headB.next return None class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: (lena, lenb) = (0, 0) if headA == None or headB == None: return None a_pointer = headA b_pointer = headB while A_pointer != B_pointer: a_pointer = headB if A_pointer == None else A_pointer.next b_pointer = headA if B_pointer == None else B_pointer.next return A_pointer
_YES_ANSWERS_ = ["y","yes"] _NO_ANSWERS_ = ["n", "no"] def getInput(_string): val = raw_input(_string) return val def getYesNoAnswer(_string): while True: val = raw_input(_string).lower() if val in _YES_ANSWERS_: return True if val in _NO_ANSWERS_: return False
_yes_answers_ = ['y', 'yes'] _no_answers_ = ['n', 'no'] def get_input(_string): val = raw_input(_string) return val def get_yes_no_answer(_string): while True: val = raw_input(_string).lower() if val in _YES_ANSWERS_: return True if val in _NO_ANSWERS_: return False
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 elif len(nums) == 1: return nums[0] # get all sum first all_sum = sum(nums)
class Solution: def max_sub_array(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 elif len(nums) == 1: return nums[0] all_sum = sum(nums)
#!/usr/bin/env python3 # File: xRpcFaker.py def SayHello(token): return f"Hello {token}!"
def say_hello(token): return f'Hello {token}!'
class EventInstance(object): """ Represents language-neutral information for an event log entry. EventInstance(instanceId: Int64,categoryId: int) EventInstance(instanceId: Int64,categoryId: int,entryType: EventLogEntryType) """ @staticmethod def __new__(self, instanceId, categoryId, entryType=None): """ __new__(cls: type,instanceId: Int64,categoryId: int) __new__(cls: type,instanceId: Int64,categoryId: int,entryType: EventLogEntryType) """ pass CategoryId = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Gets or sets the resource identifier that specifies the application-defined category of the event entry. Get: CategoryId(self: EventInstance) -> int Set: CategoryId(self: EventInstance)=value """ EntryType = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the event type of the event log entry. Get: EntryType(self: EventInstance) -> EventLogEntryType Set: EntryType(self: EventInstance)=value """ InstanceId = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Gets or sets the resource identifier that designates the message text of the event entry. Get: InstanceId(self: EventInstance) -> Int64 Set: InstanceId(self: EventInstance)=value """
class Eventinstance(object): """ Represents language-neutral information for an event log entry. EventInstance(instanceId: Int64,categoryId: int) EventInstance(instanceId: Int64,categoryId: int,entryType: EventLogEntryType) """ @staticmethod def __new__(self, instanceId, categoryId, entryType=None): """ __new__(cls: type,instanceId: Int64,categoryId: int) __new__(cls: type,instanceId: Int64,categoryId: int,entryType: EventLogEntryType) """ pass category_id = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the resource identifier that specifies the application-defined category of the event entry.\n\n\n\nGet: CategoryId(self: EventInstance) -> int\n\n\n\nSet: CategoryId(self: EventInstance)=value\n\n' entry_type = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the event type of the event log entry.\n\n\n\nGet: EntryType(self: EventInstance) -> EventLogEntryType\n\n\n\nSet: EntryType(self: EventInstance)=value\n\n' instance_id = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the resource identifier that designates the message text of the event entry.\n\n\n\nGet: InstanceId(self: EventInstance) -> Int64\n\n\n\nSet: InstanceId(self: EventInstance)=value\n\n'
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [even for even in a if even % 2 == 0] print(b) c = [even*3 for even in a] print(c)
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [even for even in a if even % 2 == 0] print(b) c = [even * 3 for even in a] print(c)
class Fenwick_Tree: def __init__(self, size): self.size = size + 1 self.array = [0 for _ in range(self.size)] def __len__(self): ''' Called when len is called on object ''' return self.size def lsb(self, index:int) -> int: ''' Returns integer value of least significant bit which is 1 If index is 352(101100000), then return value is 32(100000) ''' return index & -index def prev(self, index:int) -> int: ''' Returns last index whose element is added to element at given index ''' return index - self.lsb(index) def next(self, index:int) -> int: ''' Returns next index where element of current index is added ''' return index + self.lsb(index) def check_index(self, index:int) -> None: ''' Index bound checking Throws an exception if index is out of bounds ''' if index < 0 or index >= self.size: raise ValueError("Index out of bounds") def array_to_fenwick(self, array:list) -> None: ''' Converts the given array into a Fenwick array Writes over the data present in the object before calling this function ''' self.size = len(array) + 1 self.array = [0] for i in array: self.array.append(i) for i in range(1, self.size): next_index = self.next(i) if next_index < self.size: self.array[next_index] += self.array[i] def add(self, index:int, value:int) -> None: ''' Adds value to element at index and updates the Fenwick tree accordingly ''' index += 1 self.check_index(index) while index < self.size: self.array[index] += value index = self.next(index) def insert(self, index:int, value:int) -> None: ''' Replaces old value at index with given value ''' self.add(index, value - self.get_value_at(index)) def range_sum(self, left:int, right:int) -> int: ''' Gets the sum of all elements between left index (inclusive) and right index( exclusive) ''' if left > right: left, right = right, left self.check_index(left) self.check_index(right) s = 0 while right > left: s += self.array[right] right = self.prev(right) while left > right: s -= self.array[left] left = self.prev(left) return s def prefix_sum(self, index:int): ''' Gets the sum of all elements between first element and (index - 1)th element ''' self.check_index(index) s = 0 while index > 0: s += self.array[index] index = self.prev(index) return s def get_value_at(self, index:int) -> int: ''' Gets the value at the given index ''' return self.range_sum(index, index + 1) def get_array(self) -> list: ''' Returns the orginal values of array ''' array = self.array.copy() for i in range(self.size - 1, 0, -1): next_index = self.next(i) if next_index < self.size: array[next_index] -= array[i] array.pop(0) return array
class Fenwick_Tree: def __init__(self, size): self.size = size + 1 self.array = [0 for _ in range(self.size)] def __len__(self): """ Called when len is called on object """ return self.size def lsb(self, index: int) -> int: """ Returns integer value of least significant bit which is 1 If index is 352(101100000), then return value is 32(100000) """ return index & -index def prev(self, index: int) -> int: """ Returns last index whose element is added to element at given index """ return index - self.lsb(index) def next(self, index: int) -> int: """ Returns next index where element of current index is added """ return index + self.lsb(index) def check_index(self, index: int) -> None: """ Index bound checking Throws an exception if index is out of bounds """ if index < 0 or index >= self.size: raise value_error('Index out of bounds') def array_to_fenwick(self, array: list) -> None: """ Converts the given array into a Fenwick array Writes over the data present in the object before calling this function """ self.size = len(array) + 1 self.array = [0] for i in array: self.array.append(i) for i in range(1, self.size): next_index = self.next(i) if next_index < self.size: self.array[next_index] += self.array[i] def add(self, index: int, value: int) -> None: """ Adds value to element at index and updates the Fenwick tree accordingly """ index += 1 self.check_index(index) while index < self.size: self.array[index] += value index = self.next(index) def insert(self, index: int, value: int) -> None: """ Replaces old value at index with given value """ self.add(index, value - self.get_value_at(index)) def range_sum(self, left: int, right: int) -> int: """ Gets the sum of all elements between left index (inclusive) and right index( exclusive) """ if left > right: (left, right) = (right, left) self.check_index(left) self.check_index(right) s = 0 while right > left: s += self.array[right] right = self.prev(right) while left > right: s -= self.array[left] left = self.prev(left) return s def prefix_sum(self, index: int): """ Gets the sum of all elements between first element and (index - 1)th element """ self.check_index(index) s = 0 while index > 0: s += self.array[index] index = self.prev(index) return s def get_value_at(self, index: int) -> int: """ Gets the value at the given index """ return self.range_sum(index, index + 1) def get_array(self) -> list: """ Returns the orginal values of array """ array = self.array.copy() for i in range(self.size - 1, 0, -1): next_index = self.next(i) if next_index < self.size: array[next_index] -= array[i] array.pop(0) return array
class NofieldnameField(object): pass class FieldnameField(object): fieldname = 'hello' class RepeatedFieldnameField(FieldnameField): pass
class Nofieldnamefield(object): pass class Fieldnamefield(object): fieldname = 'hello' class Repeatedfieldnamefield(FieldnameField): pass
def for_one(): """ We are creating a user defined function for numerical pattern of One with "*" symbol """ row=7 col=5 for i in range(row): for j in range(col): if i==1 and j<3 or j==2 or i==6 and j<5: print("*",end=" ") else: print(" ",end=" ") print() def while_one(): row=0 while row<6: col=0 while col<4: if col==2 or row==5 or row==1 and col<3: print("*",end=" ") else: print(" ",end=" ") col+=1 row+=1 print()
def for_one(): """ We are creating a user defined function for numerical pattern of One with "*" symbol """ row = 7 col = 5 for i in range(row): for j in range(col): if i == 1 and j < 3 or j == 2 or (i == 6 and j < 5): print('*', end=' ') else: print(' ', end=' ') print() def while_one(): row = 0 while row < 6: col = 0 while col < 4: if col == 2 or row == 5 or (row == 1 and col < 3): print('*', end=' ') else: print(' ', end=' ') col += 1 row += 1 print()
# ## ADD THIS TO YOUR .gitignore FILE ## # APPLICATION_TITLE = 'WikiGenomes' # DJango Secret key secret_key = '<django secret key>' # OAUTH Consumer Credentials---you must register a consumer at consumer_key = '<wikimedia oauth consumer key>' consumer_secret = '<wikimedia oauth consumer secret>' # Configurations for django settings.py # ALLOWED_HOSTS add IP or domain name to list. allowed_hosts = ['wikigenomes.org'] # TIME_ZONE wg_timezone = 'America/Los_Angeles' # ## Application customization ## # ## Taxids of the organisms that will included in the instance # ## If left blank, the 120 bacterial reference genomes https://www.ncbi.nlm.nih.gov/genome/browse/reference/ that currently populate WikiGenomes # ## You may also provide a list of taxids from the list of representative species at NCBI RefSeq at the same url # ## - to get the desired taxids into Wikidata for use in your WikiGenomes instance, create an issue at https://github.com/SuLab/scheduled-bots # ## providing the list of taxids, the name and a brief description of your application. You will then be notified through GitHub when the issue is resolved # ## when the genomes, thier genes an proteins have been loaded to Wikidata taxids = []
application_title = 'WikiGenomes' secret_key = '<django secret key>' consumer_key = '<wikimedia oauth consumer key>' consumer_secret = '<wikimedia oauth consumer secret>' allowed_hosts = ['wikigenomes.org'] wg_timezone = 'America/Los_Angeles' taxids = []
"""Constants.""" CACHE_NAME = 'news_lk_si' CACHE_TIMEOUT = 3600
"""Constants.""" cache_name = 'news_lk_si' cache_timeout = 3600
name = 'AL_USDMaya' version = '0.0.1' uuid = 'c1c2376f-3640-4046-b55e-f11461431f34' authors = ['AnimalLogic'] description = 'USD to Maya translator. This rez package is purely an example and should be modifyed to your own needs' private_build_requires = [ 'cmake-2.8+', 'gcc-4.8', 'gdb-7.10' ] requires = [ 'usd-0.7', 'usdImaging-0.7', 'glew-2.0', 'python-2.7+<3', 'doubleConversion-1', 'stdlib-4.8', 'zlib-1.2', 'googletest', ] variants = [ ['CentOS-6.2+<7'] ] def commands(): prependenv('PATH', '{root}/src') prependenv('PYTHONPATH', '{root}/lib/python') prependenv('LD_LIBRARY_PATH', '{root}/lib') prependenv('MAYA_PLUG_IN_PATH', '{root}/plugin') prependenv('MAYA_SCRIPT_PATH', '{root}/lib:{root}/share/usd/plugins/usdMaya/resources') prependenv('PXR_PLUGINPATH', '{root}/share/usd/plugins') prependenv('CMAKE_MODULE_PATH', '{root}/cmake')
name = 'AL_USDMaya' version = '0.0.1' uuid = 'c1c2376f-3640-4046-b55e-f11461431f34' authors = ['AnimalLogic'] description = 'USD to Maya translator. This rez package is purely an example and should be modifyed to your own needs' private_build_requires = ['cmake-2.8+', 'gcc-4.8', 'gdb-7.10'] requires = ['usd-0.7', 'usdImaging-0.7', 'glew-2.0', 'python-2.7+<3', 'doubleConversion-1', 'stdlib-4.8', 'zlib-1.2', 'googletest'] variants = [['CentOS-6.2+<7']] def commands(): prependenv('PATH', '{root}/src') prependenv('PYTHONPATH', '{root}/lib/python') prependenv('LD_LIBRARY_PATH', '{root}/lib') prependenv('MAYA_PLUG_IN_PATH', '{root}/plugin') prependenv('MAYA_SCRIPT_PATH', '{root}/lib:{root}/share/usd/plugins/usdMaya/resources') prependenv('PXR_PLUGINPATH', '{root}/share/usd/plugins') prependenv('CMAKE_MODULE_PATH', '{root}/cmake')
def findMatching(numbers, value): for number1 in numbers: for number2 in numbers: variables = [number1, number2] if (len(set(variables)) != len(variables)): continue if number1 + number2 == value: print("{} + {} = {}, {} * {} = {}".format(number1,number2,value,number1,number2,number1*number2)) return numbers = [] with open("./1/input.txt") as inputFile: for line in inputFile: numbers.append(int(line)) findMatching(numbers, 2020)
def find_matching(numbers, value): for number1 in numbers: for number2 in numbers: variables = [number1, number2] if len(set(variables)) != len(variables): continue if number1 + number2 == value: print('{} + {} = {}, {} * {} = {}'.format(number1, number2, value, number1, number2, number1 * number2)) return numbers = [] with open('./1/input.txt') as input_file: for line in inputFile: numbers.append(int(line)) find_matching(numbers, 2020)
def triangle_reduce(triangle): last = triangle.pop() for i, n in enumerate(triangle[-1]): if last[i] > last[i+1]: triangle[-1][i] = triangle[-1][i] + last[i] else: triangle[-1][i] = triangle[-1][i] + last[i+1] return triangle def solve(triangle): while len(triangle) > 1: triangle = triangle_reduce(triangle) return triangle[0][0]
def triangle_reduce(triangle): last = triangle.pop() for (i, n) in enumerate(triangle[-1]): if last[i] > last[i + 1]: triangle[-1][i] = triangle[-1][i] + last[i] else: triangle[-1][i] = triangle[-1][i] + last[i + 1] return triangle def solve(triangle): while len(triangle) > 1: triangle = triangle_reduce(triangle) return triangle[0][0]
class URL: """ URL config strings """ GPPRO = "https://github.com/martinpaljak/GlobalPlatformPro/releases/" \ "download/v20.01.23/gp.jar" JCALGTEST = "https://github.com/crocs-muni/JCAlgTest/releases/" \ "download/v1.8.0/AlgTest_dist_1.8.0.zip" SMARTCARD_LIST = "http://ludovic.rousseau.free.fr/softwares/pcsc-tools/" \ "smartcard_list.txt" class Paths: """ Path config strings """ GPPRO = "data/bin/gp.jar" JCALGTEST = "data/bin/AlgTestJClient.jar" JCALGTEST_305 = "data/cap/AlgTest_v1.8.0_jc305.cap" JCALGTEST_304 = "data/cap/AlgTest_v1.8.0_jc304.cap" JCALGTEST_222 = "data/cap/AlgTest_v1.8.0_jc222.cap" JCALGTEST_CAPS = [JCALGTEST_305, JCALGTEST_304, JCALGTEST_222] SMARTCARD_LIST = "data/smartcard_list.txt" class MeasureJavaCard: """ Measure Java Card script config strings """ CFG_FILE = "config/measure_javacard/configurations.json" SPEED = { "instant": " You can blink once in the meantime\n", "fast": " Few minutes to fef hours.\n" " You can go make a coffee.\n", "medium": " Up to a few hours.\n" " You can compile Firefox in the meantime.\n", "slow": " Up to tens of hours.\n" " You can compile Gentoo in the meantime.\n" } RISK = { "low": " The test uses standard JCAPI calls\n", "medium": " The tests cause lot of API calls or allocations.\n" " The tests may damage the card.\n", "high": " The tests try to cause undefined behavior.\n" " There is a high possibility of bricking the card.\n" }
class Url: """ URL config strings """ gppro = 'https://github.com/martinpaljak/GlobalPlatformPro/releases/download/v20.01.23/gp.jar' jcalgtest = 'https://github.com/crocs-muni/JCAlgTest/releases/download/v1.8.0/AlgTest_dist_1.8.0.zip' smartcard_list = 'http://ludovic.rousseau.free.fr/softwares/pcsc-tools/smartcard_list.txt' class Paths: """ Path config strings """ gppro = 'data/bin/gp.jar' jcalgtest = 'data/bin/AlgTestJClient.jar' jcalgtest_305 = 'data/cap/AlgTest_v1.8.0_jc305.cap' jcalgtest_304 = 'data/cap/AlgTest_v1.8.0_jc304.cap' jcalgtest_222 = 'data/cap/AlgTest_v1.8.0_jc222.cap' jcalgtest_caps = [JCALGTEST_305, JCALGTEST_304, JCALGTEST_222] smartcard_list = 'data/smartcard_list.txt' class Measurejavacard: """ Measure Java Card script config strings """ cfg_file = 'config/measure_javacard/configurations.json' speed = {'instant': ' You can blink once in the meantime\n', 'fast': ' Few minutes to fef hours.\n You can go make a coffee.\n', 'medium': ' Up to a few hours.\n You can compile Firefox in the meantime.\n', 'slow': ' Up to tens of hours.\n You can compile Gentoo in the meantime.\n'} risk = {'low': ' The test uses standard JCAPI calls\n', 'medium': ' The tests cause lot of API calls or allocations.\n The tests may damage the card.\n', 'high': ' The tests try to cause undefined behavior.\n There is a high possibility of bricking the card.\n'}
class GoogleCredentialsException(Exception): def __init__(self): message = "GCP_JSON or GCP_B64 env variable not set properly" super().__init__(message) class TaskNotFound(Exception): def __init__(self, name: str): message = f"Task {name} not registered." super().__init__(message)
class Googlecredentialsexception(Exception): def __init__(self): message = 'GCP_JSON or GCP_B64 env variable not set properly' super().__init__(message) class Tasknotfound(Exception): def __init__(self, name: str): message = f'Task {name} not registered.' super().__init__(message)
s = "kBNCR9joiFtdAv19AhJ0mHVKassinaPSifCT5bnIrindoudUarwnZxwclalDWjgYudhVD5Sf3Z7looEZCuKQaBIAYTEKn0kQnm2rbwp3KLYsemipalmatusENYyIr6BvCNbuYXeDPFh49tBZQg2Hhw7QrPrAVpyo4RMRRIulZUMBhVNnK1kHFdFM3wxVsvBo3Kq6." a = 23 b = 29 c = 107 d = 118 print (s[a:b + 1] + " " + s[c:d + 1])
s = 'kBNCR9joiFtdAv19AhJ0mHVKassinaPSifCT5bnIrindoudUarwnZxwclalDWjgYudhVD5Sf3Z7looEZCuKQaBIAYTEKn0kQnm2rbwp3KLYsemipalmatusENYyIr6BvCNbuYXeDPFh49tBZQg2Hhw7QrPrAVpyo4RMRRIulZUMBhVNnK1kHFdFM3wxVsvBo3Kq6.' a = 23 b = 29 c = 107 d = 118 print(s[a:b + 1] + ' ' + s[c:d + 1])
def rotate(list, n): return list[n:] + list[:n] def filter_equal_values(lhs, rhs): return [a for a, b in zip(lhs, rhs) if a == b] def sum_as_integers(list_of_strings): return sum(map(int, list_of_strings)) def part_one(input): lhs = list(input) rhs = rotate(lhs, 1) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) def part_two(input): lhs = list(input) rhs = rotate(lhs, len(lhs) // 2) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) if __name__ == "__main__": input = '9513446799636685297929646689682997114316733445451534532351778534251427172168183621874641711534917291674333857423799375512628489423332297538215855176592633692631974822259161766238385922277893623911332569448978771948316155868781496698895492971356383996932885518732997624253678694279666572149831616312497994856288871586777793459926952491318336997159553714584541897294117487641872629796825583725975692264125865827534677223541484795877371955124463989228886498682421539667224963783616245646832154384756663251487668681425754536722827563651327524674183443696227523828832466473538347472991998913211857749878157579176457395375632995576569388455888156465451723693767887681392547189273391948632726499868313747261828186732986628365773728583387184112323696592536446536231376615949825166773536471531487969852535699774113163667286537193767515119362865141925612849443983484245268194842563154567638354645735331855896155142741664246715666899824364722914296492444672653852387389477634257768229772399416521198625393426443499223611843766134883441223328256883497423324753229392393974622181429913535973327323952241674979677481518733692544535323219895684629719868384266425386835539719237716339198485163916562434854579365958111931354576991558771236977242668756782139961638347251644828724786827751748399123668854393894787851872256667336215726674348886747128237416273154988619267824361227888751562445622387695218161341884756795223464751862965655559143779425283154533252573949165492138175581615176611845489857169132936848668646319955661492488428427435269169173654812114842568381636982389224236455633316898178163297452453296667661849622174541778669494388167451186352488555379581934999276412919598411422973399319799937518713422398874326665375216437246445791623283898584648278989674418242112957668397484671119761553847275799873495363759266296477844157237423239163559391553961176475377151369399646747881452252547741718734949967752564774161341784833521492494243662658471121369649641815562327698395293573991648351369767162642763475561544795982183714447737149239846151871434656618825566387329765118727515699213962477996399781652131918996434125559698427945714572488376342126989157872118279163127742349' print(part_one(input)) print(part_two(input))
def rotate(list, n): return list[n:] + list[:n] def filter_equal_values(lhs, rhs): return [a for (a, b) in zip(lhs, rhs) if a == b] def sum_as_integers(list_of_strings): return sum(map(int, list_of_strings)) def part_one(input): lhs = list(input) rhs = rotate(lhs, 1) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) def part_two(input): lhs = list(input) rhs = rotate(lhs, len(lhs) // 2) values = filter_equal_values(lhs, rhs) return sum_as_integers(values) if __name__ == '__main__': input = '9513446799636685297929646689682997114316733445451534532351778534251427172168183621874641711534917291674333857423799375512628489423332297538215855176592633692631974822259161766238385922277893623911332569448978771948316155868781496698895492971356383996932885518732997624253678694279666572149831616312497994856288871586777793459926952491318336997159553714584541897294117487641872629796825583725975692264125865827534677223541484795877371955124463989228886498682421539667224963783616245646832154384756663251487668681425754536722827563651327524674183443696227523828832466473538347472991998913211857749878157579176457395375632995576569388455888156465451723693767887681392547189273391948632726499868313747261828186732986628365773728583387184112323696592536446536231376615949825166773536471531487969852535699774113163667286537193767515119362865141925612849443983484245268194842563154567638354645735331855896155142741664246715666899824364722914296492444672653852387389477634257768229772399416521198625393426443499223611843766134883441223328256883497423324753229392393974622181429913535973327323952241674979677481518733692544535323219895684629719868384266425386835539719237716339198485163916562434854579365958111931354576991558771236977242668756782139961638347251644828724786827751748399123668854393894787851872256667336215726674348886747128237416273154988619267824361227888751562445622387695218161341884756795223464751862965655559143779425283154533252573949165492138175581615176611845489857169132936848668646319955661492488428427435269169173654812114842568381636982389224236455633316898178163297452453296667661849622174541778669494388167451186352488555379581934999276412919598411422973399319799937518713422398874326665375216437246445791623283898584648278989674418242112957668397484671119761553847275799873495363759266296477844157237423239163559391553961176475377151369399646747881452252547741718734949967752564774161341784833521492494243662658471121369649641815562327698395293573991648351369767162642763475561544795982183714447737149239846151871434656618825566387329765118727515699213962477996399781652131918996434125559698427945714572488376342126989157872118279163127742349' print(part_one(input)) print(part_two(input))
"""551. Student Attendance Record I https://leetcode.com/problems/student-attendance-record-i/ """ class Solution: def check_record(self, s: str) -> bool: l_cnt, a_cnt = 0, 0 pre = '' for c in s: if c == 'L': l_cnt += 1 if l_cnt == 3: return False elif pre == 'L': l_cnt = 0 if c == 'A': a_cnt += 1 if a_cnt == 2: return False pre = c return True
"""551. Student Attendance Record I https://leetcode.com/problems/student-attendance-record-i/ """ class Solution: def check_record(self, s: str) -> bool: (l_cnt, a_cnt) = (0, 0) pre = '' for c in s: if c == 'L': l_cnt += 1 if l_cnt == 3: return False elif pre == 'L': l_cnt = 0 if c == 'A': a_cnt += 1 if a_cnt == 2: return False pre = c return True
def KSA(key): S = bytearray(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % len(key)]) % 256 S[i], S[j] = S[j], S[i] return S def PRGA(S): i = 0 j = 0 while True: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] K = S[(S[i] + S[j]) % 256] yield K def RC4(key): S = KSA(key) return PRGA(S)
def ksa(key): s = bytearray(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % len(key)]) % 256 (S[i], S[j]) = (S[j], S[i]) return S def prga(S): i = 0 j = 0 while True: i = (i + 1) % 256 j = (j + S[i]) % 256 (S[i], S[j]) = (S[j], S[i]) k = S[(S[i] + S[j]) % 256] yield K def rc4(key): s = ksa(key) return prga(S)
#------------------------------------------------------------------------------- # Part of tweedledum. This file is distributed under the MIT License. # See accompanying file /LICENSE for details. #------------------------------------------------------------------------------- """Tests."""
"""Tests."""
# # PySNMP MIB module ARP-Spoofing-Prevent-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARP-Spoofing-Prevent-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:09:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection") dlink_common_mgmt, = mibBuilder.importSymbols("DLINK-ID-REC-MIB", "dlink-common-mgmt") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Unsigned32, Counter64, NotificationType, Bits, TimeTicks, ModuleIdentity, Integer32, Counter32, ObjectIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Gauge32, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Counter64", "NotificationType", "Bits", "TimeTicks", "ModuleIdentity", "Integer32", "Counter32", "ObjectIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Gauge32", "iso") RowStatus, MacAddress, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "MacAddress", "DisplayString", "TextualConvention") swARPSpoofingPreventMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 12, 62)) if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setLastUpdated('0805120000Z') if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setOrganization('D-Link Corp.') class PortList(OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 127) swARPSpoofingPreventCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 1)) swARPSpoofingPreventInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 2)) swARPSpoofingPreventMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 3)) swARPSpoofingPreventMgmtTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1), ) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtTable.setStatus('current') swARPSpoofingPreventMgmtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1), ).setIndexNames((0, "ARP-Spoofing-Prevent-MIB", "swARPSpoofingPreventMgmtGatewayIP"), (0, "ARP-Spoofing-Prevent-MIB", "swARPSpoofingPreventMgmtGatewayMAC")) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtEntry.setStatus('current') swARPSpoofingPreventMgmtGatewayIP = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayIP.setStatus('current') swARPSpoofingPreventMgmtGatewayMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 2), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayMAC.setStatus('current') swARPSpoofingPreventMgmtPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 3), PortList()).setMaxAccess("readcreate") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtPorts.setStatus('current') swARPSpoofingPreventMgmtStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: swARPSpoofingPreventMgmtStatus.setStatus('current') mibBuilder.exportSymbols("ARP-Spoofing-Prevent-MIB", swARPSpoofingPreventMgmtGatewayIP=swARPSpoofingPreventMgmtGatewayIP, swARPSpoofingPreventCtrl=swARPSpoofingPreventCtrl, swARPSpoofingPreventMgmtStatus=swARPSpoofingPreventMgmtStatus, swARPSpoofingPreventMgmtTable=swARPSpoofingPreventMgmtTable, swARPSpoofingPreventMgmt=swARPSpoofingPreventMgmt, PYSNMP_MODULE_ID=swARPSpoofingPreventMIB, swARPSpoofingPreventMgmtEntry=swARPSpoofingPreventMgmtEntry, PortList=PortList, swARPSpoofingPreventMgmtPorts=swARPSpoofingPreventMgmtPorts, swARPSpoofingPreventMIB=swARPSpoofingPreventMIB, swARPSpoofingPreventInfo=swARPSpoofingPreventInfo, swARPSpoofingPreventMgmtGatewayMAC=swARPSpoofingPreventMgmtGatewayMAC)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection') (dlink_common_mgmt,) = mibBuilder.importSymbols('DLINK-ID-REC-MIB', 'dlink-common-mgmt') (snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (unsigned32, counter64, notification_type, bits, time_ticks, module_identity, integer32, counter32, object_identity, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, gauge32, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'Counter64', 'NotificationType', 'Bits', 'TimeTicks', 'ModuleIdentity', 'Integer32', 'Counter32', 'ObjectIdentity', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Gauge32', 'iso') (row_status, mac_address, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'MacAddress', 'DisplayString', 'TextualConvention') sw_arp_spoofing_prevent_mib = module_identity((1, 3, 6, 1, 4, 1, 171, 12, 62)) if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setLastUpdated('0805120000Z') if mibBuilder.loadTexts: swARPSpoofingPreventMIB.setOrganization('D-Link Corp.') class Portlist(OctetString): subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 127) sw_arp_spoofing_prevent_ctrl = mib_identifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 1)) sw_arp_spoofing_prevent_info = mib_identifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 2)) sw_arp_spoofing_prevent_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 171, 12, 62, 3)) sw_arp_spoofing_prevent_mgmt_table = mib_table((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1)) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtTable.setStatus('current') sw_arp_spoofing_prevent_mgmt_entry = mib_table_row((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1)).setIndexNames((0, 'ARP-Spoofing-Prevent-MIB', 'swARPSpoofingPreventMgmtGatewayIP'), (0, 'ARP-Spoofing-Prevent-MIB', 'swARPSpoofingPreventMgmtGatewayMAC')) if mibBuilder.loadTexts: swARPSpoofingPreventMgmtEntry.setStatus('current') sw_arp_spoofing_prevent_mgmt_gateway_ip = mib_table_column((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 1), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayIP.setStatus('current') sw_arp_spoofing_prevent_mgmt_gateway_mac = mib_table_column((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 2), mac_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: swARPSpoofingPreventMgmtGatewayMAC.setStatus('current') sw_arp_spoofing_prevent_mgmt_ports = mib_table_column((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 3), port_list()).setMaxAccess('readcreate') if mibBuilder.loadTexts: swARPSpoofingPreventMgmtPorts.setStatus('current') sw_arp_spoofing_prevent_mgmt_status = mib_table_column((1, 3, 6, 1, 4, 1, 171, 12, 62, 3, 1, 1, 4), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: swARPSpoofingPreventMgmtStatus.setStatus('current') mibBuilder.exportSymbols('ARP-Spoofing-Prevent-MIB', swARPSpoofingPreventMgmtGatewayIP=swARPSpoofingPreventMgmtGatewayIP, swARPSpoofingPreventCtrl=swARPSpoofingPreventCtrl, swARPSpoofingPreventMgmtStatus=swARPSpoofingPreventMgmtStatus, swARPSpoofingPreventMgmtTable=swARPSpoofingPreventMgmtTable, swARPSpoofingPreventMgmt=swARPSpoofingPreventMgmt, PYSNMP_MODULE_ID=swARPSpoofingPreventMIB, swARPSpoofingPreventMgmtEntry=swARPSpoofingPreventMgmtEntry, PortList=PortList, swARPSpoofingPreventMgmtPorts=swARPSpoofingPreventMgmtPorts, swARPSpoofingPreventMIB=swARPSpoofingPreventMIB, swARPSpoofingPreventInfo=swARPSpoofingPreventInfo, swARPSpoofingPreventMgmtGatewayMAC=swARPSpoofingPreventMgmtGatewayMAC)
def regras(x): if x < 100: if x % 2 == 0: return x else: return (x + x) lista = [100, 200, 1000, 3000, 2, 3, 4, 5, 6, 7, 8] print(list(filter(regras,lista))) #https://pt.stackoverflow.com/q/321682/101
def regras(x): if x < 100: if x % 2 == 0: return x else: return x + x lista = [100, 200, 1000, 3000, 2, 3, 4, 5, 6, 7, 8] print(list(filter(regras, lista)))
class WarmUpScheduler(): def __init__(self,optimizer, init_lr, d_model, n_warmup_steps): self._optimizer=optimizer self.init_lr=init_lr self.d_model=d_model self.n_warmup_steps=n_warmup_steps self._steps = 0 def step(self): r"""Update parameters""" self._update_learning_rate() self._optimizer.step() def _update_learning_rate(self): r"""Learning rate scheduling per step""" self._steps += 1 lr = self.init_lr * self._get_lr_scale() for param_group in self._optimizer.param_groups: param_group['lr'] = lr def _get_lr_scale(self): d_model = self.d_model n_steps, n_warmup_steps = self._steps, self.n_warmup_steps return (d_model ** -0.5) * min(n_steps ** (-0.5), n_steps * n_warmup_steps ** (-1.5)) def zero_grad(self): self._optimizer.zero_grad() def state_dict(self): return self._optimizer.state_dict() def load_state_dict(self,state_dict): self._optimizer.load_state_dict(state_dict) def get_lr(self): lr = self.init_lr * self._get_lr_scale() return [lr]
class Warmupscheduler: def __init__(self, optimizer, init_lr, d_model, n_warmup_steps): self._optimizer = optimizer self.init_lr = init_lr self.d_model = d_model self.n_warmup_steps = n_warmup_steps self._steps = 0 def step(self): """Update parameters""" self._update_learning_rate() self._optimizer.step() def _update_learning_rate(self): """Learning rate scheduling per step""" self._steps += 1 lr = self.init_lr * self._get_lr_scale() for param_group in self._optimizer.param_groups: param_group['lr'] = lr def _get_lr_scale(self): d_model = self.d_model (n_steps, n_warmup_steps) = (self._steps, self.n_warmup_steps) return d_model ** (-0.5) * min(n_steps ** (-0.5), n_steps * n_warmup_steps ** (-1.5)) def zero_grad(self): self._optimizer.zero_grad() def state_dict(self): return self._optimizer.state_dict() def load_state_dict(self, state_dict): self._optimizer.load_state_dict(state_dict) def get_lr(self): lr = self.init_lr * self._get_lr_scale() return [lr]
def merge(a1, a2): ma = [] i1, i2 = 0, 0 while i1 < len(a1) and i2 < len(a2): if a1[i1] < a2[i2]: ma.append(a1[i1]) i1 += 1 else: ma.append(a2[i2]) i2 += 1 while i1 < len(a1): ma.append(a1[i1]) i1 += 1 while i2 < len(a2): ma.append(a2[i2]) i2 += 1 return ma
def merge(a1, a2): ma = [] (i1, i2) = (0, 0) while i1 < len(a1) and i2 < len(a2): if a1[i1] < a2[i2]: ma.append(a1[i1]) i1 += 1 else: ma.append(a2[i2]) i2 += 1 while i1 < len(a1): ma.append(a1[i1]) i1 += 1 while i2 < len(a2): ma.append(a2[i2]) i2 += 1 return ma
def wrap(string, max_width): wrapper = textwrap.TextWrapper(width=max_width) word_list = wrapper.wrap(text=string) lastWrap = word_list[-1] for element in word_list: if element != lastWrap: print(element) return lastWrap
def wrap(string, max_width): wrapper = textwrap.TextWrapper(width=max_width) word_list = wrapper.wrap(text=string) last_wrap = word_list[-1] for element in word_list: if element != lastWrap: print(element) return lastWrap
def flatten(some_list): """ Flatten a list of lists. Usage: flatten([[list a], [list b], ...]) Output: [elements of list a, elements of list b] """ new_list = [] for sub_list in some_list: new_list += sub_list return new_list def recursive_radix_sort(some_list, idex=None, size=None): """ Recursive radix sort Usage: radix([unsorted list]) Output: [sorted list] """ # Initialize variables not set in the initial call if size == None: largest_num = max(some_list) largest_num_str = str(largest_num) largest_num_len = len(largest_num_str) size = largest_num_len if idex == None: idex = size # Translate the index we're looking at into an array index. # e.g., looking at the 10's place for 100: # size: 3 # idex: 2 # i: (3-2) == 1 # str(123)[i] -> 2 i = size - idex # The recursive base case. # Hint: out of range indexing errors if i >= size: return some_list # Initialize the bins we will place numbers into bins = [[] for _ in range(10)] # Iterate over the list of numbers we are given for e in some_list: # The destination bin; e.g.,: # size: 5 # e: 29 # num_s: '00029' # i: 3 # dest_c: '2' # dest_i: 2 num_s = str(e).zfill(size) dest_c = num_s[i] dest_i = int(dest_c) bins[dest_i] += [e] result = [] for b in bins: # Make the recursive call # Sort each of the sub-lists in our bins result.append(recursive_radix_sort(b, idex-1, size)) # Flatten our list # This is also called in our recursive call, # so we don't need flatten to be recursive. flattened_result = flatten(result) return flattened_result def iterative_radix_sort(alist, base=10): if alist == []: return def key_factory(digit, base): def key(alist, index): return ((alist[index]//(base**digit)) % base) return key largest = max(alist) exp = 0 while base**exp <= largest: alist = counting_sort(alist, base - 1, key_factory(exp, base)) exp = exp + 1 return alist def counting_sort(alist, largest, key): c = [0]*(largest + 1) for i in range(len(alist)): c[key(alist, i)] = c[key(alist, i)] + 1 # Find the last index for each element c[0] = c[0] - 1 # to decrement each element for zero-based indexing for i in range(1, largest + 1): c[i] = c[i] + c[i - 1] result = [None]*len(alist) for i in range(len(alist) - 1, -1, -1): result[c[key(alist, i)]] = alist[i] c[key(alist, i)] = c[key(alist, i)] - 1 return result
def flatten(some_list): """ Flatten a list of lists. Usage: flatten([[list a], [list b], ...]) Output: [elements of list a, elements of list b] """ new_list = [] for sub_list in some_list: new_list += sub_list return new_list def recursive_radix_sort(some_list, idex=None, size=None): """ Recursive radix sort Usage: radix([unsorted list]) Output: [sorted list] """ if size == None: largest_num = max(some_list) largest_num_str = str(largest_num) largest_num_len = len(largest_num_str) size = largest_num_len if idex == None: idex = size i = size - idex if i >= size: return some_list bins = [[] for _ in range(10)] for e in some_list: num_s = str(e).zfill(size) dest_c = num_s[i] dest_i = int(dest_c) bins[dest_i] += [e] result = [] for b in bins: result.append(recursive_radix_sort(b, idex - 1, size)) flattened_result = flatten(result) return flattened_result def iterative_radix_sort(alist, base=10): if alist == []: return def key_factory(digit, base): def key(alist, index): return alist[index] // base ** digit % base return key largest = max(alist) exp = 0 while base ** exp <= largest: alist = counting_sort(alist, base - 1, key_factory(exp, base)) exp = exp + 1 return alist def counting_sort(alist, largest, key): c = [0] * (largest + 1) for i in range(len(alist)): c[key(alist, i)] = c[key(alist, i)] + 1 c[0] = c[0] - 1 for i in range(1, largest + 1): c[i] = c[i] + c[i - 1] result = [None] * len(alist) for i in range(len(alist) - 1, -1, -1): result[c[key(alist, i)]] = alist[i] c[key(alist, i)] = c[key(alist, i)] - 1 return result
needed_money = float(input()) owned_money = float(input()) days_counter = 0 spending_counter = 0 while True: action = input() amount = float(input()) days_counter += 1 if action == "spend": owned_money -= amount spending_counter += 1 if owned_money < 0: owned_money = 0 if spending_counter >= 5: print("You can\'t save the money.") print(f"{days_counter}") break else: owned_money += amount spending_counter = 0 if owned_money >= needed_money: print(f"You saved the money for {days_counter} days.") break
needed_money = float(input()) owned_money = float(input()) days_counter = 0 spending_counter = 0 while True: action = input() amount = float(input()) days_counter += 1 if action == 'spend': owned_money -= amount spending_counter += 1 if owned_money < 0: owned_money = 0 if spending_counter >= 5: print("You can't save the money.") print(f'{days_counter}') break else: owned_money += amount spending_counter = 0 if owned_money >= needed_money: print(f'You saved the money for {days_counter} days.') break
# Tanner Bornemann # Lab00 - Python Programming - Section 001 # 2017-01-13 def twenty_seventeen(): """Come up with the most creative expression that evaluates to 2017, using only numbers and the +, *, and - operators. >>> twenty_seventeen() 2017 >>> twenty_seventeen() + twenty_seventeen() 4034 >>> twenty_seventeen() * 3 6051 >>> twenty_seventeen() / 2 1008.5 """ return (9 * 9) + ((22 * 2) * 44)
def twenty_seventeen(): """Come up with the most creative expression that evaluates to 2017, using only numbers and the +, *, and - operators. >>> twenty_seventeen() 2017 >>> twenty_seventeen() + twenty_seventeen() 4034 >>> twenty_seventeen() * 3 6051 >>> twenty_seventeen() / 2 1008.5 """ return 9 * 9 + 22 * 2 * 44
DESCRIBE_GATEWAYS = [ { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-1234XXX", "OwnerId": "012345678912", "Tags": [ { "Key": "Name", "Value": "InternetGateway", }, ], }, { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-7e3a7c18", "OwnerId": "012345678912", "Tags": [ { "Key": "AWSServiceAccount", "Value": "697148468905", }, ], }, { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-f1c81494", "OwnerId": "012345678912", "Tags": [], }, ]
describe_gateways = [{'Attachments': [{'State': 'available', 'VpcId': 'vpc-XXXXXXX'}], 'InternetGatewayId': 'igw-1234XXX', 'OwnerId': '012345678912', 'Tags': [{'Key': 'Name', 'Value': 'InternetGateway'}]}, {'Attachments': [{'State': 'available', 'VpcId': 'vpc-XXXXXXX'}], 'InternetGatewayId': 'igw-7e3a7c18', 'OwnerId': '012345678912', 'Tags': [{'Key': 'AWSServiceAccount', 'Value': '697148468905'}]}, {'Attachments': [{'State': 'available', 'VpcId': 'vpc-XXXXXXX'}], 'InternetGatewayId': 'igw-f1c81494', 'OwnerId': '012345678912', 'Tags': []}]
''' 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 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 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_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_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 send_ssh_public_key(InstanceId=None, InstanceOSUser=None, SSHPublicKey=None, AvailabilityZone=None): """ Pushes an SSH public key to a particular OS user on a given EC2 instance for 60 seconds. See also: AWS API Documentation Exceptions :example: response = client.send_ssh_public_key( InstanceId='string', InstanceOSUser='string', SSHPublicKey='string', AvailabilityZone='string' ) :type InstanceId: string :param InstanceId: [REQUIRED]\nThe EC2 instance you wish to publish the SSH key to.\n :type InstanceOSUser: string :param InstanceOSUser: [REQUIRED]\nThe OS user on the EC2 instance whom the key may be used to authenticate as.\n :type SSHPublicKey: string :param SSHPublicKey: [REQUIRED]\nThe public key to be published to the instance. To use it after publication you must have the matching private key.\n :type AvailabilityZone: string :param AvailabilityZone: [REQUIRED]\nThe availability zone the EC2 instance was launched in.\n :rtype: dict ReturnsResponse Syntax { 'RequestId': 'string', 'Success': True|False } Response Structure (dict) -- RequestId (string) -- The request ID as logged by EC2 Connect. Please provide this when contacting AWS Support. Success (boolean) -- Indicates request success. Exceptions EC2InstanceConnect.Client.exceptions.AuthException EC2InstanceConnect.Client.exceptions.InvalidArgsException EC2InstanceConnect.Client.exceptions.ServiceException EC2InstanceConnect.Client.exceptions.ThrottlingException EC2InstanceConnect.Client.exceptions.EC2InstanceNotFoundException :return: { 'RequestId': 'string', 'Success': True|False } :returns: EC2InstanceConnect.Client.exceptions.AuthException EC2InstanceConnect.Client.exceptions.InvalidArgsException EC2InstanceConnect.Client.exceptions.ServiceException EC2InstanceConnect.Client.exceptions.ThrottlingException EC2InstanceConnect.Client.exceptions.EC2InstanceNotFoundException """ pass
""" 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 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 as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator('create_foo'). """ 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 ClientMethod. :type ExpiresIn: int :param ExpiresIn: The number of seconds the presigned url is valid for. By default it expires in an hour (3600 seconds) :type HttpMethod: string :param HttpMethod: The http method to use on the generated url. By default, the http method is whatever is used in the method's model. """ 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 as the method name on the client. For example, if the method name is create_foo, and you'd normally invoke the operation as client.create_foo(**kwargs), if the create_foo operation can be paginated, you can use the call client.get_paginator('create_foo'). :rtype: L{botocore.paginate.Paginator} ReturnsA paginator object. """ 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 section of the service docs for a list of available waiters. :rtype: botocore.waiter.Waiter """ pass def send_ssh_public_key(InstanceId=None, InstanceOSUser=None, SSHPublicKey=None, AvailabilityZone=None): """ Pushes an SSH public key to a particular OS user on a given EC2 instance for 60 seconds. See also: AWS API Documentation Exceptions :example: response = client.send_ssh_public_key( InstanceId='string', InstanceOSUser='string', SSHPublicKey='string', AvailabilityZone='string' ) :type InstanceId: string :param InstanceId: [REQUIRED] The EC2 instance you wish to publish the SSH key to. :type InstanceOSUser: string :param InstanceOSUser: [REQUIRED] The OS user on the EC2 instance whom the key may be used to authenticate as. :type SSHPublicKey: string :param SSHPublicKey: [REQUIRED] The public key to be published to the instance. To use it after publication you must have the matching private key. :type AvailabilityZone: string :param AvailabilityZone: [REQUIRED] The availability zone the EC2 instance was launched in. :rtype: dict ReturnsResponse Syntax { 'RequestId': 'string', 'Success': True|False } Response Structure (dict) -- RequestId (string) -- The request ID as logged by EC2 Connect. Please provide this when contacting AWS Support. Success (boolean) -- Indicates request success. Exceptions EC2InstanceConnect.Client.exceptions.AuthException EC2InstanceConnect.Client.exceptions.InvalidArgsException EC2InstanceConnect.Client.exceptions.ServiceException EC2InstanceConnect.Client.exceptions.ThrottlingException EC2InstanceConnect.Client.exceptions.EC2InstanceNotFoundException :return: { 'RequestId': 'string', 'Success': True|False } :returns: EC2InstanceConnect.Client.exceptions.AuthException EC2InstanceConnect.Client.exceptions.InvalidArgsException EC2InstanceConnect.Client.exceptions.ServiceException EC2InstanceConnect.Client.exceptions.ThrottlingException EC2InstanceConnect.Client.exceptions.EC2InstanceNotFoundException """ pass
""" Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards. """ fruit = 'banana' i = len(fruit) - 1 while i >= 0: print(fruit[i]) i -= 1 # for ch in fruit[::-1]: # print(ch)
""" Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards. """ fruit = 'banana' i = len(fruit) - 1 while i >= 0: print(fruit[i]) i -= 1
# Time: O(n^2); Space: O(1) def time_required_to_buy(tickets, k): time = 0 while tickets[k] > 0: for i, t in enumerate(tickets): if t > 0: time += 1 tickets[i] -= 1 if tickets[k] == 0: break return time # Time: O(n); Space: O(1) def time_required_to_buy2(tickets, k): time = tickets[k] # it has to buy all at kth position for i in range(len(tickets)): if i < k: time += min(tickets[i], tickets[k]) # for all pos before k it will exhaust all tickets or get till number till kth place elif i > k: time += min(tickets[i], tickets[k] - 1) # for all pos after k it can exhaust all tickets or get 1 less than the kth gets finished return time # Test cases: print(time_required_to_buy(tickets=[2, 3, 2], k=2)) print(time_required_to_buy(tickets=[5, 1, 1, 1], k=0))
def time_required_to_buy(tickets, k): time = 0 while tickets[k] > 0: for (i, t) in enumerate(tickets): if t > 0: time += 1 tickets[i] -= 1 if tickets[k] == 0: break return time def time_required_to_buy2(tickets, k): time = tickets[k] for i in range(len(tickets)): if i < k: time += min(tickets[i], tickets[k]) elif i > k: time += min(tickets[i], tickets[k] - 1) return time print(time_required_to_buy(tickets=[2, 3, 2], k=2)) print(time_required_to_buy(tickets=[5, 1, 1, 1], k=0))
# -*- coding: utf-8 -*- proxies = ( # '115.229.93.123:9000', # '114.249.116.183:9000', # '14.118.252.68:6666', # '115.229.93.123:9000', )
proxies = ()
# Django settings for yawf_sample project. DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } SITE_ID = 1 # Make this unique, and don't share it with anybody. SECRET_KEY = 'ufq^a%n=9#nbs(_p09c5gvqt(f-7td3$h8tmfbl)(1o9p)226u' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'yawf_sample.urls' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'yawf', 'yawf.message_log', 'yawf_sample.simple', 'reversion', 'django.contrib.admin', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.CallbackFilter', 'callback': lambda r: not DEBUG } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'yawf': { 'handlers': ['console'], 'level': 'WARNING', 'propagate': True, } } } YAWF_CONFIG = { 'DYNAMIC_WORKFLOW_ENABLED': True, 'MESSAGE_LOG_ENABLED': True, 'USE_SELECT_FOR_UPDATE': False, } SOUTH_TESTS_MIGRATE = False
debug = True template_debug = DEBUG databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': ''}} site_id = 1 secret_key = 'ufq^a%n=9#nbs(_p09c5gvqt(f-7td3$h8tmfbl)(1o9p)226u' middleware_classes = ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') root_urlconf = 'yawf_sample.urls' installed_apps = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'yawf', 'yawf.message_log', 'yawf_sample.simple', 'reversion', 'django.contrib.admin') logging = {'version': 1, 'disable_existing_loggers': False, 'filters': {'require_debug_false': {'()': 'django.utils.log.CallbackFilter', 'callback': lambda r: not DEBUG}}, 'handlers': {'console': {'level': 'DEBUG', 'class': 'logging.StreamHandler'}, 'mail_admins': {'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler'}}, 'loggers': {'django.request': {'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True}, 'yawf': {'handlers': ['console'], 'level': 'WARNING', 'propagate': True}}} yawf_config = {'DYNAMIC_WORKFLOW_ENABLED': True, 'MESSAGE_LOG_ENABLED': True, 'USE_SELECT_FOR_UPDATE': False} south_tests_migrate = False
# DAY 4- ACTIVITY 3 # Program Description: This is a simple word bank program. It takes in the user's input and turns it into a string # which will then be stored into the word bank list. After the user is done inputting his desired words, the program # will print out the elements inside the word bank list. # The list that will act as the word bank. bankList = [] continueRunning = True while continueRunning: # will use try-except method just in case something is wrong with the inputs that the user had entered. try: # the program will convert the user's input into a string. # Then, it will append the word into the bankList. print ( "\n-------------------- ENTER DETAILS --------------------" ) word = str ( input ( " Enter a word ( string ) : " ) ) print ( "-------------------------------------------------------\n" ) bankList.append( word ) print ( " {} has been stored in the word bank. \n".format( word ) ) print ( "-------------------------------------------------------\n" ) # Here, the program will ask the user if he would like to continue using the program. # If yes, the user will be able to continue adding more words into the bank list. # If not, the program will print out the elements inside the bankList. hasChosen = False while hasChosen == False: try: userChoice = str ( input ( " Would you like to try again? Y/y if Yes and N/n if No. " ) ) if userChoice.lower() == "y" or userChoice.lower() == "yes" : hasChosen = True elif userChoice.lower() == "n" or userChoice.lower() == "no" : print ( "\n-------------------------------------------------------\n" ) print ( " The word bank contains: " ) for x in bankList: print ( " - {}.".format( x ) ) print ( "\n-------------------------------------------------------\n" ) continueRunning = False hasChosen = True else: print ( " Invalid Input. " ) except: print ( " Invalid Input. " ) except: print ( " Invalid Input. " )
bank_list = [] continue_running = True while continueRunning: try: print('\n-------------------- ENTER DETAILS --------------------') word = str(input(' Enter a word ( string ) : ')) print('-------------------------------------------------------\n') bankList.append(word) print(' {} has been stored in the word bank. \n'.format(word)) print('-------------------------------------------------------\n') has_chosen = False while hasChosen == False: try: user_choice = str(input(' Would you like to try again? Y/y if Yes and N/n if No. ')) if userChoice.lower() == 'y' or userChoice.lower() == 'yes': has_chosen = True elif userChoice.lower() == 'n' or userChoice.lower() == 'no': print('\n-------------------------------------------------------\n') print(' The word bank contains: ') for x in bankList: print(' - {}.'.format(x)) print('\n-------------------------------------------------------\n') continue_running = False has_chosen = True else: print(' Invalid Input. ') except: print(' Invalid Input. ') except: print(' Invalid Input. ')
############################################################################### # Monitor plot arrays # ############################################################################### tag = "monitor" varpos = { 'time': 0, 'x': 1, 'y': 2, 'z': 3, 'uindex': 4, 'i': 5, 'j': 6, 'k': 7, 'head': 8, 'temp': 9, 'pres': 10, 'satn': 11, 'epot': 12, 'conc0001': 13, # 'vx': 13, # 'vy': 14, # 'vz': 15, # 'bhpr': 16, # 'kz' : 17, }
tag = 'monitor' varpos = {'time': 0, 'x': 1, 'y': 2, 'z': 3, 'uindex': 4, 'i': 5, 'j': 6, 'k': 7, 'head': 8, 'temp': 9, 'pres': 10, 'satn': 11, 'epot': 12, 'conc0001': 13}
""" Description: A demo of the different forms of string Literals available. SEE: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals """ # Raw strings; These are strings that will completely ignore special characters such as \n or \t my_string = "Hello \n\tWorld" print(my_string) """Would print: Hello World""" my_string = r"Hello \n\tWorld" # Also works with R"Hello \n\tWorld" print(my_string) # Would print: Hello \n\tWorld # Byte strings; These take the string provided and build a bytes object. # SEE: https://www.python.org/dev/peps/pep-3112/ For reference about byte string literals # SEE: https://docs.python.org/3/library/stdtypes.html#bytes For referenec about byte objects my_string = "Hello" print(type(my_string)) my_string = b"Hello" print(type(my_string)) """Unicode Literals; Unicode literals are no longer necessary, but some legacy code may contain them. It creates a unicode object with the string as the argument SEE: https://docs.python.org/3/c-api/unicode.html""" my_string = "Hello" print(type(my_string)) my_string = u"Hello" print(type(my_string)) """FStrings; Format strings can be seen in more detail in string_formatting.py. But the basics are it allows you to construct strings using variables""" name = "John Doe" greeting = f"Hello, {name}" print(greeting)
""" Description: A demo of the different forms of string Literals available. SEE: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals """ my_string = 'Hello \n\tWorld' print(my_string) 'Would print:\nHello \n World' my_string = 'Hello \\n\\tWorld' print(my_string) my_string = 'Hello' print(type(my_string)) my_string = b'Hello' print(type(my_string)) 'Unicode Literals; Unicode literals are no longer necessary, \n but some legacy code may contain them. It creates a unicode object with the string as the argument\n SEE: https://docs.python.org/3/c-api/unicode.html' my_string = 'Hello' print(type(my_string)) my_string = u'Hello' print(type(my_string)) 'FStrings; Format strings can be seen in more detail in string_formatting.py. \n But the basics are it allows you to construct strings using variables' name = 'John Doe' greeting = f'Hello, {name}' print(greeting)
def greeting_user(fname,lname): print(f"Hi {fname} {lname} !") print("How are you?") print("start") greeting_user("Lois") # we can add positional argument, this means position of the argument can shifted around # greeting_user(lname= "tracy", fname="Andrew") print("end")
def greeting_user(fname, lname): print(f'Hi {fname} {lname} !') print('How are you?') print('start') greeting_user('Lois') print('end')
DEFAULT_REGION = 'us-west-1' AMAZON_LINUX_AMI_US_WEST_2 = "ami-04534c96466647bfb" # installs and starts ngnix, nothing else USER_DATA = """ #!/bin/bash sudo amazon-linux-extras install nginx1.12 -y sudo chkconfig nginx on sudo service nginx start # to generate CPU load on start up for autoscaling debugging #cat /dev/zero > /dev/null """ SCALING_DEFAULT_TARGET_VALUE_PERCENT = 70 ASSOCIATE_PUBLIC_IP_BY_DEFAULT = True DEFAULT_COOLDOWN_SECONDS = 300 HEATHCHECK_GRACE_PERIOD_SECONDS = 120 LOGGING_STR_SIZE = 60
default_region = 'us-west-1' amazon_linux_ami_us_west_2 = 'ami-04534c96466647bfb' user_data = '\n#!/bin/bash\nsudo amazon-linux-extras install nginx1.12 -y\nsudo chkconfig nginx on\nsudo service nginx start\n# to generate CPU load on start up for autoscaling debugging\n#cat /dev/zero > /dev/null\n' scaling_default_target_value_percent = 70 associate_public_ip_by_default = True default_cooldown_seconds = 300 heathcheck_grace_period_seconds = 120 logging_str_size = 60
class Repository(object): def __init__(self, pkgs=None): """ A Repository object stores and manages packages this way, we can use multiple package indices at once. """ if pkgs is None: pkgs = {} self.pkgs = pkgs def add(self, pkg): """ Add a single package to this Repository, if it already exists, then overwrite it. """ if pkg.name in self.pkgs: if ( pkg.version.upstream_version < self.pkgs[pkg.name].version.upstream_version ): return self.pkgs[pkg.name] = pkg def update(self, pkgs): """ Update this repository with dictionary of packages if this repository has already been populated with packages, then merge this repository with the packages. """ if pkgs: return self.merge(Repository(pkgs)) self.pkgs = pkgs return self def merge(self, other): """ Merge this repository with another repository, for now let's overwrite the packages in this repository with the packages in the other repository if they alreadu exist. """ if not other.is_empty(): for pkg in other.pkgs.values(): self.add(pkg) return self def is_empty(self): """ Return true if this repository has no packages. """ return not bool(self.pkgs) def __getitem__(self, key): return self.pkgs.get(key, None) def __contains__(self, key): return key in self.pkgs
class Repository(object): def __init__(self, pkgs=None): """ A Repository object stores and manages packages this way, we can use multiple package indices at once. """ if pkgs is None: pkgs = {} self.pkgs = pkgs def add(self, pkg): """ Add a single package to this Repository, if it already exists, then overwrite it. """ if pkg.name in self.pkgs: if pkg.version.upstream_version < self.pkgs[pkg.name].version.upstream_version: return self.pkgs[pkg.name] = pkg def update(self, pkgs): """ Update this repository with dictionary of packages if this repository has already been populated with packages, then merge this repository with the packages. """ if pkgs: return self.merge(repository(pkgs)) self.pkgs = pkgs return self def merge(self, other): """ Merge this repository with another repository, for now let's overwrite the packages in this repository with the packages in the other repository if they alreadu exist. """ if not other.is_empty(): for pkg in other.pkgs.values(): self.add(pkg) return self def is_empty(self): """ Return true if this repository has no packages. """ return not bool(self.pkgs) def __getitem__(self, key): return self.pkgs.get(key, None) def __contains__(self, key): return key in self.pkgs
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): if not root: return while root: if root.left: node = root.left while node.right: node = node.right node.right = root.right root.right = root.left root.left = None root = root.right
class Solution(object): def flatten(self, root): if not root: return while root: if root.left: node = root.left while node.right: node = node.right node.right = root.right root.right = root.left root.left = None root = root.right
#Nesting Loops in Loops outer = ['Li','Na','K'] inner = ['F', 'Cl', 'Br'] for metal in outer: for halogen in inner: print(metal + halogen)
outer = ['Li', 'Na', 'K'] inner = ['F', 'Cl', 'Br'] for metal in outer: for halogen in inner: print(metal + halogen)
# https://codeforces.com/contest/1327/problem/A for _ in range(int(input())): n, k = map(int, input().split()) print("YES" if n % 2 == k % 2 and n >= k * k else "NO")
for _ in range(int(input())): (n, k) = map(int, input().split()) print('YES' if n % 2 == k % 2 and n >= k * k else 'NO')
__all__ = [ 'box.py', 'servers.py', 'network.py' ]
__all__ = ['box.py', 'servers.py', 'network.py']
def main(): while True: text = input("Text: ") if len(text) > 0: break letter = 0 word = 1 sentence = 0 for c in text: c = c.upper() if c >= "A" and c <= "Z": letter += 1 if c == " ": word += 1 if c == "." or c == "!" or c == "?": sentence += 1 # print(f"letter: {letter} word: {word} sentence: {sentence}") index = coleman_liau_index(letter, word, sentence) if index > 16: print("Grade 16+") elif index < 1: print("Before Grade 1") else: print(f"Grade {index}") def coleman_liau_index(letter, word, sentence): return round(0.0588 * (letter * 100.0 / word) - 0.296 * (sentence * 100.0 / word) - 15.8) if __name__ == "__main__": main()
def main(): while True: text = input('Text: ') if len(text) > 0: break letter = 0 word = 1 sentence = 0 for c in text: c = c.upper() if c >= 'A' and c <= 'Z': letter += 1 if c == ' ': word += 1 if c == '.' or c == '!' or c == '?': sentence += 1 index = coleman_liau_index(letter, word, sentence) if index > 16: print('Grade 16+') elif index < 1: print('Before Grade 1') else: print(f'Grade {index}') def coleman_liau_index(letter, word, sentence): return round(0.0588 * (letter * 100.0 / word) - 0.296 * (sentence * 100.0 / word) - 15.8) if __name__ == '__main__': main()
class ComposeScript: def __init__(self, name, deploy=None, ready_check=None, output_extraction=None, cleanup_on=None, unique_by=None): self.name = name self.deploy = deploy if deploy is not None else [] self.cleanup_on = cleanup_on self.unique_by = unique_by self.ready_check = ready_check self.output_extraction = output_extraction
class Composescript: def __init__(self, name, deploy=None, ready_check=None, output_extraction=None, cleanup_on=None, unique_by=None): self.name = name self.deploy = deploy if deploy is not None else [] self.cleanup_on = cleanup_on self.unique_by = unique_by self.ready_check = ready_check self.output_extraction = output_extraction
BASE_62_CHAR_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def base62_to_int(part: str) -> int: """ Simple base 62 to integer computation """ t = 0 for c in part: t = t * 62 + BASE_62_CHAR_SET.index(c) return t def get_partition(url_token: str): """ Extract partition from url token. (Based on JS code) """ partition = 0 if 'A' == url_token[0]: partition = base62_to_int([url_token[1]]) else: partition = base62_to_int(url_token[1:3]) return partition
base_62_char_set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' def base62_to_int(part: str) -> int: """ Simple base 62 to integer computation """ t = 0 for c in part: t = t * 62 + BASE_62_CHAR_SET.index(c) return t def get_partition(url_token: str): """ Extract partition from url token. (Based on JS code) """ partition = 0 if 'A' == url_token[0]: partition = base62_to_int([url_token[1]]) else: partition = base62_to_int(url_token[1:3]) return partition
class EmptyChildProxy: """ Bad because does not extends dalec.proxy.Proxy """ app = "empty_child" def _fetch(self, *args, **kwargs): print("Are you my mummy?")
class Emptychildproxy: """ Bad because does not extends dalec.proxy.Proxy """ app = 'empty_child' def _fetch(self, *args, **kwargs): print('Are you my mummy?')
class Luhn: """ Given a number determine whether or not it is valid per the Luhn formula. """ def __init__(self, card_num: str): self.card_num = card_num.replace(' ', '') self.__card_num_list = \ [int(char) for char in self.card_num if char.isdigit()] self.__digits_processor() # Declaring private method def __digits_processor(self): """ The first step of the Luhn algorithm is to double every second digit, starting from the right. If doubling the number results in a number greater than 9 then subtract 9 from the product. :return: """ for i in range(len(self.__card_num_list) - 2, -1, -2): self.__card_num_list[i] = self.__card_num_list[i] * 2 if self.__card_num_list[i] > 9: self.__card_num_list[i] = self.__card_num_list[i] - 9 def valid(self) -> bool: """ Sum all of the digits. If the sum is evenly divisible by 10, then the number is valid. :return: """ for char in self.card_num: if not char.isdigit(): return False if len(self.card_num) < 2: return False return sum(self.__card_num_list) % 10 == 0
class Luhn: """ Given a number determine whether or not it is valid per the Luhn formula. """ def __init__(self, card_num: str): self.card_num = card_num.replace(' ', '') self.__card_num_list = [int(char) for char in self.card_num if char.isdigit()] self.__digits_processor() def __digits_processor(self): """ The first step of the Luhn algorithm is to double every second digit, starting from the right. If doubling the number results in a number greater than 9 then subtract 9 from the product. :return: """ for i in range(len(self.__card_num_list) - 2, -1, -2): self.__card_num_list[i] = self.__card_num_list[i] * 2 if self.__card_num_list[i] > 9: self.__card_num_list[i] = self.__card_num_list[i] - 9 def valid(self) -> bool: """ Sum all of the digits. If the sum is evenly divisible by 10, then the number is valid. :return: """ for char in self.card_num: if not char.isdigit(): return False if len(self.card_num) < 2: return False return sum(self.__card_num_list) % 10 == 0
while True: try: S = input() count = 0 for k in input(): if k in S: count += 1 print(count) except: break
while True: try: s = input() count = 0 for k in input(): if k in S: count += 1 print(count) except: break
# def main(): # x, y, z = (int(x) for x in input().strip().split()) # result = 0 # if 1 <= x <= 31 and 1 <= y <= 12: # result += 1 # if 1 <= y <= 31 and 1 <= x <= 12: # result += 1 # print(result % 2) # # # main() def main(): a, b, c = map(int, input().split()) if a == b: print(1) elif b <= 12 and a <= 12: print(0) else: print(1) main()
def main(): (a, b, c) = map(int, input().split()) if a == b: print(1) elif b <= 12 and a <= 12: print(0) else: print(1) main()
buy_schema = { 'items': [ { 'itemKey': { 'inventoryType': 'CHAMPION', 'itemId': -1 }, 'purchaseCurrencyInfo': { 'currencyType': 'IP', 'price': -1, 'purchasable': True }, 'quantity': 1, 'source': 'cdp' } ] }
buy_schema = {'items': [{'itemKey': {'inventoryType': 'CHAMPION', 'itemId': -1}, 'purchaseCurrencyInfo': {'currencyType': 'IP', 'price': -1, 'purchasable': True}, 'quantity': 1, 'source': 'cdp'}]}
#class Solution(object): # def isNumber(self, s): # """ # :type s: str # :rtype: bool # """ # if s == '': return False # if s.strip() == '.': return False # # define the Deterministic Finite Automata # dfa = [ # DFA init: q0, valid: q2,q4,q7,q8 # {'blank':0, 'sign':1, 'digit':2, 'dot':3}, # q0 # {'digit':2, 'dot':3}, # q1 # {'digit':2, 'dot':3, 'e':5, 'blank':8}, # q2 # {'digit':4, 'e':5, 'blank':8}, # q3 # {'digit':4, 'e':5, 'blank':8}, # q4 # {'digit':7, 'sign':6}, # q5 # {'digit':7}, # q6 # {'blank':8, 'digit':7}, # q7 # {'blank':8}, # q8 # ] # state = 0 # # run the automata # for char in s: # #print(' * cursor char ', char, 'state', state) # # determine the type # if char.isnumeric(): # char_t = 'digit' # elif char == '.': # char_t = 'dot' # elif char.isspace(): # char_t = 'blank' # elif char == '+' or char == '-': # char_t = 'sign' # elif char == 'e': # char_t = 'e' # else: # return False # #print(' * cursor char is', char_t) # # is the type valid at current state? # if char_t not in dfa[state].keys(): # #print(' * invalid convertion') # return False # # go to next state # state = dfa[state][char_t] # #print(' * goto', state) # # is the final state of automata valid? # if state not in [2,3,4,7,8]: # return False # return True # Wrong answer class Solution(object): def isNumber(self, s): """ :type s: str :rtype: bool """ #define a DFA state = [{}, {'blank': 1, 'sign': 2, 'digit':3, '.':4}, {'digit':3, '.':4}, {'digit':3, '.':5, 'e':6, 'blank':9}, {'digit':5}, {'digit':5, 'e':6, 'blank':9}, {'sign':7, 'digit':8}, {'digit':8}, {'digit':8, 'blank':9}, {'blank':9}] currentState = 1 for c in s: if c >= '0' and c <= '9': c = 'digit' if c == ' ': c = 'blank' if c in ['+', '-']: c = 'sign' if c not in state[currentState].keys(): return False currentState = state[currentState][c] if currentState not in [3,5,8,9]: return False return True if __name__ == '__main__': s = Solution() tests = [ ('', False), ('3', True), ('-3', True), ('3.0', True), ('3.', True), ('3e1', True), ('3.0e1', True), ('3e+1', True), ('3e', False), ('+3.0e-1', True), ] for pair in tests: print(s.isNumber(pair[0]), pair[1])
class Solution(object): def is_number(self, s): """ :type s: str :rtype: bool """ state = [{}, {'blank': 1, 'sign': 2, 'digit': 3, '.': 4}, {'digit': 3, '.': 4}, {'digit': 3, '.': 5, 'e': 6, 'blank': 9}, {'digit': 5}, {'digit': 5, 'e': 6, 'blank': 9}, {'sign': 7, 'digit': 8}, {'digit': 8}, {'digit': 8, 'blank': 9}, {'blank': 9}] current_state = 1 for c in s: if c >= '0' and c <= '9': c = 'digit' if c == ' ': c = 'blank' if c in ['+', '-']: c = 'sign' if c not in state[currentState].keys(): return False current_state = state[currentState][c] if currentState not in [3, 5, 8, 9]: return False return True if __name__ == '__main__': s = solution() tests = [('', False), ('3', True), ('-3', True), ('3.0', True), ('3.', True), ('3e1', True), ('3.0e1', True), ('3e+1', True), ('3e', False), ('+3.0e-1', True)] for pair in tests: print(s.isNumber(pair[0]), pair[1])
class Tabs: MEMBERS = "Members" SITES = "Sites" ROLES = "Roles" DETAILS = "Details" class Details: NAME = "Name" EORI_NUMBER = "EORI number" SIC_NUMBER = "SIC code" VAT_NUMBER = "VAT number" REGISTRATION_NUMBER = "Registration number" CREATED_AT = "Created at" PRIMARY_SITE = "Primary site" TYPE = "Type"
class Tabs: members = 'Members' sites = 'Sites' roles = 'Roles' details = 'Details' class Details: name = 'Name' eori_number = 'EORI number' sic_number = 'SIC code' vat_number = 'VAT number' registration_number = 'Registration number' created_at = 'Created at' primary_site = 'Primary site' type = 'Type'
def scope_test(): def do_local(): spam = 'local spam' def do_nonLocal(): nonlocal spam spam = 'non local spam' def do_global(): global spam spam = 'global spam' spam = 'test spam' do_local() print('after local assignment: ', spam) do_nonLocal() print('after non-local assignment: ', spam) do_global() print('after global assignment: ', spam) scope_test() print('in global scope: ', spam)
def scope_test(): def do_local(): spam = 'local spam' def do_non_local(): nonlocal spam spam = 'non local spam' def do_global(): global spam spam = 'global spam' spam = 'test spam' do_local() print('after local assignment: ', spam) do_non_local() print('after non-local assignment: ', spam) do_global() print('after global assignment: ', spam) scope_test() print('in global scope: ', spam)
#!/usr/bin/env python # -*- coding: utf-8 -*- class InvalidTokenTypeError(Exception): pass class InvalidNodeTypeError(Exception): pass class InvalidTargetNodeTypeError(Exception): pass
class Invalidtokentypeerror(Exception): pass class Invalidnodetypeerror(Exception): pass class Invalidtargetnodetypeerror(Exception): pass