content stringlengths 7 1.05M |
|---|
'''
This module defines the RentalException class, which handles all exception of the type RentalException.
it does not depend on any other module.
'''
class RentalException(Exception):
'''
RentalException class handles all thrown exceptions of the type RentalException. It inherits the Exception
class.
'''
def __init__(self, message):
self._message = message
def __repr__(self, *args, **kwargs):
return "Error! " + self._message
|
"""
handler.py
A two operands handler.
"""
class Handler():
def handle(self, expression):
operator = None
operand_1 = None
operand_2 = None
error = None
try:
tokens = expression.split(" ")
operator = tokens[1]
operand_1 = int(tokens[0])
operand_2 = int(tokens[2])
except Exception as exception:
error = "Invalid expression"
return operator, operand_1, operand_2, error
|
def spd_pgs_limit_range(data, phi=None, theta=None, energy=None):
"""
Applies phi, theta, and energy limits to data structure(s) by
turning off the corresponding bin flags.
Input:
data: dict
Particle data structure
Parameters:
phi: np.ndarray
Minimum and maximum values for phi
theta: np.ndarray
Minimum and maximum values for theta
energy: np.ndarray
Minimum and maximum values for energy
Returns:
Data structure with limits applied (to the bins array)
"""
# if no limits are set, return the input data
if energy is None and theta is None and phi is None:
return data
# apply the phi limits
if phi is not None:
# get min/max phi values for all bins
phi_min = data['phi'] - 0.5*data['dphi']
phi_max = data['phi'] + 0.5*data['dphi'] % 360
# wrap negative values
phi_min[phi_min < 0.0] += 360
# the code below and the phi spectrogram code
# assume maximums at 360 are not wrapped to 0
phi_max[phi_max == 0.0] = 360.0
# find which bins were wrapped back into [0, 360]
wrapped = phi_min > phi_max
# determine which bins intersect the specified range
if phi[0] > phi[1]:
in_range = phi_min < phi[1] or phi_max > phi[0] or wrapped
else:
in_range = ((phi_min < phi[1]) & (phi_max > phi[0])) | (wrapped & ((phi_min < phi[1]) | (phi_max > phi[0])))
data['bins'][in_range == False] = 0
# apply the theta limits
if theta is not None:
lower_theta = min(theta)
upper_theta = max(theta)
# get min/max angle theta values for all bins
theta_min = data['theta'] - 0.5*data['dtheta']
theta_max = data['theta'] + 0.5*data['dtheta']
in_range = (theta_min < upper_theta) & (theta_max > lower_theta)
data['bins'][in_range == False] = 0
# apply the energy limits
if energy is not None:
data['bins'][data['energy'] < energy[0]] = 0
data['bins'][data['energy'] > energy[1]] = 0
return data |
class Solution:
def XXX(self, x: int) -> int:
start = 0
end = x
while True:
mid = int((start + end) / 2)
if mid * mid <= x < (mid + 1) * (mid + 1):
return mid
if mid * mid > x: # 偏大
end = mid - 1
else:
start = mid + 1
|
palavras = ('abacate', 'abacaxi', 'suco', 'melancia', 'limão', 'manga',
'pastel', 'pizza', 'chocolate', 'pao')
for i in palavras:
print(f'\nNa palavra {i.upper()} temos ', end='')
for letra in i:
if letra.lower() in 'aeiou':
print(letra, end=' ')
|
#O código a seguir percorre uma lista de nomes de carros em um laço e procura o valor 'bmw'. Sempre que o valor for 'bmw', ele será exibido com letras
#maiusculas, e não somente a inicial maiuscula.
requested_topping = ['mushrooms', 'extra cheese', 'green peppers']
if 'mushrooms' in requested_topping:
print('Adding mushrooms.')
if 'pepperoni' in requested_topping:
print('Adding pepperoni.')
if 'extra cheese' in requested_topping:
print('Adding extra cheese.')
print("\nFished making your pizza!")
|
class Loss(object):
def __init__(self):
self.output = 0
self.input = 0
def get_output(self, inp, target):
pass
def get_input_gradient(self, target):
pass
|
#Given two arrays, write a function to compute their intersection.
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
l=[]
for i in nums1:
if i in nums2:
l.append(i)
return list(set(l)) |
"""
Module for YamlTemplateFieldBuilder
"""
__author__ = 'DWI'
class TemplateReader(object):
"""
Class for reading complete Templates from files.
"""
def __init__(self, template_field_builder):
self.field_builder = template_field_builder
def read(self, file_name):
"""
Reads the given file and returns a template object
:param file_name: name of the template file
:return: the template that was created
"""
with open(file_name, 'r') as file:
data = self._load_data(file)
return self._build_template(data)
def _load_data(self, file):
pass
def _build_template(self, template_data):
pass
def _load_background_image(self,file_name):
"""
Reads the background image from the given file
:param file_name: name of the file to read the data from
:return: the content of the file as string
"""
try:
with open(file_name, "r") as file:
return file.read()
except FileNotFoundError:
return None |
#!/user/bin/python
'''Compute the Edit Distance Between Two Strings
The edit-distance between two strings is the minimum number of operations
(insertions, deletions, and substitutions of symbols) to transform one string
into another
'''
# Uses python3
def edit_distance(s, t):
#D[i,0] = i
#D[0,j] = j
m = len(s)
n = len(t)
d = []
for i in range(len(s) + 1):
d.append([i])
del d[0][0]
for j in range(len(t) + 1):
d[0].append(j)
for j in range(1, len(t)+1):
for i in range(1, len(s)+1):
insertion = d[i][j-1] + 1
deletion = d[i-1][j] + 1
match = d[i-1][j-1]
mismatch = d[i-1][j-1] + 1
if s[i-1] == t[j-1]:
d[i].insert(j, match)
else:
minimum = min(insertion, deletion, mismatch)
d[i].insert(j, minimum)
editDist = d[-1][-1]
return editDist
if __name__ == "__main__":
print(edit_distance(input(), input()))
|
class iron():
def __init__(self,name,kg):
self.kg = kg
self.name = name
def changeKg(self,newValue):
self.kg = newValue
def changeName(self,newName):
self.newName
|
def calculate_power(base, power):
if not power:
return 1
if not power % 2:
return calculate_power(base, power // 2) * calculate_power(base, power // 2)
else:
return calculate_power(base, power // 2) * calculate_power(base, power // 2) * base
if __name__ == "__main__":
a = int(input("Enter base: "))
n = int(input("Enter exponent: "))
print("{}^{} = {}".format(a, n, calculate_power(a, n))) |
class Node:
def __init__(self, data, nextNode=None):
self.data = data
self.next = nextNode
# find middle uses a slow pointer and fast pointer (1 ahead) to find the middle
# element of a singly linked list
def find_middle(self):
slow_pointer = self
fast_pointer = self
while fast_pointer.next and fast_pointer.next.next:
slow_pointer = slow_pointer.next
fast_pointer = fast_pointer.next.next
return slow_pointer.data
# test find_middle function
n6 = Node(7)
n5 = Node(6, n6)
n4 = Node(5, n5)
n3 = Node(4, n4)
n2 = Node(3, n3)
n1 = Node(2, n2)
head = Node(1, n1)
middle = head.find_middle()
print("Linked List: ", "1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7")
print("Middle Node: ", middle)
|
def extract_cfg(cfg, prefix, sep='.'):
out = {}
for key,val in cfg.items():
if not key.startswith(prefix): continue
key = key[len(prefix)+len(sep):]
if sep in key or not key: continue
out[key] = val
return out
if __name__=="__main__":
cfg = {
'a.1':'aaa',
'a.2':'bbb',
'a.x.1':'ccc',
'a.x.2':'ddd',
'b.x':'eee',
}
print(extract_cfg(cfg,'a.x'))
|
'''
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
# if not inorder or not postorder:
# return None
if inorder:
ind = inorder.index(postorder.pop())
root = TreeNode(inorder[ind])
root.right = self.buildTree(inorder[ind+1:], postorder)
root.left = self.buildTree(inorder[0:ind], postorder)
return root |
# -*- coding: utf-8 -*-
def get_tokens(line):
"""tokenize an Epanet line (i.e. split words; stopping when ; encountered)"""
tokens=list()
words=line.split()
for word in words:
if word[:1] == ';':
break
else:
tokens.append(word)
return tokens
def read_epanet_file(filename):
"""read ressources from a epanet input file"""
pipes = None;
tanks = None;
valves = None;
junctions = None;
reservoirs = None;
# EPANET file format is documented here :
# https://github.com/OpenWaterAnalytics/EPANET/wiki/Input-File-Format
#
# EPANET parser
# https://github.com/OpenWaterAnalytics/EPANET/blob/master/src/input3.c
line_number = 0
section = None
with open(filename, "r") as input_file:
for line in input_file:
line_number += 1
tokens = get_tokens(line)
if len(tokens) > 0:
if tokens[0][:1] == '[':
# section keyword, check that it ends with a ']'
if tokens[0][-1:] == ']':
section = tokens[0]
if tokens[0] == '[JUNCTIONS]':
if junctions is None:
junctions = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
elif tokens[0] == '[PIPES]':
if pipes is None:
pipes = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
elif tokens[0] == '[TANKS]':
if tanks is None:
tanks = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
elif tokens[0] == '[RESERVOIRS]':
if reservoirs is None:
reservoirs = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
elif tokens[0] == '[VALVES]':
if valves is None:
valves = dict()
else:
print("WARNING duplicated section at line {} : {}".format(line_number, line))
else:
print("ERROR invalid section name at line {} : {}".format(line_number, line))
else:
# in section line
if section is None:
print("WARNING lines before any section at line {} : {}".format(line_number, line))
elif section == '[JUNCTIONS]':
pass
elif section == '[PIPES]':
if tokens[0] not in pipes:
# from EPANET file format and parser implementation
# extract pipe status or use default value otherwise
status = None
if len(tokens) == 6:
# no optional status, status is Open per default
status = 'Open'
elif len(tokens) == 7:
# optional status
status = tokens[-1]
elif len(tokens) == 8:
# optional minor loss and optional status
status = tokens[-1]
# sanity check on pipe status
if status == 'Open':
pass
elif status == 'Closed':
pass
elif status == 'CV':
pass
else:
status = None
if status is None:
print("ERROR invalid pipe format line {} : {}".format(line_number, line))
else:
# ignore status for now, to be checked with Professor
status = 'Open'
pipes[tokens[0]] = (tokens[1], tokens[2], status)
else:
# sanity check
print("duplicated pipes {}".format(tokens[0]))
elif section == '[VALVES]':
if tokens[0] not in valves:
valves[tokens[0]] = (tokens[1], tokens[2])
else:
# sanity check
print("duplicated valves {}".format(tokens[0]))
elif section == '[TANKS]':
if tokens[0] not in tanks:
tanks[tokens[0]] = None
else:
# sanity check
print("duplicated tanks {}".format(tokens[0]))
elif section == '[RESERVOIRS]':
if tokens[0] not in reservoirs:
reservoirs[tokens[0]] = None
else:
# sanity check
print("duplicated reservoirs {}".format(tokens[0]))
else:
# kind of section not handled
pass
resources = dict()
resources["pipes"] = pipes
resources["valves"] = valves
resources["reservoirs"] = reservoirs
resources["tanks"] = tanks
resources["junctions"] = junctions
return resources
|
class SmMarket:
def __init__(self):
self.name = ""
self.product_dic = {}
def add_category(self, product):
self.product_dic[product.code] = product |
#project
print("welcome to the Band name generator")
city_name = input("Enter the city you were born: ")
pet_name = input("Enter your pet name: ")
print(f"your band name could be {city_name} {pet_name}")
#coding exercise(Print)
print("Day 1 - Python Print Function")
print("The function is declared like this:")
print("print(\"what to print\")")
#coding exercise(Print with new line)
print('Day 1 - String Manipulation\nString Concatenation is done with the "+" sign.\ne.g. print("Hello " + "world")\nNew lines can be created with a backslash and n.')
#coding exercise with len,input and print function
print(len(input("What is your name?\n")))
#coding exercise for swapping numbers(variables)
a = input("a: ")
b = input("b: ")
a,b = b,a
print("a: ",a)
print("b: ",b)
|
"""
signals we use to trigger regular batch jobs
"""
run_hourly_jobs = object()
run_daily_jobs = object()
run_weekly_jobs = object()
run_monthly_jobs = object()
|
num1=int(input("Enter first number :- "))
num2=int(input("Enter second number :- "))
print("Which opertation you want apply 1.add, 2.sub, 3.div")
op=input()
def add():
c=num1+num2
print("After Add",c)
def sub():
c=num1-num2
print("After sub",c)
def div():
c=num1/num2
print("After div",c)
def again():
print("If you want to perform any other operation")
print("say Yes or y else NO or n")
ans=input()
if ans=="yes" or ans=="y":
cal()
else:
print(" Good Bye")
def cal():
if op=='1' or op=="add" or op=="1.add":
add()
elif op=='2' or op=="sub" or op=="2.sub":
sub()
elif op=='3' or op=="div" or op=="3.div":
div()
else:
print("Invalid Operation")
again()
cal()
again()
|
def get_odd_and_even_sets(n):
odd_nums = set()
even_nums = set()
for line in range(1, n + 1):
name = input()
name_ascii_sum = sum([ord(char) for char in name])
devised_num = name_ascii_sum // line
if devised_num % 2 == 0:
even_nums.add(devised_num)
else:
odd_nums.add(devised_num)
return odd_nums, even_nums
def print_result(odd_nums_sum, even_nums_sum, odd_nums, even_nums):
if odd_nums_sum == even_nums_sum:
union_values = odd_nums.union(even_nums)
print(', '.join(map(str, union_values)))
elif odd_nums_sum > even_nums_sum:
different_values = odd_nums.difference(even_nums)
print(', '.join(map(str, different_values)))
else:
symmetric_different_values = even_nums.symmetric_difference(odd_nums)
print(', '.join(map(str, symmetric_different_values)))
odd_nums, even_nums = get_odd_and_even_sets(int(input()))
odd_nums_sum = sum(odd_nums)
even_nums_sum = sum(even_nums)
print_result(odd_nums_sum, even_nums_sum, odd_nums, even_nums)
|
# crie um algoritmo que leia um número e mostre
# o seu dobro, triplo e sua raiz quadrada.
num = int(input('Digite um número: '))
dobro = num * 2
triplo = num * 3
raizq = num ** (1/2)
print('O dobro de {} é igual a {}.'.format(num, dobro))
print('O triplo de {} é igual a {}.'.format(num, triplo))
print('A raiz quadrada de {} é igual a {:.2f}.'.format(num, raizq))
|
class Debugger:
def __init__(self):
self.collectors = {}
def add_collector(self, collector):
self.collectors.update({collector.name: collector})
return self
def get_collector(self, name):
return self.collectors[name]
|
frutas = open('frutas.txt', 'r')
numeros = open('numeros.txt', 'r')
def copia_lista(lista:list)->list:
return lista.copy()
"""
if __name__ == "__main__":
lista_fruta_nueva=eliminar_un_caracter_de_toda_la_lista(lista_frutas,"\n")
print(lista_fruta_nueva)
""" |
users = [['896675','123','985'],['Gil','João', 'Maria']]
i = input('Digite sua senha: ')
while i not in users[0]:
i = str(input('Senha incorreta! \nDigite sua senha:'))
j = users[0].index(i)
name = users[1][j]
print('Acesso permitido. Bem-vindo %s' % (name))
|
# Only these modalities are available for query
ALLOWED_MODALITIES = ['bold', 'T1w', 'T2w']
STRUCTURAL_MODALITIES = ['T1w', 'T2w']
# Name of a subdirectory to hold fetched query results
FETCHED_DIR = 'fetched'
# Name of a subdirectory containing MRIQC group results used as inputs.
INPUTS_DIR = 'inputs'
# Name of the subdirectory which holds output reports.
REPORTS_DIR = 'reports'
# File extensions for report files and BIDS-compliant data files.
BIDS_DATA_EXT = '.tsv'
PLOT_EXT = '.png'
REPORTS_EXT = '.html'
# Symbolic exit codes for various error exit scenarios
INPUT_FILE_EXIT_CODE = 10
OUTPUT_FILE_EXIT_CODE = 11
QUERY_FILE_EXIT_CODE = 12
FETCHED_DIR_EXIT_CODE = 20
INPUTS_DIR_EXIT_CODE = 21
REPORTS_DIR_EXIT_CODE = 22
NUM_RECS_EXIT_CODE = 30
|
"""
File IO
1.Create
-------------------
f = open('file_name.txt','w')
f.close()
-------------------
2.Write
-------------------
f = open('file_name.txt','w')
data = 'hi'
f.write(data)
f.close()
-------------------
3.Read
1) Readline
-------------------
f = open('file_name.txt','r')
line = f.readline()
print(line)
f.close()
-------------------
-------------------
f = open('file_name.txt','r')
while True:
line = f.readline()
if not line: break
print(line)
f.close
-------------------
---> if readline() has nothing to read, it returns ''(False).
2) Readlines
3) Read
4. Add new data
1) with mode 'a'
-------------------
f = open('file_name.txt','a')
data = 'hi'
f.write(data)
f.close()
-------------------
5. With : autoclose
-------------------
f = open('file_name.txt','w')
f.write('SNP what you want to SNP')
f.close
-------------------
equals to
-------------------
with open('file_name.txt','w') as f:
f.write('SNP what you want to SNP')
-------------------
""" |
# Problem Statement: https://www.hackerrank.com/challenges/symmetric-difference/problem
_, M = int(input()), set(map(int, input().split()))
_, N = int(input()), set(map(int, input().split()))
print(*sorted(M ^ N), sep='\n') |
# The manage.py of the {{ project_name }} test project
# template context:
project_name = '{{ project_name }}'
project_directory = '{{ project_directory }}'
secret_key = '{{ secret_key }}'
|
class PaymentStrategy(object):
def get_payment_metadata(self,service_client):
pass
def get_price(self,service_client):
pass
|
#this program demonstrates several functions of the list class
x = [0.0, 3.0, 5.0, 2.5, 3.7]
print(type(x)) #prints datatype of x (list)
x.pop(2) #remove the 3rd element of x (5.0)
print(x)
x.remove(2.5) #remove the element 2.5 (index 2)
print(x)
x.append(1.2) #add a new element to the end (1.2)
print(x)
y = x.copy() #make a copy of x's current state (y)
print(y)
print(y.count(0.0)) #print the number of elements equal to 0.0 (1)
print(y.index(3.7)) #print the index of the element 3.7 (2)
y.sort() #sort the list y by value
print(y)
y.reverse() #reverse the order of elements in list y
print(y)
y.clear() #remove all elements from y
print(y) |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 22:08:00 2017
@author: Roberto Piga
"""
s = 'azcbobobegghakl'
s = 'abcbcd'
subString = ""
maxString = ""
charval = ""
for char in s:
if char >= charval:
subString += char
elif char < charval:
subString = char
charval = char
if len(subString) > len(maxString):
maxString = subString
print("Longest substring in alphabetical order is:", maxString)
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
size = int(input())
nums = list(map(int, input().split()))
weights = list(map(int, input().split()))
weighted_sum = 0
for i in range(size):
weighted_sum += nums[i] * weights[i]
print(round(weighted_sum / sum(weights), 1))
|
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0]) if m else 0
if m * n == 0:
return False
if target < matrix[0][0] or target > matrix[-1][-1]:
return False
i = 0
j = len(matrix) - 1
if target>=matrix[-1][0]:
return self.searchList(matrix[-1], target)
while i < j - 1:
mid = (i + j) // 2
if matrix[mid][0] == target:
return True
if matrix[mid][0] < target:
i = mid
else:
j = mid
return self.searchList(matrix[i], target)
def searchList(self, l, t):
i = 0
j = len(l) - 1
while i <= j:
m = (i + j) // 2
if l[m] == t:
return True
if l[m] > t:
j = m - 1
else:
i = m + 1
return False
|
# Lower-level functionality for build config.
# The functions in this file might be referred by tensorflow.bzl. They have to
# be separate to avoid cyclic references.
WITH_XLA_SUPPORT = True
def tf_cuda_tests_tags():
return ["local"]
def tf_sycl_tests_tags():
return ["local"]
def tf_additional_plugin_deps():
deps = []
if WITH_XLA_SUPPORT:
deps.append("//tensorflow/compiler/jit")
return deps
def tf_additional_xla_deps_py():
return []
def tf_additional_license_deps():
licenses = []
if WITH_XLA_SUPPORT:
licenses.append("@llvm//:LICENSE.TXT")
return licenses
|
# Write a function that takes a string as input and reverse only the vowels of a string.
# Example 1:
# Input: "hello"
# Output: "holle"
# Example 2:
# Input: "leetcode"
# Output: "leotcede"
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
dic = {"a", "e", "i", "o", "u", "A", "E","I","O","U"}
string = list(s)
i,j = 0, len(string) - 1
while i < j:
while i < j and string[i] not in dic:
i += 1
while i < j and string[j] not in dic:
j -= 1
string[i], string[j] = string[j], string[i]
i += 1
j -= 1
return "".join(string)
# Time: O(n)
# Space: O(n)
# Difficulty: easy |
def estimation(text,img_num):
len_text = len(text)
read_time = (len_text/1000) + img_num*0.2
if read_time < 1:
return 1
return round(read_time) |
numbers = [10, 20, 300, 40, 50]
# random indexing --> O(1) get items if we know the index !!!
print(numbers[4])
# it can store different data types
# numbers[1] = "Adam"
# iteration methods
# for i in range(len(numbers)):
# print(numbers[i])
# for num in numbers:
# print(num)
# remove last two items
print(numbers[:-2])
# show only first 2 items
print(numbers[0:2])
# show 3rd item onwards
print(numbers[2:])
# get the highest number in the array
# O(n) linear time complexity
# this type of search is slow on large array
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
print(maximum)
|
''' Example of python control structures '''
a = 5
b = int(input("Enter an integer: "))
# If-then-else statment
if a < b:
print('{} is less than {}'.format(a,b))
elif a > b:
print('{} is greater than {}'.format(a,b))
else:
print('{} is equal to {}'.format(a,b))
# While loop
ii = 0
print("While loop:")
while ii <= b:
print( "Your number = {}, loop variable = {}".format(b,ii))
ii+=1
# For loop
print("For loop:")
for ii in range(b):
print(" for: loop variable = {}".format(ii))
print("Iterate over a list:")
for ss in ['This is', 'a list', 'of strings']:
print(ss)
# break & continue
for ii in range(100000):
if ii > b:
print("Breaking at {}".format(ii))
break
print("Continue if not divisible by 3:")
for ii in range(b+1):
if not (ii % 3) == 0:
continue
print(" {}".format(ii))
|
"""
Calculating the mean
"""
def calculate_mean(numbers):
s=sum(numbers)
N=len(numbers)
mean=s/N
return mean
def main():
donations=[100,60,70,900,100,200,500,500,503,600,1000,1200]
mean=calculate_mean(donations)
N=len(donations)
print("Mean donation over the last {0} days is {1}".format(N,mean))
|
##############################################################################################################################################################################################
#
# ┌────────────────────────┐
# │ Experiment Memory Recovery v1.2 │
# │ Author: Christopher A Varnon │
# │ Created: July 2012, Updated: 11-23-2012 │
# │ File created with Python 3.1.1 │
# │ See end of file for terms of use. │
# └────────────────────────┘
#
##############################################################################################################################################################################################
def instructions():
print("This program can recover data from a memory file in three ways.\n")
print("1) The user can specify the values of a file through prompts")
print(" in the terminal.")
print(' Type "manualinput()" to enter information manually.\n')
print("2) The user can also provide an input settings file to process")
print(" several memory files quickly.")
print(' Type "fileinput()" to use an input settings file.')
print(' See the "InputSettingsFileTemplate.txt" file for')
print(" an example and instructions on using an input settings file.")
print(" The user will be prompted to provide information about the")
print(" settings, memory and data files.\n")
print("3) The user can also use an input settings while specifying")
print(" the files directly without the use of prompts.")
print(' Type "directfileinput(settingsfile,memoryfile,datafile)"')
print(" to use an input settings file while simultaneously providing")
print(" information about the files.")
print(' In place of the parameters "settingsfile, memoryfile,"')
print(" and datafile, enter the file names in quotes.")
print(' Example: directfileinput("settings.txt","memory.txt","data.csv")\n')
print("\n")
##############################################################################################################################################################################################
#
# ┌────────────────────────────────────────────────────────────────────────┐
# │ TERMS OF USE: MIT License │
# ├────────────────────────────────────────────────────────────────────────┤
# │Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation │
# │files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, │
# │modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software│
# │is furnished to do so, subject to the following conditions: │
# │ │
# │The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.│
# │ │
# │THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE │
# │WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR │
# │COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, │
# │ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │
# └────────────────────────────────────────────────────────────────────────┘
#
##############################################################################################################################################################################################
|
'''
Created on Apr 2, 2021
@author: mballance
'''
class InitializeReq(object):
def __init__(self):
self.module = None
self.entry = None
def dump(self):
pass
@staticmethod
def load(msg) -> 'InitializeReq':
ret = InitializeReq()
if "module" in msg.keys():
ret.module = msg["module"]
if "entry" in msg.keys():
ret.entry = msg["entry"]
return ret
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
ans = True
def traversal(node_p, node_q):
nonlocal ans
if node_p is None and node_q is None:
return
if node_p is None or node_q is None:
ans = False
return
if node_p.val != node_q.val:
ans = False
return
traversal(node_p.left, node_q.left)
traversal(node_p.right, node_q.right)
traversal(p, q)
return ans
|
input = [
input(),
]
def ceil(number: int) -> int:
return int(number) + 1 if number % 2 else 0
def get_possible_ways_amount(board_width: int, board_height: int) -> int:
"""
Функция находит количество способов пройти через доску, из левой нижней клетки доски до правой верхней
:param board_width: мультимножество чисел
:param board_height: мультимножество чисел
:return: число (int) - количество способов добраться конем до правого верхнего угла доски
"""
diagonals_dict: dict[str, list[int]] = generate_diagonals()
current_diagonal: list[int] = diagonals_dict.get(str(board_width + board_height))
if (not current_diagonal):
return 0
offset: int = abs(board_width - board_height) // 2
result_index: int = ceil(len(current_diagonal) / 2) - 1 + offset
if (result_index >= len(current_diagonal) or result_index < 0):
return 0
return current_diagonal[result_index]
def generate_diagonals():
"""
Cоздает словарь диагоналей на которые модет встать конь и массив с возможным количеством вариантов
дойти в кажду точку этой диагонали
:return: словарь - где ключ это число диагонали а значения, это список из
возможных способов добраться до точек на этой диагонали
"""
diagonals_dict: dict[str, list[int]] = {'2': [1]}
for diagonal_number in range(5, 50, 3):
prev_list: dict[str, list[int]] = diagonals_dict[str(diagonal_number - 3)]
new_list: list[int] = []
for i in range(0, len(prev_list) - 1, 1):
new_list.append(prev_list[i] + prev_list[i + 1])
diagonals_dict[str(diagonal_number)] = [1] + new_list + [1]
return diagonals_dict
# предпологаем, что все данные вводятся корректно, поэтому проверять их не будем
board_width, board_height = list(map(int, input[0].split(' ')))
print(get_possible_ways_amount(board_width, board_height))
|
'''Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:'''
x = y = z = "Orange"
print(x)
print(y)
print(z) |
sisend=input("Sisestage failinimi: ")
haali={}
parim={}
f=open(sisend, encoding="UTF-8")
f.readline()
for rida in f:
erakond, haaled, nr, nimi=rida.split(",")
if erakond not in haali or int(haaled)>haali[erakond]:
haali[erakond]=int(haaled)
parim[erakond]=nimi.strip()
f.close()
for erakond in haali:
print(parim[erakond]+" ("+erakond+") - "+str(haali[erakond])+" häält")
|
#
# @lc app=leetcode id=795 lang=python3
#
# [795] Number of Subarrays with Bounded Maximum
#
# https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/
#
# algorithms
# Medium (48.43%)
# Likes: 1143
# Dislikes: 78
# Total Accepted: 40.2K
# Total Submissions: 77.7K
# Testcase Example: '[2,1,4,3]\n2\n3'
#
# We are given an array nums of positive integers, and two positive integers
# left and right (left <= right).
#
# Return the number of (contiguous, non-empty) subarrays such that the value of
# the maximum array element in that subarray is at least left and at most
# right.
#
#
# Example:
# Input:
# nums = [2, 1, 4, 3]
# left = 2
# right = 3
# Output: 3
# Explanation: There are three subarrays that meet the requirements: [2], [2,
# 1], [3].
#
#
# Note:
#
#
# left, right, and nums[i] will be an integer in the range [0, 10^9].
# The length of nums will be in the range of [1, 50000].
#
#
#
# @lc code=start
class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
i = 0
curr = 0
res = 0
for j in range(len(nums)):
if left <= nums[j] <= right:
curr = j - i + 1
res += j - i + 1
elif nums[j] < left:
res += curr
else:
i = j + 1
curr = 0
return res
# @lc code=end
|
SYMBOLS = {',', '?', '!', ':', '\'', '"', '(', ')', ';', '@', '^', '^', '&', '&', '$', '$', '£',
'[', ']', '{', '}', '<', '>', '+', '-', "*", "#", "%", "=", "~", '/', "_"}
PREP = {'about', 'above', 'across', 'after', 'against', 'aka', 'along', 'and', 'anti', 'apart', 'around', 'as',
'astride', 'at', 'away', 'because', 'before', 'behind', 'below', 'beneath', 'beside', 'between', 'beyond',
'but', 'by', 'contra', 'down', 'due to', 'during', 'ex', 'except', 'excluding', 'following', 'for', 'from',
'given', 'in', 'including', 'inside', 'into', 'like', 'near', 'nearby', 'neath', 'of', 'off', 'on', 'onto',
'or', 'out', 'over', 'past', 'per', 'plus', 'since', 'so', 'than', 'though', 'through', 'til', 'to',
'toward', 'towards', 'under', 'underneath', 'versus', 'via', 'where', 'while', 'with', 'within', 'without',
'also'}
DET = {'a', 'an', 'the'}
NON_STOP_PUNCT = {',', ';'}
STOP_PUNCT = {'.', '?', '!'}
SENT_WORD = {'we', 'us', 'patient', 'denies', 'reveals', 'no', 'none', 'he', 'she', 'his', 'her', 'they', 'them', 'is',
'was', 'who', 'when', 'where', 'which', 'are', 'be', 'have', 'had', 'has', 'this', 'will', 'that', 'the',
'to', 'in', 'with', 'for', 'an', 'and', 'but', 'or', 'as', 'at', 'of', 'have', 'it', 'that', 'by', 'from',
'on', 'include', 'other', 'another'}
UNIT = {'mg', 'lb', 'kg', 'mm', 'cm', 'm', 'doz', 'am', 'pm', 'mph', 'oz', 'ml', 'l', 'mb', 'mmHg', 'min', 'cm2', 'm2', 'M2',
'mm2', 'mL', 'F', 'ppd', 'L', 'g', 'cc', "MG", "Munits", "pack", "mcg", "K", "hrs", "N", "inch", "d",
"AM", "PM", "HS", "QAM", "QPM", "BID", "mEq", "hr", "cGy", "mGy", "mLs", "mOsm"}
MIMICIII_DEID_PATTERN = "\[\*\*|\*\*\]"
NAME_PREFIX_SUFFIX = {
'Dr', 'Mr', 'Mrs', 'Jr', 'Ms', 'Prof'
}
PROFESSIONAL_TITLE = {
'M.D.', 'Ph.D.', 'Pharm.D.'
}
SPECIAL_ABBV = {
'e.c.', 'p.o.', 'b.i.d.', 'p.r.n.', 'i.v.', 'i.m.', 'b.i.d', 'p.r.n', 'i.m', 'i.v', 'p.o', 'd.o.b', 'vo.', 'm.o',
'r.i.', 'y.o.'
}
ROMAN_NUM = {
'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'
}
WHITE_LIST = {
'NaCl', 'KCl', 'HandiHaler', 'MetroCream', 'ChloraPrep', 'NovoLog', 'FlexPen', 'EpiPen', 'CellCept', 'iPad', 'eConsult', 'PreserVision'
} |
class Human:
def __init__(self, xref_id):
self.xref_id = xref_id
self.name = None
self.father = None
self.mother = None
self.pos = None
def __repr__(self):
return "[ {} : {} - {} {} - {} ]".format(
self.xref_id,
self.name,
self.father,
self.mother,
self.pos
)
|
class Cell:
def __init__(self, row, col):
self.row = row
self.col = col
self.links = []
self.north = None
self.south = None
self.east = None
self.west = None
def neighbors(self):
n = []
self.north and n.append(self.north)
self.south and n.append(self.south)
self.east and n.append(self.east)
self.west and n.append(self.west)
return n
def link(self, cell, bidirectional=True):
self.links.append(cell)
if bidirectional:
cell.link(self, False)
def unlink(self, cell, bidirectional=True):
self.links.remove(cell)
if bidirectional:
cell.unlink(self, False)
def isLinked(self, cell):
isLinked = True if cell in self.links else False
return isLinked
|
class Notifier(object):
def notify(self, title, message, retry_forever=False):
raise NotImplementedError()
def _resolve_params(self, title, message):
if callable(title):
title = title()
if callable(message):
message = message()
return title, message
|
n = int(input())
c=0
for _ in range(n):
p, q = list(map(int, input().split()))
if q-p >=2:
c= c+1
print(c)
|
class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
minNum,maxNum = min(nums),max(nums)
if maxNum-minNum>=2*k:
return maxNum-minNum-2*k
else:
return 0 |
class Base:
""" This is a class template. All the other classes will be made according to this templae """
def __init__(self) -> None:
""" constructor function """
pass
def enter(self, **param) -> None:
""" This function is called first when we change a group """
pass
def render(self) -> None:
""" This function will render all the current objects on the screen """
pass
def update(self, param) -> None:
""" This function will be called once per frame"""
pass
def leave(self) -> None:
""" This function will be called during changing state. It helps in leaving the current state """
pass |
# Q7: What is the time complexity of
# i = 1, 2, 4, 8, 16, ..., 2^k
# El bucle termina para: i >= n
# 2^k = n
# k = log_2(n)
# O(log_2(n))
# Algoritmo
# for (i = 1; i < n; i = i*2) {
# statement;
# }
i = 1
n = 10
while i < n:
print(i)
i = i*2 |
# https://www.programiz.com/python-programming/function-argument
# Python allows functions to be called using keyword arguments. When we call
# functions in this way, the order (position) of the arguments can be changed.
# As we can see, we can mix positional arguments with keyword arguments during
# a function call. But we must keep in mind that keyword arguments must follow
# positional arguments.
def greet(name, msg = "Good morning!"):
"""
This function greets to the person with the provided message.
If message is not provided, it defaults to "Good morning!"
"""
print("Hello", name + ', ' + msg)
greet(name = "Bruce", msg = "How do you do?")
greet(msg = "How do you do?", name = "Bruce")
greet("Bruce", msg = "How do you do?")
|
"""
Topological Sort
"""
class Solution(object):
def alienOrder(self, words):
#return true if cycles are detected.
def dfs(c):
if c in path: return True
if c in visited: return False
path.add(c)
for nei in adj[c]:
if dfs(nei): return True
res.append(c)
path.remove(c)
visited.add(c)
return False
#build adjacency list
adj = {c: set() for word in words for c in word}
for i in xrange(len(words)-1):
w1, w2 = words[i], words[i+1]
minLen = min(len(w1), len(w2))
if w1[:minLen]==w2[:minLen] and len(w1)>len(w2): return ""
for j in xrange(minLen):
if w1[j]!=w2[j]:
adj[w1[j]].add(w2[j])
break
#topological sort
path = set() #path currently being reversed
visited = set() #done processing
res = []
for c in adj:
if dfs(c): return ""
return "".join(reversed(res)) |
code_map = {
"YEAR": "year",
"MALE": "male population",
"FEMALE": "female population",
"M_MALE": "matable male population",
"M_FEMALE": "matable female population",
"C_PROB": "concieving probability",
"M_AGE_START": "starting age of mating",
"M_AGE_END": "ending age of mating",
"MX_AGE": "maximum age",
"MT_PROB": "mutation probability",
"OF_FACTOR": "offspring factor",
"AGE_DTH": "dependency of age on death",
"FIT_DTH": "dependency of fitness on death",
"AFR_DTH": "dependency ratio of age and fitness on death",
"HT_SP": "dependency of height on speed",
"HT_ST": "dependency of height on stamina",
"HT_VT": "dependency of height on vitality",
"WT_SP": "dependency of weight on speed",
"WT_ST": "dependency of weight on stamina",
"WT_VT": "dependency of weight on vitality",
"VT_AP": "dependency of vitality on appetite",
"VT_SP": "dependency of vitality on speed",
"ST_AP": "dependency of stamina on appetite",
"ST_SP": "dependency of stamina on speed",
"TMB_AP": "theoretical maximum base appetite",
"TMB_HT": "theoretical maximum base height",
"TMB_SP": "theoretical maximum base speed",
"TMB_ST": "theoretical maximum base stamina",
"TMB_VT": "theoretical maximum base vitality",
"TMB_WT": "theoretical maximum base appetite",
"TM_HT": "theoretical maximum height",
"TM_SP": "theoretical maximum speed",
"TM_WT": "theoretical maximum weight",
"TMM_HT": "theoretical maximum height multiplier",
"TMM_SP": "theoretical maximum speed multiplier",
"TMM_ST": "theoretical maximum stamina multiplier",
"TMM_VT": "theoretical maximum vitality multiplier",
"TMM_WT": "theoretical maximum weight multiplier",
"SL_FACTOR": "sleep restore factor",
"AVG_GEN": "average generation",
"AVG_IMM": "average immunity",
"AVG_AGE": "average age",
"AVG_HT": "average height",
"AVG_WT": "average weight",
"AVGMA_AP": "average maximum appetite",
"AVGMA_SP": "average maximum speed",
"AVGMA_ST": "average maximum stamina",
"AVGMA_VT": "average maximum vitality",
"AVG_SFIT": "average static fitness",
"AVG_DTHF": "average death factor",
"AVG_VIS": "average vision radius",
}
def title_case(s):
res = ''
for word in s.split(' '):
if word:
res += word[0].upper()
if len(word) > 1:
res += word[1:]
res += ' '
return res.strip()
def sentence_case(s):
res = ''
if s:
res += s[0].upper()
if len(s) > 1:
res += s[1:]
return res.strip() |
txt = "I like bananas"
x = txt.replace("bananas", "mangoes")
print(x)
txt = "one one was a race horse and two two was one too."
x = txt.replace("one", "three")
print(x)
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 1)
print(x)
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)
txt = "banana"
x = txt.center(15)
print(x)
txt = "banana"
x = txt.center(20, "/")
print(x)
txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)
txt = "Hello, And Welcome To My World!"
x = txt.upper()
print(x)
txt = "Company12"
x = txt.isalnum()
print(x)
txt = "Company!@#$"
x = txt.isalnum()
print(x)
txt = "welcome to the jungle"
x = txt.split()
print(x)
txt = "hello? my name is Peter? I am 26 years old"
x = txt.split("?")
print(x)
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
|
def partition_labels(string):
#
"""
"""
indices = {}
for i, char in enumerate(string):
indices[char] = i
result = []
left, right = -1, -1
for i, char in enumerate(string):
right = max(right, indices[char])
if i == right:
result.append(right - left)
left = i
return result
if __name__ == "__main__":
print(partition_labels("ababcbacadefegdehijhklij"))
|
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_index = -1
second_max_value = -1
for i in range(len(nums)):
if i == 0:
max_index = i
continue
value = nums[i]
if value > nums[max_index]:
value = nums[max_index]
max_index = i
if value > second_max_value:
second_max_value = value
if nums[max_index] >= (second_max_value * 2):
return max_index
else:
return -1
if __name__ == '__main__':
test_data1 = [3, 6, 1, 0]
test_data2 = [1, 2, 3, 4]
test_data3 = [2, 1]
test_data4 = [1, 2]
s = Solution()
print(s.dominantIndex(test_data1))
print(s.dominantIndex(test_data2))
print(s.dominantIndex(test_data3))
print(s.dominantIndex(test_data4))
|
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
# 0 -> 0 status = 0
# 1 -> 1 status = 1
# 1 -> 0 status = 2
# 0 -> 1 status = 3
m, n = len(board), len(board[0])
directions = [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
for x in range(m):
for y in range(n):
lives = 0
for dx, dy in directions:
nx = x + dx
ny = y + dy
if 0<=nx<m and 0<=ny<n and (board[nx][ny] == 1 or board[nx][ny] == 2) :
lives+=1
if board[x][y] == 0 and lives==3: # rule 4
board[x][y] = 3
elif board[x][y] == 1 and (lives<2 or lives>3):
board[x][y] = 2
for x in range(m):
for y in range(n):
board[x][y] = board[x][y]%2
return board |
def calc(x,y,ops):
if ops not in "+-*/":
return "only +-*/!!!!!"
if ops=="+":
return (str(x) +""+ ops +str(y)+"="+str(x+y))
elif ops=="-":
return (str(x) +""+ ops +str(y)+"="+str(x-y))
elif ops == "*":
return (str(x) + "" + ops + str(y) + "=" + str(x * y))
elif ops == "/":
return (str(x) + "" + ops + str(y) + "=" + str(x / y))
while True:
x=int(input("please enter first number"))
y=int(input("please enter second number"))
ops=input("choose between +,-,*,/")
print(calc(x,y,ops))
|
n = int(input())
length = 0
while True:
length += 1
n //= 10
if n == 0:
break
print('Length is', length)
|
''' '+' Plus Operator shows polymorphism. It is overloaded to perform multiple things, so we can call it polymorphic. '''
x = 10
y = 20
print(x+y)
s1 = 'Hello'
s2 = " How are you?"
print(s1+s2)
l1 = [1,2,3]
l2 = [4,5,6]
print(l1+l2)
|
# Exercício Python 38: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre:
#A) quantas pessoas tem mais de 18 anos.
#B) quantos homens foram cadastrados.
#C) quantas mulheres tem menos de 20 anos.
print('CADASTRE UM USUÁRIO:')
idade = int(input('Insira a idade: '))
sexo = input('Insira o sexo [Homem/Mulher]: ').lower()
cont_idade = homem = mulher_20 = 0
while True:
if idade > 18:
cont_idade += 1
if sexo == 'homem':
homem += 1
if idade < 20 and sexo == 'mulher':
mulher_20 += 1
n = int(input('Digite [1] para Cadastrar mais pessoas e [0] para Sair: '))
if n == 1:
idade = int(input('Insira a idade: '))
sexo = input('Insira o sexo [Homem/Mulher]: ').lower()
elif n == 0:
print('\nSISTEMA FINALIZADO.')
break
print(f'a- Pessoas maiores de 18 anos: {cont_idade}')
print(f'b- Homens cadastrados: {homem}')
print(f'c- Mulheres com menos de 20 anos: {mulher_20}') |
people = 50 #defines the people variable
cars = 10 #defines the cars variable
trucks = 35 #defines the trucks variable
if cars > people or trucks < cars: #sets up the first branch
print("We should take the cars.") #print that runs if the if above is true
elif cars < people: #sets up second branch that runs if the first one is not true
print("We should not take the cars.") #print that runs if the elif above is true
else: #sets up third and last branch that will run if the above ifs are not true
print("We can't decide.") #print that runs if the else above is true
if trucks > cars:#sets up the first branch
print("That's too many trucks.")#print that runs if the if above is true
elif trucks < cars:#sets up second branch that runs if the first one is not true
print("Maybe we could take the trucks.")#print that runs if the elif above is true
else:#sets up third and last branch that will run if the above ifs are not true
print("We still can't decide.")#print that runs if the else above is true
if people > trucks:#sets up the first branch
print("Alright, let's just take the trucks.")#print that runs if the if above is true
else: #sets up second and last branch
print("Fine, let's stay home then.")#print that runs if the else above is true
|
DESEncryptParam = "key(16 Hex Chars), Number of rounds"
INITIAL_PERMUTATION = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7]
PERMUTED_CHOICE_1 = [57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4]
PERMUTED_CHOICE_2 = [14, 17, 11, 24, 1, 5, 3, 28,
15, 6, 21, 10, 23, 19, 12, 4,
26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32]
EXPANSION_PERMUTATION = [32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1]
S_BOX = [
[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
],
[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
[3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
[0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
],
[[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
],
[[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
],
[[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
],
[[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
],
[[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
],
[[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
[1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
]
]
PERMUTATION_TABLE = [16, 7, 20, 21, 29, 12, 28, 17,
1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25]
FINAL_PERMUTATION = [40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25]
SHIFT = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]
def toBin(input):
binval = bin(input)[2:]
while len(binval) < 4:
binval = "0" + binval
return binval
def hexToBin(input):
return bin(int(input, 16))[2:].zfill(64)
def substitute(input):
subblocks = splitToArrOfN(input, 6)
result = []
for i in range(len(subblocks)):
block = subblocks[i]
row = int(str(block[0])+str(block[5]), 2)
column = int(''.join([str(x) for x in block[1:][:-1]]), 2)
result += [int(x) for x in toBin(S_BOX[i][row][column])]
return result
def splitToArrOfN(listToSplit, newSize):
return [listToSplit[k:k+newSize] for k in range(0, len(listToSplit), newSize)]
def xor(operand1, operand2):
return [int(operand1[i]) ^ int(operand2[i]) for i in range(len(operand1))]
def shift(operand1, operand2, shiftAmount):
return operand1[shiftAmount:] + operand1[:shiftAmount], operand2[shiftAmount:] + operand2[:shiftAmount]
def permut(block, table):
return [block[x-1] for x in table]
def getKeys(initialKey):
keys = []
left, right = splitToArrOfN(
permut(hexToBin(initialKey), PERMUTED_CHOICE_1), 28)
for i in range(16):
left, right = shift(left, right, SHIFT[i])
keys.append(permut(left + right, PERMUTED_CHOICE_2))
return keys
def DESEncrypt(input, param):
key, numberOfRounds = param
numberOfRounds = int(numberOfRounds)
keys = getKeys(key)
currentPhase = input[0].strip()
for _ in range(numberOfRounds):
result = []
for block in splitToArrOfN(currentPhase, 16):
block = permut(hexToBin(block), INITIAL_PERMUTATION)
left, right = splitToArrOfN(block, 32)
intermediateValue = None
for i in range(16):
rightPermuted = permut(right, EXPANSION_PERMUTATION)
intermediateValue = xor(keys[i], rightPermuted)
intermediateValue = substitute(intermediateValue)
intermediateValue = permut(
intermediateValue, PERMUTATION_TABLE)
intermediateValue = xor(left, intermediateValue)
left, right = right, intermediateValue
result += permut(right+left, FINAL_PERMUTATION)
currentPhase = ''.join([hex(int(''.join(map(str, i)), 2))[
2] for i in splitToArrOfN(result, 4)])
return [currentPhase.upper()]
def DESDecrypt(input, param):
key, numberOfRounds = param
numberOfRounds = int(numberOfRounds)
keys = getKeys(key)
currentPhase = input[0].strip()
for _ in range(numberOfRounds):
result = []
for block in splitToArrOfN(currentPhase, 16):
block = permut(hexToBin(block), INITIAL_PERMUTATION)
left, right = splitToArrOfN(block, 32)
intermediateValue = None
for i in range(16):
rightPermuted = permut(right, EXPANSION_PERMUTATION)
intermediateValue = xor(keys[15-i], rightPermuted)
intermediateValue = substitute(intermediateValue)
intermediateValue = permut(
intermediateValue, PERMUTATION_TABLE)
intermediateValue = xor(left, intermediateValue)
left, right = right, intermediateValue
result += permut(right+left, FINAL_PERMUTATION)
currentPhase = ''.join([hex(int(''.join(map(str, i)), 2))[
2] for i in splitToArrOfN(result, 4)])
return [currentPhase.upper()]
|
# pylint: disable-all
"""Test inputs for day 2"""
test_position: str = """forward 5
down 5
forward 8
up 3
down 8
forward 2"""
test_position_answer: int = 150
test_position_answer_day_two: int = 900
|
input = """
a :- b.
b | c.
d.
:- d, a.
"""
output = """
a :- b.
b | c.
d.
:- d, a.
"""
|
class WikipediaKnowledge:
@staticmethod
def all_wikipedia_language_codes_order_by_importance():
# list from https://meta.wikimedia.org/wiki/List_of_Wikipedias as of 2017-10-07
# ordered by article count except some for extreme bot spam
# should use https://stackoverflow.com/questions/33608751/retrieve-a-list-of-all-wikipedia-languages-programmatically
# probably via wikipedia connection library
return ['en', 'de', 'fr', 'nl', 'ru', 'it', 'es', 'pl',
'vi', 'ja', 'pt', 'zh', 'uk', 'fa', 'ca', 'ar', 'no', 'sh', 'fi',
'hu', 'id', 'ko', 'cs', 'ro', 'sr', 'ms', 'tr', 'eu', 'eo', 'bg',
'hy', 'da', 'zh-min-nan', 'sk', 'min', 'kk', 'he', 'lt', 'hr',
'ce', 'et', 'sl', 'be', 'gl', 'el', 'nn', 'uz', 'simple', 'la',
'az', 'ur', 'hi', 'vo', 'th', 'ka', 'ta', 'cy', 'mk', 'mg', 'oc',
'tl', 'ky', 'lv', 'bs', 'tt', 'new', 'sq', 'tg', 'te', 'pms',
'br', 'be-tarask', 'zh-yue', 'bn', 'ml', 'ht', 'ast', 'lb', 'jv',
'mr', 'azb', 'af', 'sco', 'pnb', 'ga', 'is', 'cv', 'ba', 'fy',
'su', 'sw', 'my', 'lmo', 'an', 'yo', 'ne', 'gu', 'io', 'pa',
'nds', 'scn', 'bpy', 'als', 'bar', 'ku', 'kn', 'ia', 'qu', 'ckb',
'mn', 'arz', 'bat-smg', 'wa', 'gd', 'nap', 'bug', 'yi', 'am',
'si', 'cdo', 'map-bms', 'or', 'fo', 'mzn', 'hsb', 'xmf', 'li',
'mai', 'sah', 'sa', 'vec', 'ilo', 'os', 'mrj', 'hif', 'mhr', 'bh',
'roa-tara', 'eml', 'diq', 'pam', 'ps', 'sd', 'hak', 'nso', 'se',
'ace', 'bcl', 'mi', 'nah', 'zh-classical', 'nds-nl', 'szl', 'gan',
'vls', 'rue', 'wuu', 'bo', 'glk', 'vep', 'sc', 'fiu-vro', 'frr',
'co', 'crh', 'km', 'lrc', 'tk', 'kv', 'csb', 'so', 'gv', 'as',
'lad', 'zea', 'ay', 'udm', 'myv', 'lez', 'kw', 'stq', 'ie',
'nrm', 'nv', 'pcd', 'mwl', 'rm', 'koi', 'gom', 'ug', 'lij', 'ab',
'gn', 'mt', 'fur', 'dsb', 'cbk-zam', 'dv', 'ang', 'ln', 'ext',
'kab', 'sn', 'ksh', 'lo', 'gag', 'frp', 'pag', 'pi', 'olo', 'av',
'dty', 'xal', 'pfl', 'krc', 'haw', 'bxr', 'kaa', 'pap', 'rw',
'pdc', 'bjn', 'to', 'nov', 'kl', 'arc', 'jam', 'kbd', 'ha', 'tpi',
'tyv', 'tet', 'ig', 'ki', 'na', 'lbe', 'roa-rup', 'jbo', 'ty',
'mdf', 'kg', 'za', 'wo', 'lg', 'bi', 'srn', 'zu', 'chr', 'tcy',
'ltg', 'sm', 'om', 'xh', 'tn', 'pih', 'chy', 'rmy', 'tw', 'cu',
'kbp', 'tum', 'ts', 'st', 'got', 'rn', 'pnt', 'ss', 'fj', 'bm',
'ch', 'ady', 'iu', 'mo', 'ny', 'ee', 'ks', 'ak', 'ik', 've', 'sg',
'dz', 'ff', 'ti', 'cr', 'atj', 'din', 'ng', 'cho', 'kj', 'mh',
'ho', 'ii', 'aa', 'mus', 'hz', 'kr',
# degraded due to major low-quality bot spam
'ceb', 'sv', 'war'
]
|
# -*- coding:utf-8 -*-
# @Script: rotate_array.py
# @Author: Pradip Patil
# @Contact: @pradip__patil
# @Created: 2019-04-01 21:36:57
# @Last Modified By: Pradip Patil
# @Last Modified: 2019-04-01 22:44:02
# @Description: https://leetcode.com/problems/rotate-array/
'''
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
'''
class Solution:
def reverse(self, nums, start, end):
while start < end:
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start += 1
end -= 1
def rotate(self, nums, k):
k %= len(nums)
self.reverse(nums, 0, len(nums)-1)
self.reverse(nums, 0, k-1)
self.reverse(nums, k, len(nums)-1)
return nums
# Using builtins
class Solution_1:
def rotate(self, nums, k):
l = len(nums)
k %= l
nums[0:l] = nums[-k:] + nums[:-k]
return nums
if __name__ == "__main__":
print(Solution().rotate([-1, -100, 3, 99], 2))
print(Solution_1().rotate([-1, -100, 3, 99], 2))
print(Solution().rotate([1, 2, 3, 4, 5, 6, 7], 3))
print(Solution_1().rotate([1, 2, 3, 4, 5, 6, 7], 3))
|
class TrainingConfig():
batch_size=64
lr=0.001
epoches=20
print_step=15
class BertMRCTrainingConfig(TrainingConfig):
batch_size=64
lr=1e-5
epoches=5
class TransformerConfig(TrainingConfig):
pass
class HBTTrainingConfig(TrainingConfig):
batch_size=32
lr=1e-5
epoch=20
|
# mouse
MOUSE_BEFORE_DELAY = 0.1
MOUSE_AFTER_DELAY = 0.1
MOUSE_PRESS_TIME = 0.2
MOUSE_INTERVAL = 0.2
# keyboard
KEYBOARD_BEFORE_DELAY = 0.05
KEYBOARD_AFTER_DELAY = 0.05
KEYBOARD_PRESS_TIME = 0.15
KEYBOARD_INTERVAL = 0.1
# clipbaord
CLIPBOARD_CHARSET = 'gbk'
# window
WINDOW_TITLE = 'Program Manager'
WINDOW_MANAGE_TIMEOUT = 5
WINDOW_NEW_BUILD_TIMEOUT = 5
# image
IMAGE_SCREENSHOT_POSITION_DEFAULT = (0,0)
IMAGE_SCREENSHOT_SIZE_DEFAULT = (1920,1080)
|
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
def __call__(self):
print('My name 111111111is %s.' % self.name)
print("-----------------------")
ffl = Student('ffl')
print("ffl-->", ffl)
print("ffl-11->", ffl())
# f = lambda:34
# print(f)
# print(f())
|
LIMIT = 2000000;
def solve(limit):
a = 0
dam = limit
for i in range(2, 101):
for j in range(i, 101):
d = abs(i*(i + 1) * j*(j + 1)/4 - limit)
if d < dam:
a, dam = i * j, d
return a
if __name__ == "__main__":
print(solve(LIMIT))
|
class CajaFuerte:
def __init__(self, codigo):
self.codigo = codigo
self.caja_esta_abierta = False
self.objetos_guardados = []
def esta_abierta(self):
print(self.caja_esta_abierta)
def abrir(self, codigo):
if codigo != self.codigo:
raise Exception("La clave es inválida")
self.caja_esta_abierta = True
def cerrar(self):
self.caja_esta_abierta = False
def guardar(self, objeto):
if not self.caja_esta_abierta:
raise Exception("La caja fuerte está cerrada")
elif self.objetos_guardados:
raise Exception("No se puede guardar más de una cosa")
self.objetos_guardados.append(objeto)
def sacar(self):
if not self.caja_esta_abierta:
raise Exception("La caja fuerte está cerrada")
elif not self.objetos_guardados:
raise Exception("No hay nada para sacar")
print(self.objetos_guardados.pop())
def __str__(self):
return f"Código: {self.codigo} / Esta abierta: {self.caja_esta_abierta} / Objetos: {''.join(self.objetos_guardados)}"
caja = CajaFuerte(1234)
caja.abrir(1234)
caja.guardar("pulsera")
caja.cerrar()
print(caja) |
for _ in range(int(input())):
l,r=map(int,input().split())
b=r
a=r//2+1
if a<l:
a=l
if a>r:
a=r
print(b%a) |
########################################################
# Copyright (c) 2015-2017 by European Commission. #
# All Rights Reserved. #
########################################################
extends("BaseKPI.py")
"""
Investment Analysis (euro)
---------------------------
Indexed by
* scope
* energy
* test case
* production asset
The Investment Analysis calculates the economic profitability of a given production asset in a given delivery point, defined as the difference between the producer surplus and the investment costs for this specific asset.
The producer surplus is calculated as the benefit the producer receives for selling its product on the market.
The investment costs is the sum of the Capital Expenditure (CAPEX) and Fixed Operating Cost (FOC):
.. math::
\\small investmentAnalysis_{asset} = \\small \\sum_t producerSurplus_{t, asset} - investmentCosts_{asset}
with:
.. math::
\\small investmentCosts_{asset} = \small \\sum_t installedCapacity^{asset}*(CAPEX^{asset} + FOC^{asset})
and:
.. math::
\\small producerSurplus_{asset} = \small \\sum_t (production_{t, asset}.marginalCost_{t, dp, energy}) - productionCost_{asset}
"""
def computeIndicator(context, indexFilter, paramsIndicator, kpiDict):
timeStepDuration = getTimeStepDurationInHours(context)
selectedScopes = indexFilter.filterIndexList(0, getScopes())
selectedTestCases = indexFilter.filterIndexList(1, context.getResultsIndexSet())
selectedAssets = indexFilter.filterIndexList(2, getAssets(context, includedTechnologies = PRODUCTION_TYPES))
selectedAssetsByScope = getAssetsByScope(context, selectedScopes, includedAssetsName = selectedAssets)
producerSurplusDict = getProducerSurplusByAssetDict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
capexDict = getCapexByAssetDict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
focDict = getFocByAssetDict(context, selectedScopes, selectedTestCases, selectedAssetsByScope)
for index in producerSurplusDict:
kpiDict[index] = (producerSurplusDict[index]).getSumValue() - (capexDict[index] + focDict[index]).getMeanValue()
return kpiDict
def get_indexing(context) :
baseIndexList = [getScopesIndexing(), getTestCasesIndexing(context), getAssetsIndexing(context, includedTechnologies = PRODUCTION_TYPES)]
return baseIndexList
IndicatorLabel = "Investment Analysis"
IndicatorUnit = u"\u20ac"
IndicatorDeltaUnit = u"\u20ac"
IndicatorDescription = "Difference between the Surplus and the investment costs for a given production asset"
IndicatorParameters = []
IndicatorIcon = ""
IndicatorCategory = "Results>Welfare"
IndicatorTags = "Power System, Power Markets"
|
print('Please think of a number between 0 and 100!')
x = 54
low = 0
high = 100
guessed = False
while not guessed:
guess = (low + high)/2
print('Is your secret number ' + str(guess)+'?')
s = raw_input("Enter 'h' to indicate the guess is too high.\
Enter 'l' to indicate the guess is too low. Enter \
'c' to indicate I guessed correctly.")
if s == 'c':
guessed = True
elif s == 'l':
low = guess
elif s == 'h':
high = guess
else :
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was: '+str(guess))
|
# abcabc
# g_left = a, g_right = b
#
class Solution(object):
def __convert(self, x):
return ord(x) - ord('a') + 1
def distinctEchoSubstrings(self, text):
if len(text) == 1:
return 0
m = int(1e9 + 9)
p = 31
p_pow = 1
g_left = self.__convert(text[0])
g_right = self.__convert(text[1])
hashes = set()
for ws in range(1, len(text)):
left = g_left
right = g_right
for mid in range(len(text) - ws):
if left == right:
hashes.add(left)
first_left = self.__convert(text[ws + mid - 1]) * p_pow
last_left = self.__convert(text[ws + mid])
left = (p * (left - first_left) + last_left) % m
first_right = self.__convert(text[ws * 2 + mid -1]) * p_pow
last_right = self.__convert(text[ws * 2 + mid])
right = (p * (right - first_right) + last_right) % m
for i in range(ws, ws * 2):
first_right = self.__convert()
g_right = (p * (g_right - self.__convert(text[ws]) * p_pow))
p_pow = p_pow * p
g_left = (p * g_left + self.__convert(text[ws])) % m
if __name__ == '__main__':
s = Solution()
n = s.distinctEchoSubstrings("abab")
print(n)
|
description = 'nGI backpack setup at ICON.'
display_order = 35
pvprefix = 'SQ:ICON:ngiB:'
includes = ['ngi_g0']
excludes = ['ngi_xingi_gratings']
devices = dict(
g1_rz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'nGI Interferometer Grating Rotation G1 (Backpack)',
motorpv = pvprefix + 'g1rz',
errormsgpv = pvprefix + 'g1rz-MsgTxt',
precision = 0.01,
),
g1_tz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'nGI Interferometer Grating Talbot G1 (Backpack)',
motorpv = pvprefix + 'g1tz',
errormsgpv = pvprefix + 'g1tz-MsgTxt',
precision = 0.01,
),
g2_rz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'nGI Interferometer Grating Rotation G2 (Backpack)',
motorpv = pvprefix + 'g2rz',
errormsgpv = pvprefix + 'g2rz-MsgTxt',
precision = 0.01,
)
)
|
# -*- coding: utf-8 -*-
def roadbed_to_english(roadbed):
if roadbed in ['芝','0']:
roadbed_english='turf'
elif roadbed in ['ダ','1']:
roadbed_english='dirt'
else:
roadbed_english=roadbed
return roadbed_english
def roadbed_flg(roadbed):
if roadbed == '芝':
flg = '0'
elif roadbed == 'ダ':
flg = '1'
else:
flg = '9'
return flg
def condition_flg(condition):
if condition == '良':
flg = '0'
elif condition in ['稍','稍重']:
flg = '1'
elif condition == '重':
flg = '2'
elif condition in ['不','不良']:
flg = '3'
else:
flg = '9'
return flg
def course_flg(course):
courses={'札幌':'01','函館':'02','福島':'03','新潟':'04','東京':'05','中山':'06','中京':'07','京都':'08','阪神':'09','小倉':'10'}
if course in courses:
flg = courses[course]
else:
flg = '99'
return flg
def distance_key(distance):
if distance < 1400:
key = 'distance_sprint'
elif distance < 1900:
key = 'distance_mile'
elif distance < 2200:
key = 'distance_intermediate'
elif distance < 3000:
key = 'distance_long'
else:
key = 'distance_extended'
return key
def belongs_flg(belongs):
if '美浦' in belongs or '[東]' in belongs:
flg='0'
elif '栗東' in belongs or '[西]' in belongs:
flg='1'
else:
flg='2'
return flg
def sex_flg(sex):
if sex == '牡':
flg = '0'
elif sex == '牝':
flg = '1'
elif sex == 'セ':
flg = '2'
return flg
def winClass_flg(winClass):
if winClass == '新馬':
flg = '9'
elif winClass == '未勝利':
flg = '0'
elif winClass in ['1勝','1勝']:
flg = '1'
elif winClass in ['2勝','2勝']:
flg = '2'
elif winClass in ['3勝','3勝']:
flg = '3'
elif winClass == 'オープン':
flg = '4'
return flg
def loafCondition_flg(loafCondition):
if loafCondition == '馬齢':
flg = '0'
elif loafCondition == '定量':
flg = '1'
elif loafCondition == '別定':
flg = '2'
elif loafCondition == 'ハンデ':
flg = '3'
return flg
def distance_flg(distance):
category={
'sprint':['1000','1150','1200','1300'],
'mile':['1400','1500','1600','1700','1800'],
'intermediate':['1900','2000','2100'],
'long':['2200','2300','2400','2500','2600'],
'extended':['3000','3200','3400','3600']
}
if distance in category['sprint']:
flg='0'
elif distance in category['mile']:
flg='1'
elif distance in category['intermediate']:
flg='2'
elif distance in category['long']:
flg='3'
elif distance in category['extended']:
flg='4'
return flg
|
# coding=utf-8
"""生产环境使用的配置
"""
DB_DEBUG = False
DB = 'attr_detect_ml3'
HOST = '192.168.178.19'
USER = 'db_ae3'
PASSWD = '632#ae931gld'
CONNECT_STRING = 'mysql://%s:%s@%s/%s?charset=utf8' % (USER, PASSWD, HOST, DB)
|
def powerLevelForCell(x, y, gridSerialNumber):
rackID = x + 11
powerLevel = rackID * (y + 1)
powerLevel += gridSerialNumber
powerLevel *= rackID
powerLevel //= 100
toSubtract = powerLevel // 10 * 10
powerLevel -= toSubtract
powerLevel -= 5
return powerLevel
"""
print(powerLevelForCell(2, 4, 8))
print(powerLevelForCell(121, 78, 57))
print(powerLevelForCell(216, 195, 39))
print(powerLevelForCell(100, 152, 71))
"""
gridSerialNumber = 42
grid = []
for y in range(300):
row = []
for x in range(300):
row.append(powerLevelForCell(x, y, gridSerialNumber))
grid.append(row)
largest = -1e12
for y in range(300):
print(y)
for x in range(300):
squareValue = 0
for squareSize in range(min(50, 300 - max(x, y))):
squareValue += grid[y+squareSize][x+squareSize]
column = x + squareSize
for row in range(squareSize):
squareValue += grid[y+row][column]
row = y + squareSize
for column in range(squareSize):
squareValue += grid[row][x+column]
if squareValue > largest:
largest = squareValue
largestCoordinate = (x+1, y+1, squareSize+1)
print(largestCoordinate)
|
# Input: Two strings, Pattern and Genome
# Output: A list containing all starting positions where Pattern appears as a substring of Genome
def PatternMatching(pattern, genome):
positions = [] # output variable
# your code here
for i in range(len(genome)-len(pattern)+1):
if genome[i:i+len(pattern)] == pattern:
positions.append(i)
return positions
# Input: Strings Pattern and Text along with an integer d
# Output: A list containing all starting positions where Pattern appears
# as a substring of Text with at most d mismatches
def ApproximatePatternMatching(pattern, genome, d):
positions = [] # output variable
for i in range(len(genome)-len(pattern)+1):
variants = HammingDistance(pattern,genome[i:i+len(pattern)])
if variants <= d:
positions.append(i)
return positions
'''
Input: Strings Pattern and Text
Output: The number of times Pattern appears in Text
PatternCount("ACTAT", "ACAACTATGCATACTATCGGGAACTATCCT") = 3.
'''
def PatternCount(Pattern, Text):
count = 0
for i in range(len(Text)-len(Pattern)+1):
if Text[i:i+len(Pattern)] == Pattern:
count = count+1
return count
# Input: Strings Pattern and Text, and an integer d
# Output: The number of times Pattern appears in Text with at most d mismatches
def ApproximatePatternCount(Pattern, Text, d):
count = 0
for i in range(len(Text)-len(Pattern)+1):
variants = HammingDistance(Pattern,Text[i:i+len(Pattern)])
if variants <= d:
count = count + 1
return count
'''
Input: Strings Text and integer k
Output: The dictionary of the count of every k-mer string
CountDict("CGATATATCCATAG",3) = {0: 1, 1: 1, 2: 3, 3: 2, 4: 3, 5: 2, 6: 1, 7: 1, 8: 1, 9: 1, 10: 3, 11: 1}.
'''
def CountDict(Text, k):
Count = {}
for i in range(len(Text)-k+1):
Pattern = Text[i:i+k]
Count[i] = PatternCount(Pattern, Text)
return Count
'''
Input: a list of items
Output: the non-duplicate items
Remove_duplicates([1,2,3,3]) = [1,2,3]
'''
def Remove_duplicates(Items):
ItemsNoDuplicates = [] # output variable
ItemsNoDuplicates = list(set(Items))
return ItemsNoDuplicates
'''
Input: Strings Text and integer k
Output: The freqent k-mer
FrequentWords("GATCCAGATCCCCATAC",2) = "CC".
'''
def FrequentWords(Text, k):
FrequentPatterns = []
Count = CountDict(Text, k)
m= max(Count.values())
for i in Count:
if Count[i] == m:
FrequentPatterns.append(Text[i:i+k])
FrequentPatternsNoDuplicates = Remove_duplicates(FrequentPatterns)
return FrequentPatternsNoDuplicates
# Input: Strings Genome and symbol
# Output: SymbolArray(Genome, symbol)
def SymbolArray(Genome, symbol):
array = {}
n = len(Genome)
ExtendedGenome = Genome + Genome[0:n//2]
for i in range(n):
array[i] = PatternCount(symbol, ExtendedGenome[i:i+(n//2)])
return array
# Input: Strings Genome and symbol
# Output: FasterSymbolArray(Genome, symbol)
def FasterSymbolArray(Genome, symbol):
array = {}
n = len(Genome)
ExtendedGenome = Genome + Genome[0:n//2]
array[0] = PatternCount(symbol, Genome[0:n//2])
for i in range(1, n):
array[i] = array[i-1]
if ExtendedGenome[i-1] == symbol:
array[i] = array[i]-1
if ExtendedGenome[i+(n//2)-1] == symbol:
array[i] = array[i]+1
return array
# Input: A String Genome
# Output: Skew(Genome)
def Skew(Genome):
n = len(Genome)
skew = {} #initializing the dictionary
skew[0] = 0
for i in range(1,n+1):
skew[i] = skew[i-1]
if Genome[i-1] == 'G':
skew[i] = skew[i] + 1
if Genome[i-1] == 'C':
skew[i] = skew[i] - 1
return skew
# Input: A DNA string Genome
# Output: A list containing all integers i minimizing Skew(Prefix_i(Text)) over all values of i (from 0 to |Genome|)
def MinimumSkew(Genome):
positions = [] # output variable
# your code here
a_skew = Skew(Genome)
values = list(a_skew.values())
min_value = min(values)
for i in range(len(a_skew)):
if (a_skew[i] == min_value):
positions.append(i)
return positions
# Input: Two strings p and q (same length)
# Output: An integer value representing the Hamming Distance between p and q.
def HammingDistance(p, q):
m = len(p)
n = len(q)
result = 0
if (m != n):
return result
else:
for i in range(n):
if (p[i] != q[i]):
result = result + 1
return result
### DO NOT MODIFY THE CODE BELOW THIS LINE ###
if __name__ == '__main__':
#target ='TGATCA'
gene =str('ATCAATGATCAACGTAAGCTTCTAAGCATGATCAAGGTGCTCACACAGTTTATCCACAACCTGAGTGGATGACATCAAGATAGGTCGTTGTATCTCCTTCCTCTCGTACTCTCATGACCACGGAAAGATGATCAAGAGAGGATGATTTCTTGGCCATATCGCAATGAATACTTGTGACTTGTGCTTCCAATTGACATCTTCAGCGCCATATTGCGCTGGCCAAGGTGACGGAGCGGGATTACGAAAGCATGATCATGGCTGTTGTTCTGTTTATCTTGTTTTGACTGAGACTTGTTAGGATAGACGGTTTTTCATCACTGACTAGCCAAAGCCTTACTCTGCCTGACATCGACCGTAAATTGATAATGAATTTACATGCTTCCGCGACGATTTACCTCTTGATCATCGATCCGATTGAAGATCTTCAATTGTTAATTCTCTTGCCTCGACTCATAGCCATGATGAGCTCTTGATCATGTTTCCTTAACCCTCTATTTTTTACGGAAGAATGATCAAGCTGCTGCTCTTGATCATCGTTTC')
#print(PatternCount(target, gene))
#print (CountDict(gene,10))
print (FrequentWords(gene,10))
#print(PatternCount("TGT", "ACTGTACGATGATGTGTGTCAAAG"))
#print(PatternMatching('ATAT','GATATATGCATATACTT'))
# print(SymbolArray('AAAAGGGG','A'))
# print(FasterSymbolArray('AAAAGGGG','A'))
# print(Skew('CATGGGCATCGGCCATACGCC'))
# print(MinimumSkew('CATTCCAGTACTTCGATGATGGCGTGAAGA'))
# print(MinimumSkew('TAAAGACTGCCGAGAGGCCAACACGAGTGCTAGAACGAGGGGCGTAAACGCGGGTCCGAT'))
# print(HammingDistance('GGGCCGTTGGT','GGACCGTTGAC'))
# print(ApproximatePatternMatching('ATTCTGGA','CGCCCGAATCCAGAACGCATTCCCATATTTCGGGACCACTGGCCTCCACGGTACGGACGTCAATCAAAT',3))
# print(ApproximatePatternCount('GAGG','TTTAGAGCCTTCAGAGG',2))
# print(HammingDistance('CTTGAAGTGGACCTCTAGTTCCTCTACAAAGAACAGGTTGACCTGTCGCGAAG','ATGCCTTACCTAGATGCAATGACGGACGTATTCCTTTTGCCTCAACGGCTCCT')) |
def encodenum(num):
num = str(num)
line =""
for c in num:
line += chr(int(c) + ord('a'))
return line
def decodenum(line):
num = ""
for c in line:
num += str(ord(c)-ord('a'))
return num |
class exemplo():
def __init__(self):
pass
def thg_print(darkcode):
print(darkcode)
|
class Foo():
_myprop = 3
@property
def myprop(self):
return self.__class__._myprop
@myprop.setter
def myprop(self, val):
self.__class__._myprop = val
f = Foo()
g = Foo()
print(f.myprop, g.myprop)
f.myprop = 4
print(f.myprop, g.myprop)
|
#author: Lynijah
# date: 07-01-2021
def blank():
return print(" ")
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that prints the sum of two numbers
# 2 - create a print statement that prints the sum of three numbers
# 3 - create a print statement the prints the sum of two negative numbers
print("Addition Section")
print(2006+2000)
print(2000+9000+4)
print(-4 + -7)
blank()
# subtraction
# instructions
# 1 - create a print statement that prints the difference of two numbers
# 2 - create a print statement that prints the difference of three numbers
# 3 - create a print statement the prints the difference of two negative numbers
print("Subtraction Section")
print(2006-2000)
print(2000-10-90)
print(-4 - -7)
blank()
# multiplication and true division
# instructions
# 1 - create a print statement the prints the product of two numbers
# 2 - create a print statement that prints the dividend of two numbers
# 3 - create a print statement that evaluates an operation using both multiplication and division
print("Multiplication And True Division Section")
print(6*2000)
print(2000/9)
print(5*8/2)
blank()
# floor division
# instructions
# 1 - using floor division, print the dividend of two numbers.
print("Floor Division Section")
print(200//9)
blank()
# exponentiation
# instructions
# 1 - using exponentiation, print the power of two numbers
print("Exponent Section")
print(50**11)
blank()
# modulus
# instructions
# 1 - using modulus, print the remainder of two numbers
print("Modulus Section")
print(1083108323%22)
# --------------- Section 2 --------------- #
# ---------- String Concatenation --------- #
# concatenation
# instructions
# 1 - print the concatenation of your first and last name
print(" ")
print("Name")
x = "Lynijah "
y = "Russell"
z = x + y
print(z)
print(" ")
# 2 - print the concatenation of five animals you like
a = "Cats "
b = "Dogs "
c = "Bunnies "
d = "Merecats "
e = "Ducks"
f = a+b+c+d+e
print(f)
# 3 - print the concatenation of each word in a phrase
print(" ")
print("My name is", x , y, "and my favorite animals are", a,",",c,",",d,",",e)
# duplication
# instructions
# 1 - print the duplpication of your first 5 times
print(" ")
print("Duplication")
print("Lynijah"*5)
# 2 - print the duplication of a song you like 10 times
print("I'm not pretty"*10)
print(" ")
# concatenation and duplpication
# instructions
print("Concatenation")
# 1 - print the concatenation of two strings duplicated 3 times each
print("hey gurllll "*3 + "MWUHAHAHAHAHHAHAHAH "*3)
|
class RemoteError(Exception):
"""A base class for all remote's custom exception"""
class RemoteConnectionError(RemoteError):
"""Remote wasn't able to connect to remote host"""
class RemoteExecutionError(RemoteError):
"""A command executed remotely exited with non-zero status"""
class ConfigurationError(RemoteError):
"""The workspace configuration is incorrect"""
class InvalidInputError(RemoteError):
"""Invalid user input is passed from the cli"""
class InvalidRemoteHostLabel(RemoteError):
"""Invalid label is passed to the workspace."""
|
#
# PySNMP MIB module CISCO-ENTITY-REDUNDANCY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-REDUNDANCY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:51 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")
ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint")
CeRedunSwitchCommand, CeRedunReasonCategories, CeRedunType, CeRedunStateCategories, CeRedunScope, CeRedunMode, CeRedunMbrStatus, CeRedunArch = mibBuilder.importSymbols("CISCO-ENTITY-REDUNDANCY-TC-MIB", "CeRedunSwitchCommand", "CeRedunReasonCategories", "CeRedunType", "CeRedunStateCategories", "CeRedunScope", "CeRedunMode", "CeRedunMbrStatus", "CeRedunArch")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
PhysicalIndex, = mibBuilder.importSymbols("ENTITY-MIB", "PhysicalIndex")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
Counter64, ModuleIdentity, TimeTicks, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Bits, iso, Gauge32, Unsigned32, NotificationType, ObjectIdentity, IpAddress, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "ModuleIdentity", "TimeTicks", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Bits", "iso", "Gauge32", "Unsigned32", "NotificationType", "ObjectIdentity", "IpAddress", "Integer32")
TimeStamp, DisplayString, TextualConvention, RowStatus, TruthValue, StorageType, AutonomousType = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "DisplayString", "TextualConvention", "RowStatus", "TruthValue", "StorageType", "AutonomousType")
ciscoEntityRedunMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 498))
ciscoEntityRedunMIB.setRevisions(('2005-10-01 00:00',))
if mibBuilder.loadTexts: ciscoEntityRedunMIB.setLastUpdated('200510010000Z')
if mibBuilder.loadTexts: ciscoEntityRedunMIB.setOrganization('Cisco Systems, Inc.')
ciscoEntityRedunMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 498, 0))
ciscoEntityRedunMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 498, 1))
ciscoEntityRedunMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 498, 2))
ceRedunGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1))
ceRedunGroupTypesTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1), )
if mibBuilder.loadTexts: ceRedunGroupTypesTable.setStatus('current')
ceRedunGroupTypesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeIndex"))
if mibBuilder.loadTexts: ceRedunGroupTypesEntry.setStatus('current')
ceRedunGroupTypeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceRedunGroupTypeIndex.setStatus('current')
ceRedunGroupTypeName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1, 1, 2), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunGroupTypeName.setStatus('current')
ceRedunGroupCounts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunGroupCounts.setStatus('current')
ceRedunNextUnusedGroupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunNextUnusedGroupIndex.setStatus('current')
ceRedunMaxMbrsInGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMaxMbrsInGroup.setStatus('current')
ceRedunUsesGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1, 1, 6), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunUsesGroupName.setStatus('current')
ceRedunGroupDefinitionChanged = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 1, 1, 7), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunGroupDefinitionChanged.setStatus('current')
ceRedunVendorTypesTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 2), )
if mibBuilder.loadTexts: ceRedunVendorTypesTable.setStatus('current')
ceRedunVendorTypesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeIndex"), (0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunVendorType"))
if mibBuilder.loadTexts: ceRedunVendorTypesEntry.setStatus('current')
ceRedunVendorType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 2, 1, 1), AutonomousType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunVendorType.setStatus('current')
ceRedunInternalStatesTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 3), )
if mibBuilder.loadTexts: ceRedunInternalStatesTable.setStatus('current')
ceRedunInternalStatesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 3, 1), ).setIndexNames((0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeIndex"), (0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunInternalStateIndex"))
if mibBuilder.loadTexts: ceRedunInternalStatesEntry.setStatus('current')
ceRedunInternalStateIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 3, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceRedunInternalStateIndex.setStatus('current')
ceRedunStateCategory = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 3, 1, 2), CeRedunStateCategories()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunStateCategory.setStatus('current')
ceRedunInternalStateDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 3, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunInternalStateDescr.setStatus('current')
ceRedunSwitchoverReasonTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 4), )
if mibBuilder.loadTexts: ceRedunSwitchoverReasonTable.setStatus('current')
ceRedunSwitchoverReasonEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 4, 1), ).setIndexNames((0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeIndex"), (0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunSwitchoverReasonIndex"))
if mibBuilder.loadTexts: ceRedunSwitchoverReasonEntry.setStatus('current')
ceRedunSwitchoverReasonIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 4, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceRedunSwitchoverReasonIndex.setStatus('current')
ceRedunReasonCategory = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 4, 1, 2), CeRedunReasonCategories()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunReasonCategory.setStatus('current')
ceRedunSwitchoverReasonDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 4, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunSwitchoverReasonDescr.setStatus('current')
ceRedunGroupLastChanged = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 5), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunGroupLastChanged.setStatus('current')
ceRedunGroupTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6), )
if mibBuilder.loadTexts: ceRedunGroupTable.setStatus('current')
ceRedunGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1), ).setIndexNames((0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeIndex"), (0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupIndex"))
if mibBuilder.loadTexts: ceRedunGroupEntry.setStatus('current')
ceRedunGroupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceRedunGroupIndex.setStatus('current')
ceRedunGroupString = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 2), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupString.setStatus('current')
ceRedunGroupRedunType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 3), CeRedunType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupRedunType.setStatus('current')
ceRedunGroupScope = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 4), CeRedunScope().clone('local')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupScope.setStatus('current')
ceRedunGroupArch = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 5), CeRedunArch().clone('onePlusOne')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupArch.setStatus('current')
ceRedunGroupRevert = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("nonrevertive", 1), ("revertive", 2)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupRevert.setStatus('current')
ceRedunGroupWaitToRestore = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 7), Unsigned32().clone(300)).setUnits('seconds').setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupWaitToRestore.setStatus('current')
ceRedunGroupDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("unidirectional", 1), ("bidirectional", 2)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupDirection.setStatus('current')
ceRedunGroupStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 9), StorageType().clone('volatile')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupStorageType.setStatus('current')
ceRedunGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 1, 6, 1, 10), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunGroupRowStatus.setStatus('current')
ceRedunMembers = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2))
ceRedunMbrLastChanged = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 1), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrLastChanged.setStatus('current')
ceRedunMbrConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2), )
if mibBuilder.loadTexts: ceRedunMbrConfigTable.setStatus('current')
ceRedunMbrConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1), ).setIndexNames((0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeIndex"), (0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupIndex"), (0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrNumber"))
if mibBuilder.loadTexts: ceRedunMbrConfigEntry.setStatus('current')
ceRedunMbrNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ceRedunMbrNumber.setStatus('current')
ceRedunMbrPhysIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1, 2), PhysicalIndex()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunMbrPhysIndex.setStatus('current')
ceRedunMbrMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1, 3), CeRedunMode()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunMbrMode.setStatus('current')
ceRedunMbrAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1, 4), InetAddressType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunMbrAddressType.setStatus('current')
ceRedunMbrRemoteAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1, 5), InetAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunMbrRemoteAddress.setStatus('current')
ceRedunMbrPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("low", 1), ("high", 2))).clone('low')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunMbrPriority.setStatus('current')
ceRedunMbrStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1, 8), StorageType().clone('volatile')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunMbrStorageType.setStatus('current')
ceRedunMbrRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 2, 1, 9), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ceRedunMbrRowStatus.setStatus('current')
ceRedunMbrStatusLastChanged = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 3), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrStatusLastChanged.setStatus('current')
ceRedunMbrStatusTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4), )
if mibBuilder.loadTexts: ceRedunMbrStatusTable.setStatus('current')
ceRedunMbrStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4, 1), )
ceRedunMbrConfigEntry.registerAugmentions(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrStatusEntry"))
ceRedunMbrStatusEntry.setIndexNames(*ceRedunMbrConfigEntry.getIndexNames())
if mibBuilder.loadTexts: ceRedunMbrStatusEntry.setStatus('current')
ceRedunMbrStatusCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4, 1, 1), CeRedunMbrStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrStatusCurrent.setStatus('current')
ceRedunMbrProtectingMbr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrProtectingMbr.setStatus('current')
ceRedunMbrInternalState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrInternalState.setStatus('current')
ceRedunMbrSwitchoverCounts = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrSwitchoverCounts.setStatus('current')
ceRedunMbrLastSwitchover = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4, 1, 5), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrLastSwitchover.setStatus('current')
ceRedunMbrSwitchoverReason = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrSwitchoverReason.setStatus('current')
ceRedunMbrSwitchoverSeconds = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 2, 4, 1, 8), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceRedunMbrSwitchoverSeconds.setStatus('current')
ceRedunCommandTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 3), )
if mibBuilder.loadTexts: ceRedunCommandTable.setStatus('current')
ceRedunCommandEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 3, 1), ).setIndexNames((0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeIndex"), (0, "CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupIndex"))
if mibBuilder.loadTexts: ceRedunCommandEntry.setStatus('current')
ceRedunCommandMbrNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 2147483647))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ceRedunCommandMbrNumber.setStatus('current')
ceRedunCommandSwitch = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 3, 1, 2), CeRedunSwitchCommand()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ceRedunCommandSwitch.setStatus('current')
ceRedunEnableSwitchoverNotifs = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 4), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ceRedunEnableSwitchoverNotifs.setStatus('current')
ceRedunEnableStatusChangeNotifs = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 498, 1, 5), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ceRedunEnableStatusChangeNotifs.setStatus('current')
ceRedunEventSwitchover = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 498, 0, 1)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrProtectingMbr"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrStatusCurrent"))
if mibBuilder.loadTexts: ceRedunEventSwitchover.setStatus('current')
ceRedunProtectStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 498, 0, 2)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrStatusCurrent"))
if mibBuilder.loadTexts: ceRedunProtectStatusChange.setStatus('current')
ceRedunCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 1))
ceRedunGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2))
ceRedunCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 1, 1)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeGroup"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupObjects"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMemberConfig"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMemberStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunCompliance = ceRedunCompliance.setStatus('current')
ceRedunGroupTypeGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 1)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunNextUnusedGroupIndex"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMaxMbrsInGroup"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunUsesGroupName"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupDefinitionChanged"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunGroupTypeGroup = ceRedunGroupTypeGroup.setStatus('current')
ceRedunOptionalGroupTypes = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 2)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupTypeName"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupCounts"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunOptionalGroupTypes = ceRedunOptionalGroupTypes.setStatus('current')
ceRedunInternalStates = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 3)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunStateCategory"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunInternalStateDescr"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunInternalStates = ceRedunInternalStates.setStatus('current')
ceRedunSwitchoverReason = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 4)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunReasonCategory"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunSwitchoverReasonDescr"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunSwitchoverReason = ceRedunSwitchoverReason.setStatus('current')
ceRedunGroupObjects = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 5)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupLastChanged"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupString"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupRedunType"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupScope"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupArch"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupStorageType"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunGroupObjects = ceRedunGroupObjects.setStatus('current')
ceRedunRevertiveGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 6)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupRevert"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupWaitToRestore"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunRevertiveGroup = ceRedunRevertiveGroup.setStatus('current')
ceRedunBidirectional = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 7)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunGroupDirection"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunBidirectional = ceRedunBidirectional.setStatus('current')
ceRedunMemberConfig = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 8)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrLastChanged"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrPhysIndex"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrMode"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrStorageType"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunMemberConfig = ceRedunMemberConfig.setStatus('current')
ceRedunRemoteSystem = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 9)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrAddressType"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrRemoteAddress"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunRemoteSystem = ceRedunRemoteSystem.setStatus('current')
ceRedunOneToN = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 10)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrPriority"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunOneToN = ceRedunOneToN.setStatus('current')
ceRedunMemberStatus = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 11)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrStatusLastChanged"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrStatusCurrent"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrProtectingMbr"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrSwitchoverCounts"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrLastSwitchover"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunMemberStatus = ceRedunMemberStatus.setStatus('current')
ceRedunOptionalMbrStatus = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 12)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrInternalState"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrSwitchoverReason"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunMbrSwitchoverSeconds"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunOptionalMbrStatus = ceRedunOptionalMbrStatus.setStatus('current')
ceRedunCommandsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 13)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunCommandMbrNumber"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunCommandSwitch"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunCommandsGroup = ceRedunCommandsGroup.setStatus('current')
ceRedunNotifEnables = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 14)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunEnableSwitchoverNotifs"), ("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunEnableStatusChangeNotifs"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunNotifEnables = ceRedunNotifEnables.setStatus('current')
ceRedunSwitchNotifGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 15)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunEventSwitchover"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunSwitchNotifGroup = ceRedunSwitchNotifGroup.setStatus('current')
ceRedunProtectStatusNotifGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 498, 2, 2, 16)).setObjects(("CISCO-ENTITY-REDUNDANCY-MIB", "ceRedunProtectStatusChange"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceRedunProtectStatusNotifGroup = ceRedunProtectStatusNotifGroup.setStatus('current')
mibBuilder.exportSymbols("CISCO-ENTITY-REDUNDANCY-MIB", ceRedunCompliance=ceRedunCompliance, ceRedunSwitchoverReasonDescr=ceRedunSwitchoverReasonDescr, ceRedunMbrInternalState=ceRedunMbrInternalState, ceRedunUsesGroupName=ceRedunUsesGroupName, ceRedunSwitchoverReason=ceRedunSwitchoverReason, ceRedunEnableSwitchoverNotifs=ceRedunEnableSwitchoverNotifs, ceRedunGroups=ceRedunGroups, ceRedunGroup=ceRedunGroup, ciscoEntityRedunMIB=ciscoEntityRedunMIB, ceRedunStateCategory=ceRedunStateCategory, ceRedunGroupScope=ceRedunGroupScope, ceRedunGroupTypesTable=ceRedunGroupTypesTable, ceRedunMbrRowStatus=ceRedunMbrRowStatus, ceRedunCommandTable=ceRedunCommandTable, ceRedunCommandMbrNumber=ceRedunCommandMbrNumber, PYSNMP_MODULE_ID=ciscoEntityRedunMIB, ciscoEntityRedunMIBObjects=ciscoEntityRedunMIBObjects, ceRedunRevertiveGroup=ceRedunRevertiveGroup, ceRedunInternalStateDescr=ceRedunInternalStateDescr, ceRedunMbrSwitchoverReason=ceRedunMbrSwitchoverReason, ceRedunNextUnusedGroupIndex=ceRedunNextUnusedGroupIndex, ceRedunMbrLastChanged=ceRedunMbrLastChanged, ceRedunGroupStorageType=ceRedunGroupStorageType, ceRedunMaxMbrsInGroup=ceRedunMaxMbrsInGroup, ceRedunSwitchoverReasonEntry=ceRedunSwitchoverReasonEntry, ceRedunSwitchoverReasonIndex=ceRedunSwitchoverReasonIndex, ceRedunGroupObjects=ceRedunGroupObjects, ceRedunOneToN=ceRedunOneToN, ceRedunCommandSwitch=ceRedunCommandSwitch, ceRedunSwitchoverReasonTable=ceRedunSwitchoverReasonTable, ceRedunGroupCounts=ceRedunGroupCounts, ceRedunEnableStatusChangeNotifs=ceRedunEnableStatusChangeNotifs, ceRedunProtectStatusChange=ceRedunProtectStatusChange, ceRedunVendorTypesTable=ceRedunVendorTypesTable, ceRedunMbrStatusCurrent=ceRedunMbrStatusCurrent, ceRedunGroupArch=ceRedunGroupArch, ceRedunEventSwitchover=ceRedunEventSwitchover, ceRedunNotifEnables=ceRedunNotifEnables, ceRedunGroupDirection=ceRedunGroupDirection, ceRedunVendorTypesEntry=ceRedunVendorTypesEntry, ceRedunGroupRedunType=ceRedunGroupRedunType, ceRedunInternalStates=ceRedunInternalStates, ceRedunGroupEntry=ceRedunGroupEntry, ceRedunGroupTable=ceRedunGroupTable, ceRedunMbrAddressType=ceRedunMbrAddressType, ceRedunReasonCategory=ceRedunReasonCategory, ceRedunGroupWaitToRestore=ceRedunGroupWaitToRestore, ceRedunMbrConfigTable=ceRedunMbrConfigTable, ceRedunOptionalMbrStatus=ceRedunOptionalMbrStatus, ceRedunInternalStateIndex=ceRedunInternalStateIndex, ceRedunGroupTypeIndex=ceRedunGroupTypeIndex, ceRedunGroupRevert=ceRedunGroupRevert, ceRedunMbrConfigEntry=ceRedunMbrConfigEntry, ceRedunCompliances=ceRedunCompliances, ceRedunMemberStatus=ceRedunMemberStatus, ciscoEntityRedunMIBConform=ciscoEntityRedunMIBConform, ceRedunMbrStorageType=ceRedunMbrStorageType, ceRedunMbrPriority=ceRedunMbrPriority, ceRedunInternalStatesTable=ceRedunInternalStatesTable, ceRedunMbrMode=ceRedunMbrMode, ceRedunMbrSwitchoverSeconds=ceRedunMbrSwitchoverSeconds, ceRedunCommandsGroup=ceRedunCommandsGroup, ceRedunOptionalGroupTypes=ceRedunOptionalGroupTypes, ceRedunMbrProtectingMbr=ceRedunMbrProtectingMbr, ceRedunGroupTypeName=ceRedunGroupTypeName, ceRedunRemoteSystem=ceRedunRemoteSystem, ceRedunInternalStatesEntry=ceRedunInternalStatesEntry, ceRedunGroupIndex=ceRedunGroupIndex, ceRedunGroupTypesEntry=ceRedunGroupTypesEntry, ceRedunBidirectional=ceRedunBidirectional, ceRedunMbrLastSwitchover=ceRedunMbrLastSwitchover, ceRedunMbrSwitchoverCounts=ceRedunMbrSwitchoverCounts, ceRedunMbrRemoteAddress=ceRedunMbrRemoteAddress, ceRedunProtectStatusNotifGroup=ceRedunProtectStatusNotifGroup, ceRedunMbrPhysIndex=ceRedunMbrPhysIndex, ceRedunVendorType=ceRedunVendorType, ceRedunGroupRowStatus=ceRedunGroupRowStatus, ceRedunGroupTypeGroup=ceRedunGroupTypeGroup, ceRedunMbrStatusLastChanged=ceRedunMbrStatusLastChanged, ceRedunSwitchNotifGroup=ceRedunSwitchNotifGroup, ceRedunGroupString=ceRedunGroupString, ciscoEntityRedunMIBNotifs=ciscoEntityRedunMIBNotifs, ceRedunMbrStatusTable=ceRedunMbrStatusTable, ceRedunMbrStatusEntry=ceRedunMbrStatusEntry, ceRedunMembers=ceRedunMembers, ceRedunMbrNumber=ceRedunMbrNumber, ceRedunGroupLastChanged=ceRedunGroupLastChanged, ceRedunGroupDefinitionChanged=ceRedunGroupDefinitionChanged, ceRedunCommandEntry=ceRedunCommandEntry, ceRedunMemberConfig=ceRedunMemberConfig)
|
# Escreva a função maior_primo que recebe um número inteiro maior ou igual a 2 como parâmetro e devolve o maior número primo menor ou igual ao número passado à função
def maior_primo(n):
""" Recebe um inteiro >= 2 como parâmetro e devolve o maior número primo <= ao número passado.
Ex:
>>> maior_primo(100)
97
>>> maior_primo(7)
7
:param n: number
:return: number
"""
while n >= 2:
c = 0
p = n
while 0 < p <= n:
if n % p == 0:
c += 1
p -= 1
if c == 2:
return n
n -= 1
|
message = "This is a message!"
print(message)
message = "This is a new message!"
print(message) |
# author: Roy Kid
# contact: lijichen365@126.com
# date: 2021-09-20
# version: 0.0.1
def flat_kwargs(kwargs):
tmp = []
values = list(kwargs.values())
lenValue = len(values[0])
for v in values:
assert len(v) == lenValue, 'kwargs request aligned value'
for i in range(lenValue):
tmp.append({})
for k, v in kwargs.items():
for i, vv in enumerate(v):
tmp[i].update({k: vv})
return tmp
a = {'A': [1, 2, 3, 4], 'B': [2, 3, 4, 5]}
print(flat_kwargs(a)) |
# Feel free to add new properties and methods to the class.
"""
class MinMaxStack:
def __init__(self):
self.stack = []
self.min = float('inf')
self.max = float('-inf')
def _update_min(self, num, drop=False):
if drop and num == self.min:
self.min = min(self.stack or [float('inf')])
elif not drop and num < self.min:
self.min = num
def _update_max(self, num, drop=False):
if drop and num == self.max:
self.max = max(self.stack or [float('-inf')])
elif not drop and num > self.max:
self.max = num
def peek(self):
return self.stack[-1]
def pop(self):
num = self.stack.pop()
self._update_min(num, True)
self._update_max(num, True)
return num
def push(self, number):
self.stack.append(number)
self._update_min(number)
self._update_max(number)
def getMin(self):
return self.min
def getMax(self):
return self.max
"""
# Feel free to add new properties and methods to the class.
class MinMaxStack:
def __init__(self):
self.cached = []
self.stack = []
def peek(self):
return self.stack[-1]
def pop(self):
self.cached.pop()
return self.stack.pop()
def push(self, number):
cache = {'min': number, 'max': number}
if len(self.stack):
latest = self.cached[-1]
cache['min'] = min(number, latest['min'])
cache['max'] = max(number, latest['max'])
self.cached.append(cache)
self.stack.append(number)
def getMin(self):
return self.cached[-1]['min']
def getMax(self):
return self.cached[-1]['max']
|
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331001120
# Hideout :: Training Room 2
KINESIS = 1531000
JAY = 1531001
if "1" not in sm.getQuestEx(22700, "E2"):
sm.setNpcOverrideBoxChat(KINESIS)
sm.sendNext("Jay, I feel so slow walking around like this. I'm going to switch to my speedier moves.")
sm.setNpcOverrideBoxChat(JAY)
sm.sendSay("#face9#Fine, whatever! Just ignore the test plan I spent hours on... Okay, I updated my database with your #bTriple Jump#k and #bAttack Skills#k for the final stage. Go nuts, dude.")
sm.lockForIntro()
sm.playSound("Sound/Field.img/masteryBook/EnchantSuccess")
sm.showClearStageExpWindow(600)
sm.giveExp(600)
sm.playExclSoundWithDownBGM("Voice3.img/Kinesis/guide_04", 100)
sm.sendDelay(2500)
sm.unlockForIntro()
sm.warp(331001130, 0)
sm.setQuestEx(22700, "E1", "1") |
def do_something(x):
sq_x=x**2
return (sq_x) # this will make it much easier in future problems to see that something is actually happening
|
"""1143. Longest Common Subsequence"""
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
m = len(text1)
n = len(text2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i, a in enumerate(text1):
for j, b in enumerate(text2):
dp[i+1][j+1] = dp[i][j] + 1 if a == b else max(dp[i][j+1], dp[i+1][j])
return dp[-1][-1]
|
class Solution:
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
return s in (s[1:] + s[:-1])
if __name__ == '__main__':
solution = Solution()
print(solution.repeatedSubstringPattern("abab"))
print(solution.repeatedSubstringPattern("aaaa"))
print(solution.repeatedSubstringPattern("abaa"))
print(solution.repeatedSubstringPattern("abcabcabcabcabc"))
else:
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.