content
stringlengths
7
1.05M
rows = 6 cols = 50 grid = [] for _ in range(rows): grid.append([False] * cols) for line in open('input.txt', 'r'): if line.startswith('rect'): (a, b) = line[4:].strip().split('x') for i in range(int(b)): for j in range(int(a)): grid[i][j] = True elif line.starts...
""" Created on Jun 18 16:54 2019 @author: nishit """ #gitkeep
def question(ab): exa, exb = map(int, ab.split()) return "Odd" if exa * exb % 2 == 1 else "Even"
# general driver elements ELEMENTS = [ { "name": "sendButton", "classes": ["g-btn.m-rounded"], "text": [], "id": [] }, { "name": "enterText", "classes": [], "text": [], "id": ["new_post_text_input"] }, { "name": "enterMe...
""" Misc utils that reproduce iterating tool for coroutine """ async def async_enumerate(aiteror, start=0): """ Simple enumerate """ i = start async for value in aiteror: yield i, value i += 1
def buildUploadPypi(): info = 'pip install build twine\n' \ 'pip install --upgrade build twine\n' \ 'python -m build\n' \ 'twine upload --skip-existing --repository pypi dist/*' print(info) return info
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
""" The result_actions package holds objects deriving from ResultAction. A ResultAction represents an action that an be applied to a result. """
i = lambda x: x k = lambda x: lambda f: x
#1^3-3^3-5^3.... n=int(input("Enter number of digits: ")) sum=0 temp=1 for x in range(1,n+1): temp=temp*pow(-1,x+1) if x%2==1: sum=sum+x*x*x*temp print(x*x*x,end='-') print('=',sum)
input = """ % This originally tested the old checker (command-line -OMb-) which does not % exist any longer. strategic(4) v strategic(16). strategic(3) v strategic(15). strategic(15) v strategic(6). strategic(15) v strategic(2). strategic(12) v strategic(16). strategic(8) v strategic(2). strategic(8) v strategic(15). s...
__author__ = 'Kalyan' notes = ''' For this assignment, you have to define a few basic classes to get an idea of defining your own types. ''' # For this problem, define a iterator class called Repeater which can be used to generate an infinite # sequence of this form: 1, 2, -2, 3, -3, 3, etc. (for each numbe...
def maxab(a, b): if (a>=b): return a; else: return b; print(maxab(3,6)) print(maxab(8,4)) print(maxab(5,5))
def modulus(num, div): if (type(num) != int) or (type(div) != int): raise TypeError return num % div print(modulus(True, 1))
# # PySNMP MIB module RADLAN-SNMP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-SNMP-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:49:16 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
media = validas = 0 while True: nota = float(input()) if nota > 10 or nota < 0: print("nota invalida") else: media += nota validas += 1 if validas == 2: media /= 2 print(f"media = {media:.2f}") validas = 0 media = 0 while True: ...
#!/bin/python3 n = int(input("Input problem ID:")) n -= 101 user = n // 4 rnk = n % 4 tab = [ ['UC','DG','RB',''], ['HC','IB','FJ',''], ['GK','UH','QH',''], ['EE','DJ','IH',''], ['HL','MI','EJ',''], ['MB','UI','ED',''], ['AA','BG','ML',''], ['CF','TE','QG',''], ['PH','UJ','BB',''], ['CI','SD','NG',''], ['DK','LD','IJ...
id = "IAD" location = "dulles Intl Airport" max_temp = 32 min_temp = 13 precipitation = 0.4 #'(IAD) : (Dulles Intl Airport) : (32) / (13) / (0.4)' print("First Method") print ('{id:3s} : {location:19s} : {max_temp:3d} / {min_temp:3d} / {precipitation:5.2f}'.format( id=id, location=location, max_temp=max_temp, ...
# def max_num(a, b, c): # if a >= b and a >= c: # return a # elif b >= a and b >= c: # return b # else: # return c # print(max_num(6,3,4)) def max_num(): num1 = int(input("Please enter first number: ")) num2 = int(input("Please enter second nu...
# Copyright 2018 Ocean Protocol Foundation # SPDX-License-Identifier: Apache-2.0 class ConfigProvider: """Provides the Config instance.""" _config = None @staticmethod def get_config(): """ Get a Config instance.""" assert ConfigProvider._config, 'set_config first.' return Co...
# -*- coding: utf-8 -*- def cartesius_to_image_coord(x, y, bounds): assert bounds.is_set() assert bounds.image_width assert bounds.image_height assert x != None assert y != None x = float(x) y = float(y) x_ratio = (x - bounds.left) / (bounds.right - bounds.left) y_ratio = (y - bou...
# LIST OPERATION EDABIT SOLUTION: def list_operation(x, y, n): # creating a list to append the elements that are divisible by 'n'. l = [] # creating a for-loop to iterate from the x to y (both inclusive). for i in range(x, y + 1): # creating a nested if-statement to check for the element's divis...
def run_server(model=None): print("Starting server.") if __name__ == "__main__": run_server()
# A recursive solution for subset sum # problem # Returns true if there is a subset # of set[] with sun equal to given sum def isSubsetSum(set, n, sum): # Base Cases if (sum == 0): return True if (n == 0): return False # If last element is greater than # sum, then ignore it if (set[n - 1] > sum): retur...
class Packet(object): def __init__(self, ip_origin, ip_destination, data): self.ip_origin = ip_origin self.ip_destination = ip_destination self.data = data def __str__(self): return '{0}{1}{2}'.format(self.ip_origin, self.ip_destination, self.data)
# -*- coding: UTF-8 -*- ''' for num in range(5): for num in range(1,5): for num in range(1,5,2): ''' num_start = 1 num_end = 1000000000 num_input = input('Type a end number:') num_end = int(num_input) sum = 0 for num in range(num_start, num_end + 1): sum += num_end print(sum)
""" Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space....
n=30 n1=[10, 11, 12, 13, 14, 17, 18, 19] s1=[] i=0 c=0 l=len(n1) while i<l: j=0 while j<l: if n1[j]+n1[i]==n and n1[i]<n1[j]: s1.append([n1[i],n1[j]]) j+=1 i+=1 print(s1)
#Functions #Taking input in lowercase name = input("Enter Name?").lower() #Defining Two Functions def advaith(): print("Hello, Advaith"); def rohan(): print("Hello, rohan"); #Checking the person's data if name == "advaith": advaith() elif name == "rohan": rohan() else: print("Unknown person");
''' Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? ''' # Definition for a binary tree node. class TreeNode(object): d...
#Exemplo de herança class Pessoa: def __init__(self, nome, rg, email, telefone): #Atributos protegidos self._nome = nome self._rg = rg self._email = email self._telefone = telefone def __str__(self): return 'Nome: ' + self._nome + ', RG: ' + self._rg +\...
PRO = 'PRO' WEB = 'WEB' VENTAS = 'VENTAS' BACKEND = 'BACKEND' MODULE_CHOICES = ( (PRO, 'Profesional'), (WEB, 'Web informativa'), (VENTAS, 'Ventas'), (BACKEND, 'Backend Manager'), ) ACT = 'PRO' INACT = 'WEB' OTRO = 'VENTAS' ESTADO_CHOICES = ( (ACT, 'Activo'), (INACT, 'Baja'), (OTRO, 'Otro...
#!/usr/bin/env python3 with open("input.txt") as f: inp = f.read() layer_len = 150 num_layers = len(inp) / 150 BLACK = str(0) WHITE = str(1) TRANSPARENT = str(2) top_pixels = [None] * layer_len for i in range(num_layers): layer = inp[i * layer_len : (i + 1) * layer_len] for i, l in enumerate(layer): ...
""" @no 230 @name Kth Smallest Element in a BST """ class Solution: def count(self, root): if not root: return 0 return self.count(root.left) + self.count(root.right) + 1 def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int ""...
# -*- coding: utf-8 -*- """Top-level package for battlecl0ud.""" __author__ = """battlecloud""" __email__ = 'battlecloud@khast3x.club' __version__ = '0.1.0'
print('validando expressões matematicas!!!') print('=-=' * 15) n = str(input('Digite uma expressão: ')) n2 = [] for c in n: if c == '(': n2.append('(') elif c == ')': if len(n2) > 0: n2.pop() else: n2.append(')') break print('=-=' * 15) if len(n2) == 0...
""" TicTacToe supporting functions ------------------------------ """ def winners(): """ Returns a list of sets with winning combinations for tic tac toe. """ return [{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}] def check_win(player_st...
#!/usr/bin/env python NAME = 'Art of Defence HyperGuard' def is_waf(self): # credit goes to W3AF return self.match_cookie('^WODSESSION=')
__author__ = 'arobres' #REQUEST PARAMETERS CONTENT_TYPE = u'content-type' CONTENT_TYPE_JSON = u'application/json' CONTENT_TYPE_XML = u'application/xml' ACCEPT_HEADER = u'Accept' ACCEPT_HEADER_XML = u'application/xml' ACCEPT_HEADER_JSON = u'application/json' AUTH_TOKEN_HEADER = u'X-Auth-Token' TENANT_ID_HEADER = u'Te...
""" Module to contain 'process state' object (pstate) related functionality """ __author__ = 'sergey kharnam' class Pstate(object): """ Class to represent process state (pstate) object data store pstate contains: - hostname (str) -- hostname of execution machine - rc (int) -- return code (default...
''' from flask import Flask, current_app from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_mail import Mail from flask_babel import Babel, lazy_gettext as _l from flask_bootstrap import Bootstrap app = Flask(__name__) ap...
def describe_city(name, country='Norway'): """Display information regarding a city's name and which country it is in.""" print(name + " is in " + country + ".") describe_city(name='Oslo') describe_city(name='Bergen') describe_city(name='Cordoba', country='Argentina')
# # PySNMP MIB module TRAPEZE-NETWORKS-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-ROOT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:19:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
class Solution(object): def threeSumClosest(self, nums, target): result, min_diff = 0, float("inf") nums.sort() for i in reversed(range(2, len(nums))): if i+1 < len(nums) and nums[i] == nums[i+1]: continue left, right = 0, i-1 while left < ...
# # PySNMP MIB module ZHONE-COM-VOICE-SIG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-VOICE-SIG-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:47:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
# TSP set for Uruguay from http://www.math.uwaterloo.ca/tsp/world/countries.html#UY OPTIMAL_SOLUTION = 79114 POINTS = [ (30133.3333, 57633.3333), (30166.6667, 57100.0000), (30233.3333, 57583.3333), (30250.0000, 56850.0000), (30250.0000, 56950.0000), (30250.0000, 57583.3333), (30300.0000, 569...
matriz = [ [0 for i in range(4)] for j in range(4)] #i é a linha e j a coluna count=0 for linha in range(4): for coluna in range(4): matriz[linha][coluna] = count #preenche a matriz com números de count count += 1 for linha in range(4): for coluna in range(4): print("%4d" % matriz[linh...
class Events: INITIALIZE = "INITIALIZE" # To initialize constants in the callback. TRAIN_BEGIN = "TRAIN_BEGIN" # At the beginning of each epoch. EPOCH_BEGIN = "EPOCH_BEGIN" # Set HP before the output and loss are computed. BATCH_BEGIN = "BATCH_BEGIN" # Called after forward but before lo...
h, w = map(int, input().split()) ans = (h * w + 1) // 2 if h == 1 or w == 1: ans = 1 print(ans)
class MaxStepsExceeded(Exception): pass class MaxTimeExceeded(Exception): pass class StepControlFailure(Exception): pass class ConditionExit(Exception): pass class InvalidBrackets(Exception): pass class TransformationNotDefined(Exception): pass
""" @author: Gabriele Girelli @contact: gigi.ga90@gmail.com """ CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
# https://leetcode.com/problems/add-two-numbers/ ''' Runtime: 88 ms, faster than 38.84% of Python3 online submissions for Add Two Numbers. Memory Usage: 13.9 MB, less than 33.63% of Python3 online submissions for Add Two Numbers. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0...
x = """0 0 1.0 1 0 1.0 2 0 1.0 0 1 1.0 0 2 1.0 1 1 1.0 1 2 1.0 2 1 1.0 2 2 1.0 3 0 1.0 4 0 1.0 5 0 1.0 6 0 1.0 0 3 1.0 0 4 1.0 0 5 1.0 0 6 1.0 3 1 1.0 1 3 1.0 4 1 1.0 1 4 1.0 5 1 1.0 1 5 1.0 6 1 1.0 1 6 1.0 3 2 1.0 2 3 1.0 4 2 1.0 2 4 1.0 5 2 1.0 2 5 1.0 6 2 1.0 2 6 1.0 3 3 1.0 4 3 1.0 5 3 1.0 6 3 1.0 3 4 1.0 4 4 1.0 5...
def application(env, start_response): ip = env['REMOTE_ADDR'].encode() start_response('200', [('Content-Length', str(len(ip)))]) return ip
def sign_in_database_create_farmer(request,cursor,con): cursor.execute(""" SELECT `PhoneNumber` FROM `farmers` """) phone_numbers = cursor.fetchall() IsUnique = 1 #print(phone_numbers) [('8610342197',), ('9176580040',)] #check if phone number matches for i in phone...
cont = 1 print('-' * 34) while True: tabuada = int(input('Quer ver a tabuada de qual valor? ')) print('-' * 34) if tabuada < 0: break for c in range(1, 11): print(f'{tabuada} x {cont} = {tabuada*cont}') cont += 1 print('-' * 34) print('Programa de tabuada ENCERRADO! Volte Sem...
# Writing Basic Python Programs # Drawing in Python print(" /|") print(" / |") print(" / |") print("/___|") # Click Play or Run Button in top right to run program # After clicking run the program will appear in the consule # Order of instructions matters!
miles = float(input("Enter a distance in miles: ")) # x km = x miles * 1.609344 distance = miles*1.609344 print(f"Distance in km is: {distance}")
toolname = 'bspline' thisDir = Dir('.').abspath upDir = Dir('./../').abspath # Define tool. This must match the value of toolname. def bspline(env): env.Append(LIBS = [toolname]) env.AppendUnique(CPPPATH = [upDir]) env.AppendUnique(CPPPATH = [thisDir]) env.AppendUnique(LIBPATH = [thisDir]) env.R...
class PluginDistributionRepositoryProvider: def __init__(self, plugin, repository_url_provider): self.plugin = plugin self.repository_url_provider = repository_url_provider def get_download_url(self, host): distribution_repository = self.plugin.variables["distribution"]["repository"] ...
def get_version(): with open("tdmgr.py", "r") as tdmgr: version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", tdmgr.read(), re.M) return version_match.group(1) setup( name="map-proxy", version=get_version(), description="Translate non OSM map...
prod1 = ['maça', 10, 0.30] prod2 = ['pera', 5, 0.56] prod3 = ['kiwi', 12, 1.99] prod4 = ['laranja', 36, 0.75] compras = [prod1,prod2,prod3,prod4] print(compras)
# -*- coding: utf-8 -*- # 信用陕西-行政处罚 xinyong_shanxi_settings = { "RETRY_ENABLED": True, "RETRY_TIMES": '9', "DOWNLOAD_TIMEOUT": '20', "ITEM_PIPELINES": { "credit_china.pipelines.CreditChinaPipeline": 300, "credit_china.pipelines.MongodbIndexPipeline": 340, # "credit_china.pipel...
def transcribe(DNA): RNA = [] DNA = list(DNA) for i in DNA: if i == 'A': RNA.append(i) if i == 'C': RNA.append(i) if i == 'G': RNA.append(i) if i == 'T': RNA.append('U') RNA_string = ''.join(RNA) return RNA_strin...
#!/ usr/bin/env # coding=utf-8 """ author: b5mali4 Copyright (c) 2018 License: BSD, see LICENSE for more details. 消息通知,可以接入钉钉,邮件,或者其他安全管理运营平台 """
class LogicError(BaseException): '''逻辑异常类''' code = 0 def __str__(self): return self.__class__.__name__ def generate_logic_error(name, code): '''创建逻辑异常的子类''' base_cls = (LogicError,) return type(name, base_cls, {'code': code}) OK = generate_logic_error('OK', 0) VcodeError = generate_l...
# Linear algebra (numpy.linalg) # https://docs.scipy.org/doc/numpy/reference/routines.linalg.html unit = v / np.linalg.norm(v) z = np.cross(x, y) z = z / np.linalg.norm(z) # 0 # /S\ # 1---2 def triangle_area(p0, p1, p2): v1 = p1 - p0 v2 = p2 - p0 return np.linalg.norm(np.cross(v1, v2))
# David Markham 2019-02-24 # Solution to number 3 # Write a program that prints all numbers 1000 and 10,000, # That are divisible by 6 but not 12. # Here I set the range for the sum divisible by using the range function. # And the formula, if the range is divisible by 6 but not 12. for i in range (1000, 10000): # And...
def get_primary_key(model): return model._meta.primary_key.name def parse_like_term(term): if term.startswith("^"): stmt = "%s%%" % term[1:] elif term.startswith("="): stmt = term[1:] else: stmt = "%%%s%%" % term return stmt def get_meta_fields(model): if hasattr(mod...
# Dividindo valores em várias listas lista = [] pares = [] impares = [] while True: num = int(input('\nDigite um número qualquer: ')) lista.append(num) while True: question = str(input('Deseja continuar? [S/N]: ')).strip().lower()[0] if question in 'sn': break else: ...
BOT_PREFIX = "" TOKEN = "" APPLICATION_ID = "" OWNERS = [] #feel free to change to remove the brackets[] if only one owner BLACKLIST = [] STARTUP_COGS = [ "cogs.general", "cogs.jishaku", "cogs.help", "cogs.moderation", "cogs.owner", "cogs.errrorhandler", ]
description = 'CAMEA basic devices: motors, counters and such' pvmcu1 = 'SQ:CAMEA:mcu1:' pvmcu2 = 'SQ:CAMEA:mcu2:' pvmcu3 = 'SQ:CAMEA:mcu3:' pvmcu4 = 'SQ:CAMEA:mcu4:' devices = dict( s2t = device('nicos_ess.devices.epics.motor.EpicsMotor', epicstimeout = 3.0, description = 'Sample two theta', ...
def Exponenciacao(base, expoente): result = base for i in range(0, expoente-1): result *= base return result print(f'Exemplo: A base {5} elevada em {5} é : {Exponenciacao(5, 5)}') base = int(input('Informe a base: ')) expoente = int(input('Informe o expoente: ')) print(f'A base {base} elevada e...
class LongitudeQueryResponse: def __init__(self, rows=None, fields=None, meta=None): self.rows = rows or [] self.fields = fields or {} self.meta = meta or {} self._from_cache = False @property def from_cache(self): return self._from_cache def mark_as_cached(self...
num = int(input("Digite um número: ")) negativo = 0 if num < 0: print(num, "é um valor NEGATIVO") elif num >= 0: print(num, "é uma valor POSITIVO")
mylist = [1,2,3,4,5,6] a = mylist[::2] print(a) b = [i*i for i in mylist] print(mylist) print(b) list_org=["banana","cherry","apple"] list_cpy=list_org list_cpy.append("lemmon") list_cpy2 = list_org.copy() ## list_copy = list_org [:] list_cpy2.append ("grape") print(list_org) print(list_cpy) print(list_cpy2)
N = int(input()) MOD = 10 ** 9 + 7 # 全パターンの数 subete = (10 ** N) % MOD # 0を含まないパターン数 no_0 = (9**N) % MOD # 9を含まないパターン数 no_9 = (9**N) % MOD # 0も9も含まないパターン数 no_0_9 = (8**N) % MOD ans = subete + no_0_9 ans -= no_0 # 引いた後に負の数だったら10**9+7を足す if ans < 0: ans += MOD ans -= no_9 # 引いた後に負の数だったら10**9+7を足す if ans < 0: ans +...
""" Template project and example that demonstrates how to use the pygame_cards framework. Files description: * mygame.py, settings.json - skeleton project with templates of elements necessary to create a game powered by pygame_cards framework and their description. Can be used as a template project, ...
def greet(name): return f"Hey {name}!" def concatenate(word_one, word_two): return word_one + word_two def age_in_dog_years(age): result = age * 7 return result print(greet('Mattan')) print(greet('Chris')) print(concatenate('Mattan', 'Griffel')) print(age_in_dog_years(28)) print(concatenate(word_t...
#!/bin/python3 # Complete the repeatedString function below. def repeatedString(s, n): occurence_of_a_in_s = 0 for char in s: if char == 'a': occurence_of_a_in_s += 1 # Find how many times 's' can be completely repeated then multiple that by the occurence of a character # in 's' st...
# enumerate() example # enumerate() is used to loop through a list, and for each item in that list, to also give the index where that item can be found days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] # This is how we're used to looping -- for each item in this list, print this i...
# High Scores 2.0 (Рекорды 2.0) # Demonstrates nested sequences (Демонстрирует вложенные последовательности) scores = [] choice = None while choice != "0": print( """ High Scores 2.0 (рекорды 2.0) 0 - Quit (Выйти) 1 - List Scores (Показать рекорды) 2 - Add a Score (Добавить рекорд) "...
#testando... comprimento = str(input()) if comprimento == 'oi': print('Olá, mundo') else: print('Diga "oi" da próxima vez :)') #teste 00 falhou
""" Title: 0030 - Substring with Concatenation of All Words Tags: Binary Search Time: O(logn) = O(1) Space: O(1) Source: https://leetcode.com/problems/divide-two-integers/ Difficulty: Medium """ # Issue with finding the duplicate class Solution: def findSubstring(self, s: str, words: List[str]) -> List[int]: ...
# return the path/sample name def output(path,sample): if len(path)<1: return sample else: if path[-1]=='/': return path+sample else: return path+'/'+sample # obtain the tn barcode for each passed file def exp_bc(file): bc_in=str(file).split('_')[-2] return bc_in
class DataGridRowEditEndingEventArgs(EventArgs): """ Provides data for the System.Windows.Controls.DataGrid.RowEditEnding event. DataGridRowEditEndingEventArgs(row: DataGridRow,editAction: DataGridEditAction) """ @staticmethod def __new__(self,row,editAction): """ __new__(cls: type,row: DataGridRow,...
def convert(number): map_ = { 3: 'Pling', 5: 'Plang', 7: 'Plong' } r_str = [v for k, v in map_.items() if number % k == 0] return ''.join(r_str) if r_str else str(number)
response.title = settings.title response.subtitle = settings.subtitle response.meta.author = '%(author)s <%(author_email)s>' % settings response.meta.keywords = settings.keywords response.meta.description = settings.description response.menu = [ (T('Index'),URL('default','index')==URL(),URL('default','index'),[]), (T('...
class Accumulator(object): def __init__(self, writer): self.writer = writer self.cache = [] def writeInstruction(self, name, opCode, flag, maxFlag): self.flush() self.writer.writeInstruction(name, opCode, flag, maxFlag) def writeArgument(self, argument): self.cache.append(argument) def flush(self): ...
HTTP_METHOD_VIEWS = { "post": "create", "put": "update", "delete": "delete", }
""" print out the numbers 1 through 7. """ i = 1 while i <= 7: print(i, end=" ") i += 1
# input_lines = '''\ # cpy 41 a # inc a # inc a # dec a # jnz a 2 # dec a'''.splitlines() input_lines = open('input.txt') regs = {r:0 for r in 'abcd'} pc = 0 program = list(input_lines) regs['c'] = 1 while pc < len(program): ins, *data = program[pc].split() if ins == 'cpy': regs[data[1]] = int(regs....
############################################################################## # Copyright (c) 2016 Juan Qiu # juan_ qiu@tongji.edu.cn # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is ...
def roman_to_int(roman): values = [ {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}[c] for c in roman ] return sum( +n if n >= next else -n for n, next in zip(values, values[1:] + [0]) ) with open('roman.txt', 'r') as f: msg = f.read().strip().repla...
def test_database_creation_request(client): out = client.post( "/api/v1/database/request", json={ "superuser_fullname": "Charlie Brown", "superuser_email": "test@firstuser.com", "superuser_password": "asdf", "database_name": "test_database_endpoints", ...
# lec10memo1.py # Code shown in Lecture 10, memo 1 # An iterative "Pythonic" search procedure: def search(list, element): for e in list: if e == element: return True return False # The recursive way: def rSearch(list,element): if element == list[0]: return True if len(lis...
r1 = float(input('Primeira reta: ')) r2 = float(input('Segunda reta: ')) r3 = float(input('Terceira reta: ')) if r1 < (r2 + r3) and r2 < (r1 + r3) and r3 < (r1 + r2): print('Os seguimentos formam um triangulo ',end=("")) if r1 == r2 == r3: print('Equilátero. Todos os lados iguais.') elif r1 != r2 !=...
# 命令空间 """ 点号和无点号的变量名会有不同的处理方式,而有些作用域是用于对对象命令空间做初始化设定的 1、无点号运算的变量名(例如:X)与作用域相对应 2、点号的属性名(例如:object.X)使用的是对象的命令空间 3、有些作用域会对对象的命令空间进行初始化(模块和类) """ # 模块的属性 X = 11 def f(): print(X) def g(): # 函数内的本地变量 X = 22 print(X) class C: # 类属性 X = 33 def m(self): # 方法中的本地变量 X = 44...
def test_bulkload(O): errors = [] bulk = O.bulkAdd() bulk.addVertex("1", "Person", {"name": "marko", "age": "29"}) bulk.addVertex("2", "Person", {"name": "vadas", "age": "27"}) bulk.addVertex("3", "Software", {"name": "lop", "lang": "java"}) bulk.addVertex("4", "Person", {"name": "josh", "ag...
extensions = dict( required_params=['training_frame', 'x'], validate_required_params="", set_required_params=""" parms$training_frame <- training_frame if(!missing(x)) parms$ignored_columns <- .verify_datacols(training_frame, x)$cols_ignore """, ) doc = dict( preamble=""" Trains an Extended Isolation...