content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def aumentar(n, taxa=0):
res = n + (n * taxa / 100)
return res # moeda(res)
# return res
def diminuir(n=0, taxa=0):
res = n - (n * taxa / 100)
return res # moeda(res)
def dobro(n=0):
res = n * 2
return res # moeda(res)
def metade(n):
res = n / 2
return res # moeda(res)
def moeda(n, m='R$'):
res = f'{m} {n:.2f}'.replace(".", ",")
return res
| def aumentar(n, taxa=0):
res = n + n * taxa / 100
return res
def diminuir(n=0, taxa=0):
res = n - n * taxa / 100
return res
def dobro(n=0):
res = n * 2
return res
def metade(n):
res = n / 2
return res
def moeda(n, m='R$'):
res = f'{m} {n:.2f}'.replace('.', ',')
return res |
class Solution(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
left, right = 0, len(A) - 1
result = []
while left <= right:
leftSqr = A[left] * A[left]
rightSqr = A[right] * A[right]
if leftSqr >= rightSqr:
result.insert(0, leftSqr)
left += 1
else:
result.insert(0, rightSqr)
right -= 1
return result | class Solution(object):
def sorted_squares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
(left, right) = (0, len(A) - 1)
result = []
while left <= right:
left_sqr = A[left] * A[left]
right_sqr = A[right] * A[right]
if leftSqr >= rightSqr:
result.insert(0, leftSqr)
left += 1
else:
result.insert(0, rightSqr)
right -= 1
return result |
class MyMath:
def __init__(self):
self.answer = 0
def Add(self, first_number, second_number):
self.answer = first_number + second_number
def Subtract(self, first_number, second_number):
self.answer = first_number - second_number
def __str__(self):
return str(self.answer)
class Person:
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
person1 = Person("John", 23)
person2 = Person("Anne", 102)
person1.showAge()
person2.showName()
math = MyMath()
math.Add(10,20)
print(math)
math.Subtract(10, 20)
print(math) | class Mymath:
def __init__(self):
self.answer = 0
def add(self, first_number, second_number):
self.answer = first_number + second_number
def subtract(self, first_number, second_number):
self.answer = first_number - second_number
def __str__(self):
return str(self.answer)
class Person:
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
def show_name(self):
print(self.name)
def show_age(self):
print(self.age)
person1 = person('John', 23)
person2 = person('Anne', 102)
person1.showAge()
person2.showName()
math = my_math()
math.Add(10, 20)
print(math)
math.Subtract(10, 20)
print(math) |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
noteList = [{'freq': 8.1757989200000001, 'name': 'C', 'octave': 0},
{'freq': 8.6619572199999997, 'name': 'C#', 'octave': 0},
{'freq': 9.1770239999999994, 'name': 'D', 'octave': 0},
{'freq': 9.7227182400000007, 'name': 'D#', 'octave': 0},
{'freq': 10.300861149999999, 'name': 'E', 'octave': 0},
{'freq': 10.91338223, 'name': 'F', 'octave': 0},
{'freq': 11.56232571, 'name': 'F#', 'octave': 0},
{'freq': 12.249857370000001, 'name': 'G', 'octave': 0},
{'freq': 12.9782718, 'name': 'G#', 'octave': 0},
{'freq': 13.75, 'name': 'A', 'octave': 0},
{'freq': 14.56761755, 'name': 'A#', 'octave': 0},
{'freq': 15.43385316, 'name': 'B', 'octave': 0},
{'freq': 16.351597829999999, 'name': 'C', 'octave': 1},
{'freq': 17.323914439999999, 'name': 'C#', 'octave': 1},
{'freq': 18.354047990000002, 'name': 'D', 'octave': 1},
{'freq': 19.445436480000001, 'name': 'D#', 'octave': 1},
{'freq': 20.60172231, 'name': 'E', 'octave': 1},
{'freq': 21.82676446, 'name': 'F', 'octave': 1},
{'freq': 23.124651419999999, 'name': 'F#', 'octave': 1},
{'freq': 24.499714749999999, 'name': 'G', 'octave': 1},
{'freq': 25.9565436, 'name': 'G#', 'octave': 1},
{'freq': 27.5, 'name': 'A', 'octave': 1},
{'freq': 29.135235089999998, 'name': 'A#', 'octave': 1},
{'freq': 30.867706330000001, 'name': 'B', 'octave': 1},
{'freq': 32.703195659999999, 'name': 'C', 'octave': 2},
{'freq': 34.647828869999998, 'name': 'C#', 'octave': 2},
{'freq': 36.708095989999997, 'name': 'D', 'octave': 2},
{'freq': 38.890872969999997, 'name': 'D#', 'octave': 2},
{'freq': 41.203444609999998, 'name': 'E', 'octave': 2},
{'freq': 43.65352893, 'name': 'F', 'octave': 2},
{'freq': 46.249302839999999, 'name': 'F#', 'octave': 2},
{'freq': 48.999429499999998, 'name': 'G', 'octave': 2},
{'freq': 51.9130872, 'name': 'G#', 'octave': 2},
{'freq': 55.0, 'name': 'A', 'octave': 2},
{'freq': 58.270470189999998, 'name': 'A#', 'octave': 2},
{'freq': 61.735412660000001, 'name': 'B', 'octave': 2},
{'freq': 65.406391330000005, 'name': 'C', 'octave': 3},
{'freq': 69.295657739999996, 'name': 'C#', 'octave': 3},
{'freq': 73.416191979999994, 'name': 'D', 'octave': 3},
{'freq': 77.78174593, 'name': 'D#', 'octave': 3},
{'freq': 82.406889230000004, 'name': 'E', 'octave': 3},
{'freq': 87.30705786, 'name': 'F', 'octave': 3},
{'freq': 92.498605679999997, 'name': 'F#', 'octave': 3},
{'freq': 97.998858999999996, 'name': 'G', 'octave': 3},
{'freq': 103.8261744, 'name': 'G#', 'octave': 3},
{'freq': 110.0, 'name': 'A', 'octave': 3},
{'freq': 116.5409404, 'name': 'A#', 'octave': 3},
{'freq': 123.4708253, 'name': 'B', 'octave': 3},
{'freq': 130.81278270000001, 'name': 'C', 'octave': 4},
{'freq': 138.59131550000001, 'name': 'C#', 'octave': 4},
{'freq': 146.83238399999999, 'name': 'D', 'octave': 4},
{'freq': 155.5634919, 'name': 'D#', 'octave': 4},
{'freq': 164.81377850000001, 'name': 'E', 'octave': 4},
{'freq': 174.61411570000001, 'name': 'F', 'octave': 4},
{'freq': 184.9972114, 'name': 'F#', 'octave': 4},
{'freq': 195.99771799999999, 'name': 'G', 'octave': 4},
{'freq': 207.6523488, 'name': 'G#', 'octave': 4},
{'freq': 220.0, 'name': 'A', 'octave': 4},
{'freq': 233.08188079999999, 'name': 'A#', 'octave': 4},
{'freq': 246.9416506, 'name': 'B', 'octave': 4},
{'freq': 261.62556530000001, 'name': 'C', 'octave': 5},
{'freq': 277.18263100000001, 'name': 'C#', 'octave': 5},
{'freq': 293.66476790000002, 'name': 'D', 'octave': 5},
{'freq': 311.12698369999998, 'name': 'D#', 'octave': 5},
{'freq': 329.6275569, 'name': 'E', 'octave': 5},
{'freq': 349.22823140000003, 'name': 'F', 'octave': 5},
{'freq': 369.99442269999997, 'name': 'F#', 'octave': 5},
{'freq': 391.99543599999998, 'name': 'G', 'octave': 5},
{'freq': 415.3046976, 'name': 'G#', 'octave': 5},
{'freq': 440.0, 'name': 'A', 'octave': 5},
{'freq': 466.16376150000002, 'name': 'A#', 'octave': 5},
{'freq': 493.88330130000003, 'name': 'B', 'octave': 5},
{'freq': 523.25113060000001, 'name': 'C', 'octave': 6},
{'freq': 554.36526200000003, 'name': 'C#', 'octave': 6},
{'freq': 587.32953580000003, 'name': 'D', 'octave': 6},
{'freq': 622.25396739999996, 'name': 'D#', 'octave': 6},
{'freq': 659.2551138, 'name': 'E', 'octave': 6},
{'freq': 698.45646290000002, 'name': 'F', 'octave': 6},
{'freq': 739.98884539999995, 'name': 'F#', 'octave': 6},
{'freq': 783.99087199999997, 'name': 'G', 'octave': 6},
{'freq': 830.60939519999999, 'name': 'G#', 'octave': 6},
{'freq': 880.0, 'name': 'A', 'octave': 6},
{'freq': 932.32752300000004, 'name': 'A#', 'octave': 6},
{'freq': 987.76660249999998, 'name': 'B', 'octave': 6},
{'freq': 1046.5022610000001, 'name': 'C', 'octave': 7},
{'freq': 1108.7305240000001, 'name': 'C#', 'octave': 7},
{'freq': 1174.6590719999999, 'name': 'D', 'octave': 7},
{'freq': 1244.5079350000001, 'name': 'D#', 'octave': 7},
{'freq': 1318.5102280000001, 'name': 'E', 'octave': 7},
{'freq': 1396.912926, 'name': 'F', 'octave': 7},
{'freq': 1479.977691, 'name': 'F#', 'octave': 7},
{'freq': 1567.9817439999999, 'name': 'G', 'octave': 7},
{'freq': 1661.2187899999999, 'name': 'G#', 'octave': 7},
{'freq': 1760.0, 'name': 'A', 'octave': 7},
{'freq': 1864.6550460000001, 'name': 'A#', 'octave': 7},
{'freq': 1975.533205, 'name': 'B', 'octave': 7},
{'freq': 2093.0045220000002, 'name': 'C', 'octave': 8},
{'freq': 2217.4610480000001, 'name': 'C#', 'octave': 8},
{'freq': 2349.318143, 'name': 'D', 'octave': 8},
{'freq': 2489.0158700000002, 'name': 'D#', 'octave': 8},
{'freq': 2637.0204549999999, 'name': 'E', 'octave': 8},
{'freq': 2793.8258510000001, 'name': 'F', 'octave': 8},
{'freq': 2959.9553820000001, 'name': 'F#', 'octave': 8},
{'freq': 3135.9634879999999, 'name': 'G', 'octave': 8},
{'freq': 3322.4375810000001, 'name': 'G#', 'octave': 8},
{'freq': 3520.0, 'name': 'A', 'octave': 8},
{'freq': 3729.3100920000002, 'name': 'A#', 'octave': 8},
{'freq': 3951.0664099999999, 'name': 'B', 'octave': 8},
{'freq': 4186.0090449999998, 'name': 'C', 'octave': 9},
{'freq': 4434.9220960000002, 'name': 'C#', 'octave': 9},
{'freq': 4698.6362870000003, 'name': 'D', 'octave': 9},
{'freq': 4978.0317400000004, 'name': 'D#', 'octave': 9},
{'freq': 5274.0409110000001, 'name': 'E', 'octave': 9},
{'freq': 5587.6517030000005, 'name': 'F', 'octave': 9},
{'freq': 5919.9107629999999, 'name': 'F#', 'octave': 9},
{'freq': 6271.9269759999997, 'name': 'G', 'octave': 9},
{'freq': 6644.8751609999999, 'name': 'G#', 'octave': 9},
{'freq': 7040.0, 'name': 'A', 'octave': 9},
{'freq': 7458.6201840000003, 'name': 'A#', 'octave': 9},
{'freq': 7902.1328199999998, 'name': 'B', 'octave': 9},
{'freq': 8372.0180899999996, 'name': 'C', 'octave': 10},
{'freq': 8869.8441910000001, 'name': 'C#', 'octave': 10},
{'freq': 9397.2725730000002, 'name': 'D', 'octave': 10},
{'freq': 9956.0634790000004, 'name': 'D#', 'octave': 10},
{'freq': 10548.081819999999, 'name': 'E', 'octave': 10},
{'freq': 11175.30341, 'name': 'F', 'octave': 10},
{'freq': 11839.821529999999, 'name': 'F#', 'octave': 10},
{'freq': 12543.853950000001, 'name': 'G', 'octave': 10}]
| note_list = [{'freq': 8.17579892, 'name': 'C', 'octave': 0}, {'freq': 8.66195722, 'name': 'C#', 'octave': 0}, {'freq': 9.177024, 'name': 'D', 'octave': 0}, {'freq': 9.72271824, 'name': 'D#', 'octave': 0}, {'freq': 10.30086115, 'name': 'E', 'octave': 0}, {'freq': 10.91338223, 'name': 'F', 'octave': 0}, {'freq': 11.56232571, 'name': 'F#', 'octave': 0}, {'freq': 12.24985737, 'name': 'G', 'octave': 0}, {'freq': 12.9782718, 'name': 'G#', 'octave': 0}, {'freq': 13.75, 'name': 'A', 'octave': 0}, {'freq': 14.56761755, 'name': 'A#', 'octave': 0}, {'freq': 15.43385316, 'name': 'B', 'octave': 0}, {'freq': 16.35159783, 'name': 'C', 'octave': 1}, {'freq': 17.32391444, 'name': 'C#', 'octave': 1}, {'freq': 18.35404799, 'name': 'D', 'octave': 1}, {'freq': 19.44543648, 'name': 'D#', 'octave': 1}, {'freq': 20.60172231, 'name': 'E', 'octave': 1}, {'freq': 21.82676446, 'name': 'F', 'octave': 1}, {'freq': 23.12465142, 'name': 'F#', 'octave': 1}, {'freq': 24.49971475, 'name': 'G', 'octave': 1}, {'freq': 25.9565436, 'name': 'G#', 'octave': 1}, {'freq': 27.5, 'name': 'A', 'octave': 1}, {'freq': 29.13523509, 'name': 'A#', 'octave': 1}, {'freq': 30.86770633, 'name': 'B', 'octave': 1}, {'freq': 32.70319566, 'name': 'C', 'octave': 2}, {'freq': 34.64782887, 'name': 'C#', 'octave': 2}, {'freq': 36.70809599, 'name': 'D', 'octave': 2}, {'freq': 38.89087297, 'name': 'D#', 'octave': 2}, {'freq': 41.20344461, 'name': 'E', 'octave': 2}, {'freq': 43.65352893, 'name': 'F', 'octave': 2}, {'freq': 46.24930284, 'name': 'F#', 'octave': 2}, {'freq': 48.9994295, 'name': 'G', 'octave': 2}, {'freq': 51.9130872, 'name': 'G#', 'octave': 2}, {'freq': 55.0, 'name': 'A', 'octave': 2}, {'freq': 58.27047019, 'name': 'A#', 'octave': 2}, {'freq': 61.73541266, 'name': 'B', 'octave': 2}, {'freq': 65.40639133, 'name': 'C', 'octave': 3}, {'freq': 69.29565774, 'name': 'C#', 'octave': 3}, {'freq': 73.41619198, 'name': 'D', 'octave': 3}, {'freq': 77.78174593, 'name': 'D#', 'octave': 3}, {'freq': 82.40688923, 'name': 'E', 'octave': 3}, {'freq': 87.30705786, 'name': 'F', 'octave': 3}, {'freq': 92.49860568, 'name': 'F#', 'octave': 3}, {'freq': 97.998859, 'name': 'G', 'octave': 3}, {'freq': 103.8261744, 'name': 'G#', 'octave': 3}, {'freq': 110.0, 'name': 'A', 'octave': 3}, {'freq': 116.5409404, 'name': 'A#', 'octave': 3}, {'freq': 123.4708253, 'name': 'B', 'octave': 3}, {'freq': 130.8127827, 'name': 'C', 'octave': 4}, {'freq': 138.5913155, 'name': 'C#', 'octave': 4}, {'freq': 146.832384, 'name': 'D', 'octave': 4}, {'freq': 155.5634919, 'name': 'D#', 'octave': 4}, {'freq': 164.8137785, 'name': 'E', 'octave': 4}, {'freq': 174.6141157, 'name': 'F', 'octave': 4}, {'freq': 184.9972114, 'name': 'F#', 'octave': 4}, {'freq': 195.997718, 'name': 'G', 'octave': 4}, {'freq': 207.6523488, 'name': 'G#', 'octave': 4}, {'freq': 220.0, 'name': 'A', 'octave': 4}, {'freq': 233.0818808, 'name': 'A#', 'octave': 4}, {'freq': 246.9416506, 'name': 'B', 'octave': 4}, {'freq': 261.6255653, 'name': 'C', 'octave': 5}, {'freq': 277.182631, 'name': 'C#', 'octave': 5}, {'freq': 293.6647679, 'name': 'D', 'octave': 5}, {'freq': 311.1269837, 'name': 'D#', 'octave': 5}, {'freq': 329.6275569, 'name': 'E', 'octave': 5}, {'freq': 349.2282314, 'name': 'F', 'octave': 5}, {'freq': 369.9944227, 'name': 'F#', 'octave': 5}, {'freq': 391.995436, 'name': 'G', 'octave': 5}, {'freq': 415.3046976, 'name': 'G#', 'octave': 5}, {'freq': 440.0, 'name': 'A', 'octave': 5}, {'freq': 466.1637615, 'name': 'A#', 'octave': 5}, {'freq': 493.8833013, 'name': 'B', 'octave': 5}, {'freq': 523.2511306, 'name': 'C', 'octave': 6}, {'freq': 554.365262, 'name': 'C#', 'octave': 6}, {'freq': 587.3295358, 'name': 'D', 'octave': 6}, {'freq': 622.2539674, 'name': 'D#', 'octave': 6}, {'freq': 659.2551138, 'name': 'E', 'octave': 6}, {'freq': 698.4564629, 'name': 'F', 'octave': 6}, {'freq': 739.9888454, 'name': 'F#', 'octave': 6}, {'freq': 783.990872, 'name': 'G', 'octave': 6}, {'freq': 830.6093952, 'name': 'G#', 'octave': 6}, {'freq': 880.0, 'name': 'A', 'octave': 6}, {'freq': 932.327523, 'name': 'A#', 'octave': 6}, {'freq': 987.7666025, 'name': 'B', 'octave': 6}, {'freq': 1046.502261, 'name': 'C', 'octave': 7}, {'freq': 1108.730524, 'name': 'C#', 'octave': 7}, {'freq': 1174.659072, 'name': 'D', 'octave': 7}, {'freq': 1244.507935, 'name': 'D#', 'octave': 7}, {'freq': 1318.510228, 'name': 'E', 'octave': 7}, {'freq': 1396.912926, 'name': 'F', 'octave': 7}, {'freq': 1479.977691, 'name': 'F#', 'octave': 7}, {'freq': 1567.981744, 'name': 'G', 'octave': 7}, {'freq': 1661.21879, 'name': 'G#', 'octave': 7}, {'freq': 1760.0, 'name': 'A', 'octave': 7}, {'freq': 1864.655046, 'name': 'A#', 'octave': 7}, {'freq': 1975.533205, 'name': 'B', 'octave': 7}, {'freq': 2093.004522, 'name': 'C', 'octave': 8}, {'freq': 2217.461048, 'name': 'C#', 'octave': 8}, {'freq': 2349.318143, 'name': 'D', 'octave': 8}, {'freq': 2489.01587, 'name': 'D#', 'octave': 8}, {'freq': 2637.020455, 'name': 'E', 'octave': 8}, {'freq': 2793.825851, 'name': 'F', 'octave': 8}, {'freq': 2959.955382, 'name': 'F#', 'octave': 8}, {'freq': 3135.963488, 'name': 'G', 'octave': 8}, {'freq': 3322.437581, 'name': 'G#', 'octave': 8}, {'freq': 3520.0, 'name': 'A', 'octave': 8}, {'freq': 3729.310092, 'name': 'A#', 'octave': 8}, {'freq': 3951.06641, 'name': 'B', 'octave': 8}, {'freq': 4186.009045, 'name': 'C', 'octave': 9}, {'freq': 4434.922096, 'name': 'C#', 'octave': 9}, {'freq': 4698.636287, 'name': 'D', 'octave': 9}, {'freq': 4978.03174, 'name': 'D#', 'octave': 9}, {'freq': 5274.040911, 'name': 'E', 'octave': 9}, {'freq': 5587.651703, 'name': 'F', 'octave': 9}, {'freq': 5919.910763, 'name': 'F#', 'octave': 9}, {'freq': 6271.926976, 'name': 'G', 'octave': 9}, {'freq': 6644.875161, 'name': 'G#', 'octave': 9}, {'freq': 7040.0, 'name': 'A', 'octave': 9}, {'freq': 7458.620184, 'name': 'A#', 'octave': 9}, {'freq': 7902.13282, 'name': 'B', 'octave': 9}, {'freq': 8372.01809, 'name': 'C', 'octave': 10}, {'freq': 8869.844191, 'name': 'C#', 'octave': 10}, {'freq': 9397.272573, 'name': 'D', 'octave': 10}, {'freq': 9956.063479, 'name': 'D#', 'octave': 10}, {'freq': 10548.08182, 'name': 'E', 'octave': 10}, {'freq': 11175.30341, 'name': 'F', 'octave': 10}, {'freq': 11839.82153, 'name': 'F#', 'octave': 10}, {'freq': 12543.85395, 'name': 'G', 'octave': 10}] |
"""Python replacement for overlapSelect.
For a chain and a set of genes returns:
gene: how many bases this chain overlap in exons.
"""
__author__ = "Bogdan Kirilenko, 2020."
__version__ = "1.0"
__email__ = "kirilenk@mpi-cbg.de"
__credits__ = ["Michael Hiller", "Virag Sharma", "David Jebb"]
def make_bed_ranges(bed_line):
"""Convert a bed line to a set of ranges."""
line_info = bed_line.split("\t")
glob_start = int(line_info[1])
# glob_end = int(line_info[2])
gene_name = line_info[3]
block_starts = [glob_start + int(x) for x in line_info[11].split(",") if x != ""]
block_sizes = [int(x) for x in line_info[10].split(",") if x != ""]
blocks_num = int(line_info[9])
block_ends = [block_starts[i] + block_sizes[i] for i in range(blocks_num)]
genes = [gene_name for _ in range(blocks_num)]
return list(zip(block_starts, block_ends, genes))
def parse_bed(bed_lines):
"""Return sorted genic regions."""
ranges = []
for bed_line in bed_lines.split("\n")[:-1]:
gene_ranges = make_bed_ranges(bed_line)
ranges.extend(gene_ranges)
return list(sorted(ranges, key=lambda x: x[0]))
def chain_reader(chain):
"""Return chain blocks one by one."""
chain_data = chain.split("\n")
chain_head = chain_data[0]
del chain_data[0]
# define starting point
progress = int(chain_head.split()[5])
blocks_num = len(chain_data)
for i in range(blocks_num):
block_info = chain_data[i].split()
if len(block_info) == 1:
block_size = int(block_info[0])
block_start = progress
block_end = block_start + block_size
yield block_start, block_end
break # end the loop
block_size = int(block_info[0])
dt = int(block_info[1])
block_start = progress
block_end = block_start + block_size
progress = block_end + dt
yield block_start, block_end
def intersect(ch_block, be_block):
"""Return intersection size."""
return min(ch_block[1], be_block[1]) - max(ch_block[0], be_block[0])
def overlap_select(bed, chain):
"""Entry point."""
ranges = parse_bed(bed)
genes = [x[2] for x in ranges]
# accumulate intersections
bed_overlaps = {gene: 0 for gene in genes}
chain_len = 0 # sum of chain blocks
start_with = 0
# init blocks generator
for block in chain_reader(chain):
# add to len
chain_len += block[1] - block[0]
FLAG = False # was intersection or not?
FIRST = True
while True:
if FIRST: # start with previous start, first iteration
bed_num = start_with
FIRST = False # guarantee that this condition works ONCE per loop
else: # just increase the pointer
bed_num += 1 # to avoid inf loop
if bed_num >= len(ranges):
break # beds are over
exon = ranges[bed_num]
if block[1] < exon[0]: # too late
break # means that bed is "righter" than chain
block_vs_exon = intersect(block, (exon[0], exon[1]))
if block_vs_exon > 0:
if not FLAG: # the FIRST intersection of this chain
start_with = bed_num # guarantee that I will assign to starts with
# only the FIRST intersection (if it took place)
FLAG = True # otherwise starts with will be preserved
# save the intersection
bed_overlaps[exon[2]] += block_vs_exon
else: # we recorded all the region with intersections
if block[0] > exon[1]: # too early
# in case like:
# gene A EEEEE----------------------------------------EEEEEE #
# gene B EEEEEEEEEE #
# gene C EEEEEEEEE #
# chain ccccc #
# at gene A I will get FLAG = True and NO intersection with gene B
# --> I will miss gene C in this case without this condition.
continue
elif FLAG: # this is not a nested gene
break # and all intersections are saved --> proceed to the next chain
# return the required values
return chain_len, bed_overlaps
| """Python replacement for overlapSelect.
For a chain and a set of genes returns:
gene: how many bases this chain overlap in exons.
"""
__author__ = 'Bogdan Kirilenko, 2020.'
__version__ = '1.0'
__email__ = 'kirilenk@mpi-cbg.de'
__credits__ = ['Michael Hiller', 'Virag Sharma', 'David Jebb']
def make_bed_ranges(bed_line):
"""Convert a bed line to a set of ranges."""
line_info = bed_line.split('\t')
glob_start = int(line_info[1])
gene_name = line_info[3]
block_starts = [glob_start + int(x) for x in line_info[11].split(',') if x != '']
block_sizes = [int(x) for x in line_info[10].split(',') if x != '']
blocks_num = int(line_info[9])
block_ends = [block_starts[i] + block_sizes[i] for i in range(blocks_num)]
genes = [gene_name for _ in range(blocks_num)]
return list(zip(block_starts, block_ends, genes))
def parse_bed(bed_lines):
"""Return sorted genic regions."""
ranges = []
for bed_line in bed_lines.split('\n')[:-1]:
gene_ranges = make_bed_ranges(bed_line)
ranges.extend(gene_ranges)
return list(sorted(ranges, key=lambda x: x[0]))
def chain_reader(chain):
"""Return chain blocks one by one."""
chain_data = chain.split('\n')
chain_head = chain_data[0]
del chain_data[0]
progress = int(chain_head.split()[5])
blocks_num = len(chain_data)
for i in range(blocks_num):
block_info = chain_data[i].split()
if len(block_info) == 1:
block_size = int(block_info[0])
block_start = progress
block_end = block_start + block_size
yield (block_start, block_end)
break
block_size = int(block_info[0])
dt = int(block_info[1])
block_start = progress
block_end = block_start + block_size
progress = block_end + dt
yield (block_start, block_end)
def intersect(ch_block, be_block):
"""Return intersection size."""
return min(ch_block[1], be_block[1]) - max(ch_block[0], be_block[0])
def overlap_select(bed, chain):
"""Entry point."""
ranges = parse_bed(bed)
genes = [x[2] for x in ranges]
bed_overlaps = {gene: 0 for gene in genes}
chain_len = 0
start_with = 0
for block in chain_reader(chain):
chain_len += block[1] - block[0]
flag = False
first = True
while True:
if FIRST:
bed_num = start_with
first = False
else:
bed_num += 1
if bed_num >= len(ranges):
break
exon = ranges[bed_num]
if block[1] < exon[0]:
break
block_vs_exon = intersect(block, (exon[0], exon[1]))
if block_vs_exon > 0:
if not FLAG:
start_with = bed_num
flag = True
bed_overlaps[exon[2]] += block_vs_exon
elif block[0] > exon[1]:
continue
elif FLAG:
break
return (chain_len, bed_overlaps) |
COLUMN_VARIABLES = ['M_t', 'H_t', 'W_t']
RAW_DATA_DIRECTORY = './sample_data'
TRAIN_TEST_SPLIT_VALS = {'test_1':'2017-08-06', 'test_2':'2017-01-15',
'test_3':'2017-05-14', 'test_4':'2016-10-16'}
| column_variables = ['M_t', 'H_t', 'W_t']
raw_data_directory = './sample_data'
train_test_split_vals = {'test_1': '2017-08-06', 'test_2': '2017-01-15', 'test_3': '2017-05-14', 'test_4': '2016-10-16'} |
# URI Online Judge 2762
entrada = input().split('.')
saida = str(int(entrada[1])) + '.' + entrada[0]
print(saida) | entrada = input().split('.')
saida = str(int(entrada[1])) + '.' + entrada[0]
print(saida) |
dinero=2000
preciodelhelado=100
incrementodelpreciodelhelado=1.20
edad=19
hambrequesatisfaceelhelado=edad
hambresatisfecho=edad
n=0
while (hambresatisfecho<85 and dinero>0):
dinero=dinero-(preciodelhelado)
hambresatisfecho=hambresatisfecho+hambrequesatisfaceelhelado
preciodelhelado=preciodelhelado*incrementodelpreciodelhelado
n=n+1
print("te tienes que comer", n, "helados para llenarte")
print("te queda", dinero, "euros") | dinero = 2000
preciodelhelado = 100
incrementodelpreciodelhelado = 1.2
edad = 19
hambrequesatisfaceelhelado = edad
hambresatisfecho = edad
n = 0
while hambresatisfecho < 85 and dinero > 0:
dinero = dinero - preciodelhelado
hambresatisfecho = hambresatisfecho + hambrequesatisfaceelhelado
preciodelhelado = preciodelhelado * incrementodelpreciodelhelado
n = n + 1
print('te tienes que comer', n, 'helados para llenarte')
print('te queda', dinero, 'euros') |
class DisabledFormMixin():
def __init__(self):
for (_, field) in self.fields.items():
field.widget.attrs['disabled'] = True
field.widget.attrs['readonly'] = True
| class Disabledformmixin:
def __init__(self):
for (_, field) in self.fields.items():
field.widget.attrs['disabled'] = True
field.widget.attrs['readonly'] = True |
{
"targets": [
{
"target_name": "greet",
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"sources": [
"./src/cpp/greeting.cpp",
"./src/cpp/count.cpp",
"./src/cpp/custom_object.cpp",
"./src/cpp/index.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"],
}
]
}
| {'targets': [{'target_name': 'greet', 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'sources': ['./src/cpp/greeting.cpp', './src/cpp/count.cpp', './src/cpp/custom_object.cpp', './src/cpp/index.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS']}]} |
def get_register_info(registers, register_name):
return registers[register_name].bit_offset
def get_register_location_in_frame_data(registers, register_name, start_word_index=0):
bit_offset = get_register_info(registers, register_name)
word_index = (bit_offset >> 5) - start_word_index
bit_index = bit_offset % 32
return word_index, bit_index
def get_register_value_from_frame_data(registers, register_name, register_width, frame_data, start_word_index=0, fast=False):
value = 0
for i in range(register_width):
if register_width == 1:
name = register_name
else:
name = register_name + '[' + str(i) + ']'
word_index, bit_index = get_register_location_in_frame_data(registers, name, start_word_index)
if fast:
bit_value = ((int(frame_data[word_index], 2) >> bit_index) & 0x1) ^ 0x1
else:
bit_value = ((frame_data[word_index] >> bit_index) & 0x1) ^ 0x1
value = value | (bit_value << i)
return value | def get_register_info(registers, register_name):
return registers[register_name].bit_offset
def get_register_location_in_frame_data(registers, register_name, start_word_index=0):
bit_offset = get_register_info(registers, register_name)
word_index = (bit_offset >> 5) - start_word_index
bit_index = bit_offset % 32
return (word_index, bit_index)
def get_register_value_from_frame_data(registers, register_name, register_width, frame_data, start_word_index=0, fast=False):
value = 0
for i in range(register_width):
if register_width == 1:
name = register_name
else:
name = register_name + '[' + str(i) + ']'
(word_index, bit_index) = get_register_location_in_frame_data(registers, name, start_word_index)
if fast:
bit_value = int(frame_data[word_index], 2) >> bit_index & 1 ^ 1
else:
bit_value = frame_data[word_index] >> bit_index & 1 ^ 1
value = value | bit_value << i
return value |
files = [
"midi.vhdl", "midi.ucf", "clock_divider.vhdl", "shift_out.vhdl",
]
| files = ['midi.vhdl', 'midi.ucf', 'clock_divider.vhdl', 'shift_out.vhdl'] |
#
# PySNMP MIB module ENDRUNTECHNOLOGIES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENDRUNTECHNOLOGIES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:02:48 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, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Bits, ObjectIdentity, TimeTicks, IpAddress, ModuleIdentity, iso, Counter32, Unsigned32, MibIdentifier, Counter64, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, enterprises, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "ObjectIdentity", "TimeTicks", "IpAddress", "ModuleIdentity", "iso", "Counter32", "Unsigned32", "MibIdentifier", "Counter64", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "enterprises", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
endRunTechnologiesMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 13827))
endRunTechnologies = ModuleIdentity((1, 3, 6, 1, 4, 1, 13827, 0))
if mibBuilder.loadTexts: endRunTechnologies.setLastUpdated('0208190000Z')
if mibBuilder.loadTexts: endRunTechnologies.setOrganization('EndRun Technologies LLC')
if mibBuilder.loadTexts: endRunTechnologies.setContactInfo('Technical Support 1-877-749-3878 snmpsupport@endruntechnologies.com')
if mibBuilder.loadTexts: endRunTechnologies.setDescription('EndRun Technologies Enterprise MIB')
praecisCntp = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1))
cntp = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1, 0))
cntptrap = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0))
cdma = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1, 1))
cdmatrap = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1, 1, 0))
cntpTrapLeapIndBitsChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0, 1)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "cntpLeapIndBits"))
if mibBuilder.loadTexts: cntpTrapLeapIndBitsChange.setStatus('current')
if mibBuilder.loadTexts: cntpTrapLeapIndBitsChange.setDescription('A cntpTrapNTPLeapIndBitsChange trap signifies that the value of the leap indicator bits contained in the NTP reply packets sent by the time server has changed. The current value of these bits is contained in the included cntpLeapIndBits. The decimal value of these bits ranges from 0 to 3: 0 is the no fault, no leap warning condition 1 is the no fault, leap second insertion warning condition 2 is the no fault, leap second deletion warning condition 3 is the unsynchronized, alarm condition')
cntpTrapStratumChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0, 2)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "cntpStratum"))
if mibBuilder.loadTexts: cntpTrapStratumChange.setStatus('current')
if mibBuilder.loadTexts: cntpTrapStratumChange.setDescription('A cntpTrapStratumChange trap signifies that the value of the stratum field contained in the NTP reply packets sent by the time server has changed. The current value is contained in the included variable, cntpStratum. The decimal value of this field ranges from 1 to 16: 1 is the synchronized, actively locked to the reference UTC source stratum 11 is the synchronized, but flywheeling on the local real time clock stratum 16 is the unsynchronized stratum level')
cntpRxPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpRxPkts.setStatus('current')
if mibBuilder.loadTexts: cntpRxPkts.setDescription('Total number of NTP request packets received by the NTP daemon.')
cntpTxPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpTxPkts.setStatus('current')
if mibBuilder.loadTexts: cntpTxPkts.setDescription('Total number of NTP reply packets transmitted by the NTP daemon.')
cntpIgnoredPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpIgnoredPkts.setStatus('current')
if mibBuilder.loadTexts: cntpIgnoredPkts.setDescription('Total number of NTP request packets ignored by the NTP daemon.')
cntpDroppedPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpDroppedPkts.setStatus('current')
if mibBuilder.loadTexts: cntpDroppedPkts.setDescription('Total number of NTP request packets dropped by the NTP daemon.')
cntpAuthFail = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpAuthFail.setStatus('current')
if mibBuilder.loadTexts: cntpAuthFail.setDescription('Total number of authentication failures detected by the NTP daemon.')
cntpTimeFigureOfMerit = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(6, 7, 8, 9))).clone(namedValues=NamedValues(("lessthan100us", 6), ("lessthan1ms", 7), ("lessthan10ms", 8), ("greaterthan10ms", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts: cntpTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation with CDMA the TFOM is 6 and implies a worst case time error of 100 microseconds. During periods of signal loss, the CDMA sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
cntpLeapIndBits = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("noFaultorLeap", 0), ("leapInsWarning", 1), ("leapDelWarning", 2), ("unSynchronized", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpLeapIndBits.setStatus('current')
if mibBuilder.loadTexts: cntpLeapIndBits.setDescription('This is a status code indicating: normal operation, a leap second to be inserted in the last minute of the current day, a leap second to be deleted in the last second of the day or an alarm condition indicating loss of timing synchronization. The leap indicator field of NTP reply packets sent from this server is set to cntpLeapIndBits.')
cntpSyncSource = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpSyncSource.setStatus('current')
if mibBuilder.loadTexts: cntpSyncSource.setDescription('This is an ASCII string identifying the synchronization source for this NTP server. It is one of CDMA, CPU or NONE. If it is NONE, then the server is not synchronized, has its Leap Indicator Bits in the Alarm state and is running at Stratum 16. If it is CPU, then the server is free running on its NTP disciplined CPU clock at Stratum 11. Check the Stratum, Leap Indicator Bits and Time Figure of Merit for further information. NTP reply packets from this server will have the reference identifier field set to cntpSyncSource if it is CDMA. Otherwise it will be set to either 127.127.1.0 (CPU) or 0.0.0.0 (NONE).')
cntpOffsetToCDMAReference = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpOffsetToCDMAReference.setStatus('current')
if mibBuilder.loadTexts: cntpOffsetToCDMAReference.setDescription('This is an ASCII string containing the floating value of the current offset in units of seconds of the NTP server CPU clock to the CDMA reference time. Positive values imply that the NTP server clock is ahead of the CDMA reference time.')
cntpStratum = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 11, 16))).clone(namedValues=NamedValues(("cntpStratumOne", 1), ("cntpStratumFlywheeling", 11), ("cntpStratumUnsync", 16)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpStratum.setStatus('current')
if mibBuilder.loadTexts: cntpStratum.setDescription('This is an integer showing the current stratum level being reported by the NTP daemon in its reply packets to clients. If it is 1, then the server is fully synchronized and delivering Stratum 1 accuracy. If it is 16, then the server is unambiguously unsynchronized. If it is 11, and the previous stratum value was 1, then the server is flywheeling on the local CPU clock. However, if the previous stratum value was 16, then the server has synchronized to its CPU Real Time Clock. NTP clients on the network should be configured to not use the time from this server if the stratum is not 1.')
cntpVersion = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpVersion.setStatus('current')
if mibBuilder.loadTexts: cntpVersion.setDescription('This is an ASCII string showing the NTP server firmware version.')
cdmaTrapFaultStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 1, 1, 0, 1)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "cdmaFaultStatus"))
if mibBuilder.loadTexts: cdmaTrapFaultStatusChange.setStatus('current')
if mibBuilder.loadTexts: cdmaTrapFaultStatusChange.setDescription('A cdmaTrapFaultStatusChange trap signifies that the value of the fault status word reported by the CDMA sub-system has changed. The current value is contained in the included cdmaFaultStatus.')
cdmaFaultStatus = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 1), Bits().clone(namedValues=NamedValues(("cdmaNotUsed", 0), ("cdmaNTPNotPolling", 1), ("cdmaLOFailure", 2), ("cdmaLOPLLFlt", 3), ("cdmaFLASHWriteFlt", 4), ("cdmaFPGACfgFlt", 5), ("cdmaNoSignalTimeout", 6), ("cdmaDACNearLimit", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaFaultStatus.setStatus('current')
if mibBuilder.loadTexts: cdmaFaultStatus.setDescription("This is a bit string contained in one character representing the least significant two nibbles of the CDMA fault status word. Unfortunately, SNMP numbers the bits in the reverse order, so that the enumerated values are backwards from the description contained in the User's Manual for the fault status field returned by the cdmastat command. Each bit indicates a fault when set. Currently defined fault states encoded in this value: Bit 7: DAC controlling the TCXO is near the high or low limit. Bit 6: Time Figure of Merit has been 9 (unsynchronized) for 1 hour. Bit 5: Field Programmable Gate Array (FPGA) did not configure properly. Bit 4: FLASH memory had a write fault. Bit 3: Local Oscillator PLL fault. Bit 2: Local Oscillator PLL failed. Bit 1: NTP daemon is not polling the CDMA reference clock. Bit 0: Not Used.")
cdmaTimeFigureOfMerit = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(6, 7, 8, 9))).clone(namedValues=NamedValues(("lessthan100us", 6), ("lessthan1ms", 7), ("lessthan10ms", 8), ("greaterthan10ms", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts: cdmaTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 6 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation the TFOM is 6 and implies a worst case time error of 100 microseconds. During periods of signal loss, the CDMA sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
cdmaSigProcState = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 4, 8))).clone(namedValues=NamedValues(("cdmaAcquiring", 0), ("cdmaDetected", 1), ("cdmaCodeLocking", 2), ("cdmaCarrierLocking", 4), ("cdmaLocked", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaSigProcState.setStatus('current')
if mibBuilder.loadTexts: cdmaSigProcState.setDescription('Current CDMA signal processor state. One of 0, 1, 2, 4 or 8, with 0 indicating the acquisition state and 8 the fully locked on state.')
cdmaChannel = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("priAbandclass0subclass0", 0), ("priBbandclass0subclass0", 1), ("secAbandclass0subclass0", 2), ("secBbandclass0subclass0", 3), ("priAbandclass0subclass1", 4), ("priBbandclass0subclass1", 5), ("secAbandclass0subclass1", 6), ("secBbandclass0subclass1", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaChannel.setStatus('current')
if mibBuilder.loadTexts: cdmaChannel.setDescription('Current CDMA frequency band and channel being used. Channels 0-3 are the North American cellular channels. Channels 4-7 are the South Korean cellular channels.')
cdmaPNO = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 511))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaPNO.setStatus('current')
if mibBuilder.loadTexts: cdmaPNO.setDescription('Current Pseudo Noise Offset of the base station being tracked. The value ranges from 0 to 511 and is in units of 64 Pseudo Noise Code chips. This offset serves as a base station identifier that is analogous to the Pseudo Random Noise (PRN) codes used by the individual satellites in the GPS system.')
cdmaAGC = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaAGC.setStatus('current')
if mibBuilder.loadTexts: cdmaAGC.setDescription('Current 8 bit, Automatic Gain Control (AGC) DAC value. Typical values are around 200, but proximity to the base station, type of building construction and orientation within the building have a strong influence on this value. More positive values have the effect of increasing the RF gain.')
cdmaVCDAC = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaVCDAC.setStatus('current')
if mibBuilder.loadTexts: cdmaVCDAC.setDescription('Current 16 bit, Voltage Controlled TCXO DAC value. Typical range is 20000 to 40000, where more positive numbers have the effect of raising the TCXO frequency.')
cdmaCarrierToNoiseRatio = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaCarrierToNoiseRatio.setStatus('current')
if mibBuilder.loadTexts: cdmaCarrierToNoiseRatio.setDescription('ASCII string representing the current received CDMA signal carrier-to-noise ratio, a unitless quantity. Numbers less than 2.5 indicate a very weak signal condition.')
cdmaFrameErrorRate = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaFrameErrorRate.setStatus('current')
if mibBuilder.loadTexts: cdmaFrameErrorRate.setDescription('ASCII string representing the current sync channel message error rate, a number ranging from 0.000 to 1.000. It indicates the proportion of messages received that fail the Cyclical Redundancy Check.')
cdmaLeapMode = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaLeapMode.setStatus('current')
if mibBuilder.loadTexts: cdmaLeapMode.setDescription('ASCII string showing the current leap second mode of operation for the CDMA sub-system. It is either AUTO or USER. If the mode is USER, then the current and future values of the UTC to GPS leap second offset is also included.')
cdmaCurrentLeapSeconds = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaCurrentLeapSeconds.setStatus('current')
if mibBuilder.loadTexts: cdmaCurrentLeapSeconds.setDescription('This value is the current difference in seconds between GPS time and UTC time. GPS time is ahead of UTC time by this amount.')
cdmaFutureLeapSeconds = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 12), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaFutureLeapSeconds.setStatus('current')
if mibBuilder.loadTexts: cdmaFutureLeapSeconds.setDescription('This value is the future difference in seconds between GPS time and UTC time. Leap seconds may be inserted or deleted from the UTC timescale twice during the year: Dec 31 and June 30 at UTC midnight. If this value is the same as cdmaCurrentLeapSeconds, then no leap second insertion or deletion will occur at the next possible time. If it is different, then the change will take affect at the next possible time. GPS time will be ahead of UTC time by this amount.')
cdmaVersion = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 13), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaVersion.setStatus('current')
if mibBuilder.loadTexts: cdmaVersion.setDescription('ASCII string showing the CDMA sub-system firmware and FPGA versions.')
praecisGntp = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2))
gntp = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2, 0))
gntptrap = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0))
gps = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2, 1))
gpstrap = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2, 1, 0))
gntpTrapLeapIndBitsChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0, 1)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "gntpLeapIndBits"))
if mibBuilder.loadTexts: gntpTrapLeapIndBitsChange.setStatus('current')
if mibBuilder.loadTexts: gntpTrapLeapIndBitsChange.setDescription('A gntpTrapNTPLeapIndBitsChange trap signifies that the value of the leap indicator bits contained in the NTP reply packets sent by the time server has changed. The current value of these bits is contained in the included gntpLeapIndBits. The decimal value of these bits ranges from 0 to 3: 0 is the no fault, no leap warning condition 1 is the no fault, leap second insertion warning condition 2 is the no fault, leap second deletion warning condition 3 is the unsynchronized, alarm condition')
gntpTrapStratumChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0, 2)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "gntpStratum"))
if mibBuilder.loadTexts: gntpTrapStratumChange.setStatus('current')
if mibBuilder.loadTexts: gntpTrapStratumChange.setDescription('A gntpTrapStratumChange trap signifies that the value of the stratum field contained in the NTP reply packets sent by the time server has changed. The current value is contained in the included variable, gntpStratum. The decimal value of this field ranges from 1 to 16: 1 is the synchronized, actively locked to the reference UTC source stratum 11 is the synchronized, but flywheeling on the local real time clock stratum 16 is the unsynchronized stratum level')
gntpRxPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpRxPkts.setStatus('current')
if mibBuilder.loadTexts: gntpRxPkts.setDescription('Total number of NTP request packets received by the NTP daemon.')
gntpTxPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpTxPkts.setStatus('current')
if mibBuilder.loadTexts: gntpTxPkts.setDescription('Total number of NTP reply packets transmitted by the NTP daemon.')
gntpIgnoredPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpIgnoredPkts.setStatus('current')
if mibBuilder.loadTexts: gntpIgnoredPkts.setDescription('Total number of NTP request packets ignored by the NTP daemon.')
gntpDroppedPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpDroppedPkts.setStatus('current')
if mibBuilder.loadTexts: gntpDroppedPkts.setDescription('Total number of NTP request packets dropped by the NTP daemon.')
gntpAuthFail = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpAuthFail.setStatus('current')
if mibBuilder.loadTexts: gntpAuthFail.setDescription('Total number of authentication failures detected by the NTP daemon.')
gntpTimeFigureOfMerit = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("lessthan1us", 4), ("lessthan10us", 5), ("lessthan100us", 6), ("lessthan1ms", 7), ("lessthan10ms", 8), ("greaterthan10ms", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts: gntpTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation with GPS the TFOM is 4 and implies a worst case time error of 1 microsecond. During periods of signal loss, the GPS sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
gntpLeapIndBits = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("noFaultorLeap", 0), ("leapInsWarning", 1), ("leapDelWarning", 2), ("unSynchronized", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpLeapIndBits.setStatus('current')
if mibBuilder.loadTexts: gntpLeapIndBits.setDescription('This is a status code indicating: normal operation, a leap second to be inserted in the last minute of the current day, a leap second to be deleted in the last second of the day or an alarm condition indicating loss of timing synchronization. The leap indicator field of NTP reply packets sent from this server is set to gntpLeapIndBits.')
gntpSyncSource = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpSyncSource.setStatus('current')
if mibBuilder.loadTexts: gntpSyncSource.setDescription('This is an ASCII string identifying the synchronization source for this NTP server. It is one of GPS, CPU or NONE. If it is NONE, then the server is not synchronized, has its Leap Indicator Bits in the Alarm state and is running at Stratum 16. If it is CPU, then the server is running on its NTP disciplined CPU clock at Stratum 11. Check the Stratum, Leap Indicator Bits and Time Figure of Merit for further information. NTP reply packets from this server will have the reference identifier field set to gntpSyncSource if it is GPS. Otherwise it will be set to either 127.127.1.0 (CPU) or 0.0.0.0 (NONE).')
gntpOffsetToGPSReference = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpOffsetToGPSReference.setStatus('current')
if mibBuilder.loadTexts: gntpOffsetToGPSReference.setDescription('This is an ASCII string containing the floating value of the current offset in units of seconds of the NTP server CPU clock to the GPS reference time. Positive values imply that the NTP server clock is ahead of the GPS reference time.')
gntpStratum = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 11, 16))).clone(namedValues=NamedValues(("gntpStratumOne", 1), ("gntpStratumFlywheeling", 11), ("gntpStratumUnsync", 16)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpStratum.setStatus('current')
if mibBuilder.loadTexts: gntpStratum.setDescription('This is an integer showing the current stratum level being reported by the NTP daemon in its reply packets to clients. If it is 1, then the server is fully synchronized and delivering Stratum 1 accuracy. If it is 16, then the server is unambiguously unsynchronized. If it is 11, and the previous stratum value was 1, then the server is flywheeling on the local CPU clock. However, if the previous stratum value was 16, then the server has synchronized to its CPU Real Time Clock. NTP clients on the network should be configured to not use the time from this server if the stratum is not 1.')
gntpVersion = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpVersion.setStatus('current')
if mibBuilder.loadTexts: gntpVersion.setDescription('This is an ASCII string showing the NTP server firmware version.')
gpsTrapFaultStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 2, 1, 0, 1)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "gpsFaultStatus"))
if mibBuilder.loadTexts: gpsTrapFaultStatusChange.setStatus('current')
if mibBuilder.loadTexts: gpsTrapFaultStatusChange.setDescription('A gpsTrapFaultStatusChange trap signifies that the value of the fault status word reported by the GPS sub-system has changed. The current value is contained in the included gpsFaultStatus.')
gpsFaultStatus = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 1), Bits().clone(namedValues=NamedValues(("gpsAntennaFlt", 0), ("gpsNTPNotPolling", 1), ("gpsnotused0", 2), ("gpsnotused1", 3), ("gpsFLASHWriteFlt", 4), ("gpsFPGACfgFlt", 5), ("gpsNoSignalTimeout", 6), ("gpsDACNearLimit", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsFaultStatus.setStatus('current')
if mibBuilder.loadTexts: gpsFaultStatus.setDescription("This is a bit string contained in one character representing the least significant two nibbles of the GPS fault status word. Unfortunately, SNMP numbers the bits in the reverse order, so that the enumerated values are backwards from the description contained in the User's Manual for the fault status field returned by the gpsstat command. Each bit indicates a fault when set. Currently defined fault states encoded in this value: Bit 7: DAC controlling the TCXO is near the high or low limit. Bit 6: Time Figure of Merit has been 9 (unsynchronized) for 1 hour. Bit 5: Field Programmable Gate Array (FPGA) did not configure properly. Bit 4: FLASH memory had a write fault. Bit 3: Not Used. Bit 2: Not Used. Bit 1: NTP daemon is not polling the GPS reference clock. Bit 0: GPS antenna or feedline is shorted or open.")
gpsTimeFigureOfMerit = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("lessthan1us", 4), ("lessthan10us", 5), ("lessthan100us", 6), ("lessthan1ms", 7), ("lessthan10ms", 8), ("greaterthan10ms", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts: gpsTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation the TFOM is 4 and implies a worst case time error of 1 microsecond. During periods of signal loss, the GPS sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
gpsSigProcState = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("gpsAcquiring", 0), ("gpsLocking", 1), ("gpsLocked", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsSigProcState.setStatus('current')
if mibBuilder.loadTexts: gpsSigProcState.setDescription('Current GPS signal processor state. One of 0, 1 or 2, with 0 being the acquisition state and 2 the fully locked on state.')
gpsNumTrackSats = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 8))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsNumTrackSats.setStatus('current')
if mibBuilder.loadTexts: gpsNumTrackSats.setDescription('Current number of GPS satellites being tracked.')
gpsVCDAC = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsVCDAC.setStatus('current')
if mibBuilder.loadTexts: gpsVCDAC.setDescription('Current 16 bit, Voltage Controlled TCXO DAC value. Typical range is 20000 to 40000, where more positive numbers have the effect of raising the TCXO frequency.')
gpsAvgCarrierToNoiseRatiodB = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsAvgCarrierToNoiseRatiodB.setStatus('current')
if mibBuilder.loadTexts: gpsAvgCarrierToNoiseRatiodB.setDescription('ASCII string representing the current average carrier to noise ratio of all tracked satellites, in units of dB. Values less than 35 indicate weak signal conditions.')
gpsReferencePosition = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsReferencePosition.setStatus('current')
if mibBuilder.loadTexts: gpsReferencePosition.setDescription('WGS-84 latitude, longitude and height above the reference ellipsoid of the GPS antenna. Ellipsoid height may deviate from local Mean Sea Level by as much as 100 meters.')
gpsRefPosSource = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 3))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsRefPosSource.setStatus('current')
if mibBuilder.loadTexts: gpsRefPosSource.setDescription('ASCII string indicating the source of the GPS antenna reference position. It is one of: USR (user supplied), AVG (automatically determined by averaging thousands of 3-D position fixes, UNK (unknown).')
gpsCurrentLeapSeconds = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsCurrentLeapSeconds.setStatus('current')
if mibBuilder.loadTexts: gpsCurrentLeapSeconds.setDescription('This value is the current difference in seconds between GPS time and UTC time. GPS time is ahead of UTC time by this amount.')
gpsFutureLeapSeconds = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsFutureLeapSeconds.setStatus('current')
if mibBuilder.loadTexts: gpsFutureLeapSeconds.setDescription('This value is the future difference in seconds between GPS time and UTC time. Leap seconds may be inserted or deleted from the UTC timescale twice during the year: Dec 31 and June 30 at UTC midnight. If this value is the same as cdmaCurrentLeapSeconds, then no leap second insertion or deletion will occur at the next possible time. If it is different, then the change will take affect at the next possible time. GPS time will be ahead of UTC time by this amount.')
gpsVersion = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsVersion.setStatus('current')
if mibBuilder.loadTexts: gpsVersion.setDescription('ASCII string showing the GPS sub-system firmware and FPGA versions.')
mibBuilder.exportSymbols("ENDRUNTECHNOLOGIES-MIB", cntptrap=cntptrap, cntpDroppedPkts=cntpDroppedPkts, cdmaSigProcState=cdmaSigProcState, cdmaAGC=cdmaAGC, cdmaFutureLeapSeconds=cdmaFutureLeapSeconds, cntpAuthFail=cntpAuthFail, cdmaCurrentLeapSeconds=cdmaCurrentLeapSeconds, gntpIgnoredPkts=gntpIgnoredPkts, cdmaFaultStatus=cdmaFaultStatus, gpsAvgCarrierToNoiseRatiodB=gpsAvgCarrierToNoiseRatiodB, cdmaTimeFigureOfMerit=cdmaTimeFigureOfMerit, gntpVersion=gntpVersion, cdmaTrapFaultStatusChange=cdmaTrapFaultStatusChange, gpsReferencePosition=gpsReferencePosition, gpsFaultStatus=gpsFaultStatus, cdmatrap=cdmatrap, gntp=gntp, cntpTimeFigureOfMerit=cntpTimeFigureOfMerit, cdmaCarrierToNoiseRatio=cdmaCarrierToNoiseRatio, cdmaFrameErrorRate=cdmaFrameErrorRate, gntpTrapStratumChange=gntpTrapStratumChange, praecisGntp=praecisGntp, gntpLeapIndBits=gntpLeapIndBits, gntpRxPkts=gntpRxPkts, gntpTxPkts=gntpTxPkts, cdmaVCDAC=cdmaVCDAC, gntpOffsetToGPSReference=gntpOffsetToGPSReference, cntpIgnoredPkts=cntpIgnoredPkts, gntpTrapLeapIndBitsChange=gntpTrapLeapIndBitsChange, gntpDroppedPkts=gntpDroppedPkts, cntpStratum=cntpStratum, gntpStratum=gntpStratum, cntpOffsetToCDMAReference=cntpOffsetToCDMAReference, gpsSigProcState=gpsSigProcState, cdmaLeapMode=cdmaLeapMode, gpsRefPosSource=gpsRefPosSource, gntpSyncSource=gntpSyncSource, gpsVCDAC=gpsVCDAC, gpsNumTrackSats=gpsNumTrackSats, cntpTrapLeapIndBitsChange=cntpTrapLeapIndBitsChange, endRunTechnologiesMIB=endRunTechnologiesMIB, cdmaPNO=cdmaPNO, endRunTechnologies=endRunTechnologies, gntpAuthFail=gntpAuthFail, cntpSyncSource=cntpSyncSource, gpsCurrentLeapSeconds=gpsCurrentLeapSeconds, praecisCntp=praecisCntp, cntp=cntp, cntpRxPkts=cntpRxPkts, gntptrap=gntptrap, gpstrap=gpstrap, cdma=cdma, cntpVersion=cntpVersion, cntpTxPkts=cntpTxPkts, cntpLeapIndBits=cntpLeapIndBits, cdmaChannel=cdmaChannel, cdmaVersion=cdmaVersion, gpsTrapFaultStatusChange=gpsTrapFaultStatusChange, gpsFutureLeapSeconds=gpsFutureLeapSeconds, gntpTimeFigureOfMerit=gntpTimeFigureOfMerit, cntpTrapStratumChange=cntpTrapStratumChange, PYSNMP_MODULE_ID=endRunTechnologies, gps=gps, gpsVersion=gpsVersion, gpsTimeFigureOfMerit=gpsTimeFigureOfMerit)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'SingleValueConstraint')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(bits, object_identity, time_ticks, ip_address, module_identity, iso, counter32, unsigned32, mib_identifier, counter64, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, enterprises, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'ObjectIdentity', 'TimeTicks', 'IpAddress', 'ModuleIdentity', 'iso', 'Counter32', 'Unsigned32', 'MibIdentifier', 'Counter64', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'enterprises', 'Integer32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
end_run_technologies_mib = mib_identifier((1, 3, 6, 1, 4, 1, 13827))
end_run_technologies = module_identity((1, 3, 6, 1, 4, 1, 13827, 0))
if mibBuilder.loadTexts:
endRunTechnologies.setLastUpdated('0208190000Z')
if mibBuilder.loadTexts:
endRunTechnologies.setOrganization('EndRun Technologies LLC')
if mibBuilder.loadTexts:
endRunTechnologies.setContactInfo('Technical Support 1-877-749-3878 snmpsupport@endruntechnologies.com')
if mibBuilder.loadTexts:
endRunTechnologies.setDescription('EndRun Technologies Enterprise MIB')
praecis_cntp = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 1))
cntp = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 1, 0))
cntptrap = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0))
cdma = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 1, 1))
cdmatrap = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 1, 1, 0))
cntp_trap_leap_ind_bits_change = notification_type((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0, 1)).setObjects(('ENDRUNTECHNOLOGIES-MIB', 'cntpLeapIndBits'))
if mibBuilder.loadTexts:
cntpTrapLeapIndBitsChange.setStatus('current')
if mibBuilder.loadTexts:
cntpTrapLeapIndBitsChange.setDescription('A cntpTrapNTPLeapIndBitsChange trap signifies that the value of the leap indicator bits contained in the NTP reply packets sent by the time server has changed. The current value of these bits is contained in the included cntpLeapIndBits. The decimal value of these bits ranges from 0 to 3: 0 is the no fault, no leap warning condition 1 is the no fault, leap second insertion warning condition 2 is the no fault, leap second deletion warning condition 3 is the unsynchronized, alarm condition')
cntp_trap_stratum_change = notification_type((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0, 2)).setObjects(('ENDRUNTECHNOLOGIES-MIB', 'cntpStratum'))
if mibBuilder.loadTexts:
cntpTrapStratumChange.setStatus('current')
if mibBuilder.loadTexts:
cntpTrapStratumChange.setDescription('A cntpTrapStratumChange trap signifies that the value of the stratum field contained in the NTP reply packets sent by the time server has changed. The current value is contained in the included variable, cntpStratum. The decimal value of this field ranges from 1 to 16: 1 is the synchronized, actively locked to the reference UTC source stratum 11 is the synchronized, but flywheeling on the local real time clock stratum 16 is the unsynchronized stratum level')
cntp_rx_pkts = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpRxPkts.setStatus('current')
if mibBuilder.loadTexts:
cntpRxPkts.setDescription('Total number of NTP request packets received by the NTP daemon.')
cntp_tx_pkts = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpTxPkts.setStatus('current')
if mibBuilder.loadTexts:
cntpTxPkts.setDescription('Total number of NTP reply packets transmitted by the NTP daemon.')
cntp_ignored_pkts = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpIgnoredPkts.setStatus('current')
if mibBuilder.loadTexts:
cntpIgnoredPkts.setDescription('Total number of NTP request packets ignored by the NTP daemon.')
cntp_dropped_pkts = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpDroppedPkts.setStatus('current')
if mibBuilder.loadTexts:
cntpDroppedPkts.setDescription('Total number of NTP request packets dropped by the NTP daemon.')
cntp_auth_fail = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpAuthFail.setStatus('current')
if mibBuilder.loadTexts:
cntpAuthFail.setDescription('Total number of authentication failures detected by the NTP daemon.')
cntp_time_figure_of_merit = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(6, 7, 8, 9))).clone(namedValues=named_values(('lessthan100us', 6), ('lessthan1ms', 7), ('lessthan10ms', 8), ('greaterthan10ms', 9)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts:
cntpTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation with CDMA the TFOM is 6 and implies a worst case time error of 100 microseconds. During periods of signal loss, the CDMA sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
cntp_leap_ind_bits = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('noFaultorLeap', 0), ('leapInsWarning', 1), ('leapDelWarning', 2), ('unSynchronized', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpLeapIndBits.setStatus('current')
if mibBuilder.loadTexts:
cntpLeapIndBits.setDescription('This is a status code indicating: normal operation, a leap second to be inserted in the last minute of the current day, a leap second to be deleted in the last second of the day or an alarm condition indicating loss of timing synchronization. The leap indicator field of NTP reply packets sent from this server is set to cntpLeapIndBits.')
cntp_sync_source = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 4))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpSyncSource.setStatus('current')
if mibBuilder.loadTexts:
cntpSyncSource.setDescription('This is an ASCII string identifying the synchronization source for this NTP server. It is one of CDMA, CPU or NONE. If it is NONE, then the server is not synchronized, has its Leap Indicator Bits in the Alarm state and is running at Stratum 16. If it is CPU, then the server is free running on its NTP disciplined CPU clock at Stratum 11. Check the Stratum, Leap Indicator Bits and Time Figure of Merit for further information. NTP reply packets from this server will have the reference identifier field set to cntpSyncSource if it is CDMA. Otherwise it will be set to either 127.127.1.0 (CPU) or 0.0.0.0 (NONE).')
cntp_offset_to_cdma_reference = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 9), display_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpOffsetToCDMAReference.setStatus('current')
if mibBuilder.loadTexts:
cntpOffsetToCDMAReference.setDescription('This is an ASCII string containing the floating value of the current offset in units of seconds of the NTP server CPU clock to the CDMA reference time. Positive values imply that the NTP server clock is ahead of the CDMA reference time.')
cntp_stratum = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 11, 16))).clone(namedValues=named_values(('cntpStratumOne', 1), ('cntpStratumFlywheeling', 11), ('cntpStratumUnsync', 16)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpStratum.setStatus('current')
if mibBuilder.loadTexts:
cntpStratum.setDescription('This is an integer showing the current stratum level being reported by the NTP daemon in its reply packets to clients. If it is 1, then the server is fully synchronized and delivering Stratum 1 accuracy. If it is 16, then the server is unambiguously unsynchronized. If it is 11, and the previous stratum value was 1, then the server is flywheeling on the local CPU clock. However, if the previous stratum value was 16, then the server has synchronized to its CPU Real Time Clock. NTP clients on the network should be configured to not use the time from this server if the stratum is not 1.')
cntp_version = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 11), display_string().subtype(subtypeSpec=value_size_constraint(0, 80))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cntpVersion.setStatus('current')
if mibBuilder.loadTexts:
cntpVersion.setDescription('This is an ASCII string showing the NTP server firmware version.')
cdma_trap_fault_status_change = notification_type((1, 3, 6, 1, 4, 1, 13827, 1, 1, 0, 1)).setObjects(('ENDRUNTECHNOLOGIES-MIB', 'cdmaFaultStatus'))
if mibBuilder.loadTexts:
cdmaTrapFaultStatusChange.setStatus('current')
if mibBuilder.loadTexts:
cdmaTrapFaultStatusChange.setDescription('A cdmaTrapFaultStatusChange trap signifies that the value of the fault status word reported by the CDMA sub-system has changed. The current value is contained in the included cdmaFaultStatus.')
cdma_fault_status = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 1), bits().clone(namedValues=named_values(('cdmaNotUsed', 0), ('cdmaNTPNotPolling', 1), ('cdmaLOFailure', 2), ('cdmaLOPLLFlt', 3), ('cdmaFLASHWriteFlt', 4), ('cdmaFPGACfgFlt', 5), ('cdmaNoSignalTimeout', 6), ('cdmaDACNearLimit', 7)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaFaultStatus.setStatus('current')
if mibBuilder.loadTexts:
cdmaFaultStatus.setDescription("This is a bit string contained in one character representing the least significant two nibbles of the CDMA fault status word. Unfortunately, SNMP numbers the bits in the reverse order, so that the enumerated values are backwards from the description contained in the User's Manual for the fault status field returned by the cdmastat command. Each bit indicates a fault when set. Currently defined fault states encoded in this value: Bit 7: DAC controlling the TCXO is near the high or low limit. Bit 6: Time Figure of Merit has been 9 (unsynchronized) for 1 hour. Bit 5: Field Programmable Gate Array (FPGA) did not configure properly. Bit 4: FLASH memory had a write fault. Bit 3: Local Oscillator PLL fault. Bit 2: Local Oscillator PLL failed. Bit 1: NTP daemon is not polling the CDMA reference clock. Bit 0: Not Used.")
cdma_time_figure_of_merit = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(6, 7, 8, 9))).clone(namedValues=named_values(('lessthan100us', 6), ('lessthan1ms', 7), ('lessthan10ms', 8), ('greaterthan10ms', 9)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts:
cdmaTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 6 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation the TFOM is 6 and implies a worst case time error of 100 microseconds. During periods of signal loss, the CDMA sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
cdma_sig_proc_state = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 4, 8))).clone(namedValues=named_values(('cdmaAcquiring', 0), ('cdmaDetected', 1), ('cdmaCodeLocking', 2), ('cdmaCarrierLocking', 4), ('cdmaLocked', 8)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaSigProcState.setStatus('current')
if mibBuilder.loadTexts:
cdmaSigProcState.setDescription('Current CDMA signal processor state. One of 0, 1, 2, 4 or 8, with 0 indicating the acquisition state and 8 the fully locked on state.')
cdma_channel = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('priAbandclass0subclass0', 0), ('priBbandclass0subclass0', 1), ('secAbandclass0subclass0', 2), ('secBbandclass0subclass0', 3), ('priAbandclass0subclass1', 4), ('priBbandclass0subclass1', 5), ('secAbandclass0subclass1', 6), ('secBbandclass0subclass1', 7)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaChannel.setStatus('current')
if mibBuilder.loadTexts:
cdmaChannel.setDescription('Current CDMA frequency band and channel being used. Channels 0-3 are the North American cellular channels. Channels 4-7 are the South Korean cellular channels.')
cdma_pno = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 511))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaPNO.setStatus('current')
if mibBuilder.loadTexts:
cdmaPNO.setDescription('Current Pseudo Noise Offset of the base station being tracked. The value ranges from 0 to 511 and is in units of 64 Pseudo Noise Code chips. This offset serves as a base station identifier that is analogous to the Pseudo Random Noise (PRN) codes used by the individual satellites in the GPS system.')
cdma_agc = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaAGC.setStatus('current')
if mibBuilder.loadTexts:
cdmaAGC.setDescription('Current 8 bit, Automatic Gain Control (AGC) DAC value. Typical values are around 200, but proximity to the base station, type of building construction and orientation within the building have a strong influence on this value. More positive values have the effect of increasing the RF gain.')
cdma_vcdac = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaVCDAC.setStatus('current')
if mibBuilder.loadTexts:
cdmaVCDAC.setDescription('Current 16 bit, Voltage Controlled TCXO DAC value. Typical range is 20000 to 40000, where more positive numbers have the effect of raising the TCXO frequency.')
cdma_carrier_to_noise_ratio = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 4))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaCarrierToNoiseRatio.setStatus('current')
if mibBuilder.loadTexts:
cdmaCarrierToNoiseRatio.setDescription('ASCII string representing the current received CDMA signal carrier-to-noise ratio, a unitless quantity. Numbers less than 2.5 indicate a very weak signal condition.')
cdma_frame_error_rate = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 9), display_string().subtype(subtypeSpec=value_size_constraint(0, 5))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaFrameErrorRate.setStatus('current')
if mibBuilder.loadTexts:
cdmaFrameErrorRate.setDescription('ASCII string representing the current sync channel message error rate, a number ranging from 0.000 to 1.000. It indicates the proportion of messages received that fail the Cyclical Redundancy Check.')
cdma_leap_mode = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 10), display_string().subtype(subtypeSpec=value_size_constraint(0, 80))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaLeapMode.setStatus('current')
if mibBuilder.loadTexts:
cdmaLeapMode.setDescription('ASCII string showing the current leap second mode of operation for the CDMA sub-system. It is either AUTO or USER. If the mode is USER, then the current and future values of the UTC to GPS leap second offset is also included.')
cdma_current_leap_seconds = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 11), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaCurrentLeapSeconds.setStatus('current')
if mibBuilder.loadTexts:
cdmaCurrentLeapSeconds.setDescription('This value is the current difference in seconds between GPS time and UTC time. GPS time is ahead of UTC time by this amount.')
cdma_future_leap_seconds = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 12), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaFutureLeapSeconds.setStatus('current')
if mibBuilder.loadTexts:
cdmaFutureLeapSeconds.setDescription('This value is the future difference in seconds between GPS time and UTC time. Leap seconds may be inserted or deleted from the UTC timescale twice during the year: Dec 31 and June 30 at UTC midnight. If this value is the same as cdmaCurrentLeapSeconds, then no leap second insertion or deletion will occur at the next possible time. If it is different, then the change will take affect at the next possible time. GPS time will be ahead of UTC time by this amount.')
cdma_version = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 13), display_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdmaVersion.setStatus('current')
if mibBuilder.loadTexts:
cdmaVersion.setDescription('ASCII string showing the CDMA sub-system firmware and FPGA versions.')
praecis_gntp = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 2))
gntp = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 2, 0))
gntptrap = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0))
gps = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 2, 1))
gpstrap = mib_identifier((1, 3, 6, 1, 4, 1, 13827, 2, 1, 0))
gntp_trap_leap_ind_bits_change = notification_type((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0, 1)).setObjects(('ENDRUNTECHNOLOGIES-MIB', 'gntpLeapIndBits'))
if mibBuilder.loadTexts:
gntpTrapLeapIndBitsChange.setStatus('current')
if mibBuilder.loadTexts:
gntpTrapLeapIndBitsChange.setDescription('A gntpTrapNTPLeapIndBitsChange trap signifies that the value of the leap indicator bits contained in the NTP reply packets sent by the time server has changed. The current value of these bits is contained in the included gntpLeapIndBits. The decimal value of these bits ranges from 0 to 3: 0 is the no fault, no leap warning condition 1 is the no fault, leap second insertion warning condition 2 is the no fault, leap second deletion warning condition 3 is the unsynchronized, alarm condition')
gntp_trap_stratum_change = notification_type((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0, 2)).setObjects(('ENDRUNTECHNOLOGIES-MIB', 'gntpStratum'))
if mibBuilder.loadTexts:
gntpTrapStratumChange.setStatus('current')
if mibBuilder.loadTexts:
gntpTrapStratumChange.setDescription('A gntpTrapStratumChange trap signifies that the value of the stratum field contained in the NTP reply packets sent by the time server has changed. The current value is contained in the included variable, gntpStratum. The decimal value of this field ranges from 1 to 16: 1 is the synchronized, actively locked to the reference UTC source stratum 11 is the synchronized, but flywheeling on the local real time clock stratum 16 is the unsynchronized stratum level')
gntp_rx_pkts = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpRxPkts.setStatus('current')
if mibBuilder.loadTexts:
gntpRxPkts.setDescription('Total number of NTP request packets received by the NTP daemon.')
gntp_tx_pkts = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpTxPkts.setStatus('current')
if mibBuilder.loadTexts:
gntpTxPkts.setDescription('Total number of NTP reply packets transmitted by the NTP daemon.')
gntp_ignored_pkts = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpIgnoredPkts.setStatus('current')
if mibBuilder.loadTexts:
gntpIgnoredPkts.setDescription('Total number of NTP request packets ignored by the NTP daemon.')
gntp_dropped_pkts = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpDroppedPkts.setStatus('current')
if mibBuilder.loadTexts:
gntpDroppedPkts.setDescription('Total number of NTP request packets dropped by the NTP daemon.')
gntp_auth_fail = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpAuthFail.setStatus('current')
if mibBuilder.loadTexts:
gntpAuthFail.setDescription('Total number of authentication failures detected by the NTP daemon.')
gntp_time_figure_of_merit = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(4, 5, 6, 7, 8, 9))).clone(namedValues=named_values(('lessthan1us', 4), ('lessthan10us', 5), ('lessthan100us', 6), ('lessthan1ms', 7), ('lessthan10ms', 8), ('greaterthan10ms', 9)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts:
gntpTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation with GPS the TFOM is 4 and implies a worst case time error of 1 microsecond. During periods of signal loss, the GPS sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
gntp_leap_ind_bits = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('noFaultorLeap', 0), ('leapInsWarning', 1), ('leapDelWarning', 2), ('unSynchronized', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpLeapIndBits.setStatus('current')
if mibBuilder.loadTexts:
gntpLeapIndBits.setDescription('This is a status code indicating: normal operation, a leap second to be inserted in the last minute of the current day, a leap second to be deleted in the last second of the day or an alarm condition indicating loss of timing synchronization. The leap indicator field of NTP reply packets sent from this server is set to gntpLeapIndBits.')
gntp_sync_source = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 4))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpSyncSource.setStatus('current')
if mibBuilder.loadTexts:
gntpSyncSource.setDescription('This is an ASCII string identifying the synchronization source for this NTP server. It is one of GPS, CPU or NONE. If it is NONE, then the server is not synchronized, has its Leap Indicator Bits in the Alarm state and is running at Stratum 16. If it is CPU, then the server is running on its NTP disciplined CPU clock at Stratum 11. Check the Stratum, Leap Indicator Bits and Time Figure of Merit for further information. NTP reply packets from this server will have the reference identifier field set to gntpSyncSource if it is GPS. Otherwise it will be set to either 127.127.1.0 (CPU) or 0.0.0.0 (NONE).')
gntp_offset_to_gps_reference = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 9), display_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpOffsetToGPSReference.setStatus('current')
if mibBuilder.loadTexts:
gntpOffsetToGPSReference.setDescription('This is an ASCII string containing the floating value of the current offset in units of seconds of the NTP server CPU clock to the GPS reference time. Positive values imply that the NTP server clock is ahead of the GPS reference time.')
gntp_stratum = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 11, 16))).clone(namedValues=named_values(('gntpStratumOne', 1), ('gntpStratumFlywheeling', 11), ('gntpStratumUnsync', 16)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpStratum.setStatus('current')
if mibBuilder.loadTexts:
gntpStratum.setDescription('This is an integer showing the current stratum level being reported by the NTP daemon in its reply packets to clients. If it is 1, then the server is fully synchronized and delivering Stratum 1 accuracy. If it is 16, then the server is unambiguously unsynchronized. If it is 11, and the previous stratum value was 1, then the server is flywheeling on the local CPU clock. However, if the previous stratum value was 16, then the server has synchronized to its CPU Real Time Clock. NTP clients on the network should be configured to not use the time from this server if the stratum is not 1.')
gntp_version = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 11), display_string().subtype(subtypeSpec=value_size_constraint(0, 80))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gntpVersion.setStatus('current')
if mibBuilder.loadTexts:
gntpVersion.setDescription('This is an ASCII string showing the NTP server firmware version.')
gps_trap_fault_status_change = notification_type((1, 3, 6, 1, 4, 1, 13827, 2, 1, 0, 1)).setObjects(('ENDRUNTECHNOLOGIES-MIB', 'gpsFaultStatus'))
if mibBuilder.loadTexts:
gpsTrapFaultStatusChange.setStatus('current')
if mibBuilder.loadTexts:
gpsTrapFaultStatusChange.setDescription('A gpsTrapFaultStatusChange trap signifies that the value of the fault status word reported by the GPS sub-system has changed. The current value is contained in the included gpsFaultStatus.')
gps_fault_status = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 1), bits().clone(namedValues=named_values(('gpsAntennaFlt', 0), ('gpsNTPNotPolling', 1), ('gpsnotused0', 2), ('gpsnotused1', 3), ('gpsFLASHWriteFlt', 4), ('gpsFPGACfgFlt', 5), ('gpsNoSignalTimeout', 6), ('gpsDACNearLimit', 7)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsFaultStatus.setStatus('current')
if mibBuilder.loadTexts:
gpsFaultStatus.setDescription("This is a bit string contained in one character representing the least significant two nibbles of the GPS fault status word. Unfortunately, SNMP numbers the bits in the reverse order, so that the enumerated values are backwards from the description contained in the User's Manual for the fault status field returned by the gpsstat command. Each bit indicates a fault when set. Currently defined fault states encoded in this value: Bit 7: DAC controlling the TCXO is near the high or low limit. Bit 6: Time Figure of Merit has been 9 (unsynchronized) for 1 hour. Bit 5: Field Programmable Gate Array (FPGA) did not configure properly. Bit 4: FLASH memory had a write fault. Bit 3: Not Used. Bit 2: Not Used. Bit 1: NTP daemon is not polling the GPS reference clock. Bit 0: GPS antenna or feedline is shorted or open.")
gps_time_figure_of_merit = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(4, 5, 6, 7, 8, 9))).clone(namedValues=named_values(('lessthan1us', 4), ('lessthan10us', 5), ('lessthan100us', 6), ('lessthan1ms', 7), ('lessthan10ms', 8), ('greaterthan10ms', 9)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts:
gpsTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation the TFOM is 4 and implies a worst case time error of 1 microsecond. During periods of signal loss, the GPS sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
gps_sig_proc_state = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('gpsAcquiring', 0), ('gpsLocking', 1), ('gpsLocked', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsSigProcState.setStatus('current')
if mibBuilder.loadTexts:
gpsSigProcState.setDescription('Current GPS signal processor state. One of 0, 1 or 2, with 0 being the acquisition state and 2 the fully locked on state.')
gps_num_track_sats = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 8))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsNumTrackSats.setStatus('current')
if mibBuilder.loadTexts:
gpsNumTrackSats.setDescription('Current number of GPS satellites being tracked.')
gps_vcdac = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsVCDAC.setStatus('current')
if mibBuilder.loadTexts:
gpsVCDAC.setDescription('Current 16 bit, Voltage Controlled TCXO DAC value. Typical range is 20000 to 40000, where more positive numbers have the effect of raising the TCXO frequency.')
gps_avg_carrier_to_noise_ratiod_b = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 4))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsAvgCarrierToNoiseRatiodB.setStatus('current')
if mibBuilder.loadTexts:
gpsAvgCarrierToNoiseRatiodB.setDescription('ASCII string representing the current average carrier to noise ratio of all tracked satellites, in units of dB. Values less than 35 indicate weak signal conditions.')
gps_reference_position = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 7), display_string().subtype(subtypeSpec=value_size_constraint(0, 80))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsReferencePosition.setStatus('current')
if mibBuilder.loadTexts:
gpsReferencePosition.setDescription('WGS-84 latitude, longitude and height above the reference ellipsoid of the GPS antenna. Ellipsoid height may deviate from local Mean Sea Level by as much as 100 meters.')
gps_ref_pos_source = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 8), display_string().subtype(subtypeSpec=value_size_constraint(0, 3))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsRefPosSource.setStatus('current')
if mibBuilder.loadTexts:
gpsRefPosSource.setDescription('ASCII string indicating the source of the GPS antenna reference position. It is one of: USR (user supplied), AVG (automatically determined by averaging thousands of 3-D position fixes, UNK (unknown).')
gps_current_leap_seconds = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 9), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsCurrentLeapSeconds.setStatus('current')
if mibBuilder.loadTexts:
gpsCurrentLeapSeconds.setDescription('This value is the current difference in seconds between GPS time and UTC time. GPS time is ahead of UTC time by this amount.')
gps_future_leap_seconds = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 10), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsFutureLeapSeconds.setStatus('current')
if mibBuilder.loadTexts:
gpsFutureLeapSeconds.setDescription('This value is the future difference in seconds between GPS time and UTC time. Leap seconds may be inserted or deleted from the UTC timescale twice during the year: Dec 31 and June 30 at UTC midnight. If this value is the same as cdmaCurrentLeapSeconds, then no leap second insertion or deletion will occur at the next possible time. If it is different, then the change will take affect at the next possible time. GPS time will be ahead of UTC time by this amount.')
gps_version = mib_scalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 11), display_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
gpsVersion.setStatus('current')
if mibBuilder.loadTexts:
gpsVersion.setDescription('ASCII string showing the GPS sub-system firmware and FPGA versions.')
mibBuilder.exportSymbols('ENDRUNTECHNOLOGIES-MIB', cntptrap=cntptrap, cntpDroppedPkts=cntpDroppedPkts, cdmaSigProcState=cdmaSigProcState, cdmaAGC=cdmaAGC, cdmaFutureLeapSeconds=cdmaFutureLeapSeconds, cntpAuthFail=cntpAuthFail, cdmaCurrentLeapSeconds=cdmaCurrentLeapSeconds, gntpIgnoredPkts=gntpIgnoredPkts, cdmaFaultStatus=cdmaFaultStatus, gpsAvgCarrierToNoiseRatiodB=gpsAvgCarrierToNoiseRatiodB, cdmaTimeFigureOfMerit=cdmaTimeFigureOfMerit, gntpVersion=gntpVersion, cdmaTrapFaultStatusChange=cdmaTrapFaultStatusChange, gpsReferencePosition=gpsReferencePosition, gpsFaultStatus=gpsFaultStatus, cdmatrap=cdmatrap, gntp=gntp, cntpTimeFigureOfMerit=cntpTimeFigureOfMerit, cdmaCarrierToNoiseRatio=cdmaCarrierToNoiseRatio, cdmaFrameErrorRate=cdmaFrameErrorRate, gntpTrapStratumChange=gntpTrapStratumChange, praecisGntp=praecisGntp, gntpLeapIndBits=gntpLeapIndBits, gntpRxPkts=gntpRxPkts, gntpTxPkts=gntpTxPkts, cdmaVCDAC=cdmaVCDAC, gntpOffsetToGPSReference=gntpOffsetToGPSReference, cntpIgnoredPkts=cntpIgnoredPkts, gntpTrapLeapIndBitsChange=gntpTrapLeapIndBitsChange, gntpDroppedPkts=gntpDroppedPkts, cntpStratum=cntpStratum, gntpStratum=gntpStratum, cntpOffsetToCDMAReference=cntpOffsetToCDMAReference, gpsSigProcState=gpsSigProcState, cdmaLeapMode=cdmaLeapMode, gpsRefPosSource=gpsRefPosSource, gntpSyncSource=gntpSyncSource, gpsVCDAC=gpsVCDAC, gpsNumTrackSats=gpsNumTrackSats, cntpTrapLeapIndBitsChange=cntpTrapLeapIndBitsChange, endRunTechnologiesMIB=endRunTechnologiesMIB, cdmaPNO=cdmaPNO, endRunTechnologies=endRunTechnologies, gntpAuthFail=gntpAuthFail, cntpSyncSource=cntpSyncSource, gpsCurrentLeapSeconds=gpsCurrentLeapSeconds, praecisCntp=praecisCntp, cntp=cntp, cntpRxPkts=cntpRxPkts, gntptrap=gntptrap, gpstrap=gpstrap, cdma=cdma, cntpVersion=cntpVersion, cntpTxPkts=cntpTxPkts, cntpLeapIndBits=cntpLeapIndBits, cdmaChannel=cdmaChannel, cdmaVersion=cdmaVersion, gpsTrapFaultStatusChange=gpsTrapFaultStatusChange, gpsFutureLeapSeconds=gpsFutureLeapSeconds, gntpTimeFigureOfMerit=gntpTimeFigureOfMerit, cntpTrapStratumChange=cntpTrapStratumChange, PYSNMP_MODULE_ID=endRunTechnologies, gps=gps, gpsVersion=gpsVersion, gpsTimeFigureOfMerit=gpsTimeFigureOfMerit) |
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def max_pairwise_product_Fast(numbers):
n = len(numbers)
max_index1 = -1
for i in range(n):
if (max_index1 == -1) | (numbers[i] > numbers[max_index1]):
max_index1 = i
max_index2 = -1
for j in range(n):
if (j != max_index1) & ((max_index2 == -1) | (numbers[j] > numbers[max_index2])):
max_index2 = j
return ((numbers[max_index1])) * numbers[max_index2]
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product_Fast(input_numbers))
| def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product, numbers[first] * numbers[second])
return max_product
def max_pairwise_product__fast(numbers):
n = len(numbers)
max_index1 = -1
for i in range(n):
if (max_index1 == -1) | (numbers[i] > numbers[max_index1]):
max_index1 = i
max_index2 = -1
for j in range(n):
if (j != max_index1) & ((max_index2 == -1) | (numbers[j] > numbers[max_index2])):
max_index2 = j
return numbers[max_index1] * numbers[max_index2]
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product__fast(input_numbers)) |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage provides tools for reading and writing CRTF (CASA Region
Text Format) region files.
"""
| """
This subpackage provides tools for reading and writing CRTF (CASA Region
Text Format) region files.
""" |
## Find the prime numbers from 1 - 20
primeCheck = 0
for index in range(2,21):
# print("index values are",index)
for num in range(2,index):
# print("----> num is ",num)
if index%num == 0:
primeCheck = 0
print("Number ",index," not a prime")
break
else:
primeCheck = 1
#print("This is a prime number ",index)
if primeCheck == 1:
print("This is a prime number ",index) | prime_check = 0
for index in range(2, 21):
for num in range(2, index):
if index % num == 0:
prime_check = 0
print('Number ', index, ' not a prime')
break
else:
prime_check = 1
if primeCheck == 1:
print('This is a prime number ', index) |
class _AVLNode():
_BALANCE_FACTOR_LIMIT = 2;
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.size = 1
self._height = 0
self._balance_factor = 0
def search(self, key):
if key == self.value:
return self
elif key < self.value:
return self.left.search(key) if self._has_left_child() else None
else:
return self.right.search(key) if self._has_right_child() else None
def insert(self, value):
if value == self.value:
new_height = self._height
elif value < self.value:
if self.left is None:
self.left = _AVLNode(value)
new_height = max(self._height, 1)
else:
self.left = self.left.insert(value)
new_height = (max(self._height, self.left._height + 1)
if self._has_left_child()
else self._height)
else:
if self.right is None:
self.right = _AVLNode(value)
new_height = max(self._height, 1)
else:
self.right = self.right.insert(value)
new_height = (max(self._height, self.right._height + 1)
if self._has_right_child()
else self._height)
self._height = new_height
self._balance_factor = self._calculate_balance_factor()
if self._needs_rebalancing():
new_subtree_root = self._rebalance()
else:
new_subtree_root = self
self.size = self._recalculate_size()
return new_subtree_root
def delete(self, value):
new_subtree_root = self
if value < self.value:
self.left = (self.left.delete(value)
if self.left is not None
else None)
elif value > self.value:
self.right = (self.right.delete(value)
if self.right is not None
else None)
elif self._has_two_children():
self.value = self.right._min().value
self.right = self.right.delete(self.value)
else:
new_subtree_root = (self.left
if self.left is not None
else self.right)
self._height = self._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
if self._needs_rebalancing():
new_subtree_root = self._rebalance()
self.size = self._recalculate_size()
return new_subtree_root
def _min(self):
return self.left._min() if self._has_left_child() else self
def _needs_rebalancing(self):
return abs(self._balance_factor) >= _AVLNode._BALANCE_FACTOR_LIMIT
def _calculate_balance_factor(self):
right_subtree_height = (self.right._height
if self._has_right_child()
else -1)
left_subtree_height = (self.left._height
if self._has_left_child()
else -1)
return right_subtree_height - left_subtree_height
def _rebalance(self):
if self.right is None:
tallest_child = self.left
elif self.left is None:
tallest_child = self.right
else:
tallest_child = (self.right
if self.right._height > self.left._height
else self.left)
if tallest_child is self.left:
if tallest_child._is_right_heavy(): # Left-Right
return (self._rotate_right(
tallest_child._rotate_left(tallest_child.right)))
else: # Left-Left
return self._rotate_right(tallest_child)
elif tallest_child is self.right:
if tallest_child._is_left_heavy(): # Right-Left
return (self._rotate_left(
tallest_child._rotate_right(tallest_child.left)))
else: # Right-Right
return self._rotate_left(tallest_child)
def _rotate_left(self, pivot):
self.right = pivot.left
pivot.left = self
self._height = self._recalculate_height()
pivot._height = pivot._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
pivot.balance_factor = pivot._calculate_balance_factor()
self.size = self._recalculate_size()
pivot.size = pivot._recalculate_size()
return pivot
def _rotate_right(self, pivot):
self.left = pivot.right
pivot.right = self
self._height = self._recalculate_height()
pivot._height = pivot._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
pivot.balance_factor = pivot._calculate_balance_factor()
self.size = self._recalculate_size()
pivot.size = pivot._recalculate_size()
return pivot
def _recalculate_height(self):
return max(self.left._height if self._has_left_child() else -1,
self.right._height if self._has_right_child() else -1) + 1
def _recalculate_size(self):
size = 1
if self._has_left_child():
size += self.left.size
if self._has_right_child():
size += self.right.size
return size
def _has_two_children(self):
return self._has_left_child() and self._has_right_child()
def _has_left_child(self):
return self.left is not None
def _has_right_child(self):
return self.right is not None
def _is_right_heavy(self):
return self._balance_factor > 0
def _is_left_heavy(self):
return self._balance_factor < 0
| class _Avlnode:
_balance_factor_limit = 2
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.size = 1
self._height = 0
self._balance_factor = 0
def search(self, key):
if key == self.value:
return self
elif key < self.value:
return self.left.search(key) if self._has_left_child() else None
else:
return self.right.search(key) if self._has_right_child() else None
def insert(self, value):
if value == self.value:
new_height = self._height
elif value < self.value:
if self.left is None:
self.left = _avl_node(value)
new_height = max(self._height, 1)
else:
self.left = self.left.insert(value)
new_height = max(self._height, self.left._height + 1) if self._has_left_child() else self._height
elif self.right is None:
self.right = _avl_node(value)
new_height = max(self._height, 1)
else:
self.right = self.right.insert(value)
new_height = max(self._height, self.right._height + 1) if self._has_right_child() else self._height
self._height = new_height
self._balance_factor = self._calculate_balance_factor()
if self._needs_rebalancing():
new_subtree_root = self._rebalance()
else:
new_subtree_root = self
self.size = self._recalculate_size()
return new_subtree_root
def delete(self, value):
new_subtree_root = self
if value < self.value:
self.left = self.left.delete(value) if self.left is not None else None
elif value > self.value:
self.right = self.right.delete(value) if self.right is not None else None
elif self._has_two_children():
self.value = self.right._min().value
self.right = self.right.delete(self.value)
else:
new_subtree_root = self.left if self.left is not None else self.right
self._height = self._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
if self._needs_rebalancing():
new_subtree_root = self._rebalance()
self.size = self._recalculate_size()
return new_subtree_root
def _min(self):
return self.left._min() if self._has_left_child() else self
def _needs_rebalancing(self):
return abs(self._balance_factor) >= _AVLNode._BALANCE_FACTOR_LIMIT
def _calculate_balance_factor(self):
right_subtree_height = self.right._height if self._has_right_child() else -1
left_subtree_height = self.left._height if self._has_left_child() else -1
return right_subtree_height - left_subtree_height
def _rebalance(self):
if self.right is None:
tallest_child = self.left
elif self.left is None:
tallest_child = self.right
else:
tallest_child = self.right if self.right._height > self.left._height else self.left
if tallest_child is self.left:
if tallest_child._is_right_heavy():
return self._rotate_right(tallest_child._rotate_left(tallest_child.right))
else:
return self._rotate_right(tallest_child)
elif tallest_child is self.right:
if tallest_child._is_left_heavy():
return self._rotate_left(tallest_child._rotate_right(tallest_child.left))
else:
return self._rotate_left(tallest_child)
def _rotate_left(self, pivot):
self.right = pivot.left
pivot.left = self
self._height = self._recalculate_height()
pivot._height = pivot._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
pivot.balance_factor = pivot._calculate_balance_factor()
self.size = self._recalculate_size()
pivot.size = pivot._recalculate_size()
return pivot
def _rotate_right(self, pivot):
self.left = pivot.right
pivot.right = self
self._height = self._recalculate_height()
pivot._height = pivot._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
pivot.balance_factor = pivot._calculate_balance_factor()
self.size = self._recalculate_size()
pivot.size = pivot._recalculate_size()
return pivot
def _recalculate_height(self):
return max(self.left._height if self._has_left_child() else -1, self.right._height if self._has_right_child() else -1) + 1
def _recalculate_size(self):
size = 1
if self._has_left_child():
size += self.left.size
if self._has_right_child():
size += self.right.size
return size
def _has_two_children(self):
return self._has_left_child() and self._has_right_child()
def _has_left_child(self):
return self.left is not None
def _has_right_child(self):
return self.right is not None
def _is_right_heavy(self):
return self._balance_factor > 0
def _is_left_heavy(self):
return self._balance_factor < 0 |
#
# lithospheres
#
# =============================================================================
lith200 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,45e3,45e3,75e3,400e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith250 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,55e3,160e3,0.0e0,350e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith240 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,55e3,150e3,0.0e0,360e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith280 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,80e3,10e3,155e3,320e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith160 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,55e3,70e3,0.0e0,440e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith180 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,45e3,45e3,55e3,420e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith120 = {
"numlayers": 6,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matSLM'],
"thicknesses": [15e3,10e3,10e3,85.0e3,0.0e0,480e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.2e-6
},
"matMC": {
"H": 1.2e-6
},
"matLC": {
"H": 0.473e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 20.59375e-3
}
}
# =============================================================================
lith125 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,90e3,0.0e0,0.0e0,475e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.299e-6
},
"matMC": {
"H": 1.299e-6
},
"matLC": {
"H": 0.498e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 19.5e-3
}
}
# =============================================================================
ridge_NoOc_NoDiffLayer = {
"numlayers": 1,
"nature_layers": ['matSLM'],
"thicknesses": [600e3],
"thermalBc": ['thermBcSLM'],
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_top": 0.0e0,
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 19.5e-3
}
}
# =============================================================================
ridge_Oc6_5_NoDiffLayer = {
"numlayers": 5,
"nature_layers": ['matUC','matMC','matLC','matSLMd','matSLM'],
"thicknesses": [6.5e3, 0.0e0, 0.0e0, 118.5e3, 475.0e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcSLMd', 'thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H" : 0.0e0,
"rho": 2900.e0
},
"matMC": {
"H": 0.0e0,
"rho": 2900.e0
},
"matLC": {
"H": 0.0e0,
"rho": 2900.e0
},
"matSLMd": {
"rho": 3300,
"H": 0.0e0
},
"matSLM": {
"rho": 3300
},
"thermBcSLMd": {
"temp_bottom": 1603.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 437.2421875e-3
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 437.2421875e-3
}
}
| lith200 = {'numlayers': 7, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matLM1', 'matLM2', 'matLM3', 'matSLM'], 'thicknesses': [15000.0, 10000.0, 10000.0, 45000.0, 45000.0, 75000.0, 400000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcLM1', 'thermBcLM2', 'thermBcLM3', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 1.78e-06}, 'matMC': {'H': 1.78e-06}, 'matLC': {'H': 8.2e-07}, 'matLM1': {'rho': 3300}, 'matLM2': {'rho': 3300}, 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.0124460937}}
lith250 = {'numlayers': 7, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matLM1', 'matLM2', 'matLM3', 'matSLM'], 'thicknesses': [15000.0, 10000.0, 10000.0, 55000.0, 160000.0, 0.0, 350000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcLM1', 'thermBcLM2', 'thermBcLM3', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 1.78e-06}, 'matMC': {'H': 1.78e-06}, 'matLC': {'H': 8.2e-07}, 'matLM1': {'rho': 3300}, 'matLM2': {'rho': 3300}, 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.0124460937}}
lith240 = {'numlayers': 7, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matLM1', 'matLM2', 'matLM3', 'matSLM'], 'thicknesses': [15000.0, 10000.0, 10000.0, 55000.0, 150000.0, 0.0, 360000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcLM1', 'thermBcLM2', 'thermBcLM3', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 1.78e-06}, 'matMC': {'H': 1.78e-06}, 'matLC': {'H': 8.2e-07}, 'matLM1': {'rho': 3300}, 'matLM2': {'rho': 3300}, 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.0124460937}}
lith280 = {'numlayers': 7, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matLM1', 'matLM2', 'matLM3', 'matSLM'], 'thicknesses': [15000.0, 10000.0, 10000.0, 80000.0, 10000.0, 155000.0, 320000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcLM1', 'thermBcLM2', 'thermBcLM3', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 1.78e-06}, 'matMC': {'H': 1.78e-06}, 'matLC': {'H': 8.2e-07}, 'matLM1': {'rho': 3300}, 'matLM2': {'rho': 3300}, 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.0124460937}}
lith160 = {'numlayers': 7, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matLM1', 'matLM2', 'matLM3', 'matSLM'], 'thicknesses': [15000.0, 10000.0, 10000.0, 55000.0, 70000.0, 0.0, 440000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcLM1', 'thermBcLM2', 'thermBcLM3', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 1.78e-06}, 'matMC': {'H': 1.78e-06}, 'matLC': {'H': 8.2e-07}, 'matLM1': {'rho': 3300}, 'matLM2': {'rho': 3300}, 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.0124460937}}
lith180 = {'numlayers': 7, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matLM1', 'matLM2', 'matLM3', 'matSLM'], 'thicknesses': [15000.0, 10000.0, 10000.0, 45000.0, 45000.0, 55000.0, 420000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcLM1', 'thermBcLM2', 'thermBcLM3', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 1.78e-06}, 'matMC': {'H': 1.78e-06}, 'matLC': {'H': 8.2e-07}, 'matLM1': {'rho': 3300}, 'matLM2': {'rho': 3300}, 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.0124460937}}
lith120 = {'numlayers': 6, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matLM1', 'matLM2', 'matSLM'], 'thicknesses': [15000.0, 10000.0, 10000.0, 85000.0, 0.0, 480000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcLM1', 'thermBcLM2', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 1.2e-06}, 'matMC': {'H': 1.2e-06}, 'matLC': {'H': 4.73e-07}, 'matLM1': {'rho': 3300}, 'matLM2': {'rho': 3300}, 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.02059375}}
lith125 = {'numlayers': 7, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matLM1', 'matLM2', 'matLM3', 'matSLM'], 'thicknesses': [15000.0, 10000.0, 10000.0, 90000.0, 0.0, 0.0, 475000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcLM1', 'thermBcLM2', 'thermBcLM3', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 1.299e-06}, 'matMC': {'H': 1.299e-06}, 'matLC': {'H': 4.98e-07}, 'matLM1': {'rho': 3300}, 'matLM2': {'rho': 3300}, 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.0195}}
ridge__no_oc__no_diff_layer = {'numlayers': 1, 'nature_layers': ['matSLM'], 'thicknesses': [600000.0], 'thermalBc': ['thermBcSLM'], 'matSLM': {'rho': 3300}, 'thermBcSLM': {'temp_top': 0.0, 'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.0195}}
ridge__oc6_5__no_diff_layer = {'numlayers': 5, 'nature_layers': ['matUC', 'matMC', 'matLC', 'matSLMd', 'matSLM'], 'thicknesses': [6500.0, 0.0, 0.0, 118500.0, 475000.0], 'thermalBc': ['thermBcUC', 'thermBcMC', 'thermBcLC', 'thermBcSLMd', 'thermBcSLM'], 'matUC': {'temp_top': 0.0, 'H': 0.0, 'rho': 2900.0}, 'matMC': {'H': 0.0, 'rho': 2900.0}, 'matLC': {'H': 0.0, 'rho': 2900.0}, 'matSLMd': {'rho': 3300, 'H': 0.0}, 'matSLM': {'rho': 3300}, 'thermBcSLMd': {'temp_bottom': 1603.15, 'temp_potential': 1553.15, 'q_bottom': 0.4372421875}, 'thermBcSLM': {'temp_bottom': 1793.15, 'temp_potential': 1553.15, 'q_bottom': 0.4372421875}} |
def solution(A):
refSum = len(A) + 1
curSum = 0
for i in range(0, len(A)):
refSum += i + 1
curSum += A[i]
return refSum - curSum
assert 1 == solution([])
assert 2 == solution([ 1 ])
assert 1 == solution([ 2 ])
assert 4 == solution([ 2, 3, 1, 5 ])
MaxArrSize = 100000 # by the task
stressTestArr = []
for i in range(MaxArrSize):
stressTestArr.append(i + 1)
assert MaxArrSize + 1 == solution(stressTestArr)
| def solution(A):
ref_sum = len(A) + 1
cur_sum = 0
for i in range(0, len(A)):
ref_sum += i + 1
cur_sum += A[i]
return refSum - curSum
assert 1 == solution([])
assert 2 == solution([1])
assert 1 == solution([2])
assert 4 == solution([2, 3, 1, 5])
max_arr_size = 100000
stress_test_arr = []
for i in range(MaxArrSize):
stressTestArr.append(i + 1)
assert MaxArrSize + 1 == solution(stressTestArr) |
class Punto2D():
def __init__(self, x, y) -> None:
self.x = x
self.y = y
def traslacion(self, a, b):
punto = [self.x + a, self.y + b]
print(punto)
| class Punto2D:
def __init__(self, x, y) -> None:
self.x = x
self.y = y
def traslacion(self, a, b):
punto = [self.x + a, self.y + b]
print(punto) |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
ans = []
dfs = [[root,0]]
while dfs:
cur,i = dfs.pop()
if i >= len(ans): ans.append(0)
ans[i] += cur.val
if cur.left: dfs.append([cur.left,i+1])
if cur.right: dfs.append([cur.right,i])
return ans
| class Solution:
def solve(self, root):
ans = []
dfs = [[root, 0]]
while dfs:
(cur, i) = dfs.pop()
if i >= len(ans):
ans.append(0)
ans[i] += cur.val
if cur.left:
dfs.append([cur.left, i + 1])
if cur.right:
dfs.append([cur.right, i])
return ans |
dataset_type = 'UnconditionalImageDataset'
train_pipeline = [
dict(
type='LoadImageFromFile',
key='real_img',
io_backend='disk',
),
dict(type='Resize', keys=['real_img'], scale=(512, 384)),
dict(
type='NumpyPad',
keys=['real_img'],
padding=((64, 64), (0, 0), (0, 0)),
),
dict(type='Flip', keys=['real_img'], direction='horizontal'),
dict(
type='Normalize',
keys=['real_img'],
mean=[127.5] * 3,
std=[127.5] * 3,
to_rgb=False),
dict(type='ImageToTensor', keys=['real_img']),
dict(type='Collect', keys=['real_img'], meta_keys=['real_img_path'])
]
# `samples_per_gpu` and `imgs_root` need to be set.
data = dict(
samples_per_gpu=None,
workers_per_gpu=4,
train=dict(
type='RepeatDataset',
times=5,
dataset=dict(
type=dataset_type, imgs_root=None, pipeline=train_pipeline)),
val=dict(type=dataset_type, imgs_root=None, pipeline=train_pipeline))
| dataset_type = 'UnconditionalImageDataset'
train_pipeline = [dict(type='LoadImageFromFile', key='real_img', io_backend='disk'), dict(type='Resize', keys=['real_img'], scale=(512, 384)), dict(type='NumpyPad', keys=['real_img'], padding=((64, 64), (0, 0), (0, 0))), dict(type='Flip', keys=['real_img'], direction='horizontal'), dict(type='Normalize', keys=['real_img'], mean=[127.5] * 3, std=[127.5] * 3, to_rgb=False), dict(type='ImageToTensor', keys=['real_img']), dict(type='Collect', keys=['real_img'], meta_keys=['real_img_path'])]
data = dict(samples_per_gpu=None, workers_per_gpu=4, train=dict(type='RepeatDataset', times=5, dataset=dict(type=dataset_type, imgs_root=None, pipeline=train_pipeline)), val=dict(type=dataset_type, imgs_root=None, pipeline=train_pipeline)) |
__all__ = ['FirankaError', 'NotInDomainError', 'DomainError']
class FirankaError(Exception):
"""
Base class for firanka's exceptions
"""
class DomainError(FirankaError, ValueError):
"""Has something to do with the domain :)"""
class NotInDomainError(DomainError):
"""
Requested index is beyond this domain
"""
def __init__(self, index, domain, *args, **kwargs):
super().__init__(u'NotInDomainError: %s not in %s' % (index, domain), index, domain,
*args, **kwargs)
self.index = index
self.domain = domain
| __all__ = ['FirankaError', 'NotInDomainError', 'DomainError']
class Firankaerror(Exception):
"""
Base class for firanka's exceptions
"""
class Domainerror(FirankaError, ValueError):
"""Has something to do with the domain :)"""
class Notindomainerror(DomainError):
"""
Requested index is beyond this domain
"""
def __init__(self, index, domain, *args, **kwargs):
super().__init__(u'NotInDomainError: %s not in %s' % (index, domain), index, domain, *args, **kwargs)
self.index = index
self.domain = domain |
id_to_glfunc = {
160: "glAlphaFunc",
161: "GL_ALPHA_TEST",
162: "glBlendFunc",
163: "glBlendEquationSeparate",
164: "GL_BLEND",
165: "glCullFace",
166: "GL_CULL_FACE",
167: "glDepthFunc",
168: "glDepthMask",
169: "GL_DEPTH_TEST",
172: "glColorMask"
}
glBool_options = {
1: "GL_TRUE",
0: "GL_FALSE"
}
glEnable_options = {
1: "glEnable",
0: "glDisable"
}
glBlendFunc_options = {
0x0000: "GL_ZERO",
0x0001: "GL_ONE",
0x0300: "GL_SRC_COLOR",
0x0301: "GL_ONE_MINUS_SRC_COLOR",
0x0302: "GL_SRC_ALPHA",
0x0303: "GL_ONE_MINUS_SRC_ALPHA",
0x0304: "GL_DST_ALPHA",
0x0305: "GL_ONE_MINUS_DST_ALPHA"
}
glBlendEquationSeparate_options = {
0x8006: "GL_FUNC_ADD",
0x800A: "GL_FUNC_SUBTRACT",
0x800B: "GL_FUNC_REVERSE_SUBTRACT",
0x8007: "GL_MIN",
0x8008: "GL_MAX"
}
glCullFace_options = {
0x0404: "GL_FRONT",
0x0405: "GL_BACK",
0x0408: "GL_FRONT_AND_BACK"
}
glComparison_options = {
0x0200: "GL_NEVER",
0x0201: "GL_LESS",
0x0202: "GL_EQUAL",
0x0203: "GL_LEQUAL",
0x0204: "GL_GREATER",
0x0205: "GL_NOTEQUAL",
0x0206: "GL_GEQUAL",
0x0207: "GL_ALWAYS"
}
| id_to_glfunc = {160: 'glAlphaFunc', 161: 'GL_ALPHA_TEST', 162: 'glBlendFunc', 163: 'glBlendEquationSeparate', 164: 'GL_BLEND', 165: 'glCullFace', 166: 'GL_CULL_FACE', 167: 'glDepthFunc', 168: 'glDepthMask', 169: 'GL_DEPTH_TEST', 172: 'glColorMask'}
gl_bool_options = {1: 'GL_TRUE', 0: 'GL_FALSE'}
gl_enable_options = {1: 'glEnable', 0: 'glDisable'}
gl_blend_func_options = {0: 'GL_ZERO', 1: 'GL_ONE', 768: 'GL_SRC_COLOR', 769: 'GL_ONE_MINUS_SRC_COLOR', 770: 'GL_SRC_ALPHA', 771: 'GL_ONE_MINUS_SRC_ALPHA', 772: 'GL_DST_ALPHA', 773: 'GL_ONE_MINUS_DST_ALPHA'}
gl_blend_equation_separate_options = {32774: 'GL_FUNC_ADD', 32778: 'GL_FUNC_SUBTRACT', 32779: 'GL_FUNC_REVERSE_SUBTRACT', 32775: 'GL_MIN', 32776: 'GL_MAX'}
gl_cull_face_options = {1028: 'GL_FRONT', 1029: 'GL_BACK', 1032: 'GL_FRONT_AND_BACK'}
gl_comparison_options = {512: 'GL_NEVER', 513: 'GL_LESS', 514: 'GL_EQUAL', 515: 'GL_LEQUAL', 516: 'GL_GREATER', 517: 'GL_NOTEQUAL', 518: 'GL_GEQUAL', 519: 'GL_ALWAYS'} |
class Page:
def __init__(browser, fix, driver):
browser.fix = fix
browser.driver = driver
def find_element(browser, *locator):
return browser.fix.driver.find_element(*locator)
def find_elements(browser, *locator):
return browser.fix.driver.find_elements(*locator)
def click(browser, *locator):
e = browser.fix.driver.find_element(*locator)
e.click()
def input(browser, text, *locator):
e = browser.fix.driver.find_element(*locator)
e.click()
e.send_keys(text)
| class Page:
def __init__(browser, fix, driver):
browser.fix = fix
browser.driver = driver
def find_element(browser, *locator):
return browser.fix.driver.find_element(*locator)
def find_elements(browser, *locator):
return browser.fix.driver.find_elements(*locator)
def click(browser, *locator):
e = browser.fix.driver.find_element(*locator)
e.click()
def input(browser, text, *locator):
e = browser.fix.driver.find_element(*locator)
e.click()
e.send_keys(text) |
'''
module for implementation
of Z algorithm for
pattern matching
'''
def z_arr(string: str, z: list):
'''
fills z array for given
string
'''
len_str = len(string)
l, r, k = 0, 0, 0
for i in range (1, len_str):
if (i > r):
l, r = i, i
while (r < len_str and string[r - l] == string[r]):
r += 1
z[i] = r - l
r -= 1
else:
k = i - l
if (z[k] < r - i + 1):
z[i] = z[k]
else:
l = i
while (r < len_str and string[r - l] == string[r]):
r += 1
z[i] = r - l
r -= 1
def z_algorithm(text: str, pattern: str):
'''
returns all occurences
of pattern in the given
text
'''
result = []
concat = pattern + "$" + text
len_con = len(concat)
z = [0] * len_con
z_arr(concat, z)
for i in range (len_con):
if (z[i] == len(pattern)):
result.append(i - len(pattern) - 1)
return result
'''
PyAlgo
Devansh Singh, 2021
''' | """
module for implementation
of Z algorithm for
pattern matching
"""
def z_arr(string: str, z: list):
"""
fills z array for given
string
"""
len_str = len(string)
(l, r, k) = (0, 0, 0)
for i in range(1, len_str):
if i > r:
(l, r) = (i, i)
while r < len_str and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
k = i - l
if z[k] < r - i + 1:
z[i] = z[k]
else:
l = i
while r < len_str and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
def z_algorithm(text: str, pattern: str):
"""
returns all occurences
of pattern in the given
text
"""
result = []
concat = pattern + '$' + text
len_con = len(concat)
z = [0] * len_con
z_arr(concat, z)
for i in range(len_con):
if z[i] == len(pattern):
result.append(i - len(pattern) - 1)
return result
'\nPyAlgo\nDevansh Singh, 2021\n' |
class Solution:
def largestTimeFromDigits(self, A):
"""
:type A: List[int]
:rtype: str
"""
maxtime = ""
for i in range(4):
for j in range(4):
for k in range(4):
if i == j or i == k or k == j:
continue
h = A[i] * 10 + A[j]
m = A[k] * 10 + A[6 - i - j - k]
if 0 <= h < 24 and 0 <= m < 60:
time = "%02d:%02d" % (h, m)
if time > maxtime:
maxtime = time
return maxtime
if __name__ == '__main__':
solution = Solution()
print(solution.largestTimeFromDigits([1,2,3,4]))
print(solution.largestTimeFromDigits([5,5,5,5]))
print(solution.largestTimeFromDigits([0,0,0,0]))
print(solution.largestTimeFromDigits([2,0,6,6]))
print(solution.largestTimeFromDigits([0,2,7,6]))
else:
pass
| class Solution:
def largest_time_from_digits(self, A):
"""
:type A: List[int]
:rtype: str
"""
maxtime = ''
for i in range(4):
for j in range(4):
for k in range(4):
if i == j or i == k or k == j:
continue
h = A[i] * 10 + A[j]
m = A[k] * 10 + A[6 - i - j - k]
if 0 <= h < 24 and 0 <= m < 60:
time = '%02d:%02d' % (h, m)
if time > maxtime:
maxtime = time
return maxtime
if __name__ == '__main__':
solution = solution()
print(solution.largestTimeFromDigits([1, 2, 3, 4]))
print(solution.largestTimeFromDigits([5, 5, 5, 5]))
print(solution.largestTimeFromDigits([0, 0, 0, 0]))
print(solution.largestTimeFromDigits([2, 0, 6, 6]))
print(solution.largestTimeFromDigits([0, 2, 7, 6]))
else:
pass |
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
midIndex = round(len(aStr)/2)
if len(aStr) == 0 or len(aStr) == 1 and char != aStr[0]:
return False
# elif len(aStr) == 1 and char != aStr[0]:
# return False
elif char == aStr[midIndex]:
return True
elif char < aStr[midIndex]:
return isIn(char, aStr[:midIndex])
else:
return isIn(char, aStr[midIndex+1:])
print(isIn('e', 'bcfhhiklnrsvxxy')) | def is_in(char, aStr):
"""
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
"""
mid_index = round(len(aStr) / 2)
if len(aStr) == 0 or (len(aStr) == 1 and char != aStr[0]):
return False
elif char == aStr[midIndex]:
return True
elif char < aStr[midIndex]:
return is_in(char, aStr[:midIndex])
else:
return is_in(char, aStr[midIndex + 1:])
print(is_in('e', 'bcfhhiklnrsvxxy')) |
INPUT = 314
pos = 0
l = [0]
for i in range(1,2018):
pos = (pos + INPUT) % len(l) + 1
l.insert(pos, i)
pos += 1
if pos == len(l):
pos = 0
print("Part 1", l[pos])
size = 1
pos = 0
val = 1
for i in range(1,50000001):
pos = (pos + INPUT) % size + 1
if pos == 1:
val = size
size += 1
print("Part 2", val) | input = 314
pos = 0
l = [0]
for i in range(1, 2018):
pos = (pos + INPUT) % len(l) + 1
l.insert(pos, i)
pos += 1
if pos == len(l):
pos = 0
print('Part 1', l[pos])
size = 1
pos = 0
val = 1
for i in range(1, 50000001):
pos = (pos + INPUT) % size + 1
if pos == 1:
val = size
size += 1
print('Part 2', val) |
counter = 0
def handler(event, context):
global counter
result = {"counter": counter}
counter += 1
return result
| counter = 0
def handler(event, context):
global counter
result = {'counter': counter}
counter += 1
return result |
# Advent Of Code 2018, day 11, part 1
# http://adventofcode.com/2018/day/11
# solution by ByteCommander, 2018-12-11
with open("inputs/aoc2018_11.txt") as file:
serial = int(file.read())
def get_power(x_, y_):
rack_id = x_ + 10
power_lv = (rack_id * y_ + serial) * rack_id
return power_lv % 1000 // 100 - 5
biggest = None # (total power, (x, y))
for x in range(1, 301):
for y in range(1, 301):
big_square = sum(get_power(x + dx, y + dy) for dx in range(3) for dy in range(3))
if biggest is None or big_square > biggest[0]:
biggest = (big_square, (x, y))
print(f"The highest powered 3x3 square has {biggest[0]} total power "
f"and the coordinates {','.join(map(str, biggest[1]))}")
| with open('inputs/aoc2018_11.txt') as file:
serial = int(file.read())
def get_power(x_, y_):
rack_id = x_ + 10
power_lv = (rack_id * y_ + serial) * rack_id
return power_lv % 1000 // 100 - 5
biggest = None
for x in range(1, 301):
for y in range(1, 301):
big_square = sum((get_power(x + dx, y + dy) for dx in range(3) for dy in range(3)))
if biggest is None or big_square > biggest[0]:
biggest = (big_square, (x, y))
print(f"The highest powered 3x3 square has {biggest[0]} total power and the coordinates {','.join(map(str, biggest[1]))}") |
class Contorno:
def __init__(self, x, altura):
self.x = x
self.altura = altura
def __str__(self):
return str([self.x, self.altura])
class Edificio:
def __init__(self, izquierda, altura, derecha):
self.izquierda = izquierda
self.altura = altura
self.derecha = derecha
def conquista(listaA, listaB):
contornos = []
alturaA = 0
alturaB = 0
alturaActual = 0
while(listaA or listaB):
if(not listaB or (listaA and listaA[0].x < listaB[0].x)):
contorno = listaA.pop(0)
alturaA = contorno.altura
else:
contorno = listaB.pop(0)
alturaB = contorno.altura
alturaMax = max(alturaA, alturaB)
if alturaActual != alturaMax:
contornos.append(Contorno(contorno.x, alturaMax))
alturaActual = alturaMax
return contornos
def obtenerContorno(listaDeEdificios):
if len(listaDeEdificios) == 1:
edificio = listaDeEdificios[0]
return [Contorno(edificio.izquierda, edificio.altura), Contorno(edificio.derecha, 0)]
return conquista(
obtenerContorno(listaDeEdificios[:len(listaDeEdificios) // 2]),
obtenerContorno(listaDeEdificios[len(listaDeEdificios) // 2:])
)
def tuplasAEdificios(tuplas):
return [Edificio(a, b, c) for a,b,c in tuplas]
tuplas = [ (4,5,8) , (1,15,5) , (16,11,19) , (10,12,11) , (7,7,15) ]
# esperado (1,15) , (5,5) , (7,7) , (10,12) , (11,7) , (15,0) , (16,11) , (19,0)
result = obtenerContorno(tuplasAEdificios(tuplas))
for r in result:
print(r)
print('otra tuplaa')
otraTupla = [ (1, 11, 5), (2, 6, 7), (3, 13, 9), (12, 7, 16) , (14, 3, 25), (19,18,22) ]
# esperado Contorno: (1,11),(3,13),(9,0),(12,7),(16,3),(19,18),(22,3),(25,0)
result = obtenerContorno(tuplasAEdificios(otraTupla))
for r in result:
print(r)
| class Contorno:
def __init__(self, x, altura):
self.x = x
self.altura = altura
def __str__(self):
return str([self.x, self.altura])
class Edificio:
def __init__(self, izquierda, altura, derecha):
self.izquierda = izquierda
self.altura = altura
self.derecha = derecha
def conquista(listaA, listaB):
contornos = []
altura_a = 0
altura_b = 0
altura_actual = 0
while listaA or listaB:
if not listaB or (listaA and listaA[0].x < listaB[0].x):
contorno = listaA.pop(0)
altura_a = contorno.altura
else:
contorno = listaB.pop(0)
altura_b = contorno.altura
altura_max = max(alturaA, alturaB)
if alturaActual != alturaMax:
contornos.append(contorno(contorno.x, alturaMax))
altura_actual = alturaMax
return contornos
def obtener_contorno(listaDeEdificios):
if len(listaDeEdificios) == 1:
edificio = listaDeEdificios[0]
return [contorno(edificio.izquierda, edificio.altura), contorno(edificio.derecha, 0)]
return conquista(obtener_contorno(listaDeEdificios[:len(listaDeEdificios) // 2]), obtener_contorno(listaDeEdificios[len(listaDeEdificios) // 2:]))
def tuplas_a_edificios(tuplas):
return [edificio(a, b, c) for (a, b, c) in tuplas]
tuplas = [(4, 5, 8), (1, 15, 5), (16, 11, 19), (10, 12, 11), (7, 7, 15)]
result = obtener_contorno(tuplas_a_edificios(tuplas))
for r in result:
print(r)
print('otra tuplaa')
otra_tupla = [(1, 11, 5), (2, 6, 7), (3, 13, 9), (12, 7, 16), (14, 3, 25), (19, 18, 22)]
result = obtener_contorno(tuplas_a_edificios(otraTupla))
for r in result:
print(r) |
#Famous Quote:
Famous_person = "M. S. Dhoni"
Quote = "Hardwork, dedication, persevrance, disipline, etc all is required. But what matters the most in life is HONESTY."
print(Famous_person+" once said, \"" + Quote + "\"")
| famous_person = 'M. S. Dhoni'
quote = 'Hardwork, dedication, persevrance, disipline, etc all is required. But what matters the most in life is HONESTY.'
print(Famous_person + ' once said, "' + Quote + '"') |
EAST, NORTH, WEST, SOUTH = range(4)
def move(pos, dir):
x, y = pos
if dir == EAST:
return x + 1, y
if dir == WEST:
return x - 1, y
if dir == NORTH:
return x, y + 1
if dir == SOUTH:
return x, y - 1
def generate_spiral(n):
g = {}
x = 1
direction = EAST
pos= (0, 0)
s = 1
while x <= n:
for i in range(2):
for j in range(s):
g[x] = pos
pos = move(pos, direction)
x += 1
direction = (direction+1)%4
s += 1
return g
def num_steps_to(pos):
x, y = pos
return abs(x) + abs(y)
def main():
n = int(input())
g = generate_spiral(n)
print(num_steps_to(g[n]))
if __name__ == '__main__':
main() | (east, north, west, south) = range(4)
def move(pos, dir):
(x, y) = pos
if dir == EAST:
return (x + 1, y)
if dir == WEST:
return (x - 1, y)
if dir == NORTH:
return (x, y + 1)
if dir == SOUTH:
return (x, y - 1)
def generate_spiral(n):
g = {}
x = 1
direction = EAST
pos = (0, 0)
s = 1
while x <= n:
for i in range(2):
for j in range(s):
g[x] = pos
pos = move(pos, direction)
x += 1
direction = (direction + 1) % 4
s += 1
return g
def num_steps_to(pos):
(x, y) = pos
return abs(x) + abs(y)
def main():
n = int(input())
g = generate_spiral(n)
print(num_steps_to(g[n]))
if __name__ == '__main__':
main() |
def insertionSort(listku):
for index in range(1,len(listku)):
current_element = listku[index]
i = index
while current_element < listku[i-1] and i > 0:
listku[i] = listku[i-1]
i = i-1
listku[i] = current_element
jumlah = int(input("Berapa banyak element yang diinginkan : "))
list1 = [int(input()) for i in range (jumlah)]
insertionSort(list1)
print (list1)
| def insertion_sort(listku):
for index in range(1, len(listku)):
current_element = listku[index]
i = index
while current_element < listku[i - 1] and i > 0:
listku[i] = listku[i - 1]
i = i - 1
listku[i] = current_element
jumlah = int(input('Berapa banyak element yang diinginkan : '))
list1 = [int(input()) for i in range(jumlah)]
insertion_sort(list1)
print(list1) |
"""Generic contsnts"""
# Byte order magic numbers
# ----------------------------------------
ORDER_MAGIC_LE = 0x1A2B3C4D
ORDER_MAGIC_BE = 0x4D3C2B1A
SIZE_NOTSET = 0xFFFFFFFFFFFFFFFF # 64bit "-1"
# Endianness constants
ENDIAN_NATIVE = 0 # '='
ENDIAN_LITTLE = 1 # '<'
ENDIAN_BIG = 2 # '>'
| """Generic contsnts"""
order_magic_le = 439041101
order_magic_be = 1295788826
size_notset = 18446744073709551615
endian_native = 0
endian_little = 1
endian_big = 2 |
a = 2
b = 7
area = a * b
print(area)
c = 7
d = 8
area1 = c * d
print(area1)
e = 12
f = 5
area2 = e * f
print(area2)
side_g = int(input())
side_h = int(input())
print(side_g * side_h) | a = 2
b = 7
area = a * b
print(area)
c = 7
d = 8
area1 = c * d
print(area1)
e = 12
f = 5
area2 = e * f
print(area2)
side_g = int(input())
side_h = int(input())
print(side_g * side_h) |
#code
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def Push(self,new_data):
temp = self.head
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.prev = temp
def PrintDList(self):
temp = self.head
if self.head is None:
return
while temp is not None:
print(temp.data,end=" ")
temp = temp.next
print()
def ReversePrint(self):
temp = self.head
while temp.next is not None:
temp = temp.next
rev = temp
while rev is not None:
print(rev.data,end=" ")
rev = rev.prev
print()
if (__name__ == "__main__"):
arr = [8,2,3,1,7]
dlist = DoublyLinkedList()
for i in arr :
dlist.Push(i)
dlist.PrintDList()
dlist.ReversePrint()
| class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class Doublylinkedlist:
def __init__(self):
self.head = None
def push(self, new_data):
temp = self.head
new_node = node(new_data)
if self.head is None:
self.head = new_node
return
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.prev = temp
def print_d_list(self):
temp = self.head
if self.head is None:
return
while temp is not None:
print(temp.data, end=' ')
temp = temp.next
print()
def reverse_print(self):
temp = self.head
while temp.next is not None:
temp = temp.next
rev = temp
while rev is not None:
print(rev.data, end=' ')
rev = rev.prev
print()
if __name__ == '__main__':
arr = [8, 2, 3, 1, 7]
dlist = doubly_linked_list()
for i in arr:
dlist.Push(i)
dlist.PrintDList()
dlist.ReversePrint() |
class Model:
"""An object backed by a plain data structure.
For compatibility with JSON serialisation it's important that the inner
data structure not contain anything which cannot be serialised. This is
the responsibility of the implementer.
"""
# An optional schema to apply to the contents when set
validator = None
# Custom message to add to any validation errors
validation_error_title = None
def __init__(self, raw, validate=True):
"""
:param raw: The raw data to add to this object
"""
self.raw = raw
if validate and raw is not None:
self.validate()
def validate(self, error_title=None):
"""
Validate the contents of this object against the schema (if any)
If `validation_error_title` is set, then this will be used as a default
`error_title`.
:param error_title: A custom error message when errors are found
:raise SchemaValidationError: When errors are found
"""
if error_title is None:
error_title = self.validation_error_title
if self.validator is not None:
self.validator.validate_all(self.raw, error_title)
@classmethod
def extract_raw(cls, item):
"""Get raw data from a model, or return item if it is not a Model."""
if isinstance(item, Model):
return item.raw
return item
@classmethod
def dict_from_populated(cls, **kwargs):
"""Get a dict where keys only appear if the values are not None.
This is quite convenient for a lot of models."""
return {key: value for key, value in kwargs.items() if value is not None}
def __repr__(self):
return f"<{self.__class__.__name__}: {self.raw}>"
| class Model:
"""An object backed by a plain data structure.
For compatibility with JSON serialisation it's important that the inner
data structure not contain anything which cannot be serialised. This is
the responsibility of the implementer.
"""
validator = None
validation_error_title = None
def __init__(self, raw, validate=True):
"""
:param raw: The raw data to add to this object
"""
self.raw = raw
if validate and raw is not None:
self.validate()
def validate(self, error_title=None):
"""
Validate the contents of this object against the schema (if any)
If `validation_error_title` is set, then this will be used as a default
`error_title`.
:param error_title: A custom error message when errors are found
:raise SchemaValidationError: When errors are found
"""
if error_title is None:
error_title = self.validation_error_title
if self.validator is not None:
self.validator.validate_all(self.raw, error_title)
@classmethod
def extract_raw(cls, item):
"""Get raw data from a model, or return item if it is not a Model."""
if isinstance(item, Model):
return item.raw
return item
@classmethod
def dict_from_populated(cls, **kwargs):
"""Get a dict where keys only appear if the values are not None.
This is quite convenient for a lot of models."""
return {key: value for (key, value) in kwargs.items() if value is not None}
def __repr__(self):
return f'<{self.__class__.__name__}: {self.raw}>' |
# -*- coding: utf-8 -*-
def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
old_contacts = db.get_contact_list()
app.contact.add_new(contact)
app.contact.check_add_new_success(db, contact, old_contacts, check_ui)
| def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
old_contacts = db.get_contact_list()
app.contact.add_new(contact)
app.contact.check_add_new_success(db, contact, old_contacts, check_ui) |
def get_greater(project_arr):
version0 = project_arr[0].split(',')[1].lower()
version1 = project_arr[1].split(',')[1].lower()
split_char = None
if '.' in version0:
split_char = '.'
elif '_' in version0:
split_char = '_'
if split_char == None:
if version0 < version1:
return project_arr[0].split(',') , project_arr[1].split(',')
else:
return project_arr[1].split(',') , project_arr[0].split(',')
version0_splited = version0.split(split_char)
version1_splited = version1.split(split_char)
for i in range(len(version0_splited)):
number0 = version0_splited[i]
if (i + 1) > len(version1_splited):
break
number1 = version1_splited[i]
if number0.isdigit() and number1.isdigit():
if int(number0) < int(number1):
return project_arr[0].split(',') , project_arr[1].split(',')
elif int(number0) > int(number1):
return project_arr[1].split(',') , project_arr[0].split(',')
else:
if number0.lower() < number1.lower():
return project_arr[0].split(',') , project_arr[1].split(',')
elif number0.lower() > number1.lower():
return project_arr[1].split(',') , project_arr[0].split(',')
return project_arr[0].split(',') , project_arr[1].split(',')
projects = {}
with open('result.csv', 'r') as f:
skip_line = True
for line in f:
if skip_line:
skip_line = False
continue
line = line.strip()
projectname = line.split(',')[0]
if projectname not in projects:
projects[projectname] = [line]
else:
projects[projectname].append(line)
with open('compare.csv', 'w') as f:
f.write('projectname,diff loc,diff blocks,diff % disciplined,diff disciplined\n')
for project in projects:
if len(projects[project]) < 2:
continue
#first, second = ['','']
first,second = get_greater(projects[project])
#if projects[project][0].split(',')[1].lower() < projects[project][1].split(',')[1].lower():
# first = projects[project][0].split(',')
# second = projects[project][1].split(',')
#else:
# first = projects[project][1].split(',')
# second = projects[project][0].split(',')
diff_loc = int(second[3]) - int(first[3])
diff_blocks = int(second[4]) - int(first[4])
diff_disciplined = float(second[5]) - float(first[5])
diff_n_disciplined = int(second[-1]) - int(first[-1])
f.write(project + ',' + str(diff_loc) + ',' + str(diff_blocks) + ',' + \
str(round(diff_disciplined,2)) + ',' + str(diff_n_disciplined) + '\n') | def get_greater(project_arr):
version0 = project_arr[0].split(',')[1].lower()
version1 = project_arr[1].split(',')[1].lower()
split_char = None
if '.' in version0:
split_char = '.'
elif '_' in version0:
split_char = '_'
if split_char == None:
if version0 < version1:
return (project_arr[0].split(','), project_arr[1].split(','))
else:
return (project_arr[1].split(','), project_arr[0].split(','))
version0_splited = version0.split(split_char)
version1_splited = version1.split(split_char)
for i in range(len(version0_splited)):
number0 = version0_splited[i]
if i + 1 > len(version1_splited):
break
number1 = version1_splited[i]
if number0.isdigit() and number1.isdigit():
if int(number0) < int(number1):
return (project_arr[0].split(','), project_arr[1].split(','))
elif int(number0) > int(number1):
return (project_arr[1].split(','), project_arr[0].split(','))
elif number0.lower() < number1.lower():
return (project_arr[0].split(','), project_arr[1].split(','))
elif number0.lower() > number1.lower():
return (project_arr[1].split(','), project_arr[0].split(','))
return (project_arr[0].split(','), project_arr[1].split(','))
projects = {}
with open('result.csv', 'r') as f:
skip_line = True
for line in f:
if skip_line:
skip_line = False
continue
line = line.strip()
projectname = line.split(',')[0]
if projectname not in projects:
projects[projectname] = [line]
else:
projects[projectname].append(line)
with open('compare.csv', 'w') as f:
f.write('projectname,diff loc,diff blocks,diff % disciplined,diff disciplined\n')
for project in projects:
if len(projects[project]) < 2:
continue
(first, second) = get_greater(projects[project])
diff_loc = int(second[3]) - int(first[3])
diff_blocks = int(second[4]) - int(first[4])
diff_disciplined = float(second[5]) - float(first[5])
diff_n_disciplined = int(second[-1]) - int(first[-1])
f.write(project + ',' + str(diff_loc) + ',' + str(diff_blocks) + ',' + str(round(diff_disciplined, 2)) + ',' + str(diff_n_disciplined) + '\n') |
#Get states and coordinates and generates a csv file
lats = []
lons = []
states = []
lat = 0.0
lon = 0.0
infile = 'all_states.json'
with open(infile, 'r') as f:
for line in f:
if ('coordinates' in line):
lon = float(f.readline().strip().split(',')[0])
lat = float(f.readline().strip().split(',')[0])
#Pick only US states
if ('state' in line):
st = line.strip().split(':')[1]
print(st)
temp = f.readline()
country = f.readline().split(',')[0]
if ('country' in country):
country = country.split(':')[1]
else:
country = ""
if (len(st) < 40 and "United States of America" in country):
states.append(st)
lons.append(lon)
lats.append(lat)
with open("geo.dat", "w") as f:
f.write("state, lat, lon\n")
tam = len(states)
i = 0
while (i < tam):
line = states[i] + " " + str(lats[i]) + ", " + str(lons[i]) + "\n"
f.write(line)
i+=1
| lats = []
lons = []
states = []
lat = 0.0
lon = 0.0
infile = 'all_states.json'
with open(infile, 'r') as f:
for line in f:
if 'coordinates' in line:
lon = float(f.readline().strip().split(',')[0])
lat = float(f.readline().strip().split(',')[0])
if 'state' in line:
st = line.strip().split(':')[1]
print(st)
temp = f.readline()
country = f.readline().split(',')[0]
if 'country' in country:
country = country.split(':')[1]
else:
country = ''
if len(st) < 40 and 'United States of America' in country:
states.append(st)
lons.append(lon)
lats.append(lat)
with open('geo.dat', 'w') as f:
f.write('state, lat, lon\n')
tam = len(states)
i = 0
while i < tam:
line = states[i] + ' ' + str(lats[i]) + ', ' + str(lons[i]) + '\n'
f.write(line)
i += 1 |
# Allows us to read a espionage
def read_espionage(espionage, structures):
ans = {}
carefull = False
espionage = espionage.split('\n')
line = espionage[0].split(' ')
j = 4
while line[j][0] != '[':
j += 1
ans.update({'planet':' '.join(line[4:j])})
ans.update({'coordinates':line[j]})
ans.update({'date':'{} {}'.format(line[j+1], line[j+2])})
i = 2
name = ' '.join(espionage[i].split(' ')[1:])[1:]
pos = name.find('(')
if pos != -1:
name = name[:pos]
ans.update({'name':name})
ans.update({'inactive':pos!=-1})
i += 1
ans.update({'counterspionage':espionage[i].split(' ')[3]})
i += 3
line = espionage[i].split(' ')
resources = {}
resources.update({'metal':line[0]})
resources.update({'crystal':line[1]})
resources.update({'deuteryum':line[2]})
resources.update({'energy':line[3]})
ans.update({'resources':resources})
pipeline = ['ships','defense','buildings','research']
for element in pipeline:
i += 2
line = espionage[i].replace('.','')
care, entities = read_entities(line,structures[element])
if care:
carefull = True
ans.update({element:entities})
ans.update({'care':carefull})
return ans
def read_entity(structure,line):
num_structure = 0
#print(':' + structure + ': ---> :' + line[:len(structure)] + ':')
if structure == line[:len(structure)]:
line = line[len(structure)+1:]
j = 1
while j-1 < len(line) and line[:j].isdigit():
j += 1
num_structure = int(line[:j-1])
line = line[j-1:]
return line, num_structure
def read_entities(line, structure):
ans = {}
length = len(line)
while line != '':
for s in structure:
line, num = read_entity(structure[s], line)
if num != 0:
ans.update({s:num})
if len(line) == length:
break;
return len(ans) == 0, ans | def read_espionage(espionage, structures):
ans = {}
carefull = False
espionage = espionage.split('\n')
line = espionage[0].split(' ')
j = 4
while line[j][0] != '[':
j += 1
ans.update({'planet': ' '.join(line[4:j])})
ans.update({'coordinates': line[j]})
ans.update({'date': '{} {}'.format(line[j + 1], line[j + 2])})
i = 2
name = ' '.join(espionage[i].split(' ')[1:])[1:]
pos = name.find('(')
if pos != -1:
name = name[:pos]
ans.update({'name': name})
ans.update({'inactive': pos != -1})
i += 1
ans.update({'counterspionage': espionage[i].split(' ')[3]})
i += 3
line = espionage[i].split(' ')
resources = {}
resources.update({'metal': line[0]})
resources.update({'crystal': line[1]})
resources.update({'deuteryum': line[2]})
resources.update({'energy': line[3]})
ans.update({'resources': resources})
pipeline = ['ships', 'defense', 'buildings', 'research']
for element in pipeline:
i += 2
line = espionage[i].replace('.', '')
(care, entities) = read_entities(line, structures[element])
if care:
carefull = True
ans.update({element: entities})
ans.update({'care': carefull})
return ans
def read_entity(structure, line):
num_structure = 0
if structure == line[:len(structure)]:
line = line[len(structure) + 1:]
j = 1
while j - 1 < len(line) and line[:j].isdigit():
j += 1
num_structure = int(line[:j - 1])
line = line[j - 1:]
return (line, num_structure)
def read_entities(line, structure):
ans = {}
length = len(line)
while line != '':
for s in structure:
(line, num) = read_entity(structure[s], line)
if num != 0:
ans.update({s: num})
if len(line) == length:
break
return (len(ans) == 0, ans) |
##########################
###### MINI-MAX ######
##########################
class MiniMax:
# print utility value of root node (assuming it is max)
# print names of all nodes visited during search
def __init__(self, root):
#self.game_tree = game_tree # GameTree
self.root = root # GameNode
#self.currentNode = None # GameNode
self.successors = root.children # List of GameNodes
return
def minimax(self, node):
# first, find the max value
#best_val = self.max_value(node) # should be root node of tree
# second, find the node which HAS that max value
# --> means we need to propagate the values back up the
# tree as part of our minimax algorithm
successors = node.children
#print ("MiniMax: Utility Value of Root Node: = " + str(best_val))
# find the node with our best move
best_move = None
best_val = -1
for elem in successors: # ---> Need to propagate values up tree for this to work
print("Looking at ",elem.move, "with value: ", elem.value)
if elem.value >= best_val:
best_move = elem.move
best_val = elem.value
# return that best value that we've found
print("Best move is: ",best_move)
return best_move
def max_value(self, node):
#print ("MiniMax-->MAX: Visited Node :: " + str(node.move))
if self.isTerminal(node):
return self.getUtility(node)
infinity = float('inf')
max_value = -infinity
successors_states = self.getSuccessors(node)
for state in successors_states:
max_value = max(max_value, self.min_value(state))
return max_value
def min_value(self, node):
#print ("MiniMax-->MIN: Visited Node :: " + str(node.move))
if self.isTerminal(node):
return self.getUtility(node)
infinity = float('inf')
min_value = infinity
successor_states = self.getSuccessors(node)
for state in successor_states:
min_value = min(min_value, self.max_value(state))
return min_value
# #
# UTILITY METHODS #
# #
# successor states in a game tree are the child nodes...
def getSuccessors(self, node):
assert node is not None
return node.children
# return true if the node has NO children (successor states)
# return false if the node has children (successor states)
def isTerminal(self, node):
assert node is not None
return len(node.children) == 0
def getUtility(self, node):
assert node is not None
return node.value
| class Minimax:
def __init__(self, root):
self.root = root
self.successors = root.children
return
def minimax(self, node):
successors = node.children
best_move = None
best_val = -1
for elem in successors:
print('Looking at ', elem.move, 'with value: ', elem.value)
if elem.value >= best_val:
best_move = elem.move
best_val = elem.value
print('Best move is: ', best_move)
return best_move
def max_value(self, node):
if self.isTerminal(node):
return self.getUtility(node)
infinity = float('inf')
max_value = -infinity
successors_states = self.getSuccessors(node)
for state in successors_states:
max_value = max(max_value, self.min_value(state))
return max_value
def min_value(self, node):
if self.isTerminal(node):
return self.getUtility(node)
infinity = float('inf')
min_value = infinity
successor_states = self.getSuccessors(node)
for state in successor_states:
min_value = min(min_value, self.max_value(state))
return min_value
def get_successors(self, node):
assert node is not None
return node.children
def is_terminal(self, node):
assert node is not None
return len(node.children) == 0
def get_utility(self, node):
assert node is not None
return node.value |
# Creating a dictionary called 'birthdays' containing famous people's names as
# key and their birthday date as values.
birthdays = {
'Albert Einstein': '03/14/1879',
'Benjamin Franklin': '01/17/1706',
'Ada Lovelace': '12/10/1815',
'Donald Trump': '06/14/1946',
'Rowan Atkinson': '01/6/1955'}
# Creating a function 'print_birthdays' to display, through a for loop, the
# names of the people whose birthday date we have.
def print_birthdays():
print('''Welcome to the birthday dictionary. We know the birthdays of these
people:''')
for name in birthdays:
print(name)
# Creating a function 'return_birthday' to return the date of the requested
# famous person in the form of {famous person's name}'s birthday is
# {famous person's birthday date}; in case the requested famous person is
# not in our dictionary, we return the message 'Sadly, we don't have
# {famous person's name}'s birthday'.
def return_birthday(name):
if name in birthdays:
print('{}\'s birthday is {}.'.format(name, birthdays[name]))
else:
print('Sadly, we don\'t have {}\'s birthday.'.format(name))
def name_is_valid(name): # Check whether an input name is valid according to
# some conditions
if len(name) > 20:
return False
if name not in birthdays:
return False
if name.islower():
return False
return True
def just_the_surname(name): # Return just the surname of the person
if name in birthdays:
fullname = [name]
fullname = fullname[0].split()
return fullname[1]
def not_digit(name): # Check whether the input is a digit
if not name.isdigit():
return True
| birthdays = {'Albert Einstein': '03/14/1879', 'Benjamin Franklin': '01/17/1706', 'Ada Lovelace': '12/10/1815', 'Donald Trump': '06/14/1946', 'Rowan Atkinson': '01/6/1955'}
def print_birthdays():
print('Welcome to the birthday dictionary. We know the birthdays of these\n people:')
for name in birthdays:
print(name)
def return_birthday(name):
if name in birthdays:
print("{}'s birthday is {}.".format(name, birthdays[name]))
else:
print("Sadly, we don't have {}'s birthday.".format(name))
def name_is_valid(name):
if len(name) > 20:
return False
if name not in birthdays:
return False
if name.islower():
return False
return True
def just_the_surname(name):
if name in birthdays:
fullname = [name]
fullname = fullname[0].split()
return fullname[1]
def not_digit(name):
if not name.isdigit():
return True |
# See: https://docs.djangoproject.com/en/1.5/ref/settings/#authentication-backends
AUTH_USER_MODEL = 'auth.User'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
| auth_user_model = 'auth.User'
authentication_backends = ('django.contrib.auth.backends.ModelBackend',) |
# https://codeforces.com/problemset/problem/1519/B
t = int(input())
cases = [list(map(int, input().split())) for _ in range(t)]
for case in cases:
if (case[0]-1) + (case[0] * (case[1]-1)) == case[2]:
print('YES')
else:
print('NO') | t = int(input())
cases = [list(map(int, input().split())) for _ in range(t)]
for case in cases:
if case[0] - 1 + case[0] * (case[1] - 1) == case[2]:
print('YES')
else:
print('NO') |
subt = ''
file = 'BookCorpus2'
groups = ['ArXiv', 'BookCorpus2', 'Books3', 'DM Mathematics', 'Enron Emails', 'EuroParl', 'FreeLaw', 'Github', 'Gutenberg (PG-19)', 'HackerNews', 'NIH ExPorter', 'OpenSubtitles', 'OpenWebText2', 'Pile-CC', 'PhilPapers', 'PubMed Central', 'PubMed Abstracts', 'StackExchange', 'Ubuntu IRC', 'USPTO Backgrounds', 'Wikipedia (en)', 'YoutubeSubtitles']
for element in groups:
for a in range(0, 15):
print(f'{element}{a}')
with open(f'{element}{a}', 'r') as f:
subt = f.read()
subt = subt.encode('ascii', 'ignore').decode('unicode_escape')
# subt.join(subtL)
with open(f'lb/{element}{a}', "w") as f:
f.write(subt)
print(f'end of {a}') | subt = ''
file = 'BookCorpus2'
groups = ['ArXiv', 'BookCorpus2', 'Books3', 'DM Mathematics', 'Enron Emails', 'EuroParl', 'FreeLaw', 'Github', 'Gutenberg (PG-19)', 'HackerNews', 'NIH ExPorter', 'OpenSubtitles', 'OpenWebText2', 'Pile-CC', 'PhilPapers', 'PubMed Central', 'PubMed Abstracts', 'StackExchange', 'Ubuntu IRC', 'USPTO Backgrounds', 'Wikipedia (en)', 'YoutubeSubtitles']
for element in groups:
for a in range(0, 15):
print(f'{element}{a}')
with open(f'{element}{a}', 'r') as f:
subt = f.read()
subt = subt.encode('ascii', 'ignore').decode('unicode_escape')
with open(f'lb/{element}{a}', 'w') as f:
f.write(subt)
print(f'end of {a}') |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( s , t ) :
count = 0
for i in range ( 0 , len ( t ) ) :
if ( count == len ( s ) ) :
break
if ( t [ i ] == s [ count ] ) :
count = count + 1
return count
#TOFILL
if __name__ == '__main__':
param = [
('nObYIOjEQZ','uARTDTQbmGI',),
('84574','8538229',),
('1010001010010','11',),
('DjZtAfUudk','OewGm',),
('550','132744553919',),
('1110','0101',),
('GywyxwH','LPQqEqrDZiwY',),
('67318370914755','9928',),
('11011000000101','00000',),
('G','V',)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) | def f_gold(s, t):
count = 0
for i in range(0, len(t)):
if count == len(s):
break
if t[i] == s[count]:
count = count + 1
return count
if __name__ == '__main__':
param = [('nObYIOjEQZ', 'uARTDTQbmGI'), ('84574', '8538229'), ('1010001010010', '11'), ('DjZtAfUudk', 'OewGm'), ('550', '132744553919'), ('1110', '0101'), ('GywyxwH', 'LPQqEqrDZiwY'), ('67318370914755', '9928'), ('11011000000101', '00000'), ('G', 'V')]
n_success = 0
for (i, parameters_set) in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success += 1
print('#Results: %i, %i' % (n_success, len(param))) |
class No:
def __init__(self, valor):
self.valor = valor
self.proximo = None
self.anterior = None
def mostrar_no(self):
print(self.valor)
class FilaListaDuplamenteEncadeada:
def __init__(self):
self.primeiro = None
self.ultimo = None
def __fila_vazia(self):
return self.primeiro == None
def enfileirar(self, valor):
novo = No(valor)
if self.__fila_vazia():
self.primeiro = novo
else:
self.ultimo.proximo = novo
novo.anterior = self.ultimo
self.ultimo = novo
def mostrar_fila(self):
atual = self.primeiro
while atual != None:
atual.mostrar_no()
atual = atual.proximo
def desenfileirar(self):
temp = self.primeiro
if self.primeiro.proximo == None:
self.ultimo = None
else:
self.primeiro.proximo.anterior = None
self.primeiro = self.primeiro.proximo
return temp
fila = FilaListaDuplamenteEncadeada()
fila.enfileirar(4)
fila.enfileirar(3)
fila.enfileirar(2)
fila.enfileirar(1)
fila.enfileirar(0)
print('-'*7)
fila.mostrar_fila()
fila.desenfileirar()
fila.desenfileirar()
fila.desenfileirar()
fila.enfileirar(8)
print('-'*7)
fila.mostrar_fila()
| class No:
def __init__(self, valor):
self.valor = valor
self.proximo = None
self.anterior = None
def mostrar_no(self):
print(self.valor)
class Filalistaduplamenteencadeada:
def __init__(self):
self.primeiro = None
self.ultimo = None
def __fila_vazia(self):
return self.primeiro == None
def enfileirar(self, valor):
novo = no(valor)
if self.__fila_vazia():
self.primeiro = novo
else:
self.ultimo.proximo = novo
novo.anterior = self.ultimo
self.ultimo = novo
def mostrar_fila(self):
atual = self.primeiro
while atual != None:
atual.mostrar_no()
atual = atual.proximo
def desenfileirar(self):
temp = self.primeiro
if self.primeiro.proximo == None:
self.ultimo = None
else:
self.primeiro.proximo.anterior = None
self.primeiro = self.primeiro.proximo
return temp
fila = fila_lista_duplamente_encadeada()
fila.enfileirar(4)
fila.enfileirar(3)
fila.enfileirar(2)
fila.enfileirar(1)
fila.enfileirar(0)
print('-' * 7)
fila.mostrar_fila()
fila.desenfileirar()
fila.desenfileirar()
fila.desenfileirar()
fila.enfileirar(8)
print('-' * 7)
fila.mostrar_fila() |
class SinglyLinkedList:
def __init__(self, single_link_node_factory, *args, **kwargs):
super().__init__(*args, **kwargs)
self._linked_node_factory = single_link_node_factory
self._header = self._linked_node_factory()
self._tail = None
def __iter__(self):
return iter(self.head)
def __repr__(self):
return f"{self.__module__}.{self.__class__.__name__}()"
def __str__(self):
return self.__repr__()
def append(self, value=None):
self.insert(value)
def insert(self, value=None, link_before=None):
if link_before is not None:
link_after = link_before.next_link
link_before.next_link = self._linked_node_factory(value, link_after)
elif self.is_empty:
self._header.next_link = self._linked_node_factory(value)
self._tail = self._header.next_link
else:
old_tail = self._tail
old_tail.next_link = self._linked_node_factory(value)
self._tail = old_tail.next_link
def find(self, value):
if self.is_empty:
return None
current_link = self.head
while current_link is not None:
if current_link.value == value:
break
current_link = current_link.next_link
return current_link
@property
def head(self):
return self._header.next_link
@property
def tail(self):
return self._tail
@property
def is_empty(self):
return self.head is None
| class Singlylinkedlist:
def __init__(self, single_link_node_factory, *args, **kwargs):
super().__init__(*args, **kwargs)
self._linked_node_factory = single_link_node_factory
self._header = self._linked_node_factory()
self._tail = None
def __iter__(self):
return iter(self.head)
def __repr__(self):
return f'{self.__module__}.{self.__class__.__name__}()'
def __str__(self):
return self.__repr__()
def append(self, value=None):
self.insert(value)
def insert(self, value=None, link_before=None):
if link_before is not None:
link_after = link_before.next_link
link_before.next_link = self._linked_node_factory(value, link_after)
elif self.is_empty:
self._header.next_link = self._linked_node_factory(value)
self._tail = self._header.next_link
else:
old_tail = self._tail
old_tail.next_link = self._linked_node_factory(value)
self._tail = old_tail.next_link
def find(self, value):
if self.is_empty:
return None
current_link = self.head
while current_link is not None:
if current_link.value == value:
break
current_link = current_link.next_link
return current_link
@property
def head(self):
return self._header.next_link
@property
def tail(self):
return self._tail
@property
def is_empty(self):
return self.head is None |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def distribute_coins(self, root: TreeNode) -> int:
self.result = 0
self.post_order(root)
return self.result
def post_order(self, root) -> int:
if root is not None:
left = self.post_order(root.left)
right = self.post_order(root.right)
val = left + right + root.val - 1
self.result += abs(val)
return val
return 0
| class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def distribute_coins(self, root: TreeNode) -> int:
self.result = 0
self.post_order(root)
return self.result
def post_order(self, root) -> int:
if root is not None:
left = self.post_order(root.left)
right = self.post_order(root.right)
val = left + right + root.val - 1
self.result += abs(val)
return val
return 0 |
class Broker:
def purchase_shares():
raise NotImplementedError
def sell_shares():
raise NotImplementedError | class Broker:
def purchase_shares():
raise NotImplementedError
def sell_shares():
raise NotImplementedError |
print("#===Welcome to DNA/mRNA/tRNA/Anino Acid (Protein) Sequence Converter===#")
start = input("Press Enter to continue...")
while True:
if start == "":
print("Check Available Options:")
print("1. DNA")
print("2. mRNA")
print("3. tRNA")
print("4. Amino Acid(Protein)")
print("")
command = (input("Select input option(1-4): "))
if command == "1":
print("1. mRNA")
print("2. tRNA")
command2 = (input("Select output option(1,2): "))
data = input("Enter the DNA sequence: ")
result = ""
if command2 == "1":
for x in data:
if x.upper() == "A":
result += "A"
elif x.upper() == "T":
result += "U"
elif x.upper() == "C":
result += "C"
elif x.upper() == "G":
result += "G"
elif command2 == "2":
for x in data:
if x.upper() == "A":
result += "U"
elif x.upper() == "T":
result += "A"
elif x.upper() == "C":
result += "G"
elif x.upper() == "G":
result += "C"
else: print("Invalid Command")
print(result)
elif command == "2":
print("1. DNA")
print("2. tRNA")
command2 = (input("Select output option(1,2): "))
data = input("Enter the mRNA sequence: ")
result = ""
if command2 == "1":
for x in data:
if x.upper() == "A":
result += "A"
elif x.upper() == "T":
result += "U"
elif x.upper() == "C":
result += "C"
elif x.upper() == "G":
result += "G"
elif command2 == "2":
for x in data:
if x.upper() == "A":
result += "U"
elif x.upper() == "U":
result += "A"
elif x.upper() == "C":
result += "G"
elif x.upper() == "G":
result += "C"
print(result)
else: print("Invalid Command")
elif command == "3":
print("1. DNA")
print("2. mRNA")
command2 = (input("Select output option(1,2): "))
data = input("Enter the tRNA sequence: ")
result = ""
if command2 == "1":
for x in data:
if x.upper() == "A":
result += "T"
elif x.upper() == "U":
result += "A"
elif x.upper() == "C":
result += "G"
elif x.upper() == "G":
result += "C"
print(result)
elif command2 == "2":
for x in data:
if x.upper() == "A":
result += "U"
elif x.upper() == "U":
result += "A"
elif x.upper() == "C":
result += "G"
elif x.upper() == "G":
result += "C"
print(result)
elif command2 == "3":
print(data)
else: print("Invalid Command")
elif command == "4":
data = input("Enter mRNA sequence: ")
result = ""
array = []
if len(data)%3 != 0:
print("Invalid Sequence")
else:
for x in range(len(array)):
if array[x] == "UUU" or array[x] == "UUC":
result += "Phe"+"-"
elif array[x] == "UUA" or array[x] == "UUG" or array[x] == "CUU" or array[x] == "CUC" or array[x] == "CUA" or array[x] == "CUG":
result += "Leu"+"-"
elif array[x] == "UCU" or array[x] == "UCC" or array[x] == "UCA" or array[x] == "UCG" or array[x] == "AGU" or array[x] == "AGC":
result += "Ser"+"-"
elif array[x] == "UAU" or array[x] == "UAC":
result += "Tyr"+"-"
elif array[x] == "UGU" or array[x] == "UGC":
result += "Cys"+"-"
elif array[x] == "CCU" or array[x] == "CCC" or array[x] == "CCA" or array[x] == "CAG":
result += "Pro"+"-"
elif array[x] == "CAU" or array[x] == "CAC":
result += "His"+"-"
elif array[x] == "CAA" or array[x] == "CAG":
result += "Gin"+"-"
elif array[x] == "CGU" or array[x] == "CGC" or array[x] == "CGA" or array[x] == "CGG" or array[x] == "AGA" or array[x] == "AGG":
result += "Arg"+"-"
elif array[x] == "UGG":
result += "Trp"+"-"
elif array[x] == "AUG":
result += "Met"+"-"
elif array[x] == "AUU" or array[x] == "AUC" or array[x] == "AUA":
result += "Ile"+"-"
elif array[x] == "ACU" or array[x] == "ACC" or array[x] == "ACA" or array[x] == "ACG":
result += "Thr"+"-"
elif array[x] == "AAU" or array[x] == "AAC":
result += "Asn"+"-"
elif array[x] == "AAA" or array[x] == "AAG":
result += "Lys"+"-"
elif array[x] == "GUU" or array[x] == "GUC" or array[x] == "GUA" or array[x] == "GUG":
result += "Val"+"-"
elif array[x] == "GCU" or array[x] == "GCC" or array[x] == "GCA" or array[x] == "GCG":
result += "Ala"+"-"
elif array[x] == "GGU" or array[x] == "GGC" or array[x] == "GGA" or array[x] == "GGG":
result += "Gly"+"-"
elif array[x] == "GAU" or array[x] == "GAC":
result += "Asp"+"-"
elif array[x] == "GAA" or array[x] == "GAG":
result += "Glu"+"-"
else:
pass
final = result[:-1]
print(final)
else:
print("Something Went Wrong")
else:
break
self = input() | print('#===Welcome to DNA/mRNA/tRNA/Anino Acid (Protein) Sequence Converter===#')
start = input('Press Enter to continue...')
while True:
if start == '':
print('Check Available Options:')
print('1. DNA')
print('2. mRNA')
print('3. tRNA')
print('4. Amino Acid(Protein)')
print('')
command = input('Select input option(1-4): ')
if command == '1':
print('1. mRNA')
print('2. tRNA')
command2 = input('Select output option(1,2): ')
data = input('Enter the DNA sequence: ')
result = ''
if command2 == '1':
for x in data:
if x.upper() == 'A':
result += 'A'
elif x.upper() == 'T':
result += 'U'
elif x.upper() == 'C':
result += 'C'
elif x.upper() == 'G':
result += 'G'
elif command2 == '2':
for x in data:
if x.upper() == 'A':
result += 'U'
elif x.upper() == 'T':
result += 'A'
elif x.upper() == 'C':
result += 'G'
elif x.upper() == 'G':
result += 'C'
else:
print('Invalid Command')
print(result)
elif command == '2':
print('1. DNA')
print('2. tRNA')
command2 = input('Select output option(1,2): ')
data = input('Enter the mRNA sequence: ')
result = ''
if command2 == '1':
for x in data:
if x.upper() == 'A':
result += 'A'
elif x.upper() == 'T':
result += 'U'
elif x.upper() == 'C':
result += 'C'
elif x.upper() == 'G':
result += 'G'
elif command2 == '2':
for x in data:
if x.upper() == 'A':
result += 'U'
elif x.upper() == 'U':
result += 'A'
elif x.upper() == 'C':
result += 'G'
elif x.upper() == 'G':
result += 'C'
print(result)
else:
print('Invalid Command')
elif command == '3':
print('1. DNA')
print('2. mRNA')
command2 = input('Select output option(1,2): ')
data = input('Enter the tRNA sequence: ')
result = ''
if command2 == '1':
for x in data:
if x.upper() == 'A':
result += 'T'
elif x.upper() == 'U':
result += 'A'
elif x.upper() == 'C':
result += 'G'
elif x.upper() == 'G':
result += 'C'
print(result)
elif command2 == '2':
for x in data:
if x.upper() == 'A':
result += 'U'
elif x.upper() == 'U':
result += 'A'
elif x.upper() == 'C':
result += 'G'
elif x.upper() == 'G':
result += 'C'
print(result)
elif command2 == '3':
print(data)
else:
print('Invalid Command')
elif command == '4':
data = input('Enter mRNA sequence: ')
result = ''
array = []
if len(data) % 3 != 0:
print('Invalid Sequence')
else:
for x in range(len(array)):
if array[x] == 'UUU' or array[x] == 'UUC':
result += 'Phe' + '-'
elif array[x] == 'UUA' or array[x] == 'UUG' or array[x] == 'CUU' or (array[x] == 'CUC') or (array[x] == 'CUA') or (array[x] == 'CUG'):
result += 'Leu' + '-'
elif array[x] == 'UCU' or array[x] == 'UCC' or array[x] == 'UCA' or (array[x] == 'UCG') or (array[x] == 'AGU') or (array[x] == 'AGC'):
result += 'Ser' + '-'
elif array[x] == 'UAU' or array[x] == 'UAC':
result += 'Tyr' + '-'
elif array[x] == 'UGU' or array[x] == 'UGC':
result += 'Cys' + '-'
elif array[x] == 'CCU' or array[x] == 'CCC' or array[x] == 'CCA' or (array[x] == 'CAG'):
result += 'Pro' + '-'
elif array[x] == 'CAU' or array[x] == 'CAC':
result += 'His' + '-'
elif array[x] == 'CAA' or array[x] == 'CAG':
result += 'Gin' + '-'
elif array[x] == 'CGU' or array[x] == 'CGC' or array[x] == 'CGA' or (array[x] == 'CGG') or (array[x] == 'AGA') or (array[x] == 'AGG'):
result += 'Arg' + '-'
elif array[x] == 'UGG':
result += 'Trp' + '-'
elif array[x] == 'AUG':
result += 'Met' + '-'
elif array[x] == 'AUU' or array[x] == 'AUC' or array[x] == 'AUA':
result += 'Ile' + '-'
elif array[x] == 'ACU' or array[x] == 'ACC' or array[x] == 'ACA' or (array[x] == 'ACG'):
result += 'Thr' + '-'
elif array[x] == 'AAU' or array[x] == 'AAC':
result += 'Asn' + '-'
elif array[x] == 'AAA' or array[x] == 'AAG':
result += 'Lys' + '-'
elif array[x] == 'GUU' or array[x] == 'GUC' or array[x] == 'GUA' or (array[x] == 'GUG'):
result += 'Val' + '-'
elif array[x] == 'GCU' or array[x] == 'GCC' or array[x] == 'GCA' or (array[x] == 'GCG'):
result += 'Ala' + '-'
elif array[x] == 'GGU' or array[x] == 'GGC' or array[x] == 'GGA' or (array[x] == 'GGG'):
result += 'Gly' + '-'
elif array[x] == 'GAU' or array[x] == 'GAC':
result += 'Asp' + '-'
elif array[x] == 'GAA' or array[x] == 'GAG':
result += 'Glu' + '-'
else:
pass
final = result[:-1]
print(final)
else:
print('Something Went Wrong')
else:
break
self = input() |
# Recitation Lab 5 Question 1: Program to find smallest power of 2 greater than or equal to a number
# Author: Asmit De
# Date: 03/02/2017
# Input number
num = int(input('Enter a number: '))
# Initialize variable to the lowest power of 2
powervalue = 2
# Run loop until powervalue becomes greater than or equal to num
while powervalue < num:
# Generate the next power of 2 and update powervalue (just double it!)
powervalue *= 2
# Display final powervalue
print('The smallest power of 2 greater than or equal to', num, 'is', powervalue) | num = int(input('Enter a number: '))
powervalue = 2
while powervalue < num:
powervalue *= 2
print('The smallest power of 2 greater than or equal to', num, 'is', powervalue) |
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(s.split()[::-1])
def test_reverse_words():
s = Solution()
assert "blue is sky the" == s.reverseWords("the sky is blue")
assert "world! hello" == s.reverseWords(" hello world! ")
assert "example good a" == s.reverseWords("a good example")
| class Solution(object):
def reverse_words(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(s.split()[::-1])
def test_reverse_words():
s = solution()
assert 'blue is sky the' == s.reverseWords('the sky is blue')
assert 'world! hello' == s.reverseWords(' hello world! ')
assert 'example good a' == s.reverseWords('a good example') |
players = { "name" : "Messi", "age" : 32, "goals": 800, "cap" : 700}
players.keys()
for k in players.keys():
print(k) | players = {'name': 'Messi', 'age': 32, 'goals': 800, 'cap': 700}
players.keys()
for k in players.keys():
print(k) |
#maximo
def maximo(a,b):
if a > b:
return a
else:
return b
| def maximo(a, b):
if a > b:
return a
else:
return b |
n = int(input()) #lost fights
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
lost_fights_count = 0
helmet_brakes = 0
sword_brakes = 0
shield_brakes = 0
armor_brakes = 0
total_shield_brakes = 0
for x in range(n):
lost_fights_count += 1
if lost_fights_count % 2 == 0:
helmet_brakes += 1
if lost_fights_count % 3 == 0:
sword_brakes += 1
if lost_fights_count % 2 == 0:
shield_brakes += 1
total_shield_brakes += 1
if shield_brakes % 2 == 0 and shield_brakes != 0:
armor_brakes += 1
shield_brakes = 0
expenses = (helmet_brakes * helmet_price) + (sword_brakes * sword_price) \
+ (total_shield_brakes * shield_price) + (armor_brakes * armor_price)
print(f"Gladiator expenses: {expenses:.2f} aureus")
| n = int(input())
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
lost_fights_count = 0
helmet_brakes = 0
sword_brakes = 0
shield_brakes = 0
armor_brakes = 0
total_shield_brakes = 0
for x in range(n):
lost_fights_count += 1
if lost_fights_count % 2 == 0:
helmet_brakes += 1
if lost_fights_count % 3 == 0:
sword_brakes += 1
if lost_fights_count % 2 == 0:
shield_brakes += 1
total_shield_brakes += 1
if shield_brakes % 2 == 0 and shield_brakes != 0:
armor_brakes += 1
shield_brakes = 0
expenses = helmet_brakes * helmet_price + sword_brakes * sword_price + total_shield_brakes * shield_price + armor_brakes * armor_price
print(f'Gladiator expenses: {expenses:.2f} aureus') |
#!/usr/bin/env python
# coding: utf-8
# In[5]:
def left(i):
return 2 * i
def right(i):
return 2 * i + 1
def parent(i):
return i // 2
def MaxHeapify(lis, heap_size, i):
l = left(i)
r = right(i)
largest = 0
temp = 0
if (l <= heap_size) and lis[l] > lis[i]:
largest = l
else:
largest = i
if (r <= heap_size) and lis[r] > lis[largest]:
largest = r
if (largest != i):
temp = lis[i]
lis[i] = lis[largest]
lis[largest] = temp
MaxHeapify(lis, heap_size, largest)
def build_max_heap(lis, heap_size):
k = heap_size//2
while k >= 1:
MaxHeapify(lis, heap_size, k)
k = k - 1
return lis
lis = [0,12,7,13,5,10,17,1,2,3]
print(build_max_heap(lis, len(lis)-1))
| def left(i):
return 2 * i
def right(i):
return 2 * i + 1
def parent(i):
return i // 2
def max_heapify(lis, heap_size, i):
l = left(i)
r = right(i)
largest = 0
temp = 0
if l <= heap_size and lis[l] > lis[i]:
largest = l
else:
largest = i
if r <= heap_size and lis[r] > lis[largest]:
largest = r
if largest != i:
temp = lis[i]
lis[i] = lis[largest]
lis[largest] = temp
max_heapify(lis, heap_size, largest)
def build_max_heap(lis, heap_size):
k = heap_size // 2
while k >= 1:
max_heapify(lis, heap_size, k)
k = k - 1
return lis
lis = [0, 12, 7, 13, 5, 10, 17, 1, 2, 3]
print(build_max_heap(lis, len(lis) - 1)) |
"""ENum values dictionary for the Home Connect integration."""
enum_list = {
"BSH.Common.Status.OperationState" : "Operation State",
"BSH.Common.EnumType.OperationState.Inactive" : "Inactive",
"BSH.Common.EnumType.OperationState.Ready" : "Ready",
"BSH.Common.EnumType.OperationState.DelayedStart" : "Delayed Start",
"BSH.Common.EnumType.OperationState.Run" : "Run",
"BSH.Common.EnumType.OperationState.Pause" : "Pause",
"BSH.Common.EnumType.OperationState.ActionRequired" : "Action Required",
"BSH.Common.EnumType.OperationState.Finished" : "Finished",
"BSH.Common.EnumType.OperationState.Error" : "Error",
"BSH.Common.EnumType.OperationState.Aborting" : "Aborting",
"BSH.Common.Setting.PowerState" : "Power State",
"BSH.Common.EnumType.PowerState.Off" : "Off",
"BSH.Common.EnumType.PowerState.On" : "On",
"BSH.Common.EnumType.PowerState.Standby" : "Standby",
"BSH.Common.Setting.TemperatureUnit" : "Temperature Units",
"BSH.Common.EnumType.TemperatureUnit.Celsius" : "Celsius",
"BSH.Common.EnumType.TemperatureUnit.Fahrenheit" : "Fahrenheit",
"BSH.Common.Status.DoorState" : "Door State",
"BSH.Common.EnumType.DoorState.Open" : "Open",
"BSH.Common.EnumType.DoorState.Closed" : "Closed",
"BSH.Common.EnumType.DoorState.Locked" : "Locked",
"BSH.Common.Status.LocalControlActive" : "Local Control Activation",
"BSH.Common.Status.RemoteControlActive": "Remote Control Activation",
"BSH.Common.Status.RemoteControlStartAllowed" : "Remote Control Allowed",
"BSH.Common.Root.ActiveProgram" : "Active Program",
"BSH.Common.Root.SelectedProgram" : "Selected Program",
"BSH.Common.Option.RemainingProgramTime" : "Remaining Program Time",
"BSH.Common.Option.ElapsedProgramTime" : "Elapsed Program Time",
"BSH.Common.Option.ProgramProgress" : "Program Progress",
"BSH.Common.Option.Duration" : "Program Duration",
"BSH.Common.Event.ProgramFinished" : "Program Finished",
"BSH.Common.Event.AlarmClockElapsed" : "Alarm Clock Elapsed",
"LaundryCare.Dryer.Event.DryingProcessFinished" : "Drying Process Finished",
"BSH.Common.EnumType.EventPresentState.Present" : "Event Present",
"BSH.Common.EnumType.EventPresentState.Off" : "Event Off",
"BSH.Common.EnumType.EventPresentState.Confirmed" : "Event Confirmed",
"LaundryCare.Dryer.Program.Cotton" : "Cotton",
"LaundryCare.Dryer.Program.Synthetic" : "Synthetic",
"LaundryCare.Dryer.Program.Mix" : "Mix Textiles",
"LaundryCare.Dryer.Program.Blankets" : "Blankets",
"LaundryCare.Dryer.Program.BusinessShirts" : "Business Shirts",
"LaundryCare.Dryer.Program.DownFeathers" : "Down Feathers",
"LaundryCare.Dryer.Program.Hygiene" : "Hygiene",
"LaundryCare.Dryer.Program.Jeans" : "Jeans",
"LaundryCare.Dryer.Program.Outdoor" : "Outdoor",
"LaundryCare.Dryer.Program.SyntheticRefresh" : "Synthetic Refresh",
"LaundryCare.Dryer.Program.Towels" : "Towels",
"LaundryCare.Dryer.Program.Delicates" : "Delicates",
"LaundryCare.Dryer.Program.Super40" : "Super 40'",
"LaundryCare.Dryer.Program.Shirts15" : "Shirts 15'",
"LaundryCare.Dryer.Program.Pillow" : "Pillow",
"LaundryCare.Dryer.Program.AntiShrink" : "Anti-Shrink",
"LaundryCare.Dryer.Program.WoolFinish" : "Wool",
"LaundryCare.Dryer.Program.MyTime.MyDryingTime" : "Variable Time",
"LaundryCare.Dryer.Program.TimeCold" : "Variable Time - Cold",
"LaundryCare.Dryer.Program.TimeWarm" : "Variable Time - Warm",
"LaundryCare.Dryer.Program.InBasket" : "Variable Time - In Basket",
"LaundryCare.Dryer.Program.TimeColdFix.TimeCold20" : "Fix Time 20'- Cold",
"LaundryCare.Dryer.Program.TimeColdFix.TimeCold30" : "Fix Time 30'- Cold",
"LaundryCare.Dryer.Program.TimeColdFix.TimeCold60" : "Fix Time 60'- Cold",
"LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm30" : "Fix Time 30'- Warm",
"LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm40" : "Fix Time 40'- Warm",
"LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm60" : "Fix Time 60'- Warm",
"LaundryCare.Dryer.Program.Dessous" : "Dessous",
"LaundryCare.Dryer.Option.DryingTarget" : "Drying Target",
"LaundryCare.Dryer.EnumType.DryingTarget.IronDry" : "Iron Dry",
"LaundryCare.Dryer.EnumType.DryingTarget.CupboardDry" : "Cupboard Dry",
"LaundryCare.Dryer.EnumType.DryingTarget.CupboardDryPlus" : "Cupboard Dry Plus",
}
| """ENum values dictionary for the Home Connect integration."""
enum_list = {'BSH.Common.Status.OperationState': 'Operation State', 'BSH.Common.EnumType.OperationState.Inactive': 'Inactive', 'BSH.Common.EnumType.OperationState.Ready': 'Ready', 'BSH.Common.EnumType.OperationState.DelayedStart': 'Delayed Start', 'BSH.Common.EnumType.OperationState.Run': 'Run', 'BSH.Common.EnumType.OperationState.Pause': 'Pause', 'BSH.Common.EnumType.OperationState.ActionRequired': 'Action Required', 'BSH.Common.EnumType.OperationState.Finished': 'Finished', 'BSH.Common.EnumType.OperationState.Error': 'Error', 'BSH.Common.EnumType.OperationState.Aborting': 'Aborting', 'BSH.Common.Setting.PowerState': 'Power State', 'BSH.Common.EnumType.PowerState.Off': 'Off', 'BSH.Common.EnumType.PowerState.On': 'On', 'BSH.Common.EnumType.PowerState.Standby': 'Standby', 'BSH.Common.Setting.TemperatureUnit': 'Temperature Units', 'BSH.Common.EnumType.TemperatureUnit.Celsius': 'Celsius', 'BSH.Common.EnumType.TemperatureUnit.Fahrenheit': 'Fahrenheit', 'BSH.Common.Status.DoorState': 'Door State', 'BSH.Common.EnumType.DoorState.Open': 'Open', 'BSH.Common.EnumType.DoorState.Closed': 'Closed', 'BSH.Common.EnumType.DoorState.Locked': 'Locked', 'BSH.Common.Status.LocalControlActive': 'Local Control Activation', 'BSH.Common.Status.RemoteControlActive': 'Remote Control Activation', 'BSH.Common.Status.RemoteControlStartAllowed': 'Remote Control Allowed', 'BSH.Common.Root.ActiveProgram': 'Active Program', 'BSH.Common.Root.SelectedProgram': 'Selected Program', 'BSH.Common.Option.RemainingProgramTime': 'Remaining Program Time', 'BSH.Common.Option.ElapsedProgramTime': 'Elapsed Program Time', 'BSH.Common.Option.ProgramProgress': 'Program Progress', 'BSH.Common.Option.Duration': 'Program Duration', 'BSH.Common.Event.ProgramFinished': 'Program Finished', 'BSH.Common.Event.AlarmClockElapsed': 'Alarm Clock Elapsed', 'LaundryCare.Dryer.Event.DryingProcessFinished': 'Drying Process Finished', 'BSH.Common.EnumType.EventPresentState.Present': 'Event Present', 'BSH.Common.EnumType.EventPresentState.Off': 'Event Off', 'BSH.Common.EnumType.EventPresentState.Confirmed': 'Event Confirmed', 'LaundryCare.Dryer.Program.Cotton': 'Cotton', 'LaundryCare.Dryer.Program.Synthetic': 'Synthetic', 'LaundryCare.Dryer.Program.Mix': 'Mix Textiles', 'LaundryCare.Dryer.Program.Blankets': 'Blankets', 'LaundryCare.Dryer.Program.BusinessShirts': 'Business Shirts', 'LaundryCare.Dryer.Program.DownFeathers': 'Down Feathers', 'LaundryCare.Dryer.Program.Hygiene': 'Hygiene', 'LaundryCare.Dryer.Program.Jeans': 'Jeans', 'LaundryCare.Dryer.Program.Outdoor': 'Outdoor', 'LaundryCare.Dryer.Program.SyntheticRefresh': 'Synthetic Refresh', 'LaundryCare.Dryer.Program.Towels': 'Towels', 'LaundryCare.Dryer.Program.Delicates': 'Delicates', 'LaundryCare.Dryer.Program.Super40': "Super 40'", 'LaundryCare.Dryer.Program.Shirts15': "Shirts 15'", 'LaundryCare.Dryer.Program.Pillow': 'Pillow', 'LaundryCare.Dryer.Program.AntiShrink': 'Anti-Shrink', 'LaundryCare.Dryer.Program.WoolFinish': 'Wool', 'LaundryCare.Dryer.Program.MyTime.MyDryingTime': 'Variable Time', 'LaundryCare.Dryer.Program.TimeCold': 'Variable Time - Cold', 'LaundryCare.Dryer.Program.TimeWarm': 'Variable Time - Warm', 'LaundryCare.Dryer.Program.InBasket': 'Variable Time - In Basket', 'LaundryCare.Dryer.Program.TimeColdFix.TimeCold20': "Fix Time 20'- Cold", 'LaundryCare.Dryer.Program.TimeColdFix.TimeCold30': "Fix Time 30'- Cold", 'LaundryCare.Dryer.Program.TimeColdFix.TimeCold60': "Fix Time 60'- Cold", 'LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm30': "Fix Time 30'- Warm", 'LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm40': "Fix Time 40'- Warm", 'LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm60': "Fix Time 60'- Warm", 'LaundryCare.Dryer.Program.Dessous': 'Dessous', 'LaundryCare.Dryer.Option.DryingTarget': 'Drying Target', 'LaundryCare.Dryer.EnumType.DryingTarget.IronDry': 'Iron Dry', 'LaundryCare.Dryer.EnumType.DryingTarget.CupboardDry': 'Cupboard Dry', 'LaundryCare.Dryer.EnumType.DryingTarget.CupboardDryPlus': 'Cupboard Dry Plus'} |
lista = [];
lista.append(float(input("Digite o primeiro elemento")));
lista.append(float(input("Digite o segundo elemento")));
lista.append(float(input("Digite o terceiro elemento")));
lista.sort();
print(lista)
| lista = []
lista.append(float(input('Digite o primeiro elemento')))
lista.append(float(input('Digite o segundo elemento')))
lista.append(float(input('Digite o terceiro elemento')))
lista.sort()
print(lista) |
class HeapBinaryMin:
def __init__(self, data=[]):
self.data = data
self.build_max_heap()
def build_min_heap(self):
pass
def get_min(self):
return self.data[0]
def extract_min(self):
popped, self.data[0] = self.data[0], self.data[-1]
return popped
def insert(self, A: list):
current = len(self.data)
self.data.append(A)
while self.data[current] < self.data[self.parent(current)]:
self.data[current], self.data[self.parent(current)] = self.data[self.parent(current)], self.data[current]
current = self.parent(current)
def min_heapify(self, index):
pass
def parent(self, index: int) -> int:
'''Returns position of parent of element at index'''
return index // 2
def left_child(self, index: int) -> int:
'''Returns position of left child of element at index'''
return 2 * index
def right_child(self, index):
'''Returns position of right child of element at index'''
return 2 * index + 1
| class Heapbinarymin:
def __init__(self, data=[]):
self.data = data
self.build_max_heap()
def build_min_heap(self):
pass
def get_min(self):
return self.data[0]
def extract_min(self):
(popped, self.data[0]) = (self.data[0], self.data[-1])
return popped
def insert(self, A: list):
current = len(self.data)
self.data.append(A)
while self.data[current] < self.data[self.parent(current)]:
(self.data[current], self.data[self.parent(current)]) = (self.data[self.parent(current)], self.data[current])
current = self.parent(current)
def min_heapify(self, index):
pass
def parent(self, index: int) -> int:
"""Returns position of parent of element at index"""
return index // 2
def left_child(self, index: int) -> int:
"""Returns position of left child of element at index"""
return 2 * index
def right_child(self, index):
"""Returns position of right child of element at index"""
return 2 * index + 1 |
class ClassifierBase(object):
def getClassDistribution(self, instance):
raise NotImplementedError("This must be implemented by a concrete adapter.")
def classify(self, instance):
raise NotImplementedError("This must be implemented by a concrete adapter.")
| class Classifierbase(object):
def get_class_distribution(self, instance):
raise not_implemented_error('This must be implemented by a concrete adapter.')
def classify(self, instance):
raise not_implemented_error('This must be implemented by a concrete adapter.') |
i=int(input('enter a year'))
if (i%4)==0:
if (i%100)==0:
if (i%400)==0:
print('leap year')
else:
print('not a lep year')
else:
print('not a lep year')
else:
print('not a lep year')
| i = int(input('enter a year'))
if i % 4 == 0:
if i % 100 == 0:
if i % 400 == 0:
print('leap year')
else:
print('not a lep year')
else:
print('not a lep year')
else:
print('not a lep year') |
# -- MocaMultiProcessLock --------------------------------------------------------------------------
class MocaMultiProcessLock:
__slots__ = ("_rlock", "_blocking", "_acquired")
def __init__(self, rlock, blocking):
self._rlock = rlock
self._blocking = blocking
self._acquired = False
@property
def acquired(self):
return self._acquired
def __enter__(self):
self._acquired = self._rlock.acquire(blocking=self._blocking)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self._acquired:
self._rlock.release()
# -------------------------------------------------------------------------- MocaMultiProcessLock --
| class Mocamultiprocesslock:
__slots__ = ('_rlock', '_blocking', '_acquired')
def __init__(self, rlock, blocking):
self._rlock = rlock
self._blocking = blocking
self._acquired = False
@property
def acquired(self):
return self._acquired
def __enter__(self):
self._acquired = self._rlock.acquire(blocking=self._blocking)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self._acquired:
self._rlock.release() |
'''
Problem Statement : Single Number
Link : https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/528/week-1/3283/
score : accepted
'''
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for i in nums:
if nums.count(i)==1:
return i
| """
Problem Statement : Single Number
Link : https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/528/week-1/3283/
score : accepted
"""
class Solution:
def single_number(self, nums: List[int]) -> int:
for i in nums:
if nums.count(i) == 1:
return i |
## PARAMETERS TO CALCULATE LEARNING TIME
"----------------------------------------------------------------------------------------------------------------------"
############################################# Imports ##################################################################
"----------------------------------------------------------------------------------------------------------------------"
"--- Standard library imports ---"
"--- Third party imports ---"
"--- Local application imports ---"
"----------------------------------------------------------------------------------------------------------------------"
############### Test parameters ########################################################################################
"----------------------------------------------------------------------------------------------------------------------"
"--------------- Sample videos ---------------"
## Sample video to use module to determine duration time
duration_test_path = "/Users/rp_mbp/Desktop/USMLE STEP 1/Kaplan USMLE Step 1 Videos 2020/01 Anatomy 34h27m/01 Embryology & Histology/01 Gonad Development - Gonad Development.mp4"
"--------------- Test directory ---------------"
## Fictional directory to algorithm to convert dictionary into dataframe
test_dict_dir = {
"Topic_1": {
"Subtopic_1.1": {
"Class_1.1.1": {
"duration": 0.5
},
"Class_1.1.2": {
"duration": 0.75
},
"Class_1.1.3": {
"duration": 0.8
},
},
"Subtopic_1.2": {
"Class_1.2.1": {
"duration": 0.5
},
"Class_1.2.2": {
"duration": 0.75
},
"Class_1.2.3": {
"duration": 0.8
},
},
},
"Topic_2": {
"Subtopic_2.1": {
"Class_2.1.1": {
"duration": 0.5
},
"Class_2.1.2": {
"duration": 0.75
},
"Class_2.1.3": {
"duration": 0.8
},
},
"Subtopic_2.2": {
"Class_2.2.1": {
"duration": 0.5
},
"Class_2.2.2": {
"duration": 0.75
},
"Class_2.2.3": {
"duration": 0.8
},
},
},
}
"----------------------------------------------------------------------------------------------------------------------"
"----------------------------------------------------------------------------------------------------------------------"
############################################# END OF FILE ##############################################################
"----------------------------------------------------------------------------------------------------------------------"
"----------------------------------------------------------------------------------------------------------------------"
| """----------------------------------------------------------------------------------------------------------------------"""
'----------------------------------------------------------------------------------------------------------------------'
'--- Standard library imports ---'
'--- Third party imports ---'
'--- Local application imports ---'
'----------------------------------------------------------------------------------------------------------------------'
'----------------------------------------------------------------------------------------------------------------------'
'--------------- Sample videos ---------------'
duration_test_path = '/Users/rp_mbp/Desktop/USMLE STEP 1/Kaplan USMLE Step 1 Videos 2020/01 Anatomy 34h27m/01 Embryology & Histology/01 Gonad Development - Gonad Development.mp4'
'--------------- Test directory ---------------'
test_dict_dir = {'Topic_1': {'Subtopic_1.1': {'Class_1.1.1': {'duration': 0.5}, 'Class_1.1.2': {'duration': 0.75}, 'Class_1.1.3': {'duration': 0.8}}, 'Subtopic_1.2': {'Class_1.2.1': {'duration': 0.5}, 'Class_1.2.2': {'duration': 0.75}, 'Class_1.2.3': {'duration': 0.8}}}, 'Topic_2': {'Subtopic_2.1': {'Class_2.1.1': {'duration': 0.5}, 'Class_2.1.2': {'duration': 0.75}, 'Class_2.1.3': {'duration': 0.8}}, 'Subtopic_2.2': {'Class_2.2.1': {'duration': 0.5}, 'Class_2.2.2': {'duration': 0.75}, 'Class_2.2.3': {'duration': 0.8}}}}
'----------------------------------------------------------------------------------------------------------------------'
'----------------------------------------------------------------------------------------------------------------------'
'----------------------------------------------------------------------------------------------------------------------'
'----------------------------------------------------------------------------------------------------------------------' |
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='servod'
revs = [513]
inas = [('ina3221', '0x40:0', 'pp1000_a_pmic', 7.6, 0.010, 'rem', True), # PR127, ppvar_sys_pmic_v1
('ina3221', '0x40:1', 'ppvar_bl_pwr', 7.6, 0.005, 'rem', True), # F1, originally fuse
('ina3221', '0x40:2', 'ppvar_vcc', 7.6, 0.010, 'rem', True), # PR87, +8.4VB_VCC1_VIN
('ina3221', '0x41:0', 'pp5000_a', 5.0, 0.005, 'rem', True), # PR160
('ina3221', '0x41:1', 'pp5000_a_pmic', 7.6, 0.010, 'rem', True), # PR159, ppvar_sys_pmic_v5
('ina3221', '0x41:2', 'pp1800_a', 1.8, 0.010, 'rem', True), # PR137
('ina3221', '0x42:0', 'pp1200_vddq', 1.2, 0.005, 'rem', True), # PR152
('ina3221', '0x42:1', 'pp0600_ddrvtt', 0.6, 0.010, 'rem', True), # PR929
('ina3221', '0x42:2', 'pp1200_vddq_pmic', 7.6, 0.000, 'rem', False), # PR151, ppvar_sys_pmic_v4
('ina3221', '0x43:0', 'pp1800_a_pmic', 3.3, 0.000, 'rem', False), # PR1236, vinvr2_650830
('ina3221', '0x43:1', 'pp0600_ddrvtt_pmic', 1.2, 0.000, 'rem', False), # PR931, pp1200_vddq_ddrvttin
('ina3221', '0x43:2', 'pp3300_dsw_pmic', 7.6, 0.010, 'rem', True), # PR140, ppvar_sys_pmic_v3
# ('ina219', '0x44', 'ppvar_vcc2', 7.6, 0.010, 'rem', True), # PR92, +8.4VB_VCC2_VIN, not stuffed
('ina219', '0x45', 'ppvar_sa', 7.6, 0.010, 'rem', True), # PR99
('ina219', '0x46', 'pp3300_dsw', 3.3, 0.005, 'rem', True), # PR138
('ina219', '0x47', 'vbat', 7.6, 0.010, 'rem', True), # PR11
('ina219', '0x48', 'ppvar_gt', 7.6, 0.010, 'rem', True), # PR97
('ina219', '0x49', 'pp3300_s', 3.3, 0.010, 'rem', True), # R4920
('ina219', '0x4a', 'pp3300_dx_wlan', 3.3, 0.010, 'rem', True), # R381
('ina219', '0x4b', 'pp1000_a', 1.0, 0.005, 'rem', True), # PR128
('ina219', '0x4c', 'pp3300_dx_edp', 3.3, 0.010, 'rem', True), # R378
('ina219', '0x4d', 'pp3300_dsw_ec', 3.3, 0.010, 'rem', True)] # R953
| config_type = 'servod'
revs = [513]
inas = [('ina3221', '0x40:0', 'pp1000_a_pmic', 7.6, 0.01, 'rem', True), ('ina3221', '0x40:1', 'ppvar_bl_pwr', 7.6, 0.005, 'rem', True), ('ina3221', '0x40:2', 'ppvar_vcc', 7.6, 0.01, 'rem', True), ('ina3221', '0x41:0', 'pp5000_a', 5.0, 0.005, 'rem', True), ('ina3221', '0x41:1', 'pp5000_a_pmic', 7.6, 0.01, 'rem', True), ('ina3221', '0x41:2', 'pp1800_a', 1.8, 0.01, 'rem', True), ('ina3221', '0x42:0', 'pp1200_vddq', 1.2, 0.005, 'rem', True), ('ina3221', '0x42:1', 'pp0600_ddrvtt', 0.6, 0.01, 'rem', True), ('ina3221', '0x42:2', 'pp1200_vddq_pmic', 7.6, 0.0, 'rem', False), ('ina3221', '0x43:0', 'pp1800_a_pmic', 3.3, 0.0, 'rem', False), ('ina3221', '0x43:1', 'pp0600_ddrvtt_pmic', 1.2, 0.0, 'rem', False), ('ina3221', '0x43:2', 'pp3300_dsw_pmic', 7.6, 0.01, 'rem', True), ('ina219', '0x45', 'ppvar_sa', 7.6, 0.01, 'rem', True), ('ina219', '0x46', 'pp3300_dsw', 3.3, 0.005, 'rem', True), ('ina219', '0x47', 'vbat', 7.6, 0.01, 'rem', True), ('ina219', '0x48', 'ppvar_gt', 7.6, 0.01, 'rem', True), ('ina219', '0x49', 'pp3300_s', 3.3, 0.01, 'rem', True), ('ina219', '0x4a', 'pp3300_dx_wlan', 3.3, 0.01, 'rem', True), ('ina219', '0x4b', 'pp1000_a', 1.0, 0.005, 'rem', True), ('ina219', '0x4c', 'pp3300_dx_edp', 3.3, 0.01, 'rem', True), ('ina219', '0x4d', 'pp3300_dsw_ec', 3.3, 0.01, 'rem', True)] |
"""
Basic Variables
"""
# Create a variable that represents your favorite number, and add a note to remind yourself what this variable represents. Now print it out without re-typing the number.
fave_num = 12
print(fave_num)
# Create another variable that represents your favorite color, and do the same steps as above.
fave_color = 'blue'
print(fave_color)
| """
Basic Variables
"""
fave_num = 12
print(fave_num)
fave_color = 'blue'
print(fave_color) |
#!/usr/bin/env python3
with open("input.txt", "r") as f:
lines = [int(x) for x in f.read().splitlines()]
def part1(lines, preamble = 25):
for i, line in enumerate(lines[preamble:], preamble):
possible = lines[i - preamble : i]
for a in possible:
for b in possible:
if a + b == line:
break
else:
continue
break
else:
return line
def part2(lines, target):
for i, current in enumerate(lines):
sum = 0
for j in range(i + 1, len(lines)):
if sum == target:
group = lines[i : j - 1]
return min(group) + max(group)
if sum > target:
break
sum += lines[j]
j += 1
print(num := part1(lines))
print(part2(lines, num))
| with open('input.txt', 'r') as f:
lines = [int(x) for x in f.read().splitlines()]
def part1(lines, preamble=25):
for (i, line) in enumerate(lines[preamble:], preamble):
possible = lines[i - preamble:i]
for a in possible:
for b in possible:
if a + b == line:
break
else:
continue
break
else:
return line
def part2(lines, target):
for (i, current) in enumerate(lines):
sum = 0
for j in range(i + 1, len(lines)):
if sum == target:
group = lines[i:j - 1]
return min(group) + max(group)
if sum > target:
break
sum += lines[j]
j += 1
print((num := part1(lines)))
print(part2(lines, num)) |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name' : 'Invoicing',
'version' : '1.1',
'summary': 'Send Invoices and Track Payments',
'sequence': 30,
'description': """
Invoicing & Payments
====================
The specific and easy-to-use Invoicing system in Odoo allows you to keep track of your accounting, even when you are not an accountant. It provides an easy way to follow up on your vendors and customers.
You could use this simplified accounting in case you work with an (external) account to keep your books, and you still want to keep track of payments. This module also offers you an easy method of registering payments, without having to encode complete abstracts of account.
""",
'category': 'Accounting',
'website': 'https://www.odoo.com/page/billing',
'images' : ['images/accounts.jpeg','images/bank_statement.jpeg','images/cash_register.jpeg','images/chart_of_accounts.jpeg','images/customer_invoice.jpeg','images/journal_entries.jpeg'],
'depends' : ['base_setup', 'product', 'analytic', 'report', 'web_planner'],
'data': [
'security/account_security.xml',
'security/ir.model.access.csv',
'data/data_account_type.xml',
'data/account_data.xml',
'views/account_menuitem.xml',
'views/account_payment_view.xml',
'wizard/account_reconcile_view.xml',
'wizard/account_unreconcile_view.xml',
'wizard/account_move_reversal_view.xml',
'views/account_view.xml',
'views/account_report.xml',
'wizard/account_invoice_refund_view.xml',
'wizard/account_validate_move_view.xml',
'wizard/account_invoice_state_view.xml',
'wizard/pos_box.xml',
'views/account_end_fy.xml',
'views/account_invoice_view.xml',
'data/invoice_action_data.xml',
'views/partner_view.xml',
'views/product_view.xml',
'views/account_analytic_view.xml',
'views/res_config_view.xml',
'views/account_tip_data.xml',
'views/account.xml',
'views/report_invoice.xml',
'report/account_invoice_report_view.xml',
'report/inherited_layouts.xml',
'views/account_journal_dashboard_view.xml',
'views/report_overdue.xml',
'views/web_planner_data.xml',
'views/report_overdue.xml',
'wizard/account_report_common_view.xml',
'wizard/account_report_print_journal_view.xml',
'views/report_journal.xml',
'wizard/account_report_partner_ledger_view.xml',
'views/report_partnerledger.xml',
'wizard/account_report_general_ledger_view.xml',
'views/report_generalledger.xml',
'wizard/account_report_trial_balance_view.xml',
'views/report_trialbalance.xml',
'views/account_financial_report_data.xml',
'wizard/account_financial_report_view.xml',
'views/report_financial.xml',
'wizard/account_report_aged_partner_balance_view.xml',
'views/report_agedpartnerbalance.xml',
'views/tax_adjustments.xml',
'wizard/wizard_tax_adjustments_view.xml',
],
'demo': [
'demo/account_demo.xml',
],
'qweb': [
"static/src/xml/account_reconciliation.xml",
"static/src/xml/account_payment.xml",
"static/src/xml/account_report_backend.xml",
],
'installable': True,
'application': True,
'auto_install': False,
'post_init_hook': '_auto_install_l10n',
}
| {'name': 'Invoicing', 'version': '1.1', 'summary': 'Send Invoices and Track Payments', 'sequence': 30, 'description': '\nInvoicing & Payments\n====================\nThe specific and easy-to-use Invoicing system in Odoo allows you to keep track of your accounting, even when you are not an accountant. It provides an easy way to follow up on your vendors and customers.\n\nYou could use this simplified accounting in case you work with an (external) account to keep your books, and you still want to keep track of payments. This module also offers you an easy method of registering payments, without having to encode complete abstracts of account.\n ', 'category': 'Accounting', 'website': 'https://www.odoo.com/page/billing', 'images': ['images/accounts.jpeg', 'images/bank_statement.jpeg', 'images/cash_register.jpeg', 'images/chart_of_accounts.jpeg', 'images/customer_invoice.jpeg', 'images/journal_entries.jpeg'], 'depends': ['base_setup', 'product', 'analytic', 'report', 'web_planner'], 'data': ['security/account_security.xml', 'security/ir.model.access.csv', 'data/data_account_type.xml', 'data/account_data.xml', 'views/account_menuitem.xml', 'views/account_payment_view.xml', 'wizard/account_reconcile_view.xml', 'wizard/account_unreconcile_view.xml', 'wizard/account_move_reversal_view.xml', 'views/account_view.xml', 'views/account_report.xml', 'wizard/account_invoice_refund_view.xml', 'wizard/account_validate_move_view.xml', 'wizard/account_invoice_state_view.xml', 'wizard/pos_box.xml', 'views/account_end_fy.xml', 'views/account_invoice_view.xml', 'data/invoice_action_data.xml', 'views/partner_view.xml', 'views/product_view.xml', 'views/account_analytic_view.xml', 'views/res_config_view.xml', 'views/account_tip_data.xml', 'views/account.xml', 'views/report_invoice.xml', 'report/account_invoice_report_view.xml', 'report/inherited_layouts.xml', 'views/account_journal_dashboard_view.xml', 'views/report_overdue.xml', 'views/web_planner_data.xml', 'views/report_overdue.xml', 'wizard/account_report_common_view.xml', 'wizard/account_report_print_journal_view.xml', 'views/report_journal.xml', 'wizard/account_report_partner_ledger_view.xml', 'views/report_partnerledger.xml', 'wizard/account_report_general_ledger_view.xml', 'views/report_generalledger.xml', 'wizard/account_report_trial_balance_view.xml', 'views/report_trialbalance.xml', 'views/account_financial_report_data.xml', 'wizard/account_financial_report_view.xml', 'views/report_financial.xml', 'wizard/account_report_aged_partner_balance_view.xml', 'views/report_agedpartnerbalance.xml', 'views/tax_adjustments.xml', 'wizard/wizard_tax_adjustments_view.xml'], 'demo': ['demo/account_demo.xml'], 'qweb': ['static/src/xml/account_reconciliation.xml', 'static/src/xml/account_payment.xml', 'static/src/xml/account_report_backend.xml'], 'installable': True, 'application': True, 'auto_install': False, 'post_init_hook': '_auto_install_l10n'} |
class HTMLTable:
"""Class to easily generate a ranking table in HTML for WordPress"""
def __init__(self, columns: int):
self.columns = columns
self.header = str()
self.rows = list()
def add_header(self, *cells):
if len(cells) != self.columns:
return
self.header = '<thead><tr>'
for cell in cells:
self.header += f'<th>{cell}</th>'
self.header += '</tr></thead>'
def add_row(self, *cells):
if len(cells) != self.columns:
return
row = str()
if len(self.rows) % 2 != 0:
row += '<tr class="table-row-even">'
else:
row += '<tr class="table-row-odd">'
for cell in cells:
try:
int(cell)
row += f'<td class="data-number">{cell}</td>'
except ValueError:
row += f'<td class="data-text">{cell}</td>'
row += '</tr>'
self.rows.append(row)
def generate(self):
html = '<figure class="wp-block-table tg is-style-stripes"><table>'
if len(self.header) > 0:
html += self.header
if len(self.rows) > 0:
html += '<tbody>'
for row in self.rows:
html += row
html += '</tbody>'
html += '</figure></table>'
return html
| class Htmltable:
"""Class to easily generate a ranking table in HTML for WordPress"""
def __init__(self, columns: int):
self.columns = columns
self.header = str()
self.rows = list()
def add_header(self, *cells):
if len(cells) != self.columns:
return
self.header = '<thead><tr>'
for cell in cells:
self.header += f'<th>{cell}</th>'
self.header += '</tr></thead>'
def add_row(self, *cells):
if len(cells) != self.columns:
return
row = str()
if len(self.rows) % 2 != 0:
row += '<tr class="table-row-even">'
else:
row += '<tr class="table-row-odd">'
for cell in cells:
try:
int(cell)
row += f'<td class="data-number">{cell}</td>'
except ValueError:
row += f'<td class="data-text">{cell}</td>'
row += '</tr>'
self.rows.append(row)
def generate(self):
html = '<figure class="wp-block-table tg is-style-stripes"><table>'
if len(self.header) > 0:
html += self.header
if len(self.rows) > 0:
html += '<tbody>'
for row in self.rows:
html += row
html += '</tbody>'
html += '</figure></table>'
return html |
Cell = DT('Cell', ('vitality', int))
def main():
assert match(Cell(50), ("Cell(n)", lambda n: n + 1)) == 51, "Match"
m = match(Cell(20))
if m('Cell(21)'):
assert False, "Wrong block intlit match"
elif m('Cell(x)'):
assert m.x == 20, "Block intlit binding"
return 0
| cell = dt('Cell', ('vitality', int))
def main():
assert match(cell(50), ('Cell(n)', lambda n: n + 1)) == 51, 'Match'
m = match(cell(20))
if m('Cell(21)'):
assert False, 'Wrong block intlit match'
elif m('Cell(x)'):
assert m.x == 20, 'Block intlit binding'
return 0 |
# Author: Ben Wichser
# Date: 12/13/2019
# Description: Play the breakout game. What's the score after winning? see www.adventofcode.com/2019 (day 13) for more information
class IntCode:
"""
IntCode Computer.
Public Data Members:
code_list -- intcode instruction set
Public Methods:
intcode_run -- runs computer.
"""
def __init__(self, code_list):
"""
Creates IntCode computer. Sets i (index, int) and relative_base to zero. Accepts code_list (instructions, list).
"""
self.code_list = code_list
self.i = 0
self.relative_base = 0
self.code_list[0] = 2
def intcode_run(self, computer_input):
"""
Runs computer. Returns output from code 4 or 'Halt' from code 99
"""
self.computer_input = computer_input
while True:
# reads raw opcode
self.raw_opcode = self.code_list[self.i]
self.i += 1
# does intcode operation direction parsing
(self.opcode, self.raw_parameter_code_list) = self.__intcode_parse(self.raw_opcode)
# Ensure the parameter code list is correct length for the code.
self.parameter_code_list = self.__parameter_code_sizer(
self.opcode, self.raw_parameter_code_list)
# Create actual list of parameters for each opcode operation
self.parameter_list = []
# grabs parameters, as necessary
self.index = 0
while len(self.parameter_list) < len(self.parameter_code_list):
self.parameter_list.append(self.__parameter_tuple_maker(
self.parameter_code_list[self.index], self.code_list, self.i))
self.i += 1
self.index += 1
if self.opcode == 1:
self.__intcode_one(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 2:
self.__intcode_two(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 3:
self.__intcode_three(self.parameter_list, self.code_list,
self.relative_base, self.computer_input)
elif self.opcode == 4:
return self.__intcode_four(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 5:
self.i = self.__intcode_five(self.parameter_list, self.code_list, self.relative_base, self.i)
elif self.opcode == 6:
self.i = self.__intcode_six(self.parameter_list, self.code_list, self.relative_base, self.i)
elif self.opcode == 7:
self.__intcode_seven(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 8:
self.__intcode_eight(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 9:
self.relative_base = self.__intcode_nine(
self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 99:
return self.__intcode_ninetynine(self.parameter_list, self.code_list)
else:
print('and I oop... opcode error')
def __intcode_parse(self, code):
"""Private. Accepts intcode. Parses intcode and returns individual parameters. """
self.code = code
self.actual_code = self.code % 100
self.parameter_piece = self.code - self.actual_code
self.parameter_piece = self.parameter_piece // 100
self.parameter_code_list = []
while self.parameter_piece > 0:
self.parameter_code_list.append(self.parameter_piece % 10)
self.parameter_piece = self.parameter_piece // 10
return (self.actual_code, self.parameter_code_list)
def __parameter_code_sizer(self, opcode, raw_parameter_code_list):
"""Ensures parameter code list is the correct length, according to the particular opcode."""
self.parameter_lengths = {1: 3, 2: 3, 3: 1, 4: 1,
5: 2, 6: 2, 7: 3, 8: 3, 9: 1, 99: 0}
while len(self.raw_parameter_code_list) < self.parameter_lengths[self.opcode]:
self.raw_parameter_code_list.append(0)
return self.raw_parameter_code_list
def __code_list_lengthener(self, code_list, parameter):
"""Ensures that code_list is long enough to accept an item in its parameter-th location"""
while len(self.code_list) < parameter + 1:
self.code_list.append(0)
return self.code_list
def __parameter_tuple_maker(self, parameter_code, code_list, i):
"""
Accepts parameter_code, code_list, relative_base, and i.
Returns parameter_code, parameter tuple for opcode operation.
"""
return (parameter_code, self.code_list[i])
def __parameter_tuple_parser(self, parameter_tuple, code_list, relative_base):
"""
Accepts parameter_tuple, code_list, and relative_base. Returns parameter for use in intcode operation.
"""
if parameter_tuple[0] == 0:
self.__code_list_lengthener(self.code_list, parameter_tuple[1])
return self.code_list[parameter_tuple[1]]
elif parameter_tuple[0] == 1:
return parameter_tuple[1]
elif parameter_tuple[0] == 2:
self.__code_list_lengthener(self.code_list, parameter_tuple[1]+ self.relative_base)
return self.code_list[parameter_tuple[1] + relative_base]
else:
print('And I oop.... parameter_tuple_parser')
def __intcode_one(self, parameter_list, code_list, relative_base):
"""Adds elements in the parameter_list's first two elements. Places sum in parameter_list[2]. Returns True. """
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1][1])
self.code_list[self.parameter_list[-1][1]
] = self.parameter_list[0] + self.parameter_list[1]
elif self.parameter_list[-1][0] == 2:
self.code_list = self.__code_list_lengthener(
self.code_list, self.parameter_list[-1][1]+ self.relative_base)
self.code_list[self.parameter_list[-1][1] +
self.relative_base] = self.parameter_list[0] + self.parameter_list[1]
else:
print("And I oop... intcode_one")
return True
def __intcode_two(self, parameter_list, code_list, relative_base):
"""Multiplies elements in the parameter_list's first two elements. Places product in parameter_list[2]. Returns True. """
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1][1])
self.code_list[self.parameter_list[-1][1]
] = self.parameter_list[0] * self.parameter_list[1]
elif self.parameter_list[-1][0] == 2:
self.code_list = self.__code_list_lengthener(
self.code_list, self.parameter_list[-1][1] + self.relative_base)
self.code_list[self.parameter_list[-1][1] +
self.relative_base] = self.parameter_list[0] * self.parameter_list[1]
else:
print("And I oop...intcode_two")
return True
def __intcode_three(self, parameter_list, code_list, relative_base, computer_input):
""" Accepts input and places it in parameter_list[0] place in code_list. Returns True. """
if self.parameter_list[0][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[0][1])
self.code_list[self.parameter_list[0][1]] = computer_input
elif self.parameter_list[0][0] == 2:
self.code_list = self.__code_list_lengthener(
self.code_list, self.parameter_list[0][1]+ self.relative_base)
self.code_list[self.parameter_list[0][1] + self.relative_base] = computer_input
else:
print("And I oop...intcode_three")
return True
def __intcode_four(self, parameter_list, code_list, relative_base):
""" Returns item in parameter_list[0] place in code_list. """
for i in range(len(self.parameter_list)):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
return self.parameter_list[-1]
def __intcode_five(self, parameter_list, code_list, relative_base, i):
"""If first parameter is non-zero, sets instruction pointer to second parameter. Returns i"""
for j in range(len(self.parameter_list)):
self.parameter_list[j] = self.__parameter_tuple_parser(
self.parameter_list[j], self.code_list, self.relative_base)
if self.parameter_list[0] != 0:
self.i = self.parameter_list[-1]
return self.i
def __intcode_six(self, parameter_list, code_list, relative_base, i):
"""If first parameter is zero, sets instruction pointer to second parameter. Returns i"""
for j in range(len(self.parameter_list)):
self.parameter_list[j] = self.__parameter_tuple_parser(
self.parameter_list[j], self.code_list, self.relative_base)
if self.parameter_list[0] == 0:
self.i = self.parameter_list[-1]
return self.i
def __intcode_seven(self, parameter_list, code_list, relative_base):
"""If first parameter is less than second parameter, stores 1 in third parameter. Else stores 0 in third parameter. Returns True"""
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.parameter_list[-1] = self.parameter_list[-1][1]
elif self.parameter_list[-1][0] == 2:
self.parameter_list[-1] = self.parameter_list[-1][1] + self.relative_base
if self.parameter_list[0] < self.parameter_list[1]:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 1
else:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 0
return True
def __intcode_eight(self, parameter_list, code_list, relative_base):
"""If first parameter is equal to second parameter, stores 1 in third parameter. Else stores 0 in third parameter. Returns True"""
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.parameter_list[-1] = self.parameter_list[-1][1]
elif self.parameter_list[-1][0] == 2:
self.parameter_list[-1] = self.parameter_list[-1][1] + self.relative_base
if self.parameter_list[0] == self.parameter_list[1]:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[parameter_list[-1]] = 1
else:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 0
return True
def __intcode_nine(self, parameter_list, code_list, relative_base):
""" Adjust the relative base by the first parameter. Returns new relative_base"""
for i in range(len(self.parameter_list)):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
self.relative_base += self.parameter_list[0]
return self.relative_base
def __intcode_ninetynine(self, parameter_list, code_list):
"""Returns False, so we can exit loop and script."""
return 'Halt'
class Breakout:
"""
Breakout Game. Requires IntCode Computer.
Public Data Members:
width - width of the game board
height -- height of the game board
Public Methods:
play_game - plays the Breakout Game
print_grid - prints the game board
"""
def __init__(self, width, height):
"""
Initializes the breakout game. Sets the game's width and height according to inputs. Initializes initial locations of _ball_location and _paddle_location, each to (0,0).
"""
self.width = width
self.height = height
self._ball_location = (0,0)
self._paddle_location = (0,0)
self._grid = self.__grid_maker(self.width, self.height)
def play_game(self, computer):
"""
Autoplays the breakout game, using intcode computer object for calculations.
"""
self.computer = computer
instruction_list = []
keep_going = True
while keep_going:
while len(instruction_list) < 3:
self._computer_input = self.__input_generator(self._ball_location, self._paddle_location)
output = self.computer.intcode_run(self._computer_input)
if output == 'Halt':
keep_going = False
else:
instruction_list.append(output)
game_won = self.__win_check(instruction_list)
if game_won == True:
keep_going = False
else:
self._grid, self._ball_location, self._paddle_location = self.__update_game(self._grid, instruction_list)
self.print_grid(self._grid)
instruction_list = []
def print_grid(self, grid):
"""Prints the game grid."""
for row in grid:
for column in row:
if column !='.':
print(column, end='')
print('')
return True
def __input_generator(self, ball_location, paddle_location):
""" Private. Accepts ball and paddle locations. Produces and returns the input for computer (paddle movement)."""
if ball_location[1] > paddle_location[1]:
computer_input = 1
elif ball_location[1] < paddle_location[1]:
computer_input = -1
else:
computer_input = 0
return computer_input
def __grid_maker(self, width, height):
"""Private method. Accepts width, height (ints). Returns width x height grid with '.' as values."""
grid = [['.' for _ in range(width)] for _ in range(height)]
return grid
def __update_game(self, grid, instruction_list):
"""Updates the game board according to rules."""
location_y = instruction_list[1]
location_x = instruction_list[0]
tile = instruction_list[2]
if tile == 0:
grid[location_y][location_x] = ' '
elif tile == 1:
grid[location_y][location_x] = '#'
elif tile == 2:
grid[location_y][location_x] = 'B'
elif tile == 3:
grid[location_y][location_x] = '_'
self._paddle_location = (location_y, location_x)
elif tile == 4:
grid[location_y][location_x] = 'O'
self._ball_location = (location_y, location_x)
else:
print('And I oop...play_game')
return grid, self._ball_location, self._paddle_location
def __win_check(self, instruction_list):
"""Private. Checks to see if the game is won. If so, returns True and prints score. Else returns false."""
if instruction_list[0] == -1 and instruction_list[1] == 0:
number_of_blocks = 0
for k in range(len(self._grid)):
for j in range(len(self._grid[k])):
if self._grid[k][j] == 'B':
number_of_blocks += 1
if number_of_blocks == 0:
print('You won! Final score:', instruction_list[2])
return True
return False
code_list = [1,380,379,385,1008,2531,381039,381,1005,381,12,99,109,2532,1101,0,0,383,1101,0,0,382,21002,382,1,1,21002,383,1,2,21101,0,37,0,1106,0,578,4,382,4,383,204,1,1001,382,1,382,1007,382,43,381,1005,381,22,1001,383,1,383,1007,383,22,381,1005,381,18,1006,385,69,99,104,-1,104,0,4,386,3,384,1007,384,0,381,1005,381,94,107,0,384,381,1005,381,108,1106,0,161,107,1,392,381,1006,381,161,1101,-1,0,384,1105,1,119,1007,392,41,381,1006,381,161,1102,1,1,384,20101,0,392,1,21102,20,1,2,21101,0,0,3,21101,138,0,0,1106,0,549,1,392,384,392,20102,1,392,1,21102,20,1,2,21102,1,3,3,21101,0,161,0,1105,1,549,1101,0,0,384,20001,388,390,1,21001,389,0,2,21102,180,1,0,1105,1,578,1206,1,213,1208,1,2,381,1006,381,205,20001,388,390,1,20101,0,389,2,21101,205,0,0,1106,0,393,1002,390,-1,390,1102,1,1,384,20101,0,388,1,20001,389,391,2,21101,0,228,0,1106,0,578,1206,1,261,1208,1,2,381,1006,381,253,21001,388,0,1,20001,389,391,2,21102,253,1,0,1106,0,393,1002,391,-1,391,1101,0,1,384,1005,384,161,20001,388,390,1,20001,389,391,2,21101,0,279,0,1105,1,578,1206,1,316,1208,1,2,381,1006,381,304,20001,388,390,1,20001,389,391,2,21101,304,0,0,1106,0,393,1002,390,-1,390,1002,391,-1,391,1101,0,1,384,1005,384,161,21002,388,1,1,21002,389,1,2,21101,0,0,3,21102,1,338,0,1106,0,549,1,388,390,388,1,389,391,389,21002,388,1,1,20101,0,389,2,21101,4,0,3,21102,1,365,0,1106,0,549,1007,389,21,381,1005,381,75,104,-1,104,0,104,0,99,0,1,0,0,0,0,0,0,291,19,17,1,1,21,109,3,22101,0,-2,1,21202,-1,1,2,21102,0,1,3,21102,1,414,0,1105,1,549,22102,1,-2,1,22101,0,-1,2,21102,1,429,0,1106,0,601,1202,1,1,435,1,386,0,386,104,-1,104,0,4,386,1001,387,-1,387,1005,387,451,99,109,-3,2106,0,0,109,8,22202,-7,-6,-3,22201,-3,-5,-3,21202,-4,64,-2,2207,-3,-2,381,1005,381,492,21202,-2,-1,-1,22201,-3,-1,-3,2207,-3,-2,381,1006,381,481,21202,-4,8,-2,2207,-3,-2,381,1005,381,518,21202,-2,-1,-1,22201,-3,-1,-3,2207,-3,-2,381,1006,381,507,2207,-3,-4,381,1005,381,540,21202,-4,-1,-1,22201,-3,-1,-3,2207,-3,-4,381,1006,381,529,22101,0,-3,-7,109,-8,2106,0,0,109,4,1202,-2,43,566,201,-3,566,566,101,639,566,566,1202,-1,1,0,204,-3,204,-2,204,-1,109,-4,2106,0,0,109,3,1202,-1,43,593,201,-2,593,593,101,639,593,593,21002,0,1,-2,109,-3,2106,0,0,109,3,22102,22,-2,1,22201,1,-1,1,21102,479,1,2,21101,0,201,3,21101,946,0,4,21102,630,1,0,1105,1,456,21201,1,1585,-2,109,-3,2106,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,0,0,0,2,2,0,2,2,0,0,2,0,2,2,0,2,2,2,2,2,0,1,1,0,2,0,2,2,2,2,2,2,0,2,2,0,2,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,2,2,0,2,0,2,0,0,0,0,0,0,1,1,0,2,2,0,2,0,0,0,2,2,0,2,0,0,0,2,0,0,0,0,2,2,2,0,2,0,0,0,2,0,2,2,0,0,2,0,2,0,2,2,0,1,1,0,0,2,0,2,0,0,2,2,2,2,2,0,2,0,2,2,0,0,0,2,2,0,0,2,2,0,2,2,2,0,0,2,0,2,0,2,0,0,2,0,1,1,0,2,0,2,0,2,2,2,0,0,0,0,0,0,2,0,2,0,0,2,0,2,0,0,2,0,0,0,0,2,2,0,2,2,0,0,2,0,0,0,0,1,1,0,0,0,2,2,2,2,0,2,2,2,2,0,2,0,0,2,2,0,2,2,2,0,0,0,2,2,0,0,2,2,0,0,0,0,2,2,0,0,2,0,1,1,0,0,0,0,0,0,2,2,2,2,2,2,0,0,2,2,0,0,2,2,2,0,0,2,2,2,0,2,0,2,0,0,2,0,2,2,2,0,2,0,0,1,1,0,2,0,0,0,0,2,2,2,0,0,2,0,0,2,0,2,2,2,2,0,2,0,2,0,0,0,0,2,0,2,2,0,2,2,0,2,2,0,2,0,1,1,0,0,2,2,0,2,2,0,2,0,2,0,2,0,2,0,0,0,0,2,2,2,2,0,2,0,2,2,0,2,0,2,2,0,2,2,0,2,2,0,0,1,1,0,0,2,0,0,2,2,2,0,2,0,0,2,2,0,2,2,0,0,0,2,2,0,2,2,2,0,0,2,0,0,0,0,2,2,2,0,0,0,2,0,1,1,0,0,2,2,0,0,2,0,2,2,2,2,0,2,2,2,2,2,2,2,2,2,0,2,2,0,2,2,0,2,0,2,2,0,2,2,0,2,2,2,0,1,1,0,0,0,2,2,2,0,2,0,0,0,0,2,2,2,2,2,2,2,2,0,0,0,2,2,2,2,2,0,0,2,0,0,0,0,2,2,0,2,2,0,1,1,0,2,0,0,2,2,0,2,0,0,0,2,2,2,2,2,2,0,2,2,0,2,0,2,2,0,2,2,0,2,2,2,2,2,0,0,2,0,0,0,0,1,1,0,2,0,0,2,0,2,0,0,2,0,0,2,2,2,2,2,0,2,0,2,2,0,2,2,0,0,2,2,0,0,0,2,2,0,2,2,0,2,2,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,37,59,35,82,55,63,50,72,81,61,59,5,1,69,3,36,79,19,94,73,56,24,20,10,1,25,20,49,14,41,74,10,1,48,97,35,54,11,81,35,36,54,58,49,82,25,96,37,51,26,65,35,51,78,95,58,66,62,83,44,62,53,19,35,90,77,50,38,53,16,24,10,59,72,21,24,91,15,80,80,83,67,27,51,49,31,38,51,10,47,22,68,71,30,19,57,64,6,63,91,63,34,53,95,87,27,83,15,5,2,22,23,34,80,75,27,15,88,73,28,23,4,85,54,68,43,55,31,81,78,16,88,75,85,8,9,27,82,95,34,86,94,31,33,42,94,26,98,73,73,74,89,43,1,55,63,21,93,97,18,57,41,66,83,32,13,67,23,80,22,95,8,68,26,8,76,22,10,53,56,76,11,82,77,83,31,43,49,45,19,72,13,7,21,40,58,94,67,16,84,38,11,62,22,56,5,2,42,2,38,37,83,3,74,9,4,52,91,38,45,31,60,81,52,19,7,54,49,64,73,26,11,38,84,49,79,48,92,48,28,88,71,8,66,86,44,90,21,73,33,15,5,34,34,30,66,29,13,59,30,7,52,59,77,71,4,42,28,73,50,40,77,33,18,66,5,36,49,98,48,29,32,21,10,18,2,79,44,67,19,26,64,27,92,29,3,19,67,73,44,41,49,45,34,61,65,97,56,4,44,85,38,19,43,61,10,97,44,3,93,86,71,36,52,95,36,13,28,53,2,79,66,92,38,8,92,47,40,78,51,67,22,42,76,49,41,23,47,49,87,81,26,11,20,17,11,93,64,78,63,29,80,54,20,62,45,78,38,6,14,14,62,86,10,17,77,60,20,77,42,6,68,28,62,37,44,17,85,16,33,55,85,11,35,2,8,3,88,4,67,16,97,51,40,72,70,45,28,36,47,48,95,60,77,63,1,31,54,52,18,25,46,39,58,86,26,75,48,85,34,56,93,16,98,36,24,61,63,90,32,93,16,53,48,74,73,95,43,81,55,85,29,32,91,34,4,14,3,24,41,44,64,7,78,19,17,75,71,16,22,75,78,89,93,12,90,54,38,61,3,54,61,69,58,17,27,46,75,19,13,46,53,33,87,25,65,67,22,50,90,53,98,11,54,52,57,4,49,92,73,26,70,43,12,7,70,7,58,13,8,27,12,20,86,45,3,98,56,66,58,47,52,87,79,31,37,48,56,46,26,50,75,1,24,96,67,94,11,56,57,7,58,2,21,57,40,64,73,81,13,58,68,45,32,55,13,91,43,59,62,34,28,44,35,68,35,70,1,78,77,69,3,38,11,63,12,56,13,20,82,58,59,22,69,34,82,80,86,15,30,92,39,49,75,27,83,59,89,35,86,19,26,18,50,9,91,82,4,63,57,22,96,54,72,3,76,8,19,24,81,92,76,86,48,70,72,72,75,97,36,95,44,53,40,81,81,33,7,55,58,23,13,24,16,24,67,88,13,32,98,62,71,49,72,52,34,9,61,78,33,72,38,30,35,17,66,35,81,79,62,45,64,11,67,69,49,33,91,74,24,21,36,84,14,75,87,21,57,88,79,70,74,62,4,45,35,76,1,84,74,59,25,3,88,38,34,97,82,31,17,56,95,40,21,77,9,4,1,40,68,60,26,45,55,17,51,7,34,82,27,82,24,72,84,42,72,23,11,48,42,51,22,49,9,80,31,51,39,15,64,44,40,36,67,97,70,39,48,71,75,12,62,11,22,19,80,78,11,58,98,98,69,3,6,14,29,41,10,76,27,5,58,18,22,73,80,34,53,51,87,5,31,13,82,34,10,59,20,10,39,89,12,59,84,31,66,73,7,19,69,86,85,2,34,20,87,28,98,19,50,74,95,69,87,63,63,67,11,47,56,38,9,28,25,46,69,28,63,95,65,83,41,19,78,50,96,77,52,84,37,71,92,51,92,35,97,46,17,71,43,58,54,26,38,9,90,56,9,55,85,52,63,20,8,63,23,24,63,81,22,86,11,90,74,23,19,52,53,22,52,15,85,13,37,52,69,36,10,68,20,54,77,35,15,17,46,88,38,57,69,15,38,60,70,40,17,12,79,33,17,88,90,72,2,62,23,91,41,18,56,22,38,35,37,11,23,381039]
#create computer
computer = IntCode(code_list)
# Create game
height = 25
width = 45
this_game = Breakout(width, height)
this_game.play_game(computer)
| class Intcode:
"""
IntCode Computer.
Public Data Members:
code_list -- intcode instruction set
Public Methods:
intcode_run -- runs computer.
"""
def __init__(self, code_list):
"""
Creates IntCode computer. Sets i (index, int) and relative_base to zero. Accepts code_list (instructions, list).
"""
self.code_list = code_list
self.i = 0
self.relative_base = 0
self.code_list[0] = 2
def intcode_run(self, computer_input):
"""
Runs computer. Returns output from code 4 or 'Halt' from code 99
"""
self.computer_input = computer_input
while True:
self.raw_opcode = self.code_list[self.i]
self.i += 1
(self.opcode, self.raw_parameter_code_list) = self.__intcode_parse(self.raw_opcode)
self.parameter_code_list = self.__parameter_code_sizer(self.opcode, self.raw_parameter_code_list)
self.parameter_list = []
self.index = 0
while len(self.parameter_list) < len(self.parameter_code_list):
self.parameter_list.append(self.__parameter_tuple_maker(self.parameter_code_list[self.index], self.code_list, self.i))
self.i += 1
self.index += 1
if self.opcode == 1:
self.__intcode_one(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 2:
self.__intcode_two(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 3:
self.__intcode_three(self.parameter_list, self.code_list, self.relative_base, self.computer_input)
elif self.opcode == 4:
return self.__intcode_four(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 5:
self.i = self.__intcode_five(self.parameter_list, self.code_list, self.relative_base, self.i)
elif self.opcode == 6:
self.i = self.__intcode_six(self.parameter_list, self.code_list, self.relative_base, self.i)
elif self.opcode == 7:
self.__intcode_seven(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 8:
self.__intcode_eight(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 9:
self.relative_base = self.__intcode_nine(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 99:
return self.__intcode_ninetynine(self.parameter_list, self.code_list)
else:
print('and I oop... opcode error')
def __intcode_parse(self, code):
"""Private. Accepts intcode. Parses intcode and returns individual parameters. """
self.code = code
self.actual_code = self.code % 100
self.parameter_piece = self.code - self.actual_code
self.parameter_piece = self.parameter_piece // 100
self.parameter_code_list = []
while self.parameter_piece > 0:
self.parameter_code_list.append(self.parameter_piece % 10)
self.parameter_piece = self.parameter_piece // 10
return (self.actual_code, self.parameter_code_list)
def __parameter_code_sizer(self, opcode, raw_parameter_code_list):
"""Ensures parameter code list is the correct length, according to the particular opcode."""
self.parameter_lengths = {1: 3, 2: 3, 3: 1, 4: 1, 5: 2, 6: 2, 7: 3, 8: 3, 9: 1, 99: 0}
while len(self.raw_parameter_code_list) < self.parameter_lengths[self.opcode]:
self.raw_parameter_code_list.append(0)
return self.raw_parameter_code_list
def __code_list_lengthener(self, code_list, parameter):
"""Ensures that code_list is long enough to accept an item in its parameter-th location"""
while len(self.code_list) < parameter + 1:
self.code_list.append(0)
return self.code_list
def __parameter_tuple_maker(self, parameter_code, code_list, i):
"""
Accepts parameter_code, code_list, relative_base, and i.
Returns parameter_code, parameter tuple for opcode operation.
"""
return (parameter_code, self.code_list[i])
def __parameter_tuple_parser(self, parameter_tuple, code_list, relative_base):
"""
Accepts parameter_tuple, code_list, and relative_base. Returns parameter for use in intcode operation.
"""
if parameter_tuple[0] == 0:
self.__code_list_lengthener(self.code_list, parameter_tuple[1])
return self.code_list[parameter_tuple[1]]
elif parameter_tuple[0] == 1:
return parameter_tuple[1]
elif parameter_tuple[0] == 2:
self.__code_list_lengthener(self.code_list, parameter_tuple[1] + self.relative_base)
return self.code_list[parameter_tuple[1] + relative_base]
else:
print('And I oop.... parameter_tuple_parser')
def __intcode_one(self, parameter_list, code_list, relative_base):
"""Adds elements in the parameter_list's first two elements. Places sum in parameter_list[2]. Returns True. """
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1][1])
self.code_list[self.parameter_list[-1][1]] = self.parameter_list[0] + self.parameter_list[1]
elif self.parameter_list[-1][0] == 2:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1][1] + self.relative_base)
self.code_list[self.parameter_list[-1][1] + self.relative_base] = self.parameter_list[0] + self.parameter_list[1]
else:
print('And I oop... intcode_one')
return True
def __intcode_two(self, parameter_list, code_list, relative_base):
"""Multiplies elements in the parameter_list's first two elements. Places product in parameter_list[2]. Returns True. """
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1][1])
self.code_list[self.parameter_list[-1][1]] = self.parameter_list[0] * self.parameter_list[1]
elif self.parameter_list[-1][0] == 2:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1][1] + self.relative_base)
self.code_list[self.parameter_list[-1][1] + self.relative_base] = self.parameter_list[0] * self.parameter_list[1]
else:
print('And I oop...intcode_two')
return True
def __intcode_three(self, parameter_list, code_list, relative_base, computer_input):
""" Accepts input and places it in parameter_list[0] place in code_list. Returns True. """
if self.parameter_list[0][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[0][1])
self.code_list[self.parameter_list[0][1]] = computer_input
elif self.parameter_list[0][0] == 2:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[0][1] + self.relative_base)
self.code_list[self.parameter_list[0][1] + self.relative_base] = computer_input
else:
print('And I oop...intcode_three')
return True
def __intcode_four(self, parameter_list, code_list, relative_base):
""" Returns item in parameter_list[0] place in code_list. """
for i in range(len(self.parameter_list)):
self.parameter_list[i] = self.__parameter_tuple_parser(self.parameter_list[i], self.code_list, self.relative_base)
return self.parameter_list[-1]
def __intcode_five(self, parameter_list, code_list, relative_base, i):
"""If first parameter is non-zero, sets instruction pointer to second parameter. Returns i"""
for j in range(len(self.parameter_list)):
self.parameter_list[j] = self.__parameter_tuple_parser(self.parameter_list[j], self.code_list, self.relative_base)
if self.parameter_list[0] != 0:
self.i = self.parameter_list[-1]
return self.i
def __intcode_six(self, parameter_list, code_list, relative_base, i):
"""If first parameter is zero, sets instruction pointer to second parameter. Returns i"""
for j in range(len(self.parameter_list)):
self.parameter_list[j] = self.__parameter_tuple_parser(self.parameter_list[j], self.code_list, self.relative_base)
if self.parameter_list[0] == 0:
self.i = self.parameter_list[-1]
return self.i
def __intcode_seven(self, parameter_list, code_list, relative_base):
"""If first parameter is less than second parameter, stores 1 in third parameter. Else stores 0 in third parameter. Returns True"""
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.parameter_list[-1] = self.parameter_list[-1][1]
elif self.parameter_list[-1][0] == 2:
self.parameter_list[-1] = self.parameter_list[-1][1] + self.relative_base
if self.parameter_list[0] < self.parameter_list[1]:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 1
else:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 0
return True
def __intcode_eight(self, parameter_list, code_list, relative_base):
"""If first parameter is equal to second parameter, stores 1 in third parameter. Else stores 0 in third parameter. Returns True"""
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.parameter_list[-1] = self.parameter_list[-1][1]
elif self.parameter_list[-1][0] == 2:
self.parameter_list[-1] = self.parameter_list[-1][1] + self.relative_base
if self.parameter_list[0] == self.parameter_list[1]:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[parameter_list[-1]] = 1
else:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 0
return True
def __intcode_nine(self, parameter_list, code_list, relative_base):
""" Adjust the relative base by the first parameter. Returns new relative_base"""
for i in range(len(self.parameter_list)):
self.parameter_list[i] = self.__parameter_tuple_parser(self.parameter_list[i], self.code_list, self.relative_base)
self.relative_base += self.parameter_list[0]
return self.relative_base
def __intcode_ninetynine(self, parameter_list, code_list):
"""Returns False, so we can exit loop and script."""
return 'Halt'
class Breakout:
"""
Breakout Game. Requires IntCode Computer.
Public Data Members:
width - width of the game board
height -- height of the game board
Public Methods:
play_game - plays the Breakout Game
print_grid - prints the game board
"""
def __init__(self, width, height):
"""
Initializes the breakout game. Sets the game's width and height according to inputs. Initializes initial locations of _ball_location and _paddle_location, each to (0,0).
"""
self.width = width
self.height = height
self._ball_location = (0, 0)
self._paddle_location = (0, 0)
self._grid = self.__grid_maker(self.width, self.height)
def play_game(self, computer):
"""
Autoplays the breakout game, using intcode computer object for calculations.
"""
self.computer = computer
instruction_list = []
keep_going = True
while keep_going:
while len(instruction_list) < 3:
self._computer_input = self.__input_generator(self._ball_location, self._paddle_location)
output = self.computer.intcode_run(self._computer_input)
if output == 'Halt':
keep_going = False
else:
instruction_list.append(output)
game_won = self.__win_check(instruction_list)
if game_won == True:
keep_going = False
else:
(self._grid, self._ball_location, self._paddle_location) = self.__update_game(self._grid, instruction_list)
self.print_grid(self._grid)
instruction_list = []
def print_grid(self, grid):
"""Prints the game grid."""
for row in grid:
for column in row:
if column != '.':
print(column, end='')
print('')
return True
def __input_generator(self, ball_location, paddle_location):
""" Private. Accepts ball and paddle locations. Produces and returns the input for computer (paddle movement)."""
if ball_location[1] > paddle_location[1]:
computer_input = 1
elif ball_location[1] < paddle_location[1]:
computer_input = -1
else:
computer_input = 0
return computer_input
def __grid_maker(self, width, height):
"""Private method. Accepts width, height (ints). Returns width x height grid with '.' as values."""
grid = [['.' for _ in range(width)] for _ in range(height)]
return grid
def __update_game(self, grid, instruction_list):
"""Updates the game board according to rules."""
location_y = instruction_list[1]
location_x = instruction_list[0]
tile = instruction_list[2]
if tile == 0:
grid[location_y][location_x] = ' '
elif tile == 1:
grid[location_y][location_x] = '#'
elif tile == 2:
grid[location_y][location_x] = 'B'
elif tile == 3:
grid[location_y][location_x] = '_'
self._paddle_location = (location_y, location_x)
elif tile == 4:
grid[location_y][location_x] = 'O'
self._ball_location = (location_y, location_x)
else:
print('And I oop...play_game')
return (grid, self._ball_location, self._paddle_location)
def __win_check(self, instruction_list):
"""Private. Checks to see if the game is won. If so, returns True and prints score. Else returns false."""
if instruction_list[0] == -1 and instruction_list[1] == 0:
number_of_blocks = 0
for k in range(len(self._grid)):
for j in range(len(self._grid[k])):
if self._grid[k][j] == 'B':
number_of_blocks += 1
if number_of_blocks == 0:
print('You won! Final score:', instruction_list[2])
return True
return False
code_list = [1, 380, 379, 385, 1008, 2531, 381039, 381, 1005, 381, 12, 99, 109, 2532, 1101, 0, 0, 383, 1101, 0, 0, 382, 21002, 382, 1, 1, 21002, 383, 1, 2, 21101, 0, 37, 0, 1106, 0, 578, 4, 382, 4, 383, 204, 1, 1001, 382, 1, 382, 1007, 382, 43, 381, 1005, 381, 22, 1001, 383, 1, 383, 1007, 383, 22, 381, 1005, 381, 18, 1006, 385, 69, 99, 104, -1, 104, 0, 4, 386, 3, 384, 1007, 384, 0, 381, 1005, 381, 94, 107, 0, 384, 381, 1005, 381, 108, 1106, 0, 161, 107, 1, 392, 381, 1006, 381, 161, 1101, -1, 0, 384, 1105, 1, 119, 1007, 392, 41, 381, 1006, 381, 161, 1102, 1, 1, 384, 20101, 0, 392, 1, 21102, 20, 1, 2, 21101, 0, 0, 3, 21101, 138, 0, 0, 1106, 0, 549, 1, 392, 384, 392, 20102, 1, 392, 1, 21102, 20, 1, 2, 21102, 1, 3, 3, 21101, 0, 161, 0, 1105, 1, 549, 1101, 0, 0, 384, 20001, 388, 390, 1, 21001, 389, 0, 2, 21102, 180, 1, 0, 1105, 1, 578, 1206, 1, 213, 1208, 1, 2, 381, 1006, 381, 205, 20001, 388, 390, 1, 20101, 0, 389, 2, 21101, 205, 0, 0, 1106, 0, 393, 1002, 390, -1, 390, 1102, 1, 1, 384, 20101, 0, 388, 1, 20001, 389, 391, 2, 21101, 0, 228, 0, 1106, 0, 578, 1206, 1, 261, 1208, 1, 2, 381, 1006, 381, 253, 21001, 388, 0, 1, 20001, 389, 391, 2, 21102, 253, 1, 0, 1106, 0, 393, 1002, 391, -1, 391, 1101, 0, 1, 384, 1005, 384, 161, 20001, 388, 390, 1, 20001, 389, 391, 2, 21101, 0, 279, 0, 1105, 1, 578, 1206, 1, 316, 1208, 1, 2, 381, 1006, 381, 304, 20001, 388, 390, 1, 20001, 389, 391, 2, 21101, 304, 0, 0, 1106, 0, 393, 1002, 390, -1, 390, 1002, 391, -1, 391, 1101, 0, 1, 384, 1005, 384, 161, 21002, 388, 1, 1, 21002, 389, 1, 2, 21101, 0, 0, 3, 21102, 1, 338, 0, 1106, 0, 549, 1, 388, 390, 388, 1, 389, 391, 389, 21002, 388, 1, 1, 20101, 0, 389, 2, 21101, 4, 0, 3, 21102, 1, 365, 0, 1106, 0, 549, 1007, 389, 21, 381, 1005, 381, 75, 104, -1, 104, 0, 104, 0, 99, 0, 1, 0, 0, 0, 0, 0, 0, 291, 19, 17, 1, 1, 21, 109, 3, 22101, 0, -2, 1, 21202, -1, 1, 2, 21102, 0, 1, 3, 21102, 1, 414, 0, 1105, 1, 549, 22102, 1, -2, 1, 22101, 0, -1, 2, 21102, 1, 429, 0, 1106, 0, 601, 1202, 1, 1, 435, 1, 386, 0, 386, 104, -1, 104, 0, 4, 386, 1001, 387, -1, 387, 1005, 387, 451, 99, 109, -3, 2106, 0, 0, 109, 8, 22202, -7, -6, -3, 22201, -3, -5, -3, 21202, -4, 64, -2, 2207, -3, -2, 381, 1005, 381, 492, 21202, -2, -1, -1, 22201, -3, -1, -3, 2207, -3, -2, 381, 1006, 381, 481, 21202, -4, 8, -2, 2207, -3, -2, 381, 1005, 381, 518, 21202, -2, -1, -1, 22201, -3, -1, -3, 2207, -3, -2, 381, 1006, 381, 507, 2207, -3, -4, 381, 1005, 381, 540, 21202, -4, -1, -1, 22201, -3, -1, -3, 2207, -3, -4, 381, 1006, 381, 529, 22101, 0, -3, -7, 109, -8, 2106, 0, 0, 109, 4, 1202, -2, 43, 566, 201, -3, 566, 566, 101, 639, 566, 566, 1202, -1, 1, 0, 204, -3, 204, -2, 204, -1, 109, -4, 2106, 0, 0, 109, 3, 1202, -1, 43, 593, 201, -2, 593, 593, 101, 639, 593, 593, 21002, 0, 1, -2, 109, -3, 2106, 0, 0, 109, 3, 22102, 22, -2, 1, 22201, 1, -1, 1, 21102, 479, 1, 2, 21101, 0, 201, 3, 21101, 946, 0, 4, 21102, 630, 1, 0, 1105, 1, 456, 21201, 1, 1585, -2, 109, -3, 2106, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 2, 2, 0, 2, 0, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 0, 2, 2, 0, 0, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 1, 1, 0, 2, 0, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 1, 1, 0, 2, 2, 0, 2, 0, 0, 0, 2, 2, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 2, 2, 2, 0, 2, 0, 0, 0, 2, 0, 2, 2, 0, 0, 2, 0, 2, 0, 2, 2, 0, 1, 1, 0, 0, 2, 0, 2, 0, 0, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, 0, 0, 2, 2, 0, 2, 2, 2, 0, 0, 2, 0, 2, 0, 2, 0, 0, 2, 0, 1, 1, 0, 2, 0, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 2, 0, 2, 0, 0, 2, 0, 0, 0, 0, 2, 2, 0, 2, 2, 0, 0, 2, 0, 0, 0, 0, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 2, 0, 0, 2, 2, 0, 2, 2, 2, 0, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 0, 0, 2, 2, 0, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 2, 0, 0, 2, 2, 2, 0, 2, 0, 2, 0, 0, 2, 0, 2, 2, 2, 0, 2, 0, 0, 1, 1, 0, 2, 0, 0, 0, 0, 2, 2, 2, 0, 0, 2, 0, 0, 2, 0, 2, 2, 2, 2, 0, 2, 0, 2, 0, 0, 0, 0, 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 0, 2, 0, 1, 1, 0, 0, 2, 2, 0, 2, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 0, 2, 2, 0, 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 0, 0, 1, 1, 0, 0, 2, 0, 0, 2, 2, 2, 0, 2, 0, 0, 2, 2, 0, 2, 2, 0, 0, 0, 2, 2, 0, 2, 2, 2, 0, 0, 2, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 2, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 0, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 2, 0, 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 2, 0, 1, 1, 0, 0, 0, 2, 2, 2, 0, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 0, 0, 2, 0, 0, 0, 0, 2, 2, 0, 2, 2, 0, 1, 1, 0, 2, 0, 0, 2, 2, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 2, 0, 0, 0, 0, 1, 1, 0, 2, 0, 0, 2, 0, 2, 0, 0, 2, 0, 0, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 0, 2, 2, 0, 0, 2, 2, 0, 0, 0, 2, 2, 0, 2, 2, 0, 2, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 37, 59, 35, 82, 55, 63, 50, 72, 81, 61, 59, 5, 1, 69, 3, 36, 79, 19, 94, 73, 56, 24, 20, 10, 1, 25, 20, 49, 14, 41, 74, 10, 1, 48, 97, 35, 54, 11, 81, 35, 36, 54, 58, 49, 82, 25, 96, 37, 51, 26, 65, 35, 51, 78, 95, 58, 66, 62, 83, 44, 62, 53, 19, 35, 90, 77, 50, 38, 53, 16, 24, 10, 59, 72, 21, 24, 91, 15, 80, 80, 83, 67, 27, 51, 49, 31, 38, 51, 10, 47, 22, 68, 71, 30, 19, 57, 64, 6, 63, 91, 63, 34, 53, 95, 87, 27, 83, 15, 5, 2, 22, 23, 34, 80, 75, 27, 15, 88, 73, 28, 23, 4, 85, 54, 68, 43, 55, 31, 81, 78, 16, 88, 75, 85, 8, 9, 27, 82, 95, 34, 86, 94, 31, 33, 42, 94, 26, 98, 73, 73, 74, 89, 43, 1, 55, 63, 21, 93, 97, 18, 57, 41, 66, 83, 32, 13, 67, 23, 80, 22, 95, 8, 68, 26, 8, 76, 22, 10, 53, 56, 76, 11, 82, 77, 83, 31, 43, 49, 45, 19, 72, 13, 7, 21, 40, 58, 94, 67, 16, 84, 38, 11, 62, 22, 56, 5, 2, 42, 2, 38, 37, 83, 3, 74, 9, 4, 52, 91, 38, 45, 31, 60, 81, 52, 19, 7, 54, 49, 64, 73, 26, 11, 38, 84, 49, 79, 48, 92, 48, 28, 88, 71, 8, 66, 86, 44, 90, 21, 73, 33, 15, 5, 34, 34, 30, 66, 29, 13, 59, 30, 7, 52, 59, 77, 71, 4, 42, 28, 73, 50, 40, 77, 33, 18, 66, 5, 36, 49, 98, 48, 29, 32, 21, 10, 18, 2, 79, 44, 67, 19, 26, 64, 27, 92, 29, 3, 19, 67, 73, 44, 41, 49, 45, 34, 61, 65, 97, 56, 4, 44, 85, 38, 19, 43, 61, 10, 97, 44, 3, 93, 86, 71, 36, 52, 95, 36, 13, 28, 53, 2, 79, 66, 92, 38, 8, 92, 47, 40, 78, 51, 67, 22, 42, 76, 49, 41, 23, 47, 49, 87, 81, 26, 11, 20, 17, 11, 93, 64, 78, 63, 29, 80, 54, 20, 62, 45, 78, 38, 6, 14, 14, 62, 86, 10, 17, 77, 60, 20, 77, 42, 6, 68, 28, 62, 37, 44, 17, 85, 16, 33, 55, 85, 11, 35, 2, 8, 3, 88, 4, 67, 16, 97, 51, 40, 72, 70, 45, 28, 36, 47, 48, 95, 60, 77, 63, 1, 31, 54, 52, 18, 25, 46, 39, 58, 86, 26, 75, 48, 85, 34, 56, 93, 16, 98, 36, 24, 61, 63, 90, 32, 93, 16, 53, 48, 74, 73, 95, 43, 81, 55, 85, 29, 32, 91, 34, 4, 14, 3, 24, 41, 44, 64, 7, 78, 19, 17, 75, 71, 16, 22, 75, 78, 89, 93, 12, 90, 54, 38, 61, 3, 54, 61, 69, 58, 17, 27, 46, 75, 19, 13, 46, 53, 33, 87, 25, 65, 67, 22, 50, 90, 53, 98, 11, 54, 52, 57, 4, 49, 92, 73, 26, 70, 43, 12, 7, 70, 7, 58, 13, 8, 27, 12, 20, 86, 45, 3, 98, 56, 66, 58, 47, 52, 87, 79, 31, 37, 48, 56, 46, 26, 50, 75, 1, 24, 96, 67, 94, 11, 56, 57, 7, 58, 2, 21, 57, 40, 64, 73, 81, 13, 58, 68, 45, 32, 55, 13, 91, 43, 59, 62, 34, 28, 44, 35, 68, 35, 70, 1, 78, 77, 69, 3, 38, 11, 63, 12, 56, 13, 20, 82, 58, 59, 22, 69, 34, 82, 80, 86, 15, 30, 92, 39, 49, 75, 27, 83, 59, 89, 35, 86, 19, 26, 18, 50, 9, 91, 82, 4, 63, 57, 22, 96, 54, 72, 3, 76, 8, 19, 24, 81, 92, 76, 86, 48, 70, 72, 72, 75, 97, 36, 95, 44, 53, 40, 81, 81, 33, 7, 55, 58, 23, 13, 24, 16, 24, 67, 88, 13, 32, 98, 62, 71, 49, 72, 52, 34, 9, 61, 78, 33, 72, 38, 30, 35, 17, 66, 35, 81, 79, 62, 45, 64, 11, 67, 69, 49, 33, 91, 74, 24, 21, 36, 84, 14, 75, 87, 21, 57, 88, 79, 70, 74, 62, 4, 45, 35, 76, 1, 84, 74, 59, 25, 3, 88, 38, 34, 97, 82, 31, 17, 56, 95, 40, 21, 77, 9, 4, 1, 40, 68, 60, 26, 45, 55, 17, 51, 7, 34, 82, 27, 82, 24, 72, 84, 42, 72, 23, 11, 48, 42, 51, 22, 49, 9, 80, 31, 51, 39, 15, 64, 44, 40, 36, 67, 97, 70, 39, 48, 71, 75, 12, 62, 11, 22, 19, 80, 78, 11, 58, 98, 98, 69, 3, 6, 14, 29, 41, 10, 76, 27, 5, 58, 18, 22, 73, 80, 34, 53, 51, 87, 5, 31, 13, 82, 34, 10, 59, 20, 10, 39, 89, 12, 59, 84, 31, 66, 73, 7, 19, 69, 86, 85, 2, 34, 20, 87, 28, 98, 19, 50, 74, 95, 69, 87, 63, 63, 67, 11, 47, 56, 38, 9, 28, 25, 46, 69, 28, 63, 95, 65, 83, 41, 19, 78, 50, 96, 77, 52, 84, 37, 71, 92, 51, 92, 35, 97, 46, 17, 71, 43, 58, 54, 26, 38, 9, 90, 56, 9, 55, 85, 52, 63, 20, 8, 63, 23, 24, 63, 81, 22, 86, 11, 90, 74, 23, 19, 52, 53, 22, 52, 15, 85, 13, 37, 52, 69, 36, 10, 68, 20, 54, 77, 35, 15, 17, 46, 88, 38, 57, 69, 15, 38, 60, 70, 40, 17, 12, 79, 33, 17, 88, 90, 72, 2, 62, 23, 91, 41, 18, 56, 22, 38, 35, 37, 11, 23, 381039]
computer = int_code(code_list)
height = 25
width = 45
this_game = breakout(width, height)
this_game.play_game(computer) |
#!/usr/bin/env python3
mat_mul = __import__('8-ridin_bareback').mat_mul
mat1 = [[1, 2],
[3, 4],
[5, 6]]
mat2 = [[1, 2, 3, 4],
[5, 6, 7, 8]]
print(mat_mul(mat1, mat2))
| mat_mul = __import__('8-ridin_bareback').mat_mul
mat1 = [[1, 2], [3, 4], [5, 6]]
mat2 = [[1, 2, 3, 4], [5, 6, 7, 8]]
print(mat_mul(mat1, mat2)) |
OK = 0
ERROR = 1
INVALID_ARGUMENT = 2
INTERNAL_ERROR = 3
REQUIRE_LANG = 4
REQUIRE_CAPTCHA = 5
CAPTCHA_ERROR = 6
VALIDATE_CODE_ERROR = 7
PROTECT_OPERATE_ERROR = 8
PROTECT_OPERATE_REQUIRED = 9
REQUIRE_NUMBER = 10
IMAGE_FORMAT_ERROR = 11
FILE_FORMAT_ERROR = 12
IMAGE_TOO_BIG = 13
CANCEL_FAILED = 14
EDIT_FAILED = 15
ADD_FAILED = 16
CAN_NOT_CANCEL = 17
STATUS_PASS = 18
DELETE_ERROR = 19
STATUS_FINISH = 20
STATUS_CREATED = 21
STATUS_NOT_PASS = 22
IP_NOT_ALLOW = 23
ACCESS_ID_NOT_EXIST = 24
SIGNATURE_ERROR = 25
STATUS_PROCESSING = 26
TOO_MANY_REQUESTS = 27
CAPTCHA_WAS_USED = 28
SMS_REQUEST_TOO_MANY = 29
CAS_ERROR = 30
APP_UPDATE_CONFIG_EXISTS = 31
APP_VERSION_LESS = 32
APP_UPDATE_LOG_REPEAT = 33
INVALID_APP_CLIENT_VERSION = 34
MESSAGES = {
# 0-99 common error
0: 'OK',
1: 'Error',
2: 'Invalid argument',
3: 'Internal error',
4: 'The header is missing a accept-language',
5: 'Captcha is missing',
6: 'Captcha error',
7: 'Verification code error',
8: 'Protect operate error',
9: 'Protect operate is required.',
10: 'Number is required.',
11: 'Only supports upload png/jpg/jpeg/bmp/gif image format.',
12: 'Only supports upload .xls file format.',
13: 'Only supports upload 6M.',
14: 'Cancel failed',
15: 'Edit failed',
16: 'Add failed',
17: 'Can not cancel',
18: 'Status pass',
19: 'Delete error',
20: 'Status finish',
21: 'Status created',
22: 'Status not pass',
23: 'IP not allow',
24: 'Access id not exist',
25: 'Signature error',
26: 'Status processing',
27: 'Too many requests',
28: 'Captcha was used',
29: 'Sms request too many',
30: 'Cas api error',
31: 'App update config exists',
32: 'App version less than current',
33: 'App update log repeat',
34: 'Invalid app1 client version',
} | ok = 0
error = 1
invalid_argument = 2
internal_error = 3
require_lang = 4
require_captcha = 5
captcha_error = 6
validate_code_error = 7
protect_operate_error = 8
protect_operate_required = 9
require_number = 10
image_format_error = 11
file_format_error = 12
image_too_big = 13
cancel_failed = 14
edit_failed = 15
add_failed = 16
can_not_cancel = 17
status_pass = 18
delete_error = 19
status_finish = 20
status_created = 21
status_not_pass = 22
ip_not_allow = 23
access_id_not_exist = 24
signature_error = 25
status_processing = 26
too_many_requests = 27
captcha_was_used = 28
sms_request_too_many = 29
cas_error = 30
app_update_config_exists = 31
app_version_less = 32
app_update_log_repeat = 33
invalid_app_client_version = 34
messages = {0: 'OK', 1: 'Error', 2: 'Invalid argument', 3: 'Internal error', 4: 'The header is missing a accept-language', 5: 'Captcha is missing', 6: 'Captcha error', 7: 'Verification code error', 8: 'Protect operate error', 9: 'Protect operate is required.', 10: 'Number is required.', 11: 'Only supports upload png/jpg/jpeg/bmp/gif image format.', 12: 'Only supports upload .xls file format.', 13: 'Only supports upload 6M.', 14: 'Cancel failed', 15: 'Edit failed', 16: 'Add failed', 17: 'Can not cancel', 18: 'Status pass', 19: 'Delete error', 20: 'Status finish', 21: 'Status created', 22: 'Status not pass', 23: 'IP not allow', 24: 'Access id not exist', 25: 'Signature error', 26: 'Status processing', 27: 'Too many requests', 28: 'Captcha was used', 29: 'Sms request too many', 30: 'Cas api error', 31: 'App update config exists', 32: 'App version less than current', 33: 'App update log repeat', 34: 'Invalid app1 client version'} |
class Computer:
__IMAGES = [
r'''
.----.
.---------. | == |
|.-"""""-.| |----|
|| || | == |
|| || |----|
|'-.....-'| |::::|
`"")---(""` |___.|
/:::::::::::\" _ "
/:::=======:::\`\`\
`"""""""""""""` '-'
''',
r'''
.----.
.---------. | == |
|.-"""""-.| |----|
|| * * || | == |
|| \---/ || |----|
|'-.....-'| |::::|
`"")---(""` |___.|
/:::::::::::\" _ "
/:::=======:::\`\`\
`"""""""""""""` '-'
''',
]
def __init__(
self,
is_turned_on=True,
keyboard='Redragon Karura',
mouse='Common Genius',
monitor='Samsung S19C300',
speakers='Common Genius',
case='Sentey 199',
cpu='Amd Bulldozer FX 6300'
):
self.__is_turned_on = is_turned_on
self.__keyboard = keyboard
self.__mouse = mouse
self.__monitor = monitor
self.__speakers = speakers
self.__case = case
self.__cpu = cpu
def on(self):
self.__is_turned_on = True
def off(self):
self.__is_turned_on = False
def show(self):
if self.__is_turned_on:
print(self.__IMAGES[1])
else:
print(self.__IMAGES[0])
# Getters and Setters
def get_keyboard(self):
return self.__keyboard
def get_mouse(self):
return self.__mouse
def get_monitor(self):
return self.__monitor
def get_speakers(self):
return self.__speakers
def get_case(self):
return self.__case
def get_cpu(self):
return self.__keyboard
def set_keyboard(self, keyboard):
self.__keyboard = keyboard
def set_mouse(self, mouse):
self.__mouse = mouse
def set_monitor(self, monitor):
self.__monitor = monitor
def set_speakers(self, speakers):
self.__speakers = speakers
def set_case(self, case):
self.__case = case
def set_cpu(self, cpu):
self.__cpu = cpu
def run():
pc_nasa = Computer()
if __name__ == '__main__':
run()
| class Computer:
__images = ['\n .----.\n .---------. | == |\n |.-"""""-.| |----|\n || || | == |\n || || |----|\n |\'-.....-\'| |::::|\n `"")---(""` |___.|\n /:::::::::::\\" _ "\n /:::=======:::\\`\\`\\\n `"""""""""""""` \'-\'\n ', '\n .----.\n .---------. | == |\n |.-"""""-.| |----|\n || * * || | == |\n || \\---/ || |----|\n |\'-.....-\'| |::::|\n `"")---(""` |___.|\n /:::::::::::\\" _ "\n /:::=======:::\\`\\`\\\n `"""""""""""""` \'-\'\n ']
def __init__(self, is_turned_on=True, keyboard='Redragon Karura', mouse='Common Genius', monitor='Samsung S19C300', speakers='Common Genius', case='Sentey 199', cpu='Amd Bulldozer FX 6300'):
self.__is_turned_on = is_turned_on
self.__keyboard = keyboard
self.__mouse = mouse
self.__monitor = monitor
self.__speakers = speakers
self.__case = case
self.__cpu = cpu
def on(self):
self.__is_turned_on = True
def off(self):
self.__is_turned_on = False
def show(self):
if self.__is_turned_on:
print(self.__IMAGES[1])
else:
print(self.__IMAGES[0])
def get_keyboard(self):
return self.__keyboard
def get_mouse(self):
return self.__mouse
def get_monitor(self):
return self.__monitor
def get_speakers(self):
return self.__speakers
def get_case(self):
return self.__case
def get_cpu(self):
return self.__keyboard
def set_keyboard(self, keyboard):
self.__keyboard = keyboard
def set_mouse(self, mouse):
self.__mouse = mouse
def set_monitor(self, monitor):
self.__monitor = monitor
def set_speakers(self, speakers):
self.__speakers = speakers
def set_case(self, case):
self.__case = case
def set_cpu(self, cpu):
self.__cpu = cpu
def run():
pc_nasa = computer()
if __name__ == '__main__':
run() |
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
def my_startswith(haystack: str, needle: str, start: int):
if len(needle) + start > len(haystack):
return False
for i in range(len(needle)):
if haystack[start + i] != needle[i]:
return False
return True
if needle == '':
return 0
for i in range(len(haystack) - len(needle) + 1):
if my_startswith(haystack, needle, i):
return i
return -1
| class Solution:
def str_str(self, haystack: str, needle: str) -> int:
def my_startswith(haystack: str, needle: str, start: int):
if len(needle) + start > len(haystack):
return False
for i in range(len(needle)):
if haystack[start + i] != needle[i]:
return False
return True
if needle == '':
return 0
for i in range(len(haystack) - len(needle) + 1):
if my_startswith(haystack, needle, i):
return i
return -1 |
# -*- coding: utf-8 -*-
{
'name': "eJob Recruitment",
'sequence': 1,
'summary': """
A job recruitment module.""",
'description': """
A job recruitment module
""",
'author': "Kamrul",
'website': "http://www.yourcompany.com",
'category': 'Services',
'version': '0.1',
'license': 'LGPL-3',
'website': "http://www.yourcompany.com",
'depends': ['base', 'mail', 'hr', 'website'],
'data': [
'security/security.xml',
'security/ir.model.access.csv',
'data/application_sequence.xml',
'views/all_munu_items.xml',
'views/job_position_views.xml',
'views/job_applicant_views.xml',
'views/recruit_stage_views.xml',
'views/tags_views.xml',
'views/department_views.xml',
'views/employee_views.xml',
'views/website_view_form.xml',
'views/website_job_view.xml',
'reports/applicant_report.xml',
],
'demo': [
# 'demo/demo.xml',
],
'installable': True,
'application': True,
'auto_install': False,
}
| {'name': 'eJob Recruitment', 'sequence': 1, 'summary': '\n A job recruitment module.', 'description': '\n A job recruitment module\n ', 'author': 'Kamrul', 'website': 'http://www.yourcompany.com', 'category': 'Services', 'version': '0.1', 'license': 'LGPL-3', 'website': 'http://www.yourcompany.com', 'depends': ['base', 'mail', 'hr', 'website'], 'data': ['security/security.xml', 'security/ir.model.access.csv', 'data/application_sequence.xml', 'views/all_munu_items.xml', 'views/job_position_views.xml', 'views/job_applicant_views.xml', 'views/recruit_stage_views.xml', 'views/tags_views.xml', 'views/department_views.xml', 'views/employee_views.xml', 'views/website_view_form.xml', 'views/website_job_view.xml', 'reports/applicant_report.xml'], 'demo': [], 'installable': True, 'application': True, 'auto_install': False} |
"""
Finds the maximum path sum in a given triangle of numbers
"""
def max_path_sum_in_triangle(triangle):
"""
Finds the maximum sum path in a triangle(tree) and returns it
:param triangle:
:return: maximum sum path in the given tree
:rtype: int
"""
length = len(triangle)
for _ in range(length - 1):
a = triangle[-1]
b = triangle[-2]
for y in range(len(b)):
b[y] += max(a[y], a[y + 1])
triangle.pop(-1)
triangle[-1] = b
return triangle[0][0]
if __name__ == "__main__":
triangle_1 = [
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
]
print(f"Maximum path sum in {triangle_1} is {max_path_sum_in_triangle(triangle_1)}")
with open("triangle.txt", "r") as numbers:
triangle_2 = []
for line in numbers:
k = [int(x) for x in line.split(" ")]
triangle_2.append(k)
print(f"Maximum path sum in {triangle_2} is {max_path_sum_in_triangle(triangle_2)}")
| """
Finds the maximum path sum in a given triangle of numbers
"""
def max_path_sum_in_triangle(triangle):
"""
Finds the maximum sum path in a triangle(tree) and returns it
:param triangle:
:return: maximum sum path in the given tree
:rtype: int
"""
length = len(triangle)
for _ in range(length - 1):
a = triangle[-1]
b = triangle[-2]
for y in range(len(b)):
b[y] += max(a[y], a[y + 1])
triangle.pop(-1)
triangle[-1] = b
return triangle[0][0]
if __name__ == '__main__':
triangle_1 = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]]
print(f'Maximum path sum in {triangle_1} is {max_path_sum_in_triangle(triangle_1)}')
with open('triangle.txt', 'r') as numbers:
triangle_2 = []
for line in numbers:
k = [int(x) for x in line.split(' ')]
triangle_2.append(k)
print(f'Maximum path sum in {triangle_2} is {max_path_sum_in_triangle(triangle_2)}') |
#
# PySNMP MIB module ELTEX-MES-COPY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-COPY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:01:07 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, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint")
eltMesCopy, = mibBuilder.importSymbols("ELTEX-MES", "eltMesCopy")
InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress")
RlCopyLocationType, = mibBuilder.importSymbols("RADLAN-COPY-MIB", "RlCopyLocationType")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
TimeTicks, Bits, Integer32, NotificationType, ObjectIdentity, Gauge32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Unsigned32, IpAddress, iso, ModuleIdentity, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Bits", "Integer32", "NotificationType", "ObjectIdentity", "Gauge32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Unsigned32", "IpAddress", "iso", "ModuleIdentity", "Counter64")
RowStatus, DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TruthValue", "TextualConvention")
eltCopyAutoBackupEnable = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 1), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupEnable.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupEnable.setDescription('Enabling on automatic backup configuration.')
eltCopyAutoBackupTimeout = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 2), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupTimeout.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupTimeout.setDescription(' This MIB should be used in order to change the time-interval of automatic copy of running-config to external server. The value should be the number of minutes for the interval of time from the backup.')
eltCopyAutoBackupFilePath = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 3), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupFilePath.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupFilePath.setDescription('The name of the destination file.')
eltCopyAutoBackupServerAddress = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupServerAddress.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupServerAddress.setDescription('The Inet address of the destination remote host')
eltCopyAutoBackupOnWrite = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 5), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupOnWrite.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupOnWrite.setDescription('Performing automatic backups every time you write configuration in memory.')
class EltCopyUserBackupStatus(TextualConvention, Integer32):
description = 'Starting backup manually.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("starting", 1), ("stopped", 2))
eltCopyUserBackupStart = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 6), EltCopyUserBackupStatus().clone('stopped')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyUserBackupStart.setStatus('current')
if mibBuilder.loadTexts: eltCopyUserBackupStart.setDescription('Starting backup manually.')
eltCopyBackupHistoryEnable = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 7), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryEnable.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryEnable.setDescription('Performing automatic backups every time you write configuration in memory.')
eltCopyBackupHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8), )
if mibBuilder.loadTexts: eltCopyBackupHistoryTable.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryTable.setDescription('A DHCP interface configuration table.')
eltCopyBackupHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1), ).setIndexNames((0, "ELTEX-MES-COPY-MIB", "eltCopyBackupHistoryIndex"))
if mibBuilder.loadTexts: eltCopyBackupHistoryEntry.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryEntry.setDescription('A DHCP interface configuration entry.')
eltCopyBackupHistoryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 1), Integer32())
if mibBuilder.loadTexts: eltCopyBackupHistoryIndex.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryIndex.setDescription('An arbitrary incremental index for the profiles table. Zero for next free index.')
eltCopyBackupHistoryDateTime = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 2), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryDateTime.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryDateTime.setDescription('Name of profile.')
eltCopyBackupHistoryDstLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 3), RlCopyLocationType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryDstLocation.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryDstLocation.setDescription('Destination File Location')
eltCopyBackupHistoryServerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryServerAddr.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryServerAddr.setDescription('Name of profile.')
eltCopyBackupHistoryFilePath = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 5), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryFilePath.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryFilePath.setDescription('Name of profile.')
eltCopyBackupHistoryStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 6), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryStatus.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryStatus.setDescription('The status of a table entry. Only three statuses are aceptable: CreateAndGo to create, Active to update,Destroy to delete. All other values cause error.')
eltCopyBackupHistoryAction = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("noAction", 1), ("clearNow", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryAction.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryAction.setDescription('Used to clear backup Table.')
mibBuilder.exportSymbols("ELTEX-MES-COPY-MIB", eltCopyBackupHistoryFilePath=eltCopyBackupHistoryFilePath, eltCopyAutoBackupOnWrite=eltCopyAutoBackupOnWrite, eltCopyBackupHistoryDateTime=eltCopyBackupHistoryDateTime, eltCopyBackupHistoryServerAddr=eltCopyBackupHistoryServerAddr, eltCopyBackupHistoryTable=eltCopyBackupHistoryTable, eltCopyBackupHistoryDstLocation=eltCopyBackupHistoryDstLocation, eltCopyBackupHistoryEntry=eltCopyBackupHistoryEntry, EltCopyUserBackupStatus=EltCopyUserBackupStatus, eltCopyAutoBackupEnable=eltCopyAutoBackupEnable, eltCopyBackupHistoryEnable=eltCopyBackupHistoryEnable, eltCopyBackupHistoryAction=eltCopyBackupHistoryAction, eltCopyBackupHistoryIndex=eltCopyBackupHistoryIndex, eltCopyAutoBackupTimeout=eltCopyAutoBackupTimeout, eltCopyAutoBackupFilePath=eltCopyAutoBackupFilePath, eltCopyUserBackupStart=eltCopyUserBackupStart, eltCopyBackupHistoryStatus=eltCopyBackupHistoryStatus, eltCopyAutoBackupServerAddress=eltCopyAutoBackupServerAddress)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint')
(elt_mes_copy,) = mibBuilder.importSymbols('ELTEX-MES', 'eltMesCopy')
(inet_address_type, inet_address) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressType', 'InetAddress')
(rl_copy_location_type,) = mibBuilder.importSymbols('RADLAN-COPY-MIB', 'RlCopyLocationType')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(time_ticks, bits, integer32, notification_type, object_identity, gauge32, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, unsigned32, ip_address, iso, module_identity, counter64) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'Bits', 'Integer32', 'NotificationType', 'ObjectIdentity', 'Gauge32', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'Unsigned32', 'IpAddress', 'iso', 'ModuleIdentity', 'Counter64')
(row_status, display_string, truth_value, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'DisplayString', 'TruthValue', 'TextualConvention')
elt_copy_auto_backup_enable = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 1), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyAutoBackupEnable.setStatus('current')
if mibBuilder.loadTexts:
eltCopyAutoBackupEnable.setDescription('Enabling on automatic backup configuration.')
elt_copy_auto_backup_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 2), unsigned32()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyAutoBackupTimeout.setStatus('current')
if mibBuilder.loadTexts:
eltCopyAutoBackupTimeout.setDescription(' This MIB should be used in order to change the time-interval of automatic copy of running-config to external server. The value should be the number of minutes for the interval of time from the backup.')
elt_copy_auto_backup_file_path = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 3), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyAutoBackupFilePath.setStatus('current')
if mibBuilder.loadTexts:
eltCopyAutoBackupFilePath.setDescription('The name of the destination file.')
elt_copy_auto_backup_server_address = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 4), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyAutoBackupServerAddress.setStatus('current')
if mibBuilder.loadTexts:
eltCopyAutoBackupServerAddress.setDescription('The Inet address of the destination remote host')
elt_copy_auto_backup_on_write = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 5), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyAutoBackupOnWrite.setStatus('current')
if mibBuilder.loadTexts:
eltCopyAutoBackupOnWrite.setDescription('Performing automatic backups every time you write configuration in memory.')
class Eltcopyuserbackupstatus(TextualConvention, Integer32):
description = 'Starting backup manually.'
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('starting', 1), ('stopped', 2))
elt_copy_user_backup_start = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 6), elt_copy_user_backup_status().clone('stopped')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyUserBackupStart.setStatus('current')
if mibBuilder.loadTexts:
eltCopyUserBackupStart.setDescription('Starting backup manually.')
elt_copy_backup_history_enable = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 7), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyBackupHistoryEnable.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryEnable.setDescription('Performing automatic backups every time you write configuration in memory.')
elt_copy_backup_history_table = mib_table((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8))
if mibBuilder.loadTexts:
eltCopyBackupHistoryTable.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryTable.setDescription('A DHCP interface configuration table.')
elt_copy_backup_history_entry = mib_table_row((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1)).setIndexNames((0, 'ELTEX-MES-COPY-MIB', 'eltCopyBackupHistoryIndex'))
if mibBuilder.loadTexts:
eltCopyBackupHistoryEntry.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryEntry.setDescription('A DHCP interface configuration entry.')
elt_copy_backup_history_index = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 1), integer32())
if mibBuilder.loadTexts:
eltCopyBackupHistoryIndex.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryIndex.setDescription('An arbitrary incremental index for the profiles table. Zero for next free index.')
elt_copy_backup_history_date_time = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 2), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyBackupHistoryDateTime.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryDateTime.setDescription('Name of profile.')
elt_copy_backup_history_dst_location = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 3), rl_copy_location_type()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyBackupHistoryDstLocation.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryDstLocation.setDescription('Destination File Location')
elt_copy_backup_history_server_addr = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 4), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyBackupHistoryServerAddr.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryServerAddr.setDescription('Name of profile.')
elt_copy_backup_history_file_path = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 5), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyBackupHistoryFilePath.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryFilePath.setDescription('Name of profile.')
elt_copy_backup_history_status = mib_table_column((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 6), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyBackupHistoryStatus.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryStatus.setDescription('The status of a table entry. Only three statuses are aceptable: CreateAndGo to create, Active to update,Destroy to delete. All other values cause error.')
elt_copy_backup_history_action = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('noAction', 1), ('clearNow', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltCopyBackupHistoryAction.setStatus('current')
if mibBuilder.loadTexts:
eltCopyBackupHistoryAction.setDescription('Used to clear backup Table.')
mibBuilder.exportSymbols('ELTEX-MES-COPY-MIB', eltCopyBackupHistoryFilePath=eltCopyBackupHistoryFilePath, eltCopyAutoBackupOnWrite=eltCopyAutoBackupOnWrite, eltCopyBackupHistoryDateTime=eltCopyBackupHistoryDateTime, eltCopyBackupHistoryServerAddr=eltCopyBackupHistoryServerAddr, eltCopyBackupHistoryTable=eltCopyBackupHistoryTable, eltCopyBackupHistoryDstLocation=eltCopyBackupHistoryDstLocation, eltCopyBackupHistoryEntry=eltCopyBackupHistoryEntry, EltCopyUserBackupStatus=EltCopyUserBackupStatus, eltCopyAutoBackupEnable=eltCopyAutoBackupEnable, eltCopyBackupHistoryEnable=eltCopyBackupHistoryEnable, eltCopyBackupHistoryAction=eltCopyBackupHistoryAction, eltCopyBackupHistoryIndex=eltCopyBackupHistoryIndex, eltCopyAutoBackupTimeout=eltCopyAutoBackupTimeout, eltCopyAutoBackupFilePath=eltCopyAutoBackupFilePath, eltCopyUserBackupStart=eltCopyUserBackupStart, eltCopyBackupHistoryStatus=eltCopyBackupHistoryStatus, eltCopyAutoBackupServerAddress=eltCopyAutoBackupServerAddress) |
#Input: length of the series N
n=int(input())
if n <=0 or n >100: #Check for boundary conditions
print("invalid")
else: # Check for in range conditions
for i in range(1,n+1):
if i%2==0: #For even positions
sum=0
for j in range(1, i+1):
sum=sum+(j*j)
print(sum,end=' ')
else: #For odd positions
print(2*i,end=' ')
| n = int(input())
if n <= 0 or n > 100:
print('invalid')
else:
for i in range(1, n + 1):
if i % 2 == 0:
sum = 0
for j in range(1, i + 1):
sum = sum + j * j
print(sum, end=' ')
else:
print(2 * i, end=' ') |
#
# PySNMP MIB module RADLAN-rndMng (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-rndMng
# Produced by pysmi-0.3.4 at Wed May 1 14:51:28 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")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
rnd, = mibBuilder.importSymbols("RADLAN-MIB", "rnd")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, Counter64, Bits, ModuleIdentity, Gauge32, MibIdentifier, Counter32, ObjectIdentity, IpAddress, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, NotificationType, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Counter64", "Bits", "ModuleIdentity", "Gauge32", "MibIdentifier", "Counter32", "ObjectIdentity", "IpAddress", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "NotificationType", "iso")
RowStatus, TextualConvention, TruthValue, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "TruthValue", "DisplayString")
rndMng = ModuleIdentity((1, 3, 6, 1, 4, 1, 89, 1))
rndMng.setRevisions(('2012-12-04 00:00', '2012-04-04 00:00', '2009-02-24 00:00', '2007-10-24 00:00', '2006-06-20 00:00', '2004-06-01 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: rndMng.setRevisionsDescriptions(('Added rlSysNameTable object.', 'Added rlScheduledReload object.', 'Added rlRunningCDBequalToStartupCDB object.', 'Added rlGroupManagement branch.', 'Added rlRebootDelay object', 'Initial version of this MIB.',))
if mibBuilder.loadTexts: rndMng.setLastUpdated('201212040000Z')
if mibBuilder.loadTexts: rndMng.setOrganization('Radlan Computer Communications Ltd.')
if mibBuilder.loadTexts: rndMng.setContactInfo('radlan.com')
if mibBuilder.loadTexts: rndMng.setDescription('The private MIB module definition for RND general management MIB.')
rndSysId = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rndSysId.setStatus('current')
if mibBuilder.loadTexts: rndSysId.setDescription('Identification of an RND device. The device type for each integer clarifies the sysObjectID in MIB - II.')
rndAction = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27))).clone(namedValues=NamedValues(("reset", 1), ("sendNetworkTab", 2), ("deleteNetworkTab", 3), ("sendRoutingTab", 4), ("deleteRoutingTab", 5), ("sendLanTab", 6), ("deleteLanTab", 7), ("deleteArpTab", 8), ("sendArpTab", 9), ("deleteRouteTab", 10), ("sendRouteTab", 11), ("backupSPFRoutingTab", 12), ("backupIPRoutingTab", 13), ("backupNetworkTab", 14), ("backupLanTab", 15), ("backupArpTab", 16), ("backupIPXRipTab", 17), ("backupIPXSAPTab", 18), ("resetStartupCDB", 19), ("eraseStartupCDB", 20), ("deleteZeroHopRoutingAllocTab", 21), ("slipDisconnect", 22), ("deleteDynamicLanTab", 23), ("eraseRunningCDB", 24), ("copyStartupToRunning", 25), ("none", 26), ("resetToFactoryDefaults", 27)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rndAction.setStatus('current')
if mibBuilder.loadTexts: rndAction.setDescription('This variable enables the operator to perform one of the specified actions on the tables maintained by the network device. Send actions require support of proprietery File exchange protocol.')
rndFileName = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 3), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rndFileName.setStatus('current')
if mibBuilder.loadTexts: rndFileName.setDescription('The name of the file used internally by RND for transferring tables maintained by network devices, using a prorietary File exchange protocol.')
rlSnmpVersionSupported = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSnmpVersionSupported.setStatus('current')
if mibBuilder.loadTexts: rlSnmpVersionSupported.setDescription('Indicates the snmp versions that are supported by this device.')
rlSnmpMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSnmpMibVersion.setStatus('current')
if mibBuilder.loadTexts: rlSnmpMibVersion.setDescription('Indicates the snmp support version that is supported by this device.')
rlCpuUtilEnable = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 6), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlCpuUtilEnable.setStatus('current')
if mibBuilder.loadTexts: rlCpuUtilEnable.setDescription('Enables measurement of the device CPU utilization. In order to get real values for rlCpuUtilDuringLastSecond, rlCpuUtilDuringLastMinute and rlCpuUtilDuringLast5Minutes, the value of this object must be true.')
rlCpuUtilDuringLastSecond = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 101))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlCpuUtilDuringLastSecond.setStatus('current')
if mibBuilder.loadTexts: rlCpuUtilDuringLastSecond.setDescription('Percentage of the device CPU utilization during last second. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last second).')
rlCpuUtilDuringLastMinute = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 101))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlCpuUtilDuringLastMinute.setStatus('current')
if mibBuilder.loadTexts: rlCpuUtilDuringLastMinute.setDescription('Percentage of the device CPU utilization during last minute. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last minute).')
rlCpuUtilDuringLast5Minutes = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 101))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlCpuUtilDuringLast5Minutes.setStatus('current')
if mibBuilder.loadTexts: rlCpuUtilDuringLast5Minutes.setDescription('Percentage of the device CPU utilization during the last 5 minutes. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last 5 minutes).')
rlRebootDelay = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 10), TimeTicks()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlRebootDelay.setStatus('current')
if mibBuilder.loadTexts: rlRebootDelay.setDescription('Setting the variable will cause the device to reboot rlRebootDelay timeticks from the moment this variable was set. If not set, the variable will return a value of 4294967295. If set to 4294967295, reboot action is cancelled. The maximum delay is set by the host parameter: reboot_delay_max')
rlGroupManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 89, 1, 11))
rlGroupMngQuery = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("query", 1), ("idle", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlGroupMngQuery.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngQuery.setDescription('Setting value query will cause the device to query for UPNP devices on the network. The device will always return value idle for GET.')
rlGroupMngQueryPeriod = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 2), Integer32()).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlGroupMngQueryPeriod.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngQueryPeriod.setDescription('Sets desired interval between queries for UPNP devices on the network. Setting 0 will result in no such query. Note that the actual query interval might be less than the set value if another application running in the device requested a shorter interval. Likewise setting 0 will not necessarily stop periodic queries if another application is still interested in periodic polling.')
rlGroupMngLastUpdate = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngLastUpdate.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngLastUpdate.setDescription('The last time rlGroupMng MIB was updated.')
rlGroupMngDevicesTable = MibTable((1, 3, 6, 1, 4, 1, 89, 1, 11, 4), )
if mibBuilder.loadTexts: rlGroupMngDevicesTable.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDevicesTable.setDescription('The table showing the discovered devices.')
rlGroupMngDeviceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1), ).setIndexNames((0, "RADLAN-rndMng", "rlGroupMngDeviceIdType"), (0, "RADLAN-rndMng", "rlGroupMngDeviceId"), (0, "RADLAN-rndMng", "rlGroupMngSubdevice"))
if mibBuilder.loadTexts: rlGroupMngDeviceEntry.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceEntry.setDescription(' The row definition for this table.')
rlGroupMngDeviceIdType = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 1), InetAddressType())
if mibBuilder.loadTexts: rlGroupMngDeviceIdType.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceIdType.setDescription('The IP address type of the discovered device ')
rlGroupMngDeviceId = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 2), InetAddress())
if mibBuilder.loadTexts: rlGroupMngDeviceId.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceId.setDescription('The IP address of the discovered device ')
rlGroupMngSubdevice = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 3), Integer32())
if mibBuilder.loadTexts: rlGroupMngSubdevice.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngSubdevice.setDescription('A subdevice within the rlGroupMngDeviceId. Only subdevices with greatest specifity will be kept (specific UUID device is more specific than basic device which is in turn more specific than root device. ')
rlGroupMngDeviceDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceDescription.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceDescription.setDescription('The discovery protocol description of the device.')
rlGroupMngGroupMngEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngGroupMngEnabled.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngGroupMngEnabled.setDescription('Indicates whether the device has Group Management enable.')
rlGroupMngGroupLLDPDeviceId = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngGroupLLDPDeviceId.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngGroupLLDPDeviceId.setDescription('The LLDP device id. If it is empty the device id is not known (either it is a non-MTS device or a non-LLDP supporting MTS device.')
rlGroupMngDeviceVendor = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceVendor.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceVendor.setDescription('The vendor of the device. If empty the vendor is not known.')
rlGroupMngDeviceAdvertisedCachingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 8), Integer32()).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceAdvertisedCachingTime.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceAdvertisedCachingTime.setDescription('The caching time advertised by the device. If no update for this device has been received during this caching time the system will assume that the device has left the network and will therefore remove its entry from the table.')
rlGroupMngDeviceLocationURL = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 9), DisplayString()).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceLocationURL.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceLocationURL.setDescription('The URL inidicating the location of the XML presenting the details of the device.')
rlGroupMngDeviceLastSeen = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 10), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceLastSeen.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceLastSeen.setDescription('The value of sysUpTime at the moment of last reception of an update for this device. ')
rlRunningCDBequalToStartupCDB = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 13), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlRunningCDBequalToStartupCDB.setStatus('current')
if mibBuilder.loadTexts: rlRunningCDBequalToStartupCDB.setDescription('Indicates whether there are changes in running CDB that were not saved in flash.')
rlClearMib = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 14), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlClearMib.setStatus('current')
if mibBuilder.loadTexts: rlClearMib.setDescription('Clear MIB value for scalars or tables: Delete all entries for tables with dynamic entries. Set table entries default values for table with static entries. Set scalar default value.')
rlScheduledReload = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 15), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 10))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlScheduledReload.setStatus('current')
if mibBuilder.loadTexts: rlScheduledReload.setDescription("Used for requesting a delayed reload of the device in a specific desired time, should be configured in one of the following formats: 'athhmmddMM' , 'inhhhmmm' or '', setting this value to an empty string will result in request for cancellation of a (previously) committed system reload. to complete the request, the 'rlScheduledReloadCommit' must also be set to either TRUE (apply) or FALSE (discard) for completion of the transaction. failing from doing so will result in an indefinite lock of the API")
rlScheduledReloadPendingDate = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 16), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 24))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlScheduledReloadPendingDate.setStatus('current')
if mibBuilder.loadTexts: rlScheduledReloadPendingDate.setDescription("Displays the most recently requested scheduled-reload due date in 'inhhhmmathhmmssddMMYYYYw' format. where 'w' stands for weekDay (1-7). if there is no pending/scheduled reload request, string will be empty")
rlScheduledReloadApprovedDate = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 17), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 24))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlScheduledReloadApprovedDate.setStatus('current')
if mibBuilder.loadTexts: rlScheduledReloadApprovedDate.setDescription("Displays the most recently approved/committed scheduled-reload date in 'inhhhmmathhmmssddMMYYYYw' format. where 'w' stands for weekDay (1-7). if there is no committed scheduled-reload , string will be empty")
rlScheduledReloadCommit = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 18), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlScheduledReloadCommit.setStatus('current')
if mibBuilder.loadTexts: rlScheduledReloadCommit.setDescription("commits the pending scheduled-reload request, and completes the transaction. when this value is set to TRUE, the system is instructed to perform the requested reload operation at the requested date/time as was given in 'rlScheduledReload'. setting this value to FALSE will discard the request.")
rlSysNameTable = MibTable((1, 3, 6, 1, 4, 1, 89, 1, 19), )
if mibBuilder.loadTexts: rlSysNameTable.setStatus('current')
if mibBuilder.loadTexts: rlSysNameTable.setDescription('Holds the current system name configuration.')
rlSysNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 89, 1, 19, 1), ).setIndexNames((0, "RADLAN-rndMng", "rlSysNameSource"), (0, "RADLAN-rndMng", "rlSysNameIfIndex"))
if mibBuilder.loadTexts: rlSysNameEntry.setStatus('current')
if mibBuilder.loadTexts: rlSysNameEntry.setDescription('The row definition of this table.')
rlSysNameSource = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("dhcpv6", 1), ("dhcpv4", 2), ("static", 3))).clone('static'))
if mibBuilder.loadTexts: rlSysNameSource.setStatus('current')
if mibBuilder.loadTexts: rlSysNameSource.setDescription("The system name source. 'static' if defined by user through CLI, 'dhcpv6' or 'dhcpv4' if received by DHCP network protocol.")
rlSysNameIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 2), InterfaceIndex().clone(1))
if mibBuilder.loadTexts: rlSysNameIfIndex.setStatus('current')
if mibBuilder.loadTexts: rlSysNameIfIndex.setDescription('The IfIndex from which the system-name configuration was received, for static entries, value will always be 1.')
rlSysNameName = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlSysNameName.setStatus('current')
if mibBuilder.loadTexts: rlSysNameName.setDescription("An administratively-assigned name for this managed node. By convention, this is the node's fully-qualified domain name. If the name is unknown, the value is the zero-length string.")
rlSysNameRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlSysNameRowStatus.setStatus('current')
if mibBuilder.loadTexts: rlSysNameRowStatus.setDescription('The row status variable, used according to row installation and removal conventions.')
rlErrdisableLinkFlappingCause = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 20), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlErrdisableLinkFlappingCause.setStatus('current')
if mibBuilder.loadTexts: rlErrdisableLinkFlappingCause.setDescription('Enable/Disable Link flapping error disable in the switch.')
mibBuilder.exportSymbols("RADLAN-rndMng", rlGroupMngDeviceAdvertisedCachingTime=rlGroupMngDeviceAdvertisedCachingTime, rlGroupManagement=rlGroupManagement, rlCpuUtilDuringLastMinute=rlCpuUtilDuringLastMinute, rlGroupMngDevicesTable=rlGroupMngDevicesTable, rlCpuUtilDuringLast5Minutes=rlCpuUtilDuringLast5Minutes, rlSysNameIfIndex=rlSysNameIfIndex, rlGroupMngDeviceIdType=rlGroupMngDeviceIdType, rlSysNameSource=rlSysNameSource, rlGroupMngLastUpdate=rlGroupMngLastUpdate, rlGroupMngDeviceLastSeen=rlGroupMngDeviceLastSeen, rndAction=rndAction, rlGroupMngDeviceLocationURL=rlGroupMngDeviceLocationURL, rlGroupMngDeviceVendor=rlGroupMngDeviceVendor, rlSysNameName=rlSysNameName, rlGroupMngDeviceEntry=rlGroupMngDeviceEntry, rlScheduledReloadApprovedDate=rlScheduledReloadApprovedDate, rndMng=rndMng, rlScheduledReloadCommit=rlScheduledReloadCommit, rndSysId=rndSysId, rlGroupMngSubdevice=rlGroupMngSubdevice, rlGroupMngDeviceDescription=rlGroupMngDeviceDescription, rlScheduledReload=rlScheduledReload, rlGroupMngQueryPeriod=rlGroupMngQueryPeriod, rlGroupMngDeviceId=rlGroupMngDeviceId, rlErrdisableLinkFlappingCause=rlErrdisableLinkFlappingCause, rlCpuUtilEnable=rlCpuUtilEnable, rlSnmpMibVersion=rlSnmpMibVersion, rlSysNameTable=rlSysNameTable, rndFileName=rndFileName, rlRebootDelay=rlRebootDelay, rlRunningCDBequalToStartupCDB=rlRunningCDBequalToStartupCDB, PYSNMP_MODULE_ID=rndMng, rlSnmpVersionSupported=rlSnmpVersionSupported, rlScheduledReloadPendingDate=rlScheduledReloadPendingDate, rlSysNameRowStatus=rlSysNameRowStatus, rlGroupMngGroupLLDPDeviceId=rlGroupMngGroupLLDPDeviceId, rlGroupMngQuery=rlGroupMngQuery, rlSysNameEntry=rlSysNameEntry, rlGroupMngGroupMngEnabled=rlGroupMngGroupMngEnabled, rlCpuUtilDuringLastSecond=rlCpuUtilDuringLastSecond, rlClearMib=rlClearMib)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint')
(interface_index,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex')
(inet_address, inet_address_type) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddress', 'InetAddressType')
(rnd,) = mibBuilder.importSymbols('RADLAN-MIB', 'rnd')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(integer32, counter64, bits, module_identity, gauge32, mib_identifier, counter32, object_identity, ip_address, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, notification_type, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'Counter64', 'Bits', 'ModuleIdentity', 'Gauge32', 'MibIdentifier', 'Counter32', 'ObjectIdentity', 'IpAddress', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'NotificationType', 'iso')
(row_status, textual_convention, truth_value, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'TextualConvention', 'TruthValue', 'DisplayString')
rnd_mng = module_identity((1, 3, 6, 1, 4, 1, 89, 1))
rndMng.setRevisions(('2012-12-04 00:00', '2012-04-04 00:00', '2009-02-24 00:00', '2007-10-24 00:00', '2006-06-20 00:00', '2004-06-01 00:00'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
rndMng.setRevisionsDescriptions(('Added rlSysNameTable object.', 'Added rlScheduledReload object.', 'Added rlRunningCDBequalToStartupCDB object.', 'Added rlGroupManagement branch.', 'Added rlRebootDelay object', 'Initial version of this MIB.'))
if mibBuilder.loadTexts:
rndMng.setLastUpdated('201212040000Z')
if mibBuilder.loadTexts:
rndMng.setOrganization('Radlan Computer Communications Ltd.')
if mibBuilder.loadTexts:
rndMng.setContactInfo('radlan.com')
if mibBuilder.loadTexts:
rndMng.setDescription('The private MIB module definition for RND general management MIB.')
rnd_sys_id = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rndSysId.setStatus('current')
if mibBuilder.loadTexts:
rndSysId.setDescription('Identification of an RND device. The device type for each integer clarifies the sysObjectID in MIB - II.')
rnd_action = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27))).clone(namedValues=named_values(('reset', 1), ('sendNetworkTab', 2), ('deleteNetworkTab', 3), ('sendRoutingTab', 4), ('deleteRoutingTab', 5), ('sendLanTab', 6), ('deleteLanTab', 7), ('deleteArpTab', 8), ('sendArpTab', 9), ('deleteRouteTab', 10), ('sendRouteTab', 11), ('backupSPFRoutingTab', 12), ('backupIPRoutingTab', 13), ('backupNetworkTab', 14), ('backupLanTab', 15), ('backupArpTab', 16), ('backupIPXRipTab', 17), ('backupIPXSAPTab', 18), ('resetStartupCDB', 19), ('eraseStartupCDB', 20), ('deleteZeroHopRoutingAllocTab', 21), ('slipDisconnect', 22), ('deleteDynamicLanTab', 23), ('eraseRunningCDB', 24), ('copyStartupToRunning', 25), ('none', 26), ('resetToFactoryDefaults', 27)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rndAction.setStatus('current')
if mibBuilder.loadTexts:
rndAction.setDescription('This variable enables the operator to perform one of the specified actions on the tables maintained by the network device. Send actions require support of proprietery File exchange protocol.')
rnd_file_name = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 3), octet_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rndFileName.setStatus('current')
if mibBuilder.loadTexts:
rndFileName.setDescription('The name of the file used internally by RND for transferring tables maintained by network devices, using a prorietary File exchange protocol.')
rl_snmp_version_supported = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 4), octet_string().subtype(subtypeSpec=value_size_constraint(1, 1)).setFixedLength(1)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSnmpVersionSupported.setStatus('current')
if mibBuilder.loadTexts:
rlSnmpVersionSupported.setDescription('Indicates the snmp versions that are supported by this device.')
rl_snmp_mib_version = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 5), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSnmpMibVersion.setStatus('current')
if mibBuilder.loadTexts:
rlSnmpMibVersion.setDescription('Indicates the snmp support version that is supported by this device.')
rl_cpu_util_enable = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 6), truth_value().clone('true')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlCpuUtilEnable.setStatus('current')
if mibBuilder.loadTexts:
rlCpuUtilEnable.setDescription('Enables measurement of the device CPU utilization. In order to get real values for rlCpuUtilDuringLastSecond, rlCpuUtilDuringLastMinute and rlCpuUtilDuringLast5Minutes, the value of this object must be true.')
rl_cpu_util_during_last_second = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 101))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlCpuUtilDuringLastSecond.setStatus('current')
if mibBuilder.loadTexts:
rlCpuUtilDuringLastSecond.setDescription('Percentage of the device CPU utilization during last second. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last second).')
rl_cpu_util_during_last_minute = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(0, 101))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlCpuUtilDuringLastMinute.setStatus('current')
if mibBuilder.loadTexts:
rlCpuUtilDuringLastMinute.setDescription('Percentage of the device CPU utilization during last minute. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last minute).')
rl_cpu_util_during_last5_minutes = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(0, 101))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlCpuUtilDuringLast5Minutes.setStatus('current')
if mibBuilder.loadTexts:
rlCpuUtilDuringLast5Minutes.setDescription('Percentage of the device CPU utilization during the last 5 minutes. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last 5 minutes).')
rl_reboot_delay = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 10), time_ticks()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlRebootDelay.setStatus('current')
if mibBuilder.loadTexts:
rlRebootDelay.setDescription('Setting the variable will cause the device to reboot rlRebootDelay timeticks from the moment this variable was set. If not set, the variable will return a value of 4294967295. If set to 4294967295, reboot action is cancelled. The maximum delay is set by the host parameter: reboot_delay_max')
rl_group_management = mib_identifier((1, 3, 6, 1, 4, 1, 89, 1, 11))
rl_group_mng_query = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('query', 1), ('idle', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlGroupMngQuery.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngQuery.setDescription('Setting value query will cause the device to query for UPNP devices on the network. The device will always return value idle for GET.')
rl_group_mng_query_period = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 2), integer32()).setUnits('seconds').setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlGroupMngQueryPeriod.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngQueryPeriod.setDescription('Sets desired interval between queries for UPNP devices on the network. Setting 0 will result in no such query. Note that the actual query interval might be less than the set value if another application running in the device requested a shorter interval. Likewise setting 0 will not necessarily stop periodic queries if another application is still interested in periodic polling.')
rl_group_mng_last_update = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 3), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlGroupMngLastUpdate.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngLastUpdate.setDescription('The last time rlGroupMng MIB was updated.')
rl_group_mng_devices_table = mib_table((1, 3, 6, 1, 4, 1, 89, 1, 11, 4))
if mibBuilder.loadTexts:
rlGroupMngDevicesTable.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDevicesTable.setDescription('The table showing the discovered devices.')
rl_group_mng_device_entry = mib_table_row((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1)).setIndexNames((0, 'RADLAN-rndMng', 'rlGroupMngDeviceIdType'), (0, 'RADLAN-rndMng', 'rlGroupMngDeviceId'), (0, 'RADLAN-rndMng', 'rlGroupMngSubdevice'))
if mibBuilder.loadTexts:
rlGroupMngDeviceEntry.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDeviceEntry.setDescription(' The row definition for this table.')
rl_group_mng_device_id_type = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 1), inet_address_type())
if mibBuilder.loadTexts:
rlGroupMngDeviceIdType.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDeviceIdType.setDescription('The IP address type of the discovered device ')
rl_group_mng_device_id = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 2), inet_address())
if mibBuilder.loadTexts:
rlGroupMngDeviceId.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDeviceId.setDescription('The IP address of the discovered device ')
rl_group_mng_subdevice = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 3), integer32())
if mibBuilder.loadTexts:
rlGroupMngSubdevice.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngSubdevice.setDescription('A subdevice within the rlGroupMngDeviceId. Only subdevices with greatest specifity will be kept (specific UUID device is more specific than basic device which is in turn more specific than root device. ')
rl_group_mng_device_description = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 4), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlGroupMngDeviceDescription.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDeviceDescription.setDescription('The discovery protocol description of the device.')
rl_group_mng_group_mng_enabled = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 5), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlGroupMngGroupMngEnabled.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngGroupMngEnabled.setDescription('Indicates whether the device has Group Management enable.')
rl_group_mng_group_lldp_device_id = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 6), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlGroupMngGroupLLDPDeviceId.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngGroupLLDPDeviceId.setDescription('The LLDP device id. If it is empty the device id is not known (either it is a non-MTS device or a non-LLDP supporting MTS device.')
rl_group_mng_device_vendor = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 7), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlGroupMngDeviceVendor.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDeviceVendor.setDescription('The vendor of the device. If empty the vendor is not known.')
rl_group_mng_device_advertised_caching_time = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 8), integer32()).setUnits('seconds').setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlGroupMngDeviceAdvertisedCachingTime.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDeviceAdvertisedCachingTime.setDescription('The caching time advertised by the device. If no update for this device has been received during this caching time the system will assume that the device has left the network and will therefore remove its entry from the table.')
rl_group_mng_device_location_url = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 9), display_string()).setUnits('seconds').setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlGroupMngDeviceLocationURL.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDeviceLocationURL.setDescription('The URL inidicating the location of the XML presenting the details of the device.')
rl_group_mng_device_last_seen = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 10), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlGroupMngDeviceLastSeen.setStatus('current')
if mibBuilder.loadTexts:
rlGroupMngDeviceLastSeen.setDescription('The value of sysUpTime at the moment of last reception of an update for this device. ')
rl_running_cd_bequal_to_startup_cdb = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 13), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlRunningCDBequalToStartupCDB.setStatus('current')
if mibBuilder.loadTexts:
rlRunningCDBequalToStartupCDB.setDescription('Indicates whether there are changes in running CDB that were not saved in flash.')
rl_clear_mib = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 14), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlClearMib.setStatus('current')
if mibBuilder.loadTexts:
rlClearMib.setDescription('Clear MIB value for scalars or tables: Delete all entries for tables with dynamic entries. Set table entries default values for table with static entries. Set scalar default value.')
rl_scheduled_reload = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 15), display_string().subtype(subtypeSpec=value_size_constraint(0, 10))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlScheduledReload.setStatus('current')
if mibBuilder.loadTexts:
rlScheduledReload.setDescription("Used for requesting a delayed reload of the device in a specific desired time, should be configured in one of the following formats: 'athhmmddMM' , 'inhhhmmm' or '', setting this value to an empty string will result in request for cancellation of a (previously) committed system reload. to complete the request, the 'rlScheduledReloadCommit' must also be set to either TRUE (apply) or FALSE (discard) for completion of the transaction. failing from doing so will result in an indefinite lock of the API")
rl_scheduled_reload_pending_date = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 16), display_string().subtype(subtypeSpec=value_size_constraint(0, 24))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlScheduledReloadPendingDate.setStatus('current')
if mibBuilder.loadTexts:
rlScheduledReloadPendingDate.setDescription("Displays the most recently requested scheduled-reload due date in 'inhhhmmathhmmssddMMYYYYw' format. where 'w' stands for weekDay (1-7). if there is no pending/scheduled reload request, string will be empty")
rl_scheduled_reload_approved_date = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 17), display_string().subtype(subtypeSpec=value_size_constraint(0, 24))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlScheduledReloadApprovedDate.setStatus('current')
if mibBuilder.loadTexts:
rlScheduledReloadApprovedDate.setDescription("Displays the most recently approved/committed scheduled-reload date in 'inhhhmmathhmmssddMMYYYYw' format. where 'w' stands for weekDay (1-7). if there is no committed scheduled-reload , string will be empty")
rl_scheduled_reload_commit = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 18), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlScheduledReloadCommit.setStatus('current')
if mibBuilder.loadTexts:
rlScheduledReloadCommit.setDescription("commits the pending scheduled-reload request, and completes the transaction. when this value is set to TRUE, the system is instructed to perform the requested reload operation at the requested date/time as was given in 'rlScheduledReload'. setting this value to FALSE will discard the request.")
rl_sys_name_table = mib_table((1, 3, 6, 1, 4, 1, 89, 1, 19))
if mibBuilder.loadTexts:
rlSysNameTable.setStatus('current')
if mibBuilder.loadTexts:
rlSysNameTable.setDescription('Holds the current system name configuration.')
rl_sys_name_entry = mib_table_row((1, 3, 6, 1, 4, 1, 89, 1, 19, 1)).setIndexNames((0, 'RADLAN-rndMng', 'rlSysNameSource'), (0, 'RADLAN-rndMng', 'rlSysNameIfIndex'))
if mibBuilder.loadTexts:
rlSysNameEntry.setStatus('current')
if mibBuilder.loadTexts:
rlSysNameEntry.setDescription('The row definition of this table.')
rl_sys_name_source = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('dhcpv6', 1), ('dhcpv4', 2), ('static', 3))).clone('static'))
if mibBuilder.loadTexts:
rlSysNameSource.setStatus('current')
if mibBuilder.loadTexts:
rlSysNameSource.setDescription("The system name source. 'static' if defined by user through CLI, 'dhcpv6' or 'dhcpv4' if received by DHCP network protocol.")
rl_sys_name_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 2), interface_index().clone(1))
if mibBuilder.loadTexts:
rlSysNameIfIndex.setStatus('current')
if mibBuilder.loadTexts:
rlSysNameIfIndex.setDescription('The IfIndex from which the system-name configuration was received, for static entries, value will always be 1.')
rl_sys_name_name = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
rlSysNameName.setStatus('current')
if mibBuilder.loadTexts:
rlSysNameName.setDescription("An administratively-assigned name for this managed node. By convention, this is the node's fully-qualified domain name. If the name is unknown, the value is the zero-length string.")
rl_sys_name_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 4), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
rlSysNameRowStatus.setStatus('current')
if mibBuilder.loadTexts:
rlSysNameRowStatus.setDescription('The row status variable, used according to row installation and removal conventions.')
rl_errdisable_link_flapping_cause = mib_scalar((1, 3, 6, 1, 4, 1, 89, 1, 20), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlErrdisableLinkFlappingCause.setStatus('current')
if mibBuilder.loadTexts:
rlErrdisableLinkFlappingCause.setDescription('Enable/Disable Link flapping error disable in the switch.')
mibBuilder.exportSymbols('RADLAN-rndMng', rlGroupMngDeviceAdvertisedCachingTime=rlGroupMngDeviceAdvertisedCachingTime, rlGroupManagement=rlGroupManagement, rlCpuUtilDuringLastMinute=rlCpuUtilDuringLastMinute, rlGroupMngDevicesTable=rlGroupMngDevicesTable, rlCpuUtilDuringLast5Minutes=rlCpuUtilDuringLast5Minutes, rlSysNameIfIndex=rlSysNameIfIndex, rlGroupMngDeviceIdType=rlGroupMngDeviceIdType, rlSysNameSource=rlSysNameSource, rlGroupMngLastUpdate=rlGroupMngLastUpdate, rlGroupMngDeviceLastSeen=rlGroupMngDeviceLastSeen, rndAction=rndAction, rlGroupMngDeviceLocationURL=rlGroupMngDeviceLocationURL, rlGroupMngDeviceVendor=rlGroupMngDeviceVendor, rlSysNameName=rlSysNameName, rlGroupMngDeviceEntry=rlGroupMngDeviceEntry, rlScheduledReloadApprovedDate=rlScheduledReloadApprovedDate, rndMng=rndMng, rlScheduledReloadCommit=rlScheduledReloadCommit, rndSysId=rndSysId, rlGroupMngSubdevice=rlGroupMngSubdevice, rlGroupMngDeviceDescription=rlGroupMngDeviceDescription, rlScheduledReload=rlScheduledReload, rlGroupMngQueryPeriod=rlGroupMngQueryPeriod, rlGroupMngDeviceId=rlGroupMngDeviceId, rlErrdisableLinkFlappingCause=rlErrdisableLinkFlappingCause, rlCpuUtilEnable=rlCpuUtilEnable, rlSnmpMibVersion=rlSnmpMibVersion, rlSysNameTable=rlSysNameTable, rndFileName=rndFileName, rlRebootDelay=rlRebootDelay, rlRunningCDBequalToStartupCDB=rlRunningCDBequalToStartupCDB, PYSNMP_MODULE_ID=rndMng, rlSnmpVersionSupported=rlSnmpVersionSupported, rlScheduledReloadPendingDate=rlScheduledReloadPendingDate, rlSysNameRowStatus=rlSysNameRowStatus, rlGroupMngGroupLLDPDeviceId=rlGroupMngGroupLLDPDeviceId, rlGroupMngQuery=rlGroupMngQuery, rlSysNameEntry=rlSysNameEntry, rlGroupMngGroupMngEnabled=rlGroupMngGroupMngEnabled, rlCpuUtilDuringLastSecond=rlCpuUtilDuringLastSecond, rlClearMib=rlClearMib) |
s = '100'
print(s)
s = 'abc1234-09232<>?323'
print(s)
s = 'abc 123'
print(s)
s = ' '
print(s)
| s = '100'
print(s)
s = 'abc1234-09232<>?323'
print(s)
s = 'abc 123'
print(s)
s = ' '
print(s) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 8 17:29:02 2021
@author: dopiwoo
Given a binary tree and a number 'S', find if the tree has a path from root-to-leaf such that the sum of all the node
values of that path equals 'S'.
"""
class TreeNode:
def __init__(self, val: int = 0, left: 'TreeNode' = None, right: 'TreeNode' = None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return str(self.val)
def has_path(root: TreeNode, path_sum: int) -> bool:
"""
Time Complexity: O(N)
Space Complexity: O(N)
Parameters
----------
root : TreeNode
Input binary tree.
path_sum : int
Input number 'S'.
Returns
-------
bool
Whether the tree has a path from root-to-leaf such that the sum of all the node values of that path equals 'S'.
"""
if not root:
return False
if path_sum == root.val and not root.left and not root.right:
return True
return has_path(root.left, path_sum - root.val) or has_path(root.right, path_sum - root.val)
if __name__ == '__main__':
root_node = TreeNode(12)
root_node.left = TreeNode(7)
root_node.right = TreeNode(1)
root_node.left.left = TreeNode(9)
root_node.right.left = TreeNode(10)
root_node.right.right = TreeNode(5)
print(has_path(root_node, 23))
print(has_path(root_node, 16))
| """
Created on Mon Mar 8 17:29:02 2021
@author: dopiwoo
Given a binary tree and a number 'S', find if the tree has a path from root-to-leaf such that the sum of all the node
values of that path equals 'S'.
"""
class Treenode:
def __init__(self, val: int=0, left: 'TreeNode'=None, right: 'TreeNode'=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return str(self.val)
def has_path(root: TreeNode, path_sum: int) -> bool:
"""
Time Complexity: O(N)
Space Complexity: O(N)
Parameters
----------
root : TreeNode
Input binary tree.
path_sum : int
Input number 'S'.
Returns
-------
bool
Whether the tree has a path from root-to-leaf such that the sum of all the node values of that path equals 'S'.
"""
if not root:
return False
if path_sum == root.val and (not root.left) and (not root.right):
return True
return has_path(root.left, path_sum - root.val) or has_path(root.right, path_sum - root.val)
if __name__ == '__main__':
root_node = tree_node(12)
root_node.left = tree_node(7)
root_node.right = tree_node(1)
root_node.left.left = tree_node(9)
root_node.right.left = tree_node(10)
root_node.right.right = tree_node(5)
print(has_path(root_node, 23))
print(has_path(root_node, 16)) |
"""https://github.com/biocommons/hgvs/issues/525"""
def test_525(parser, am38):
"""https://github.com/biocommons/hgvs/issues/525"""
# simple test case
hgvs = "NM_000551.3:c.3_4insTAG" # insert stop in phase at AA 2
var_c = parser.parse_hgvs_variant(hgvs)
var_p = am38.c_to_p(var_c)
assert str(var_p) == "NP_000542.1:p.(Pro2Ter)"
# variant reported in issue
hgvs = "NM_001256125.1:c.1015_1016insAGGGACTGGGCGGGGCCATGGTCT"
var_c = parser.parse_hgvs_variant(hgvs)
var_p = am38.c_to_p(var_c)
assert str(var_p) == "NP_001243054.2:p.(Trp339Ter)"
| """https://github.com/biocommons/hgvs/issues/525"""
def test_525(parser, am38):
"""https://github.com/biocommons/hgvs/issues/525"""
hgvs = 'NM_000551.3:c.3_4insTAG'
var_c = parser.parse_hgvs_variant(hgvs)
var_p = am38.c_to_p(var_c)
assert str(var_p) == 'NP_000542.1:p.(Pro2Ter)'
hgvs = 'NM_001256125.1:c.1015_1016insAGGGACTGGGCGGGGCCATGGTCT'
var_c = parser.parse_hgvs_variant(hgvs)
var_p = am38.c_to_p(var_c)
assert str(var_p) == 'NP_001243054.2:p.(Trp339Ter)' |
description = 'Slit ZB0 using Beckhoff controllers'
group = 'lowlevel'
includes = ['zz_absoluts']
instrument_values = configdata('instrument.values')
showcase_values = configdata('cf_showcase.showcase_values')
optic_values = configdata('cf_optic.optic_values')
tango_base = instrument_values['tango_base']
code_base = instrument_values['code_base']
index = 4
devices = dict(
# zb0_a = device('nicos.devices.generic.Axis',
# description = 'zb0 axis',
# motor = 'zb0_motor',
# precision = 0.02,
# maxtries = 3,
# lowlevel = True,
# ),
zb0 = device(code_base + 'slits.SingleSlit',
# length: 13 mm
description = 'zb0, singleslit',
motor = 'zb0_motor',
nok_start = 4121.5,
nok_end = 4134.5,
nok_gap = 1,
masks = {
'slit': 0,
'point': 0,
'gisans': -110 * optic_values['gisans_scale'],
},
unit = 'mm',
),
# zb0_temp = device(code_base + 'beckhoff.nok.BeckhoffTemp',
# description = 'Temperatur for ZB0 Motor',
# tangodevice = tango_base + 'optic/io/modbus',
# address = 0x3020+index*10, # word address
# abslimits = (-1000, 1000),
# lowlevel = showcase_values['hide_temp'],
# ),
# zb0_analog = device(code_base + 'beckhoff.nok.BeckhoffPoti',
# description = 'Poti for ZB0 no ref',
# tangodevice = tango_base + 'optic/io/modbus',
# address = 0x3020+index*10, # word address
# abslimits = (-1000, 1000),
# poly = [-176.49512271969755, 0.00794154091586989],
# lowlevel = True or showcase_values['hide_poti'],
# ),
# zb0_acc = device(code_base + 'nok_support.MotorEncoderDifference',
# description = 'calc error Motor and poti',
# motor = 'zb0_motor',
# analog = 'zb0_analog',
# lowlevel = True or showcase_values['hide_acc'],
# unit = 'mm'
# ),
)
| description = 'Slit ZB0 using Beckhoff controllers'
group = 'lowlevel'
includes = ['zz_absoluts']
instrument_values = configdata('instrument.values')
showcase_values = configdata('cf_showcase.showcase_values')
optic_values = configdata('cf_optic.optic_values')
tango_base = instrument_values['tango_base']
code_base = instrument_values['code_base']
index = 4
devices = dict(zb0=device(code_base + 'slits.SingleSlit', description='zb0, singleslit', motor='zb0_motor', nok_start=4121.5, nok_end=4134.5, nok_gap=1, masks={'slit': 0, 'point': 0, 'gisans': -110 * optic_values['gisans_scale']}, unit='mm')) |
# Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.
# An integer y is a power of three if there exists an integer x such that y == 3x.
def checkPowersOfThree(n):
while n > 0:
if n % 3 > 1:
return False
n //= 3
return True
print(checkPowersOfThree(12))
print(checkPowersOfThree(21))
print(checkPowersOfThree(91))
print(checkPowersOfThree(100)) | def check_powers_of_three(n):
while n > 0:
if n % 3 > 1:
return False
n //= 3
return True
print(check_powers_of_three(12))
print(check_powers_of_three(21))
print(check_powers_of_three(91))
print(check_powers_of_three(100)) |
#!/usr/bin/python3.4
# -*- coding: utf-8 -*-
"""
This app calculates the accuracy of shots on goal in football
Author: Alexander A. Laurence
Last modified: January 2019
Website: www.celestial.tokyo
"""
# number of shots that didn't hit the goal
shots_offTarget = input("How many shots did not hit the target? ")
print("Ok, so %s shots failed to the target." % shots_offTarget)
# number of shots that hit the goal
shots_onTarget = input("How many shots hit the target? ")
print("Ok, so %s shots hit the target." % shots_offTarget)
# the percentage accuracy
shot_accuracy = (shots_onTarget / (shots_onTarget + shots_offTarget))*100
print("That means your shot accuracy was %s." % shot_accuracy)
| """
This app calculates the accuracy of shots on goal in football
Author: Alexander A. Laurence
Last modified: January 2019
Website: www.celestial.tokyo
"""
shots_off_target = input('How many shots did not hit the target? ')
print('Ok, so %s shots failed to the target.' % shots_offTarget)
shots_on_target = input('How many shots hit the target? ')
print('Ok, so %s shots hit the target.' % shots_offTarget)
shot_accuracy = shots_onTarget / (shots_onTarget + shots_offTarget) * 100
print('That means your shot accuracy was %s.' % shot_accuracy) |
"""
# Implementation of all_keys function.
* It will return all the keys present in the object.
* It will also return the nested keys at all levels.
"""
__all__ = ["all_keys"]
def _recursive_items(dictionary):
"""This function will accept the dictionary
and iterate over it and yield all the keys
Args:
dictionary (dict): dictionary to iterate
Yields:
string: key in dictionary object.
"""
for key, value in dictionary.items():
yield key
if isinstance(value, dict):
yield from _recursive_items(value)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
yield from _recursive_items(item)
else:
yield key
def all_keys(obj):
"""This function will accept one param
and return all keys
* It will return all the keys in the object
Args:
obj (dict): dictionary object
Returns:
set: set of all the keys
"""
key_from_obj = set()
for key in _recursive_items(dictionary=obj):
key_from_obj.add(key)
return key_from_obj
| """
# Implementation of all_keys function.
* It will return all the keys present in the object.
* It will also return the nested keys at all levels.
"""
__all__ = ['all_keys']
def _recursive_items(dictionary):
"""This function will accept the dictionary
and iterate over it and yield all the keys
Args:
dictionary (dict): dictionary to iterate
Yields:
string: key in dictionary object.
"""
for (key, value) in dictionary.items():
yield key
if isinstance(value, dict):
yield from _recursive_items(value)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
yield from _recursive_items(item)
else:
yield key
def all_keys(obj):
"""This function will accept one param
and return all keys
* It will return all the keys in the object
Args:
obj (dict): dictionary object
Returns:
set: set of all the keys
"""
key_from_obj = set()
for key in _recursive_items(dictionary=obj):
key_from_obj.add(key)
return key_from_obj |
def longest_increasing_subsequency(l: List) -> int:
result = end = 0
for i in range(len(l)):
if i > 0 and l[i - 1] >= l[i]:
end = i
result = max(result, i - end+1)
return result
print(longest_increasing_subsequency([3,5,7,2,1]))
print(longest_increasing_subsequency([2,2,2,2]))
print(longest_increasing_subsequency([]))
print(longest_increasing_subsequency([2,2,3,4,4])) | def longest_increasing_subsequency(l: List) -> int:
result = end = 0
for i in range(len(l)):
if i > 0 and l[i - 1] >= l[i]:
end = i
result = max(result, i - end + 1)
return result
print(longest_increasing_subsequency([3, 5, 7, 2, 1]))
print(longest_increasing_subsequency([2, 2, 2, 2]))
print(longest_increasing_subsequency([]))
print(longest_increasing_subsequency([2, 2, 3, 4, 4])) |
"""
Created on 3 Mar. 2018
@author: oliver
"""
class LineClassifier(object):
"""
classdocs
"""
def __init__(self, classification_description, line_collection):
"""
Constructor
"""
self._descr = classification_description
self._collection = line_collection
def classify_file(self, f):
assert f or not f
| """
Created on 3 Mar. 2018
@author: oliver
"""
class Lineclassifier(object):
"""
classdocs
"""
def __init__(self, classification_description, line_collection):
"""
Constructor
"""
self._descr = classification_description
self._collection = line_collection
def classify_file(self, f):
assert f or not f |
train_data_path = "data/chunked/train/train_*"
valid_data_path = "data/chunked/valid/valid_*"
test_data_path = "data/chunked/test/test_*"
vocab_path = "data/vocab"
# Hyperparameters
hidden_dim = 512
emb_dim = 256
batch_size = 200
max_enc_steps = 55 #99% of the articles are within length 55
max_dec_steps = 15 #99% of the titles are within length 15
beam_size = 4
min_dec_steps= 3
vocab_size = 50000
lr = 0.001
rand_unif_init_mag = 0.02
trunc_norm_init_std = 1e-4
eps = 1e-12
max_iterations = 500000
save_model_path = "data/saved_models"
intra_encoder = True
intra_decoder = True | train_data_path = 'data/chunked/train/train_*'
valid_data_path = 'data/chunked/valid/valid_*'
test_data_path = 'data/chunked/test/test_*'
vocab_path = 'data/vocab'
hidden_dim = 512
emb_dim = 256
batch_size = 200
max_enc_steps = 55
max_dec_steps = 15
beam_size = 4
min_dec_steps = 3
vocab_size = 50000
lr = 0.001
rand_unif_init_mag = 0.02
trunc_norm_init_std = 0.0001
eps = 1e-12
max_iterations = 500000
save_model_path = 'data/saved_models'
intra_encoder = True
intra_decoder = True |
"""
Write a program to solve the following problem: You have two jugs: a 4-gallon
jug and a 3-gallon jug. Neither of the jugs have markings on them. There is a
pump that can be used to fill the jugs with water. How can you get exactly two
gallons of water in the 4-gallon jug?
"""
def recursive_jugs(big_jug, little_jug, amt):
"""Displays how to get amt when given a big jug and little jug without
markings
:big_jug: TODO
:little_jug: TODO
:amt: TODO
:returns: TODO
"""
if little_jug == amt:
print(f"Little jug:{little_jug} equals target:{amt}")
return "Dump big jug and fill with remainder in little jug"
else:
print("Dump big jug")
print("Fill big jug with little jug")
big = little_jug
print(f"Big jug:{big}")
print("Refill little jug and put into big jug")
little = little_jug - (big_jug % little_jug)
# big = big_jug
print(f"Little jug:{little}")
return recursive_jugs(big, little, amt)
if __name__ == "__main__":
print(recursive_jugs(4, 3, 2))
| """
Write a program to solve the following problem: You have two jugs: a 4-gallon
jug and a 3-gallon jug. Neither of the jugs have markings on them. There is a
pump that can be used to fill the jugs with water. How can you get exactly two
gallons of water in the 4-gallon jug?
"""
def recursive_jugs(big_jug, little_jug, amt):
"""Displays how to get amt when given a big jug and little jug without
markings
:big_jug: TODO
:little_jug: TODO
:amt: TODO
:returns: TODO
"""
if little_jug == amt:
print(f'Little jug:{little_jug} equals target:{amt}')
return 'Dump big jug and fill with remainder in little jug'
else:
print('Dump big jug')
print('Fill big jug with little jug')
big = little_jug
print(f'Big jug:{big}')
print('Refill little jug and put into big jug')
little = little_jug - big_jug % little_jug
print(f'Little jug:{little}')
return recursive_jugs(big, little, amt)
if __name__ == '__main__':
print(recursive_jugs(4, 3, 2)) |
# from https://github.com/pyca/bcrypt/blob/3.1.7/tests/test_bcrypt.py
#
# Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
[
(
b"Kk4DQuMMfZL9o",
b"$2b$04$cVWp4XaNU8a4v1uMRum2SO",
b"$2b$04$cVWp4XaNU8a4v1uMRum2SO026BWLIoQMD/TXg5uZV.0P.uO8m3YEm",
),
(
b"9IeRXmnGxMYbs",
b"$2b$04$pQ7gRO7e6wx/936oXhNjrO",
b"$2b$04$pQ7gRO7e6wx/936oXhNjrOUNOHL1D0h1N2IDbJZYs.1ppzSof6SPy",
),
(
b"xVQVbwa1S0M8r",
b"$2b$04$SQe9knOzepOVKoYXo9xTte",
b"$2b$04$SQe9knOzepOVKoYXo9xTteNYr6MBwVz4tpriJVe3PNgYufGIsgKcW",
),
(
b"Zfgr26LWd22Za",
b"$2b$04$eH8zX.q5Q.j2hO1NkVYJQO",
b"$2b$04$eH8zX.q5Q.j2hO1NkVYJQOM6KxntS/ow3.YzVmFrE4t//CoF4fvne",
),
(
b"Tg4daC27epFBE",
b"$2b$04$ahiTdwRXpUG2JLRcIznxc.",
b"$2b$04$ahiTdwRXpUG2JLRcIznxc.s1.ydaPGD372bsGs8NqyYjLY1inG5n2",
),
(
b"xhQPMmwh5ALzW",
b"$2b$04$nQn78dV0hGHf5wUBe0zOFu",
b"$2b$04$nQn78dV0hGHf5wUBe0zOFu8n07ZbWWOKoGasZKRspZxtt.vBRNMIy",
),
(
b"59je8h5Gj71tg",
b"$2b$04$cvXudZ5ugTg95W.rOjMITu",
b"$2b$04$cvXudZ5ugTg95W.rOjMITuM1jC0piCl3zF5cmGhzCibHZrNHkmckG",
),
(
b"wT4fHJa2N9WSW",
b"$2b$04$YYjtiq4Uh88yUsExO0RNTu",
b"$2b$04$YYjtiq4Uh88yUsExO0RNTuEJ.tZlsONac16A8OcLHleWFjVawfGvO",
),
(
b"uSgFRnQdOgm4S",
b"$2b$04$WLTjgY/pZSyqX/fbMbJzf.",
b"$2b$04$WLTjgY/pZSyqX/fbMbJzf.qxCeTMQOzgL.CimRjMHtMxd/VGKojMu",
),
(
b"tEPtJZXur16Vg",
b"$2b$04$2moPs/x/wnCfeQ5pCheMcu",
b"$2b$04$2moPs/x/wnCfeQ5pCheMcuSJQ/KYjOZG780UjA/SiR.KsYWNrC7SG",
),
(
b"vvho8C6nlVf9K",
b"$2b$04$HrEYC/AQ2HS77G78cQDZQ.",
b"$2b$04$HrEYC/AQ2HS77G78cQDZQ.r44WGcruKw03KHlnp71yVQEwpsi3xl2",
),
(
b"5auCCY9by0Ruf",
b"$2b$04$vVYgSTfB8KVbmhbZE/k3R.",
b"$2b$04$vVYgSTfB8KVbmhbZE/k3R.ux9A0lJUM4CZwCkHI9fifke2.rTF7MG",
),
(
b"GtTkR6qn2QOZW",
b"$2b$04$JfoNrR8.doieoI8..F.C1O",
b"$2b$04$JfoNrR8.doieoI8..F.C1OQgwE3uTeuardy6lw0AjALUzOARoyf2m",
),
(
b"zKo8vdFSnjX0f",
b"$2b$04$HP3I0PUs7KBEzMBNFw7o3O",
b"$2b$04$HP3I0PUs7KBEzMBNFw7o3O7f/uxaZU7aaDot1quHMgB2yrwBXsgyy",
),
(
b"I9VfYlacJiwiK",
b"$2b$04$xnFVhJsTzsFBTeP3PpgbMe",
b"$2b$04$xnFVhJsTzsFBTeP3PpgbMeMREb6rdKV9faW54Sx.yg9plf4jY8qT6",
),
(
b"VFPO7YXnHQbQO",
b"$2b$04$WQp9.igoLqVr6Qk70mz6xu",
b"$2b$04$WQp9.igoLqVr6Qk70mz6xuRxE0RttVXXdukpR9N54x17ecad34ZF6",
),
(
b"VDx5BdxfxstYk",
b"$2b$04$xgZtlonpAHSU/njOCdKztO",
b"$2b$04$xgZtlonpAHSU/njOCdKztOPuPFzCNVpB4LGicO4/OGgHv.uKHkwsS",
),
(
b"dEe6XfVGrrfSH",
b"$2b$04$2Siw3Nv3Q/gTOIPetAyPr.",
b"$2b$04$2Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe",
),
(
b"cTT0EAFdwJiLn",
b"$2b$04$7/Qj7Kd8BcSahPO4khB8me",
b"$2b$04$7/Qj7Kd8BcSahPO4khB8me4ssDJCW3r4OGYqPF87jxtrSyPj5cS5m",
),
(
b"J8eHUDuxBB520",
b"$2b$04$VvlCUKbTMjaxaYJ.k5juoe",
b"$2b$04$VvlCUKbTMjaxaYJ.k5juoecpG/7IzcH1AkmqKi.lIZMVIOLClWAk.",
),
(
b"U*U",
b"$2a$05$CCCCCCCCCCCCCCCCCCCCC.",
b"$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
),
(
b"U*U*",
b"$2a$05$CCCCCCCCCCCCCCCCCCCCC.",
b"$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK",
),
(
b"U*U*U",
b"$2a$05$XXXXXXXXXXXXXXXXXXXXXO",
b"$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a",
),
(
b"0123456789abcdefghijklmnopqrstuvwxyz"
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
#b"chars after 72 are ignored"
,
b"$2a$05$abcdefghijklmnopqrstuu",
b"$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui",
),
(
b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa"
b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa"
b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa"
b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa"
b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa"
b"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa"
#b"chars after 72 are ignored as usual"
,
b"$2a$05$/OK.fbVrR/bpIqNJ5ianF.",
b"$2a$05$/OK.fbVrR/bpIqNJ5ianF.swQOIzjOiJ9GHEPuhEkvqrUyvWhEMx6"
),
(
b"\xa3",
b"$2a$05$/OK.fbVrR/bpIqNJ5ianF.",
b"$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq"
),
]
| [(b'Kk4DQuMMfZL9o', b'$2b$04$cVWp4XaNU8a4v1uMRum2SO', b'$2b$04$cVWp4XaNU8a4v1uMRum2SO026BWLIoQMD/TXg5uZV.0P.uO8m3YEm'), (b'9IeRXmnGxMYbs', b'$2b$04$pQ7gRO7e6wx/936oXhNjrO', b'$2b$04$pQ7gRO7e6wx/936oXhNjrOUNOHL1D0h1N2IDbJZYs.1ppzSof6SPy'), (b'xVQVbwa1S0M8r', b'$2b$04$SQe9knOzepOVKoYXo9xTte', b'$2b$04$SQe9knOzepOVKoYXo9xTteNYr6MBwVz4tpriJVe3PNgYufGIsgKcW'), (b'Zfgr26LWd22Za', b'$2b$04$eH8zX.q5Q.j2hO1NkVYJQO', b'$2b$04$eH8zX.q5Q.j2hO1NkVYJQOM6KxntS/ow3.YzVmFrE4t//CoF4fvne'), (b'Tg4daC27epFBE', b'$2b$04$ahiTdwRXpUG2JLRcIznxc.', b'$2b$04$ahiTdwRXpUG2JLRcIznxc.s1.ydaPGD372bsGs8NqyYjLY1inG5n2'), (b'xhQPMmwh5ALzW', b'$2b$04$nQn78dV0hGHf5wUBe0zOFu', b'$2b$04$nQn78dV0hGHf5wUBe0zOFu8n07ZbWWOKoGasZKRspZxtt.vBRNMIy'), (b'59je8h5Gj71tg', b'$2b$04$cvXudZ5ugTg95W.rOjMITu', b'$2b$04$cvXudZ5ugTg95W.rOjMITuM1jC0piCl3zF5cmGhzCibHZrNHkmckG'), (b'wT4fHJa2N9WSW', b'$2b$04$YYjtiq4Uh88yUsExO0RNTu', b'$2b$04$YYjtiq4Uh88yUsExO0RNTuEJ.tZlsONac16A8OcLHleWFjVawfGvO'), (b'uSgFRnQdOgm4S', b'$2b$04$WLTjgY/pZSyqX/fbMbJzf.', b'$2b$04$WLTjgY/pZSyqX/fbMbJzf.qxCeTMQOzgL.CimRjMHtMxd/VGKojMu'), (b'tEPtJZXur16Vg', b'$2b$04$2moPs/x/wnCfeQ5pCheMcu', b'$2b$04$2moPs/x/wnCfeQ5pCheMcuSJQ/KYjOZG780UjA/SiR.KsYWNrC7SG'), (b'vvho8C6nlVf9K', b'$2b$04$HrEYC/AQ2HS77G78cQDZQ.', b'$2b$04$HrEYC/AQ2HS77G78cQDZQ.r44WGcruKw03KHlnp71yVQEwpsi3xl2'), (b'5auCCY9by0Ruf', b'$2b$04$vVYgSTfB8KVbmhbZE/k3R.', b'$2b$04$vVYgSTfB8KVbmhbZE/k3R.ux9A0lJUM4CZwCkHI9fifke2.rTF7MG'), (b'GtTkR6qn2QOZW', b'$2b$04$JfoNrR8.doieoI8..F.C1O', b'$2b$04$JfoNrR8.doieoI8..F.C1OQgwE3uTeuardy6lw0AjALUzOARoyf2m'), (b'zKo8vdFSnjX0f', b'$2b$04$HP3I0PUs7KBEzMBNFw7o3O', b'$2b$04$HP3I0PUs7KBEzMBNFw7o3O7f/uxaZU7aaDot1quHMgB2yrwBXsgyy'), (b'I9VfYlacJiwiK', b'$2b$04$xnFVhJsTzsFBTeP3PpgbMe', b'$2b$04$xnFVhJsTzsFBTeP3PpgbMeMREb6rdKV9faW54Sx.yg9plf4jY8qT6'), (b'VFPO7YXnHQbQO', b'$2b$04$WQp9.igoLqVr6Qk70mz6xu', b'$2b$04$WQp9.igoLqVr6Qk70mz6xuRxE0RttVXXdukpR9N54x17ecad34ZF6'), (b'VDx5BdxfxstYk', b'$2b$04$xgZtlonpAHSU/njOCdKztO', b'$2b$04$xgZtlonpAHSU/njOCdKztOPuPFzCNVpB4LGicO4/OGgHv.uKHkwsS'), (b'dEe6XfVGrrfSH', b'$2b$04$2Siw3Nv3Q/gTOIPetAyPr.', b'$2b$04$2Siw3Nv3Q/gTOIPetAyPr.GNj3aO0lb1E5E9UumYGKjP9BYqlNWJe'), (b'cTT0EAFdwJiLn', b'$2b$04$7/Qj7Kd8BcSahPO4khB8me', b'$2b$04$7/Qj7Kd8BcSahPO4khB8me4ssDJCW3r4OGYqPF87jxtrSyPj5cS5m'), (b'J8eHUDuxBB520', b'$2b$04$VvlCUKbTMjaxaYJ.k5juoe', b'$2b$04$VvlCUKbTMjaxaYJ.k5juoecpG/7IzcH1AkmqKi.lIZMVIOLClWAk.'), (b'U*U', b'$2a$05$CCCCCCCCCCCCCCCCCCCCC.', b'$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW'), (b'U*U*', b'$2a$05$CCCCCCCCCCCCCCCCCCCCC.', b'$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK'), (b'U*U*U', b'$2a$05$XXXXXXXXXXXXXXXXXXXXXO', b'$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a'), (b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', b'$2a$05$abcdefghijklmnopqrstuu', b'$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui'), (b'\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa', b'$2a$05$/OK.fbVrR/bpIqNJ5ianF.', b'$2a$05$/OK.fbVrR/bpIqNJ5ianF.swQOIzjOiJ9GHEPuhEkvqrUyvWhEMx6'), (b'\xa3', b'$2a$05$/OK.fbVrR/bpIqNJ5ianF.', b'$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq')] |
question_data = [
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "In the 1988 film "Akira", Tetsuo ends up destroying Tokyo.",
"correct_answer": "True",
"incorrect_answers": [
"False"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "Studio Ghibli is a Japanese animation studio responsible for the films "Wolf Children" and "The Boy and the Beast".",
"correct_answer": "False",
"incorrect_answers": [
"True"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "In Kill La Kill, the weapon of the main protagonist is a katana. ",
"correct_answer": "False",
"incorrect_answers": [
"True"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "No Game No Life first aired in 2014.",
"correct_answer": "True",
"incorrect_answers": [
"False"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "In the "Melancholy of Haruhi Suzumiya" series, the narrator goes by the nickname Kyon.",
"correct_answer": "True",
"incorrect_answers": [
"False"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "In Pokémon, Ash's Pikachu refuses to go into a pokeball.",
"correct_answer": "True",
"incorrect_answers": [
"False"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "In the "Toaru Kagaku no Railgun" anime, espers can only reach a maximum of level 6 in their abilities.",
"correct_answer": "False",
"incorrect_answers": [
"True"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "Kiznaiver is an adaptation of a manga.",
"correct_answer": "False",
"incorrect_answers": [
"True"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "In the "To Love-Ru" series, Golden Darkness is sent to kill Lala Deviluke.",
"correct_answer": "False",
"incorrect_answers": [
"True"
]
},
{
"category": "Entertainment: Japanese Anime & Manga",
"type": "boolean",
"difficulty": "easy",
"question": "In Chobits, Hideki found Chii in his apartment.",
"correct_answer": "False",
"incorrect_answers": [
"True"
]
}
]
| question_data = [{'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'In the 1988 film "Akira", Tetsuo ends up destroying Tokyo.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'Studio Ghibli is a Japanese animation studio responsible for the films "Wolf Children" and "The Boy and the Beast".', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'In Kill La Kill, the weapon of the main protagonist is a katana. ', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'No Game No Life first aired in 2014.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'In the "Melancholy of Haruhi Suzumiya" series, the narrator goes by the nickname Kyon.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'In Pokémon, Ash's Pikachu refuses to go into a pokeball.', 'correct_answer': 'True', 'incorrect_answers': ['False']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'In the "Toaru Kagaku no Railgun" anime, espers can only reach a maximum of level 6 in their abilities.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'Kiznaiver is an adaptation of a manga.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'In the "To Love-Ru" series, Golden Darkness is sent to kill Lala Deviluke.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Entertainment: Japanese Anime & Manga', 'type': 'boolean', 'difficulty': 'easy', 'question': 'In Chobits, Hideki found Chii in his apartment.', 'correct_answer': 'False', 'incorrect_answers': ['True']}] |
class EOLError(ValueError):
""" Signals that the buffer is reading after the end of a line."""
class EOFError(ValueError):
""" Signals that the buffer is reading after the end of the text."""
class TextBuffer:
def __init__(self, text=None):
self.load(text)
def reset(self):
self.line = 0
self.column = 0
def load(self, text):
self.text = text
self.lines = text.split('\n') if text else []
self.reset()
@property
def current_line(self):
try:
return self.lines[self.line]
except IndexError:
raise EOFError(
"EOF reading line {}".format(self.line)
)
@property
def current_char(self):
try:
return self.current_line[self.column]
except IndexError:
raise EOLError(
"EOL reading column {} at line {}".format(
self.column, self.line
)
)
@property
def next_char(self):
try:
return self.current_line[self.column + 1]
except IndexError:
raise EOLError(
"EOL reading column {} at line {}".format(
self.column, self.line
)
)
@property
def tail(self):
return self.current_line[self.column:]
@property
def position(self):
return (self.line, self.column)
def newline(self):
self.line += 1
self.column = 0
def skip(self, steps=1):
self.column += steps
def goto(self, line, column=0):
self.line, self.column = line, column
| class Eolerror(ValueError):
""" Signals that the buffer is reading after the end of a line."""
class Eoferror(ValueError):
""" Signals that the buffer is reading after the end of the text."""
class Textbuffer:
def __init__(self, text=None):
self.load(text)
def reset(self):
self.line = 0
self.column = 0
def load(self, text):
self.text = text
self.lines = text.split('\n') if text else []
self.reset()
@property
def current_line(self):
try:
return self.lines[self.line]
except IndexError:
raise eof_error('EOF reading line {}'.format(self.line))
@property
def current_char(self):
try:
return self.current_line[self.column]
except IndexError:
raise eol_error('EOL reading column {} at line {}'.format(self.column, self.line))
@property
def next_char(self):
try:
return self.current_line[self.column + 1]
except IndexError:
raise eol_error('EOL reading column {} at line {}'.format(self.column, self.line))
@property
def tail(self):
return self.current_line[self.column:]
@property
def position(self):
return (self.line, self.column)
def newline(self):
self.line += 1
self.column = 0
def skip(self, steps=1):
self.column += steps
def goto(self, line, column=0):
(self.line, self.column) = (line, column) |
def do_helm(s):
if not s.command_available('helm'):
# https://docs.helm.sh/using_helm/#installing-the-helm-client
s.send('curl https://raw.githubusercontent.com/helm/helm/master/scripts/get | bash')
s.send('helm init')
s.send('kubectl get pods --namespace kube-system')
| def do_helm(s):
if not s.command_available('helm'):
s.send('curl https://raw.githubusercontent.com/helm/helm/master/scripts/get | bash')
s.send('helm init')
s.send('kubectl get pods --namespace kube-system') |
tuplas=("inacio","python","udemy")
print(tuplas)
print(tuplas[0])
print(tuplas[1])
print(tuplas[2])
print(tuplas[0:2])
print(tuplas+tuplas)
print(tuplas*5)
print(4 in tuplas)
print("udemy" in tuplas)
lista=[1,2,4,"inacio"]
print(lista)
tuplas2=lista
print(tuplas2)
| tuplas = ('inacio', 'python', 'udemy')
print(tuplas)
print(tuplas[0])
print(tuplas[1])
print(tuplas[2])
print(tuplas[0:2])
print(tuplas + tuplas)
print(tuplas * 5)
print(4 in tuplas)
print('udemy' in tuplas)
lista = [1, 2, 4, 'inacio']
print(lista)
tuplas2 = lista
print(tuplas2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.