content
stringlengths
7
1.05M
''' Merge sort of singly linked list Merge sort is often prefered for sorting a linked list. The slow random access performance of linked list make other algorithms such as quicksort perform poorly and others such as heapsort completely impossible. ''' #Code class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def Push(self,new_data): if(self.head==None): self.head = Node(new_data) else: new_node = Node(new_data) new_node.next = None temp = self.head while(temp.next): temp = temp.next temp.next = new_node def PrintList(self): # function for printing linked list. temp = self.head while(temp): print(temp.data,end=" ") temp = temp.next print('') def MergeSort(self,h): # main Merge Sort function if h is None or h.next is None : return h self.PrintList() middle = self.GetMiddle(h) nexttomiddle = middle.next middle.next = None left = self.MergeSort(h) right = self.MergeSort(nexttomiddle) sortedlist = self.SortedMerge(left,right) return sortedlist def GetMiddle(self,head): # function to get middle of linked list if (head == None): return head slow = fast = head while(fast.next != None and fast.next.next != None): slow = slow.next fast = fast.next.next return slow def SortedMerge(self,a,b): result = None if a == None: return b if b == None: return a if (a.data <= b.data): result = a result.next = self.SortedMerge(a.next,b) else: result = b result.next = self.SortedMerge(a,b.next) return result # Driver if(__name__=="__main__"): list1 = LinkedList() values = [8,2,3,1,7] # 8 2 3 1 7 for i in values: list1.Push(i) list1.PrintList() list1.head = list1.MergeSort(list1.head) list1.PrintList()
# regular if/else statement a = 10 if a > 5: print('a > 5') else: print('a <= 5') # if/elif/else a = 3 if a > 5: print('a > 5') elif a > 0: print('a > 0') else: print('a <= 0') # assignment with if/else - ternary statement b = 'a is positive' if a >= 0 else 'a is negative' print(b)
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def insertionSortList(self, head: ListNode) -> ListNode: node = head shead = None dummy = ListNode(0, head) while node: nodeNext = node.next if not shead: shead = node shead.next = None else: dummy = ListNode(0, shead) pnode = dummy snode = shead while snode: if node.val < snode.val: pnode.next = node node.next = snode break pnode = snode snode = snode.next if not snode and node.val >= pnode.val: pnode.next = node node.next = None shead = dummy.next node = nodeNext return dummy.next
#import wx Q3_IMPL_QT="ui.pyqt5" Q3_IMPL_WX="ui.wx" #Q3_IMPL="wx" #default impl #global Q3_IMPL Q3_IMPL=Q3_IMPL_QT Q3_IMPL_SIM='sim.default' #from wx import ID_EXIT #from wx import ID_ABOUT ID_EXIT = 1 ID_ABOUT = 2 MAX_PINS = 256 MAX_INPUTS = 256 MAX_OUTPUTS = 256 MAX_DYNAMICS = 256 MAX_SIGNAL_SIZE = 64
# lec11prob5.py # # Lecture 11 - Classes # Problem 5 # # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python ''' Consider the following code from the last lecture video. Your task is to define the following two methods for the intSet class: 1. Define an intersect method that returns a new intSet containing elements that appear in both sets. In other words, s1.intersect(s2) would return a new intSet of integers that appear in both s1 and s2. Think carefully - what should happen if s1 and s2 have no elements in common? 2. Add the appropriate method(s) so that len(s) returns the number of elements in s. Hint: look through the Python docs to figure out what you'll need to solve this problem. http://docs.python.org/release/2.7.3/reference/datamodel.html ''' class intSet(object): """An intSet is a set of integers The value is represented by a list of ints, self.vals. Each int in the set occurs in self.vals exactly once.""" def __init__(self): """Create an empty set of integers""" self.vals = [] def insert(self, e): """Assumes e is an integer and inserts e into self""" if not e in self.vals: self.vals.append(e) def member(self, e): """Assumes e is an integer Returns True if e is in self, and False otherwise""" return e in self.vals def remove(self, e): """Assumes e is an integer and removes e from self Raises ValueError if e is not in self""" try: self.vals.remove(e) except: raise ValueError(str(e) + ' not found') def __str__(self): """Returns a string representation of self""" self.vals.sort() return '{' + ','.join([str(e) for e in self.vals]) + '}' def intersect(self, other): """ Returns a new IntSet that contains of integers in both s1 & s2 """ # create a new intSet commonVals = intSet() for x in self.vals: if other.member(x): commonVals.insert(x) return commonVals def __len__(self): return len(self) # return len(self.vals) # s = intSet() # print s # s.insert(3) # s.insert(4) # s.insert(3) # print s # s.member(3) # s.member(5) # s.insert(6) # print s # s.remove(3) # print s # s.remove(3)
print('-=-' * 10, '\nEmpréstimo Garantido!!!') print('-=-' * 10) valor = float(input('Qual o valor da casa: R$')) sal = float(input('Qual seu salário? R$')) anos = int(input('Pretende pagar em quantos anos? ')) meses = anos * 12 prest = valor / meses if prest > (sal*0.30): print('Empréstimo não autorizado as prestações de R${:.2f} são mais que 30% do seu salário!'.format(prest)) else: print('Empréstimo autorizado, com pretações de R${:.2f}!'.format(prest))
# This test is here so we don't get a non-zero code from Pytest in Travis CI build. def test_dummy(): assert 5 == 5
# 矩形覆盖 class Solution: def rectCover(self, number): # write code here if number == 0: return 0 if number == 1: return 1 if number == 2: return 2 a = 1 b = 2 for i in range(3, number + 1): b = a + b a = b - a return b
__metaclass__ = type #classes inherting from _UIBase are expected to also inherit UIBase separately. class _UIBase(object): id_gen = 0 def __init__(self): #protocol self._content_id = _UIBase.id_gen _UIBase.id_gen += 1 def _copy_values_deep(self, other): pass def _clone(self): result = self.__class__() result._copy_values_deep(self) return result
#https://www.codewars.com/kata/the-office-ii-boredom-score """Every now and then people in the office moves teams or departments. Depending what people are doing with their time they can become more or less boring. Time to assess the current team. You will be provided with an object(staff) containing the staff names as keys, and the department they work in as values. Each department has a different boredom assessment score, as follows: accounts = 1 finance = 2 canteen = 10 regulation = 3 trading = 6 change = 6 IS = 8 retail = 5 cleaning = 4 pissing about = 25 Depending on the cumulative score of the team, return the appropriate sentiment: <=80: 'kill me now' < 100 & > 80: 'i can handle this' 100 or over: 'party time!!'""" score_values = { 'accounts' : 1, 'finance' : 2, 'canteen' : 10, 'regulation' : 3, 'trading' : 6, 'change' : 6, 'IS' : 8, 'retail' : 5, 'cleaning' : 4, 'pissing about' : 25} def boredom(staff): resultado = 0 for x in staff: resultado += score_values[staff[x]] if resultado <= 80 : return "Kill me now" elif resultado < 100 and resultado > 80: return "i can handle this" else: return "party time!!" boredom({"tim": "change", "jim": "accounts", "randy": "canteen", "sandy": "change", "andy": "change", "katie": "IS", "laura": "change", "saajid": "IS", "alex": "trading", "john": "accounts", "mr": "finance"}) #rw 22/06/2021 #Other Solutions """ n = sum(lookup[s] for s in staff.values()) if n <= 80: return "kill me now" if n < 100: return "i can handle this" return "party time!! """
"""Docstring. Details """ __all__ = ('InvalidParameterError') class InvalidParameterError(Exception): """A specific exception for invalid parameter.""" def __init__(self, message): # pylint:disable=W0235 """Init function.""" super().__init__(message)
""" 고객들이 원하는 토핑을 골라 주문할 수 있는 피자집의 주문 시스템을 만든다고 하자. 이 피자집에는 0부터 19까지의 번호를 갖는 스무가지의 토핑이 있으며, 주문시 토핑을 넣기/ 넣지 않기를 선택할 수 있다. 그러면 한 피자의 정보는 스무 종류의 원소만을 갖는 집합이 되고, 비트마스크를 이용해 표현할 수 있다. """ # 비트마스크를 이용하는 집합에서 공집합을 표현하는것은 너무나 간단하다. -> 0 # 꽉 찬 집합을 표현하는 것 1 << 20 - 1이 된다. # 집합의 가장 기초적인 연산은 원소를 추가하고 삭제하는 것이다. 비트마스크를 사용한 집합에서 원소를 추가한다는 것은 # 해당 비트를 켠다는 뜻이다.
#!/usr/bin/env python3 class Node(object): def __init__(self, ip, port): self.ip = ip self.port=port self.name="Node: %s:%d" % (ip, port) def __name__(self): return self.name def start(self): return def stop(self): return
description = 'PANDA Heusler-analyzer' group = 'lowlevel' includes = ['monofoci', 'monoturm', 'panda_mtt'] extended = dict(dynamic_loaded = True) devices = dict( ana_heusler = device('nicos.devices.tas.Monochromator', description = 'PANDA\'s Heusler ana', unit = 'A-1', theta = 'ath', twotheta = 'att', focush = 'afh_heusler', focusv = None, abslimits = (1, 10), # hfocuspars = [44.8615, 4.64632, 2.22023], # 2009 # hfocuspars = [-66.481, 36.867, -2.8148], # 2013-11 hfocuspars = [-478, 483.74, -154.68, 16.644], # 2013-11 2nd dvalue = 3.45, scatteringsense = -1, crystalside = -1, ), afh_heusler_step = device('nicos.devices.generic.VirtualMotor', description = 'stepper for horizontal focus of heusler ana', unit = 'deg', abslimits = (-179, 179), speed = 1, lowlevel = True, ), afh_heusler = device('nicos_mlz.panda.devices.rot_axis.RotAxis', description = 'horizontal focus of heusler ana', motor = 'afh_heusler_step', dragerror = 5, abslimits = (-179, 179), precision = 1, fmtstr = '%.1f', autoref = None, # disable autoref since there is no refswitch lowlevel = True, ), ) startupcode = ''' try: _ = (ana, mono, mfv, mfh, focibox) except NameError as e: printerror("The requested setup 'panda' is not fully loaded!") raise NameError('One of the required devices is not loaded : %s, please check!' % e) from nicos import session ana.alias = session.getDevice('ana_heusler') afh.alias = session.getDevice('afh_heusler') del session '''
#!/usr/bin/env python ############################################################################# ## # This file is part of Taurus ## # http://taurus-scada.org ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Taurus is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. ## # Taurus is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. ## # You should have received a copy of the GNU Lesser General Public License # along with Taurus. If not, see <http://www.gnu.org/licenses/>. ## ############################################################################# """ This module contains some Taurus-wide default configurations. The idea is that the final user may edit the values here to customize certain aspects of Taurus. """ #: A map for using custom widgets for certain devices in TaurusForms. It is a #: dictionary with the following structure: #: device_class_name:(classname_with_full_module_path, args, kwargs) #: where the args and kwargs will be passed to the constructor of the class T_FORM_CUSTOM_WIDGET_MAP = \ {'SimuMotor': ('sardana.taurus.qt.qtgui.extra_pool.PoolMotorTV', (), {}), 'Motor': ('sardana.taurus.qt.qtgui.extra_pool.PoolMotorTV', (), {}), 'PseudoMotor': ('sardana.taurus.qt.qtgui.extra_pool.PoolMotorTV', (), {}), 'PseudoCounter': ('sardana.taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), 'CTExpChannel': ('sardana.taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), 'ZeroDExpChannel': ('sardana.taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), 'OneDExpChannel': ('sardana.taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), 'TwoDExpChannel': ('sardana.taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), 'IORegister': ('sardana.taurus.qt.qtgui.extra_pool.PoolIORegisterTV', (), {}) } #: Compact mode for widgets #: True sets the preferred mode of TaurusForms to use "compact" widgets T_FORM_COMPACT = False #: Strict RFC3986 URI names in models. #: True makes Taurus only use the strict URI names #: False enables a backwards-compatibility mode for pre-sep3 model names STRICT_MODEL_NAMES = False #: Lightweight imports: #: True enables delayed imports (may break older code). #: False (or commented out) for backwards compatibility LIGHTWEIGHT_IMPORTS = False #: Default scheme (if not defined, "tango" is assumed) DEFAULT_SCHEME = "tango" #: Filter old tango events: #: Sometimes TangoAttribute can receive an event with an older timestamp #: than its current one. See https://github.com/taurus-org/taurus/issues/216 #: True discards (Tango) events whose timestamp is older than the cached one. #: False (or commented out) for backwards (pre 4.1) compatibility FILTER_OLD_TANGO_EVENTS = True #: Extra Taurus schemes. You can add a list of modules to be loaded for #: providing support to new schemes #: (e.g. EXTRA_SCHEME_MODULES = ['myownschememodule'] EXTRA_SCHEME_MODULES = [] #: Custom formatter. Taurus widgets use a default formatter based on the #: attribute type, but sometimes a custom formatter is needed. #: IMPORTANT: setting this option in this file will affect ALL widgets #: of ALL applications (which is probably **not** what you want, since it #: may have unexpected effects in some applications). #: Consider using the API for modifying this on a per-widget or per-class #: basis at runtime, or using the related `--default-formatter` parameter #: from TaurusApplication, e.g.: #: $ taurus form MODEL --default-formatter='{:2.3f}' #: The formatter can be a python format string or the name of a formatter #: callable, e.g. #: DEFAULT_FORMATTER = '{0}' #: DEFAULT_FORMATTER = 'taurus.core.tango.util.tangoFormatter' #: If not defined, taurus.qt.qtgui.base.defaultFormatter will be used #: Default serialization mode **for the tango scheme**. Possible values are: #: 'Serial', 'Concurrent', or 'TangoSerial' (default) TANGO_SERIALIZATION_MODE = 'TangoSerial' #: PLY (lex/yacc) optimization: 1=Active (default) , 0=disabled. #: Set PLY_OPTIMIZE = 0 if you are getting yacc exceptions while loading #: synoptics PLY_OPTIMIZE = 1 # Taurus namespace # TODO: NAMESPACE setting seems to be unused. remove? NAMESPACE = 'taurus' # ---------------------------------------------------------------------------- # Qt configuration # ---------------------------------------------------------------------------- #: Set preferred API (if one is not already loaded) DEFAULT_QT_API = 'pyqt' #: Auto initialize Qt logging to python logging QT_AUTO_INIT_LOG = True #: Remove input hook (only valid for PyQt4) QT_AUTO_REMOVE_INPUTHOOK = True #: Avoid application abort on unhandled python exceptions #: (which happens since PyQt 5.5). #: http://pyqt.sf.net/Docs/PyQt5/incompatibilities.html#unhandled-python-exceptions #: If True (or commented out) an except hook is added to force the old # behaviour (exception is just printed) on pyqt5 QT_AVOID_ABORT_ON_EXCEPTION = True #: Select the theme to be used: set the theme dir and the theme name. #: The path can be absolute or relative to the dir of taurus.qt.qtgui.icon #: If not set, the dir of taurus.qt.qtgui.icon will be used QT_THEME_DIR = '' #: The name of the icon theme (e.g. 'Tango', 'Oxygen', etc). Default='Tango' QT_THEME_NAME = 'Tango' #: In Linux the QT_THEME_NAME is not applied (to respect the system theme) #: setting QT_THEME_FORCE_ON_LINUX=True overrides this. QT_THEME_FORCE_ON_LINUX = False #: Full Qt designer path (including filename. Default is None, meaning: #: - linux: look for the system designer following Qt.QLibraryInfo.BinariesPath #: - windows: look for the system designer following #: Qt.QLibraryInfo.BinariesPath. If this fails, taurus tries to locate binary #: manually QT_DESIGNER_PATH = None #: Custom organization logo. Set the absolute path to an image file to be used as your #: organization logo. Qt registered paths can also be used. #: If not set, it defaults to 'logos:taurus.png" #: (note that "logos:" is a Qt a registered path for "<taurus>/qt/qtgui/icon/logos/") ORGANIZATION_LOGO = "logos:taurus.png" # ---------------------------------------------------------------------------- # Deprecation handling: # Note: this API is still experimental and may be subject to change # (hence the "_" in the options) # ---------------------------------------------------------------------------- #: set the maximum number of same-message deprecations to be logged. #: None (or not set) indicates no limit. -1 indicates that an exception should #: be raised instead of logging the message (useful for finding obsolete code) _MAX_DEPRECATIONS_LOGGED = 1
# -*- coding: utf-8 -*- def test_cookies_group(testdir): result = testdir.runpytest( '--help', ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines([ 'cookies:', '*--template=TEMPLATE*', ])
class TestFixupsToPywb: # Test random fixups we've made to improve `pywb` behavior def test_we_do_not_try_and_rewrite_rel_manifest(self, proxied_content): # The '_id' here means a transparent rewrite, and no insertion of # wombat stuff assert ( '<link rel="manifest" href="/proxy/id_/http://localhost:8080/manifest.json"' in proxied_content ) def test_we_do_rewrite_other_rels(self, proxied_content): assert ( '<link rel="other" href="/proxy/oe_/http://localhost:8080/other.json"' in proxied_content )
def transpose(the_array): ret = map(list, zip(*the_array)) ret = list(ret) return ret def get_unique_list(dict_list, key="id"): # https://stackoverflow.com/questions/10024646/how-to-get-list-of-objects-with-unique-attribute seen = set() return [seen.add(d[key]) or d for d in dict_list if d and d[key] not in seen] def color_variants(hex_colors, brightness_offset=1): return [color_variant(c, brightness_offset) for c in hex_colors] def color_variant(hex_color, brightness_offset=1): """ takes a color like #87c95f and produces a lighter or darker variant """ # https://chase-seibert.github.io/blog/2011/07/29/python-calculate-lighterdarker-rgb-colors.html if len(hex_color) != 7: raise Exception("Passed %s into color_variant(), needs to be in #87c95f format." % hex_color) rgb_hex = [hex_color[x:x+2] for x in [1, 3, 5]] new_rgb_int = [int(hex_value, 16) + brightness_offset for hex_value in rgb_hex] new_rgb_int = [min([255, max([0, i])]) for i in new_rgb_int] # make sure new values are between 0 and 255 # hex() produces "0x88", we want just "88" return "#" + "".join([hex(i)[2:] for i in new_rgb_int])
#################################################### # package version -- named "pkgdir.testapi" # this function is loaded and run by testapi.c; # change this file between calls: auto-reload mode # gets the new version each time 'func' is called; # for the test, the last line was changed to: # return x + y # return x * y # return x \ y - syntax error # return x / 0 - zero-divide error # return pow(x, y) #################################################### def func(x, y): # called by C return x + y # change me
"""Author @Sowjanya""" """Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.""" class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashMap = {} for i,n in enumerate(nums): if (target-n) in hashMap: return [i,hashMap[target-n]] else: hashMap[n]=i
def part1(input) -> int: count1 = count3 = 0 for i in range(len(input) - 1): if input[i+1] - input[i] == 1: count1 += 1 elif input[i+1] - input[i] == 3: count3 += 1 return count1 * count3 def part2(input) -> int: valid = {} def possibleArrangements(input) -> int: if len(input) <= 1: return 1 if input[0] in valid: return valid[input[0]] i = 1 res = 0 while i < len(input) and input[i] - input[0] <= 3: res += possibleArrangements(input[i:]) i += 1 valid[input[0]] = res return res return possibleArrangements(input) f = open("input.txt", "r") input = f.read().splitlines() for i in range(len(input)): input[i] = int(input[i]) input.append(0) input.sort() input.append(input[-1] + 3) print(part1(input)) #2310 print(part2(input)) #64793042714624
#!/usr/bin/python # -*- coding: UTF-8 -*- # Function: formatted text document by adding newline # Author: king def main(): print('This python script help you formatted text document.') fin = input('Input the file location : ') fout = input('Input the new file location: ') print('begin...') MAX_SIZE = 78 newlines = '' with open(fin, encoding='utf-8') as fp: lines = fp.readlines() for line in lines: content = line.encode('gbk') while len(content) > MAX_SIZE + 1: newcontent = content[:MAX_SIZE] content = content[MAX_SIZE:] try: newline = newcontent.decode('gbk') newlines += newline + '\n' except: newcontent += content[:1] content = content[1:] newline = newcontent.decode('gbk') newlines += content.decode('gbk') with open(fout, 'w', encoding='utf-8') as fo: fo.write(newlines) print('Finish Done!') pass if __name__ == '__main__': main()
s=0 i=0 v=0 while v>=0: v = float(input("digite o valor da idade: ")) if v>=0: s = s+v print(s) i = i+1 print(i) r = s/(i) print(r) print(r)
numeros = { 'william': 16, 'igor': 5, 'milly': 7, 'iago': 10, 'kelly': 25, } for nome, num in numeros.items(): print(f'O número favorito de {nome.title()} é {num}.')
__author__ = 'zz' class BaseVerifier: def verify(self, value): raise NotImplementedError class IntVerifier(BaseVerifier): def __index__(self, upper, bot): self.upper = upper self.bot = bot def verify(self, value): if isinstance(value, int): return False if not (self.bot <= value <= self.upper): return False return True class StringNotEmptyVerifier(BaseVerifier): def verify(self, value): if str(value).strip(): return True return False
# # LeetCode # Algorithm 141 Linked List Cycle # # Rick Lan, May 6, 2017. # See LICENSE # # Your runtime beats 69.76 % of python submissions. # # # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if head == None: return False crash = ListNode(0) p = head p = p.next while p != None: if p == crash: return True next = p.next p.next = crash p = next return False
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @param {integer} m # @param {integer} n # @return {ListNode} def reverseBetween(self, head, m, n): dumpy = ListNode(0) dumpy.next = head pre = dumpy diff = n - m while m > 1: pre = pre.next m -= 1 p = pre.next while diff > 0 and p and p.next: # print p.val diff -= 1 tmp = p.next p.next = tmp.next q = pre.next pre.next = tmp tmp.next = q return dumpy.next
class Solution: def twoSum(self, nums, target: int): d = {} for i in range(len(nums)): j = target - nums[i] if j in d: return [d[j], i] else: d[nums[i]] = i s = Solution() print(s.twoSum( [3, 2, 4], 6))
n = float(input('Digite o 1º numero: ')) n1 = float(input('Digite o 2º numero: ')) n2 = 0 while n2 != 5: print(''' [1] somar [2] Multiplicar [3] Maior [4] Novos numeros [5] Sair do programa''') n2 = int(input('Sua opção: ')) if n2 == 1: n3 = n + n1 print(f'A soma entre {n} + {n1} é igual a {n3}') elif n2 == 2: n4 = n * n1 print(f'O produto de {n} x {n1} é igual a {n4}') elif n2 == 3: if n > n1: print(f'O maior numero digitado foi {n}') else: print(f'O maior numero digitado foi {n1}') elif n2 == 4: n7 = float(input('Digite o 1º numero: ')) n8 = float(input('Digite o 2º numero: ')) n = n7 n1 = n8 elif n2 == 5: print('FINALIZANDO o programa!') else: print('Opção invalida por favor digite novamente:')
""" Addoperation class """ class AddOperation: """ Class for add operation """ def __init__(self, num1, num2): """ Init function """ self.num1 = num1 self.num2 = num2 self.result = 0 def process(self): """ Process function to perform operation""" self.result = self.num1 + self.num2 def get_output_json(self): """ Function to create output json """ self.process() output_json = { "input": { "num1": self.num1, "num2": self.num2, }, "result": { "operation": "add", "value": self.result } } return output_json
def tri_bulle(L): pointer = 0 while pointer < len(L): left = 0 right = 1 while right < len(L) - pointer: if L[right] < L[left]: L[left], L[right] = L[right], L[left] left += 1 right += 1 pointer += 1 return L print(tri_bulle([8, -1, 2, 5, 3, -2]))
""" Brightness """ class Brightness(object): """ Brightness facade """ def current_level(self): return self._current_level() def set_level(self, level): return self._set_level(level) # private def _current_level(self): raise NotImplementedError() def _set_level(self, level): raise NotImplementedError()
def maximo(a, b): """ Função que retorna o valor máximo entre dois parâmetros. >>> maximo(3, 4) 4 >>> maximo(0, -1) 0 :param a: number :param b: number :return: number """ if a > b: return a else: return b
t = int(input()) for case in range(t): s = input() numbers = '0123456789' if (s[0] == 'R' and (s[1] in numbers) and ('C' in s)): iC = 0 for i in range(len(s)): if (s[i] == 'C'): iC = i break row = s[1:iC] col = int(s[iC + 1:]) cols = '' rem = 0 while (col > 0): rem = col % 26 col //= 26 if rem == 0: col -= 1 cols = (chr(rem + 64) if rem != 0 else 'Z') + cols print(cols + row) else: iN = 0 for i in range(len(s)): if (s[i] in numbers): iN = i break pow = 0 cols = s[:iN] row = s[iN:] col = 0 for i in range(len(cols) - 1, -1, -1): col += (26 ** pow) * (ord(cols[i]) - 64) pow += 1 print('R' + row + 'C' + str(col))
# # PySNMP MIB module STACK-TOP (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STACK-TOP # Produced by pysmi-0.3.4 at Wed May 1 15:10:55 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") ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") Counter64, ModuleIdentity, ObjectIdentity, Counter32, NotificationType, iso, Bits, IpAddress, enterprises, Gauge32, Unsigned32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "ModuleIdentity", "ObjectIdentity", "Counter32", "NotificationType", "iso", "Bits", "IpAddress", "enterprises", "Gauge32", "Unsigned32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "MibIdentifier") DisplayString, MacAddress, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "MacAddress", "TextualConvention") zte = MibIdentifier((1, 3, 6, 1, 4, 1, 3902)) zxr10 = MibIdentifier((1, 3, 6, 1, 4, 1, 3902, 3)) stacktop = ModuleIdentity((1, 3, 6, 1, 4, 1, 3902, 3, 301)) stacktop.setRevisions(('2004-05-14 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: stacktop.setRevisionsDescriptions(('',)) if mibBuilder.loadTexts: stacktop.setLastUpdated('200705280000Z') if mibBuilder.loadTexts: stacktop.setOrganization('ZTE Corp.') if mibBuilder.loadTexts: stacktop.setContactInfo('') if mibBuilder.loadTexts: stacktop.setDescription('') class VendorIdType(OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(3, 3) fixedLength = 3 sysMasterVoteTimes = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysMasterVoteTimes.setStatus('current') if mibBuilder.loadTexts: sysMasterVoteTimes.setDescription("How many times stack system's master device be voted.") sysMasterLastVoteTime = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 2), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysMasterLastVoteTime.setStatus('current') if mibBuilder.loadTexts: sysMasterLastVoteTime.setDescription("The ending time when stack system's master device be voted.") sysLastDetecTopEndTime = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 3), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysLastDetecTopEndTime.setStatus('current') if mibBuilder.loadTexts: sysLastDetecTopEndTime.setDescription('The ending time when the system detected top at the last time.') sysTopChagTimes = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysTopChagTimes.setStatus('current') if mibBuilder.loadTexts: sysTopChagTimes.setDescription('How many times the system top changed.') sysTopDetecMsgCount = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysTopDetecMsgCount.setStatus('current') if mibBuilder.loadTexts: sysTopDetecMsgCount.setDescription('System topo detected topo protocol message count.') sysTopInfoTable = MibTable((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6), ) if mibBuilder.loadTexts: sysTopInfoTable.setStatus('current') if mibBuilder.loadTexts: sysTopInfoTable.setDescription('A list of the topo information.') sysTopInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1), ).setIndexNames((0, "STACK-TOP", "sysDeviceMacAddr"), (0, "STACK-TOP", "sysDeviceStkPortIndex")) if mibBuilder.loadTexts: sysTopInfoEntry.setStatus('current') if mibBuilder.loadTexts: sysTopInfoEntry.setDescription('An entry to the topo info table.') sysDeviceMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 1), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceMacAddr.setStatus('current') if mibBuilder.loadTexts: sysDeviceMacAddr.setDescription('System Device mac address.') sysDeviceStkPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkPortIndex.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkPortIndex.setDescription('System device stack interface port index.') sysDeviceType = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceType.setStatus('current') if mibBuilder.loadTexts: sysDeviceType.setDescription('System device type.') sysDeviceStkPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkPortNum.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkPortNum.setDescription('System device stack interface port number.') sysDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceID.setStatus('current') if mibBuilder.loadTexts: sysDeviceID.setDescription('System device ID.') sysDeviceMasterPri = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceMasterPri.setStatus('current') if mibBuilder.loadTexts: sysDeviceMasterPri.setDescription("System device's priority in voting master device.") sysDeviceStkIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkIfStatus.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkIfStatus.setDescription('System device stack interface status 1: up 2: down.') sysDeviceStkIfPanel = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkIfPanel.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkIfPanel.setDescription('System device stack interface panel num.') sysDeviceStkIfPortID = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkIfPortID.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkIfPortID.setDescription('System device stack interface port num.') sysDeviceStkPortNeibMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 10), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkPortNeibMacAddr.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkPortNeibMacAddr.setDescription('System device stack interface neighbor device mac address.') sysDeviceStkPortNeibPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkPortNeibPortIndex.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkPortNeibPortIndex.setDescription('System device stack interface neighbor device port index.') sysStkPortMsgStacTable = MibTable((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7), ) if mibBuilder.loadTexts: sysStkPortMsgStacTable.setStatus('current') if mibBuilder.loadTexts: sysStkPortMsgStacTable.setDescription('A list of the stack interface receive and send message statistic information.') sysStkPortMsgStacEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1), ).setIndexNames((0, "STACK-TOP", "sysStkDeviceID"), (0, "STACK-TOP", "sysStkDeviceStkIfIndex")) if mibBuilder.loadTexts: sysStkPortMsgStacEntry.setStatus('current') if mibBuilder.loadTexts: sysStkPortMsgStacEntry.setDescription('An entry to the stack interface receive and send message statistic information table.') sysStkDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysStkDeviceID.setStatus('current') if mibBuilder.loadTexts: sysStkDeviceID.setDescription('System device ID.') sysStkDeviceStkIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysStkDeviceStkIfIndex.setStatus('current') if mibBuilder.loadTexts: sysStkDeviceStkIfIndex.setDescription('System device stack interface index.') sysStkPortRecMsgCount = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysStkPortRecMsgCount.setStatus('current') if mibBuilder.loadTexts: sysStkPortRecMsgCount.setDescription('System stack interface received message count.') sysStkPortSendMsgCount = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysStkPortSendMsgCount.setStatus('current') if mibBuilder.loadTexts: sysStkPortSendMsgCount.setDescription('System stack interface send message count.') mibBuilder.exportSymbols("STACK-TOP", sysTopChagTimes=sysTopChagTimes, zxr10=zxr10, PYSNMP_MODULE_ID=stacktop, stacktop=stacktop, VendorIdType=VendorIdType, sysLastDetecTopEndTime=sysLastDetecTopEndTime, sysStkPortMsgStacTable=sysStkPortMsgStacTable, sysStkPortSendMsgCount=sysStkPortSendMsgCount, sysTopDetecMsgCount=sysTopDetecMsgCount, sysDeviceMacAddr=sysDeviceMacAddr, sysDeviceType=sysDeviceType, sysDeviceID=sysDeviceID, sysMasterLastVoteTime=sysMasterLastVoteTime, zte=zte, sysDeviceStkIfStatus=sysDeviceStkIfStatus, sysTopInfoTable=sysTopInfoTable, sysStkPortRecMsgCount=sysStkPortRecMsgCount, sysStkPortMsgStacEntry=sysStkPortMsgStacEntry, sysStkDeviceStkIfIndex=sysStkDeviceStkIfIndex, sysDeviceMasterPri=sysDeviceMasterPri, sysMasterVoteTimes=sysMasterVoteTimes, sysDeviceStkIfPanel=sysDeviceStkIfPanel, sysTopInfoEntry=sysTopInfoEntry, sysDeviceStkPortNum=sysDeviceStkPortNum, sysDeviceStkPortNeibPortIndex=sysDeviceStkPortNeibPortIndex, sysDeviceStkIfPortID=sysDeviceStkIfPortID, sysDeviceStkPortNeibMacAddr=sysDeviceStkPortNeibMacAddr, sysStkDeviceID=sysStkDeviceID, sysDeviceStkPortIndex=sysDeviceStkPortIndex)
class Solution: def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ if len(candies) == 0 or len(candies)%2 !=0: return 0 h = set() for i in candies: h.add(i) l=len(candies)/2 if(len(h)>l): return int(l) return len(h)
all_bps = """BFBBBBBLLR BBFFBBFRRL FBFBFFFRRL BBFFFBFRRL BFFBFBFRLL FFBBBFBLRL BFFFBFFLLR FBFFFFBLRR FBFFBBBRRR BFFBFFFLLR BFFFFFBLLL FFBBFFBLRR BFFFFFBRLR FBFBFBFLLL FFBFBFFLLL BBFFFFFLLL FFFBBBFLLL BBFFBFBLLR FFBFBFBRRR BFFBFFFRRR BBFFBFBRLR FFFBFBFLRL BBFFBBBLRR FBBFFFFLLR BBBFBBFLLL BFFFFBBRLL FBBFBFBRRL FFBBBFFRRR BBFFFFBRRR FBBBBFFLLR BFFFFFBLRR FFBBFBFLLR BFFBFBBLLL BBFBBBBLLL FBFBBBFRLL FFBFFFBLRL FFFFBBBLRL BBBBFBFRRR FFBBFBBRLL FFFBBBBRRL FFBFFFBRLR BFBFBFBLLL FFFBFFBLLL BBFBFBBLRL BBBBBFFLLL FBBBBFFRRR FBFFFFBLLL FFFFBBBRRL FBFBBBFRRR FBBFFBFLRL BFBFFBFLLR FFBBBFBLLL BFBFFFFLLL BBBFFFFLLL BFBBFBFRLR BFBBBBFLRL BBBFBFBLRL BFFFBFBLRL BFBBBBBRLL FBBBFFBRLL BFBFFBBRRL BFFBBBFLLR BFFBFFBRRR FBFBFBFRRL FBFBFBFLRL BBBFFFBRRR FBFFBBFRRR FFBBFFFRLL BFBFBBBLLR BFFFFBFLLR FFBBBBFRLR FFFBFFFRRR BFBBFFFRLL BBBFBFFLRL BFBBFBFLRR BBBBFBBLRL FBFBFBFLRR BBFBFBBLLL BFBBBFBLRL BFBBFBFLRL FFFBBFBLLL BBBFBFBLLR FBBBBBFLLR FFBBBFBRLL BBBBFBBRRL FBFFFBBRLL BBFBBFFRRL FBFFBFBLLL BFFBFBBRRL BFFFBFFRLR BBFBFBFRRR FBBFBFFRRR BBBFBFBLRR FFBFFBFRLR FFBFBBBLRL FFFFBBFRRL FFBBBFBRLR FBFBFBBLLL FBBBFBFRLL BBBBFBBLLR BFBFBBFRLR FBBFBBFLRR BBBBFBFLRL FBFBFBFRLL FFBFBFBLLR FBFFBBFRRL BFFFFFFRLR FFFFBFFRRL BBFFFBFLRR FBBFFBFRRL FFFFBFBLLL FFBBFFFRRL BBFBFFFRLL BFFFFBFRLR FBFBFBBRRL FBBFBBFRLR BFBFFFBRRL FFFBFFBRLR BFBFFBFLRL FBBFBFFRRL FFBFFFBLLL FBFFFBFRRR FBFFFBBRRL FBFFBFBRLL BFBFFFFRLL FFFBBBFLRR BBFFFFFLRR BFBBFBBLLR BFBFFBFLLL FBBBBFBLLR BFBBFFFLLR BFBBFFFRRL BFFBBFFLLR BBBFFFFRRL BBBFBBBLLR FFFBFBBRLL FFBFFBBLRR FFBFBBFLLL BBBFFBFRLL BBBFBFFLRR FBFBFFBRLR FBBFFBBLRL BBFBBFFLLR BBFBBFBRLR BFBFFBBRLR BBBBFFBRLL FFFBBBFRLL FBBFFFFRLR BFBBBBFRRR BBBBFFBLRR FBBBBBFLRR FBBBFFBLRL BFFBBBFRRR BBBBFBFRLL BFBBBFBLRR FFBFFFFLLL FBFFFFBRLL FFBFFBBRLR BFFBBFFLLL FFBFBFBLRL FFBFBFFRRR BBBFBBFLRR BBBFBBBLLL BFFFFFFLRL FBBBBBBRLR FFFBFBFLRR FFBBFFBRRL FBBFBBBRLR BBBFBBFLLR FFBFFBFLRR BFBBFBBRRL FBFFFBBLRL BFFBBFBLRL BBFFBFFLLL FBBBFBFRLR BBBBFFFRLL FFBFBFBLRR FBBFFFBRRL FFBBBFFLLL BBFFFBBLLR BFFFFBFRRL FBFFFFBRRL BFBBFFFRLR FFFBBBBLLL FBFBFBBRLR FFFBFBBRLR FBFBFFFLRR BFFFFFFRRR FFFFBBBRRR BBFBFFFRRL FFFBFBBLLL BFBBFBFLLR BBFBBBBRRL BBFFBBFRRR BBBFFBBLRL FBFBFFFLLR BFFFBBBRRR FFBFFFFLLR FBBBFBFLLL FBBBFBBLRR BBBFBFBRRR FBBBFBFRRL BBBBFFBRLR FBFBBBBLLR FFFFBBFRLR BBFBBBFLLL BBFBBBBLRR FFFFBFBRRR FBFFFBFLRR BFFFBBFLRR BBBFBFFLLR BFFBBBBRLR FBFBBFBLLR BFBBBFFLRR BFFBBFFRRR FFFBFFFRLL FFBFBBBRRR BBBFFFBLLR BBFFFFFLLR FBBBBFBLRR FBFBBFFRRL BFBFBFFRRL BFFFFBFRRR FFBFFBBLLL BFBFBFBRRR BFFFFFFLLR FFFBBFBRRL BFBBBFBRRL BBFFFBFRLL BFBBBBBLRL FBFBBFFLRR FFBBBFFRLR FBBBFBBRRR FFBBBFFRRL FFBBBBFLLR BBFBBFBRRL BBFBBBFRLL BBFFFFFLRL BBBFFFBLLL BBFFFFFRRR FFBFBBBLRR FFBBBFFLRR BFFBFBFRLR FFBBBFBRRR FBBBBFBLRL BBBFBBBRLL FBFBFFBRRL BFFFFBBRRL BBFFBBFRLR FFBFBFFRLR BFFFBFBRRR BBBFBBFRRL FFFBFFFLRL FBBFFBFRRR FFBBBBBLLL FFBFFBFLRL FBFBFBBLRR FFFBFFBRLL BBBFFFBRRL BFBFBBBRLL BBBFFFFLRR BBFFBFFLLR FBBFFBFLRR FBBBFFBLRR BFBFFBBLLL FBFFFBBRLR FBBFBBBLLR BFBBBBBRLR FBBBFFFLLL BFFFBBFLLL BFFFFBBRLR FBBFBFBRLL FBFFBFBLRL BBBFFFFRLL FBFFFFFRLL FBBBFBFLRL FBFBBFBRRL FFBFBFFLLR BBBFFBBLLL FFBFBBFLLR BBBFBBFRLL BFFBFBBLRR FBBFBBFRRL FBFFBFFLLL BFBBFBFLLL FFBBFFBRLL BFFFFFFLLL BFFFFFFRLL BFBFFFFLRR FFBBFFFLRR BBFFBBBRLR BFFFFBFLRR FFBFBFFLRR BBBBBFFLRL BBFBBBBRLR BFFBFFBRLL BFBFBBFLRL FBFBBFBLLL BFFBBFFRLR FFFFBFBRLR BFBFBFBRLL BFBBFFBLRR BBBBBFFRLL BBFFFBBRLL BFBFBBBLLL FBBBFFFLRR FBBBBBFRRL BFFBBFBRRL FFBBFFBLLL FBFFFBFRLL BBBFFFBRLL FFFBBFFLLL BBFBFBBLLR FFFBFFBLRL BFFBBBBLLL BBFFBFFLRR FFBBFBFLRR BBBBFBFRRL BBFBFBBRRR BBFFFFBLLR BBBBFFBLLR BBBFFBFLRR FFBFFBBLRL BBFBBBFRLR FBFFBFFLRL FFFFBFBLRL BFBFFFBLRL FBBBFBFLRR BFFFBBBLLL FBBBFFFRRR BFBFBFFLLR BFFBFBFLLR FFFBBBFRRL BBBFFBFLLR FFBFBFBLLL BFBBBFFRLR BBBFFBFRRL FBFBFFFRLR BFBFBBFRRL FBFFFFFLRR BFBFFBBLLR BBFBFBBRLR FBBBFFFLRL BBBBFBBRRR FFBBBBFLLL FBFFFBBLLR FFBBBBBRRR BFFFBBBLRR BBFBBBBRLL BBFBFBFLRR BFBBFFBLLR FBBFFBBRLL FBBBBFFRLL FBFBFFBLLR FFBFBBBRRL FFFBBFBRLL BFFBBFBLLR BBBBBFFRRL BFBBFFBRRL BFFBFFBRLR FFBFBBFRRL FFFFBBFLRL BBFFFFBLRL BFBFFFBRLL BFBFFFFRRR BBBFFBBRRL FFFFBBFLLL BBBFFFFLRL BBBFBFFLLL FBFBFFBRLL FBBFFFBLRL BFBFBFFLLL BBBFFFBLRR FBFBFBFRLR BFBFBFFLRL BFFFBBBRRL BFBFFBBRLL FFBFFFBRLL FFBFFBFLLR FFFBFFBRRL FFBBFFFLRL BFBFFFFRRL FBFFFFFRRR BBFBBFBLLR FFBFBFBRLR BFFFBFFRRR FBBBBFBLLL BBFFBBBRRR BBFBBBBRRR BBBFBBBLRR BBFBBFBRLL BFBFBFFLRR FBFFFBFLRL FFFFBFFRRR BFFBFFFLRR FBFFBBBRLL BFFFBFBLLL FBBFBFBLLR FFBFFBBRRR BFBFBBFLRR BBFFFFBLLL FBBFFFFRRR FBFBBBFRRL FBBFFFBLLR FBFBBFBRLR BBFFBBBLLR FFFBBFFLRL BBFFBFBRRR BFBFFFFLRL FFFFBFBRLL FBFFFBFRRL BBBFBBBLRL FFBBBFFRLL BBFBFFBRRL BFFBFFBLLL BBFBBFBRRR FBBFBBFLLR BFFFFFFLRR FBBBBBBRRR BBFBBBFRRL FFFBBBFLLR FBBBBFFLRL FBFFBFFRLL BFBFBFBRLR FBBBFFFRLL BBFFFBBRRR BBFBFBBLRR BFFFFFBRLL FBFBFFFLLL FBFFBFBLLR BFFBFFBRRL BFBBFFFLRR BFBBBFBLLR FFFBBBBRLR FFBFFBFRRL FFBBBFBLLR BBFBFFBRRR FFBBBBBRLR BBFFBBBLLL BFBBFFBLLL BFBFBBFRRR BBBBFFFLLL FBBFFBBRRL FFBBBFBRRL BFBFBBBRRR FBFBBFFLLL FFBBFFFLLR FBBBBBFLLL FFBFBFFLRL FFBFFBFRRR FBBBFBBRLR BFFFFBFLRL FFFBFFFLLR BBFBFFBLLR FFBBFFBLRL FFFBFBBLRL BFFFBBBRLR BBFFFFBRRL FBBFFBBLRR FBFFFFFLRL BBFFBFFRLR BBFBFFFRLR FFFBFBFRLR BFFFBBFRRL BBBFFBFLLL BBFBBBBLRL BFFFFFBLLR BFFFFBBLLR BBBFFBFRRR BBFFFFFRRL BBFFFFBRLR FFBBBFFLRL BFFFBBBRLL BFFFBBFRLL FBFBBBFRLR BBFBFBFRRL FBFFBFBRLR FBFFBFFRRR FBFFFBBLRR BFFFBBFLRL FBFBFFBLRL FBBBBBBRRL BFFFBFBRLR FBBBBFBRLL BBFFBBFLLR BBFBBFFLRR FBFFFBFLLR FBBBFBBLLL FFBFFFBLRR BBFBFFBLRR FFBFFBBRLL BFFBBFFRLL FBFFFFBRRR FFFBFBBRRL BBBBFBFLLR BBFBFFFLRL BFBFFFFRLR BBFBFFFRRR BBBFBBBRRL BFFBBBBLRR BFFFBBBLRL BBFFFBBRLR FBBBFFBRLR FBBBFFBLLL FBBBBBBLRL BBBFFFBLRL FBFBFFFLRL BFBFFBFRLL BBFFFFBRLL BBFFFFFRLL FFFBFFFRRL BBFFBBFLRR BBBBFFFRRL BFFBBBBLLR BBBBFFFRLR BBBFFFBRLR FBBFFBBRLR BFFBBFBLLL BBBFBBFLRL BFBFBBFLLR BBFBBFFLRL BFFBBBFRRL FFFFBBFLRR FBFFBBBLLR BFBFBFBLLR FBBBFFBRRR FBBBBBFRLR BBFBFFBRLR BBFFBFFRLL FFFBFFBLLR BBFFBFBLRR FBFFFBBRRR BFFBBBBRRR FBFFBBBRRL BBFBFBFLLR FBFBBFFLRL BBBBFFFRRR BBFBFFFLLL BFFFBFBLLR FBBBBFFLRR FBFFBBFLLL FFFFBFBRRL BBFBFBFLLL BFBBFFBLRL BFFFBFBLRR BBBBFFBRRR FBFBBFBRRR FBBFBFBRLR FBBFBFFLRR FBFBBBBLRR FBBFBFFRLR FBBBBBFLRL FBBFBFFRLL FFBBFFBRRR BFBFBFBLRR FBBFBBBLRL FBBBFBFRRR BFFBFBFRRL FBBFFFFLRL BFBBBBFRLR FFBFBBBRLL BFFBBBBRRL BFBBFBBLLL FBFBFFFRRR BFBFBFBLRL FBBFFBFLLR FFFBFBBRRR FBBBBFFLLL FBFBBBBLRL FBBFBFBLRL FFBBFBBRRR FBFBFFBLRR FBFBFBBLLR FFFBFBFRLL FFFFBBFRRR BFBBBBBLLL BBFBBBBLLR FBBFFFFRRL FBBFBFBLLL BFFFBBFLLR FBBBFFBLLR FFBFFBFLLL BBBFFBBLLR BFBFFFFLLR FBFBBBFLRR FFBBBBFRRL FFFFBBBLRR FFBFFFFRRL BFBBFFFLRL BBBFBFBLLL FBFBBFBLRR BBFBBFBLLL BFFBFBBRLR BFBBFBBRRR FFBBFBFRLL BFFBFBFLLL BFFBBFBLRR FBBBBFBRRL BFBFBBBLRR FBBBBBBLLL BFFFBBBLLR BBFBFFFLLR BBBFFBBRLL BFFBBBFLRR BFFBFBFRRR BBBBBFFRLR BFFBFFFRLR FBFFFFFLLL BFFFBFBRLL FBBFBBFLLL FBBFBFBRRR FBFFBBFLLR FBBBFBFLLR FFFBFFFLRR FFBBBBFRRR BBBBFBFLRR FBFBFFBRRR BFFBFFBLLR FFBBFBBRLR FBFBFBBRRR FFBBBBBLRL FBBBBBFRRR FFFBFBFRRL FFBFBFBRRL BFBBBFBRLR BBBFBFFRRR BFFBBFBRLR BFFBBBBRLL FBBBBFFRRL BBBFBBBRLR BFFFFFFRRL FFFBBFFLRR BBFBFFBLRL BFFBFBFLRR BBBFFBBLRR BFBFFBFRRR BBBBFFBLLL FBFFBBBLRR BBFFBBFLLL FBFBBBBRRR BBFFBFBLLL BBBBFFFLRR FBFFBBBRLR BFBFFFBLRR BBFBBFFLLL BFFBBFFRRL BFFFBFFRRL BBFFFBBLRR FFBFFFFLRL FFBFBBFRLL FBFBFFFRLL BBFFFBFRLR FFFBBFBLRR BFBBBFBLLL BBFBFBFRLL BFBFBBFRLL BFFFFFBRRL FFBFBBBRLR BFBBFFBRLR BFBFBFFRLR FBBBBBBLRR FFBBBBFLRL FFFFBFBLRR FFBFFFBRRR FFBFBBFRLR BBBFFBFLRL FBBBBFFRLR BFFBBFBRLL BFFBBBFRLR FFFBFFBRRR BBBFBBBRRR FBFFBFFRRL FBFFFBFLLL BFBBBFFRRL BBFBFBBRLL BBFBFBBRRL FFFBFBFRRR BFBBFBBLRR FFFBBBFRRR BFFBFBBLRL BFFBFFBLRR BFBBBFFRRR FFFBBBFLRL FFBBFBFRRR FFBFBFBRLL FFBFFFBLLR FBBBBBBRLL FFFFBFBLLR FFBBFFFRRR FFFBFFFLLL FFBBFBBLLR FFBBBBFLRR FBBFFBBLLL BFBBFBBRLR FFFBFBBLLR BBFFBFBLRL FFBFBBFRRR BBBBFBBRLR BBBFBBFRLR BBFFBFFRRR FFBBBBBLLR FBFFBFBLRR FBBBBFBRLR FFFFBBFLLR BFBFBBFLLL FBBFBFBLRR FBBFFBFRLL BBFFFFFRLR FFBBFBFLRL BFBFBBBRLR FBBFBBFRRR FBFBFBBLRL BBBFFBBRRR FBBFFBBRRR FBFFFFBRLR FBBFBBFLRL FFFBBFBRRR FBFBBBBRLR FBBFFBBLLR FFFBBBBRRR BBBBBFFLLR FFFFBBBLLL BFFBBBFRLL FBFBBFBLRL BBBBFBFRLR BBFBFFBLLL BFBFFBFLRR BFFFFFBLRL BBBFBBFRRR FFBBBBBLRR FBFFFFFLLR FBFBBFFRLL BFBBBBBRRL FBFBFBBRLL FBBFBBBRRL FBFFBBBLRL BFFFBFFLLL BFBBBBBRRR FFFBBFFRRR BBFBBBFLRL FFFFBBFRLL FBFFFFFRLR FFFFBBBRLR FBFFBBFRLR FFFFBBBRLL BBFFBBBLRL FFBFBBFLRR BFBBBBBLRR BFFFFBBLLL FBFBBBBRRL BBBFBFFRRL BFBBFBBLRL BFBBBBFRRL FBFFFBBLLL FFBBFBBLRL BBFBFFBRLL BBBFFFFRRR FFFBBBBLRR FFFBBFBLRL FFFBBBBLLR BFBFBBBRRL BBBBBFFLRR BBBBFBBLLL BBBBFBBLRR FFFBBBFRLR FBBBFFFLLR BFFFBFBRRL BBFFFBFLLR BFBBFBFRLL BFBBBFFLRL FFBFFBBRRL FBFBBFFRLR BFFFFFBRRR FBFFFFBLLR FBBFBFFLLR FBBBFFFRLR FBFBFBFLLR FFFBBFBLLR BFBFFBFRRL FFFBBFBRLR FFBBFBBLRR FBBBFBBLLR BBBFFFFLLR BBBBFBFLLL BBFFFBFLLL BFFFBFFLRL BBFBBFFRLR BBFFBBFLRL FBBBBFBRRR FBBFFBFLLL FFFBFFBLRR FFBBFFFRLR FBBFFFBRLR BBBFBFBRLL BFBBFFFLLL FFFBBFFRLL BBFFBFBRLL FFBBBBBRRL FBFFBBBLLL FBBFFFBRRR BFFFBFFRLL FFBBBFFLLR FBBFBBFRLL FBBFFFFLRR FBBBBBFRLL BBBFFBBRLR FBFFBBFLRL FBBFFFBLLL BFBBBFFRLL FFFBBFFRLR BFBFFFBLLL FFFFBBBLLR BFFBFFFLLL BFBBFFBRRR BFFBFBBLLR FFBFFBFRLL FFFBBFFLLR FBFFFFFRRL BFFBBFFLRR FFBBFFBLLR FBBBFFBRRL FBBBFBBLRL BBFFBFFLRL BBBBFFBRRL BFBFFBBLRL BFBBFBFRRR FFFBBBBRLL FBBFBBBRRR BBBBFFFLRL FBFFBFBRRR BBBBFFFLLR FBBFFBFRLR FFFBBBBLRL BBFBBFBLRL BFBBBBFLLR BBBFBFBRRL BFBBBBFLLL BFBFFFBRRR FFBBFFBRLR FBBBFFFRRL BFFFFBBRRR FBFBBFBRLL BFBBFFBRLL FBBFBFFLRL BFFBBBBLRL BFFBFBFLRL FBBBFBBRRL BFBBBBFLRR BFBFFBBRRR BFFFBBFRLR BFFBFFBLRL BFFBBFBRRR BBFFBBBRRL BBBBFBBRLL FBBFBBBLRR FFBFBFFRLL FFBFFFFRRR BFFBBFFLRL BFBBFBBRLL BFBFFBBLRR FBFBFBFRRR BBFFFBFRRR BBFBBFFRRR FFBFBBBLLR FFFBFBFLLL BBFFFBBLLL FFBBFBBLLL BFBBFFFRRR BFBFBBBLRL FBFBBBFLRL BFBFBFBRRL FFFBFBFLLR BBFFFFBLRR BBFBFBFRLR FFBBFBFLLL BFBBBFBRLL BBBFFBFRLR BFFFFBFLLL FFBBBBFRLL BBFBBFFRLL BFFFBFFLRR BBFBBBFLLR FFBFBBFLRL BBBBFFBLRL BFBBBFBRRR FBBFBFFLLL FBFFBFFRLR BFFBFFFLRL FBFFBFFLLR FBFBBBBRLL BBFFFBFLRL BBFBBFBLRR BFFFFBBLRL BBFBFBFLRL FBBFBBBRLL FBBFFFFRLL FFBFBBBLLL FFBFFBBLLR BFBBBFFLLR BBBFBFFRLR BFFBFFFRRL BBFFBBBRLL BBFFBBFRLL FBBBBBBLLR BFFBFBBRRR BBFFFBBRRL FFBFFFFRLL FFFBFBBLRR BBFFBFBRRL BBFFFBBLRL FBFFFFBLRL BFFFFBFRLL BFFBBBFLLL BFBBFBFRRL FBBFFFBLRR FFBFFFFRLR FBBFFFFLLL FBFBBFFRRR FBFBBFFLLR FFBFFFBRRL BFBBBBFRLL BFFBBBFLRL FBFFBFBRRL FFBFFFFLRR FBBBFBBRLL BBFBBBFRRR BFFBFFFRLL FFFBBFFRRL BFBFFFBLLR FBFFFBFRLR FBFBBBFLLL FFBBFBFRRL BBBFBFFRLL FBFFBFFLRR BBFBBBFLRR FFBBBFBLRR FFFBFFFRLR FBFBFFBLLL BFBBBFFLLL BFFFFBBLRR FBFBBBFLLR FBFFBBFLRR FFBBFBBRRL BBFBFFFLRR BBFFBFFRRL FFBBFFFLLL FFBFBFFRRL BBBFBFBRLR BFBFFFBRLR FBFBBBBLLL FFBBBBBRLL FBBFBBBLLL BFFFBBFRRR BFBFFBFRLR BBBFFFFRLR FBFFBBFRLL FFBBFBFRLR BFFBFBBRLL BFBFBFFRRR FBBFFFBRLL"""
def Setup(Settings,DefaultModel): # set1-test_of_models_against_datasets/models_30m_640px.py Settings["experiment_name"] = "set1c_Models_Test_30m_640px" Settings["graph_histories"] = ['together', [0,1], [1,2], [0,2]] n=0 # 5556x_minlen30_640px 5556x_minlen20_640px 5556x_reslen20_299px 5556x_reslen30_299px Settings["models"][n]["dataset_name"] = "5556x_minlen30_640px" Settings["models"][n]["dump_file_override"] = 'SegmentsData_marked_R100_4Tables.dump' Settings["models"][n]["pixels"] = 640 Settings["models"][n]["model_type"] = 'img_osm_mix' Settings["models"][n]["unique_id"] = 'mix' Settings["models"][n]["top_repeat_FC_block"] = 2 Settings["models"][n]["epochs"] = 800 # c Settings["models"][n]["loss_func"] = 'mean_absolute_error' Settings["models"][n]["metrics"] = ['mean_squared_error'] Settings["models"].append(DefaultModel.copy()) n=1 Settings["models"][n]["dataset_pointer"] = -1 # 0 - reuse the first dataset Settings["models"][n]["dataset_name"] = "5556x_minlen30_640px" Settings["models"][n]["dump_file_override"] = 'SegmentsData_marked_R100_4Tables.dump' Settings["models"][n]["pixels"] = 640 Settings["models"][n]["model_type"] = 'osm_only' Settings["models"][n]["unique_id"] = 'osm_only' Settings["models"][n]["top_repeat_FC_block"] = 2 Settings["models"][n]["epochs"] = 800 # c Settings["models"][n]["loss_func"] = 'mean_absolute_error' Settings["models"][n]["metrics"] = ['mean_squared_error'] Settings["models"].append(DefaultModel.copy()) n=2 Settings["models"][n]["dataset_pointer"] = -1 # 0 - reuse the first dataset Settings["models"][n]["dataset_name"] = "5556x_minlen30_640px" Settings["models"][n]["dump_file_override"] = 'SegmentsData_marked_R100_4Tables.dump' Settings["models"][n]["pixels"] = 640 Settings["models"][n]["model_type"] = 'simple_cnn_with_top' Settings["models"][n]["unique_id"] = 'img_only' Settings["models"][n]["top_repeat_FC_block"] = 2 Settings["models"][n]["epochs"] = 800 # c Settings["models"][n]["loss_func"] = 'mean_absolute_error' Settings["models"][n]["metrics"] = ['mean_squared_error'] return Settings
#!/usr/bin/env python3 DEV = "/dev/input/event19" CONTROLS = { 144: [ "SELECT", "START", "CROSS", "CIRCLE", "SQUARE", "TRIANGLE", "UP", "RIGHT", "DOWN", "LEFT", ], 96: [ "CENTER", ] } def trial(n: int) -> None: for size in CONTROLS.keys(): for control in CONTROLS[size]: print(f"PRESS {control}") with open(DEV, "rb") as f: sequence = f.read(size) print(f"READ {size} BYTES") with open(f"./samples/{control}_t{n}.hex", "wb") as f: f.write(sequence) print(f"WRITTEN TO ./samples/{control}_t{n}.hex") print() def main(): for i in range(10): trial(i) if __name__ == "__main__": main()
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # class Solution(object): # def swapPairs(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ class Solution(object): # def swapPairs(self, head): # current = last = last2 = head # while current is not None: # nex = current.next # if current == last.next: # last.next = nex # current.next = last # if last == head: # head = current # else: # last2.next = current # last2 = last # last = nex # current = nex # return head def swapPairs(self, head): dummyHead = ListNode(-1) dummyHead.next = head prev, p = dummyHead, head while p != None and p.next != None: q, r = p.next, p.next.next prev.next = q q.next = p p.next = r prev = p p = r return dummyHead.next
# Demo Python Functions - Keyword Arguments ''' Keyword Arguments You can also send arguments with the key = value syntax. This way the order of the arguments does not matter. ''' # Example: def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") # The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
N, L = input().split() N = int(N) L = int(L) #print(N, L) s_list = input().split() citations = [ int(s) for s in s_list] def findHIndex(citations): citations.sort(reverse=True) N = len(citations) res = N for i in range(N): if citations[i]<i+1: res = i break return res k = findHIndex(citations) while L > 0 and k>=0: citations[k] += 1 L -= 1 k -= 1 k = findHIndex(citations) print(k)
####################################### ## ADD SOME COLOR # pinched and tweaked from https://github.com/impshum/Multi-Quote/blob/master/run.py class color: white, cyan, blue, red, green, yellow, magenta, black, gray, bold = '\033[0m', '\033[96m','\033[94m', '\033[91m','\033[92m','\033[93m','\033[95m', '\033[30m', '\033[30m', "\033[1m"
# -*-coding: utf-8 - # 매도호가 정보의 경우 동시호가 시간에도 올라오므로 주의 AUTO_TRADING_OPERATION_TIME = [[[9, 0], [15, 19]]] # 조건검색식 적용시간 CONDITION_INFO = { "장초반": { "start_time": { "hour": 8, "minute": 5, "second": 0, }, "end_time": { "hour": 15, "minute": 0, "second": 0, } } } MAESU_UNIT = 100000 # 매수 기본 단위 BUNHAL_MAESU_LIMIT = 5 # 분할 매수 횟수 제한 MAX_STOCK_POSSESION_COUNT = 3 # 제외 종목 리스트 불포함한 최대 종목 보유 수 STOP_LOSS_CALCULATE_DAY = 1 # 최근 ? 일간 특정 가격 기준으로 손절 계산 REQUEST_MINUTE_CANDLE_TYPE = 3 # 운영중 요청할 분봉 종류 MAX_SAVE_CANDLE_COUNT = (STOP_LOSS_CALCULATE_DAY + 1) * 140 # 3분봉 기준 저장 분봉 갯수 MAESU_TOTAL_PRICE = [MAESU_UNIT * 1, MAESU_UNIT * 1, MAESU_UNIT * 1, MAESU_UNIT * 1] # 추가 매수 진행시 stoploss 및 stopplus 퍼센티지 변경 # 추가 매수 어느 단계에서든지 손절금액은 확정적이여야 함 # 세금 수수료 별도 계산 BASIC_STOP_LOSS_PERCENT = -0.6 STOP_PLUS_PER_MAESU_COUNT = [10, 10, 10, 10] STOP_LOSS_PER_MAESU_COUNT = [BASIC_STOP_LOSS_PERCENT, BASIC_STOP_LOSS_PERCENT, BASIC_STOP_LOSS_PERCENT, BASIC_STOP_LOSS_PERCENT] EXCEPTION_LIST = ['035480'] # 장기 보유 종목 번호 리스트 ex) EXCEPTION_LIST = ['034220'] ################################################################################################### TEST_MODE = False # 주의 TEST_MODE 를 True 로 하면 1주 단위로 삼o ################################################################################################### # for slack bot SLACK_BOT_ENABLED = True SLACK_BOT_TOKEN = "xoxb-1714142869761-1701528609762-glK9C3yZLPbAcWCBFdRy91Eb" SLACK_BOT_CHANNEL = "주식" ################################################################################################### # for google spread GOOGLE_SPREAD_AUTH_JSON_FILE = 'python-kiwoom-ac25d8a75873.json' GOOGLE_SPREAD_SHEET_NAME = 'kw3_trade'
def lex_lambda_handler(event, context): intent_name = event['currentIntent']['name'] parameters = event['currentIntent']['slots'] attributes = event['sessionAttributes'] if event['sessionAttributes'] is not None else {} response = init_contact(intent_name, parameters, attributes) return response def init_contact(intent_name, parameters, attributes): first_name = parameters.get('FirstName') last_name = parameters.get('LastName') prev_first_name = attributes.get('FirstName') prev_last_name = attributes.get('LastName') if first_name is None and prev_first_name is not None: parameters['FirstName'] = prev_first_name if last_name is None and prev_last_name is not None: parameters['LastName'] = prev_last_name if parameters['FirstName'] is not None and parameters['LastName'] is not None: response = intent_delegation(intent_name, parameters, attributes) elif parameters['FirstName'] is None: response = intent_elicitation(intent_name, parameters, attributes, 'FirstName') elif parameters['LastName'] is None: response = intent_elicitation(intent_name, parameters, attributes, 'LastName') return response ##### # lex response helper functions ##### def intent_success(intent_name, parameters, attributes): return { 'sessionAttributes': attributes, 'dialogAction': { 'type': 'Close', 'fulfillmentState': 'Fulfilled' } } def intent_failure(intent_name, parameters, attributes, message): return { 'dialogAction': { 'type': 'Close', 'fulfillmentState': 'Failed', 'message': { 'contentType': 'PlainText', 'content': message } } } def intent_delegation(intent_name, parameters, attributes): return { 'sessionAttributes': attributes, 'dialogAction': { 'type': 'Delegate', 'slots': parameters, } } def intent_elicitation(intent_name, parameters, attributes, parameter_name): return { 'sessionAttributes': attributes, 'dialogAction': { 'type': 'ElicitSlot', 'intentName': intent_name, 'slots': parameters, 'slotToElicit': parameter_name } }
# Copyright (C) 2018 Henrique Pereira Coutada Miranda # All rights reserved. # # This file is part of yambopy # # """ submodule with classes to read BSE optical absorption spectra claculations and information about the excitonic states """
BLACK = (0, 0, 0) GREY = (142, 142, 142) RED = (200, 72, 72) ORANGE = (198, 108, 58) BROWN = (180, 122, 48) YELLOW = (162, 162, 42) GREEN = (72, 160, 72) BLUE = (66, 72, 200)
#!/usr/bin/env python def square_gen(is_true): i = 0 while True: yield i**2 i += 1 g = square_gen(False) print(next(g)) print(next(g)) print(next(g))
class A: def __bool__(self): print('__bool__') return True def __len__(self): print('__len__') return 1 class B: def __len__(self): print('__len__') return 0 print(bool(A())) print(len(A())) print(bool(B())) print(len(B()))
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None c = 0 class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: global c return_head = head prev = ListNode(0) prev.next = return_head c = 0 print(n) while(head): temp = head while(c != n): print("UP TOP") temp = temp.next if temp: c += 1 print(temp.val,c) # input() else: c += 1 print("NONE DA") break # if temp == None: # if n == 1: # print("INGA DA baade") # prev = head # prev = prev.next # return prev # else: # prev.next = prev.next.next # return return_head if temp == None: # fake_head = return_head # c = 0 # while(c !=n): # if fake_head == None: # break # else: # c += 1 # fake_head = fake_head.next # if c == n: # if return_head.next == None: # prev = head # prev = prev.next # return prev # else: # prev.next = prev.next.next # head1 = prev.next # return head1 prev.next = prev.next.next head1 = prev.next return head1 else: print("Down here") c = 0 prev = head head = head.next print(prev.val) print(head.val) t1 = ListNode(1) t2 = ListNode(2) # t3 = ListNode(9) t1.next = t2 # t2.next = t3 l1 = t1 s = Solution() ans = s.removeNthFromEnd(l1,2) while(ans): print(ans.val) ans = ans.next
d1 = {1:'Sugandh', 2:'Divya', 3:'Mintoo'} print("deleting a key from the dictionary...") del d1[3] print(d1) print("deleting the same key again...") del d1[3] print(d1)
class ObtenedorDeEntrada: def getEntrada(self): f = open ('Entrada.txt','r') entrada = f.read() print(entrada) f.close() return entrada #input("Introduce el texto\n")
{ "name": "train-nn", "s3_path": "s3://tht-spark/executables/SDG_Data_Technologies_Model.py", "executors": 2, }
# parameters of the system # data files temp = np.load('./data/temp_norm.npy') y = np.load('./data/total_load_norm.npy') load_meters = np.load('./data/load_meters_norm.npy') # system parameters T, num_meters = load_meters.shape num_samples = T # training parameters hist_samples = 24 train_samples = int(0.8 * num_samples) test_samples_a = int(0.1 * num_samples) use_mse = False if use_mse: loss_f = 'mean_squared_error' loss = 'mse' else: loss_f = 'mean_absolute_error' loss = 'mae' early_stopping = EarlyStopping(monitor='val_loss', patience=10, mode='min', restore_best_weights=False, min_delta=0.001)
datas = { 'style' : 'sys', 'parent' :'boost', 'prefix' :['boost','simd'], }
class Solution: def maxProfit(self, prices: List[int]) -> int: profit = 0 buy = math.inf for price in prices: if price < buy: buy = price elif (p := price - buy) > profit: profit = p return profit
def maior_elemento(lista): elemento_ref = lista[0] maior_elemento = 0 for i in lista: if i >= elemento_ref: maior_elemento = i return maior_elemento
#!/usr/bin/env python # Copyright JS Foundation and other contributors, http://js.foundation # # 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 _constants: default_test_count = 100 # The default value of --test-count option default_seed = 10000 # The default value of random seed test_case_in_a_file = 700 # Maximum number of test for each file operand_count_max = 11 # The --operand-count option's maximum value operand_count_min = 2 # The --operand-count option's minimum value max = (1 << 53) - 1 # The max value of random number (See also Number.MAX_SAFE_INTEGER) min = - 1 * max # The min value of random number (See also Number.MIN_SAFE_INTEGER) bitmax = (1 << 31) - 1 # The max value of random number for bitwise operations bitmin = - bitmax - 1 # The min value of random number for bitwise operations uint32max = (1 << 32) - 1 # The max value of random number for unsigned right shift (See also unsigned int 32) uint32min = 0 # The min value of random number for unsigned right shift (See also unsigned int 32) bitmax_exposant = 31 # Maximum number for safely shifting an integer in python to # be precise for JS 32 bit numbers
pjs_setting = {"hyperopt" :{"AGENT_TYPE":'"randomwalk"', "CIRCLE_TYPE":'"line"', "min_n_circle":1000, "max_n_circle":4000}, "gaopt" :{"AGENT_TYPE":'"ga"', "CIRCLE_TYPE":'"normal_sw"', "min_n_circle":500, "max_n_circle":3000}, "bayesopt" :{"AGENT_TYPE":'"randomwalk"', "CIRCLE_TYPE":'"quad"', "min_n_circle":1000, "max_n_circle":3000}, "randomopt" :{"AGENT_TYPE":'"random"', "CIRCLE_TYPE":'"normal"', "min_n_circle":50, "max_n_circle":500}, } n_iter_setting = {"min":0, "max":256} additional_head = """ <style> .bk-root {width:1000px; margin-left:auto; margin-right:auto;} #bg { position:fixed; top:0; left:0; width:100%; height:100%; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.6.6/processing.js"></script> """ pjs = """ <script type="application/processing"> class Circle{ float x, y; float radius; color linecolor; //color fillcolor; float alpha; String type; Circle(float init_x, float init_y, float init_radius, float init_alpha, color init_linecolor, String init_type) { x = init_x; y = init_y; radius = init_radius; alpha = init_alpha; linecolor = init_linecolor; //fillcolor = init_fillcolor; type = init_type; } void show() { stroke(linecolor, alpha); if (type == "normal"){ noFill(); ellipse(x, y, radius*2, radius*2); } if (type == "normal_sw"){ noFill(); strokeWeight(random(0.5,5)); ellipse(x, y, radius*2, radius*2); } else if (type == "line"){ float angle_step = 25; for (float angle=0; angle <= 360*2; angle+=angle_step) { float rad = radians(angle); float rad_next = radians(angle+angle_step*random(0.8,1.2)); strokeWeight(random(1,2)); line(x+radius*cos(rad), y+radius*sin(rad), x+radius*cos(rad_next)+rad*random(1), y+radius*sin(rad_next)+rad*random(1)); if (angle > random(360, 720)){ break; } } } else if (type == "quad"){ float angle_step = 17; beginShape(QUAD_STRIP); for (float angle=0; angle <= 360; angle+=angle_step) { if (0.8 > random(1)){ fill(#ffffff, random(0,50)); stroke(linecolor, alpha); } else{ noFill(); noStroke(); } float rad = radians(angle); vertex(x+radius*cos(rad)+rad*random(1), y+radius*sin(rad)+rad*random(1)); } endShape(); } } } class Agent{ int time; PVector cr_pos; PVector[] poss = {}; String type; float x, y; float rd_max, rw_seed, rw_step, rad; Agent(float init_x, float init_y, String init_type){ cr_pos = new PVector(init_x, init_y); poss = (PVector[])append(poss, cr_pos); time = 0; type = init_type; rd_max = 100; rw_seed = 1; rw_step = (disp_width+disp_height)/50; } void step(){ // algorism if (type == "random"){ x = random(rd_max); x = map(x, 0, rd_max, 0, disp_width); y = random(rd_max); y = map(y, 0, rd_max, 0, disp_height); } else if (type == "randomwalk"){ rad = random(rd_max); rad = map(rad, 0, 1, 0, 2*PI); x = poss[time].x + rw_step*cos(rad); y = poss[time].y + rw_step*sin(rad); } else if (type == "ga"){ float r = random(1); if ((time < 10) || r < 0.05){ x = random(rd_max); x = map(x, 0, rd_max, 0, disp_width); y = random(rd_max); y = map(y, 0, rd_max, 0, disp_height); } else{ int p_0 = int(random(0, time)); int p_1 = int(random(0, time)); //float w = random(1); //x = w*poss[p_0].x + (1-w)*poss[p_1].x; //y = w*poss[p_0].y + (1-w)*poss[p_1].y; x = poss[p_0].x + poss[p_1].x; y = poss[p_0].y + poss[p_1].y; } } // for out of screen if (abs(x) > disp_width*1.5){ x = x * 0.5; } if (abs(y) > disp_width*1.5){ y = y * 0.5; } cr_pos = new PVector(x, y); poss = (PVector[])append(poss, cr_pos); time ++; } } int N_CIRCLE = REP_N_CIRCLE; String AGENT_TYPE = REP_AGENT_TYPE; String CIRCLE_TYPE = REP_CIRCLE_TYPE; Circle[] circles = {}; Agent agent; float disp_width, disp_height; void setup() { size(innerWidth, innerHeight); colorMode(RGB, 255, 255, 255, 100); background(#f2f2f2); smooth(); noLoop(); disp_width = innerWidth; disp_height = innerHeight; agent = new Agent(disp_width/2, disp_height/2, AGENT_TYPE); } void draw() { for (int i = 0; i < N_CIRCLE; i++) { agent.step(); float radius = random(1, 150); //float radius = 300; float alpha = 100; color linecolor = #b7b7b7; Circle circle = new Circle(agent.cr_pos.x, agent.cr_pos.y, radius, alpha, linecolor, CIRCLE_TYPE); circles = (Circle[])append(circles, circle); } for (int i = 0; i < N_CIRCLE; i++) { Circle circle = circles[i]; circle.show(); } } </script> <canvas id="bg"></canvas> """
# 28. Implement strStr() class Solution: def strStr(self, haystack: str, needle: str) -> int: """ Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. """ if not len(needle): return 0 s = needle + '$' + haystack n = len(s) z = [0 for _ in range(n)] left = right = 0 for index in range(1, n): x = min(z[index - left], right - index + 1) if index <= right else 0 while x + index < n and s[x] == s[x + index]: x += 1 z[index] = x if x == len(needle): return index - len(needle) - 1 if x + index - 1 > right: left, right = index, x + index - 1 return -1
for c in range(1, 10): print(c) print('FIM') w = 1 while w < 10: print(w) w = w +1 print('FIM') for i in range(1, 5): n = int(input('Digite um número: ')) print('FIM') num = 1 while num != 0: num = int(input('Digite um número: ')) print('FIM') r = 'S' while r == 'S': number = int(input('Digite um número: ')) r = str(input('Continuar? [S/N]: ')).upper() print('FIM') numero = 1 par = impar = 0 while numero != 0: numero = int(input('Digite um número: ')) if numero != 0: if numero % 2 == 0: par +=1 else: impar += 1 print('Você digitou {} números pares, e {} números ímpares.'.format(par, impar))
#!/usr/bin/python #coding=utf-8 # 稳定排序,算法时间复杂度O(n^2) arr = [1,3,4,2,8,0,3,6,14,9] def sort(arr): current = None for i in range(len(arr)-1): current = arr[ i+1 ] preIndex = i while ( preIndex >= 0 and current < arr[preIndex] ): arr[preIndex+1] = arr[preIndex] preIndex -= 1 arr[ preIndex+1 ] = current return arr print("over") print( str(sort(arr)) )
__version__ = "11.0.2-2022.02.08" if __name__ == "__main__": print(__version__)
array = [3,5,-4,8,11,1,-1,6] targetSum = 10 # def twoNumberSum(array, targetSum): # # Write your code here. # arrayOut = [] # for num1 in array: # for num2 in array: # if (num1+num2==targetSum) and (num1 != num2): # arrayOut.append(num1) # arrayOut.append(num2) # finalList =sorted(list(set(arrayOut))) # return finalList # def twoNumberSum(array, targetSum): # # Write your code here. # arrayOut =[] # newDict = dict.fromkeys(array) # for num1 in newDict: # num2 = targetSum- num1 # if (num2 in newDict) and (num1 != num2): # arrayOut.append(num1) # arrayOut.append(num2) # finalList =sorted(arrayOut) # return finalList # return arrayOut def twoNumberSum(array, targetSum): # Write your code here. arrayOut =[] newDict = {} for num1 in array: num2 = targetSum- num1 if (num2 in newDict): arrayOut.append(num1) arrayOut.append(num2) finalList =sorted(arrayOut) return finalList else: newDict[num1]=True return arrayOut # def twoNumberSum(array, targetSum): # # Write your code here. # array.sort() # left =0 # right = len(array) -1 # while (left < right): # currSum = array[left] + array[right] # if currSum == targetSum: # return [array[left],array[right]] # elif currSum < targetSum: # left += 1 # else: # right -= 1 # return [] print(twoNumberSum(array, targetSum))
class Annotation: def __init__(self, val, min_y, max_y, min_x, max_x): self.val = val self.min_y = min_y self.max_y = max_y self.min_x = min_x self.max_x = max_x class Bitmap: def __init__(self, min_y, max_y, min_x, max_x): self.min_y = min_y self.max_y = max_y self.min_x = min_x self.max_x = max_x height = max_y - min_y + 1 width = max_x - min_x + 1 self.a = [[False for _ in range(width)] for _ in range(height)] def get(self, y, x): if self.min_y <= y <= self.max_y and self.min_x <= x <= self.max_x: return self.a[y - self.min_y][x - self.min_x] else: return False def set(self, y, x, val): self.a[y - self.min_y][x - self.min_x] = val def annotate_picture(vectors): if len(vectors) == 0: return [] bitmap = vectors_to_bitmap(vectors) annotations = [] annotations += annotate_numbers(bitmap) return annotations def vectors_to_bitmap(vectors): min_x = 10000 max_x = -10000 min_y = 10000 max_y = -10000 for x, y in vectors: min_x = min(min_x, x) max_x = max(max_x, x) min_y = min(min_y, y) max_y = max(max_y, y) bitmap = Bitmap(min_y, max_y, min_x, max_x) for x, y in vectors: bitmap.set(y, x, True) return bitmap def annotate_numbers(a): annotations = [] for y in range(a.min_y, a.max_y + 1): for x in range(a.min_x, a.max_x + 1): # .# # #? # 左上にこういう構造が必要 if not (not a.get(y, x) and a.get(y, x + 1) and a.get(y + 1, x)): continue # 下方向にどれだけ白が続くか h = 0 while a.get(y + h + 1, x): h += 1 # 右方向にどれだけ白が続くか w = 0 while a.get(y, x + w + 1): w += 1 if not 0 <= h - w <= 1: continue d = w # 正方形の一辺の長さ if not check_isolated(a, y, y + d, x, x + d): continue num = 0 for dy in range(d): for dx in range(d): if a.get(y + 1 + dy, x + 1 + dx): num += 1 << (dy * d + dx) if h - w == 1: num *= -1 annotations.append(Annotation(num, y, y + h, x, x + w)) erase_rectangle(a, y, y + h, x, x + w) return annotations def erase_rectangle(a, min_y, max_y, min_x, max_x): for y in range(min_y, max_y + 1): for x in range(min_x, max_x + 1): a.set(y, x, False) def check_isolated(a, min_y, max_y, min_x, max_x): """ [min_y, max_y] × [min_x, max_x] の小長方形の周り 1 ピクセルがすべて黒であるかチェック。 :param a: :param min_y: :param max_y: :param min_x: :param max_x: :return: """ for y in range(min_y - 1, max_y + 2): if a.get(y, min_x - 1) or a.get(y, max_x + 1): return False for x in range(min_x - 1, max_x + 2): if a.get(min_y - 1, x) or a.get(max_y + 1, x): return False return True
# Print multiplication tables # 1 2 3 4 .. 10 # 2 4 6 8 20 # 3 6 9 12 30 # .. .. .. .. .. for i in range(1, 11): for j in range(1, 11): print(str(j * i) + '\t', end='') print('')
# -------------- ##File path for the file file_path #Code starts here def read_file(path): file=open(file_path,'r') sentence=file.readline() file.close() return sentence sample_message=read_file(file_path) # -------------- #Code starts here file_path_1,file_path_2 message_1=read_file(file_path_1) message_2=read_file(file_path_2) print(message_1) print(message_2) def fuse_msg(message_a,message_b): int_message_a = int(message_a) int_message_b = int(message_b) quotient=int_message_b//int_message_a return str(quotient) secret_msg_1=fuse_msg(message_1,message_2) print(secret_msg_1) # -------------- #Code starts here file_path_3 message_3=read_file(file_path_3) print(message_3) def substitute_msg(message_c): sub =' ' if message_c=='Red': sub = 'Army General' return sub elif message_c=='Green': sub = 'Data Scientist' return sub elif message_c=='Blue': sub = 'Marine Biologist' return sub secret_msg_2=substitute_msg(message_3) print(secret_msg_2) # -------------- # File path for message 4 and message 5 file_path_4 file_path_5 #Code starts here message_4=read_file(file_path_4) message_5=read_file(file_path_5) print(message_4) print(message_5) def compare_msg(message_d,message_e): a_list=message_d.split() print(a_list) b_list=message_e.split() print(b_list) c_list= [i for i in a_list if i not in b_list] print(c_list) final_msg=" ".join(c_list) return final_msg secret_msg_3=compare_msg(message_4,message_5) print(secret_msg_3) # -------------- #Code starts here file_path_6 message_6=read_file(file_path_6) print(message_6) def extract_msg(message_f): a_list=message_f.split() print(a_list) # lambda function for even words even_word=lambda x:((len(x)%2)==0) # filter() to filter out even words b_list=list(filter(even_word,a_list)) print(b_list) final_msg=" ".join(b_list) return final_msg secret_msg_4=extract_msg(message_6) print(secret_msg_4) # -------------- #Secret message parts in the correct order message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] final_path= user_data_dir + '/secret_message.txt' #Code starts here secret_msg=" ".join(message_parts) def write_file(secret_msg,path): file= open(path,'a+') file.write(secret_msg) file.close() write_file(secret_msg,final_path) print(secret_msg)
# Python > Sets > The Captain's Room # Out of a list of room numbers, determine the number of the captain's room. # # https://www.hackerrank.com/challenges/py-the-captains-room/problem # k = int(input()) rooms = list(map(int, input().split())) a = set() room_group = set() for room in rooms: if room in a: room_group.add(room) else: a.add(room) a = a - room_group print(a.pop())
class Config: device = 'cpu' RBF_url = "https://github.com/Practical-AI/deep_utils/releases/download/0.2.0/version-RFB-320.pth" RBF_cache = 'weights/vision/face_detection/ultra-light/torch/RBF/version-RFB-320.pth' RBF = None slim_url = "https://github.com/Practical-AI/deep_utils/releases/download/0.2.0/version-slim-320.pth" slim_cache = 'weights/vision/face_detection/ultra-light/torch/slim/version-slim-320.pth' slim = None
alphabet = """1 2 3 4 5 6 7 8 9 10 11 12 """
'''https://leetcode.com/problems/unique-paths/''' class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [1 for i in range(m)] for i in range(1,n): for j in range(1,m): dp[j] += dp[j-1] return dp[-1]
# Time: O(n) # Space: O(1) class Solution(object): def optimalDivision(self, nums): """ :type nums: List[int] :rtype: str """ if len(nums) == 1: return str(nums[0]) if len(nums) == 2: return str(nums[0]) + "/" + str(nums[1]) result = [str(nums[0]) + "/(" + str(nums[1])] for i in range(2, len(nums)): result += "/" + str(nums[i]) result += ")" return "".join(result)
# ANALISADOR DE EXPRESSÕES NUMÉRICAS """Verifica se o número de parênteses abertos corresponde ao número de parênteses fechados.""" exp = '((a+(b/c)) * ( f - (c-d + e) ) ^3 + )4)' #exp = str(input('Digite uma expressão: _ ')).strip() print(f'Você digitou a expressão: \033[1;30;45m {exp} \033[m.') # fatiando a string em caracteres fatia = list() for i in exp: fatia.append(i) abriu = fatia.count('(') # qtd de parênteses abertos fechou = fatia.count(')') # qtd de parênteses fechados if abriu != fechou: # número diferente de parênteses abertos e fechados # expressão inválida! print('Essa expressão é \033[1;30;41m inválida! \033[m') # exibe se foram abertos ou fechados mais parênteses if abriu > fechou: print(f'Você abriu {abriu} parênteses mas fechou apenas {fechou}.') else: print(f'Você fechou {fechou} parênteses mas apenas {abriu} foram abertos.') else: # número igual de parênteses abertos e fechados # expressão válida! print('Essa expressão é \033[1;30;44m válida! \033[m') print(f'Você abriu e fechou {abriu} parênteses.') print('=' * 30) print('Solução alternativa do Guanabara') pilha = [] # empilhamento de parênteses for sym in exp: # varre a string de expressão if sym == '(': # encontrou um parênteses aberto, então adiciona-o à pilha pilha.append(sym) elif sym == ')': # encontrou um parênteses fechado if len(pilha) > 0: # se a pilha já contiver elementos, remove um item da lista pilha.pop() else: # caso contrário, adiciona o parênteses fechado pilha.append(sym) # ideia geral: cada parênteses aberto é inserido na pilha e cada # parênteses fechado remove um parênteses aberto. a pilha correta, # portanto, não deve conter elementos! if len(pilha) == 0: # expressão válida! print('Essa expressão é \033[1;30;44m válida! \033[m') else: # expressão inválida! print('Essa expressão é \033[1;30;41m inválida! \033[m') print('Fim do programa (:')
experiments_20 = { 'data': {'n_experiments': 20, 'max_set_size': 500, 'network_filename': 'H_sapiens.net', #'S_cerevisiae.net' 'directed_interactions_filename': 'KPI_dataset', 'sources_filename': 'drug_targets.txt', 'terminals_filename': 'drug_expressions.txt', 'load_prop_scores': False, 'save_prop_scores': False, 'balance_dataset': True, 'prop_scores_filename': 'balanced_kpi_prop_scores', 'random_seed': 0, 'normalization_method': 'power', # Standard, Power 'split_type': 'normal'}, # 'regular'/harsh 'propagation': {'alpha': 0.8, 'eps': 1e-6, 'n_iterations': 200}, 'model': {'feature_extractor_layers': [64, 32], 'classifier_layers': [64, 32], 'pulling_func': 'mean', 'exp_emb_size': 4, 'feature_extractor_dropout': 0, 'classifier_dropout': 0, 'pair_degree_feature': 0 }, 'train': {'intermediate_loss_weight': 0, 'intermediate_loss_type': 'BCE', 'focal_gamma': 1, 'train_val_test_split': [0.66, 0.14, 0.2], # sum([train, val, test])=1 'train_batch_size': 32, 'test_batch_size': 32, 'n_epochs': 1000, 'eval_interval': 3, 'learning_rate': 1e-3, 'max_evals_no_imp': 3, 'optimizer' : 'ADAMW' # ADAM/WADAM }} experiments_50 = { 'data': {'n_experiments': 50, 'max_set_size': 500, 'network_filename': 'H_sapiens.net', 'directed_interactions_filename': 'KPI_dataset', 'sources_filename': 'drug_targets.txt', 'terminals_filename': 'drug_expressions.txt', 'load_prop_scores': True, 'save_prop_scores': False, 'prop_scores_filename': 'balanced_kpi_prop_scores', 'random_seed': 0, 'normalization_method': 'standard' }, 'propagation': {'alpha': 0.8, 'eps': 1e-6, 'n_iterations': 200}, 'model': {'feature_extractor_layers': [128, 64], 'classifier_layers': [128, 64], 'pulling_func': 'mean', 'exp_emb_size': 12, 'feature_extractor_dropout': 0, 'classifier_dropout': 0, 'pair_degree_feature': 0 }, 'train': {'intermediate_loss_weight': 0.5, 'intermediate_loss_type': 'BCE', 'focal_gamma': 1, 'train_val_test_split': [0.66, 0.14, 0.2], # sum([train, val, test])=1 'train_batch_size': 32, 'test_batch_size': 32, 'n_epochs': 4, 'eval_interval': 2, 'learning_rate': 5e-4, 'max_evals_no_imp': 3, 'optimizer' : 'ADAMW' # ADAM/WADAM }} experiments_0 = { 'data': {'n_experiments': 0, 'max_set_size': 500, 'network_filename': 'H_sapiens.net', 'directed_interactions_filename': ['KPI'], 'sources_filename': 'drug_targets.txt', 'terminals_filename': 'drug_expressions.txt', 'load_prop_scores': True, 'save_prop_scores': False, 'balance_dataset': True, 'prop_scores_filename': 'drug_KPI_0', 'random_seed': 0, 'normalization_method': 'power', # Standard, Power 'split_type': 'normal'}, # 'regular'/harsh 'propagation': {'alpha': 0.8, 'eps': 1e-6, 'n_iterations': 200}, 'model': {'feature_extractor_layers': [128, 64], 'classifier_layers': [64], 'pulling_func': 'mean', 'exp_emb_size': 16, 'feature_extractor_dropout': 0, 'classifier_dropout': 0, 'pair_degree_feature': 0, }, 'train': {'intermediate_loss_weight': 0.5, 'intermediate_loss_type': 'BCE', 'focal_gamma': 1, 'train_val_test_split': [0.66, 0.14, 0.2], # sum([train, val, test])=1 'train_batch_size': 4, 'test_batch_size': 32, 'n_epochs': 4, 'eval_interval': 2, 'learning_rate': 1e-3, 'max_evals_no_imp': 3, 'optimizer': 'ADAMW' # ADAM/WADAM }} experiments_all_datasets = { 'data': {'n_experiments': 0, 'max_set_size': 500, 'network_filename': 'H_sapiens.net', 'directed_interactions_filename': ['KPI', 'STKE', 'EGFR', 'E3','PDI'], 'sources_filename': 'drug_targets.txt', 'terminals_filename': 'drug_expressions.txt', 'load_prop_scores': True, 'save_prop_scores': False, 'balance_dataset': True, 'prop_scores_filename': 'balanced_KPI_STKE_EGFR_E3', 'random_seed': 0, 'normalization_method': 'power', # Standard, Power 'split_type': 'normal'}, # 'regular'/harsh 'propagation': {'alpha': 0.8, 'eps': 1e-6, 'n_iterations': 200}, 'model': {'feature_extractor_layers': [64, 32, 16], 'classifier_layers': [32, 16], 'pulling_func': 'mean', 'exp_emb_size': 12, 'feature_extractor_dropout': 0, 'classifier_dropout': 0, 'pair_degree_feature': 0, }, 'train': {'intermediate_loss_weight': 0.95, 'intermediate_loss_type': 'BCE', 'focal_gamma': 1, 'train_val_test_split': [0.66, 0.14, 0.2], # sum([train, val, test])=1 'train_batch_size': 8, 'test_batch_size': 8, 'n_epochs': 2000, 'eval_interval': 2, 'learning_rate': 1e-3, 'max_evals_no_imp': 15, }}
def notas(*n, sit=False): """ Analisa as notas e situação de vários alunos. :param n: uma ou mais notas dos alunos. :param sit: Opcional. Apresenta a situação. :return: dicionário com várias informações da turma. """ dic={} dic['total'] = len(n) dic['maior'] = max(n) dic['menor'] = min(n) dic['media'] = (sum(n)/len(n)) if sit is True: #ou if sit: if dic['media'] >= 7: dic['situação'] = 'BOM!' elif dic['media'] >= 5: #elif já considera a condição anterior. dic['situação'] = 'REGULAR!!' elif dic['media'] < 5: dic['situação'] = 'RUIM!!' return dic resp = notas(3.0, 6, 10, 0, 5.6, sit=True) print(resp) help(notas)
# 网络带宽计算 # print(100 / 8) bandwidth = 100 ratio = 8 print(bandwidth / ratio)
""" Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. """ org = [1,2,3,4,5,6,7] steps = 3 lis1 = org[steps+1:] lis2 = org[0:steps+1] print(lis1+lis2)
#Esercizio: Scrivere un programma in Python che calcola il triangolo di tartaglia #def tartaglia(stop): # if(stop < 0): # return 1 # return tartaglia(stop-1)+stop #print(tartaglia(5)) #Per trovare i numeri di fibonacci bisogna sommare i numeri del triangolo di tartaglia in diagonale, il primo è 1 il secondo è 1 il terzo è 2 da 1+1 e così via: # 1 1 2 3 Seguendo le diagonali immaginarie si vede che il primo 1 risulta 1 il secondo 1 a sinistra non ha nessuno che copra la sua diagonale a destra e quindi 1+0=1 poi 1+1=2 e in diagonale 1+2=3 # 1 # 1 1 # 1 2 1 # 1 3 3 1 # 1 4 6 4 1 # 1 5 10 10 5 1 #Adesso funziona!!! def generaTriangolo(stop): #stop è la linea di arresto v = [0]*(stop+1) #come si definisce un vettore?così va bene v[0] = 1 for i in range(0,stop): #Per tutte le posizioni del vettore se i è 0 ci metto uno altrimenti faccio ogni volta la copia del vettore effettuo un ciclo for da 1 a i+1 e se tempVet[c]!=0 stampo il contenuto poi aumento c di 1 if(i==0): v[i+1] = 1 print(v[i]) else: #print("Sono temp: ") tempVet = v[:] #Prima senza saperlo facevo alias cioè una copia ad indirizzo tempVet=v se modifico v modifico anche tempVet, ma con v[:] prendo una porzione di tutto il vettore effettuando una clonazione #print(tempVet) c=0 for j in range(1,(i+1)):#poi assegno a v[j] (v[1]) il valore di tempVet[j-1] (quindi 1 per il primo ciclo) + tempVet[j] (zero per il primo ciclo) quindi v[j] prende 1 e il secondo valore in v[j] è 1 e assegno al valore successivo #parlo di v[i+1] un 1 come nel triangolo di tartaglia poi stampo tempVet[c] (che era incrementato di 1)e quindi ottengo una vera porcheria che però funziona. if(tempVet[c]!=0): print(tempVet[c], sep=' ', end=" ", flush=True) c = c+1 #print("TEMPdiJ_PRIMA: " + str(tempVet[j])) v[j] = tempVet[j-1] + tempVet[j] #ci credo che non fa, tempVet[j] viene incrementato senza motivo di 1 dopo la somma col suo precedente Il motivo era il cosidetto alias #print("TEMPdiJ_DOPO: " + str(tempVet[j])) #print("v[j]["+str(j)+"] prende " + "tempVet[j-1]["+str(j-1)+"]=" + str(tempVet[j-1]) + " + tempVet[j]["+str(j)+"]="+str(tempVet[j]) + " => v[j]: " + str(v[j])) v[i+1] = 1 print(tempVet[c], sep=' ', end=" ", flush=True) c=0 #print("Sono V: ") #print(v) print() print(generaTriangolo(15)) #def tartaglia(n,k): # if n<1 or k<1: # return 1; # return 7 #print (tartaglia(1,3)) #Nel triangolo di tartaglia si vede che le righe dispari hanno un valore centrale #Il valore centrale forse viene generato seguendo una qualche regola che non richiede che venga calcolato tutto il triangolo #I valori centrali a me conosciuti sono: 1,2,6,20,70.. #Visto che n corrisponde alla riga del triangolo e k alla posizione sapendo che i valori centrali sopra esposti sono la riga dispari si potrebbe trovare tutti i valori vicini partendo da quello centrale più vicino #ad n senza calcolare tutto il triangolo di tartaglia, per esempio con n=4 basta sommarvi 1 spostandoci quindi sulla linea dispari numerata come quinta, su questa linea sappiamo esserci il 6 perchè 1 è alla prima linea, la seconda si #salta sulla terza c'è il 2 e la quarta si salta e sulla 5 c'è il 6, quindi bisogna ottenere una formula per ottenere da n la posizione nel vettore in cui beccare il valore, esempio 5-2 = 3 in 3 posizione abbiamo il 6 la formula #corrisponde a se (n+1) è dispari faccio(n+1)//2 altrimenti n//2, ottenendo la posizione del vettore in cui c'è il valore centrale del triangolo comunque questo non ci permette di ottenere tutti i valori centrali del triangolo #Nel triangolo di tartaglia si nota che ci sono anche i numeri primi
#!/usr/bin/env python # -*- coding: utf-8 -*- student_list_file = "alunos.txt" shelf_file = "shelf.shelf" included_files_location = u"/home/bjorn/Dropbox/python_packages/bio_info_questions/bio_info_questions/files_to_be_included" password_to_open_exam = u"zyxpep93" password_to_see_correct_exam = u"LWQsGHefywehfLSFKG6Q3W" exam_folder = "./empty_exams" start_separator = u"\n=========== start of exame =====================================================\n" question_separator = u"\n*********** Question {} ***********\n" endseparator = u"\n========== end of exame ========================================================" header = u'''================================================================================ Genética Molecular e Bioinformática 2704N9 | Licenciatura em Bioquímica Nome {name} Número mecanográfico (mec) {mec} Exam date 2014-06-25|Wednesday June 25|Week 25 Unix time stamp {timestamp} ================================================================================ Instruções para o exame: Este exame tem {number_of_questions} questões. Deve responder às questões dentro neste documento. Preencha a sua resposta, substituindo os simbolos "?". Por favor NÂO MODIFIQUE MAIS NADA no exame, será corrigido automaticamente. em particular, não modifique ou remova o QuestionID, que serve para identificar as respostas certas. Instructions for completing the exam: This exam has {number_of_questions} questions. You shuld respond to these questions within this document. Fill in your answers where you find the "?" symbol(s) in each question. Please do not edit anything else, as this exam will be automatically corrected. In particular, do NOT modify the QuestionID as this is used for identifying the correct answer. '''
# pylint: disable=missing-docstring TEST = map(str, (1, 2, 3)) # [bad-builtin] TEST1 = filter(str, (1, 2, 3)) # [bad-builtin]
expected = [ { "xlink_href": "elife00013inf001", "type": "inline-graphic", "position": 1, "ordinal": 1, } ]
APIYNFLAG_YES = "Y" APIYNFLAG_NO = "N" APILOGLEVEL_NONE = "N" APILOGLEVEL_ERROR = "E" APILOGLEVEL_WARNING = "W" APILOGLEVEL_DEBUG = "D" TAPI_COMMODITY_TYPE_NONE = "N" TAPI_COMMODITY_TYPE_SPOT = "P" TAPI_COMMODITY_TYPE_FUTURES = "F" TAPI_COMMODITY_TYPE_OPTION = "O" TAPI_COMMODITY_TYPE_SPREAD_MONTH = "S" TAPI_COMMODITY_TYPE_SPREAD_COMMODITY = "M" TAPI_COMMODITY_TYPE_BUL = "U" TAPI_COMMODITY_TYPE_BER = "E" TAPI_COMMODITY_TYPE_STD = "D" TAPI_COMMODITY_TYPE_STG = "G" TAPI_COMMODITY_TYPE_PRT = "R" TAPI_COMMODITY_TYPE_BLT = "L" TAPI_COMMODITY_TYPE_BRT = "Q" TAPI_COMMODITY_TYPE_DIRECTFOREX = "X" TAPI_COMMODITY_TYPE_INDIRECTFOREX = "I" TAPI_COMMODITY_TYPE_CROSSFOREX = "C" TAPI_COMMODITY_TYPE_INDEX = "Z" TAPI_COMMODITY_TYPE_STOCK = "T" TAPI_COMMODITY_TYPE_SPOT_TRADINGDEFER = "Y" TAPI_COMMODITY_TYPE_FUTURE_LOCK = "J" TAPI_COMMODITY_TYPE_EFP = "A" TAPI_COMMODITY_TYPE_TAS = "B" TAPI_CALLPUT_FLAG_CALL = "C" TAPI_CALLPUT_FLAG_PUT = "P" TAPI_CALLPUT_FLAG_NONE = "N" TAPI_AUTHTYPE_DIRECT = "1" TAPI_AUTHTYPE_RELAY = "2"
# # PySNMP MIB module ASCEND-MIBSCRTY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBSCRTY-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:28:15 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) # configuration, = mibBuilder.importSymbols("ASCEND-MIB", "configuration") ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ObjectIdentity, IpAddress, TimeTicks, iso, Gauge32, MibIdentifier, Integer32, ModuleIdentity, Unsigned32, Bits, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "IpAddress", "TimeTicks", "iso", "Gauge32", "MibIdentifier", "Integer32", "ModuleIdentity", "Unsigned32", "Bits", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "NotificationType") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") class DisplayString(OctetString): pass mibsecurityProfile = MibIdentifier((1, 3, 6, 1, 4, 1, 529, 23, 107)) mibsecurityProfileTable = MibTable((1, 3, 6, 1, 4, 1, 529, 23, 107, 1), ) if mibBuilder.loadTexts: mibsecurityProfileTable.setStatus('mandatory') if mibBuilder.loadTexts: mibsecurityProfileTable.setDescription('A list of mibsecurityProfile profile entries.') mibsecurityProfileEntry = MibTableRow((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1), ).setIndexNames((0, "ASCEND-MIBSCRTY-MIB", "securityProfile-Name")) if mibBuilder.loadTexts: mibsecurityProfileEntry.setStatus('mandatory') if mibBuilder.loadTexts: mibsecurityProfileEntry.setDescription('A mibsecurityProfile entry containing objects that maps to the parameters of mibsecurityProfile profile.') securityProfile_Name = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 1), DisplayString()).setLabel("securityProfile-Name").setMaxAccess("readonly") if mibBuilder.loadTexts: securityProfile_Name.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_Name.setDescription('Profile name.') securityProfile_Password = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 2), DisplayString()).setLabel("securityProfile-Password").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_Password.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_Password.setDescription('Password to access the security levels defined by this profile.') securityProfile_Operations = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-Operations").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_Operations.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_Operations.setDescription('TRUE = able to do things other than look.') securityProfile_EditSecurity = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditSecurity").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditSecurity.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditSecurity.setDescription('TRUE = able to edit the security profiles.') securityProfile_EditSystem = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditSystem").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditSystem.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditSystem.setDescription('TRUE = able to edit the system profiles.') securityProfile_EditLine = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditLine").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditLine.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditLine.setDescription('TRUE = able to edit the line profile.') securityProfile_EditOwnPort = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditOwnPort").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditOwnPort.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditOwnPort.setDescription('TRUE = able to edit port associated port profile (for remote terminal).') securityProfile_EditAllPort = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditAllPort").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditAllPort.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditAllPort.setDescription('TRUE = able to edit all port profiles.') securityProfile_EditCurCall = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditCurCall").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditCurCall.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditCurCall.setDescription('TRUE = able to edit the current call profile.') securityProfile_EditOwnCall = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditOwnCall").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditOwnCall.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditOwnCall.setDescription('TRUE = able to edit port associated call profiles (for remote terminal).') securityProfile_EditComCall = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditComCall").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditComCall.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditComCall.setDescription('TRUE = able to edit the common call profiles (for remote terminal).') securityProfile_EditAllCall = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-EditAllCall").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_EditAllCall.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_EditAllCall.setDescription('TRUE = able to edit all call profiles.') securityProfile_SysDiag = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-SysDiag").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_SysDiag.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_SysDiag.setDescription('TRUE = able to perform system diagnostics.') securityProfile_OwnPortDiag = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-OwnPortDiag").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_OwnPortDiag.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_OwnPortDiag.setDescription('TRUE = able to perform port associated port diagnostics (for remote terminal).') securityProfile_AllPortDiag = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-AllPortDiag").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_AllPortDiag.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_AllPortDiag.setDescription('TRUE = able to perform port diagnostics for all ports.') securityProfile_Download = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-Download").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_Download.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_Download.setDescription('TRUE = able to download configuration.') securityProfile_Upload = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-Upload").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_Upload.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_Upload.setDescription('TRUE = able to upload configuration.') securityProfile_FieldService = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-FieldService").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_FieldService.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_FieldService.setDescription('TRUE = able to perform field service.') securityProfile_UseTacacsPlus = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2)))).setLabel("securityProfile-UseTacacsPlus").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_UseTacacsPlus.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_UseTacacsPlus.setDescription('Use TACACS+ to authenticate security level changes') securityProfile_Action_o = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 107, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noAction", 1), ("createProfile", 2), ("deleteProfile", 3)))).setLabel("securityProfile-Action-o").setMaxAccess("readwrite") if mibBuilder.loadTexts: securityProfile_Action_o.setStatus('mandatory') if mibBuilder.loadTexts: securityProfile_Action_o.setDescription('') mibBuilder.exportSymbols("ASCEND-MIBSCRTY-MIB", securityProfile_Action_o=securityProfile_Action_o, mibsecurityProfileEntry=mibsecurityProfileEntry, securityProfile_EditComCall=securityProfile_EditComCall, securityProfile_EditLine=securityProfile_EditLine, securityProfile_FieldService=securityProfile_FieldService, securityProfile_EditOwnCall=securityProfile_EditOwnCall, securityProfile_Upload=securityProfile_Upload, DisplayString=DisplayString, mibsecurityProfile=mibsecurityProfile, securityProfile_EditCurCall=securityProfile_EditCurCall, securityProfile_Name=securityProfile_Name, securityProfile_Download=securityProfile_Download, securityProfile_UseTacacsPlus=securityProfile_UseTacacsPlus, securityProfile_OwnPortDiag=securityProfile_OwnPortDiag, securityProfile_Operations=securityProfile_Operations, securityProfile_EditSecurity=securityProfile_EditSecurity, securityProfile_AllPortDiag=securityProfile_AllPortDiag, securityProfile_Password=securityProfile_Password, securityProfile_EditSystem=securityProfile_EditSystem, securityProfile_SysDiag=securityProfile_SysDiag, securityProfile_EditAllPort=securityProfile_EditAllPort, mibsecurityProfileTable=mibsecurityProfileTable, securityProfile_EditAllCall=securityProfile_EditAllCall, securityProfile_EditOwnPort=securityProfile_EditOwnPort)
while True: s = input("Ukucaj nesto: ") if s == "izlaz": break if len(s) < 3: print("Previse je kratko.") continue print("Input je zadovoljavajuce duzine.") #mozete zadavati druge komande za neki rad ovdej
pancakes = int(input()) if pancakes > 3: print("Yum!") else: #if pancakes < 3: print("Still hungry!")
users_calculation = {} def request_addition(user, num1, num2): users_calcs = users_calculation.get(user) if (users_calcs is None): users_calcs = list() users_calcs.append(num1+num2) users_calculation[user] = users_calcs def get_last_calculation(user): users_calcs = users_calculation.get(user) results = None if (users_calcs is not None and len(users_calcs) > 0): results = users_calcs.pop() return results
def x(a, b, c): p = 5 b = int(x) print(b)
def teste(v, i): valor = v incremento = i resultado = valor + incremento return resultado """ imprimindo 'a' passando os atributos '(10, 1)' """ a = teste(10, 1) print("\n") print(a) """ .............CLASSES E METODOS............. Como se escrreve: 'def didatica_tech' # letras minusculas e underline se necessario 'class DidaticaTech' # primeira letra maiuscula SEM underline uma 'class' pode ter varias 'def' 'def' dentro de 'class' PRECISA TER A PALAVRA reservada 'self' """ class DidaticaTech: def incrementa(self, v, i): valor = v incremento = i resultado = valor + incremento return resultado """ instanciando a CLASSE na VARIAVEL 'a' """ a = DidaticaTech() """ toda FUNCAO dentro de uma CLASSE é chamado de METODO chamando o METODO 'incrementa' da CLASSE 'DidaticaTech' """ b = a.incrementa(10, 1) print("\n") print(b) """ .............PARA ACESSAR A VARIAVEL DENTRO DO METODO DA CLASSE............. 'self' permite instanciar a variavel dentro do METODO para ser usada fora. """ class DidaticaTech: def incrementa(self, v, i): self.valor = v self.incremento = i self.resultado = self.valor + self.incremento return self.resultado a = DidaticaTech() b = a.incrementa(10, 1) print("\n") print(b) print(a.valor) """ .............PARA ACESSAR A VARIAVEL DENTRO DO METODO DA CLASSE............. '__init__' METODO CONSTRUTOR (funcao dentro da CLASSE) usado para inicializar variaveis. '__init__' permite instanciar os valores de 'v' e 'í' direto da CLASSE 'DidaticaTech'. a = DidaticaTech(10, 1) """ class DidaticaTech: def __init__(self, v: int, i: int): self.valor = v self.incremento = i def incrementa(self): self.valor = self.valor + self.incremento a = DidaticaTech(10, 1) b = a.incrementa() print('\n.....self.....') print(a.valor) b = a.incrementa() print(a.valor) b = a.incrementa() print(a.valor) """ .............PARA ACESSAR A VARIAVEL DENTRO DO METODO DA CLASSE com valores pre-definidos no CONSTRUTOR............. '__init__' METODO CONSTRUTOR (funcao dentro da CLASSE) usado para inicializar variaveis. '__init__' permite instanciar os valores de 'v' e 'í' direto da CLASSE 'DidaticaTech'. a = DidaticaTech() Depois de instanciarmos 'a = DidaticaTech()', quando executamos 'a.incrementa(), o que a IDE está fazendo é: 'DidaticaTech().incrementa(a, 10, 1)' """ class DidaticaTech: def __init__(self, v=10, i=1): self.valor = v self.incremento = i def incrementa(self): self.valor = self.valor + self.incremento a = DidaticaTech() b = a.incrementa() print('\n.....self pré definido no CONSTRUTOR.....') print(a.valor) b = a.incrementa() print(a.valor) b = a.incrementa() print(a.valor) b = a.incrementa() print(a.valor) """ .............FUNCAO chama FUNCAO dentro da CLASSE............. '__init__' METODO CONSTRUTOR (funcao dentro da CLASSE) usado para inicializar variaveis. '__init__' permite instanciar os valores de 'v' e 'í' direto da CLASSE 'DidaticaTech'. Exemplo: a = DidaticaTech() Depois de instanciarmos 'a = DidaticaTech()', quando executamos 'a.incrementa(), o que a IDE está fazendo é: 'DidaticaTech().incrementa(a, 10, 1)' Uma FUNCAO pode chamar outra FUNCAO dentro da CLASSE. Exemplo: def incrementa_quadrado(self): self.incrementa() self.exponencial(2) """ class DidaticaTech: def __init__(self, v=10, i=1): self.valor = v self.incremento = i self.valor_exponencial = v def incrementa(self): self.valor = self.valor + self.incremento def verifica(self): if self.valor > 12: print("Ultrapassou 12") else: print("Nao Ultrapassou 12") def exponencial(self, e): # '(self, e)' indica que o METODO 'exponencial' tem um # PARAMETRO/VALOR 'e' que deve ser passado ao ser chamado. self.valor_exponencial = self.valor**e def incrementa_quadrado(self): self.incrementa() self.exponencial(2) a = DidaticaTech() b = a.incrementa() print('\n.....self --> FUNCAO chama FUNCAO dentro da CLASSE.....') print(a.valor) print(a.verifica()) b = a.incrementa() print(a.valor) print(a.verifica()) b = a.incrementa() print(a.valor) print(a.verifica()) b = a.incrementa() print(a.valor) c = a.exponencial(3) print(a.valor_exponencial, '= a.valor_exponencial') c = a.incrementa_quadrado() print(a.valor, '= a.valor') print(a.valor_exponencial, '= valor_exponencial\n') """ .............HERANÇA............. Uma CLASSE criada HERDA tudo de uma classe já existente. Exemplo: class Calculos(DidaticaTech): """ print('.............HERANÇA.............') class Calculos(DidaticaTech): pass c = Calculos() c.incrementa() print(c.valor, '= c.valor') print(c.valor_exponencial, '= c.valor_exponencial') """ .............HERANÇA............. Uma CLASSE criada HERDA tudo de uma classe já existente. class Calculos(DidaticaTech): Herdo uma CLASSE ja existente, para nao ter que fazer novamente e acrescento o que preciso nela. Exemplo: class Calculos(DidaticaTech): def decrementa(self): self.valor = self.valor - self.incremento """ class Calculos(DidaticaTech): def decrementa(self): self.valor = self.valor - self.incremento c = Calculos() c.incrementa() print(c.valor, '= c.valor') c.decrementa() print(c.valor, '= c.valor apos rodar o "c.decrementa"') """ .............HERANÇA............. Acrescentando atributos ao metodo '__init__' fará com que o metodo '__init__'anterior deixe de existir e passe a ter apenas os atributos do atual criado. Assim alguns metodos HERDADOS podem parar de funcionar. Para que eu HERDE tb todo o '__init__' da CLASSE mãe eu uso o comando 'super' e posso alterar o valor dos atributos se quiser. Exemplo: super().__init__(v=10, i=5) """ class Calculos(DidaticaTech): def __init__(self, d=5): super().__init__(v=10, i=5) self.divisor = d def decrementa(self): self.valor = self.valor - self.incremento def divide(self): self.valor = self.valor / self.divisor c = Calculos() c.incrementa() print(c.valor, '= "c.valor" de "c.incrementa()" apos criar outro "__init__" e adicionar a ele o "__init__" da CLASSE ' 'mãe') c.decrementa() print(c.valor, '= "c.valor" de "c.decrementa()" apos criar outro "__init__" e adicionar a ele o "__init__" da CLASSE ' 'mãe') c.divide() print(c.valor, '= "c.valor" de "c.divide()" apos criar outro "__init__" e adicionar a ele o "__init__" da CLASSE mãe')
print('*'*5, 'CONVERSOR DE TEMPERATURA', '*'*5) temp = float(input('Informe a temperatura em °C: ')) f = temp*1.800 + 32 print(f'A temperatura de {temp:.1f}°C é equivalente a {f:.1f}°F.') print('*'*10, '+++++', '*'*10)
# from https://en.wikipedia.org/wiki/Test_functions_for_optimization # # takes input parameters x,y # returns value in "ans" # optimal minimum at f(3,0.5) = 0 # parameter range is -4.5 <= x,y <= 4.5 def evaluate(x,y): return (1.5 - x + x*y)**2 + (2.25 - x + x*y*y)**2 + (2.625 - x + x*y*y*y)**2 def run(self,Inputs): if abs(self.y - 0.24392555296) <= 0.00001 and abs(self.x - 0.247797586626) <= 0.00001 : print("Expected failure for testing ... x:"+str(self.x)+" | y:"+str(self.y)) raise Exception("expected failure for testing") self.ans = evaluate(self.x,self.y)
# -*- coding: utf-8 -*- def create(): resourceDict = dict() return resourceDict def addOne(resourceDict, key, value): if (len(key)<=2): return 'err' if (key[0:2]!="##"): print("key must be like '##xx' : %s " % key) return 'err' resourceDict[key] = value return 'ok'
class DuplicateTagsWarning(UserWarning): def get_warning_message(self, duplicate_tags, name): return f"Semantic tag(s) '{', '.join(duplicate_tags)}' already present on column '{name}'" class StandardTagsChangedWarning(UserWarning): def get_warning_message(self, use_standard_tags, col_name=None): changed = "added to" if use_standard_tags else "removed from" name = ('"' + col_name + '"') if col_name is not None else "your column" return f"Standard tags have been {changed} {name}" class UpgradeSchemaWarning(UserWarning): def get_warning_message(self, saved_version_str, current_schema_version): return ( "The schema version of the saved Woodwork table " "%s is greater than the latest supported %s. " "You may need to upgrade woodwork. Attempting to load Woodwork table ..." % (saved_version_str, current_schema_version) ) class OutdatedSchemaWarning(UserWarning): def get_warning_message(self, saved_version_str): return ( "The schema version of the saved Woodwork table " "%s is no longer supported by this version " "of woodwork. Attempting to load Woodwork table ..." % (saved_version_str) ) class IndexTagRemovedWarning(UserWarning): pass class TypingInfoMismatchWarning(UserWarning): def get_warning_message(self, attr, invalid_reason, object_type): return ( f"Operation performed by {attr} has invalidated the Woodwork typing information:\n " f"{invalid_reason}.\n " f"Please initialize Woodwork with {object_type}.ww.init" ) class TypeConversionError(Exception): def __init__(self, series, new_dtype, logical_type): message = f"Error converting datatype for {series.name} from type {str(series.dtype)} " message += f"to type {new_dtype}. Please confirm the underlying data is consistent with " message += f"logical type {logical_type}." super().__init__(message) class TypeConversionWarning(UserWarning): pass class ParametersIgnoredWarning(UserWarning): pass class ColumnNotPresentError(KeyError): def __init__(self, column): if isinstance(column, str): return super().__init__( f"Column with name '{column}' not found in DataFrame" ) elif isinstance(column, list): return super().__init__(f"Column(s) '{column}' not found in DataFrame") class WoodworkNotInitError(AttributeError): pass class WoodworkNotInitWarning(UserWarning): pass
""" write your first program in python """ print("helloworld in python !!")
a = float(input("1.Sayı:")) b = float(input("2.Sayı:")) c = str(input("Hangi işlemi yapmak istiyorsunuz (bolme,carpma,cikarma,toplama):")) if c == "bolme"or c == "carpma"or c == "cikarma"or c == "toplama": print(c,"işleminiz gerçekleştiriliyor...") else: print("İşleminiz gerçekleştirilemiyor.") if c == "bolme": if b != 0: #0dan farklı ise print(a/b) else: print("0'a bölünemez!") elif c == "carpma": print(a*b) elif c == "toplama": print(a+b) elif c == "cikarma": print(a-b)
def soma(n1,n2): r = n1+n2 return r def sub(n1,n2): r = n1-n2 return r def mult(n1,n2): r = n1*n2 return r def divfra(n1,n2): r = n1/n2 return r def divint(n1,n2): r = n1//n2 return r def restodiv(n1,n2): r = n1%n2 return r def raiz1(n1,n2): r = n1**(0.5) return r def raiz2(n1,n2): r = n2**(1/2) return r
# Edit and set server name and version test_server_name = '<put server name here>' test_server_version = '201X' # Edit and direct to your test folders on your server test_folder = r'\Tests' test_mkfolder = r'\Tests\New Folder' test_newfoldername = 'Renamed folder' test_renamedfolder = r'\Tests\Renamed folder' # Edit and direct to your test models on your server test_file = r'\Tests\TestModel.rvt' test_cpyfile = r'\Tests\TestModelCopy.rvt' test_mvfile = r'\Tests\TestModelMove.rvt' test_mhistory = r'\Tests\TestModel.rvt'
''' Created on Aug 8, 2017 Check permutation: Given two strings, write a method to decide if one is a permutation of the other Things to learn: - a python set orders set content - in a set, one uses == to compare same content @author: igoroya ''' def check_string_permuntation(str1, str2): if len(str1) is not len(str2): return False strset1 = {i for i in str1} strset2 = {i for i in str2} if strset1 == strset2: return True else: return False if __name__ == '__main__': str1 = 'aeiou' str2 = 'aeiuo' str3 = 'pepe' str4 = 'aeiouaeiou' print(check_string_permuntation(str1, str2)) print(check_string_permuntation(str1, str3)) print(check_string_permuntation(str1, str4))
# # PySNMP MIB module IEEE8021-MIRP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IEEE8021-MIRP-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:52:27 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, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion") ieee8021BridgeBasePortEntry, = mibBuilder.importSymbols("IEEE8021-BRIDGE-MIB", "ieee8021BridgeBasePortEntry") ieee8021PbbBackboneEdgeBridgeObjects, = mibBuilder.importSymbols("IEEE8021-PBB-MIB", "ieee8021PbbBackboneEdgeBridgeObjects") IEEE8021BridgePortNumberOrZero, = mibBuilder.importSymbols("IEEE8021-TC-MIB", "IEEE8021BridgePortNumberOrZero") VlanIdOrNone, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "VlanIdOrNone") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") systemGroup, = mibBuilder.importSymbols("SNMPv2-MIB", "systemGroup") Counter64, Counter32, NotificationType, TimeTicks, ModuleIdentity, MibIdentifier, Gauge32, ObjectIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Unsigned32, IpAddress, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "Counter32", "NotificationType", "TimeTicks", "ModuleIdentity", "MibIdentifier", "Gauge32", "ObjectIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Unsigned32", "IpAddress", "Bits") TextualConvention, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TruthValue") ieee8021MirpMib = ModuleIdentity((1, 3, 111, 2, 802, 1, 1, 23)) ieee8021MirpMib.setRevisions(('2011-04-05 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ieee8021MirpMib.setRevisionsDescriptions(('Included in IEEE Std. 802.1Qbe-2011 Copyright (C) IEEE802.1.',)) if mibBuilder.loadTexts: ieee8021MirpMib.setLastUpdated('201104050000Z') if mibBuilder.loadTexts: ieee8021MirpMib.setOrganization('IEEE 802.1 Working Group') if mibBuilder.loadTexts: ieee8021MirpMib.setContactInfo('WG-URL: http://grouper.ieee.org/groups/802/1/index.html WG-EMail: stds-802-1@ieee.org Contact: Norman Finn c/o Tony Jeffree, IEEE 802.1 Working Group Chair Postal: IEEE Standards Board 445 Hoes Lane P.O. Box 1331 Piscataway, NJ 08855-1331 USA E-mail: tony@jeffree.co.uk ') if mibBuilder.loadTexts: ieee8021MirpMib.setDescription('Multiple I-SID Registration Protocol module for managing IEEE 802.1Qbe ') ieee8021MirpMIBObjects = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 23, 1)) ieee8021MirpConformance = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 23, 2)) ieee8021MirpPortTable = MibTable((1, 3, 111, 2, 802, 1, 1, 23, 1, 1), ) if mibBuilder.loadTexts: ieee8021MirpPortTable.setReference('12.9.2') if mibBuilder.loadTexts: ieee8021MirpPortTable.setStatus('current') if mibBuilder.loadTexts: ieee8021MirpPortTable.setDescription('A table that contains controls for the Multiple I-SID Registration Protocol (MIRP) state machines for all of the Ports of a Bridge.') ieee8021MirpPortEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 23, 1, 1, 1), ) ieee8021BridgeBasePortEntry.registerAugmentions(("IEEE8021-MIRP-MIB", "ieee8021MirpPortEntry")) ieee8021MirpPortEntry.setIndexNames(*ieee8021BridgeBasePortEntry.getIndexNames()) if mibBuilder.loadTexts: ieee8021MirpPortEntry.setStatus('current') if mibBuilder.loadTexts: ieee8021MirpPortEntry.setDescription('Each entry contains the MIRP Participant controls for one Port.') ieee8021MirpPortEnabledStatus = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 23, 1, 1, 1, 1), TruthValue().clone('true')).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021MirpPortEnabledStatus.setReference('12.7.7.1, 12.7.7.2, 39.2.1.11') if mibBuilder.loadTexts: ieee8021MirpPortEnabledStatus.setStatus('current') if mibBuilder.loadTexts: ieee8021MirpPortEnabledStatus.setDescription("The state of MIRP operation on this port. The value true(1) indicates that MIRP is enabled on this port, as long as ieee8021PbbMirpEnableStatus is also enabled for this component. When false(2) but ieee8021PbbMirpEnableStatus is still enabled for the device, MIRP is disabled on this port. If MIRP is enabled on a VIP, then the MIRP Participant is enabled on that VIP's PIP. If MIRP is enabled on none of the VIPs on a PIP, then the MIRP Participant on the PIP is diabled; any MIRP packets received will be silently discarded, and no MIRP registrations will be propagated from the PIP. A transition from all VIPs on a PIP false(2) to at least one VIP on the PIP true(1) will cause a reset of all MIRP state machines on this PIP. If MIRP is enabled on any port not a VIP, then the MIRP Participant is enabled on that port. If MIRP is disabled on a non-VIP port, then MIRP packets received will be silently discarded, and no MIRP registrations will be propagated from the port. A transition from false(2) to true(1) will cause a reset of all MIRP state machines on a non-VIP port. The value of this object MUST be retained across reinitializations of the management system.") ieee8021PbbMirpEnableStatus = MibScalar((1, 3, 111, 2, 802, 1, 1, 9, 1, 1, 1, 7), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: ieee8021PbbMirpEnableStatus.setReference('12.16.1.1.3:i, 12.16.1.2.2:b') if mibBuilder.loadTexts: ieee8021PbbMirpEnableStatus.setStatus('current') if mibBuilder.loadTexts: ieee8021PbbMirpEnableStatus.setDescription('The administrative status requested by management for MIRP. The value true(1) indicates that MIRP should be enabled on this component, on all ports for which it has not been specifically disabled. When false(2), MIRP is disabled on all ports. This object affects all MIRP Applicant and Registrar state machines. A transition from false(2) to true(1) will cause a reset of all MIRP state machines on all ports. The value of this object MUST be retained across reinitializations of the management system.') ieee8021PbbMirpBvid = MibScalar((1, 3, 111, 2, 802, 1, 1, 9, 1, 1, 1, 8), VlanIdOrNone()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ieee8021PbbMirpBvid.setReference('12.16.1.1.3:j, 12.16.1.2.2:c') if mibBuilder.loadTexts: ieee8021PbbMirpBvid.setStatus('current') if mibBuilder.loadTexts: ieee8021PbbMirpBvid.setDescription('The B-VID to which received MIRPDUs are to be assigned, or 0, if they are to be sent on the CBP PVID.') ieee8021PbbMirpDestSelector = MibScalar((1, 3, 111, 2, 802, 1, 1, 9, 1, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("cbpMirpGroup", 1), ("cbpMirpVlan", 2), ("cbpMirpTable", 3))).clone('cbpMirpGroup')).setMaxAccess("readwrite") if mibBuilder.loadTexts: ieee8021PbbMirpDestSelector.setReference('Table 8-1, 12.16.1.1.3:k, 12.16.1.2.2:d') if mibBuilder.loadTexts: ieee8021PbbMirpDestSelector.setStatus('current') if mibBuilder.loadTexts: ieee8021PbbMirpDestSelector.setDescription('An enumerated value specifying what destination_address and vlan_identifier are to be used when the MIRP Participant transmits an MIRPDU towards the MAC relay entity: cbpMirpGroup (1) Use the Nearest Customer Bridge group address from Table 8-1 with the MIRP B-VID. cbpMirpVlan (2) Use the Nearest Customer Bridge group address from Table 8-1 with the Backbone VLAN Identifier field from the Backbone Service Instance table. cbpMirpTable (3) Use the Default Backbone Destination and Backbone VLAN Identifier fields from the Backbone Service Instance table. The value of this object MUST be retained across reinitializations of the management system.') ieee8021PbbMirpPnpEnable = MibScalar((1, 3, 111, 2, 802, 1, 1, 9, 1, 1, 1, 10), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: ieee8021PbbMirpPnpEnable.setReference('12.16.1.1.3:j, 12.16.1.2.2:c') if mibBuilder.loadTexts: ieee8021PbbMirpPnpEnable.setStatus('current') if mibBuilder.loadTexts: ieee8021PbbMirpPnpEnable.setDescription('A Boolean value specifying the administrative status requested by management for attaching a MIRP Participant to a PNP if and only if this system is a Backbone Edge Bridge (BEB): true(1) The BEB is to attach a MIRP Participant to exactly one Port, either a management Port with no LAN connection external to the BEB, or a PNP. false(2) No MIRP Participant is to be present on any PNP (or on the MAC Relay-facing side of a CBP). The value of this object MUST be retained across reinitializations of the management system. ') ieee8021PbbMirpPnpPortNumber = MibScalar((1, 3, 111, 2, 802, 1, 1, 9, 1, 1, 1, 11), IEEE8021BridgePortNumberOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: ieee8021PbbMirpPnpPortNumber.setReference('12.16.1.1.3:j, 12.16.1.2.2:c') if mibBuilder.loadTexts: ieee8021PbbMirpPnpPortNumber.setStatus('current') if mibBuilder.loadTexts: ieee8021PbbMirpPnpPortNumber.setDescription('The Bridge Port Number of the Provider Network Port (PNP) that has an associated MIRP Participant, or 0, if no Bridge Port has an associated MIRP Participant. This object indexes an entry in the Bridge Port Table. The system SHALL ensure that either ieee8021PbbMirpPnpPortNumber contains 0, or that the indexed ieee8021BridgeBasePortType object contains the value providerNetworkPort(3).') ieee8021MirpCompliances = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 23, 2, 1)) ieee8021MirpGroups = MibIdentifier((1, 3, 111, 2, 802, 1, 1, 23, 2, 2)) ieee8021MirpReqdGroup = ObjectGroup((1, 3, 111, 2, 802, 1, 1, 23, 2, 2, 1)).setObjects(("IEEE8021-MIRP-MIB", "ieee8021MirpPortEnabledStatus"), ("IEEE8021-MIRP-MIB", "ieee8021PbbMirpEnableStatus"), ("IEEE8021-MIRP-MIB", "ieee8021PbbMirpBvid"), ("IEEE8021-MIRP-MIB", "ieee8021PbbMirpDestSelector"), ("IEEE8021-MIRP-MIB", "ieee8021PbbMirpPnpEnable"), ("IEEE8021-MIRP-MIB", "ieee8021PbbMirpPnpPortNumber")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021MirpReqdGroup = ieee8021MirpReqdGroup.setStatus('current') if mibBuilder.loadTexts: ieee8021MirpReqdGroup.setDescription('Objects in the MIRP augmentation required group.') ieee8021MirpBridgeCompliance = ModuleCompliance((1, 3, 111, 2, 802, 1, 1, 23, 2, 1, 1)).setObjects(("SNMPv2-MIB", "systemGroup"), ("IEEE8021-MIRP-MIB", "ieee8021MirpReqdGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021MirpBridgeCompliance = ieee8021MirpBridgeCompliance.setStatus('current') if mibBuilder.loadTexts: ieee8021MirpBridgeCompliance.setDescription('The compliance statement for support by a bridge of the IEEE8021-MIRP-MIB module.') mibBuilder.exportSymbols("IEEE8021-MIRP-MIB", ieee8021PbbMirpBvid=ieee8021PbbMirpBvid, ieee8021MirpMib=ieee8021MirpMib, ieee8021MirpPortEntry=ieee8021MirpPortEntry, ieee8021MirpGroups=ieee8021MirpGroups, ieee8021MirpMIBObjects=ieee8021MirpMIBObjects, ieee8021MirpBridgeCompliance=ieee8021MirpBridgeCompliance, ieee8021MirpReqdGroup=ieee8021MirpReqdGroup, ieee8021MirpCompliances=ieee8021MirpCompliances, ieee8021MirpPortEnabledStatus=ieee8021MirpPortEnabledStatus, PYSNMP_MODULE_ID=ieee8021MirpMib, ieee8021PbbMirpEnableStatus=ieee8021PbbMirpEnableStatus, ieee8021MirpConformance=ieee8021MirpConformance, ieee8021PbbMirpDestSelector=ieee8021PbbMirpDestSelector, ieee8021PbbMirpPnpPortNumber=ieee8021PbbMirpPnpPortNumber, ieee8021PbbMirpPnpEnable=ieee8021PbbMirpPnpEnable, ieee8021MirpPortTable=ieee8021MirpPortTable)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2021 all rights reserved # """ A comprehensive test of arithmetic operator overloading """ class Node: """A sample object that supports algebraic expressions among its instances and floats""" # public data value = None # meta methods def __init__(self, value): self.value = value # algebra def __add__(self, other): if isinstance(other, Node): value = self.value + other.value else: value = self.value + other return type(self)(value=value) def __sub__(self, other): if isinstance(other, Node): value = self.value - other.value else: value = self.value - other return type(self)(value=value) def __mul__(self, other): if isinstance(other, Node): value = self.value * other.value else: value = self.value * other return type(self)(value=value) def __truediv__(self, other): if isinstance(other, Node): value = self.value / other.value else: value = self.value / other return type(self)(value=value) def __floordiv__(self, other): if isinstance(other, Node): value = self.value // other.value else: value = self.value // other return type(self)(value=value) def __mod__(self, other): if isinstance(other, Node): value = self.value % other.value else: value = self.value % other return type(self)(value=value) def __divmod__(self, other): if isinstance(other, Node): d, m = divmod(self.value, other.value) else: d, m = divmod(self.value, other) return type(self)(value=d), type(self)(value=m) def __pow__(self, other): if isinstance(other, Node): value = self.value ** other.value else: value = self.value ** other return type(self)(value=value) def __radd__(self, other): value = self.value + other return type(self)(value=value) def __rsub__(self, other): value = other - self.value return type(self)(value=value) def __rmul__(self, other): value = self.value * other return type(self)(value=value) def __rtruediv__(self, other): value = other / self.value return type(self)(value=value) def __rfloordiv__(self, other): value = other // self.value return type(self)(value=value) def __rmod__(self, other): value = other % self.value return type(self)(value=value) def __rdivmod__(self, other): d, m = divmod(other, self.value) return type(self)(value=d), type(self)(value=m) def __rpow__(self, other): value = other ** self.value return type(self)(value=value) def __iadd__(self, other): self.value += other return self def __isub__(self, other): self.value -= other return self def __imul__(self, other): self.value *= other return self def __itruediv__(self, other): self.value /= other return self def __ifloordiv__(self, other): self.value //= other return self def __imod__(self, other): self.value %= other return self def __ipow__(self, other): self.value **= other return self def __neg__(self): return type(self)(value=-self.value) def __pos__(self): return self def __abs__(self): return type(self)(value=abs(self.value)) def test(): # declare a couple of nodes n1 = Node(value=1) n2 = Node(value=2) # unary operators assert (- n1).value == -1 assert (+ n2).value == 2 assert (abs(n1)).value == 1 # basic arithmetic with two operands assert (n1 + n2).value == 1 + 2 assert (n1 - n2).value == 1 - 2 assert (n1 * n2).value == 1 * 2 assert (n1 / n2).value == 1 / 2 assert (n1 // n2).value == 1 // 2 # basic arithmetic with more than two operands assert (n1 + n2 - n1).value == 1 + 2 - 1 assert (n1 * n2 / n1).value == 1 * 2 / 1 assert ((n1 - n2)*n2).value == (1 - 2)*2 # basic arithmetic with floats assert (1 + n2).value == 1 + 2 assert (n2 + 1).value == 2 + 1 assert (1 - n2).value == 1 - 2 assert (n2 - 1).value == 2 - 1 assert (2 * n1).value == 2 * 1 assert (n1 * 2).value == 1 * 2 assert (3 / n2).value == 3 / 2 assert (n2 / 3).value == 2 / 3 assert (n2 ** 3).value == 2**3 assert (3 ** n2).value == 3**2 # more complicated forms assert ((n1**2 + 2*n1*n2 + n2**2)).value == ((n1+n2)**2).value assert ((n1**2 - 2*n1*n2 + n2**2)).value == ((n1-n2)**2).value assert (2*(.5 - n1*n2 + n2**2)*n1).value == 2*(.5 - 1*2 + 2**2)*1 return # main if __name__ == "__main__": test() # end of file
def comparison(start,end, path_to_file): file = open(path_to_file) for res in file: pred_start = int(res.split(" ")[1]) pred_end = int(res.split(" ")[2].split("\t")[0]) if not (pred_end < int(start) or pred_start > int(end)): return res.split("\t")[-1] return ''