content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# These are local default variables for development # In deployment on Heroku's systems, these variables are changed DEBUG = True SECRET_KEY = "super_secret_key" LILLINK_REDIS_URL = "redis://localhost:6379/0"
debug = True secret_key = 'super_secret_key' lillink_redis_url = 'redis://localhost:6379/0'
numeroA = int(input('Digite um numero...')) outroNumero = int(input('Digite outro numero')) sum = numeroA + outroNumero print('A soma de {} e {} eh igual a {}' .format(numeroA, outroNumero, sum))
numero_a = int(input('Digite um numero...')) outro_numero = int(input('Digite outro numero')) sum = numeroA + outroNumero print('A soma de {} e {} eh igual a {}'.format(numeroA, outroNumero, sum))
file = open('2021\D8\input.txt','r').read().splitlines() s = [] mapcode = { 'a':'', 'b':'', 'c':'', 'd':'', 'e':'', 'f':'', 'g':'' } wirecode = { 0:'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:'', 8:'', 9:'' } numcode = { 0:'abcefg', 1:'cf', 2:'acdeg', 3:'acdfg', 4:'bcdf', 5:'abdfg', 6:'abdefg', 7:'acf', 8:'abcdefg', 9:'abcdfg' } for line in file: s.append(line.split('|')[1].split()) out = 0 for a in s: for i in a: l = len(i) if l==2 or l==3 or l==4 or l==7: out += 1 print(out) thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["brand"] = "no" print(thisdict["brand"])
file = open('2021\\D8\\input.txt', 'r').read().splitlines() s = [] mapcode = {'a': '', 'b': '', 'c': '', 'd': '', 'e': '', 'f': '', 'g': ''} wirecode = {0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: ''} numcode = {0: 'abcefg', 1: 'cf', 2: 'acdeg', 3: 'acdfg', 4: 'bcdf', 5: 'abdfg', 6: 'abdefg', 7: 'acf', 8: 'abcdefg', 9: 'abcdfg'} for line in file: s.append(line.split('|')[1].split()) out = 0 for a in s: for i in a: l = len(i) if l == 2 or l == 3 or l == 4 or (l == 7): out += 1 print(out) thisdict = {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} thisdict['brand'] = 'no' print(thisdict['brand'])
#!/usr/bin/env python # -*- coding: utf-8 -*- n = list(map(int, input().split())) def slove1(): ans, tmp = 0, -1 lmax,rmax = [0]*len(n), [0]*len(n) for i in range(1, len(n)): tmp = max(tmp, n[i-1]) lmax[i] = tmp tmp = -1 for i in range(len(n)-2, -1, -1): tmp = max(tmp, n[i+1]) rmax[i] = tmp for i in range(len(n)): if lmax[i] > n[i] and rmax[i] > n[i]: ans += min(lmax[i], rmax[i]) - n[i] return ans def slove2(): l, r = 0, len(n) - 1 lmax,rmax,ans = n[0],n[-1],0 while l < r: if lmax < rmax: l += 1 if n[l] > lmax: lmax = n[l] else: ans += lmax - n[l] else: r -= 1 if n[r] > rmax: rmax = n[r] else: ans += rmax -n[r] return ans print(slove1()) print(slove2())
n = list(map(int, input().split())) def slove1(): (ans, tmp) = (0, -1) (lmax, rmax) = ([0] * len(n), [0] * len(n)) for i in range(1, len(n)): tmp = max(tmp, n[i - 1]) lmax[i] = tmp tmp = -1 for i in range(len(n) - 2, -1, -1): tmp = max(tmp, n[i + 1]) rmax[i] = tmp for i in range(len(n)): if lmax[i] > n[i] and rmax[i] > n[i]: ans += min(lmax[i], rmax[i]) - n[i] return ans def slove2(): (l, r) = (0, len(n) - 1) (lmax, rmax, ans) = (n[0], n[-1], 0) while l < r: if lmax < rmax: l += 1 if n[l] > lmax: lmax = n[l] else: ans += lmax - n[l] else: r -= 1 if n[r] > rmax: rmax = n[r] else: ans += rmax - n[r] return ans print(slove1()) print(slove2())
# listFunctions.py # Contains basic list manipulation functions # J. Hassler Thurston # 26 November 2013 (Adapted from Mathematica code written in 2010/2011) # Python 2.7.6 # returns a running sum of the elements in ls def cumulativeSum(ls): total = 0 answer = [] for i in ls: total += i answer.append(total) return answer # returns a running sum of the elements in ls, starting with 0 def cumulativeSumZero(ls): total = 0 answer = [0] for i in ls: total += i answer.append(total) return answer
def cumulative_sum(ls): total = 0 answer = [] for i in ls: total += i answer.append(total) return answer def cumulative_sum_zero(ls): total = 0 answer = [0] for i in ls: total += i answer.append(total) return answer
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: binary_list = [] current = head while current: binary_list.append(str(current.val)) current = current.next return int("".join(binary_list), 2)
class Solution: def get_decimal_value(self, head: ListNode) -> int: binary_list = [] current = head while current: binary_list.append(str(current.val)) current = current.next return int(''.join(binary_list), 2)
_item_fullname_='Bio.Seq.Seq' def is_biopython_Seq(item): item_fullname = item.__class__.__module__+'.'+item.__class__.__name__ return _item_fullname_==item_fullname
_item_fullname_ = 'Bio.Seq.Seq' def is_biopython__seq(item): item_fullname = item.__class__.__module__ + '.' + item.__class__.__name__ return _item_fullname_ == item_fullname
def ci(A, l, r, k): while r-l > 1: mid = (l + (r-l))//2 if A[mid] >= k: r=mid else: l=mid return r def longestSubsequence(a,n): t = [0 for _ in range(n+1)] l=0 t[0] = a[0] l=1 for i in range(1, n): if a[i] < t[0]: t[0] = a[i] elif a[i] > t[l-1]: t[l] = a[i] l+=1 else: x = ci(a, -1, l-1, a[i]) t[x] = a[i] return l a = list(map(int, input().split(','))) print(longestSubsequence(a,len(a)))
def ci(A, l, r, k): while r - l > 1: mid = (l + (r - l)) // 2 if A[mid] >= k: r = mid else: l = mid return r def longest_subsequence(a, n): t = [0 for _ in range(n + 1)] l = 0 t[0] = a[0] l = 1 for i in range(1, n): if a[i] < t[0]: t[0] = a[i] elif a[i] > t[l - 1]: t[l] = a[i] l += 1 else: x = ci(a, -1, l - 1, a[i]) t[x] = a[i] return l a = list(map(int, input().split(','))) print(longest_subsequence(a, len(a)))
passmark=0 # declaring variables defer=0 fail=0 all=0 def all(): try: #this won't let strings to pass while True: passmark=int(input("Enter the Pass mark :")) # getting the user's passmark if passmark == 0 or passmark == 20 or passmark == 40 or passmark == 60 or passmark == 80 or passmark == 100 or passmark == 120: while True: defer=int(input("Enter the Defer mark :")) # getting the user's defermark if defer == 0 or defer == 20 or defer == 40 or defer == 60 or defer == 80 or defer == 100 or defer == 120: while True: fail=int(input("Enter the fail mark :")) # getting the user's failmark if fail == 0 or fail == 20 or fail == 40 or fail == 60 or fail == 80 or fail == 100 or fail == 120: tot = passmark + defer + fail if tot == 120: # checking whether total of enterted marks are equal to 120 if passmark ==120: print ("progress") #printing outputs elif passmark==100: print ("Progress-module treiler\n") elif fail >= 80: print("Exclude") else: print("Do not progress-module retriever\n") else: print("Total Incorrect") #printing errors all() else: print("Range error\n") all() break else: print("Range error\n") all() break else: print("Range error\n") all() break except ValueError: #checking integer errors print("Integer error") all() all()
passmark = 0 defer = 0 fail = 0 all = 0 def all(): try: while True: passmark = int(input('Enter the Pass mark :')) if passmark == 0 or passmark == 20 or passmark == 40 or (passmark == 60) or (passmark == 80) or (passmark == 100) or (passmark == 120): while True: defer = int(input('Enter the Defer mark :')) if defer == 0 or defer == 20 or defer == 40 or (defer == 60) or (defer == 80) or (defer == 100) or (defer == 120): while True: fail = int(input('Enter the fail mark :')) if fail == 0 or fail == 20 or fail == 40 or (fail == 60) or (fail == 80) or (fail == 100) or (fail == 120): tot = passmark + defer + fail if tot == 120: if passmark == 120: print('progress') elif passmark == 100: print('Progress-module treiler\n') elif fail >= 80: print('Exclude') else: print('Do not progress-module retriever\n') else: print('Total Incorrect') all() else: print('Range error\n') all() break else: print('Range error\n') all() break else: print('Range error\n') all() break except ValueError: print('Integer error') all() all()
def extract(graph): ''' Generate a dictionary from a NetworkX Graph. The key is the index (primary node identifier) of the node in the graph. The value is a dict with index, label (original node identifier), room (a node attribute from the source data), and a list of neighbors (by graph index value). ''' result = {} for node in graph.nodes: result[node] = {'index': node, 'label': graph.nodes[node]['label'], 'room': graph.nodes[node]['room'], 'neighbors': [edge[1] for edge in graph.edges(nbunch=node)]} return result def transform(extract): ''' Transforms the Graph extract, replacing all Graph index values with original dource data labels. The result is a dictionary, where the key is a node label and the value is a dict with room and a sored list of neighbors (labels, the original node identifiers). ''' result = {} for index in extract.keys(): result[extract[index]['label']] = {'room': extract[index]['room'], 'neighbors': sorted([extract[n]['label'] for n in extract[index]['neighbors']])} return result def dotted(numbers): ''' Transform a space-separated list of numbers into a string with dots separating the numbers. ''' return ".".join([str(n) for n in numbers]) def flatten(transform): ''' Convert the transformed Graph extract dict into a list of lists. Each list entry contains three elements: the node label, the room, and dotted string of neighbors. ''' result = [] for label in transform.keys(): #result.append(f"{label},{transform[label]['room']},{dotted(transform[label]['neighbors'])}") result.append([label,f"{transform[label]['room']}",f"{dotted(transform[label]['neighbors'])}"]) return result def equal(graph1, graph2): ''' Compare two graphs, at a basic level: a sort of extended node-edge list ''' return (sorted(flatten(transform(extract(graph1)))) == sorted(flatten(transform(extract(graph2))))) def compare(graphs1, graphs2): ''' Compare two lists of Graphs. ''' for i in range(len(graphs1)): print(i,equal(graphs1[i], graphs2[i]))
def extract(graph): """ Generate a dictionary from a NetworkX Graph. The key is the index (primary node identifier) of the node in the graph. The value is a dict with index, label (original node identifier), room (a node attribute from the source data), and a list of neighbors (by graph index value). """ result = {} for node in graph.nodes: result[node] = {'index': node, 'label': graph.nodes[node]['label'], 'room': graph.nodes[node]['room'], 'neighbors': [edge[1] for edge in graph.edges(nbunch=node)]} return result def transform(extract): """ Transforms the Graph extract, replacing all Graph index values with original dource data labels. The result is a dictionary, where the key is a node label and the value is a dict with room and a sored list of neighbors (labels, the original node identifiers). """ result = {} for index in extract.keys(): result[extract[index]['label']] = {'room': extract[index]['room'], 'neighbors': sorted([extract[n]['label'] for n in extract[index]['neighbors']])} return result def dotted(numbers): """ Transform a space-separated list of numbers into a string with dots separating the numbers. """ return '.'.join([str(n) for n in numbers]) def flatten(transform): """ Convert the transformed Graph extract dict into a list of lists. Each list entry contains three elements: the node label, the room, and dotted string of neighbors. """ result = [] for label in transform.keys(): result.append([label, f"{transform[label]['room']}", f"{dotted(transform[label]['neighbors'])}"]) return result def equal(graph1, graph2): """ Compare two graphs, at a basic level: a sort of extended node-edge list """ return sorted(flatten(transform(extract(graph1)))) == sorted(flatten(transform(extract(graph2)))) def compare(graphs1, graphs2): """ Compare two lists of Graphs. """ for i in range(len(graphs1)): print(i, equal(graphs1[i], graphs2[i]))
def dobra_lista(lista): nova_lista = [] for valor in lista: novo_elemento = 2 * valor nova_lista.append(novo_elemento) return nova_lista #---------------------------------------------------------------- numeros = [3, 6, 10] numeros_emdobro = dobra_lista(numeros) print(numeros) print(numeros_emdobro)
def dobra_lista(lista): nova_lista = [] for valor in lista: novo_elemento = 2 * valor nova_lista.append(novo_elemento) return nova_lista numeros = [3, 6, 10] numeros_emdobro = dobra_lista(numeros) print(numeros) print(numeros_emdobro)
def test_length(devnetwork, chain): assert len(chain) == 1 chain.mine(4) assert len(chain) == 5 def test_length_after_revert(devnetwork, chain): chain.mine(4) chain.snapshot() chain.mine(20) assert len(chain) == 25 chain.revert() assert len(chain) == 5 def test_getitem_negative_index(devnetwork, accounts, chain, web3): block = chain[-1] assert block == web3.eth.getBlock("latest") accounts[0].transfer(accounts[1], 1000) assert chain[-1] != block assert chain[-1] == web3.eth.getBlock("latest") def test_getitem_positive_index(devnetwork, accounts, chain, web3): block = chain[0] assert block == web3.eth.getBlock("latest") accounts[0].transfer(accounts[1], 1000) assert chain[0] == block assert chain[0] != web3.eth.getBlock("latest")
def test_length(devnetwork, chain): assert len(chain) == 1 chain.mine(4) assert len(chain) == 5 def test_length_after_revert(devnetwork, chain): chain.mine(4) chain.snapshot() chain.mine(20) assert len(chain) == 25 chain.revert() assert len(chain) == 5 def test_getitem_negative_index(devnetwork, accounts, chain, web3): block = chain[-1] assert block == web3.eth.getBlock('latest') accounts[0].transfer(accounts[1], 1000) assert chain[-1] != block assert chain[-1] == web3.eth.getBlock('latest') def test_getitem_positive_index(devnetwork, accounts, chain, web3): block = chain[0] assert block == web3.eth.getBlock('latest') accounts[0].transfer(accounts[1], 1000) assert chain[0] == block assert chain[0] != web3.eth.getBlock('latest')
class Node: __slots__ = ['key','value','prev','next'] def __init__(self, key, value): self.key = key self.value = value self.prev = None self.next = None class LRUCache: def __init__(self, capacity): self.capacity = capacity self.size = 0 self.mapping = {} self.head = self.tail = None def __insert_to_head(self, node): saved_head = self.head self.head = node node.prev = None if saved_head is None: # first node self.tail = node return node.next = saved_head saved_head.prev = node def __move_to_head(self, node): # node is already the head if node.prev is None: return # link node's neighbors if node.next is None: # tail was this node, moving it will cause tail change. self.tail = node.prev else: node.next.prev = node.prev node.prev.next = node.next self.__insert_to_head(node) def __cut_tail(self): if self.tail is None: return saved_tail = self.tail saved_key = saved_tail.key self.tail = saved_tail.prev self.tail.next = None self.mapping.pop(saved_key) self.size -= 1 def __add_new(self, key, value): node = Node(key, value) self.__insert_to_head(node) self.mapping[key] = node self.size += 1 if self.size > self.capacity: self.__cut_tail() def get(self, key): node = self.mapping.get(key) if node is not None: self.__move_to_head(node) return node.value else: return None def set(self, key, value): node = self.mapping.get(key) if node is not None: node.value = value self.__move_to_head(node) else: self.__add_new(key, value) def touch(self, key, value): self.set(key, value)
class Node: __slots__ = ['key', 'value', 'prev', 'next'] def __init__(self, key, value): self.key = key self.value = value self.prev = None self.next = None class Lrucache: def __init__(self, capacity): self.capacity = capacity self.size = 0 self.mapping = {} self.head = self.tail = None def __insert_to_head(self, node): saved_head = self.head self.head = node node.prev = None if saved_head is None: self.tail = node return node.next = saved_head saved_head.prev = node def __move_to_head(self, node): if node.prev is None: return if node.next is None: self.tail = node.prev else: node.next.prev = node.prev node.prev.next = node.next self.__insert_to_head(node) def __cut_tail(self): if self.tail is None: return saved_tail = self.tail saved_key = saved_tail.key self.tail = saved_tail.prev self.tail.next = None self.mapping.pop(saved_key) self.size -= 1 def __add_new(self, key, value): node = node(key, value) self.__insert_to_head(node) self.mapping[key] = node self.size += 1 if self.size > self.capacity: self.__cut_tail() def get(self, key): node = self.mapping.get(key) if node is not None: self.__move_to_head(node) return node.value else: return None def set(self, key, value): node = self.mapping.get(key) if node is not None: node.value = value self.__move_to_head(node) else: self.__add_new(key, value) def touch(self, key, value): self.set(key, value)
#!/usr/bin/env python3 # https://abc067.contest.atcoder.jp/tasks/arc078_a n = int(input()) a = [int(x) for x in input().split()] s = sum(a) b = a[0] m = abs(s - 2 * b) for i in range(1, n - 1): b += a[i] m = min(m, abs(s - 2 * b)) print(m)
n = int(input()) a = [int(x) for x in input().split()] s = sum(a) b = a[0] m = abs(s - 2 * b) for i in range(1, n - 1): b += a[i] m = min(m, abs(s - 2 * b)) print(m)
# SPDX-License-Identifier: MIT # # keys.py - includes Discord bot token # # Copyright (c) 2019 Joe Dai. TOKEN = ''
token = ''
model = Model() i1 = Input("input", "TENSOR_FLOAT32", "{3,4,2}") perms = Parameter("perms", "TENSOR_INT32", "{3}", [1, 0, 2]) output = Output("output", "TENSOR_FLOAT32", "{4,3,2}") model = model.Operation("TRANSPOSE", i1, perms).To(output) # Example 1. Input in operand 0, input0 = {i1: # input 0 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]} output0 = {output: # output 0 [ 0, 1, 8, 9, 16, 17, 2, 3, 10, 11, 18, 19, 4, 5, 12, 13, 20, 21, 6, 7, 14, 15, 22, 23]} # Instantiate an example Example((input0, output0))
model = model() i1 = input('input', 'TENSOR_FLOAT32', '{3,4,2}') perms = parameter('perms', 'TENSOR_INT32', '{3}', [1, 0, 2]) output = output('output', 'TENSOR_FLOAT32', '{4,3,2}') model = model.Operation('TRANSPOSE', i1, perms).To(output) input0 = {i1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]} output0 = {output: [0, 1, 8, 9, 16, 17, 2, 3, 10, 11, 18, 19, 4, 5, 12, 13, 20, 21, 6, 7, 14, 15, 22, 23]} example((input0, output0))
description = 'TOF counter devices' group = 'lowlevel' tango_base = 'tango://cpci3.toftof.frm2:10000/' devices = dict( timer = device('nicos.devices.entangle.TimerChannel', description = 'The TOFTOF timer', tangodevice = tango_base + 'toftof/det/timer', fmtstr = '%.1f', visibility = (), ), monitor = device('nicos.devices.entangle.CounterChannel', description = 'The TOFTOF monitor', tangodevice = tango_base + 'toftof/det/monitor', type = 'monitor', presetaliases = ['mon1'], fmtstr = '%d', unit = 'cts', visibility = (), ), image = device('nicos_mlz.toftof.devices.TOFTOFChannel', description = 'The TOFTOF image', tangodevice = tango_base + 'toftof/det/histogram', timechannels = 1024, fmtstr = '%d', unit = 'cts', visibility = (), ), det = device('nicos_mlz.toftof.devices.Detector', description = 'The TOFTOF detector device', timers = ['timer'], monitors = ['monitor'], images = ['image'], rc = 'rc_onoff', chopper = 'ch', chdelay = 'chdelay', pollinterval = None, liveinterval = 10.0, saveintervals = [30.], detinfofile = '/toftofcontrol/nicos_mlz/toftof/detinfo.dat', ), )
description = 'TOF counter devices' group = 'lowlevel' tango_base = 'tango://cpci3.toftof.frm2:10000/' devices = dict(timer=device('nicos.devices.entangle.TimerChannel', description='The TOFTOF timer', tangodevice=tango_base + 'toftof/det/timer', fmtstr='%.1f', visibility=()), monitor=device('nicos.devices.entangle.CounterChannel', description='The TOFTOF monitor', tangodevice=tango_base + 'toftof/det/monitor', type='monitor', presetaliases=['mon1'], fmtstr='%d', unit='cts', visibility=()), image=device('nicos_mlz.toftof.devices.TOFTOFChannel', description='The TOFTOF image', tangodevice=tango_base + 'toftof/det/histogram', timechannels=1024, fmtstr='%d', unit='cts', visibility=()), det=device('nicos_mlz.toftof.devices.Detector', description='The TOFTOF detector device', timers=['timer'], monitors=['monitor'], images=['image'], rc='rc_onoff', chopper='ch', chdelay='chdelay', pollinterval=None, liveinterval=10.0, saveintervals=[30.0], detinfofile='/toftofcontrol/nicos_mlz/toftof/detinfo.dat'))
def colorify(s, color): color_map = { "grey": "\033[90m", "red": "\033[91m", "green": "\033[92m", "yellow": "\033[93m", "purple": "\033[94m", "pink": "\033[95m", "blue": "\033[96m", } return color_map[color] + s + "\033[0m" def underline(s): return "\033[4m" + s + "\033[0m"
def colorify(s, color): color_map = {'grey': '\x1b[90m', 'red': '\x1b[91m', 'green': '\x1b[92m', 'yellow': '\x1b[93m', 'purple': '\x1b[94m', 'pink': '\x1b[95m', 'blue': '\x1b[96m'} return color_map[color] + s + '\x1b[0m' def underline(s): return '\x1b[4m' + s + '\x1b[0m'
class ItemAlreadyStored(Exception): pass class ItemNotStored(Exception): pass
class Itemalreadystored(Exception): pass class Itemnotstored(Exception): pass
_base_="../base-chexpert-chest_xray_kids-config.py" # epoch related total_iters=5000 checkpoint_config = dict(interval=total_iters) model = dict( pretrained='work_dirs/hpt-pretrain/resisc/moco_v2_800ep_basetrain/50000-iters/moco_v2_800ep_basetrain-resisc_50000it.pth', backbone=dict( norm_train=True, frozen_stages=4, ) ) optimizer = dict(type='SGD', lr=0.003, weight_decay=0.0001, momentum=0.9)
_base_ = '../base-chexpert-chest_xray_kids-config.py' total_iters = 5000 checkpoint_config = dict(interval=total_iters) model = dict(pretrained='work_dirs/hpt-pretrain/resisc/moco_v2_800ep_basetrain/50000-iters/moco_v2_800ep_basetrain-resisc_50000it.pth', backbone=dict(norm_train=True, frozen_stages=4)) optimizer = dict(type='SGD', lr=0.003, weight_decay=0.0001, momentum=0.9)
# # Copyright 2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # CIM 4.20.2 # Defines tags associated with data models. Used to determine the DM's associated with tags returned by the Splunk # search for eg: 'tag': "['authentication', 'insecure', 'network', 'resolution', 'dns', 'success']" matches # 'Authentication': ['authentication'], 'Authentication_Insecure_Authentication': ['authentication', 'insecure'], # 'Network_Resolution': ['network', 'resolution', 'dns'] dict_datamodel_tag = { "Alerts": ["alert"], "Authentication": ["authentication"], "Authentication_Default_Authentication": ["default", "authentication"], "Authentication_Insecure_Authentication": ["authentication", "insecure"], "Authentication_Insecure_Authentication.2": ["authentication", "cleartext"], "Authentication_Privileged_Authentication": ["authentication", "privileged"], "Certificates": ["certificate"], "Certificates_SSL": ["certificate", "ssl"], "Change": ["change"], "Change_Auditing_Changes": ["change", "audit"], "Change_Endpoint_Changes": ["change", "endpoint"], "Change_Network_Changes": ["change", "network"], "Change_Account_Management": ["change", "account"], "Change_Instance_Changes": ["change", "instance"], "Compute_Inventory_CPU": ["inventory", "cpu"], "Compute_Inventory_Memory": ["inventory", "memory"], "Compute_Inventory_Network": ["inventory", "network"], "Compute_Inventory_Storage": ["inventory", "storage"], "Compute_Inventory_OS": ["inventory", "system", "version"], "Compute_Inventory_User": ["inventory", "user"], "Compute_Inventory_User_Default_Accounts": ["inventory", "user", "default"], "Compute_Inventory_Virtual_OS": ["inventory", "virtual"], "Compute_Inventory_Virtual_OS_Snapshot": ["inventory", "virtual", "snapshot"], "Compute_Inventory_Virtual_OS_Tools": ["inventory", "virtual", "tools"], "Databases": ["database"], "Databases_Database_Instance": ["database", "instance"], "Databases_Database_Instance_Instance_Stats": ["database", "instance", "stats"], "Databases_Database_Instance_Session_Info": ["database", "instance", "session"], "Databases_Database_Instance_Lock_Info": ["database", "instance", "lock"], "Databases_Database_Query": ["database", "query"], "Databases_Database_Query_tablespace": ["database", "query", "tablespace"], "Databases_Database_Query_Query_Stats": ["database", "query", "stats"], "DLP": ["dlp", "incident"], "Email": ["email"], "Email_Delivery": ["email", "delivery"], "Email_Content": ["email", "content"], "Email_Filtering": ["email", "filter"], "Endpoint_ports": ["listening", "port"], "Endpoint_Processes": ["process", "report"], "Endpoint_Filesystem": ["endpoint", "filesystem"], "Endpoint_Services": ["service", "report"], "Endpoint_Registry": ["endpoint", "registry"], "Event_Signatures_Signatures": ["track_event_signatures"], "Interprocess_Messaging": ["messaging"], "Intrusion_Detection": ["ids", "attack"], "JVM": ["jvm"], "JVM_Runtime": ["jvm", "runtime"], "JVM_OS": ["jvm", "os"], "JVM_Classloading": ["jvm", "classloading"], "JVM_Memory": ["jvm", "memory"], "JVM_Threading": ["jvm", "threading"], "JVM_Compilation": ["jvm", "compilation"], "Malware_Malware_Attacks": ["malware", "attack"], "Malware_Malware_Operations": ["malware", "operations"], "Network_Resolution_DNS": ["network", "resolution", "dns"], "Network_Sessions": ["network", "session"], "Network_Sessions_Session_Start": ["network", "session", "start"], "Network_Sessions_Session_End": ["network", "session", "end"], "Network_Sessions_DHCP": ["network", "session", "dhcp"], "Network_Sessions_VPN": ["network", "session", "vpn"], "Network_Traffic": ["network", "communicate"], "Performance_CPU": ["performance", "cpu"], "Performance_Facilities": ["performance", "facilities"], "Performance_Memory": ["performance", "memory"], "Performance_Storage": ["performance", "storage"], "Performance_Network": ["performance", "network"], "Performance_OS": ["performance", "os"], "Performance_OS_Timesync": ["performance", "os", "time", "synchronize"], "Performance_OS_Uptime": ["performance", "os", "uptime"], "Splunk_Audit": ["modaction"], "Splunk_Audit_Modular_Action_Invocations": ["modaction", "invocation"], "Ticket_Management": ["ticketing"], "Ticket_Management_Change": ["ticketing", "change"], "Ticket_Management_Incident": ["ticketing", "incident"], "Ticket_Management_Problem": ["ticketing", "problem"], "Updates": ["update", "status"], "Updates_Update_Errors": ["update", "error"], "Vulnerabilities": ["report", "vulnerability"], "Web": ["web"], "Web_Proxy": ["web", "proxy"], "Web_Storage": ["web", "storage"], "Data_Access": ["data", "access"], }
dict_datamodel_tag = {'Alerts': ['alert'], 'Authentication': ['authentication'], 'Authentication_Default_Authentication': ['default', 'authentication'], 'Authentication_Insecure_Authentication': ['authentication', 'insecure'], 'Authentication_Insecure_Authentication.2': ['authentication', 'cleartext'], 'Authentication_Privileged_Authentication': ['authentication', 'privileged'], 'Certificates': ['certificate'], 'Certificates_SSL': ['certificate', 'ssl'], 'Change': ['change'], 'Change_Auditing_Changes': ['change', 'audit'], 'Change_Endpoint_Changes': ['change', 'endpoint'], 'Change_Network_Changes': ['change', 'network'], 'Change_Account_Management': ['change', 'account'], 'Change_Instance_Changes': ['change', 'instance'], 'Compute_Inventory_CPU': ['inventory', 'cpu'], 'Compute_Inventory_Memory': ['inventory', 'memory'], 'Compute_Inventory_Network': ['inventory', 'network'], 'Compute_Inventory_Storage': ['inventory', 'storage'], 'Compute_Inventory_OS': ['inventory', 'system', 'version'], 'Compute_Inventory_User': ['inventory', 'user'], 'Compute_Inventory_User_Default_Accounts': ['inventory', 'user', 'default'], 'Compute_Inventory_Virtual_OS': ['inventory', 'virtual'], 'Compute_Inventory_Virtual_OS_Snapshot': ['inventory', 'virtual', 'snapshot'], 'Compute_Inventory_Virtual_OS_Tools': ['inventory', 'virtual', 'tools'], 'Databases': ['database'], 'Databases_Database_Instance': ['database', 'instance'], 'Databases_Database_Instance_Instance_Stats': ['database', 'instance', 'stats'], 'Databases_Database_Instance_Session_Info': ['database', 'instance', 'session'], 'Databases_Database_Instance_Lock_Info': ['database', 'instance', 'lock'], 'Databases_Database_Query': ['database', 'query'], 'Databases_Database_Query_tablespace': ['database', 'query', 'tablespace'], 'Databases_Database_Query_Query_Stats': ['database', 'query', 'stats'], 'DLP': ['dlp', 'incident'], 'Email': ['email'], 'Email_Delivery': ['email', 'delivery'], 'Email_Content': ['email', 'content'], 'Email_Filtering': ['email', 'filter'], 'Endpoint_ports': ['listening', 'port'], 'Endpoint_Processes': ['process', 'report'], 'Endpoint_Filesystem': ['endpoint', 'filesystem'], 'Endpoint_Services': ['service', 'report'], 'Endpoint_Registry': ['endpoint', 'registry'], 'Event_Signatures_Signatures': ['track_event_signatures'], 'Interprocess_Messaging': ['messaging'], 'Intrusion_Detection': ['ids', 'attack'], 'JVM': ['jvm'], 'JVM_Runtime': ['jvm', 'runtime'], 'JVM_OS': ['jvm', 'os'], 'JVM_Classloading': ['jvm', 'classloading'], 'JVM_Memory': ['jvm', 'memory'], 'JVM_Threading': ['jvm', 'threading'], 'JVM_Compilation': ['jvm', 'compilation'], 'Malware_Malware_Attacks': ['malware', 'attack'], 'Malware_Malware_Operations': ['malware', 'operations'], 'Network_Resolution_DNS': ['network', 'resolution', 'dns'], 'Network_Sessions': ['network', 'session'], 'Network_Sessions_Session_Start': ['network', 'session', 'start'], 'Network_Sessions_Session_End': ['network', 'session', 'end'], 'Network_Sessions_DHCP': ['network', 'session', 'dhcp'], 'Network_Sessions_VPN': ['network', 'session', 'vpn'], 'Network_Traffic': ['network', 'communicate'], 'Performance_CPU': ['performance', 'cpu'], 'Performance_Facilities': ['performance', 'facilities'], 'Performance_Memory': ['performance', 'memory'], 'Performance_Storage': ['performance', 'storage'], 'Performance_Network': ['performance', 'network'], 'Performance_OS': ['performance', 'os'], 'Performance_OS_Timesync': ['performance', 'os', 'time', 'synchronize'], 'Performance_OS_Uptime': ['performance', 'os', 'uptime'], 'Splunk_Audit': ['modaction'], 'Splunk_Audit_Modular_Action_Invocations': ['modaction', 'invocation'], 'Ticket_Management': ['ticketing'], 'Ticket_Management_Change': ['ticketing', 'change'], 'Ticket_Management_Incident': ['ticketing', 'incident'], 'Ticket_Management_Problem': ['ticketing', 'problem'], 'Updates': ['update', 'status'], 'Updates_Update_Errors': ['update', 'error'], 'Vulnerabilities': ['report', 'vulnerability'], 'Web': ['web'], 'Web_Proxy': ['web', 'proxy'], 'Web_Storage': ['web', 'storage'], 'Data_Access': ['data', 'access']}
# Python - 3.6.0 Test.describe('thirt') Test.it('Basic tests') Test.assert_equals(thirt(8529), 79) Test.assert_equals(thirt(85299258), 31) Test.assert_equals(thirt(5634), 57) Test.assert_equals(thirt(1111111111), 71) Test.assert_equals(thirt(987654321), 30)
Test.describe('thirt') Test.it('Basic tests') Test.assert_equals(thirt(8529), 79) Test.assert_equals(thirt(85299258), 31) Test.assert_equals(thirt(5634), 57) Test.assert_equals(thirt(1111111111), 71) Test.assert_equals(thirt(987654321), 30)
class HistMovementManager: def __init__(self): self.boards_hist = [] self.cur_board = -1 self.offset = 0 def make_screen(self, board): if self.cur_board != -1 and self.boards_hist[self.cur_board] == board: return self.boards_hist.append(board) self.cur_board += 1 def get_prev(self): if self.cur_board + self.offset > 0: self.offset -= 1 return self.boards_hist[self.cur_board + self.offset] def get_next(self): if self.offset < 0: self.offset += 1 return self.boards_hist[self.cur_board + self.offset] def clear(self): self.boards_hist = [] self.cur_board = -1 self.offset = 0 def get_hist_board(self): return self.boards_hist[self.cur_board + self.offset] def up_to_date(self): return self.offset == 0 def reset_offset(self): self.offset = 0
class Histmovementmanager: def __init__(self): self.boards_hist = [] self.cur_board = -1 self.offset = 0 def make_screen(self, board): if self.cur_board != -1 and self.boards_hist[self.cur_board] == board: return self.boards_hist.append(board) self.cur_board += 1 def get_prev(self): if self.cur_board + self.offset > 0: self.offset -= 1 return self.boards_hist[self.cur_board + self.offset] def get_next(self): if self.offset < 0: self.offset += 1 return self.boards_hist[self.cur_board + self.offset] def clear(self): self.boards_hist = [] self.cur_board = -1 self.offset = 0 def get_hist_board(self): return self.boards_hist[self.cur_board + self.offset] def up_to_date(self): return self.offset == 0 def reset_offset(self): self.offset = 0
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- __all__ = [ "functions", "dbcontent", "sqlite_helper", "global_variable" ]
__all__ = ['functions', 'dbcontent', 'sqlite_helper', 'global_variable']
float_type = type(1.0) int_type = type(1) string_type = type('') date_type = 'iso8601' unicode_type = type(u'') bool_type = type(True) map_type = type({}) seq_type = type([]) tuple_type = type(()) def is_string(obj): t = type(obj) return t is string_type or t is unicode_type def is_int(obj): return type(obj) is int_type def is_float(obj): return type(obj) is float_type def is_number(obj): t = type(obj) return t is int_type or t is float_type def is_map(obj): return type(obj) is map_type def is_seq(obj): return type(obj) is seq_type def is_tuple(obj): return type(obj) is tuple_type def is_bool(obj): return type(obj) is bool_type def is_scalar(obj): t = type(obj) return not (t is map_type or t is seq_type or t is tuple_type) def get_simple_type_name(obj): if is_string(obj): return 'str' if is_map(obj): return 'map' if is_seq(obj): return 'seq' if is_tuple(obj): return 'tuple' if is_int(obj): return 'int' if is_float(obj): return 'float' if is_bool(obj): return 'bool' if obj is None: return 'null' return str(type(obj))
float_type = type(1.0) int_type = type(1) string_type = type('') date_type = 'iso8601' unicode_type = type(u'') bool_type = type(True) map_type = type({}) seq_type = type([]) tuple_type = type(()) def is_string(obj): t = type(obj) return t is string_type or t is unicode_type def is_int(obj): return type(obj) is int_type def is_float(obj): return type(obj) is float_type def is_number(obj): t = type(obj) return t is int_type or t is float_type def is_map(obj): return type(obj) is map_type def is_seq(obj): return type(obj) is seq_type def is_tuple(obj): return type(obj) is tuple_type def is_bool(obj): return type(obj) is bool_type def is_scalar(obj): t = type(obj) return not (t is map_type or t is seq_type or t is tuple_type) def get_simple_type_name(obj): if is_string(obj): return 'str' if is_map(obj): return 'map' if is_seq(obj): return 'seq' if is_tuple(obj): return 'tuple' if is_int(obj): return 'int' if is_float(obj): return 'float' if is_bool(obj): return 'bool' if obj is None: return 'null' return str(type(obj))
class Field(object): sql_type = None py_type = None def __init__(self, name=None, value=None, pk=None, unique=None, not_null=None): self.name = name self.pk = pk self.unique = unique self.not_null = not_null self.value = value def set_name(self, name): self.name = name def set_value(self, value): self.value = value def get_sql_ddl(self): ret = f'{self.name} {self.sql_type.name}' if self.pk: ret += ' PRIMARY KEY' if self.unique: ret += ' UNIQUE' if self.not_null: ret += ' NOT NULL' return ret def from_sql_to_python(self): return self.py_type(self.value) def from_python_to_sql(self): return self.sql_type.from_python_to_sql(self.value) class SqlType(object): name = None def from_python_to_sql(self, value): raise NotImplemented class IntegerType(SqlType): name = 'INT' def from_python_to_sql(self, value): return str(value) class TextType(SqlType): name = 'TEXT' def from_python_to_sql(self, value): return f"'{value}'"
class Field(object): sql_type = None py_type = None def __init__(self, name=None, value=None, pk=None, unique=None, not_null=None): self.name = name self.pk = pk self.unique = unique self.not_null = not_null self.value = value def set_name(self, name): self.name = name def set_value(self, value): self.value = value def get_sql_ddl(self): ret = f'{self.name} {self.sql_type.name}' if self.pk: ret += ' PRIMARY KEY' if self.unique: ret += ' UNIQUE' if self.not_null: ret += ' NOT NULL' return ret def from_sql_to_python(self): return self.py_type(self.value) def from_python_to_sql(self): return self.sql_type.from_python_to_sql(self.value) class Sqltype(object): name = None def from_python_to_sql(self, value): raise NotImplemented class Integertype(SqlType): name = 'INT' def from_python_to_sql(self, value): return str(value) class Texttype(SqlType): name = 'TEXT' def from_python_to_sql(self, value): return f"'{value}'"
# cypher.py - encrypt and decrypt messages def cypher(message, key): result = "" for ch in message: ch = chr(ord(ch) ^ key) result += ch return result def run(): plaintext = input("message? ") key = input("hex number for key? ") key = int(key, 16) cyphertext = cypher(plaintext, key) print(cyphertext)
def cypher(message, key): result = '' for ch in message: ch = chr(ord(ch) ^ key) result += ch return result def run(): plaintext = input('message? ') key = input('hex number for key? ') key = int(key, 16) cyphertext = cypher(plaintext, key) print(cyphertext)
__all__ = [ 'q1_itertools_product', 'q2_itertools_permutations', 'q3_itertools_combinations', 'q4_itertools_combinations_with_replacement', 'q5_compress_the_string', 'q6_iterables_and_iterators', 'q7_maximize_it' ]
__all__ = ['q1_itertools_product', 'q2_itertools_permutations', 'q3_itertools_combinations', 'q4_itertools_combinations_with_replacement', 'q5_compress_the_string', 'q6_iterables_and_iterators', 'q7_maximize_it']
# This file is part of LibCSS. # Licensed under the MIT License, # http://www.opensource.org/licenses/mit-license.php # Copyright 2017 Lucas Neves <lcneves@gmail.com> # Configuration of CSS values. # The tuples in this set will be unpacked as arguments to the CSSValue # class. # Args: see docstring for class CSSValue in select_generator.py. values = { ('length', 'css_fixed', 4, '0', 'unit', 'css_unit', 5, 'CSS_UNIT_PX'), ('integer', 'int32_t', 4, '0'), ('fixed', 'css_fixed', 4, '0'), ('color', 'css_color', 4, '0'), ('string', 'lwc_string*'), ('string_arr', 'lwc_string**'), ('counter_arr', 'css_computed_counter*'), ('content_item', 'css_computed_content_item*') } # Configuration of property groups. # The tuples in these sets will be unpacked as arguments to the # CSSproperty class. # Args: see docstring for class CSSProperty in select_generator.py. style = { # Style group, only opcode ('align_content', 3), ('align_items', 3), ('align_self', 3), ('background_attachment', 2), ('background_repeat', 3), ('border_collapse', 2), ('border_top_style', 4), ('border_right_style', 4), ('border_bottom_style', 4), ('border_left_style', 4), ('box_sizing', 2), ('caption_side', 2), ('clear', 3), ('direction', 2), ('display', 5), ('empty_cells', 2), ('flex_direction', 3), ('flex_wrap', 2), ('float', 2), ('font_style', 2), ('font_variant', 2), ('font_weight', 4), ('justify_content', 3), ('list_style_position', 2), ('list_style_type', 4), ('overflow_x', 3), ('overflow_y', 3), ('outline_style', 4), ('position', 3), ('table_layout', 2), ('text_align', 4), ('text_decoration', 5), ('text_transform', 3), ('unicode_bidi', 2), ('visibility', 2), ('white_space', 3), # Style group, with additional value ('background_color', 2, 'color'), ('background_image', 1, 'string'), ('background_position', 1, (('length',), ('length',)), 'CSS_BACKGROUND_POSITION_SET'), ('border_top_color', 2, 'color'), ('border_right_color', 2, 'color'), ('border_bottom_color', 2, 'color'), ('border_left_color', 2, 'color'), ('border_top_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_right_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_bottom_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_left_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('top', 2, 'length', 'CSS_TOP_SET', None, None, 'get'), ('right', 2, 'length', 'CSS_RIGHT_SET', None, None, 'get'), ('bottom', 2, 'length', 'CSS_BOTTOM_SET', None, None, 'get'), ('left', 2, 'length', 'CSS_LEFT_SET', None, None, 'get'), ('color', 1, 'color'), ('flex_basis', 2, 'length', 'CSS_FLEX_BASIS_SET'), ('flex_grow', 1, 'fixed', 'CSS_FLEX_GROW_SET'), ('flex_shrink', 1, 'fixed', 'CSS_FLEX_SHRINK_SET'), ('font_size', 4, 'length', 'CSS_FONT_SIZE_DIMENSION'), ('height', 2, 'length', 'CSS_HEIGHT_SET'), ('line_height', 2, 'length', None, None, None, 'get'), ('list_style_image', 1, 'string'), ('margin_top', 2, 'length', 'CSS_MARGIN_SET'), ('margin_right', 2, 'length', 'CSS_MARGIN_SET'), ('margin_bottom', 2, 'length', 'CSS_MARGIN_SET'), ('margin_left', 2, 'length', 'CSS_MARGIN_SET'), ('max_height', 2, 'length', 'CSS_MAX_HEIGHT_SET'), ('max_width', 2, 'length', 'CSS_MAX_WIDTH_SET'), ('min_height', 2, 'length', 'CSS_MIN_HEIGHT_SET'), ('min_width', 2, 'length', 'CSS_MIN_WIDTH_SET'), ('opacity', 1, 'fixed', 'CSS_OPACITY_SET'), ('order', 1, 'integer', 'CSS_ORDER_SET'), ('padding_top', 1, 'length', 'CSS_PADDING_SET'), ('padding_right', 1, 'length', 'CSS_PADDING_SET'), ('padding_left', 1, 'length', 'CSS_PADDING_SET'), ('padding_bottom', 1, 'length', 'CSS_PADDING_SET'), ('text_indent', 1, 'length', 'CSS_TEXT_INDENT_SET'), ('vertical_align', 4, 'length', 'CSS_VERTICAL_ALIGN_SET'), ('width', 2, 'length', 'CSS_WIDTH_SET'), ('z_index', 2, 'integer'), # Style group, arrays ('font_family', 3, 'string_arr', None, None, 'Encode font family as an array of string objects, terminated with a ' 'blank entry.'), ('quotes', 1, 'string_arr', None, None, 'Encode quotes as an array of string objects, terminated with a ' 'blank entry.'), # Style group, w3d properties ('depth', 2, 'length', 'CSS_DEPTH_SET'), ('max_depth', 2, 'length', 'CSS_MAX_DEPTH_SET'), ('min_depth', 2, 'length', 'CSS_MIN_DEPTH_SET'), ('far', 2, 'length', 'CSS_FAR_SET', None, None, 'get'), ('near', 2, 'length', 'CSS_NEAR_SET', None, None, 'get'), ('margin_far', 2, 'length', 'CSS_MARGIN_SET'), ('margin_near', 2, 'length', 'CSS_MARGIN_SET'), ('padding_far', 1, 'length', 'CSS_PADDING_SET'), ('padding_near', 1, 'length', 'CSS_PADDING_SET'), ('overflow_z', 3) } page = { # Page group ('page_break_after', 3, None, None, 'CSS_PAGE_BREAK_AFTER_AUTO'), ('page_break_before', 3, None, None, 'CSS_PAGE_BREAK_BEFORE_AUTO'), ('page_break_inside', 2, None, None, 'CSS_PAGE_BREAK_INSIDE_AUTO'), ('widows', 1, (('integer', '2'),), None, 'CSS_WIDOWS_SET'), ('orphans', 1, (('integer', '2'),), None, 'CSS_ORPHANS_SET') } uncommon = { # Uncommon group ('border_spacing', 1, (('length',), ('length',)), 'CSS_BORDER_SPACING_SET', 'CSS_BORDER_SPACING_SET'), ('break_after', 4, None, None, 'CSS_BREAK_AFTER_AUTO'), ('break_before', 4, None, None, 'CSS_BREAK_BEFORE_AUTO'), ('break_inside', 4, None, None, 'CSS_BREAK_INSIDE_AUTO'), ('clip', 6, (('length',), ('length',), ('length',), ('length',)), 'CSS_CLIP_RECT', 'CSS_CLIP_AUTO', None, ('get', 'set')), ('column_count', 2, 'integer', None, 'CSS_COLUMN_COUNT_AUTO'), ('column_fill', 2, None, None, 'CSS_COLUMN_FILL_BALANCE'), ('column_gap', 2, 'length', 'CSS_COLUMN_GAP_SET', 'CSS_COLUMN_GAP_NORMAL'), ('column_rule_color', 2, 'color', None, 'CSS_COLUMN_RULE_COLOR_CURRENT_COLOR'), ('column_rule_style', 4, None, None, 'CSS_COLUMN_RULE_STYLE_NONE'), ('column_rule_width', 3, 'length', 'CSS_COLUMN_RULE_WIDTH_WIDTH', 'CSS_COLUMN_RULE_WIDTH_MEDIUM'), ('column_span', 2, None, None, 'CSS_COLUMN_SPAN_NONE'), ('column_width', 2, 'length', 'CSS_COLUMN_WIDTH_SET', 'CSS_COLUMN_WIDTH_AUTO'), ('letter_spacing', 2, 'length', 'CSS_LETTER_SPACING_SET', 'CSS_LETTER_SPACING_NORMAL'), ('outline_color', 2, 'color', 'CSS_OUTLINE_COLOR_COLOR', 'CSS_OUTLINE_COLOR_INVERT'), ('outline_width', 3, 'length', 'CSS_OUTLINE_WIDTH_WIDTH', 'CSS_OUTLINE_WIDTH_MEDIUM'), ('word_spacing', 2, 'length', 'CSS_WORD_SPACING_SET', 'CSS_WORD_SPACING_NORMAL'), ('writing_mode', 2, None, None, 'CSS_WRITING_MODE_HORIZONTAL_TB'), # Uncommon group, arrays ('counter_increment', 1, 'counter_arr', None, 'CSS_COUNTER_INCREMENT_NONE', 'Encode counter_increment as an array of name, value pairs, ' 'terminated with a blank entry.'), ('counter_reset', 1, 'counter_arr', None, 'CSS_COUNTER_RESET_NONE', 'Encode counter_reset as an array of name, value pairs, ' 'terminated with a blank entry.'), ('cursor', 5, 'string_arr', None, 'CSS_CURSOR_AUTO', 'Encode cursor uri(s) as an array of string objects, terminated ' 'with a blank entry'), ('content', 2, 'content_item', 'CSS_CONTENT_NORMAL', 'CSS_CONTENT_NORMAL', 'Encode content as an array of content items, terminated with ' 'a blank entry.', 'set') } groups = [ { 'name': 'uncommon', 'props': uncommon }, { 'name': 'page', 'props': page }, { 'name': 'style', 'props': style } ]
values = {('length', 'css_fixed', 4, '0', 'unit', 'css_unit', 5, 'CSS_UNIT_PX'), ('integer', 'int32_t', 4, '0'), ('fixed', 'css_fixed', 4, '0'), ('color', 'css_color', 4, '0'), ('string', 'lwc_string*'), ('string_arr', 'lwc_string**'), ('counter_arr', 'css_computed_counter*'), ('content_item', 'css_computed_content_item*')} style = {('align_content', 3), ('align_items', 3), ('align_self', 3), ('background_attachment', 2), ('background_repeat', 3), ('border_collapse', 2), ('border_top_style', 4), ('border_right_style', 4), ('border_bottom_style', 4), ('border_left_style', 4), ('box_sizing', 2), ('caption_side', 2), ('clear', 3), ('direction', 2), ('display', 5), ('empty_cells', 2), ('flex_direction', 3), ('flex_wrap', 2), ('float', 2), ('font_style', 2), ('font_variant', 2), ('font_weight', 4), ('justify_content', 3), ('list_style_position', 2), ('list_style_type', 4), ('overflow_x', 3), ('overflow_y', 3), ('outline_style', 4), ('position', 3), ('table_layout', 2), ('text_align', 4), ('text_decoration', 5), ('text_transform', 3), ('unicode_bidi', 2), ('visibility', 2), ('white_space', 3), ('background_color', 2, 'color'), ('background_image', 1, 'string'), ('background_position', 1, (('length',), ('length',)), 'CSS_BACKGROUND_POSITION_SET'), ('border_top_color', 2, 'color'), ('border_right_color', 2, 'color'), ('border_bottom_color', 2, 'color'), ('border_left_color', 2, 'color'), ('border_top_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_right_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_bottom_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_left_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('top', 2, 'length', 'CSS_TOP_SET', None, None, 'get'), ('right', 2, 'length', 'CSS_RIGHT_SET', None, None, 'get'), ('bottom', 2, 'length', 'CSS_BOTTOM_SET', None, None, 'get'), ('left', 2, 'length', 'CSS_LEFT_SET', None, None, 'get'), ('color', 1, 'color'), ('flex_basis', 2, 'length', 'CSS_FLEX_BASIS_SET'), ('flex_grow', 1, 'fixed', 'CSS_FLEX_GROW_SET'), ('flex_shrink', 1, 'fixed', 'CSS_FLEX_SHRINK_SET'), ('font_size', 4, 'length', 'CSS_FONT_SIZE_DIMENSION'), ('height', 2, 'length', 'CSS_HEIGHT_SET'), ('line_height', 2, 'length', None, None, None, 'get'), ('list_style_image', 1, 'string'), ('margin_top', 2, 'length', 'CSS_MARGIN_SET'), ('margin_right', 2, 'length', 'CSS_MARGIN_SET'), ('margin_bottom', 2, 'length', 'CSS_MARGIN_SET'), ('margin_left', 2, 'length', 'CSS_MARGIN_SET'), ('max_height', 2, 'length', 'CSS_MAX_HEIGHT_SET'), ('max_width', 2, 'length', 'CSS_MAX_WIDTH_SET'), ('min_height', 2, 'length', 'CSS_MIN_HEIGHT_SET'), ('min_width', 2, 'length', 'CSS_MIN_WIDTH_SET'), ('opacity', 1, 'fixed', 'CSS_OPACITY_SET'), ('order', 1, 'integer', 'CSS_ORDER_SET'), ('padding_top', 1, 'length', 'CSS_PADDING_SET'), ('padding_right', 1, 'length', 'CSS_PADDING_SET'), ('padding_left', 1, 'length', 'CSS_PADDING_SET'), ('padding_bottom', 1, 'length', 'CSS_PADDING_SET'), ('text_indent', 1, 'length', 'CSS_TEXT_INDENT_SET'), ('vertical_align', 4, 'length', 'CSS_VERTICAL_ALIGN_SET'), ('width', 2, 'length', 'CSS_WIDTH_SET'), ('z_index', 2, 'integer'), ('font_family', 3, 'string_arr', None, None, 'Encode font family as an array of string objects, terminated with a blank entry.'), ('quotes', 1, 'string_arr', None, None, 'Encode quotes as an array of string objects, terminated with a blank entry.'), ('depth', 2, 'length', 'CSS_DEPTH_SET'), ('max_depth', 2, 'length', 'CSS_MAX_DEPTH_SET'), ('min_depth', 2, 'length', 'CSS_MIN_DEPTH_SET'), ('far', 2, 'length', 'CSS_FAR_SET', None, None, 'get'), ('near', 2, 'length', 'CSS_NEAR_SET', None, None, 'get'), ('margin_far', 2, 'length', 'CSS_MARGIN_SET'), ('margin_near', 2, 'length', 'CSS_MARGIN_SET'), ('padding_far', 1, 'length', 'CSS_PADDING_SET'), ('padding_near', 1, 'length', 'CSS_PADDING_SET'), ('overflow_z', 3)} page = {('page_break_after', 3, None, None, 'CSS_PAGE_BREAK_AFTER_AUTO'), ('page_break_before', 3, None, None, 'CSS_PAGE_BREAK_BEFORE_AUTO'), ('page_break_inside', 2, None, None, 'CSS_PAGE_BREAK_INSIDE_AUTO'), ('widows', 1, (('integer', '2'),), None, 'CSS_WIDOWS_SET'), ('orphans', 1, (('integer', '2'),), None, 'CSS_ORPHANS_SET')} uncommon = {('border_spacing', 1, (('length',), ('length',)), 'CSS_BORDER_SPACING_SET', 'CSS_BORDER_SPACING_SET'), ('break_after', 4, None, None, 'CSS_BREAK_AFTER_AUTO'), ('break_before', 4, None, None, 'CSS_BREAK_BEFORE_AUTO'), ('break_inside', 4, None, None, 'CSS_BREAK_INSIDE_AUTO'), ('clip', 6, (('length',), ('length',), ('length',), ('length',)), 'CSS_CLIP_RECT', 'CSS_CLIP_AUTO', None, ('get', 'set')), ('column_count', 2, 'integer', None, 'CSS_COLUMN_COUNT_AUTO'), ('column_fill', 2, None, None, 'CSS_COLUMN_FILL_BALANCE'), ('column_gap', 2, 'length', 'CSS_COLUMN_GAP_SET', 'CSS_COLUMN_GAP_NORMAL'), ('column_rule_color', 2, 'color', None, 'CSS_COLUMN_RULE_COLOR_CURRENT_COLOR'), ('column_rule_style', 4, None, None, 'CSS_COLUMN_RULE_STYLE_NONE'), ('column_rule_width', 3, 'length', 'CSS_COLUMN_RULE_WIDTH_WIDTH', 'CSS_COLUMN_RULE_WIDTH_MEDIUM'), ('column_span', 2, None, None, 'CSS_COLUMN_SPAN_NONE'), ('column_width', 2, 'length', 'CSS_COLUMN_WIDTH_SET', 'CSS_COLUMN_WIDTH_AUTO'), ('letter_spacing', 2, 'length', 'CSS_LETTER_SPACING_SET', 'CSS_LETTER_SPACING_NORMAL'), ('outline_color', 2, 'color', 'CSS_OUTLINE_COLOR_COLOR', 'CSS_OUTLINE_COLOR_INVERT'), ('outline_width', 3, 'length', 'CSS_OUTLINE_WIDTH_WIDTH', 'CSS_OUTLINE_WIDTH_MEDIUM'), ('word_spacing', 2, 'length', 'CSS_WORD_SPACING_SET', 'CSS_WORD_SPACING_NORMAL'), ('writing_mode', 2, None, None, 'CSS_WRITING_MODE_HORIZONTAL_TB'), ('counter_increment', 1, 'counter_arr', None, 'CSS_COUNTER_INCREMENT_NONE', 'Encode counter_increment as an array of name, value pairs, terminated with a blank entry.'), ('counter_reset', 1, 'counter_arr', None, 'CSS_COUNTER_RESET_NONE', 'Encode counter_reset as an array of name, value pairs, terminated with a blank entry.'), ('cursor', 5, 'string_arr', None, 'CSS_CURSOR_AUTO', 'Encode cursor uri(s) as an array of string objects, terminated with a blank entry'), ('content', 2, 'content_item', 'CSS_CONTENT_NORMAL', 'CSS_CONTENT_NORMAL', 'Encode content as an array of content items, terminated with a blank entry.', 'set')} groups = [{'name': 'uncommon', 'props': uncommon}, {'name': 'page', 'props': page}, {'name': 'style', 'props': style}]
class CSharpReference(): def __init__(self,): self.reference_object = None self.line_in_file = -1 self.file_name = ''
class Csharpreference: def __init__(self): self.reference_object = None self.line_in_file = -1 self.file_name = ''
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. version_info = (20, 0, 4, "custom") __version__ = ".".join([str(v) for v in version_info]) SERVER = "gunicorn" SERVER_SOFTWARE = "%s/%s" % (SERVER, __version__)
version_info = (20, 0, 4, 'custom') __version__ = '.'.join([str(v) for v in version_info]) server = 'gunicorn' server_software = '%s/%s' % (SERVER, __version__)
''' 03 - Creating histograms Histograms show the full distribution of a variable. In this exercise, we will display the distribution of weights of medalists in gymnastics and in rowing in the 2016 Olympic games for a comparison between them. You will have two DataFrames to use. The first is called mens_rowing and includes information about the medalists in the men's rowing events. The other is called mens_gymnastics and includes information about medalists in all of the Gymnastics events. Instructions: - Use the ax.hist method to add a histogram of the "Weight" column from the mens_rowing DataFrame. - Use ax.hist to add a histogram of "Weight" for the mens_gymnastics DataFrame. - Set the x-axis label to "Weight (kg)" and the y-axis label to "# of observations". ''' fig, ax = plt.subplots() # Plot a histogram of "Weight" for mens_rowing ax.hist(mens_rowing['Weight']) # Compare to histogram of "Weight" for mens_gymnastics ax.hist(mens_gymnastics['Weight']) # Set the x-axis label to "Weight (kg)" ax.set_xlabel('Weight (kg)') # Set the y-axis label to "# of observations" ax.set_ylabel('# of observations') plt.show()
""" 03 - Creating histograms Histograms show the full distribution of a variable. In this exercise, we will display the distribution of weights of medalists in gymnastics and in rowing in the 2016 Olympic games for a comparison between them. You will have two DataFrames to use. The first is called mens_rowing and includes information about the medalists in the men's rowing events. The other is called mens_gymnastics and includes information about medalists in all of the Gymnastics events. Instructions: - Use the ax.hist method to add a histogram of the "Weight" column from the mens_rowing DataFrame. - Use ax.hist to add a histogram of "Weight" for the mens_gymnastics DataFrame. - Set the x-axis label to "Weight (kg)" and the y-axis label to "# of observations". """ (fig, ax) = plt.subplots() ax.hist(mens_rowing['Weight']) ax.hist(mens_gymnastics['Weight']) ax.set_xlabel('Weight (kg)') ax.set_ylabel('# of observations') plt.show()
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained=None, backbone=dict( type='MixVisionTransformer', in_channels=3, embed_dims=32, num_stages=4, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], patch_sizes=[7, 3, 3, 3], sr_ratios=[8, 4, 2, 1], out_indices=(0, 1, 2, 3), mlp_ratio=4, qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1), decode_head=dict( type='SegformerHead', in_channels=[32, 64, 160, 256], in_index=[0, 1, 2, 3], channels=256, dropout_ratio=0.1, num_classes=3, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole'))
norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict(type='EncoderDecoder', pretrained=None, backbone=dict(type='MixVisionTransformer', in_channels=3, embed_dims=32, num_stages=4, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], patch_sizes=[7, 3, 3, 3], sr_ratios=[8, 4, 2, 1], out_indices=(0, 1, 2, 3), mlp_ratio=4, qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1), decode_head=dict(type='SegformerHead', in_channels=[32, 64, 160, 256], in_index=[0, 1, 2, 3], channels=256, dropout_ratio=0.1, num_classes=3, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), train_cfg=dict(), test_cfg=dict(mode='whole'))
# how to create a function def greet(): print("Hello") print("welcome, Edgar") greet() # prints greet() # prints(2) greet() # prints(3) # arguments and parameters def greet(name): # name is a parameter print('hello') print('welcome, ', name) greet('Edgar') # Edgar is the argument # return def greet(name): if name == 'Edgar': return else: print('hello') print('welcome, ', name) greet('Edgar') # return values def greet(name): if name == 'Jose': return 'Go away' return "hello ", name, "Welcome to my app" returned = greet('Edgar') print(returned)
def greet(): print('Hello') print('welcome, Edgar') greet() greet() greet() def greet(name): print('hello') print('welcome, ', name) greet('Edgar') def greet(name): if name == 'Edgar': return else: print('hello') print('welcome, ', name) greet('Edgar') def greet(name): if name == 'Jose': return 'Go away' return ('hello ', name, 'Welcome to my app') returned = greet('Edgar') print(returned)
def convert_date_string_to_period(timestamp) -> int: try: month = int(timestamp.month) except AttributeError: return -1 else: return month
def convert_date_string_to_period(timestamp) -> int: try: month = int(timestamp.month) except AttributeError: return -1 else: return month
exe = "tester.exe" toolchain = "msvc" # optional link_pool_depth = 1 # optional builddir = { "gnu" : "build" , "msvc" : "build" , "clang" : "build" } includes = { "gnu" : [ "-I." ] , "msvc" : [ "/I." ] , "clang" : [ "-I." ] } defines = { "gnu" : [ "-DEXAMPLE=1" ] , "msvc" : [ "/DEXAMPLE=1" ] , "clang" : [ "-DEXAMPLE=1" ] } cflags = { "gnu" : [ "-O2", "-g" ] , "msvc" : [ "/O2" ] , "clang" : [ "-O2", "-g" ] } cxxflags = { "gnu" : [ "-O2", "-g" ] , "msvc" : [ "/O2", "/W4", "/EHsc"] , "clang" : [ "-O2", "-g", "-fsanitize=address" ] } ldflags = { "gnu" : [ ] , "msvc" : [ ] , "clang" : [ "-fsanitize=address" ] } # optionsl cxx_files = [ "tester.cc" ] c_files = [ ] # You can register your own toolchain through register_toolchain function def register_toolchain(ninja): pass
exe = 'tester.exe' toolchain = 'msvc' link_pool_depth = 1 builddir = {'gnu': 'build', 'msvc': 'build', 'clang': 'build'} includes = {'gnu': ['-I.'], 'msvc': ['/I.'], 'clang': ['-I.']} defines = {'gnu': ['-DEXAMPLE=1'], 'msvc': ['/DEXAMPLE=1'], 'clang': ['-DEXAMPLE=1']} cflags = {'gnu': ['-O2', '-g'], 'msvc': ['/O2'], 'clang': ['-O2', '-g']} cxxflags = {'gnu': ['-O2', '-g'], 'msvc': ['/O2', '/W4', '/EHsc'], 'clang': ['-O2', '-g', '-fsanitize=address']} ldflags = {'gnu': [], 'msvc': [], 'clang': ['-fsanitize=address']} cxx_files = ['tester.cc'] c_files = [] def register_toolchain(ninja): pass
# Problem: https://www.hackerrank.com/challenges/alphabet-rangoli/problem def print_rangoli(size): alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alorder = ''.join([i.lower() for i in alorder]) string, width , side_l, side_str = alorder[:size], (size-1)*4+1, [], '' # top half for i in range(size-1): print((side_str + '-' + string[size-1-i] + '-' + side_str[::-1]).center(width,'-')) side_l.append(string[size-1-i]) side_str = '-'.join(side_l) # middle if size == 1: print(string[0]) else: print(side_str+'-'+string[0]+'-'+side_str[::-1]) # lower half for i in range(size-1): center_str = side_l.pop() side_str = '-'.join(side_l) print((side_str + '-' + center_str + '-' + side_str[::-1]).center(width,'-')) n = int(input("Enter alphabet rangoli's size: ")) print_rangoli(n)
def print_rangoli(size): alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alorder = ''.join([i.lower() for i in alorder]) (string, width, side_l, side_str) = (alorder[:size], (size - 1) * 4 + 1, [], '') for i in range(size - 1): print((side_str + '-' + string[size - 1 - i] + '-' + side_str[::-1]).center(width, '-')) side_l.append(string[size - 1 - i]) side_str = '-'.join(side_l) if size == 1: print(string[0]) else: print(side_str + '-' + string[0] + '-' + side_str[::-1]) for i in range(size - 1): center_str = side_l.pop() side_str = '-'.join(side_l) print((side_str + '-' + center_str + '-' + side_str[::-1]).center(width, '-')) n = int(input("Enter alphabet rangoli's size: ")) print_rangoli(n)
# Cooling Settings cool_circuit = \ {'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'], 'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet', 'specifier': 'checklist_activate_cooling', 'command': {'function': 'set_status', 'args': [[[1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2], [4, 0], [4, 1], [4, 2], [5, 0], [5, 1], [5, 2], [6, 0], [6, 1], [6, 2], [7, 0], [7, 1], [7, 2], [8, 0], [8, 1], [8, 2]]]}} # 'args2': [1, 2, 3, 4, 5, 6, 7]}} cool_channel_length = \ {'label': 'Coolant Channel Length:', 'value': 0.4, 'sim_name': ['coolant_channel', 'length'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_height = \ {'label': 'Coolant Channel Height:', 'value': 1e-3, 'sim_name': ['coolant_channel', 'height'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_width = \ {'label': 'Coolant Channel Width:', 'value': 1e-3, 'sim_name': ['coolant_channel', 'width'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_number = \ {'label': 'Coolant Channel Number:', 'value': 2, 'sim_name': ['temperature_system', 'cool_ch_numb'], 'specifier': 'disabled_cooling', 'type': 'EntrySet'} cool_channel_bends = \ {'label': 'Number of Coolant Channel Bends:', 'value': 0, 'sim_name': ['coolant_channel', 'bend_number'], 'specifier': 'disabled_cooling', 'type': 'EntrySet'} cool_bend_pressure_loss_coefficient = \ {'label': 'Pressure Loss Coefficient for Coolant Channel Bend:', 'sim_name': ['coolant_channel', 'bend_friction_factor'], 'specifier': 'disabled_cooling', 'value': 0.5, 'dimensions': '-', 'type': 'EntrySet'} cool_flow_end_cells = \ {'label': 'Activate Cooling Flow at End Plates:', 'value': False, 'sim_name': ['temperature_system', 'cool_ch_bc'], 'specifier': 'disabled_cooling', 'sticky': ['NW', 'NWE'], 'type': 'CheckButtonSet'} channel_flow_direction = \ {'label': 'Channel Flow Direction (1 or -1):', 'value': 1, 'sim_name': ['coolant_channel', 'flow_direction'], 'specifier': 'disabled_cooling', 'dtype': 'int', 'type': 'EntrySet', 'sticky': ['NW', 'NWE']} cool_frame_dict = \ {'title': 'Cooling Settings', 'show_title': False, 'font': 'Arial 10 bold', 'sticky': 'WEN', 'size_label': 'xl', 'size_unit': 's', 'widget_dicts': [cool_circuit, cool_channel_number, cool_channel_length, cool_channel_height, cool_channel_width, cool_channel_bends, cool_bend_pressure_loss_coefficient, channel_flow_direction, cool_flow_end_cells], # 'highlightbackground': 'grey', 'highlightthickness': 1 } tab_dict = {'title': 'Cooling', 'show_title': False, 'sub_frame_dicts': [cool_frame_dict]} # geometry_frame_dict = \ # {'title': 'Geometry', 'show_title': False, 'font': 'Arial 10 bold', # 'sub_frame_dicts': [cool_frame_dict, manifold_frame_dict, # cell_frame_dict], # 'highlightbackground': 'grey', 'highlightthickness': 1} # main_frame_dicts = [geometry_frame_dict, simulation_frame_dict]
cool_circuit = {'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'], 'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet', 'specifier': 'checklist_activate_cooling', 'command': {'function': 'set_status', 'args': [[[1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2], [4, 0], [4, 1], [4, 2], [5, 0], [5, 1], [5, 2], [6, 0], [6, 1], [6, 2], [7, 0], [7, 1], [7, 2], [8, 0], [8, 1], [8, 2]]]}} cool_channel_length = {'label': 'Coolant Channel Length:', 'value': 0.4, 'sim_name': ['coolant_channel', 'length'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_height = {'label': 'Coolant Channel Height:', 'value': 0.001, 'sim_name': ['coolant_channel', 'height'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_width = {'label': 'Coolant Channel Width:', 'value': 0.001, 'sim_name': ['coolant_channel', 'width'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_number = {'label': 'Coolant Channel Number:', 'value': 2, 'sim_name': ['temperature_system', 'cool_ch_numb'], 'specifier': 'disabled_cooling', 'type': 'EntrySet'} cool_channel_bends = {'label': 'Number of Coolant Channel Bends:', 'value': 0, 'sim_name': ['coolant_channel', 'bend_number'], 'specifier': 'disabled_cooling', 'type': 'EntrySet'} cool_bend_pressure_loss_coefficient = {'label': 'Pressure Loss Coefficient for Coolant Channel Bend:', 'sim_name': ['coolant_channel', 'bend_friction_factor'], 'specifier': 'disabled_cooling', 'value': 0.5, 'dimensions': '-', 'type': 'EntrySet'} cool_flow_end_cells = {'label': 'Activate Cooling Flow at End Plates:', 'value': False, 'sim_name': ['temperature_system', 'cool_ch_bc'], 'specifier': 'disabled_cooling', 'sticky': ['NW', 'NWE'], 'type': 'CheckButtonSet'} channel_flow_direction = {'label': 'Channel Flow Direction (1 or -1):', 'value': 1, 'sim_name': ['coolant_channel', 'flow_direction'], 'specifier': 'disabled_cooling', 'dtype': 'int', 'type': 'EntrySet', 'sticky': ['NW', 'NWE']} cool_frame_dict = {'title': 'Cooling Settings', 'show_title': False, 'font': 'Arial 10 bold', 'sticky': 'WEN', 'size_label': 'xl', 'size_unit': 's', 'widget_dicts': [cool_circuit, cool_channel_number, cool_channel_length, cool_channel_height, cool_channel_width, cool_channel_bends, cool_bend_pressure_loss_coefficient, channel_flow_direction, cool_flow_end_cells]} tab_dict = {'title': 'Cooling', 'show_title': False, 'sub_frame_dicts': [cool_frame_dict]}
class Solution: # @param {integer} n # @param {integer} k # @return {string} def getPermutation(self, n, k): nums = [i+1 for i in xrange(n)] facts = [0 for i in xrange(n)] facts[0] = 1 for i in range(1,n): facts[i] = i*facts[i-1] k = k-1 res = [] for i in range(n,0,-1): idx = k/facts[i-1] k = k%facts[i-1] res.append(nums[idx]) nums.pop(idx) return ''.join([str(i) for i in res])
class Solution: def get_permutation(self, n, k): nums = [i + 1 for i in xrange(n)] facts = [0 for i in xrange(n)] facts[0] = 1 for i in range(1, n): facts[i] = i * facts[i - 1] k = k - 1 res = [] for i in range(n, 0, -1): idx = k / facts[i - 1] k = k % facts[i - 1] res.append(nums[idx]) nums.pop(idx) return ''.join([str(i) for i in res])
# Python 3 compatibility (no longer includes `basestring`): try: basestring except NameError: basestring = str class Item(object): '''Common logic shared across all kinds of objects.''' class UnknownAttributeError(ValueError): def __init__(self, attributes): super(Item.UnknownAttributeError, self).__init__( "Unknown attributes: {0}".format(attributes)) COMMON_ATTRIBUTES = ('name', 'namespace', 'labels') def __init__(self, config, info): self._config = config for attr in self.COMMON_ATTRIBUTES: val = info.get(attr) if not val and 'metadata' in info: val = info['metadata'].get(attr) if val: setattr(self, attr, val) def __repr__(self): return '<{0}: {1}>'.format( self.__class__.__name__, ' '.join('{0}={1}'.format(a, v) for a, v in self._simple_attrvals) ) def attrvals(self, attributes): unknown = set(attributes) - set(self.ATTRIBUTES) if unknown: raise self.UnknownAttributeError(unknown) return ((a, getattr(self, a)) for a in attributes) @property def _simple_attrvals(self): for attr in self.COMMON_ATTRIBUTES: av = self._attrval_if_simple(attr) if av: yield av for attr in self.PRIMARY_ATTRIBUTES: if attr not in self.COMMON_ATTRIBUTES: av = self._attrval_if_simple(attr) if av: yield av def _attrval_if_simple(self, attr): if hasattr(self, attr): if not self._property(attr): val = getattr(self, attr) if self._simple(val): return (attr, val) @staticmethod def _simple(val): return isinstance(val, (basestring, int, float, None.__class__)) def _property(self, attr): return isinstance(getattr(type(self), attr, None), property)
try: basestring except NameError: basestring = str class Item(object): """Common logic shared across all kinds of objects.""" class Unknownattributeerror(ValueError): def __init__(self, attributes): super(Item.UnknownAttributeError, self).__init__('Unknown attributes: {0}'.format(attributes)) common_attributes = ('name', 'namespace', 'labels') def __init__(self, config, info): self._config = config for attr in self.COMMON_ATTRIBUTES: val = info.get(attr) if not val and 'metadata' in info: val = info['metadata'].get(attr) if val: setattr(self, attr, val) def __repr__(self): return '<{0}: {1}>'.format(self.__class__.__name__, ' '.join(('{0}={1}'.format(a, v) for (a, v) in self._simple_attrvals))) def attrvals(self, attributes): unknown = set(attributes) - set(self.ATTRIBUTES) if unknown: raise self.UnknownAttributeError(unknown) return ((a, getattr(self, a)) for a in attributes) @property def _simple_attrvals(self): for attr in self.COMMON_ATTRIBUTES: av = self._attrval_if_simple(attr) if av: yield av for attr in self.PRIMARY_ATTRIBUTES: if attr not in self.COMMON_ATTRIBUTES: av = self._attrval_if_simple(attr) if av: yield av def _attrval_if_simple(self, attr): if hasattr(self, attr): if not self._property(attr): val = getattr(self, attr) if self._simple(val): return (attr, val) @staticmethod def _simple(val): return isinstance(val, (basestring, int, float, None.__class__)) def _property(self, attr): return isinstance(getattr(type(self), attr, None), property)
word = input().lower() ans = [] vowels = ('a', 'i', 'u', 'e', 'o', 'y') filtered_word = word for i in word: if i in vowels: filtered_word = filtered_word.replace(i, "") for i in filtered_word: ans.append('.') ans.append(i) print(''.join(ans))
word = input().lower() ans = [] vowels = ('a', 'i', 'u', 'e', 'o', 'y') filtered_word = word for i in word: if i in vowels: filtered_word = filtered_word.replace(i, '') for i in filtered_word: ans.append('.') ans.append(i) print(''.join(ans))
def ft_map(function_to_apply, list_of_inputs): return [function_to_apply(x) for x in list_of_inputs] c = [0,1,2,3,4,5] def add1(t): return t+1 print(list(map(lambda x: x+1,c))) print(ft_map(lambda x: x+1,c))
def ft_map(function_to_apply, list_of_inputs): return [function_to_apply(x) for x in list_of_inputs] c = [0, 1, 2, 3, 4, 5] def add1(t): return t + 1 print(list(map(lambda x: x + 1, c))) print(ft_map(lambda x: x + 1, c))
#!/bin/python2.7 #CLASS PARA VERIFICAR OS GRUPOS DE CONFLITO class ScdGrupoConflito(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False self.dl_type = False self.solucao = str("") #CLASS PARA VERIFICAR SE OS CAMPOS SAO WILDCARDS class ScdWildcards(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False self.dl_type = False #CLASS PARA CONTAR O TOTAL DE WILDCARDS class ScdWildcardsTotal(object): def __init__(self): self.in_port = 0 self.ip = 0 self.dl = 0 self.tp = 0 class ScdRegraGenerica(object): def __init__(self): self.in_port = False self.ip = False self.dl = False self.tp = False class ScdSugestao(object): def __init__(self): self.sugestao_resolucao = None self.nivel_conflito = 0 #QUANTO AO NIVEL, DEFINIDO COMO # 0 - Nenhum # 1 - Medio # 2 - Alto def analise_Conflito(pscd_rule_1, pscd_rule_2): # Inicia a verificacao das rules ##DECLARACAO DAS VARIAVEIS UTILIZADAS NA FUNCTION grp_conflito = ScdGrupoConflito() wildcards_rule_1 = ScdWildcards() wildcards_rule_2 = ScdWildcards() wildcards_total_1 = ScdWildcardsTotal() wildcards_total_2 = ScdWildcardsTotal() regra_generica = ScdRegraGenerica() sugestao = ScdSugestao() #print "Iniciando verificacao de Conflitos" #print "################################################" #PRIMEIRO VERIFICA SE SAO DO MESMA SWITCH if pscd_rule_1.switch == pscd_rule_2.switch: #VERIFICA SE SAO DA MESMA PORTA DE ENTRADA E DO MESMO TIPO (DL_TYPE) if pscd_rule_1.dl_type != pscd_rule_2.dl_type: #print "REGRAS NAO SAO DO MESMO DL_TYPE" return sugestao else: #print "REGRAS SAO DO MESMO DL_TYPE" grp_conflito.dl_type = True #print "------------------------------------" #print "----> VERIFICA IN_PORT - GRUPO 1" #print "------------------------------------" #SE UMA DAS IN_PORT FOR WILDCARD OU AS DUAS FOREM IGUAIS, PROSSEGUE if (((pscd_rule_1.in_port == None) and (pscd_rule_2.in_port == None)) or (pscd_rule_1.in_port == pscd_rule_2.in_port)): if (pscd_rule_1.in_port == None): #print "IN_PORT 1 EH WILDCARD" grp_conflito.in_port = True if (pscd_rule_2.in_port == None): #print "IN_PORT 2 EH WILDCARD" grp_conflito.in_port = True if (pscd_rule_1.in_port == pscd_rule_2.in_port): #print "IN_PORT IGUAIS" grp_conflito.in_port = True #print ("Conflito Grupo 1: %s" %grp_conflito.in_port) ####FIM GRUPO 1 ## Verifica IP_SRC e IP_DST - GRUPO 2 ################################### #print "------------------------------------" #print "----> GRUPO 2 - VERIFICA IP SRC/DST" #print "------------------------------------" ##IP_SRC if pscd_rule_1.nw_src == pscd_rule_2.nw_src: #print "GRUPO 2 - IP_SRC iguais" grp_conflito.ip_src = True if pscd_rule_1.nw_src == None and pscd_rule_2.nw_src == None: #print "GRUPO 2 - IP_SRC 1 e 2 Wildcards" wildcards_rule_1.ip_src = True wildcards_rule_2.ip_src = True else: if pscd_rule_1.nw_src == None: #print "GRUPO 2 - IP_SRC 1 Wildcard" grp_conflito.ip_src = True wildcards_rule_1.ip_src = True if pscd_rule_2.nw_src == None: #print "GRUPO 2 - IP_SRC 2 Wildcard" grp_conflito.ip_src = True wildcards_rule_2.ip_src = True elif pscd_rule_1.nw_src is not None and pscd_rule_2.nw_src is not None: mask = 0 if pscd_rule_1.nw_src[0] == pscd_rule_2.nw_src[0]: if pscd_rule_1.nw_src[1] == pscd_rule_2.nw_src[1]: if pscd_rule_1.nw_src[2] == pscd_rule_2.nw_src[2]: if pscd_rule_1.nw_src[3] == pscd_rule_2.nw_src[3]: mask = 1 else: if pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[3] == 0: mask = 1 else: if pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1 else: if pscd_rule_1.nw_src[1] == 0 and pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[1] == 0 and pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1 else: if pscd_rule_1.nw_src[0] == 0 and pscd_rule_1.nw_src[1] == 0 and pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[0] == 0 and pscd_rule_2.nw_src[1] == 0 and pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1 if mask > 0: grp_conflito.ip_src = True #print ("Net_Mask SRC: %s" % mask) ##IP_DST if pscd_rule_1.nw_dst == pscd_rule_2.nw_dst: #print "GRUPO 2 - IP_DST iguais" grp_conflito.ip_dst = True if pscd_rule_1.nw_dst == None and pscd_rule_2.nw_dst == None: #print "GRUPO 2 - IP_DST 1 e 2 Wildcards" wildcards_rule_1.ip_dst = True wildcards_rule_2.ip_dst = True else: if pscd_rule_1.nw_dst == None: #print "GRUPO 2 - IP_DST 1 Wildcard" grp_conflito.ip_dst = True wildcards_rule_1.ip_dst = True if pscd_rule_2.nw_dst == None: #print "GRUPO 2 - IP_DST 2 Wildcard" grp_conflito.ip_dst = True wildcards_rule_2.ip_dst = True elif pscd_rule_1.nw_dst is not None and pscd_rule_2.nw_dst is not None: mask = 0 if pscd_rule_1.nw_dst[0] == pscd_rule_2.nw_dst[0]: if pscd_rule_1.nw_dst[1] == pscd_rule_2.nw_dst[1]: if pscd_rule_1.nw_dst[2] == pscd_rule_2.nw_dst[2]: if pscd_rule_1.nw_dst[3] == pscd_rule_2.nw_dst[3]: mask = 1 else: if pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[3] == 0: mask = 1 else: if pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1 else: if pscd_rule_1.nw_dst[1] == 0 and pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[1] == 0 and pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1 else: if pscd_rule_1.nw_dst[0] == 0 and pscd_rule_1.nw_dst[1] == 0 and pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[0] == 0 and pscd_rule_2.nw_dst[1] == 0 and pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1 if mask > 0: grp_conflito.ip_dst = True #print ("Net_Mask dst: %s" % mask) ######FIM GRUPO 2 #Verifica MAC_SRC e MAC_DST - GRUPO 3 ##################################### #print "------------------------------------" #print "----> GRUPO 3 - VERIFICA MAC SRC/DST" #print "------------------------------------" #ANALISA OS DOIS MAC if pscd_rule_1.dl_src != None and pscd_rule_2.dl_src != None and pscd_rule_1.dl_dst != None and pscd_rule_2.dl_dst != None: if pscd_rule_1.dl_src == pscd_rule_2.dl_src and pscd_rule_1.dl_dst != pscd_rule_2.dl_dst: grp_conflito.dl_dst = False grp_conflito.dl_src = False if pscd_rule_1.dl_src != pscd_rule_2.dl_src and pscd_rule_1.dl_dst == pscd_rule_2.dl_dst: grp_conflito.dl_dst = False grp_conflito.dl_src = False else: # MAC SRC if pscd_rule_1.dl_src == pscd_rule_2.dl_src: #print "GRUPO 3 - DL_SRC iguais" grp_conflito.dl_src = True if pscd_rule_1.dl_src == None: wildcards_rule_1.dl_src = True if pscd_rule_2.dl_src == None: wildcards_rule_2.dl_src = True else: if pscd_rule_1.dl_src == None: #print "GRUPO 3 - DL_SRC 1 Wildcard" grp_conflito.dl_src = True wildcards_rule_1.dl_src = True else: if pscd_rule_2.dl_src == None: #print "GRUPO 3 - DL_SRC 2 Wildcard" grp_conflito.dl_src = True wildcards_rule_2.dl_src = True # MAC DST if pscd_rule_1.dl_dst == pscd_rule_2.dl_dst: #print "GRUPO 3 - DL_DST iguais" grp_conflito.dl_dst = True if pscd_rule_1.dl_dst == None: wildcards_rule_1.dl_dst = True if pscd_rule_2.dl_dst == None: wildcards_rule_2.dl_dst = True else: if pscd_rule_1.dl_dst == None: #print "GRUPO 3 - DL_DST 1 Wildcard" grp_conflito.dl_dst = True wildcards_rule_1.dl_dst = True else: if pscd_rule_2.dl_dst == None: #print "GRUPO 3 - DL_DST 2 Wildcard" grp_conflito.dl_dst = True wildcards_rule_2.dl_dst = True #print ("Conflito Grupo 3: MAC_SRC: %s MAC_DST: %s" % (grp_conflito.dl_src, grp_conflito.dl_dst)) ####FIM GRUPO 3 # Verifica TP_SRC e TP_DST - GRUPO 4 #print "------------------------------------" #print "----> GRUPO 4 - VERIFICA PORTA TCP/UDP SRC/DST" #print "------------------------------------" #PRIMEIRO, VERIFICAMOS SE O PROTOCOLO EH IP/TCP/UDP/SCTP, VIDE COMENTARIO NO SCRIPT COLETOR #ANALISA SOMENTE UMA DAS REGRAS, POIS AS DUAS JA PASSARAM PELO TESTE DE IGUALDADE if (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp"): # PORTA TCP/UDP SRC if pscd_rule_1.tp_src == pscd_rule_2.tp_src: #print "GRUPO 4 - TP_SRC iguais" grp_conflito.tp_src = True else: if pscd_rule_1.tp_src == None: #print "GRUPO 4 - TP_SRC 1 Wildcard" grp_conflito.tp_src = True wildcards_rule_1.tp_src = True else: if pscd_rule_2.tp_src == None: #print "GRUPO 4 - TP_SRC 2 Wildcard" grp_conflito.tp_src = True wildcards_rule_2.tp_src = True # PORTA TCP/UDP DST if pscd_rule_1.tp_dst == pscd_rule_2.tp_dst: #print "GRUPO 4 - TP_DST iguais" grp_conflito.tp_dst = True else: if pscd_rule_1.tp_dst == None: #print "GRUPO 4 - TP_DST 1 Wildcard" grp_conflito.tp_dst = True wildcards_rule_2.tp_dst = True else: if pscd_rule_2.tp_dst == None: #print "GRUPO 4 - TP_DST 2 Wildcard" grp_conflito.tp_dst = True wildcards_rule_2.tp_dst = True #print ("Conflito Grupo 4: TP_SRC: %s TP_DST: %s" % (grp_conflito.tp_dst, grp_conflito.tp_dst)) #print ("----------------------------") #print ("RESULTADO DAS ANALISES:") #print ("----------------------------") #print ("Grupo Conflitos: %s" % grp_conflito.__dict__) #print ("Wildcards Regra 1: %s" % wildcards_rule_1.__dict__) #print ("Wildcards Regra 2: %s" % wildcards_rule_2.__dict__) #print ("----------------------------") #print ("----------------------------") ##Conta os WildCards #REGRA 1 if wildcards_rule_1.in_port == True: wildcards_total_1.in_port += 1 if wildcards_rule_1.dl_src == True: wildcards_total_1.dl += 1 if wildcards_rule_1.dl_dst == True: wildcards_total_1.dl += 1 if wildcards_rule_1.ip_dst == True: wildcards_total_1.ip += 1 if wildcards_rule_1.ip_src == True: wildcards_total_1.ip += 1 if wildcards_rule_1.tp_dst == True: wildcards_total_1.tp += 1 if wildcards_rule_1.tp_src == True: wildcards_total_1.tp += 1 #REGRA 2 if wildcards_rule_2.in_port == True: wildcards_total_2.in_port += 1 if wildcards_rule_2.dl_src == True: wildcards_total_2.dl += 1 if wildcards_rule_2.dl_dst == True: wildcards_total_2.dl += 1 if wildcards_rule_2.ip_dst == True: wildcards_total_2.ip += 1 if wildcards_rule_2.ip_src == True: wildcards_total_2.ip += 1 if wildcards_rule_2.tp_dst == True: wildcards_total_2.tp += 1 if wildcards_rule_2.tp_src == True: wildcards_total_2.tp += 1 #Compara as regras para ver se a regra 1 eh a mais generica if wildcards_total_1.in_port > wildcards_total_2.in_port: regra_generica.in_port = True if wildcards_total_1.ip > wildcards_total_2.ip: regra_generica.ip = True if wildcards_total_1.dl > wildcards_total_2.dl: regra_generica.dl = True if wildcards_total_1.tp > wildcards_total_2.tp: regra_generica.tp = True generica_count = 0 if regra_generica.in_port==True: generica_count += 1 if regra_generica.ip==True: generica_count += 1 if regra_generica.tp==True: generica_count += 1 if regra_generica.dl==True: generica_count += 1 #if generica_count >= 3: print ("Regra 1 eh a mais Generica: %s" %generica_count) #elif generica_count == 2: print ("Regras Genericas: %s" %generica_count) #else: print ("Regra 2 eh a mais Generica: %s" %generica_count) ####### FAZ A DECISAO FINAL PARA VER SE AS REGRAS CONFLITAM grupo_2 = 0 grupo_3 = 0 grupo_4 = 0 if grp_conflito.ip_src == True: grupo_2 += 1 if grp_conflito.ip_dst == True: grupo_2 += 1 if grp_conflito.dl_src == True: grupo_3 += 1 if grp_conflito.dl_dst == True: grupo_3 += 1 if grp_conflito.tp_src == True: grupo_4 += 1 if grp_conflito.tp_dst == True: grupo_4 += 1 #Conflita Totalmente if (grupo_2 == 2) and (grupo_3 == 2) and (grupo_4 == 2): #print "Conflitam em IP, MAC e TCP" #COMO CONFLITA COM TUDO, VERIFICAR A PRIORIDADE E A QUANTIDADE DE WILDCARDS if (pscd_rule_1.priority > pscd_rule_2.priority) and (generica_count >= 3): sugestao.sugestao_resolucao = ("Voce pode alterar a prioridade da Regra. Ela eh a mais generica e sobreescreve a Regra %s!"%pscd_rule_2.flow_id) elif (pscd_rule_1.priority > pscd_rule_2.priority) and (generica_count == 2): sugestao.sugestao_resolucao = "Voce pode alterar a prioridade da Regra. As duas regras sao genericas!" elif generica_count < 2: sugestao.sugestao_resolucao = "Possuem caracteristicas de IP, MAC E TCP muito semelhantes. Confira estes campos!" sugestao.nivel_conflito = 2 #Conflitos Parciais elif (grupo_2 == 1) and (grupo_3 == 2) and (grupo_4 == 2): #print "Conflitam em IP/Parcialmente, MAC e TCP" #Analisa IP para ver qual eh wildcard if wildcards_rule_1.ip_src == True and (pscd_rule_1.priority > pscd_rule_2.priority): sugestao.sugestao_resolucao = "Verifique o IP de Origem da Regra. Estah bem generico" sugestao.nivel_conflito = 2 elif wildcards_rule_2.ip_src == True and (pscd_rule_1.priority > pscd_rule_2.priority): sugestao.sugestao_resolucao = ("Verifique o IP de Origem da Regra %s. Estah bem generico"%pscd_rule_2.flow_id) sugestao.nivel_conflito = 2 elif wildcards_rule_1.ip_dst == True and (pscd_rule_1.priority > pscd_rule_2.priority): sugestao.sugestao_resolucao = "Verifique o IP de Destino da Regra. Estah bem generico" sugestao.nivel_conflito = 2 elif wildcards_rule_2.ip_dst == True and (pscd_rule_1.priority > pscd_rule_2.priority): sugestao.sugestao_resolucao = ("Verifique o IP de Destino da Regra %s. Estah bem generico"%pscd_rule_2.flow_id) sugestao.nivel_conflito = 2 else: sugestao.sugestao_resolucao = "Verifique o IP das Regras. Grande probabilidade de conflito em MAC e Portas TCP" sugestao.nivel_conflito = 2 ##COMPARA QUANDO FOR UMA REGRA TCP elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==2) and (grupo_4==2): sugestao.sugestao_resolucao = "Regra TCP. Os Campos IP e Portas TCP/UDP estao bem genericos." sugestao.nivel_conflito = 2 elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==1) and (grupo_4==2): sugestao.sugestao_resolucao = "Regra TCP. As Portas TCP/UDP estao bem genericos. Confira tambem os Campos IP, podem vir a conflitar." sugestao.nivel_conflito = 2 elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==2) and (grupo_4==1): sugestao.sugestao_resolucao = "Regra TCP. Os Campos IP estao bem generico. Confira tambem as Portas TCP/UDP, podem vir a conflitar." sugestao.nivel_conflito = 2 elif (grupo_2 == 1) and (grupo_3 == 1) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"): sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP e MAC. Algum deles estah bem generico."%pscd_rule_1.dl_type) sugestao.nivel_conflito = 1 elif (grupo_2 == 2) and (grupo_3 == 2) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"): sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP e MAC que estao bem genericos."%pscd_rule_1.dl_type) sugestao.nivel_conflito = 2 elif (grupo_2 == 1) and (grupo_3 == 2) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"): sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos MAC que estao bem genericos."%pscd_rule_1.dl_type) sugestao.nivel_conflito = 2 #elif (grupo_2 == 2) and (grupo_3 == 0) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"): # sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP que estao bem genericos."%pscd_rule_1.dl_type) # sugestao.nivel_conflito = 2 elif (grupo_2 == 2) and (grupo_3 == 1) and (grupo_4 == 2): #print "Conflitam em IP, MAC/Parcialmente e TCP" sugestao.sugestao_resolucao = "Verifique os campos de IP e Portas TCP/UDP das Regras. Estao bem Genericos" sugestao.nivel_conflito = 2 elif (grupo_2 == 2) and (grupo_3 == 2) and (grupo_4 == 1): #print "Conflitam em IP, MAC e TCP/Parcialmente" sugestao.sugestao_resolucao = "Verifique os campos de IP e MAC das Regras. Estao bem Genericos" sugestao.nivel_conflito = 2 elif (grupo_2 == 2) and (grupo_3 == 1) and (grupo_4 == 1): #print "Conflitam em IP, MAC/Parcialmente e TCP/Parcialmente" sugestao.sugestao_resolucao = "Verifique os campos de IP das Regras. Estao bem Genericos. Os campos de Porta TCP/UDP e MAC tambem podem vir a conflitar!" sugestao.nivel_conflito = 1 elif (grupo_2 == 1) and (grupo_3 == 2) and (grupo_4 == 1): #print "Conflitam em IP/Parcialmente, MAC e TCP/Parcialmente" sugestao.sugestao_resolucao = "Verifique os campos de MAC das Regras. Estao bem Genericos. Os campos de IP e Porta TCP/UDP tambem podem vir a conflitar!" sugestao.nivel_conflito = 1 elif (grupo_2 == 1) and (grupo_3 == 1) and (grupo_4 == 2): #print "Conflitam em IP/Parcialmente, MAC/Parcialmente e TCP" sugestao.sugestao_resolucao = "Verifique os campos de Portas TCP/UDP das Regras. Estao bem Genericos. Os campos de IP e MAC tambem podem vir a conflitar!" sugestao.nivel_conflito = 1 return sugestao #SE NAO, ASSUME QUE NAO EH CONFLITO else: #print "IN_PORT DIFERENTES, NAO EH CONLITO" return sugestao else: return sugestao
class Scdgrupoconflito(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False self.dl_type = False self.solucao = str('') class Scdwildcards(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False self.dl_type = False class Scdwildcardstotal(object): def __init__(self): self.in_port = 0 self.ip = 0 self.dl = 0 self.tp = 0 class Scdregragenerica(object): def __init__(self): self.in_port = False self.ip = False self.dl = False self.tp = False class Scdsugestao(object): def __init__(self): self.sugestao_resolucao = None self.nivel_conflito = 0 def analise__conflito(pscd_rule_1, pscd_rule_2): grp_conflito = scd_grupo_conflito() wildcards_rule_1 = scd_wildcards() wildcards_rule_2 = scd_wildcards() wildcards_total_1 = scd_wildcards_total() wildcards_total_2 = scd_wildcards_total() regra_generica = scd_regra_generica() sugestao = scd_sugestao() if pscd_rule_1.switch == pscd_rule_2.switch: if pscd_rule_1.dl_type != pscd_rule_2.dl_type: return sugestao else: grp_conflito.dl_type = True if pscd_rule_1.in_port == None and pscd_rule_2.in_port == None or pscd_rule_1.in_port == pscd_rule_2.in_port: if pscd_rule_1.in_port == None: grp_conflito.in_port = True if pscd_rule_2.in_port == None: grp_conflito.in_port = True if pscd_rule_1.in_port == pscd_rule_2.in_port: grp_conflito.in_port = True if pscd_rule_1.nw_src == pscd_rule_2.nw_src: grp_conflito.ip_src = True if pscd_rule_1.nw_src == None and pscd_rule_2.nw_src == None: wildcards_rule_1.ip_src = True wildcards_rule_2.ip_src = True else: if pscd_rule_1.nw_src == None: grp_conflito.ip_src = True wildcards_rule_1.ip_src = True if pscd_rule_2.nw_src == None: grp_conflito.ip_src = True wildcards_rule_2.ip_src = True elif pscd_rule_1.nw_src is not None and pscd_rule_2.nw_src is not None: mask = 0 if pscd_rule_1.nw_src[0] == pscd_rule_2.nw_src[0]: if pscd_rule_1.nw_src[1] == pscd_rule_2.nw_src[1]: if pscd_rule_1.nw_src[2] == pscd_rule_2.nw_src[2]: if pscd_rule_1.nw_src[3] == pscd_rule_2.nw_src[3]: mask = 1 elif pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[3] == 0: mask = 1 elif pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1 elif pscd_rule_1.nw_src[1] == 0 and pscd_rule_1.nw_src[2] == 0 and (pscd_rule_1.nw_src[3] == 0): mask = 1 elif pscd_rule_2.nw_src[1] == 0 and pscd_rule_2.nw_src[2] == 0 and (pscd_rule_2.nw_src[3] == 0): mask = 1 elif pscd_rule_1.nw_src[0] == 0 and pscd_rule_1.nw_src[1] == 0 and (pscd_rule_1.nw_src[2] == 0) and (pscd_rule_1.nw_src[3] == 0): mask = 1 elif pscd_rule_2.nw_src[0] == 0 and pscd_rule_2.nw_src[1] == 0 and (pscd_rule_2.nw_src[2] == 0) and (pscd_rule_2.nw_src[3] == 0): mask = 1 if mask > 0: grp_conflito.ip_src = True if pscd_rule_1.nw_dst == pscd_rule_2.nw_dst: grp_conflito.ip_dst = True if pscd_rule_1.nw_dst == None and pscd_rule_2.nw_dst == None: wildcards_rule_1.ip_dst = True wildcards_rule_2.ip_dst = True else: if pscd_rule_1.nw_dst == None: grp_conflito.ip_dst = True wildcards_rule_1.ip_dst = True if pscd_rule_2.nw_dst == None: grp_conflito.ip_dst = True wildcards_rule_2.ip_dst = True elif pscd_rule_1.nw_dst is not None and pscd_rule_2.nw_dst is not None: mask = 0 if pscd_rule_1.nw_dst[0] == pscd_rule_2.nw_dst[0]: if pscd_rule_1.nw_dst[1] == pscd_rule_2.nw_dst[1]: if pscd_rule_1.nw_dst[2] == pscd_rule_2.nw_dst[2]: if pscd_rule_1.nw_dst[3] == pscd_rule_2.nw_dst[3]: mask = 1 elif pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[3] == 0: mask = 1 elif pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1 elif pscd_rule_1.nw_dst[1] == 0 and pscd_rule_1.nw_dst[2] == 0 and (pscd_rule_1.nw_dst[3] == 0): mask = 1 elif pscd_rule_2.nw_dst[1] == 0 and pscd_rule_2.nw_dst[2] == 0 and (pscd_rule_2.nw_dst[3] == 0): mask = 1 elif pscd_rule_1.nw_dst[0] == 0 and pscd_rule_1.nw_dst[1] == 0 and (pscd_rule_1.nw_dst[2] == 0) and (pscd_rule_1.nw_dst[3] == 0): mask = 1 elif pscd_rule_2.nw_dst[0] == 0 and pscd_rule_2.nw_dst[1] == 0 and (pscd_rule_2.nw_dst[2] == 0) and (pscd_rule_2.nw_dst[3] == 0): mask = 1 if mask > 0: grp_conflito.ip_dst = True if pscd_rule_1.dl_src != None and pscd_rule_2.dl_src != None and (pscd_rule_1.dl_dst != None) and (pscd_rule_2.dl_dst != None): if pscd_rule_1.dl_src == pscd_rule_2.dl_src and pscd_rule_1.dl_dst != pscd_rule_2.dl_dst: grp_conflito.dl_dst = False grp_conflito.dl_src = False if pscd_rule_1.dl_src != pscd_rule_2.dl_src and pscd_rule_1.dl_dst == pscd_rule_2.dl_dst: grp_conflito.dl_dst = False grp_conflito.dl_src = False else: if pscd_rule_1.dl_src == pscd_rule_2.dl_src: grp_conflito.dl_src = True if pscd_rule_1.dl_src == None: wildcards_rule_1.dl_src = True if pscd_rule_2.dl_src == None: wildcards_rule_2.dl_src = True elif pscd_rule_1.dl_src == None: grp_conflito.dl_src = True wildcards_rule_1.dl_src = True elif pscd_rule_2.dl_src == None: grp_conflito.dl_src = True wildcards_rule_2.dl_src = True if pscd_rule_1.dl_dst == pscd_rule_2.dl_dst: grp_conflito.dl_dst = True if pscd_rule_1.dl_dst == None: wildcards_rule_1.dl_dst = True if pscd_rule_2.dl_dst == None: wildcards_rule_2.dl_dst = True elif pscd_rule_1.dl_dst == None: grp_conflito.dl_dst = True wildcards_rule_1.dl_dst = True elif pscd_rule_2.dl_dst == None: grp_conflito.dl_dst = True wildcards_rule_2.dl_dst = True if pscd_rule_1.dl_type == 'ip' or pscd_rule_1.dl_type == 'tcp' or pscd_rule_1.dl_type == 'udp' or (pscd_rule_1.dl_type == 'sctp'): if pscd_rule_1.tp_src == pscd_rule_2.tp_src: grp_conflito.tp_src = True elif pscd_rule_1.tp_src == None: grp_conflito.tp_src = True wildcards_rule_1.tp_src = True elif pscd_rule_2.tp_src == None: grp_conflito.tp_src = True wildcards_rule_2.tp_src = True if pscd_rule_1.tp_dst == pscd_rule_2.tp_dst: grp_conflito.tp_dst = True elif pscd_rule_1.tp_dst == None: grp_conflito.tp_dst = True wildcards_rule_2.tp_dst = True elif pscd_rule_2.tp_dst == None: grp_conflito.tp_dst = True wildcards_rule_2.tp_dst = True if wildcards_rule_1.in_port == True: wildcards_total_1.in_port += 1 if wildcards_rule_1.dl_src == True: wildcards_total_1.dl += 1 if wildcards_rule_1.dl_dst == True: wildcards_total_1.dl += 1 if wildcards_rule_1.ip_dst == True: wildcards_total_1.ip += 1 if wildcards_rule_1.ip_src == True: wildcards_total_1.ip += 1 if wildcards_rule_1.tp_dst == True: wildcards_total_1.tp += 1 if wildcards_rule_1.tp_src == True: wildcards_total_1.tp += 1 if wildcards_rule_2.in_port == True: wildcards_total_2.in_port += 1 if wildcards_rule_2.dl_src == True: wildcards_total_2.dl += 1 if wildcards_rule_2.dl_dst == True: wildcards_total_2.dl += 1 if wildcards_rule_2.ip_dst == True: wildcards_total_2.ip += 1 if wildcards_rule_2.ip_src == True: wildcards_total_2.ip += 1 if wildcards_rule_2.tp_dst == True: wildcards_total_2.tp += 1 if wildcards_rule_2.tp_src == True: wildcards_total_2.tp += 1 if wildcards_total_1.in_port > wildcards_total_2.in_port: regra_generica.in_port = True if wildcards_total_1.ip > wildcards_total_2.ip: regra_generica.ip = True if wildcards_total_1.dl > wildcards_total_2.dl: regra_generica.dl = True if wildcards_total_1.tp > wildcards_total_2.tp: regra_generica.tp = True generica_count = 0 if regra_generica.in_port == True: generica_count += 1 if regra_generica.ip == True: generica_count += 1 if regra_generica.tp == True: generica_count += 1 if regra_generica.dl == True: generica_count += 1 grupo_2 = 0 grupo_3 = 0 grupo_4 = 0 if grp_conflito.ip_src == True: grupo_2 += 1 if grp_conflito.ip_dst == True: grupo_2 += 1 if grp_conflito.dl_src == True: grupo_3 += 1 if grp_conflito.dl_dst == True: grupo_3 += 1 if grp_conflito.tp_src == True: grupo_4 += 1 if grp_conflito.tp_dst == True: grupo_4 += 1 if grupo_2 == 2 and grupo_3 == 2 and (grupo_4 == 2): if pscd_rule_1.priority > pscd_rule_2.priority and generica_count >= 3: sugestao.sugestao_resolucao = 'Voce pode alterar a prioridade da Regra. Ela eh a mais generica e sobreescreve a Regra %s!' % pscd_rule_2.flow_id elif pscd_rule_1.priority > pscd_rule_2.priority and generica_count == 2: sugestao.sugestao_resolucao = 'Voce pode alterar a prioridade da Regra. As duas regras sao genericas!' elif generica_count < 2: sugestao.sugestao_resolucao = 'Possuem caracteristicas de IP, MAC E TCP muito semelhantes. Confira estes campos!' sugestao.nivel_conflito = 2 elif grupo_2 == 1 and grupo_3 == 2 and (grupo_4 == 2): if wildcards_rule_1.ip_src == True and pscd_rule_1.priority > pscd_rule_2.priority: sugestao.sugestao_resolucao = 'Verifique o IP de Origem da Regra. Estah bem generico' sugestao.nivel_conflito = 2 elif wildcards_rule_2.ip_src == True and pscd_rule_1.priority > pscd_rule_2.priority: sugestao.sugestao_resolucao = 'Verifique o IP de Origem da Regra %s. Estah bem generico' % pscd_rule_2.flow_id sugestao.nivel_conflito = 2 elif wildcards_rule_1.ip_dst == True and pscd_rule_1.priority > pscd_rule_2.priority: sugestao.sugestao_resolucao = 'Verifique o IP de Destino da Regra. Estah bem generico' sugestao.nivel_conflito = 2 elif wildcards_rule_2.ip_dst == True and pscd_rule_1.priority > pscd_rule_2.priority: sugestao.sugestao_resolucao = 'Verifique o IP de Destino da Regra %s. Estah bem generico' % pscd_rule_2.flow_id sugestao.nivel_conflito = 2 else: sugestao.sugestao_resolucao = 'Verifique o IP das Regras. Grande probabilidade de conflito em MAC e Portas TCP' sugestao.nivel_conflito = 2 elif (pscd_rule_1.dl_type == 'ip' or pscd_rule_1.dl_type == 'tcp' or pscd_rule_1.dl_type == 'udp' or (pscd_rule_1.dl_type == 'sctp')) and grupo_2 == 2 and (grupo_4 == 2): sugestao.sugestao_resolucao = 'Regra TCP. Os Campos IP e Portas TCP/UDP estao bem genericos.' sugestao.nivel_conflito = 2 elif (pscd_rule_1.dl_type == 'ip' or pscd_rule_1.dl_type == 'tcp' or pscd_rule_1.dl_type == 'udp' or (pscd_rule_1.dl_type == 'sctp')) and grupo_2 == 1 and (grupo_4 == 2): sugestao.sugestao_resolucao = 'Regra TCP. As Portas TCP/UDP estao bem genericos. Confira tambem os Campos IP, podem vir a conflitar.' sugestao.nivel_conflito = 2 elif (pscd_rule_1.dl_type == 'ip' or pscd_rule_1.dl_type == 'tcp' or pscd_rule_1.dl_type == 'udp' or (pscd_rule_1.dl_type == 'sctp')) and grupo_2 == 2 and (grupo_4 == 1): sugestao.sugestao_resolucao = 'Regra TCP. Os Campos IP estao bem generico. Confira tambem as Portas TCP/UDP, podem vir a conflitar.' sugestao.nivel_conflito = 2 elif grupo_2 == 1 and grupo_3 == 1 and (pscd_rule_1.dl_type == 'arp' or pscd_rule_1.dl_type == 'rarp' or pscd_rule_1.dl_type == 'icmp'): sugestao.sugestao_resolucao = 'Em regras %s, voce pode verificar os campos IP e MAC. Algum deles estah bem generico.' % pscd_rule_1.dl_type sugestao.nivel_conflito = 1 elif grupo_2 == 2 and grupo_3 == 2 and (pscd_rule_1.dl_type == 'arp' or pscd_rule_1.dl_type == 'rarp' or pscd_rule_1.dl_type == 'icmp'): sugestao.sugestao_resolucao = 'Em regras %s, voce pode verificar os campos IP e MAC que estao bem genericos.' % pscd_rule_1.dl_type sugestao.nivel_conflito = 2 elif grupo_2 == 1 and grupo_3 == 2 and (pscd_rule_1.dl_type == 'arp' or pscd_rule_1.dl_type == 'rarp' or pscd_rule_1.dl_type == 'icmp'): sugestao.sugestao_resolucao = 'Em regras %s, voce pode verificar os campos MAC que estao bem genericos.' % pscd_rule_1.dl_type sugestao.nivel_conflito = 2 elif grupo_2 == 2 and grupo_3 == 1 and (grupo_4 == 2): sugestao.sugestao_resolucao = 'Verifique os campos de IP e Portas TCP/UDP das Regras. Estao bem Genericos' sugestao.nivel_conflito = 2 elif grupo_2 == 2 and grupo_3 == 2 and (grupo_4 == 1): sugestao.sugestao_resolucao = 'Verifique os campos de IP e MAC das Regras. Estao bem Genericos' sugestao.nivel_conflito = 2 elif grupo_2 == 2 and grupo_3 == 1 and (grupo_4 == 1): sugestao.sugestao_resolucao = 'Verifique os campos de IP das Regras. Estao bem Genericos. Os campos de Porta TCP/UDP e MAC tambem podem vir a conflitar!' sugestao.nivel_conflito = 1 elif grupo_2 == 1 and grupo_3 == 2 and (grupo_4 == 1): sugestao.sugestao_resolucao = 'Verifique os campos de MAC das Regras. Estao bem Genericos. Os campos de IP e Porta TCP/UDP tambem podem vir a conflitar!' sugestao.nivel_conflito = 1 elif grupo_2 == 1 and grupo_3 == 1 and (grupo_4 == 2): sugestao.sugestao_resolucao = 'Verifique os campos de Portas TCP/UDP das Regras. Estao bem Genericos. Os campos de IP e MAC tambem podem vir a conflitar!' sugestao.nivel_conflito = 1 return sugestao else: return sugestao else: return sugestao
def get_slice_length(path): for i in range(len(path)): if path[i].isalpha(): return i return -1
def get_slice_length(path): for i in range(len(path)): if path[i].isalpha(): return i return -1
entrada = int(input()) #resultado = entrada % 2 #comp = 10 % 2 i = 1 while i <= entrada: if i % 2 != 0: print(i) i+= 1
entrada = int(input()) i = 1 while i <= entrada: if i % 2 != 0: print(i) i += 1
class ModaError(Exception): pass class ModaTimeoutError(ModaError): pass class ModaCannotInteractError(ModaError): pass
class Modaerror(Exception): pass class Modatimeouterror(ModaError): pass class Modacannotinteracterror(ModaError): pass
def recurse(a,i): if i == len(a)-1: print(a[i]) return else: recurse(a,i+1) print(a[i]) recurse([1,2,3,4,5],0)
def recurse(a, i): if i == len(a) - 1: print(a[i]) return else: recurse(a, i + 1) print(a[i]) recurse([1, 2, 3, 4, 5], 0)
# https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem # Trial division def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True if __name__ == '__main__': n, nums = int(input()), [] for i in range(n): nums.append(int(input())) # nums = [5, 97, 98, 3] # nums = [1000000000, 1000000001, 1000000002, 1000000003, 1000000004, 1000000005, 1000000006, 1000000007, 1000000008, # 1000000009] # nums = [1000000006] for num in nums: print('Prime' if is_prime(num) else 'Not prime')
def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True if __name__ == '__main__': (n, nums) = (int(input()), []) for i in range(n): nums.append(int(input())) for num in nums: print('Prime' if is_prime(num) else 'Not prime')
bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember') pertengahan_tahun = bulan_pembelian[4:8] print(pertengahan_tahun) awal_tahun = bulan_pembelian[:5] print(awal_tahun) akhir_tahun = bulan_pembelian[8:] print(akhir_tahun) print(bulan_pembelian[-4:-1])
bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember') pertengahan_tahun = bulan_pembelian[4:8] print(pertengahan_tahun) awal_tahun = bulan_pembelian[:5] print(awal_tahun) akhir_tahun = bulan_pembelian[8:] print(akhir_tahun) print(bulan_pembelian[-4:-1])
def test_one(app): response = app.get('/api/services', status=200) response.json.should.be.is_instance(list) def test_two(app): response = app.get('/api/services/1', status=200) response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'})
def test_one(app): response = app.get('/api/services', status=200) response.json.should.be.is_instance(list) def test_two(app): response = app.get('/api/services/1', status=200) response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'})
def str_to_int(value, default=int(0)): stripped_value = value.strip() try: return int(stripped_value) except ValueError: return default def str_to_float(value, default=float(0)): stripped_value = value.strip() try: return float(stripped_value) except ValueError: return default
def str_to_int(value, default=int(0)): stripped_value = value.strip() try: return int(stripped_value) except ValueError: return default def str_to_float(value, default=float(0)): stripped_value = value.strip() try: return float(stripped_value) except ValueError: return default
k=1 suma=(k**2+1)/k cont=0 while cont<1000: cont+=suma print(k) k+=1 suma=(k**2+1)/k
k = 1 suma = (k ** 2 + 1) / k cont = 0 while cont < 1000: cont += suma print(k) k += 1 suma = (k ** 2 + 1) / k
# Copyright 2017-2021 object_database Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class SortWrapper: def __init__(self, x): self.x = x def __lt__(self, other): try: if type(self.x) in (int, float) and type(other.x) in (int, float): return self.x < other.x if type(self.x) is type(other.x): # noqa: E721 return self.x < other.x else: return str(type(self.x)) < str(type(other.x)) except Exception: try: return str(self.x) < str(self.other) except Exception: return False def __eq__(self, other): try: if type(self.x) is type(other.x): # noqa: E721 return self.x == other.x else: return str(type(self.x)) == str(type(other.x)) except Exception: try: return str(self.x) == str(self.other) except Exception: return True
class Sortwrapper: def __init__(self, x): self.x = x def __lt__(self, other): try: if type(self.x) in (int, float) and type(other.x) in (int, float): return self.x < other.x if type(self.x) is type(other.x): return self.x < other.x else: return str(type(self.x)) < str(type(other.x)) except Exception: try: return str(self.x) < str(self.other) except Exception: return False def __eq__(self, other): try: if type(self.x) is type(other.x): return self.x == other.x else: return str(type(self.x)) == str(type(other.x)) except Exception: try: return str(self.x) == str(self.other) except Exception: return True
# encoding=utf8 # coding=UTF-8 #pastaArquivoCsv = "/home/00937325465/familiai/acompanhaig/arquivos/csv/" #pastaArquivoCsvProc = "/home/00937325465/familiai/acompanhaig/arquivos/csv/processados/" #pastaArquivoZip = "/home/00937325465/familiai/acompanhaig/arquivos/zip/" #pastaArquivoZipProc = "/home/00937325465/familiai/acompanhaig/arquivos/zip/processados/" #pastaArquivosHTML = "/home/00937325465/familiai/acompanhaig/html/" #templateBasico = "/home/00937325465/familiai/acompanhaig/templates/template_basico.html" pastaArquivoCsv = "/home/ubuntu/workspace/public/python/input/csv/" pastaArquivoCsvProc = "/home/ubuntu/workspace/public/python/input/csv/processados/" pastaArquivoZip = "/home/ubuntu/workspace/public/python/input/zip/" pastaArquivoZipProc = "/home/ubuntu/workspace/public/python/input/zip/processados/" pastaArquivosHTML = "/home/ubuntu/workspace/public/python/output/html/" templateBasico = "/home/ubuntu/workspace/public/python/input/templates/template_basico.html" sep = "|" sepNmArq = "_" txDepto = "DERCE" txLotacao = "LOTACAO" tagLotacao = "<<lotacao>>"
pasta_arquivo_csv = '/home/ubuntu/workspace/public/python/input/csv/' pasta_arquivo_csv_proc = '/home/ubuntu/workspace/public/python/input/csv/processados/' pasta_arquivo_zip = '/home/ubuntu/workspace/public/python/input/zip/' pasta_arquivo_zip_proc = '/home/ubuntu/workspace/public/python/input/zip/processados/' pasta_arquivos_html = '/home/ubuntu/workspace/public/python/output/html/' template_basico = '/home/ubuntu/workspace/public/python/input/templates/template_basico.html' sep = '|' sep_nm_arq = '_' tx_depto = 'DERCE' tx_lotacao = 'LOTACAO' tag_lotacao = '<<lotacao>>'
def slices(number, n): initial, res = 0, [] if n > len(number) or n == 0: raise ValueError("Desired slices greater than number length") elif n == len(number): return [[int(x) for x in number]] elif n == 1: return [[int(x)] for x in number] else: while n <= len(number): res.append([int(x) for x in number[initial:n]]) initial += 1 n += 1 return res
def slices(number, n): (initial, res) = (0, []) if n > len(number) or n == 0: raise value_error('Desired slices greater than number length') elif n == len(number): return [[int(x) for x in number]] elif n == 1: return [[int(x)] for x in number] else: while n <= len(number): res.append([int(x) for x in number[initial:n]]) initial += 1 n += 1 return res
# # PySNMP MIB module HUAWEI-LswSMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-LswSMON-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:34:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") huaweiDatacomm, huaweiMgmt = mibBuilder.importSymbols("HUAWEI-3COM-OID-MIB", "huaweiDatacomm", "huaweiMgmt") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Unsigned32, Counter64, Counter32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ObjectIdentity, iso, Gauge32, MibIdentifier, Bits, IpAddress, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Counter64", "Counter32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ObjectIdentity", "iso", "Gauge32", "MibIdentifier", "Bits", "IpAddress", "TimeTicks", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") hwSmonExtend = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26)) smonExtendObject = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1)) hwdot1qVlanStatNumber = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwdot1qVlanStatNumber.setStatus('mandatory') hwdot1qVlanStatStatusTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2), ) if mibBuilder.loadTexts: hwdot1qVlanStatStatusTable.setStatus('mandatory') hwdot1qVlanStatStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1), ).setIndexNames((0, "HUAWEI-LswSMON-MIB", "hwdot1qVlanStatEnableIndex")) if mibBuilder.loadTexts: hwdot1qVlanStatStatusEntry.setStatus('mandatory') hwdot1qVlanStatEnableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwdot1qVlanStatEnableIndex.setStatus('mandatory') hwdot1qVlanStatEnableStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwdot1qVlanStatEnableStatus.setStatus('mandatory') mibBuilder.exportSymbols("HUAWEI-LswSMON-MIB", hwdot1qVlanStatEnableIndex=hwdot1qVlanStatEnableIndex, smonExtendObject=smonExtendObject, hwdot1qVlanStatNumber=hwdot1qVlanStatNumber, hwdot1qVlanStatStatusTable=hwdot1qVlanStatStatusTable, hwSmonExtend=hwSmonExtend, hwdot1qVlanStatEnableStatus=hwdot1qVlanStatEnableStatus, hwdot1qVlanStatStatusEntry=hwdot1qVlanStatStatusEntry)
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint') (huawei_datacomm, huawei_mgmt) = mibBuilder.importSymbols('HUAWEI-3COM-OID-MIB', 'huaweiDatacomm', 'huaweiMgmt') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (unsigned32, counter64, counter32, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, object_identity, iso, gauge32, mib_identifier, bits, ip_address, time_ticks, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'Counter64', 'Counter32', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ObjectIdentity', 'iso', 'Gauge32', 'MibIdentifier', 'Bits', 'IpAddress', 'TimeTicks', 'Integer32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') hw_smon_extend = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26)) smon_extend_object = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1)) hwdot1q_vlan_stat_number = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwdot1qVlanStatNumber.setStatus('mandatory') hwdot1q_vlan_stat_status_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2)) if mibBuilder.loadTexts: hwdot1qVlanStatStatusTable.setStatus('mandatory') hwdot1q_vlan_stat_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1)).setIndexNames((0, 'HUAWEI-LswSMON-MIB', 'hwdot1qVlanStatEnableIndex')) if mibBuilder.loadTexts: hwdot1qVlanStatStatusEntry.setStatus('mandatory') hwdot1q_vlan_stat_enable_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hwdot1qVlanStatEnableIndex.setStatus('mandatory') hwdot1q_vlan_stat_enable_status = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hwdot1qVlanStatEnableStatus.setStatus('mandatory') mibBuilder.exportSymbols('HUAWEI-LswSMON-MIB', hwdot1qVlanStatEnableIndex=hwdot1qVlanStatEnableIndex, smonExtendObject=smonExtendObject, hwdot1qVlanStatNumber=hwdot1qVlanStatNumber, hwdot1qVlanStatStatusTable=hwdot1qVlanStatStatusTable, hwSmonExtend=hwSmonExtend, hwdot1qVlanStatEnableStatus=hwdot1qVlanStatEnableStatus, hwdot1qVlanStatStatusEntry=hwdot1qVlanStatStatusEntry)
INPUTS = [ ['Select', False], ['Signal Only', ''], ['Probe', 'motion.probe-input'], ['Digital In 0', 'motion.digital-in-00'], ['Digital In 1', 'motion.digital-in-01'], ['Digital In 2', 'motion.digital-in-02'], ['Digital In 3', 'motion.digital-in-03'], ] OUTPUTS = [ ['Select', False], ['Signal Only', ''], ['Coolant Flood', 'iocontrol.0.coolant-flood'], ['Coolant Mist', 'iocontrol.0.coolant-mist'], ['Spindle On', 'spindle.0.on'], ['Spindle CW', 'spindle.0.forward'], ['Spindle CCW', 'spindle.0.reverse'], ['Spindle Brake', 'spindle.0.brake'], ['E-Stop Out', 'iocontrol.0.user-enable-out'], ['Digital Out 0', 'motion.digital-out-00'], ['Digital Out 1', 'motion.digital-out-01'], ['Digital Out 2', 'motion.digital-out-02'], ['Digital Out 3', 'motion.digital-out-03'], ] AIN = [ ['Select', False], ['Analog In 0', 'motion.analog-in-00'], ['Analog In 1', 'motion.analog-in-01'], ['Analog In 2', 'motion.analog-in-02'], ['Analog In 3', 'motion.analog-in-03'], ] def build(parent): sscards = { 'Select':'No Card Selected', '7i64':'24 Outputs, 24 Inputs', '7i69':'48 Digital I/O Bits', '7i70':'48 Inputs', '7i71':'48 Sourcing Outputs', '7i72':'48 Sinking Outputs', '7i73':'Pendant Card', '7i84':'32 Inputs 16 Outputs', '7i87':'8 Analog Inputs' } sspage = { 'Select':0, '7i64':1, '7i69':2, '7i70':3, '7i71':4, '7i72':5, '7i73':6, '7i84':7, '7i87':8 } parent.smartSerialInfoLbl.setText(sscards[parent.ssCardCB.currentText()]) parent.smartSerialSW.setCurrentIndex(sspage[parent.ssCardCB.currentText()]) pins7i64 = {} pins7i69 = {} pins7i70 = {} pins7i71 = {} pins7i72 = {} pins7i73 = {} pins7i84 = {} pins7i87 = {} def buildCB(parent): for i in range(16): for item in INPUTS: getattr(parent, 'ss7i73in_' + str(i)).addItem(item[0], item[1]) for i in range(2): for item in OUTPUTS: getattr(parent, 'ss7i73out_' + str(i)).addItem(item[0], item[1]) # 7i87 Combo Boxes for i in range(8): for item in AIN: getattr(parent, 'ss7i87in_' + str(i)).addItem(item[0], item[1]) def ss7i73setup(parent): if parent.ss7i97lcdCB.currentData() == 'w7d': # no LCD parent.ss7i97w7Lbl.setText('W7 Down') lcd = False elif parent.ss7i97lcdCB.currentData() == 'w7u': # LCD parent.ss7i97w7Lbl.setText('W7 Up') lcd = True if parent.ss7i73_keypadCB.currentData()[0] == 'w5d': if parent.ss7i73_keypadCB.currentData()[1] == 'w6d': # no keypad parent.ss7i73w5Lbl.setText('W5 Down') parent.ss7i73w6Lbl.setText('W6 Down') keypad = False elif parent.ss7i73_keypadCB.currentData()[1] == 'w6u': # 4x8 keypad parent.ss7i73w5Lbl.setText('W5 Down') parent.ss7i73w6Lbl.setText('W6 Up') keypad = True keys = '4x8' elif parent.ss7i73_keypadCB.currentData()[0] == 'w5u': # 8x8 keypad parent.ss7i73w5Lbl.setText('W5 Up') parent.ss7i73w6Lbl.setText('W6 Down') keypad = True keys = '8x8' # No LCD No Keypad if not lcd and not keypad: for i in range(8): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+10}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8,16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i+8}') for item in INPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(8,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+10}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) # LCD No Keypad if lcd and not keypad: for i in range(8): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+6}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8,16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i+8}') for item in INPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() # LCD 4x8 Keypad if lcd and keypad and keys == '4x8': for i in range(4): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+6}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(4,16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() # LCD 8x8 Keypad if lcd and keypad and keys == '8x8': for i in range(16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() # No LCD 4x8 Keypad if not lcd and keypad and keys == '4x8': for i in range(4): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+10}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(4,16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(8): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(8,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+6}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) # No LCD 8x8 Keypad if not lcd and keypad and keys == '8x8': for i in range(16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
inputs = [['Select', False], ['Signal Only', ''], ['Probe', 'motion.probe-input'], ['Digital In 0', 'motion.digital-in-00'], ['Digital In 1', 'motion.digital-in-01'], ['Digital In 2', 'motion.digital-in-02'], ['Digital In 3', 'motion.digital-in-03']] outputs = [['Select', False], ['Signal Only', ''], ['Coolant Flood', 'iocontrol.0.coolant-flood'], ['Coolant Mist', 'iocontrol.0.coolant-mist'], ['Spindle On', 'spindle.0.on'], ['Spindle CW', 'spindle.0.forward'], ['Spindle CCW', 'spindle.0.reverse'], ['Spindle Brake', 'spindle.0.brake'], ['E-Stop Out', 'iocontrol.0.user-enable-out'], ['Digital Out 0', 'motion.digital-out-00'], ['Digital Out 1', 'motion.digital-out-01'], ['Digital Out 2', 'motion.digital-out-02'], ['Digital Out 3', 'motion.digital-out-03']] ain = [['Select', False], ['Analog In 0', 'motion.analog-in-00'], ['Analog In 1', 'motion.analog-in-01'], ['Analog In 2', 'motion.analog-in-02'], ['Analog In 3', 'motion.analog-in-03']] def build(parent): sscards = {'Select': 'No Card Selected', '7i64': '24 Outputs, 24 Inputs', '7i69': '48 Digital I/O Bits', '7i70': '48 Inputs', '7i71': '48 Sourcing Outputs', '7i72': '48 Sinking Outputs', '7i73': 'Pendant Card', '7i84': '32 Inputs 16 Outputs', '7i87': '8 Analog Inputs'} sspage = {'Select': 0, '7i64': 1, '7i69': 2, '7i70': 3, '7i71': 4, '7i72': 5, '7i73': 6, '7i84': 7, '7i87': 8} parent.smartSerialInfoLbl.setText(sscards[parent.ssCardCB.currentText()]) parent.smartSerialSW.setCurrentIndex(sspage[parent.ssCardCB.currentText()]) pins7i64 = {} pins7i69 = {} pins7i70 = {} pins7i71 = {} pins7i72 = {} pins7i73 = {} pins7i84 = {} pins7i87 = {} def build_cb(parent): for i in range(16): for item in INPUTS: getattr(parent, 'ss7i73in_' + str(i)).addItem(item[0], item[1]) for i in range(2): for item in OUTPUTS: getattr(parent, 'ss7i73out_' + str(i)).addItem(item[0], item[1]) for i in range(8): for item in AIN: getattr(parent, 'ss7i87in_' + str(i)).addItem(item[0], item[1]) def ss7i73setup(parent): if parent.ss7i97lcdCB.currentData() == 'w7d': parent.ss7i97w7Lbl.setText('W7 Down') lcd = False elif parent.ss7i97lcdCB.currentData() == 'w7u': parent.ss7i97w7Lbl.setText('W7 Up') lcd = True if parent.ss7i73_keypadCB.currentData()[0] == 'w5d': if parent.ss7i73_keypadCB.currentData()[1] == 'w6d': parent.ss7i73w5Lbl.setText('W5 Down') parent.ss7i73w6Lbl.setText('W6 Down') keypad = False elif parent.ss7i73_keypadCB.currentData()[1] == 'w6u': parent.ss7i73w5Lbl.setText('W5 Down') parent.ss7i73w6Lbl.setText('W6 Up') keypad = True keys = '4x8' elif parent.ss7i73_keypadCB.currentData()[0] == 'w5u': parent.ss7i73w5Lbl.setText('W5 Up') parent.ss7i73w6Lbl.setText('W6 Down') keypad = True keys = '8x8' if not lcd and (not keypad): for i in range(8): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i + 10}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8, 16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i + 8}') for item in INPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(8, 12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 10}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) if lcd and (not keypad): for i in range(8): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i + 6}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8, 16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i + 8}') for item in INPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4, 12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() if lcd and keypad and (keys == '4x8'): for i in range(4): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i + 6}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(4, 16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4, 12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() if lcd and keypad and (keys == '8x8'): for i in range(16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4, 12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() if not lcd and keypad and (keys == '4x8'): for i in range(4): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i + 10}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(4, 16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(8): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(8, 12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 6}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) if not lcd and keypad and (keys == '8x8'): for i in range(16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i + 2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
n=int(input()) d=2 i = 0 while n>d : if n%d==0 : i+=1 print ("divisible by",d, "and count",i) else: print ("not divisible by this number",d) d+=1
n = int(input()) d = 2 i = 0 while n > d: if n % d == 0: i += 1 print('divisible by', d, 'and count', i) else: print('not divisible by this number', d) d += 1
# -*- encoding: utf-8 -*- EPILOG = 'Docker Hub in your terminal' DESCRIPTION = 'Access docker hub from your terminal' HELPMSGS = { 'method': 'The api method to query {%(choices)s}', 'orgname': 'Your orgname', 'reponame': 'The name of repository', 'username': 'The Docker Hub username', 'format': 'You can dispaly results in %(choices)s formats', 'page': 'The page of result to fetch', 'all_pages': 'Fetch all pages', 'status': 'To query for only builds with specified status', 'login': 'Authenticate with Docker Hub', 'config': 'Manage configuration values', 'action': 'Action to perform on an api method', } VALID_METHODS = ['repos', 'tags', 'builds', 'users', 'queue', 'version', 'login', 'config'] VALID_ACTIONS = ['set', 'get'] VALID_CONFIG_NAMES = ['orgname'] NO_TIP_METHODS = ['login', 'version', 'config'] NO_TIP_FORMATS = ['json'] VALID_DISPLAY_FORMATS = ['table', 'json'] DOCKER_AUTH_FILE = '~/.docker/config.json' CONFIG_FILE = '~/.docker-hub/config.json' DOCKER_HUB_API_ENDPOINT = 'https://hub.docker.com/v2/' PER_PAGE = 15 SECURE_CONFIG_KEYS = ['auth_token'] BUILD_STATUS = { -4: 'canceled', -2: 'exception', -1: 'error', 0: 'pending', 1: 'claimed', 2: 'started', 3: 'cloned', 4: 'readme', 5: 'dockerfile', 6: 'built', 7: 'bundled', 8: 'uploaded', 9: 'pushed', 10: 'done' } TIPS = [ 'You are not authenticated with Docker Hub. Hence only public \ resources will be fetched. Try authenticating using `docker login` or \ `docker-hub login` command to see more.' ]
epilog = 'Docker Hub in your terminal' description = 'Access docker hub from your terminal' helpmsgs = {'method': 'The api method to query {%(choices)s}', 'orgname': 'Your orgname', 'reponame': 'The name of repository', 'username': 'The Docker Hub username', 'format': 'You can dispaly results in %(choices)s formats', 'page': 'The page of result to fetch', 'all_pages': 'Fetch all pages', 'status': 'To query for only builds with specified status', 'login': 'Authenticate with Docker Hub', 'config': 'Manage configuration values', 'action': 'Action to perform on an api method'} valid_methods = ['repos', 'tags', 'builds', 'users', 'queue', 'version', 'login', 'config'] valid_actions = ['set', 'get'] valid_config_names = ['orgname'] no_tip_methods = ['login', 'version', 'config'] no_tip_formats = ['json'] valid_display_formats = ['table', 'json'] docker_auth_file = '~/.docker/config.json' config_file = '~/.docker-hub/config.json' docker_hub_api_endpoint = 'https://hub.docker.com/v2/' per_page = 15 secure_config_keys = ['auth_token'] build_status = {-4: 'canceled', -2: 'exception', -1: 'error', 0: 'pending', 1: 'claimed', 2: 'started', 3: 'cloned', 4: 'readme', 5: 'dockerfile', 6: 'built', 7: 'bundled', 8: 'uploaded', 9: 'pushed', 10: 'done'} tips = ['You are not authenticated with Docker Hub. Hence only public resources will be fetched. Try authenticating using `docker login` or `docker-hub login` command to see more.']
adj = [[False for i in range(10)] for j in range(10)] result = [0] def findthepath(S, v): result[0] = v for i in range(1, len(S)): if (adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]): v = ord(S[i]) - ord('A') elif (adj[v][ord(S[i]) - ord('A') + 5] or adj[ord(S[i]) - ord('A') + 5][v]): v = ord(S[i]) - ord('A') + 5 else: return False result.append(v) return True adj[0][1] = adj[1][2] = adj[2][3] = \ adj[3][4] = adj[4][0] = adj[0][5] = \ adj[1][6] = adj[2][7] = adj[3][8] = \ adj[4][9] = adj[5][7] = adj[7][9] = \ adj[9][6] = adj[6][8] = adj[8][5] = True S = "ABB" S = list(S) if (findthepath(S, ord(S[0]) - ord('A')) or findthepath(S, ord(S[0]) - ord('A') + 5)): print(*result, sep="") else: print("-1")
adj = [[False for i in range(10)] for j in range(10)] result = [0] def findthepath(S, v): result[0] = v for i in range(1, len(S)): if adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]: v = ord(S[i]) - ord('A') elif adj[v][ord(S[i]) - ord('A') + 5] or adj[ord(S[i]) - ord('A') + 5][v]: v = ord(S[i]) - ord('A') + 5 else: return False result.append(v) return True adj[0][1] = adj[1][2] = adj[2][3] = adj[3][4] = adj[4][0] = adj[0][5] = adj[1][6] = adj[2][7] = adj[3][8] = adj[4][9] = adj[5][7] = adj[7][9] = adj[9][6] = adj[6][8] = adj[8][5] = True s = 'ABB' s = list(S) if findthepath(S, ord(S[0]) - ord('A')) or findthepath(S, ord(S[0]) - ord('A') + 5): print(*result, sep='') else: print('-1')
# Create a program that reads a positive integer N as input and prints on the console a rhombus with size n: def generate_pyramid(size: int, inverted: bool = False) -> list: steps = [i for i in range(1, size + 1)] if inverted: steps.reverse() return [' ' * (size - i) + '* ' * i for i in steps] def generate_rhombus(size: int) -> list: retval = generate_pyramid(size) retval.extend(generate_pyramid(size, True)[1:]) return retval n = int(input()) output = generate_rhombus(n) print(*output, sep='\n')
def generate_pyramid(size: int, inverted: bool=False) -> list: steps = [i for i in range(1, size + 1)] if inverted: steps.reverse() return [' ' * (size - i) + '* ' * i for i in steps] def generate_rhombus(size: int) -> list: retval = generate_pyramid(size) retval.extend(generate_pyramid(size, True)[1:]) return retval n = int(input()) output = generate_rhombus(n) print(*output, sep='\n')
#!/usr/bin/env python3 # ~*~ coding: utf-8 ~*~ # Write a program that has a user guess your name, but they only get 3 # chances to do so until the program quits. print("Try to guess my name!") count = 1 name = "guileherme" guess = input("What is my name? ") while count < 3 and guess.lower() != name: # . lower allows things like Guileherme to still match. print("You are wrong!") guess = input("What is my name? ") count = count + 1 if guess.lower() != name: print("You are wrong!") # this message isn't printed in the third chance, so we print it now print("You ran out of chances.") else: print("Yes! My name is", name + "!")
print('Try to guess my name!') count = 1 name = 'guileherme' guess = input('What is my name? ') while count < 3 and guess.lower() != name: print('You are wrong!') guess = input('What is my name? ') count = count + 1 if guess.lower() != name: print('You are wrong!') print('You ran out of chances.') else: print('Yes! My name is', name + '!')
def minimumDistances(a): min_distance = -1 length = len(a) for number in range(0, length-1): for another_number in range(number+1, length): if a[number] == a[another_number]: distance = another_number - number if min_distance == -1: min_distance = distance elif min_distance > distance: min_distance = distance return min_distance
def minimum_distances(a): min_distance = -1 length = len(a) for number in range(0, length - 1): for another_number in range(number + 1, length): if a[number] == a[another_number]: distance = another_number - number if min_distance == -1: min_distance = distance elif min_distance > distance: min_distance = distance return min_distance
# -*- coding: utf-8 -*- # # ax_spines.py # # Copyright 2017 Sebastian Spreizer # The MIT License def set_default(ax): set_visible(ax, ['bottom', 'left']) def set_visible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side in sides) def set_invisible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side not in sides)
def set_default(ax): set_visible(ax, ['bottom', 'left']) def set_visible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side in sides) def set_invisible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side not in sides)
''' https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s ''' b = input() count = 0 buf = "0" zeros = [] ones = [] for i in range(len(b)): if b[i] == buf: count += 1 else: if buf == "0": zeros.append(count) else: ones.append(count) count = 1 buf = b[i] if buf == "0": zeros.append(count) else: ones.append(count) max_ones = 1 for i in range(len(ones)): left = 1 this_zero = zeros[i] # Left dead-end (no flip) if this_zero == 0: left = ones[i] # Left bridge (good flip) elif this_zero == 1: left = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i-1] # Left addition (poor flip) elif this_zero > 1: left = ones[i] + 1 if left > max_ones: max_ones = left right = 1 if i < len(zeros) - 1: next_zero = zeros[i+1] # Right dead-end (no flip) if zeros[i] == 0: right = ones[i] # Right bridge (good flip) elif zeros[i] == 1: right = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i-1] # Right addition (poor flip) elif zeros[i] > 1: right = ones[i] + 1 if right > max_ones: max_ones = right print(max_ones)
""" https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s """ b = input() count = 0 buf = '0' zeros = [] ones = [] for i in range(len(b)): if b[i] == buf: count += 1 else: if buf == '0': zeros.append(count) else: ones.append(count) count = 1 buf = b[i] if buf == '0': zeros.append(count) else: ones.append(count) max_ones = 1 for i in range(len(ones)): left = 1 this_zero = zeros[i] if this_zero == 0: left = ones[i] elif this_zero == 1: left = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i - 1] elif this_zero > 1: left = ones[i] + 1 if left > max_ones: max_ones = left right = 1 if i < len(zeros) - 1: next_zero = zeros[i + 1] if zeros[i] == 0: right = ones[i] elif zeros[i] == 1: right = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i - 1] elif zeros[i] > 1: right = ones[i] + 1 if right > max_ones: max_ones = right print(max_ones)
#This program calculates how many tiles you #need when tiling a floor (in m2) length = float(input("Enter room length:")) width = float(input("Enter room width:")) area = length * width needed = area * 1.05 print("You need", needed, "tiles in squared metres")
length = float(input('Enter room length:')) width = float(input('Enter room width:')) area = length * width needed = area * 1.05 print('You need', needed, 'tiles in squared metres')
# # PySNMP MIB module ZYXEL-CLUSTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-CLUSTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:49:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") iso, Counter32, Unsigned32, Counter64, Gauge32, Integer32, Bits, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, TimeTicks, NotificationType, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Counter32", "Unsigned32", "Counter64", "Gauge32", "Integer32", "Bits", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "TimeTicks", "NotificationType", "ModuleIdentity") MacAddress, DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "MacAddress", "DisplayString", "TextualConvention", "RowStatus") esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt") zyxelCluster = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14)) if mibBuilder.loadTexts: zyxelCluster.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelCluster.setOrganization('Enterprise Solution ZyXEL') if mibBuilder.loadTexts: zyxelCluster.setContactInfo('') if mibBuilder.loadTexts: zyxelCluster.setDescription('The subtree for cluster') zyxelClusterSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1)) zyxelClusterStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2)) zyxelClusterManager = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1)) zyClusterManagerMaxNumberOfManagers = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterManagerMaxNumberOfManagers.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerMaxNumberOfManagers.setDescription('The maximum number of cluster managers that can be created.') zyxelClusterManagerTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2), ) if mibBuilder.loadTexts: zyxelClusterManagerTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterManagerTable.setDescription('The table contains cluster manager configuration.') zyxelClusterManagerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterManagerVid")) if mibBuilder.loadTexts: zyxelClusterManagerEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterManagerEntry.setDescription('An entry contains cluster manager configuration. ') zyClusterManagerVid = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: zyClusterManagerVid.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerVid.setDescription('This is the VLAN ID and is only applicable if the switch is set to 802.1Q VLAN. All switches must be directly connected and in the same VLAN group to belong to the same cluster.') zyClusterManagerName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyClusterManagerName.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerName.setDescription('Type a name to identify the cluster manager.') zyClusterManagerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zyClusterManagerRowStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerRowStatus.setDescription('This object allows cluster manager entries to be created and deleted from cluster manager table.') zyxelClusterMembers = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2)) zyClusterMemberMaxNumberOfMembers = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterMemberMaxNumberOfMembers.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberMaxNumberOfMembers.setDescription('The maximum number of cluster members that can be created.') zyxelClusterMemberTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2), ) if mibBuilder.loadTexts: zyxelClusterMemberTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterMemberTable.setDescription('The table contains cluster member configuration.') zyxelClusterMemberEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterMemberMacAddress")) if mibBuilder.loadTexts: zyxelClusterMemberEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterMemberEntry.setDescription('An entry contains cluster member configuration.') zyClusterMemberMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 1), MacAddress()) if mibBuilder.loadTexts: zyClusterMemberMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.") zyClusterMemberName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterMemberName.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberName.setDescription("This is the cluster member switch's system name.") zyClusterMemberModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterMemberModel.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberModel.setDescription("This is the cluster member switch's model name.") zyClusterMemberPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyClusterMemberPassword.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberPassword.setDescription("Each cluster member's password is its administration password.") zyClusterMemberRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zyClusterMemberRowStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberRowStatus.setDescription('This object allows cluster member entries to be created and deleted from cluster member table.') zyxelClusterCandidate = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1)) zyxelClusterCandidateTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1), ) if mibBuilder.loadTexts: zyxelClusterCandidateTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterCandidateTable.setDescription('The table contains cluster candidate information.') zyxelClusterCandidateEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterCandidateMacAddress")) if mibBuilder.loadTexts: zyxelClusterCandidateEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterCandidateEntry.setDescription('An entry contains cluster candidate information.') zyClusterCandidateMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 1), MacAddress()) if mibBuilder.loadTexts: zyClusterCandidateMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateMacAddress.setDescription("This is the cluster candidate switch's hardware MAC address.") zyClusterCandidateName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterCandidateName.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateName.setDescription("This is the cluster candidate switch's system name.") zyClusterCandidateModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterCandidateModel.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateModel.setDescription("This is the cluster candidate switch's model name.") zyClusterRole = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("manager", 1), ("member", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterRole.setStatus('current') if mibBuilder.loadTexts: zyClusterRole.setDescription('The role of this switch within the cluster.') zyClusterInfoManager = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterInfoManager.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoManager.setDescription("The cluster manager switch's hardware MAC address.") zyxelClusterInfoMemberTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4), ) if mibBuilder.loadTexts: zyxelClusterInfoMemberTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterInfoMemberTable.setDescription('The table contains cluster member information.') zyxelClusterInfoMemberEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterInfoMemberMacAddress")) if mibBuilder.loadTexts: zyxelClusterInfoMemberEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterInfoMemberEntry.setDescription('An entry contains cluster member information.') zyClusterInfoMemberMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 1), MacAddress()) if mibBuilder.loadTexts: zyClusterInfoMemberMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.") zyClusterInfoMemberName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterInfoMemberName.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberName.setDescription("This is the cluster member switch's system name.") zyClusterInfoMemberModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterInfoMemberModel.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberModel.setDescription("This is the cluster member switch's model name.") zyClusterInfoMemberStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("error", 0), ("online", 1), ("offline", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterInfoMemberStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberStatus.setDescription('There are three types in cluster status. Online(the cluster member switch is accessible), Error (for example, the cluster member switch password was changed or the switch was set as the manager and so left the member list, etc.), Offline (the switch is disconnected - Offline shows approximately 1.5 minutes after the link between cluster member and manager goes down).') mibBuilder.exportSymbols("ZYXEL-CLUSTER-MIB", zyClusterCandidateModel=zyClusterCandidateModel, zyxelClusterManager=zyxelClusterManager, zyxelClusterCandidateEntry=zyxelClusterCandidateEntry, zyxelClusterMembers=zyxelClusterMembers, zyxelCluster=zyxelCluster, zyClusterInfoManager=zyClusterInfoManager, zyClusterInfoMemberModel=zyClusterInfoMemberModel, zyxelClusterSetup=zyxelClusterSetup, zyxelClusterInfoMemberTable=zyxelClusterInfoMemberTable, zyClusterMemberName=zyClusterMemberName, zyClusterCandidateName=zyClusterCandidateName, zyxelClusterStatus=zyxelClusterStatus, zyClusterManagerRowStatus=zyClusterManagerRowStatus, zyxelClusterManagerEntry=zyxelClusterManagerEntry, zyClusterManagerVid=zyClusterManagerVid, zyClusterInfoMemberMacAddress=zyClusterInfoMemberMacAddress, zyxelClusterManagerTable=zyxelClusterManagerTable, zyxelClusterInfoMemberEntry=zyxelClusterInfoMemberEntry, zyxelClusterMemberEntry=zyxelClusterMemberEntry, zyClusterInfoMemberStatus=zyClusterInfoMemberStatus, zyClusterRole=zyClusterRole, zyClusterMemberRowStatus=zyClusterMemberRowStatus, zyxelClusterCandidateTable=zyxelClusterCandidateTable, zyClusterMemberMaxNumberOfMembers=zyClusterMemberMaxNumberOfMembers, zyxelClusterMemberTable=zyxelClusterMemberTable, zyClusterInfoMemberName=zyClusterInfoMemberName, zyClusterManagerName=zyClusterManagerName, zyClusterMemberModel=zyClusterMemberModel, zyClusterMemberMacAddress=zyClusterMemberMacAddress, zyClusterCandidateMacAddress=zyClusterCandidateMacAddress, PYSNMP_MODULE_ID=zyxelCluster, zyClusterMemberPassword=zyClusterMemberPassword, zyxelClusterCandidate=zyxelClusterCandidate, zyClusterManagerMaxNumberOfManagers=zyClusterManagerMaxNumberOfManagers)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (iso, counter32, unsigned32, counter64, gauge32, integer32, bits, mib_identifier, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, time_ticks, notification_type, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Counter32', 'Unsigned32', 'Counter64', 'Gauge32', 'Integer32', 'Bits', 'MibIdentifier', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'TimeTicks', 'NotificationType', 'ModuleIdentity') (mac_address, display_string, textual_convention, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'MacAddress', 'DisplayString', 'TextualConvention', 'RowStatus') (es_mgmt,) = mibBuilder.importSymbols('ZYXEL-ES-SMI', 'esMgmt') zyxel_cluster = module_identity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14)) if mibBuilder.loadTexts: zyxelCluster.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelCluster.setOrganization('Enterprise Solution ZyXEL') if mibBuilder.loadTexts: zyxelCluster.setContactInfo('') if mibBuilder.loadTexts: zyxelCluster.setDescription('The subtree for cluster') zyxel_cluster_setup = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1)) zyxel_cluster_status = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2)) zyxel_cluster_manager = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1)) zy_cluster_manager_max_number_of_managers = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterManagerMaxNumberOfManagers.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerMaxNumberOfManagers.setDescription('The maximum number of cluster managers that can be created.') zyxel_cluster_manager_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2)) if mibBuilder.loadTexts: zyxelClusterManagerTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterManagerTable.setDescription('The table contains cluster manager configuration.') zyxel_cluster_manager_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1)).setIndexNames((0, 'ZYXEL-CLUSTER-MIB', 'zyClusterManagerVid')) if mibBuilder.loadTexts: zyxelClusterManagerEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterManagerEntry.setDescription('An entry contains cluster manager configuration. ') zy_cluster_manager_vid = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 1), integer32()) if mibBuilder.loadTexts: zyClusterManagerVid.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerVid.setDescription('This is the VLAN ID and is only applicable if the switch is set to 802.1Q VLAN. All switches must be directly connected and in the same VLAN group to belong to the same cluster.') zy_cluster_manager_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 2), display_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyClusterManagerName.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerName.setDescription('Type a name to identify the cluster manager.') zy_cluster_manager_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 3), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: zyClusterManagerRowStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerRowStatus.setDescription('This object allows cluster manager entries to be created and deleted from cluster manager table.') zyxel_cluster_members = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2)) zy_cluster_member_max_number_of_members = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterMemberMaxNumberOfMembers.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberMaxNumberOfMembers.setDescription('The maximum number of cluster members that can be created.') zyxel_cluster_member_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2)) if mibBuilder.loadTexts: zyxelClusterMemberTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterMemberTable.setDescription('The table contains cluster member configuration.') zyxel_cluster_member_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1)).setIndexNames((0, 'ZYXEL-CLUSTER-MIB', 'zyClusterMemberMacAddress')) if mibBuilder.loadTexts: zyxelClusterMemberEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterMemberEntry.setDescription('An entry contains cluster member configuration.') zy_cluster_member_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 1), mac_address()) if mibBuilder.loadTexts: zyClusterMemberMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.") zy_cluster_member_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterMemberName.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberName.setDescription("This is the cluster member switch's system name.") zy_cluster_member_model = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterMemberModel.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberModel.setDescription("This is the cluster member switch's model name.") zy_cluster_member_password = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 4), display_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyClusterMemberPassword.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberPassword.setDescription("Each cluster member's password is its administration password.") zy_cluster_member_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 5), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: zyClusterMemberRowStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberRowStatus.setDescription('This object allows cluster member entries to be created and deleted from cluster member table.') zyxel_cluster_candidate = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1)) zyxel_cluster_candidate_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1)) if mibBuilder.loadTexts: zyxelClusterCandidateTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterCandidateTable.setDescription('The table contains cluster candidate information.') zyxel_cluster_candidate_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1)).setIndexNames((0, 'ZYXEL-CLUSTER-MIB', 'zyClusterCandidateMacAddress')) if mibBuilder.loadTexts: zyxelClusterCandidateEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterCandidateEntry.setDescription('An entry contains cluster candidate information.') zy_cluster_candidate_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 1), mac_address()) if mibBuilder.loadTexts: zyClusterCandidateMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateMacAddress.setDescription("This is the cluster candidate switch's hardware MAC address.") zy_cluster_candidate_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterCandidateName.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateName.setDescription("This is the cluster candidate switch's system name.") zy_cluster_candidate_model = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterCandidateModel.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateModel.setDescription("This is the cluster candidate switch's model name.") zy_cluster_role = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('none', 0), ('manager', 1), ('member', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterRole.setStatus('current') if mibBuilder.loadTexts: zyClusterRole.setDescription('The role of this switch within the cluster.') zy_cluster_info_manager = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterInfoManager.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoManager.setDescription("The cluster manager switch's hardware MAC address.") zyxel_cluster_info_member_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4)) if mibBuilder.loadTexts: zyxelClusterInfoMemberTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterInfoMemberTable.setDescription('The table contains cluster member information.') zyxel_cluster_info_member_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1)).setIndexNames((0, 'ZYXEL-CLUSTER-MIB', 'zyClusterInfoMemberMacAddress')) if mibBuilder.loadTexts: zyxelClusterInfoMemberEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterInfoMemberEntry.setDescription('An entry contains cluster member information.') zy_cluster_info_member_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 1), mac_address()) if mibBuilder.loadTexts: zyClusterInfoMemberMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.") zy_cluster_info_member_name = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterInfoMemberName.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberName.setDescription("This is the cluster member switch's system name.") zy_cluster_info_member_model = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 3), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterInfoMemberModel.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberModel.setDescription("This is the cluster member switch's model name.") zy_cluster_info_member_status = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('error', 0), ('online', 1), ('offline', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: zyClusterInfoMemberStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberStatus.setDescription('There are three types in cluster status. Online(the cluster member switch is accessible), Error (for example, the cluster member switch password was changed or the switch was set as the manager and so left the member list, etc.), Offline (the switch is disconnected - Offline shows approximately 1.5 minutes after the link between cluster member and manager goes down).') mibBuilder.exportSymbols('ZYXEL-CLUSTER-MIB', zyClusterCandidateModel=zyClusterCandidateModel, zyxelClusterManager=zyxelClusterManager, zyxelClusterCandidateEntry=zyxelClusterCandidateEntry, zyxelClusterMembers=zyxelClusterMembers, zyxelCluster=zyxelCluster, zyClusterInfoManager=zyClusterInfoManager, zyClusterInfoMemberModel=zyClusterInfoMemberModel, zyxelClusterSetup=zyxelClusterSetup, zyxelClusterInfoMemberTable=zyxelClusterInfoMemberTable, zyClusterMemberName=zyClusterMemberName, zyClusterCandidateName=zyClusterCandidateName, zyxelClusterStatus=zyxelClusterStatus, zyClusterManagerRowStatus=zyClusterManagerRowStatus, zyxelClusterManagerEntry=zyxelClusterManagerEntry, zyClusterManagerVid=zyClusterManagerVid, zyClusterInfoMemberMacAddress=zyClusterInfoMemberMacAddress, zyxelClusterManagerTable=zyxelClusterManagerTable, zyxelClusterInfoMemberEntry=zyxelClusterInfoMemberEntry, zyxelClusterMemberEntry=zyxelClusterMemberEntry, zyClusterInfoMemberStatus=zyClusterInfoMemberStatus, zyClusterRole=zyClusterRole, zyClusterMemberRowStatus=zyClusterMemberRowStatus, zyxelClusterCandidateTable=zyxelClusterCandidateTable, zyClusterMemberMaxNumberOfMembers=zyClusterMemberMaxNumberOfMembers, zyxelClusterMemberTable=zyxelClusterMemberTable, zyClusterInfoMemberName=zyClusterInfoMemberName, zyClusterManagerName=zyClusterManagerName, zyClusterMemberModel=zyClusterMemberModel, zyClusterMemberMacAddress=zyClusterMemberMacAddress, zyClusterCandidateMacAddress=zyClusterCandidateMacAddress, PYSNMP_MODULE_ID=zyxelCluster, zyClusterMemberPassword=zyClusterMemberPassword, zyxelClusterCandidate=zyxelClusterCandidate, zyClusterManagerMaxNumberOfManagers=zyClusterManagerMaxNumberOfManagers)
# import math # def squareRoot(a): # return round(math.sqrt(float(a)),9) def squareRoot(a): return round(float(a)**(1/2),8)
def square_root(a): return round(float(a) ** (1 / 2), 8)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if not head: return None dummyHead = currentNode = ListNode() dummyHead.next = head while currentNode.next: if currentNode.next.val == val: currentNode.next = currentNode.next.next else: currentNode = currentNode.next return dummyHead.next
class Solution: def remove_elements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if not head: return None dummy_head = current_node = list_node() dummyHead.next = head while currentNode.next: if currentNode.next.val == val: currentNode.next = currentNode.next.next else: current_node = currentNode.next return dummyHead.next
# 2021 April 16. Surrendered entirely. # 2-d dp. # text1 = "abcba", text2 = "abcbcba" # At any two positions i, j in t1 and t2, if 1) t1[i] == t2[j] # then the length of common subsequence count should increment by 1 and # we then check from t1[i+1] and t2[j+1]. If 2) t1[i] != t2[j], then we # should keep on finding common susbequence of t1[i], t2[j+1] and t1[i+1] # and t2[j], whichever includes a bigger common subsequence. So in the # example, checking from the left to the right, "abcb" is common (logic 1) # at work). Then we are left with "a" vs. "cba", "a","c" don't match, so # dp of "a","c" refers to "","c" (0) and "a","b", which in turn refers # to "", "b"(0) and "a", "a". Since "a","a" is a match, dp of it is 1 # plus that of "", "", which is 0. So the boundary of common subseq # length all 0, propagates the value back to the topleft corner # dp[0][0] that we want, through some route that is determined by the # matchings in the two texts. But algo won't know which route it takes # beforehand, so solving the entire matrix, from bottom right to top left # , would be necessary. # dp a b c b a "" # a 1 0 # b 1 0 # c 1 0 # b 1 0 # c *,1 0 # b *,1 0 # a 1 0 # "" 0 0 0 0 0 0 # * represents not knowing the value first, have to check right and # downward. This checking keeps going until it reaches the bottom. class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # One additional row and col to store bounary conditions. # 0, 1, ..., len(text1) - 1, for each char in text1, then len(text1) for boundary 0. ROWS, COLS = len(text1) + 1, len(text2) + 1 dp = [[0 for _ in range(COLS)] for _ in range(ROWS)] for row in range(ROWS - 2, -1, -1): for col in range(COLS - 2, -1, -1): if text1[row] == text2[col]: dp[row][col] = 1 + dp[row+1][col+1] else: dp[row][col] = max(dp[row+1][col], dp[row][col+1]) return dp[0][0] if __name__ == "__main__": print(Solution().longestCommonSubsequence("papmretkborsrurgtina", "nsnupotstmnkfcfavaxgl"))
class Solution: def longest_common_subsequence(self, text1: str, text2: str) -> int: (rows, cols) = (len(text1) + 1, len(text2) + 1) dp = [[0 for _ in range(COLS)] for _ in range(ROWS)] for row in range(ROWS - 2, -1, -1): for col in range(COLS - 2, -1, -1): if text1[row] == text2[col]: dp[row][col] = 1 + dp[row + 1][col + 1] else: dp[row][col] = max(dp[row + 1][col], dp[row][col + 1]) return dp[0][0] if __name__ == '__main__': print(solution().longestCommonSubsequence('papmretkborsrurgtina', 'nsnupotstmnkfcfavaxgl'))
class BaseSensor(): def __init__(self): self.null_value = 0 self.sensor = None self.measurements = [] self.upper_reasonable_bound = 200 self.lower_reasonable_bound = 0 def setup(self): self.sensor = None def read(self): return None def average(self, measurements): if len(measurements) != 0: return sum(measurements)/len(measurements) else: return self.null_value def rolling_average(self, measurement, measurements, size): if measurement == None: return None if self.lower_reasonable_bound < measurement < self.upper_reasonable_bound: if len(measurements) >= size: measurements.pop(0) measurements.append(measurement) return self.average(measurements) def mapNum(self, val, old_max, old_min, new_max, new_min): try: old_range = float(old_max - old_min) new_range = float(new_max - new_min) new_value = float(((val - old_min) * new_range) / old_range) + new_min return new_value except Exception: return val
class Basesensor: def __init__(self): self.null_value = 0 self.sensor = None self.measurements = [] self.upper_reasonable_bound = 200 self.lower_reasonable_bound = 0 def setup(self): self.sensor = None def read(self): return None def average(self, measurements): if len(measurements) != 0: return sum(measurements) / len(measurements) else: return self.null_value def rolling_average(self, measurement, measurements, size): if measurement == None: return None if self.lower_reasonable_bound < measurement < self.upper_reasonable_bound: if len(measurements) >= size: measurements.pop(0) measurements.append(measurement) return self.average(measurements) def map_num(self, val, old_max, old_min, new_max, new_min): try: old_range = float(old_max - old_min) new_range = float(new_max - new_min) new_value = float((val - old_min) * new_range / old_range) + new_min return new_value except Exception: return val
def time_in_range(data, bg_range=(4.0, 7.0)): # data[0] is the time values - assume they are equally spaced, so we can ignore values = data[1] return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values) def mean(data): values = data[1] return float(sum(values)) / len(values) def estimated_hba1c(data): # from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2742903/ return hba1c_ngsp_to_ifcc((mean(data) + 2.59) / 1.59) def hba1c_ngsp_to_ifcc(ngsp): # from http://www.ngsp.org/ifccngsp.asp return 10.93 * ngsp - 23.50
def time_in_range(data, bg_range=(4.0, 7.0)): values = data[1] return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values) def mean(data): values = data[1] return float(sum(values)) / len(values) def estimated_hba1c(data): return hba1c_ngsp_to_ifcc((mean(data) + 2.59) / 1.59) def hba1c_ngsp_to_ifcc(ngsp): return 10.93 * ngsp - 23.5
def maior_primo(x) -> object: for maior in reversed(range(1,x+1)): if all(maior%n!=0 for n in range(2,maior)): return maior
def maior_primo(x) -> object: for maior in reversed(range(1, x + 1)): if all((maior % n != 0 for n in range(2, maior))): return maior
USER_CREATED = "user_created" USER_ADDED = "user_added_to_request" USER_REMOVED = "user_removed_from_request" USER_PERM_CHANGED = "user_permissions_changed" USER_STATUS_CHANGED = "user_status_changed" # user, admin, super USER_INFO_EDITED = "user_information_edited" REQUESTER_INFO_EDITED = "requester_information_edited" REQ_CREATED = "request_created" AGENCY_REQ_CREATED = "agency_submitted_request" REQ_ACKNOWLEDGED = "request_acknowledged" REQ_DENIED = "request_denied" REQ_STATUS_CHANGED = "request_status_changed" REQ_EXTENDED = "request_extended" REQ_CLOSED = "request_closed" REQ_REOPENED = "request_reopened" REQ_TITLE_EDITED = "request_title_edited" REQ_AGENCY_REQ_SUM_EDITED = "request_agency_request_summary_edited" REQ_TITLE_PRIVACY_EDITED = "request_title_privacy_edited" REQ_AGENCY_REQ_SUM_PRIVACY_EDITED = "request_agency_request_summary_privacy_edited" REQ_AGENCY_REQ_SUM_DATE_SET = "request_agency_request_summary_date_set" REQ_POINT_OF_CONTACT_ADDED = "request_point_of_contact_added" REQ_POINT_OF_CONTACT_REMOVED = "request_point_of_contact_removed" EMAIL_NOTIFICATION_SENT = "email_notification_sent" FILE_ADDED = "file_added" FILE_EDITED = "file_edited" FILE_PRIVACY_EDITED = "file_privacy_edited" FILE_REPLACED = "file_replaced" FILE_REMOVED = "file_removed" LINK_ADDED = "link_added" LINK_EDITED = "link_edited" LINK_PRIVACY_EDITED = "link_privacy_edited" LINK_REMOVED = "link_removed" INSTRUCTIONS_ADDED = "instructions_added" INSTRUCTIONS_EDITED = "instructions_edited" INSTRUCTIONS_PRIVACY_EDITED = "instructions_privacy_edited" INSTRUCTIONS_REMOVED = "instructions_removed" NOTE_ADDED = "note_added" NOTE_EDITED = "note_edited" NOTE_PRIVACY_EDITED = "note_privacy_edited" NOTE_REMOVED = "note_removed" AGENCY_ACTIVATED = "agency_activated" AGENCY_DEACTIVATED = "agency_deactivated" AGENCY_USER_ACTIVATED = "agency_user_activated" AGENCY_USER_DEACTIVATED = "agency_user_deactivated" CONTACT_EMAIL_SENT = "contact_email_sent" USER_LOGIN = "user_logged_in" USER_AUTHORIZED = "user_authorized" USER_LOGGED_OUT = "user_logged_out" USER_MADE_AGENCY_ADMIN = "user_made_agency_admin" USER_MADE_AGENCY_USER = "user_made_agency_user" USER_PROFILE_UPDATED = "user_profile_updated" ACKNOWLEDGMENT_LETTER_CREATED = 'acknowledgment_letter_created' DENIAL_LETTER_CREATED = 'denial_letter_created' CLOSING_LETTER_CREATED = 'closing_letter_created' EXTENSION_LETTER_CREATED = 'extension_letter_created' ENVELOPE_CREATED = 'envelope_created' RESPONSE_LETTER_CREATED = 'response_letter_created' REOPENING_LETTER_CREATED = 'reopening_letter_created' FOR_REQUEST_HISTORY = [ USER_ADDED, USER_REMOVED, USER_PERM_CHANGED, REQUESTER_INFO_EDITED, REQ_CREATED, AGENCY_REQ_CREATED, REQ_STATUS_CHANGED, REQ_ACKNOWLEDGED, REQ_EXTENDED, REQ_CLOSED, REQ_REOPENED, REQ_TITLE_EDITED, REQ_AGENCY_REQ_SUM_EDITED, REQ_TITLE_PRIVACY_EDITED, REQ_AGENCY_REQ_SUM_PRIVACY_EDITED, FILE_ADDED, FILE_EDITED, FILE_REMOVED, LINK_ADDED, LINK_EDITED, LINK_REMOVED, INSTRUCTIONS_ADDED, INSTRUCTIONS_EDITED, INSTRUCTIONS_REMOVED, NOTE_ADDED, NOTE_EDITED, NOTE_REMOVED, ENVELOPE_CREATED, RESPONSE_LETTER_CREATED ] RESPONSE_ADDED_TYPES = [ FILE_ADDED, LINK_ADDED, INSTRUCTIONS_ADDED, NOTE_ADDED, ] RESPONSE_EDITED_TYPES = [ FILE_EDITED, FILE_REPLACED, FILE_PRIVACY_EDITED, LINK_EDITED, LINK_PRIVACY_EDITED, INSTRUCTIONS_EDITED, INSTRUCTIONS_PRIVACY_EDITED, NOTE_ADDED, NOTE_PRIVACY_EDITED ] RESPONSE_REMOVED_TYPES = [ FILE_REMOVED, LINK_REMOVED, INSTRUCTIONS_REMOVED, NOTE_REMOVED ] SYSTEM_TYPES = [ AGENCY_ACTIVATED, AGENCY_DEACTIVATED, AGENCY_USER_ACTIVATED, AGENCY_USER_DEACTIVATED, CONTACT_EMAIL_SENT, USER_LOGIN, USER_AUTHORIZED, USER_LOGGED_OUT, USER_MADE_AGENCY_ADMIN, USER_MADE_AGENCY_USER, USER_PROFILE_UPDATED ]
user_created = 'user_created' user_added = 'user_added_to_request' user_removed = 'user_removed_from_request' user_perm_changed = 'user_permissions_changed' user_status_changed = 'user_status_changed' user_info_edited = 'user_information_edited' requester_info_edited = 'requester_information_edited' req_created = 'request_created' agency_req_created = 'agency_submitted_request' req_acknowledged = 'request_acknowledged' req_denied = 'request_denied' req_status_changed = 'request_status_changed' req_extended = 'request_extended' req_closed = 'request_closed' req_reopened = 'request_reopened' req_title_edited = 'request_title_edited' req_agency_req_sum_edited = 'request_agency_request_summary_edited' req_title_privacy_edited = 'request_title_privacy_edited' req_agency_req_sum_privacy_edited = 'request_agency_request_summary_privacy_edited' req_agency_req_sum_date_set = 'request_agency_request_summary_date_set' req_point_of_contact_added = 'request_point_of_contact_added' req_point_of_contact_removed = 'request_point_of_contact_removed' email_notification_sent = 'email_notification_sent' file_added = 'file_added' file_edited = 'file_edited' file_privacy_edited = 'file_privacy_edited' file_replaced = 'file_replaced' file_removed = 'file_removed' link_added = 'link_added' link_edited = 'link_edited' link_privacy_edited = 'link_privacy_edited' link_removed = 'link_removed' instructions_added = 'instructions_added' instructions_edited = 'instructions_edited' instructions_privacy_edited = 'instructions_privacy_edited' instructions_removed = 'instructions_removed' note_added = 'note_added' note_edited = 'note_edited' note_privacy_edited = 'note_privacy_edited' note_removed = 'note_removed' agency_activated = 'agency_activated' agency_deactivated = 'agency_deactivated' agency_user_activated = 'agency_user_activated' agency_user_deactivated = 'agency_user_deactivated' contact_email_sent = 'contact_email_sent' user_login = 'user_logged_in' user_authorized = 'user_authorized' user_logged_out = 'user_logged_out' user_made_agency_admin = 'user_made_agency_admin' user_made_agency_user = 'user_made_agency_user' user_profile_updated = 'user_profile_updated' acknowledgment_letter_created = 'acknowledgment_letter_created' denial_letter_created = 'denial_letter_created' closing_letter_created = 'closing_letter_created' extension_letter_created = 'extension_letter_created' envelope_created = 'envelope_created' response_letter_created = 'response_letter_created' reopening_letter_created = 'reopening_letter_created' for_request_history = [USER_ADDED, USER_REMOVED, USER_PERM_CHANGED, REQUESTER_INFO_EDITED, REQ_CREATED, AGENCY_REQ_CREATED, REQ_STATUS_CHANGED, REQ_ACKNOWLEDGED, REQ_EXTENDED, REQ_CLOSED, REQ_REOPENED, REQ_TITLE_EDITED, REQ_AGENCY_REQ_SUM_EDITED, REQ_TITLE_PRIVACY_EDITED, REQ_AGENCY_REQ_SUM_PRIVACY_EDITED, FILE_ADDED, FILE_EDITED, FILE_REMOVED, LINK_ADDED, LINK_EDITED, LINK_REMOVED, INSTRUCTIONS_ADDED, INSTRUCTIONS_EDITED, INSTRUCTIONS_REMOVED, NOTE_ADDED, NOTE_EDITED, NOTE_REMOVED, ENVELOPE_CREATED, RESPONSE_LETTER_CREATED] response_added_types = [FILE_ADDED, LINK_ADDED, INSTRUCTIONS_ADDED, NOTE_ADDED] response_edited_types = [FILE_EDITED, FILE_REPLACED, FILE_PRIVACY_EDITED, LINK_EDITED, LINK_PRIVACY_EDITED, INSTRUCTIONS_EDITED, INSTRUCTIONS_PRIVACY_EDITED, NOTE_ADDED, NOTE_PRIVACY_EDITED] response_removed_types = [FILE_REMOVED, LINK_REMOVED, INSTRUCTIONS_REMOVED, NOTE_REMOVED] system_types = [AGENCY_ACTIVATED, AGENCY_DEACTIVATED, AGENCY_USER_ACTIVATED, AGENCY_USER_DEACTIVATED, CONTACT_EMAIL_SENT, USER_LOGIN, USER_AUTHORIZED, USER_LOGGED_OUT, USER_MADE_AGENCY_ADMIN, USER_MADE_AGENCY_USER, USER_PROFILE_UPDATED]
# Find the sum of the numbers 8, 9, 10 # Var declarations num1 = 8 num2 = 9 num3 = 10 # Code sum = num1 + num2 + num3 # Result print(sum)
num1 = 8 num2 = 9 num3 = 10 sum = num1 + num2 + num3 print(sum)
# Write your make_spoonerism function here: def make_spoonerism(word1, word2): a = word1[0] b = word2[0] c = word1[0].replace(a,b) + word1[1:] d = word2[0].replace(b,a) + word2[1:] e = c + ' ' + d return e # Uncomment these function calls to test your function: print(make_spoonerism("Codecademy", "Learn")) # should print Lodecademy Cearn print(make_spoonerism("Hello", "world!")) # should print wello Horld! print(make_spoonerism("a", "b")) # should print b a # OR # OR # # Write your make_spoonerism function here: # def make_spoonerism(word1, word2): # return word2[0]+word1[1:]+" "+word1[0]+word2[1:] # # Uncomment these function calls to test your tip function: # print(make_spoonerism("Codecademy", "Learn")) # # should print Lodecademy Cearn # print(make_spoonerism("Hello", "world!")) # # should print wello Horld! # print(make_spoonerism("a", "b")) # # should print b a
def make_spoonerism(word1, word2): a = word1[0] b = word2[0] c = word1[0].replace(a, b) + word1[1:] d = word2[0].replace(b, a) + word2[1:] e = c + ' ' + d return e print(make_spoonerism('Codecademy', 'Learn')) print(make_spoonerism('Hello', 'world!')) print(make_spoonerism('a', 'b'))
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"trace_log": "01_convert_time_log.ipynb", "format_value": "01_convert_time_log.ipynb", "strip_extra_EnmacClientTime_elements": "01_convert_time_log.ipynb", "unix_time_milliseconds": "01_convert_time_log.ipynb", "parse_dt": "01_convert_time_log.ipynb", "parse_dt_to_milliseconds": "01_convert_time_log.ipynb", "parse_httpd_dt": "01_convert_time_log.ipynb", "parse_httpd_dt_to_milliseconds": "01_convert_time_log.ipynb", "match_last2digits": "01_convert_time_log.ipynb", "parse_timing_log": "01_convert_time_log.ipynb", "parse_log_line": "01_convert_time_log.ipynb", "parse_log_line_to_dict": "01_convert_time_log.ipynb", "parse_httpd_log": "01_convert_time_log.ipynb", "log_re": "01_convert_time_log.ipynb", "request_re": "01_convert_time_log.ipynb", "parse_httpd_log_file": "01_convert_time_log.ipynb", "parse_timing_log_file": "01_convert_time_log.ipynb"} modules = ["convert_time_log.py"] doc_url = "https://3ideas.github.io/cronos/" git_url = "https://github.com/3ideas/cronos/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'trace_log': '01_convert_time_log.ipynb', 'format_value': '01_convert_time_log.ipynb', 'strip_extra_EnmacClientTime_elements': '01_convert_time_log.ipynb', 'unix_time_milliseconds': '01_convert_time_log.ipynb', 'parse_dt': '01_convert_time_log.ipynb', 'parse_dt_to_milliseconds': '01_convert_time_log.ipynb', 'parse_httpd_dt': '01_convert_time_log.ipynb', 'parse_httpd_dt_to_milliseconds': '01_convert_time_log.ipynb', 'match_last2digits': '01_convert_time_log.ipynb', 'parse_timing_log': '01_convert_time_log.ipynb', 'parse_log_line': '01_convert_time_log.ipynb', 'parse_log_line_to_dict': '01_convert_time_log.ipynb', 'parse_httpd_log': '01_convert_time_log.ipynb', 'log_re': '01_convert_time_log.ipynb', 'request_re': '01_convert_time_log.ipynb', 'parse_httpd_log_file': '01_convert_time_log.ipynb', 'parse_timing_log_file': '01_convert_time_log.ipynb'} modules = ['convert_time_log.py'] doc_url = 'https://3ideas.github.io/cronos/' git_url = 'https://github.com/3ideas/cronos/tree/master/' def custom_doc_links(name): return None
#Planetary database #Source for planetary data, and some of the data on #the moons, is http://nssdc.gsfc.nasa.gov/planetary/factsheet/ class Planet: ''' A Planet object contains basic planetary data. If P is a Planet object, the data are: P.name = Name of the planet P.a = Mean radius of planet (m) P.g = Surface gravitational acceleration (m/s**2) P.L = Annual mean solar constant (current) (W/m**2) P.albedo Bond albedo (fraction) P.rsm = Semi-major axis of orbit about Sun (m) P.year = Sidereal length of year (s) P.eccentricity = Eccentricity (unitless) P.day = Mean tropical length of day (s) P.obliquity = Obliquity to orbit (degrees) P.Lequinox = Longitude of equinox (degrees) P.Tsbar = Mean surface temperature (K) P.Tsmax = Maximum surface temperature (K) For gas giants, "surface" quantities are given at the 1 bar level ''' #__repr__ object prints out a help string when help is #invoked on the planet object or the planet name is typed def __repr__(self): line1 =\ 'This planet object contains information on %s\n'%self.name line2 = 'Type \"help(Planet)\" for more information\n' return line1+line2 def __init__(self): self.name = None #Name of the planet self.a = None #Mean radius of planet self.g = None #Surface gravitational acceleration self.L = None #Annual mean solar constant (current) self.albedo = None #Bond albedo self.rsm = None #Semi-major axis self.year = None #Sidereal length of year self.eccentricity = None # Eccentricity self.day = None #Mean tropical length of day self.obliquity = None #Obliquity to orbit self.Lequinox = None #Longitude of equinox self.Tsbar = None #Mean surface temperature self.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Mercury = Planet() Mercury.name = 'Mercury' #Name of the planet Mercury.a = 2.4397e6 #Mean radius of planet Mercury.g = 3.70 #Surface gravitational acceleration Mercury.albedo = .119 #Bond albedo Mercury.L = 9126.6 #Annual mean solar constant (current) # Mercury.rsm = 57.91e9 #Semi-major axis Mercury.year = 87.969*24.*3600. #Sidereal length of year Mercury.eccentricity = .2056 # Eccentricity Mercury.day = 4222.6*3600. #Mean tropical length of day Mercury.obliquity = .01 #Obliquity to orbit (deg) Mercury.Lequinox = None #Longitude of equinox (deg) # Mercury.Tsbar = 440. #Mean surface temperature Mercury.Tsmax = 725. #Maximum surface temperature #---------------------------------------------------- Venus = Planet() Venus.name = 'Venus' #Name of the planet Venus.a = 6.0518e6 #Mean radius of planet Venus.g = 8.87 #Surface gravitational acceleration Venus.albedo = .750 #Bond albedo Venus.L = 2613.9 #Annual mean solar constant (current) # Venus.rsm = 108.21e9 #Semi-major axis Venus.year = 224.701*24.*3600. #Sidereal length of year Venus.eccentricity = .0067 # Eccentricity Venus.day = 2802.*3600. #Mean tropical length of day Venus.obliquity = 177.36 #Obliquity to orbit (deg) Venus.Lequinox = None #Longitude of equinox (deg) # Venus.Tsbar = 737. #Mean surface temperature Venus.Tsmax = 737. #Maximum surface temperature #---------------------------------------------------- Earth = Planet() Earth.name = 'Earth' #Name of the planet Earth.a = 6.371e6 #Mean radius of planet Earth.g = 9.798 #Surface gravitational acceleration Earth.albedo = .306 #Bond albedo Earth.L = 1367.6 #Annual mean solar constant (current) # Earth.rsm = 149.60e9 #Semi-major axis Earth.year = 365.256*24.*3600. #Sidereal length of year Earth.eccentricity = .0167 # Eccentricity Earth.day = 24.000*3600. #Mean tropical length of day Earth.obliquity = 23.45 #Obliquity to orbit (deg) Earth.Lequinox = None #Longitude of equinox (deg) # Earth.Tsbar = 288. #Mean surface temperature Earth.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Mars = Planet() Mars.name = 'Mars' #Name of the planet Mars.a = 3.390e6 #Mean radius of planet Mars.g = 3.71 #Surface gravitational acceleration Mars.albedo = .250 #Bond albedo Mars.L = 589.2 #Annual mean solar constant (current) # Mars.rsm = 227.92e9 #Semi-major axis Mars.year = 686.98*24.*3600. #Sidereal length of year Mars.eccentricity = .0935 # Eccentricity Mars.day = 24.6597*3600. #Mean tropical length of day Mars.obliquity = 25.19 #Obliquity to orbit (deg) Mars.Lequinox = None #Longitude of equinox (deg) # Mars.Tsbar = 210. #Mean surface temperature Mars.Tsmax = 295. #Maximum surface temperature #---------------------------------------------------- Jupiter = Planet() Jupiter.name = 'Jupiter' #Name of the planet Jupiter.a = 69.911e6 #Mean radius of planet Jupiter.g = 24.79 #Surface gravitational acceleration Jupiter.albedo = .343 #Bond albedo Jupiter.L = 50.5 #Annual mean solar constant (current) # Jupiter.rsm = 778.57e9 #Semi-major axis Jupiter.year = 4332.*24.*3600. #Sidereal length of year Jupiter.eccentricity = .0489 # Eccentricity Jupiter.day = 9.9259*3600. #Mean tropical length of day Jupiter.obliquity = 3.13 #Obliquity to orbit (deg) Jupiter.Lequinox = None #Longitude of equinox (deg) # Jupiter.Tsbar = 165. #Mean surface temperature Jupiter.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Saturn = Planet() Saturn.name = 'Saturn' #Name of the planet Saturn.a = 58.232e6 #Mean radius of planet Saturn.g = 10.44 #Surface gravitational acceleration Saturn.albedo = .342 #Bond albedo Saturn.L = 14.90 #Annual mean solar constant (current) # Saturn.rsm = 1433.e9 #Semi-major axis Saturn.year = 10759.*24.*3600. #Sidereal length of year Saturn.eccentricity = .0565 # Eccentricity Saturn.day = 10.656*3600. #Mean tropical length of day Saturn.obliquity = 26.73 #Obliquity to orbit (deg) Saturn.Lequinox = None #Longitude of equinox (deg) # Saturn.Tsbar = 134. #Mean surface temperature Saturn.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Uranus = Planet() Uranus.name = 'Uranus' #Name of the planet Uranus.a = 25.362e6 #Mean radius of planet Uranus.g = 8.87 #Surface gravitational acceleration Uranus.albedo = .300 #Bond albedo Uranus.L = 3.71 #Annual mean solar constant (current) # Uranus.rsm = 2872.46e9 #Semi-major axis Uranus.year = 30685.4*24.*3600. #Sidereal length of year Uranus.eccentricity = .0457 # Eccentricity Uranus.day = 17.24*3600. #Mean tropical length of day Uranus.obliquity = 97.77 #Obliquity to orbit (deg) Uranus.Lequinox = None #Longitude of equinox (deg) # Uranus.Tsbar = 76. #Mean surface temperature Uranus.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Neptune = Planet() Neptune.name = 'Neptune' #Name of the planet Neptune.a = 26.624e6 #Mean radius of planet Neptune.g = 11.15 #Surface gravitational acceleration Neptune.albedo = .290 #Bond albedo Neptune.L = 1.51 #Annual mean solar constant (current) # Neptune.rsm = 4495.06e9 #Semi-major axis Neptune.year = 60189.0*24.*3600. #Sidereal length of year Neptune.eccentricity = .0113 # Eccentricity Neptune.day = 16.11*3600. #Mean tropical length of day Neptune.obliquity = 28.32 #Obliquity to orbit (deg) Neptune.Lequinox = None #Longitude of equinox (deg) # Neptune.Tsbar = 72. #Mean surface temperature Neptune.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Pluto = Planet() Pluto.name = 'Pluto' #Name of the planet Pluto.a = 1.195e6 #Mean radius of planet Pluto.g = .58 #Surface gravitational acceleration Pluto.albedo = .5 #Bond albedo Pluto.L = .89 #Annual mean solar constant (current) # Pluto.rsm = 5906.e9 #Semi-major axis Pluto.year = 90465.*24.*3600. #Sidereal length of year Pluto.eccentricity = .2488 # Eccentricity Pluto.day = 153.2820*3600. #Mean tropical length of day Pluto.obliquity = 122.53 #Obliquity to orbit (deg) Pluto.Lequinox = None #Longitude of equinox (deg) # Pluto.Tsbar = 50. #Mean surface temperature Pluto.Tsmax = None #Maximum surface temperature #Selected moons #---------------------------------------------------- Moon = Planet() Moon.name = 'Moon' #Name of the planet Moon.a = 1.737e6 #Mean radius of planet Moon.g = 1.62 #Surface gravitational acceleration Moon.albedo = .11 #Bond albedo Moon.L = 1367.6 #Annual mean solar constant (current) # Moon.rsm = Earth.rsm #Semi-major axis Moon.year = Earth.year #Sidereal length of year Moon.eccentricity = None # Eccentricity Moon.day = 28.*24.*3600. #Mean tropical length of day (approx) Moon.obliquity = None #Obliquity to orbit (deg) Moon.Lequinox = None #Longitude of equinox (deg) # Moon.Tsbar = None #Mean surface temperature Moon.Tsmax = 400. #Maximum surface temperature Moon.Tsmin = 100. #Minimum surface temperature Titan = Planet() Titan.name = 'Titan' #Name of the planet Titan.a = 2.575e6 #Mean radius of planet Titan.g = 1.35 #Surface gravitational acceleration Titan.L = Saturn.L #Annual mean solar constant (current) Titan.albedo = .21 #Bond albedo (Not yet updated from Cassini) # Titan.rsm = None #Semi-major axis Titan.year = Saturn.year #Sidereal length of year Titan.eccentricity = Saturn.eccentricity # Eccentricity ABOUT SUN Titan.day = 15.9452*24.*3600. #Mean tropical length of day Titan.obliquity = Saturn.obliquity #Obliquity to plane of Ecliptic #(Titan's rotation axis approx parallel # to Saturn's Titan.Lequinox = Saturn.Lequinox #Longitude of equinox # Titan.Tsbar = 95. #Mean surface temperature Titan.Tsmax = None #Maximum surface temperature Europa = Planet() Europa.name = 'Europa' #Name of the planet Europa.a = 1.560e6 #Mean radius of planet Europa.g = 1.31 #Surface gravitational acceleration Europa.L = Jupiter.L #Annual mean solar constant (current) Europa.albedo = .67 #Bond albedo # Europa.rsm = Jupiter.rsm #Semi-major axis Europa.year = Jupiter.year #Sidereal length of year Europa.eccentricity = Jupiter.eccentricity # Eccentricity Europa.day = 3.551*24.*3600. #Mean tropical length of day Europa.obliquity = Jupiter.obliquity #Obliquity to plane of ecliptic Europa.Lequinox = None #Longitude of equinox # Europa.Tsbar = 103. #Mean surface temperature Europa.Tsmax = 125. #Maximum surface temperature Triton = Planet() Triton.name = 'Triton' #Name of the planet Triton.a = 2.7068e6/2. #Mean radius of planet Triton.g = .78 #Surface gravitational acceleration Triton.L = Neptune.L #Annual mean solar constant (current) Triton.albedo = .76 #Bond albedo # Triton.rsm = Neptune.rsm #Semi-major axis Triton.year = Neptune.year #Sidereal length of year Triton.eccentricity = Neptune.eccentricity # Eccentricity about Sun Triton.day = 5.877*24.*3600. #Mean tropical length of day #Triton's rotation is retrograde Triton.obliquity = 156. #Obliquity to ecliptic **ToDo: Check this. #Note: Seasons are influenced by the inclination #of Triton's orbit? (About 20 degrees to #Neptune's equator Triton.Lequinox = None #Longitude of equinox # Triton.Tsbar = 34.5 #Mean surface temperature #This is probably a computed blackbody #temperature, rather than an observation Triton.Tsmax = None #Maximum surface temperature
class Planet: """ A Planet object contains basic planetary data. If P is a Planet object, the data are: P.name = Name of the planet P.a = Mean radius of planet (m) P.g = Surface gravitational acceleration (m/s**2) P.L = Annual mean solar constant (current) (W/m**2) P.albedo Bond albedo (fraction) P.rsm = Semi-major axis of orbit about Sun (m) P.year = Sidereal length of year (s) P.eccentricity = Eccentricity (unitless) P.day = Mean tropical length of day (s) P.obliquity = Obliquity to orbit (degrees) P.Lequinox = Longitude of equinox (degrees) P.Tsbar = Mean surface temperature (K) P.Tsmax = Maximum surface temperature (K) For gas giants, "surface" quantities are given at the 1 bar level """ def __repr__(self): line1 = 'This planet object contains information on %s\n' % self.name line2 = 'Type "help(Planet)" for more information\n' return line1 + line2 def __init__(self): self.name = None self.a = None self.g = None self.L = None self.albedo = None self.rsm = None self.year = None self.eccentricity = None self.day = None self.obliquity = None self.Lequinox = None self.Tsbar = None self.Tsmax = None mercury = planet() Mercury.name = 'Mercury' Mercury.a = 2439700.0 Mercury.g = 3.7 Mercury.albedo = 0.119 Mercury.L = 9126.6 Mercury.rsm = 57910000000.0 Mercury.year = 87.969 * 24.0 * 3600.0 Mercury.eccentricity = 0.2056 Mercury.day = 4222.6 * 3600.0 Mercury.obliquity = 0.01 Mercury.Lequinox = None Mercury.Tsbar = 440.0 Mercury.Tsmax = 725.0 venus = planet() Venus.name = 'Venus' Venus.a = 6051800.0 Venus.g = 8.87 Venus.albedo = 0.75 Venus.L = 2613.9 Venus.rsm = 108210000000.0 Venus.year = 224.701 * 24.0 * 3600.0 Venus.eccentricity = 0.0067 Venus.day = 2802.0 * 3600.0 Venus.obliquity = 177.36 Venus.Lequinox = None Venus.Tsbar = 737.0 Venus.Tsmax = 737.0 earth = planet() Earth.name = 'Earth' Earth.a = 6371000.0 Earth.g = 9.798 Earth.albedo = 0.306 Earth.L = 1367.6 Earth.rsm = 149600000000.0 Earth.year = 365.256 * 24.0 * 3600.0 Earth.eccentricity = 0.0167 Earth.day = 24.0 * 3600.0 Earth.obliquity = 23.45 Earth.Lequinox = None Earth.Tsbar = 288.0 Earth.Tsmax = None mars = planet() Mars.name = 'Mars' Mars.a = 3390000.0 Mars.g = 3.71 Mars.albedo = 0.25 Mars.L = 589.2 Mars.rsm = 227920000000.0 Mars.year = 686.98 * 24.0 * 3600.0 Mars.eccentricity = 0.0935 Mars.day = 24.6597 * 3600.0 Mars.obliquity = 25.19 Mars.Lequinox = None Mars.Tsbar = 210.0 Mars.Tsmax = 295.0 jupiter = planet() Jupiter.name = 'Jupiter' Jupiter.a = 69911000.0 Jupiter.g = 24.79 Jupiter.albedo = 0.343 Jupiter.L = 50.5 Jupiter.rsm = 778570000000.0 Jupiter.year = 4332.0 * 24.0 * 3600.0 Jupiter.eccentricity = 0.0489 Jupiter.day = 9.9259 * 3600.0 Jupiter.obliquity = 3.13 Jupiter.Lequinox = None Jupiter.Tsbar = 165.0 Jupiter.Tsmax = None saturn = planet() Saturn.name = 'Saturn' Saturn.a = 58232000.0 Saturn.g = 10.44 Saturn.albedo = 0.342 Saturn.L = 14.9 Saturn.rsm = 1433000000000.0 Saturn.year = 10759.0 * 24.0 * 3600.0 Saturn.eccentricity = 0.0565 Saturn.day = 10.656 * 3600.0 Saturn.obliquity = 26.73 Saturn.Lequinox = None Saturn.Tsbar = 134.0 Saturn.Tsmax = None uranus = planet() Uranus.name = 'Uranus' Uranus.a = 25362000.0 Uranus.g = 8.87 Uranus.albedo = 0.3 Uranus.L = 3.71 Uranus.rsm = 2872460000000.0 Uranus.year = 30685.4 * 24.0 * 3600.0 Uranus.eccentricity = 0.0457 Uranus.day = 17.24 * 3600.0 Uranus.obliquity = 97.77 Uranus.Lequinox = None Uranus.Tsbar = 76.0 Uranus.Tsmax = None neptune = planet() Neptune.name = 'Neptune' Neptune.a = 26624000.0 Neptune.g = 11.15 Neptune.albedo = 0.29 Neptune.L = 1.51 Neptune.rsm = 4495060000000.0 Neptune.year = 60189.0 * 24.0 * 3600.0 Neptune.eccentricity = 0.0113 Neptune.day = 16.11 * 3600.0 Neptune.obliquity = 28.32 Neptune.Lequinox = None Neptune.Tsbar = 72.0 Neptune.Tsmax = None pluto = planet() Pluto.name = 'Pluto' Pluto.a = 1195000.0 Pluto.g = 0.58 Pluto.albedo = 0.5 Pluto.L = 0.89 Pluto.rsm = 5906000000000.0 Pluto.year = 90465.0 * 24.0 * 3600.0 Pluto.eccentricity = 0.2488 Pluto.day = 153.282 * 3600.0 Pluto.obliquity = 122.53 Pluto.Lequinox = None Pluto.Tsbar = 50.0 Pluto.Tsmax = None moon = planet() Moon.name = 'Moon' Moon.a = 1737000.0 Moon.g = 1.62 Moon.albedo = 0.11 Moon.L = 1367.6 Moon.rsm = Earth.rsm Moon.year = Earth.year Moon.eccentricity = None Moon.day = 28.0 * 24.0 * 3600.0 Moon.obliquity = None Moon.Lequinox = None Moon.Tsbar = None Moon.Tsmax = 400.0 Moon.Tsmin = 100.0 titan = planet() Titan.name = 'Titan' Titan.a = 2575000.0 Titan.g = 1.35 Titan.L = Saturn.L Titan.albedo = 0.21 Titan.rsm = None Titan.year = Saturn.year Titan.eccentricity = Saturn.eccentricity Titan.day = 15.9452 * 24.0 * 3600.0 Titan.obliquity = Saturn.obliquity Titan.Lequinox = Saturn.Lequinox Titan.Tsbar = 95.0 Titan.Tsmax = None europa = planet() Europa.name = 'Europa' Europa.a = 1560000.0 Europa.g = 1.31 Europa.L = Jupiter.L Europa.albedo = 0.67 Europa.rsm = Jupiter.rsm Europa.year = Jupiter.year Europa.eccentricity = Jupiter.eccentricity Europa.day = 3.551 * 24.0 * 3600.0 Europa.obliquity = Jupiter.obliquity Europa.Lequinox = None Europa.Tsbar = 103.0 Europa.Tsmax = 125.0 triton = planet() Triton.name = 'Triton' Triton.a = 2706800.0 / 2.0 Triton.g = 0.78 Triton.L = Neptune.L Triton.albedo = 0.76 Triton.rsm = Neptune.rsm Triton.year = Neptune.year Triton.eccentricity = Neptune.eccentricity Triton.day = 5.877 * 24.0 * 3600.0 Triton.obliquity = 156.0 Triton.Lequinox = None Triton.Tsbar = 34.5 Triton.Tsmax = None
palavras = {} arquivo = open('words.txt', 'r') for p in arquivo.readlines(): palavra = p.split(' ') for l in palavra: try: palavras[l] += 1 except: palavras[l] = 1 arquivo.close() print(palavras)
palavras = {} arquivo = open('words.txt', 'r') for p in arquivo.readlines(): palavra = p.split(' ') for l in palavra: try: palavras[l] += 1 except: palavras[l] = 1 arquivo.close() print(palavras)
def getKey(dictionary, svalue): for key, value in dictionary.items(): if value == svalue: return key # def hasKey(dictionary, key): # if key in dictionary: # return True # return False
def get_key(dictionary, svalue): for (key, value) in dictionary.items(): if value == svalue: return key
# https://www.codewars.com/kata/529872bdd0f550a06b00026e/ ''' Instructions : Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: greatestProduct("123834539327238239583") // should return 3240 The input string always has more than five digits. Adapted from Project Euler. ''' def product(n): p = 1 for i in n: p *= int(i) return p def greatest_product(n): res = [] mul = 1 digit = 5 while len(n)>= digit: res.append(product(n[:digit])) n = n[1:] print(res) print(n) return(max(res))
""" Instructions : Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: greatestProduct("123834539327238239583") // should return 3240 The input string always has more than five digits. Adapted from Project Euler. """ def product(n): p = 1 for i in n: p *= int(i) return p def greatest_product(n): res = [] mul = 1 digit = 5 while len(n) >= digit: res.append(product(n[:digit])) n = n[1:] print(res) print(n) return max(res)
@auth.route('/login', methods=['GET', 'POST']) # define login page path def login(): # define login page fucntion if request.method=='GET': # if the request is a GET we return the login page return render_template('login.html') else: # if the request is POST the we check if the user exist # and with te right password email = request.form.get('email') password = request.form.get('password') remember = True if request.form.get('remember') else False user = User.query.filter_by(email=email).first() # check if the user actually exists # take the user-supplied password, hash it, and compare it # to the hashed password in the database if not user: flash('Please sign up before!') return redirect(url_for('auth.signup')) elif not check_password_hash(user.password, password): flash('Please check your login details and try again.') return redirect(url_for('auth.login')) # if the user #doesn't exist or password is wrong, reload the page # if the above check passes, then we know the user has the # right credentials login_user(user, remember=remember) return redirect(url_for('main.profile'))
@auth.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: email = request.form.get('email') password = request.form.get('password') remember = True if request.form.get('remember') else False user = User.query.filter_by(email=email).first() if not user: flash('Please sign up before!') return redirect(url_for('auth.signup')) elif not check_password_hash(user.password, password): flash('Please check your login details and try again.') return redirect(url_for('auth.login')) login_user(user, remember=remember) return redirect(url_for('main.profile'))
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_norm_stats": "00_utils.ipynb", "draw_rect": "00_utils.ipynb", "convert_cords": "00_utils.ipynb", "resize": "00_utils.ipynb", "noise": "00_utils.ipynb", "get_prompt_points": "00_utils.ipynb", "yolo_to_coco": "00_utils.ipynb", "PTBDataset": "01_data.ipynb", "PTBTransform": "01_data.ipynb", "PTBImage": "01_data.ipynb", "ConversionDataset": "01_data.ipynb", "EfficientLoc": "02_model.ipynb", "CIoU": "02_model.ipynb"} modules = ["utils.py", "data.py", "model.py", "fastai.py", "None.py"] doc_url = "https://BavarianToolbox.github.io/point_to_box/" git_url = "https://github.com/BavarianToolbox/point_to_box/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'get_norm_stats': '00_utils.ipynb', 'draw_rect': '00_utils.ipynb', 'convert_cords': '00_utils.ipynb', 'resize': '00_utils.ipynb', 'noise': '00_utils.ipynb', 'get_prompt_points': '00_utils.ipynb', 'yolo_to_coco': '00_utils.ipynb', 'PTBDataset': '01_data.ipynb', 'PTBTransform': '01_data.ipynb', 'PTBImage': '01_data.ipynb', 'ConversionDataset': '01_data.ipynb', 'EfficientLoc': '02_model.ipynb', 'CIoU': '02_model.ipynb'} modules = ['utils.py', 'data.py', 'model.py', 'fastai.py', 'None.py'] doc_url = 'https://BavarianToolbox.github.io/point_to_box/' git_url = 'https://github.com/BavarianToolbox/point_to_box/tree/master/' def custom_doc_links(name): return None
class OutcomeInfo: '''Details for individual outcomes of a Market.''' def __init__(self, id, volume, price, description): self._id = id self._volume = volume self._price = price self._description = description @property def id(self): '''Market Outcome ID Returns int ''' return self._id @property def volume(self): '''Trading volume for this Outcome. Returns decimal.Decimal ''' return self._volume @property def price(self): '''Last price at which the outcome was traded. If no trades have taken place in the Market, this value is set to the Market midpoint. If there is no volume on this Outcome, but there is volume on another Outcome in the Market, price is set to 0 for Yes/No Markets and Categorical Markets. Returns decimal.Decimal ''' return self._price @property def description(self): '''Description for the Outcome. Returns str ''' return self._description
class Outcomeinfo: """Details for individual outcomes of a Market.""" def __init__(self, id, volume, price, description): self._id = id self._volume = volume self._price = price self._description = description @property def id(self): """Market Outcome ID Returns int """ return self._id @property def volume(self): """Trading volume for this Outcome. Returns decimal.Decimal """ return self._volume @property def price(self): """Last price at which the outcome was traded. If no trades have taken place in the Market, this value is set to the Market midpoint. If there is no volume on this Outcome, but there is volume on another Outcome in the Market, price is set to 0 for Yes/No Markets and Categorical Markets. Returns decimal.Decimal """ return self._price @property def description(self): """Description for the Outcome. Returns str """ return self._description
''' @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 ''' LETTERS = '_YZWVUTS' def index_category(category, nargs, result_index=0, arg_index=1, self_index=0): attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else '') if category.result is None: result_str = '' else: if category.result.equals(category.arg, ignore_attr=True): if len(category.arg.attr) == 0 or (category.arg.attr == category.result.attr): result_index = arg_index result_str, result_index, arg_index, self_index = index_category(category.result, nargs-1, result_index, arg_index, result_index) # if category.result.has_children(): # result_str = f'({result_str})' if category.arg is None: arg_str = '' else: arg_str, result_index, arg_index, self_index = index_category(category.arg, -1, arg_index, arg_index+1, arg_index) # if category.arg.has_children(): # arg_str = f'({arg_str})' if not category.has_children(): cat_str = f'{category.root}{attr_str}{{{LETTERS[self_index]}}}' elif nargs < 0: cat_str = f'({result_str}{category.root}{arg_str}){attr_str}{{{LETTERS[self_index]}}}' else: cat_str = f'({result_str}{category.root}{arg_str}<{nargs}>){attr_str}{{{LETTERS[self_index]}}}' return cat_str, result_index, arg_index, self_index def make_rule(category): result = str(category) nargs = category.nargs() indexed, _, _, _ = index_category(category, nargs) result += f'\n {nargs} {indexed}' cat = category for n in range(nargs): result += f'\n {n+1} ignore' cat = cat.result return result
""" @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 """ letters = '_YZWVUTS' def index_category(category, nargs, result_index=0, arg_index=1, self_index=0): attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else '') if category.result is None: result_str = '' else: if category.result.equals(category.arg, ignore_attr=True): if len(category.arg.attr) == 0 or category.arg.attr == category.result.attr: result_index = arg_index (result_str, result_index, arg_index, self_index) = index_category(category.result, nargs - 1, result_index, arg_index, result_index) if category.arg is None: arg_str = '' else: (arg_str, result_index, arg_index, self_index) = index_category(category.arg, -1, arg_index, arg_index + 1, arg_index) if not category.has_children(): cat_str = f'{category.root}{attr_str}{{{LETTERS[self_index]}}}' elif nargs < 0: cat_str = f'({result_str}{category.root}{arg_str}){attr_str}{{{LETTERS[self_index]}}}' else: cat_str = f'({result_str}{category.root}{arg_str}<{nargs}>){attr_str}{{{LETTERS[self_index]}}}' return (cat_str, result_index, arg_index, self_index) def make_rule(category): result = str(category) nargs = category.nargs() (indexed, _, _, _) = index_category(category, nargs) result += f'\n {nargs} {indexed}' cat = category for n in range(nargs): result += f'\n {n + 1} ignore' cat = cat.result return result
def cpu_bound(n): return sum(i * i for i in range(n)) if __name__ == "__main__": n = int(input()) res = cpu_bound(n) print(res)
def cpu_bound(n): return sum((i * i for i in range(n))) if __name__ == '__main__': n = int(input()) res = cpu_bound(n) print(res)
# Implement a queue using two stacks. Recall that a queue is a FIFO # (first-in, first-out) data structure with the following methods: enqueue, # which inserts an element into the queue, and dequeue, which removes it. class Queue: def __init__(self): self.ins = [] self.out = [] def enqueue(self, value): self.ins.append(value) def dequeue(self): if not self.out: while self.ins: self.out.append(self.ins.pop()) return self.out.pop() if __name__ == '__main__': q = Queue() for i in range(5): q.enqueue(i) for _ in range(3): print(q.dequeue()) for i in range(5, 10): q.enqueue(i) for _ in range(7): print(q.dequeue())
class Queue: def __init__(self): self.ins = [] self.out = [] def enqueue(self, value): self.ins.append(value) def dequeue(self): if not self.out: while self.ins: self.out.append(self.ins.pop()) return self.out.pop() if __name__ == '__main__': q = queue() for i in range(5): q.enqueue(i) for _ in range(3): print(q.dequeue()) for i in range(5, 10): q.enqueue(i) for _ in range(7): print(q.dequeue())
MOCK_DATA = [ { "symbol": "sy1", "companyName": "cn1", "exchange": "ex1", "industry": "in1", "website": "ws1", "description": "dc1", "CEO": "ceo1", "issueType": "is1", "sector": "sc1", }, { "symbol": "sy2", "companyName": "cn2", "exchange": "ex2", "industry": "in2", "website": "ws2", "description": "dc2", "CEO": "ceo2", "issueType": "is2", "sector": "sc2", }, { "symbol": "sy3", "companyName": "cn3", "exchange": "ex3", "industry": "in3", "website": "ws3", "description": "dc3", "CEO": "ceo3", "issueType": "is3", "sector": "sc3", }, { "symbol": "sy4", "companyName": "cn4", "exchange": "ex4", "industry": "in4", "website": "ws4", "description": "dc4", "CEO": "ceo4", "issueType": "is4", "sector": "sc4", }, { "symbol": "sy5", "companyName": "cn5", "exchange": "ex5", "industry": "in5", "website": "ws5", "description": "dc5", "CEO": "ceo5", "issueType": "is5", "sector": "sc5", }, { "symbol": "sy6", "companyName": "cn6", "exchange": "ex6", "industry": "in6", "website": "ws6", "description": "dc6", "CEO": "ceo6", "issueType": "is6", "sector": "sc6", }, { "symbol": "sy7", "companyName": "cn7", "exchange": "ex7", "industry": "in7", "website": "ws7", "description": "dc7", "CEO": "ceo7", "issueType": "is7", "sector": "sc7", }, { "symbol": "sy8", "companyName": "cn8", "exchange": "ex8", "industry": "in8", "website": "ws8", "description": "dc8", "CEO": "ceo8", "issueType": "is8", "sector": "sc8", }, { "symbol": "sy9", "companyName": "cn9", "exchange": "ex9", "industry": "in9", "website": "ws9", "description": "dc9", "CEO": "ceo9", "issueType": "is9", "sector": "sc9", }, { "symbol": "sy", "companyName": "cn", "exchange": "ex", "industry": "in", "website": "ws", "description": "dc", "CEO": "ceo", "issueType": "is", "sector": "sc", } ]
mock_data = [{'symbol': 'sy1', 'companyName': 'cn1', 'exchange': 'ex1', 'industry': 'in1', 'website': 'ws1', 'description': 'dc1', 'CEO': 'ceo1', 'issueType': 'is1', 'sector': 'sc1'}, {'symbol': 'sy2', 'companyName': 'cn2', 'exchange': 'ex2', 'industry': 'in2', 'website': 'ws2', 'description': 'dc2', 'CEO': 'ceo2', 'issueType': 'is2', 'sector': 'sc2'}, {'symbol': 'sy3', 'companyName': 'cn3', 'exchange': 'ex3', 'industry': 'in3', 'website': 'ws3', 'description': 'dc3', 'CEO': 'ceo3', 'issueType': 'is3', 'sector': 'sc3'}, {'symbol': 'sy4', 'companyName': 'cn4', 'exchange': 'ex4', 'industry': 'in4', 'website': 'ws4', 'description': 'dc4', 'CEO': 'ceo4', 'issueType': 'is4', 'sector': 'sc4'}, {'symbol': 'sy5', 'companyName': 'cn5', 'exchange': 'ex5', 'industry': 'in5', 'website': 'ws5', 'description': 'dc5', 'CEO': 'ceo5', 'issueType': 'is5', 'sector': 'sc5'}, {'symbol': 'sy6', 'companyName': 'cn6', 'exchange': 'ex6', 'industry': 'in6', 'website': 'ws6', 'description': 'dc6', 'CEO': 'ceo6', 'issueType': 'is6', 'sector': 'sc6'}, {'symbol': 'sy7', 'companyName': 'cn7', 'exchange': 'ex7', 'industry': 'in7', 'website': 'ws7', 'description': 'dc7', 'CEO': 'ceo7', 'issueType': 'is7', 'sector': 'sc7'}, {'symbol': 'sy8', 'companyName': 'cn8', 'exchange': 'ex8', 'industry': 'in8', 'website': 'ws8', 'description': 'dc8', 'CEO': 'ceo8', 'issueType': 'is8', 'sector': 'sc8'}, {'symbol': 'sy9', 'companyName': 'cn9', 'exchange': 'ex9', 'industry': 'in9', 'website': 'ws9', 'description': 'dc9', 'CEO': 'ceo9', 'issueType': 'is9', 'sector': 'sc9'}, {'symbol': 'sy', 'companyName': 'cn', 'exchange': 'ex', 'industry': 'in', 'website': 'ws', 'description': 'dc', 'CEO': 'ceo', 'issueType': 'is', 'sector': 'sc'}]
# Only used for PyTorch open source BUCK build # @lint-ignore-every BUCKRESTRICTEDSYNTAX def is_arvr_mode(): if read_config("pt", "is_oss", "0") == "0": fail("This file is for open source pytorch build. Do not use it in fbsource!") return False
def is_arvr_mode(): if read_config('pt', 'is_oss', '0') == '0': fail('This file is for open source pytorch build. Do not use it in fbsource!') return False
# Diffusion 2D nx = 20 # number of elements ny = nx # number of nodes mx = nx + 1 my = ny + 1 # initial values iv = {} for j in range(int(0.2*my), int(0.3*my)): for i in range(int(0.5*mx), int(0.8*mx)): index = j*mx + i iv[index] = 1.0 print("iv: ",iv) config = { "solverStructureDiagramFile": "solver_structure.txt", # output file of a diagram that shows data connection between solvers "logFormat": "csv", # "csv" or "json", format of the lines in the log file, csv gives smaller files "scenarioName": "diffusion", # scenario name to find the run in the log file "mappingsBetweenMeshesLogFile": "", # a log file about mappings between meshes, here we do not want that because there are no mappings "Heun" : { "initialValues": iv, "timeStepWidth": 1e-3, "endTime": 1.0, "timeStepOutputInterval": 100, "checkForNanInf": False, "inputMeshIsGlobal": True, "nAdditionalFieldVariables": 0, "additionalSlotNames": [], "dirichletBoundaryConditions": {}, "dirichletOutputFilename": None, # filename for a vtp file that contains the Dirichlet boundary condition nodes and their values, set to None to disable "FiniteElementMethod" : { "nElements": [nx, ny], "physicalExtent": [4.0,4.0], "inputMeshIsGlobal": True, "prefactor": 0.1, # solver parameters "solverType": "gmres", "preconditionerType": "none", "relativeTolerance": 1e-15, # relative tolerance of the residual normal, respective to the initial residual norm, linear solver "absoluteTolerance": 1e-10, # 1e-10 absolute tolerance of the residual "maxIterations": 10000, "dumpFilename": "", "dumpFormat": "ascii", # ascii, default or matlab "slotName": "", }, "OutputWriter" : [ {"format": "Paraview", "outputInterval": 10, "filename": "out/filename", "binary": "false", "fixedFormat": False, "onlyNodalValues": True, "combineFiles": True, "fileNumbering": "incremental"}, {"format": "PythonFile", "outputInterval": 10, "filename": "out/out_diffusion2d", "binary": True, "onlyNodalValues": True, "combineFiles": True, "fileNumbering": "incremental"} ] }, }
nx = 20 ny = nx mx = nx + 1 my = ny + 1 iv = {} for j in range(int(0.2 * my), int(0.3 * my)): for i in range(int(0.5 * mx), int(0.8 * mx)): index = j * mx + i iv[index] = 1.0 print('iv: ', iv) config = {'solverStructureDiagramFile': 'solver_structure.txt', 'logFormat': 'csv', 'scenarioName': 'diffusion', 'mappingsBetweenMeshesLogFile': '', 'Heun': {'initialValues': iv, 'timeStepWidth': 0.001, 'endTime': 1.0, 'timeStepOutputInterval': 100, 'checkForNanInf': False, 'inputMeshIsGlobal': True, 'nAdditionalFieldVariables': 0, 'additionalSlotNames': [], 'dirichletBoundaryConditions': {}, 'dirichletOutputFilename': None, 'FiniteElementMethod': {'nElements': [nx, ny], 'physicalExtent': [4.0, 4.0], 'inputMeshIsGlobal': True, 'prefactor': 0.1, 'solverType': 'gmres', 'preconditionerType': 'none', 'relativeTolerance': 1e-15, 'absoluteTolerance': 1e-10, 'maxIterations': 10000, 'dumpFilename': '', 'dumpFormat': 'ascii', 'slotName': ''}, 'OutputWriter': [{'format': 'Paraview', 'outputInterval': 10, 'filename': 'out/filename', 'binary': 'false', 'fixedFormat': False, 'onlyNodalValues': True, 'combineFiles': True, 'fileNumbering': 'incremental'}, {'format': 'PythonFile', 'outputInterval': 10, 'filename': 'out/out_diffusion2d', 'binary': True, 'onlyNodalValues': True, 'combineFiles': True, 'fileNumbering': 'incremental'}]}}
__title__ = 'lightwood' __package_name__ = 'mindsdb' __version__ = '0.14.1' __description__ = "Lightwood's goal is to make it very simple for developers to use the power of artificial neural networks in their projects." __email__ = "jorge@mindsdb.com" __author__ = 'MindsDB Inc' __github__ = 'https://github.com/mindsdb/lightwood' __pypi__ = 'https://pypi.org/project/lightwood' __license__ = 'MIT' __copyright__ = 'Copyright 2019- mindsdb'
__title__ = 'lightwood' __package_name__ = 'mindsdb' __version__ = '0.14.1' __description__ = "Lightwood's goal is to make it very simple for developers to use the power of artificial neural networks in their projects." __email__ = 'jorge@mindsdb.com' __author__ = 'MindsDB Inc' __github__ = 'https://github.com/mindsdb/lightwood' __pypi__ = 'https://pypi.org/project/lightwood' __license__ = 'MIT' __copyright__ = 'Copyright 2019- mindsdb'
# Problem: input: an unsorted array A[lo..hi]; | output: the (left) median of the given array # Source: SCU COEN279 DAA HW3 Q3 # Author: Shreyas Padhye # Algorithm: Decrease-Conquer class solution(): def left_median(self, A): if len(A) == 1 or len(A) == 2: return A[0] else: median = self.left_median(A[:-1]) if len(A[:-1]) % 2 == 0: if median > A[-1]: return median else: med_neighbour = A.index(median) + 1 if A[-1] < A[med_neighbour]: temp = A[-1] A[-1] = A[med_neighbour] A[med_neighbour] = temp return A[med_neighbour] elif median < A[-1]: return median else: med_neighbour = A.index(median) - 1 if A[-1] > A[med_neighbour]: temp = A[-1] A[-1] = A[med_neighbour] A[med_neighbour] = temp return A[med_neighbour] t = solution() # t.left_median([0, 1, 3, 5]) #1 # t.left_median([0, 1, 3, 5, 2]) #2 # t.left_median([0, 1, 3, 5]) #1 t.left_median([0, 1, 3, 5]) #1 t.left_median([5, 1, 3, 8, 2]) #5 t.left_median([7, 0, 1, 12, 1, 45, 2]) #7 t.left_median([7, 0, 1, 12, 45, 2, 11, 8, 101, 14]) #correct: 8, mine: 12 # t.left_median([7, 0, 1, 12, 1, 45, 2, 11, 8, 101, 14]) #correct: 8, mine: 1
class Solution: def left_median(self, A): if len(A) == 1 or len(A) == 2: return A[0] else: median = self.left_median(A[:-1]) if len(A[:-1]) % 2 == 0: if median > A[-1]: return median else: med_neighbour = A.index(median) + 1 if A[-1] < A[med_neighbour]: temp = A[-1] A[-1] = A[med_neighbour] A[med_neighbour] = temp return A[med_neighbour] elif median < A[-1]: return median else: med_neighbour = A.index(median) - 1 if A[-1] > A[med_neighbour]: temp = A[-1] A[-1] = A[med_neighbour] A[med_neighbour] = temp return A[med_neighbour] t = solution() t.left_median([0, 1, 3, 5]) t.left_median([5, 1, 3, 8, 2]) t.left_median([7, 0, 1, 12, 1, 45, 2]) t.left_median([7, 0, 1, 12, 45, 2, 11, 8, 101, 14])
def get_belief(sent): if '<|belief|>' in sent: tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|action|>')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofbelief|>', '') tmp = tmp.replace('<|endoftext|>', '') belief = tmp.split(',') new_belief = [] for bs in belief: bs = bs.strip(' .,') if bs not in new_belief: new_belief.append(bs) return new_belief def get_belief_dbsearch(sent): if '<|belief|>' in sent: tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|endofbelief|>')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofbelief|>', '') tmp = tmp.replace('<|endoftext|>', '') belief = tmp.split(',') new_belief = [] for bs in belief: bs = bs.strip(' .,') if bs not in new_belief: new_belief.append(bs) return new_belief def get_belief_openaigpt(sent): if '< | belief | >' in sent: tmp = sent.strip(' ').split('< | belief | >')[-1].split('< | action | >')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('< | endofbelief | >', '') tmp = tmp.replace('< | endoftext | >', '') belief = tmp.split(',') new_belief = [] for bs in belief: bs = bs.strip(' .,') if bs not in new_belief: new_belief.append(bs) return new_belief def get_response(sent, tokenizer): if '<|response|>' in sent: tmp = sent.split('<|belief|>')[-1].split('<|action|>')[-1].split('<|response|>')[-1] else: return '' tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofresponse|>', '') tmp = tmp.replace('<|endoftext|>', '') tokens = tokenizer.encode(tmp) new_tokens = [] for tok in tokens: if tok in tokenizer.encode(tokenizer._eos_token): continue new_tokens.append(tok) response = tokenizer.decode(new_tokens).strip(' ,.') return response def get_response_openaigpt(sent, tokenizer): if '< | response | >' in sent: tmp = sent.split('< | belief | >')[-1].split('< | action | >')[-1].split('< | response | >')[-1] else: return '' tmp = tmp.strip(' .,') tmp = tmp.replace('< | endofresponse | >', '') tmp = tmp.replace('< | endoftext | >', '') tokens = tokenizer.encode(tmp) new_tokens = [] for tok in tokens: if tok in tokenizer.encode(tokenizer._eos_token): continue new_tokens.append(tok) response = tokenizer.decode(new_tokens).strip(' ,.') response = response.replace('[ ', '[') response = response.replace(' ]', ']') response = response.replace(' _ ', '_') response = response.replace('i d', 'id') return response def get_action(sent): if '<|action|>' not in sent: return [] elif '<|belief|>' in sent: tmp = sent.split('<|belief|>')[-1].split('<|response|>')[0].split('<|action|>')[-1].strip() elif '<|action|>' in sent: tmp = sent.split('<|response|>')[0].split('<|action|>')[-1].strip() else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofaction|>', '') tmp = tmp.replace('<|endoftext|>', '') action = tmp.split(',') new_action = [] for act in action: if act == '': continue act = act.strip(' .,') if act not in new_action: new_action.append(act) return new_action def get_action_openaigpt(sent): if '< | belief | >' in sent: tmp = sent.split('< | belief | >')[-1].split('< | response | >')[0].split('< | action | >')[-1].strip() elif '< | action | >' in sent: tmp = sent.split('< | response | >')[0].split('< | action | >')[-1].strip() else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('< | endofaction | >', '') tmp = tmp.replace('< | endoftext | >', '') action = tmp.split(',') new_action = [] for act in action: if act == '': continue act = act.strip(' .,') if act not in new_action: act = act.replace('i d', 'id') new_action.append(act) return new_action def get_db_dynamically(predicted_text, goal, multiwoz_db): gen_belief = get_belief_dbsearch(predicted_text) belief_domain = {} belief_book_domain = {} for bs in gen_belief: if bs in ['', ' ']: continue bs_domain = bs.split()[0] if 'book' in bs: bs_slot = bs.split()[2] bs_val = ' '.join(bs.split()[3:]) if bs_domain not in belief_book_domain: belief_book_domain[bs_domain] = {} belief_book_domain[bs_domain][bs_slot] = bs_val else: bs_slot = bs.split()[1] bs_val = ' '.join(bs.split()[2:]) if bs_domain not in belief_domain: belief_domain[bs_domain] = {} belief_book_domain[bs_domain] = {} belief_domain[bs_domain][bs_slot] = bs_val db_text_tmp = [] for dom in belief_domain: if dom not in ['restaurant', 'hotel', 'attraction', 'train']: continue domain_match = len(multiwoz_db.queryResultVenues(dom, belief_domain[dom], real_belief=True)) if dom != 'train': if domain_match >= 5: domain_match_text = '>=5' else: domain_match_text = '={}'.format(domain_match) elif dom == 'train': if domain_match == 0: domain_match_text = '=0' elif domain_match == 2: domain_match_text = '<3' elif domain_match == 5: domain_match_text = '<6' elif domain_match == 10: domain_match_text = '<11' elif domain_match == 40: domain_match_text = '<41' else: domain_match_text = '>40' if 'fail_book' in goal[dom]: for item in goal[dom]['fail_book'].items(): if item in belief_book_domain[dom].items(): domain_book_text = 'not available' break else: domain_book_text = 'available' else: if domain_match == 0: domain_book_text = 'not available' else: domain_book_text = 'available' db_text_tmp.append('{} match{} booking={}'.format(dom, domain_match_text, domain_book_text)) db_text = ' <|dbsearch|> {} <|endofdbsearch|>'.format(' , '.join(db_text_tmp)) return db_text
def get_belief(sent): if '<|belief|>' in sent: tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|action|>')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofbelief|>', '') tmp = tmp.replace('<|endoftext|>', '') belief = tmp.split(',') new_belief = [] for bs in belief: bs = bs.strip(' .,') if bs not in new_belief: new_belief.append(bs) return new_belief def get_belief_dbsearch(sent): if '<|belief|>' in sent: tmp = sent.strip(' ').split('<|belief|>')[-1].split('<|endofbelief|>')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofbelief|>', '') tmp = tmp.replace('<|endoftext|>', '') belief = tmp.split(',') new_belief = [] for bs in belief: bs = bs.strip(' .,') if bs not in new_belief: new_belief.append(bs) return new_belief def get_belief_openaigpt(sent): if '< | belief | >' in sent: tmp = sent.strip(' ').split('< | belief | >')[-1].split('< | action | >')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('< | endofbelief | >', '') tmp = tmp.replace('< | endoftext | >', '') belief = tmp.split(',') new_belief = [] for bs in belief: bs = bs.strip(' .,') if bs not in new_belief: new_belief.append(bs) return new_belief def get_response(sent, tokenizer): if '<|response|>' in sent: tmp = sent.split('<|belief|>')[-1].split('<|action|>')[-1].split('<|response|>')[-1] else: return '' tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofresponse|>', '') tmp = tmp.replace('<|endoftext|>', '') tokens = tokenizer.encode(tmp) new_tokens = [] for tok in tokens: if tok in tokenizer.encode(tokenizer._eos_token): continue new_tokens.append(tok) response = tokenizer.decode(new_tokens).strip(' ,.') return response def get_response_openaigpt(sent, tokenizer): if '< | response | >' in sent: tmp = sent.split('< | belief | >')[-1].split('< | action | >')[-1].split('< | response | >')[-1] else: return '' tmp = tmp.strip(' .,') tmp = tmp.replace('< | endofresponse | >', '') tmp = tmp.replace('< | endoftext | >', '') tokens = tokenizer.encode(tmp) new_tokens = [] for tok in tokens: if tok in tokenizer.encode(tokenizer._eos_token): continue new_tokens.append(tok) response = tokenizer.decode(new_tokens).strip(' ,.') response = response.replace('[ ', '[') response = response.replace(' ]', ']') response = response.replace(' _ ', '_') response = response.replace('i d', 'id') return response def get_action(sent): if '<|action|>' not in sent: return [] elif '<|belief|>' in sent: tmp = sent.split('<|belief|>')[-1].split('<|response|>')[0].split('<|action|>')[-1].strip() elif '<|action|>' in sent: tmp = sent.split('<|response|>')[0].split('<|action|>')[-1].strip() else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('<|endofaction|>', '') tmp = tmp.replace('<|endoftext|>', '') action = tmp.split(',') new_action = [] for act in action: if act == '': continue act = act.strip(' .,') if act not in new_action: new_action.append(act) return new_action def get_action_openaigpt(sent): if '< | belief | >' in sent: tmp = sent.split('< | belief | >')[-1].split('< | response | >')[0].split('< | action | >')[-1].strip() elif '< | action | >' in sent: tmp = sent.split('< | response | >')[0].split('< | action | >')[-1].strip() else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('< | endofaction | >', '') tmp = tmp.replace('< | endoftext | >', '') action = tmp.split(',') new_action = [] for act in action: if act == '': continue act = act.strip(' .,') if act not in new_action: act = act.replace('i d', 'id') new_action.append(act) return new_action def get_db_dynamically(predicted_text, goal, multiwoz_db): gen_belief = get_belief_dbsearch(predicted_text) belief_domain = {} belief_book_domain = {} for bs in gen_belief: if bs in ['', ' ']: continue bs_domain = bs.split()[0] if 'book' in bs: bs_slot = bs.split()[2] bs_val = ' '.join(bs.split()[3:]) if bs_domain not in belief_book_domain: belief_book_domain[bs_domain] = {} belief_book_domain[bs_domain][bs_slot] = bs_val else: bs_slot = bs.split()[1] bs_val = ' '.join(bs.split()[2:]) if bs_domain not in belief_domain: belief_domain[bs_domain] = {} belief_book_domain[bs_domain] = {} belief_domain[bs_domain][bs_slot] = bs_val db_text_tmp = [] for dom in belief_domain: if dom not in ['restaurant', 'hotel', 'attraction', 'train']: continue domain_match = len(multiwoz_db.queryResultVenues(dom, belief_domain[dom], real_belief=True)) if dom != 'train': if domain_match >= 5: domain_match_text = '>=5' else: domain_match_text = '={}'.format(domain_match) elif dom == 'train': if domain_match == 0: domain_match_text = '=0' elif domain_match == 2: domain_match_text = '<3' elif domain_match == 5: domain_match_text = '<6' elif domain_match == 10: domain_match_text = '<11' elif domain_match == 40: domain_match_text = '<41' else: domain_match_text = '>40' if 'fail_book' in goal[dom]: for item in goal[dom]['fail_book'].items(): if item in belief_book_domain[dom].items(): domain_book_text = 'not available' break else: domain_book_text = 'available' elif domain_match == 0: domain_book_text = 'not available' else: domain_book_text = 'available' db_text_tmp.append('{} match{} booking={}'.format(dom, domain_match_text, domain_book_text)) db_text = ' <|dbsearch|> {} <|endofdbsearch|>'.format(' , '.join(db_text_tmp)) return db_text
''' Created on 2016-01-13 @author: Wu Wenxiang (wuwenxiang.sh@gmail.com) ''' DEBUG = False
""" Created on 2016-01-13 @author: Wu Wenxiang (wuwenxiang.sh@gmail.com) """ debug = False
description = 'Helmholtz field coil' group = 'optional' includes = ['alias_B'] tango_base = 'tango://phys.kws1.frm2:10000/kws1/' devices = dict( I_helmholtz = device('nicos.devices.entangle.PowerSupply', description = 'Current in coils', tangodevice = tango_base + 'gesupply/ps2', unit = 'A', fmtstr = '%.2f', ), B_helmholtz = device('nicos.devices.generic.CalibratedMagnet', currentsource = 'I_helmholtz', description = 'Magnet field', unit = 'T', fmtstr = '%.5f', calibration = ( 0.0032507550, # slope 0.003255221(old) 0, 0, 0, 0 ) ), ) alias_config = { 'B': {'B_helmholtz': 100}, } extended = dict( representative = 'B_helmholtz', )
description = 'Helmholtz field coil' group = 'optional' includes = ['alias_B'] tango_base = 'tango://phys.kws1.frm2:10000/kws1/' devices = dict(I_helmholtz=device('nicos.devices.entangle.PowerSupply', description='Current in coils', tangodevice=tango_base + 'gesupply/ps2', unit='A', fmtstr='%.2f'), B_helmholtz=device('nicos.devices.generic.CalibratedMagnet', currentsource='I_helmholtz', description='Magnet field', unit='T', fmtstr='%.5f', calibration=(0.003250755, 0, 0, 0, 0))) alias_config = {'B': {'B_helmholtz': 100}} extended = dict(representative='B_helmholtz')
# Test checked class SymbolTable(object): def __init__(self): self._symbols = \ { \ 'SP':0, 'LCL':1, 'ARG':2, 'THIS':3, 'THAT':4, \ 'R0':0, 'R1':1, 'R2':2, 'R3':3, 'R4':4, 'R5':5, 'R6':6, 'R7':7, \ 'R8':8, 'R9':9, 'R10':10, 'R11':11, 'R12':12, 'R13':13, 'R14':14, \ 'R15':15, 'SCREEN':0x4000, 'KBD':0x6000 \ } def add_entry(self, symbol, address): self._symbols[symbol] = address def contains(self, symbol): return symbol in self._symbols def get_address(self, symbol): return self._symbols[symbol]
class Symboltable(object): def __init__(self): self._symbols = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14, 'R15': 15, 'SCREEN': 16384, 'KBD': 24576} def add_entry(self, symbol, address): self._symbols[symbol] = address def contains(self, symbol): return symbol in self._symbols def get_address(self, symbol): return self._symbols[symbol]
# File: question3.py # Author: David Lechner # Date: 11/19/2019 '''Ask some questions about goats''' # REVIEW: We write `NUM_GOATS` in all caps because it is a constant. We set it # once at the begining of the program and don't change after that. NUM_GOATS = 10 # This is how many goats I have # REVIEW: The input() function gives us a string, but we need a number, so we # use int() to convert what the user types in to an integer. # TRY IT: What happens if the user types in a letter instead of a nubmer? What # about a number with a decimal point? answer = int(input('How many goats do you see?')) # LEARN: We can use inequality operators to compare numbers if answer < NUM_GOATS: print('Some of your goats are missing!') if answer == NUM_GOATS: print('All of the goats are there.') if answer > NUM_GOATS: print('You have extra goats!')
"""Ask some questions about goats""" num_goats = 10 answer = int(input('How many goats do you see?')) if answer < NUM_GOATS: print('Some of your goats are missing!') if answer == NUM_GOATS: print('All of the goats are there.') if answer > NUM_GOATS: print('You have extra goats!')
# lec6.4-removeDups.py # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python # Lecture 6, video 4 # Demonstrates performing operations on lists # Demonstrates how changing a list while iterating over it creates # unintended problems def removeDups(L1, L2): for e1 in L1: if e1 in L2: # Note: we are iterating over L1, but just removed one of # its elements L1.remove(e1) # L1 is now [2,3,4] so when it loops through again the next # element is 3. As a result the 2 is skipped and not removed # as intended L1 = [1,2,3,4] L2 = [1,2,5,6] removeDups(L1, L2) print(L1) # Better way to perform operations on list by creating a copy of L1 # then iterating over that as it will not change def removeDupsBetter(L1, L2): # Make a copy of L1 and put into L1Start L1Start = L1[:] for e1 in L1Start: if e1 in L2: L1.remove(e1) L1 = [1,2,3,4] L2 = [1,2,5,6] removeDupsBetter(L1, L2) print(L1)
def remove_dups(L1, L2): for e1 in L1: if e1 in L2: L1.remove(e1) l1 = [1, 2, 3, 4] l2 = [1, 2, 5, 6] remove_dups(L1, L2) print(L1) def remove_dups_better(L1, L2): l1_start = L1[:] for e1 in L1Start: if e1 in L2: L1.remove(e1) l1 = [1, 2, 3, 4] l2 = [1, 2, 5, 6] remove_dups_better(L1, L2) print(L1)
def compareTriplets(a, b): result = [] aliceScore =0 bobScore = 0 for Alice, Bob in zip(a, b): if Alice > Bob: aliceScore +=1 continue if Bob > Alice: bobScore +=1 continue if Alice == Bob: continue result.append(aliceScore) result.append(bobScore) return result if __name__ == '__main__': a = list(map(int, input('::: ').strip().split())) b = list(map(int, input('::: ').strip().split())) print(compareTriplets(a, b))
def compare_triplets(a, b): result = [] alice_score = 0 bob_score = 0 for (alice, bob) in zip(a, b): if Alice > Bob: alice_score += 1 continue if Bob > Alice: bob_score += 1 continue if Alice == Bob: continue result.append(aliceScore) result.append(bobScore) return result if __name__ == '__main__': a = list(map(int, input('::: ').strip().split())) b = list(map(int, input('::: ').strip().split())) print(compare_triplets(a, b))
#file extension '''n = input("enter file name with extension:") f_ext = n.split('.') x = f_ext[-1] print(x) #sum n = input("enter one number:") temp = n temp1 = temp+temp temp2 = temp+temp+temp val = int(n)+int(temp1)+int(temp2) print(val) #Multiline comment print("a string that you \"don\'t\" have to escape \n This \n is a ....... multi-line \n here doc string -------->") #4 n = int(input("enter num")) dif = n - 19 if(dif>0): print("value is ", 2 * dif) else: print(dif) #5 n = input("Enter string: ") if(n[0:2] == "Is"): print("String is ", n) else: n = "Is" + n print("String",n) #9 import math n = int(input("enter value:")) x= hex(n) print("hexa decimal value is", x) #10 import math n = int(input("enter value:")) x= bin(n) print("hexa decimal value is", x) #7 import math n = input("enter character:") x= ord(n) print("ASCII value is", x) #6 sec=int(input("enter the number of seconds:")) if(sec >= 86400): m = sec/60 h = m/60 d = h/24 print("Time in Minutes is ", m,"mins") print("Time in Hours is ", h,"hrs") print("Days is", d,"days") else: print("Seconds can\'t redable") #8 x = int(input("enter first num:")) y = int(input("enter second num:")) f1 = float(x) f2 = float(y) if(x>y): print("largest integer value",x) else: print("largest integer value",y) if(f1>f2): print("largest float value",f1) else: print("largest float value",f2)'''
"""n = input("enter file name with extension:") f_ext = n.split('.') x = f_ext[-1] print(x) #sum n = input("enter one number:") temp = n temp1 = temp+temp temp2 = temp+temp+temp val = int(n)+int(temp1)+int(temp2) print(val) #Multiline comment print("a string that you "don't" have to escape This is a ....... multi-line here doc string -------->") #4 n = int(input("enter num")) dif = n - 19 if(dif>0): print("value is ", 2 * dif) else: print(dif) #5 n = input("Enter string: ") if(n[0:2] == "Is"): print("String is ", n) else: n = "Is" + n print("String",n) #9 import math n = int(input("enter value:")) x= hex(n) print("hexa decimal value is", x) #10 import math n = int(input("enter value:")) x= bin(n) print("hexa decimal value is", x) #7 import math n = input("enter character:") x= ord(n) print("ASCII value is", x) #6 sec=int(input("enter the number of seconds:")) if(sec >= 86400): m = sec/60 h = m/60 d = h/24 print("Time in Minutes is ", m,"mins") print("Time in Hours is ", h,"hrs") print("Days is", d,"days") else: print("Seconds can't redable") #8 x = int(input("enter first num:")) y = int(input("enter second num:")) f1 = float(x) f2 = float(y) if(x>y): print("largest integer value",x) else: print("largest integer value",y) if(f1>f2): print("largest float value",f1) else: print("largest float value",f2)"""