content stringlengths 7 1.05M |
|---|
kwargs = {"a": 1, "b": 2, "c": 3}
print(kwargs.pop("d"))
|
#!/usr/bin/env python3
class Interface:
""" Defines the interface of the padding oracle. """
def oracle(self, ciphertext):
""" This function expects a ciphertext and returns true if there is
no padding error and false otherwise.
Args:
ciphertext (bytes): the ciphertext tha... |
'''
单例模式
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
主要解决:一个全局使用的类频繁地创建与销毁。
何时使用:当您想控制实例数目,节省系统资源的时候。
'''
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._i... |
#!/usr/bin/env python3
def reverse_str(name: str) -> str:
""" Reverses a string """
name_lst = list(name)
name_lst.reverse()
ret = ''
for i in range(len(name_lst)):
ret += name_lst[i]
return ret
|
print("Printing n fibonacci numbers")
i=1
x=0
y=1
p=int(input("How many numbers would you like to have displayed: "))
while(i<=p):
print(x,end=' ')
s=x+y
x=y
y=s
i=i+1
print("\n\nEnd of Program\n")
print("Press \"Enter key\" to exit")
u=input()
|
# Write your solutions for 1.5 here!
class Superheros:
def __init__(self, name,superpower, strengh):
self.name = name
self.superpower = superpower
self.strengh = strengh
def name_strengh(self):
print("the name of the superhero is: " + self.name +",his strengh level is: "+str(self.strengh))
def save_civilian(... |
A=[[1,2, 8], [3, 7,4]]
B=[[5,6, 9], [7,6 ,0]]
c=[]
for i in range(len(A)): #range of len gives me indecesc.
c.append([])
for j in range(len(A[i])):
sum = A[i][j]+B[i][j]
c[i].append(sum)
print(c)
# for i in range(len(A)): #range of len gives me indeces
# for j in range(len(A[i])): #again ind... |
# output shape openpose keypoints for body, hands, and face
body_keypoints_num = 25
left_hand_keyp_num = 21
right_hand_keyp_num = 21
face_keyp_num = 51
face_contour_keyp_num = 17
|
class Hello:
def __init__(self, name):
self.name = name
def say(self):
print('Hello!,', self.name) |
class A:
def __init__(self):
super().__init__()
print("A")
class B(A):
def __init__(self):
super().__init__()
print("B")
class C:
def __init__(self):
super().__init__()
print("C")
class D(B, C):
def __init__(self):
super().__init__()
... |
class ServiceError(Exception):
pass
class LicenceError(Exception):
pass
class AccountError(Exception):
pass
class RateLimited(Exception):
pass
codeToError = {
0: "There was an error contacting the ProfanityBlocker service. Please try again later.",
104: "There was an error with your licence ... |
with open("../pokemon_type_relations.csv", "r") as reader:
header = reader.readline().split(",") # Read header
while True:
line = reader.readline()
if not line:
break
line = line.split(",")
attacker = line[0]
weak = []
... |
def dobro(n=0, formato=False):
res = n*2
return res if formato is False else moeda(res)
def metade(n=0, formato=False):
res = n/2
return res if formato is False else moeda(res)
def aumento(n=0, formato=False):
res = n + (n * 0.1)
return res if formato is False else moeda(res)
def diminuir(... |
#Criei uma função e esta recebeu parâmetros.
def funcaoParametros(Par1,Par2):
print(Par1+" "+"é a mãe da"+" "+Par2)
#Vou chamar a função, passando o valor dos parâmetros:
funcaoParametros("Renata","Rafaela")
#Criei nova função com parâmetro que retorna um valor.
def funcaoMultiplica(x):
return x * x
#Vou... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
# Solution 1: Solve the challenge:
# "Can you solve it without using extra space?"
#
# Hint:
# 1. like 102 Linked List Cycle, you can figure out if there is a cycle
# 2. if... |
TIPOS = (('P', 'PASAPORTE'), ('I', 'CARTA DE IDENTIDAD EXTRANJERA'), ('N', 'NIE O TARJETA ESPAÑOLA DE EXTRANJEROS'),
('P', 'PASAPORTE'), ('I', 'CARTA DE IDENTIDAD EXTRANJERA'), ('N', 'NIE O TARJETA ESPAÑOLA DE EXTRANJEROS'),
('X', 'PERMISO DE RESIDENCIA DE ESTADO MIEMBRO DE LA UE'), ('', 'SELECCIONAR.... |
N = int(input())
vals1 = [int(a) for a in input().split()]
vals2 = [int(a) for a in input().split()]
total = 0
for i in range(N):
h1, h2 = vals1[i], vals1[i + 1]
width = vals2[i]
h_dif = abs(h1 - h2)
min_h = min(h1, h2)
total += min_h * width
total += (h_dif * width) / 2
print(total) |
WIDTH = 16
HEIGHT = 32
FIRST = 0
LAST = 255
_FONT = \
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x0... |
record_list=[]
y=int(input('Enter no.of records to be entered'))
for x in range(1,y+1,1):
name=input('Enter name: ')
roll_num=int(input("Enter roll number: "))
sub=input("Enter subject: ")
score=float(input("Enter score: "))
record_list.append([name,roll_num,sub,score])
print(record_list)
q=1
f... |
# Copyright 2020 The Monogon Project Authors.
#
# SPDX-License-Identifier: Apache-2.0
#
# 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
... |
names = [
'John',
'Mary',
'Joe',
'Matt',
'David',
'Matt',
'John'
]
results = []
for name in names:
if name in results:
continue
results.append(name)
print(results) |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'chromium',
'chromium_android',
'recipe_engine/path',
]
def RunSteps(api):
api.chromium.set_config('chromium')
api.chromium_android.stac... |
# For Keystone Engine. AUTO-GENERATED FILE, DO NOT EDIT [systemz_const.py]
KS_ERR_ASM_SYSTEMZ_INVALIDOPERAND = 512
KS_ERR_ASM_SYSTEMZ_MISSINGFEATURE = 513
KS_ERR_ASM_SYSTEMZ_MNEMONICFAIL = 514
|
#!/usr/bin/env python
NAME = 'Citrix NetScaler'
def is_waf(self):
"""
First checks if a cookie associated with Netscaler is present,
if not it will try to find if a "Cneonction" or "nnCoection" is returned
for any of the attacks sent
"""
# NSC_ and citrix_ns_id come from David S. Langlands <... |
# Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# GYP file to build experimental directory.
{
'targets': [
{
'target_name': 'experimental',
'type': 'static_library',
'include_dirs': [
'../include/config'... |
class NodeCapacity:
def __init__(self, json):
self.cpu = json['cpu']
self.memory = self.__convert_mem_str_to_int__(json['memory'])
self.pods = json['pods']
def __convert_mem_str_to_int__(self, mem_str):
''' unit of retrurned value is Mi '''
value = float(mem_str[0:-2])
... |
class nloptSolver( optwSolver ):
def solve( self ):
algorithm = solver[6:]
if( algorithm == "" or algorithm == "MMA" ):
#this is the default
opt = nlopt.opt( nlopt.LD_MMA, self.n )
elif( algorithm == "SLSQP" ):
opt = nlopt.opt( nlopt.LD_SLSQP, self.n )
... |
class Solution:
def trap(self, height: List[int]) -> int:
res = 0
# build memos
max_height_left = [0] * len(height)
max_height_left[0] = height[0]
for i in range(1, len(height)):
max_height_left[i] = max(max_height_left[i-1], height[i])
max_height_right = ... |
# Copyright esse.io 2016 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 agre... |
'''
判断一个数字是否可以表示成三的幂的和
给你一个整数 n ,如果你可以将 n 表示成若干个不同的三的幂之和,请你返回 true ,否则请返回 false 。
对于一个整数 y ,如果存在整数 x 满足 y == 3x ,我们称这个整数 y 是三的幂。
提示:
1 <= n <= 107
'''
'''
思路:数学
对于一个整数x,如果是3的幂的和,说明x=y*3 or x= y*3+1
也就是x是3的整数倍或整数倍+1
不对,是3个不同的幂之和如果是21,3^2+3^2+3^1
TODO
'''
|
"""
Fosdick SDK configuration
"""
# Used for puling information
FOSDICK_API_USERNAME = '<YOUR_API_USERNAME>'
FOSDICK_API_PASSWORD = '<YOUR_API_PASSWORD>'
# Used for order posting.
CLIENT_CODE = '<YOUR_CLIENT_CODE>'
CLIENT_NAME = '<YOUR_CLIENT_NAME>'
# To denote test order.
TESTFLAG = 'y'
# Url's used for pulling in... |
'''
*
***
*****
*******
*********
*******
*****
***
*
'''
n = int(input())
i = 0
while i < (n//2) + 1:
j = 1
while j <= (n//2) - i:
print(' ', end='')
j += 1
k = 0
while k <= i:
print('*', end='')
k += 1
l = i
while l >= 1:
print('*', ... |
# -*- coding: utf8 -*-
"""
Storage backend definition
Author: Romary Dupuis <romary@me.com>
Copyright (C) 2017 Romary Dupuis
"""
class Backend(object):
""" Basic backend class """
def __init__(self, prefix, secondary_indexes):
self._prefix = prefix
self._secondary_indexes = secondary_indexes... |
def take_List(li,Qu_st):
r=[]
for i in range(len(li)):
if(Qu_st in li[i] ):
r.append(li[i])
print(r)
li=['sser','ser','song']
q='ss'
take_List(li,q)
|
_base_ = "./ss_mlBCE_MaskFull_PredDouble_PBR05_woCenter_edgeLower_refinePM10_01_02MasterChefCan.py"
OUTPUT_DIR = "output/self6dpp/ssYCBV/ss_mlBCE_MaskFull_PredDouble_PBR05_woCenter_edgeLower_refinePM10/13_24Bowl"
DATASETS = dict(
TRAIN=("ycbv_024_bowl_train_real_aligned_Kuw",),
TRAIN2=("ycbv_024_bowl_train_pbr"... |
# scrapy shell variable, response is from each single jury page
# using this response >> jurors = response.css('h3::text').extract()
all_jurors = ['Charles de Dreuille', 'Edwin Tofslie', 'Felipe Medeiros', 'Gabriel Segura', 'Georgios Athanassiadis', 'Goksel Eryigit', 'Irene Demetri', 'Lea Verou', 'Loïc Dupasquier', 'Ma... |
# -*- coding: utf-8 -*-
class Pessoa:
def __init__(self, *filhos, nome =None, idade=33 ):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
def nome_e_atributos_de_classe(cls):
return f'{cls} - olhos {... |
class Solution:
def isHappy(self, n: int) -> bool:
l = set()
while True:
s = 0
while n > 0:
s += (n % 10) ** 2
n = n // 10
if s == 1:
return True
if s in l:
return False
n = s
... |
toSort = [8, 1, 5, 15, 3, 20, 11, 7]
print("Tak wygląda tablica: ", toSort)
def mergeSort(tab):
if len(tab) > 1:
middle = len(tab) // 2
left = tab[:middle]
right = tab[middle:]
print("Podział na podtablice\nLewa:", left, "\nPrawa: ", right)
mergeSort(left)
mergeSort(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Problem 076
Integers Come In All Sizes
Source : https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes/problem
"""
a, b, c, d = (int(input()) for _ in range(4))
print(a**b + c**d)
|
try:
fd = file("/srv/www/htdocs/index.html")
_head = ""
buf = fd.readline()
while buf:
if buf.startswith("<!-- end header -->"):
break
_head += buf
buf = fd.readline()
except IOError:
_head="""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E... |
DATABASE_ENGINE = 'sqlite3'
SECRET_KEY = 'abcd123'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': './example.db',
}
}
INSTALLED_APPS = (
'django_bouncy',
)
BOUNCY_TOPIC_ARN = ['arn:aws:sns:us-east-1:250214102493:Demo_App_Unsubscribes']
TEST_RUNNER = 'django_n... |
while 1:
a = int(input("please input a: "))
b = int(input("please input b: "))
print(a+b)
|
n1=int(input('Um valor: '))
n2=int(input('Outro valor: '))
s=n1+n2
m=n1*n2
d=n1/n2
di=n1//n2
e=n1**n2
print('A soma vale: {}, \n o produto vale {}, \n e a divisão {:.2f} ' .format(s,m,d) ,end=' <<< >>> ')
print('divisão inteira {} e potencia {}'.format(di,e))
n=int(input('Informe um numero: '))
doub = n * 2
trip = ... |
name = 'Python'
age = 27
new_str = "我是" + name + "," + "今年" + str(age) + "岁了"
print(new_str)
new_str_1 = "我是%s,今年%d岁了" % (name, age)
print(new_str_1)
new_str_2 = "我是{name},今年{age}岁了".format(
name='aaaa', age='bbb'
)
print(new_str_2)
name1 = 'abc'
age1 = 30
new_str_3 = f"我是{name1},今年{age1}岁了"
print(new_str_... |
name = "pybah"
version = "5"
requires = ["python-2.5"]
|
def test_user_can_register_and_then_login_then_logout(simpy_test_container, firefox_browser):
# Edith has heard about a new app to help manage her invoices
# She opens a browser and navigates to the registration page
firefox_browser.get('http://127.0.0.1:5000/')
# She notices that the name of the app i... |
# -*- coding: utf-8 -*-
# Coded by Sungwook Kim
# 2020-12-14
# IDE: Jupyter Notebook
N = int(input())
def num(N):
b = N
while True:
if b >= 10:
b = b - 10
else:
break
return b
k = -1
res = 0
trig = False
while True:
if trig == False:
b = num(N)
... |
d = {
0: ["a", "f", "g", "l", "q", "r", "w"],
2: ["b", "m", "x"],
6: ["h", "s"],
12: ["c", "n", "y"],
20: ["i", "t"],
30: ["d", "o", "z"],
42: ["j", "u"],
56: ["e", "p"],
72: ["k", "v"]
}
def dinf_cipher(inp):
inp = inp.split(".")
x = []
for i in inp:
... |
"""
main.py
Algorithm
Created by Mohd Shoaib Rayeen on 31/07/18.
Copyright © 2018 Shoaib Rayeen. All rights reserved.
"""
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
... |
[n, budget] = [int(x) for x in input().split()]
pow2 = [ [ [int(x) for x in input().split() ] for _ in range(n) ] ]
power = 0
while True:
power += 1
pow2.append( [ [ min(budget+1, min(pow2[power-1][i][k] + pow2[power-1][k][j] for k in range(n))) for j in range(n)] for i in range(n)] )
if min(pow2[power][0]) > budg... |
def is_intersect(box1, box2):
len_x = abs((box1[0] + box1[2]) / 2 - (box2[0] + box2[2]) / 2)
len_y = abs((box1[1] + box1[3]) / 2 - (box2[1] + box2[3]) / 2)
box1_x = abs(box1[0] - box1[2])
box2_x = abs(box2[0] - box2[2])
box1_y = abs(box1[1] - box1[3])
box2_y = abs(box2[1] - box2[3])
... |
#!/usr/bin/env pytest-3
"""
Understanding Functional Programming
Functional programming defines a computation using expressions and evaluation; often these are
encapsulated in function definitions. It de-emphasizes or avoids the complexity of state change
and mutable objects.
In an imperative language, such as Python... |
idadetotal = 0
médiaidade = 0
maioridadeM = 0
nomeH = ''
totmulher = 0
for p in range(1, 5):
print('----- {}ª PESSOA -----'.format(p))
nome = str(input('Nome: ')).strip()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: ')).strip().upper()
idadetotal += idade
if p == 1 and sexo == '... |
#
# PySNMP MIB module CISCO-MMAIL-DIAL-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-MMAIL-DIAL-CONTROL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:07:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... |
"""
File: anagram.py
Name: Jasmine Tsai
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for ea... |
"""This modules provides strng formatting functions
prepare_data_for_db insert:
formatting data to be inserted in database table
concat_list:
concatenate list elements in a string w/wo separator
to_str:
transform value to str
is_str:
test if value is str
concat_key_value:
concatenate key values of ... |
class Solution:
def isPalindrome(self, x: int) -> bool:
if(x<0):
return False
elif(x==0):
return True
else:
reverse = 0
divi = x
while(divi!=0):
rem = divi%10
reverse = reverse*10 + rem
... |
"""
Java dependencies
"""
load("@rules_jvm_external//:defs.bzl", "maven_install")
def maven_fetch_remote_artifacts():
"""
Fetch maven artifacts
"""
maven_install(
artifacts = [
"com.fasterxml.jackson.core:jackson-core:2.11.2",
"com.fasterxml.jackson.core:jackson-databin... |
# -*- coding: utf-8 -*-
"""Main module."""
def hello_world():
"""Say hello to world.
:returns: Nothing
:rtype: NoneType
"""
print("Hello world")
|
#
# @lc app=leetcode.cn id=461 lang=python3
#
# [461] hamming-distance
#
None
# @lc code=end |
lista= []
while True:
valor = int(input('Digite um valor: '))
if valor not in lista:
lista.append(valor)
print('Valor adicionado com sucesso...')
else:
print('Valor duplicado, impossível adicionar!')
opcao = input('Deseja continuar? [S/N] ')
while opcao not in 'SsNn':
... |
# Can you do it with a conditional statement (if / if-else) instead?
x1 = float(input("number? "))
x2 = float(input("number? "))
#if x1 > x2:
# mx = x1
#elif x2 > x1:
# mx = x2
#else:
# mx = x1
print("Maximum:", x1 if x1 > x2 else x2)
|
#!/usr/bin/env python3
'''
TITLE:
[2018-09-04] Challenge #367 [Easy] Subfactorials - Another Twist on Factorials
LINK:
https://www.reddit.com/r/dailyprogrammer/comments/9cvo0f/20180904_challenge_367_easy_subfactorials_another/
DERIVATION:
Start with n numbers 1...n, and n slots #1...#n. Take the number 1 and place i... |
def run():
my_list = ["Hello", 1, True, 4.5]
my_dict = { "firstname": "Sebastian", "lastname": "Granda" }
super_list = [
{ "firstname": "Valentina", "lastname": "Mora" },
{ "firstname": "Sebastian", "lastname": "Granda" },
{ "firstname": "Isaac", "lastname": "Hincapie" },
{ "firstname": "Camilo",... |
# -*- coding: utf-8 -*-
{
"name": "WeCom HRM",
"author": "RStudio",
"sequence": 607,
"installable": True,
"application": True,
"auto_install": False,
"category": "WeCom/WeCom",
"website": "https://gitee.com/rainbowstudio/wecom",
"version": "15.0.0.1",
"summary": """
... |
#Reference for basic numerical operations and comparisons
x = 9
y = 3
#Arithmetic Operators
print(x+y) #Addition
print(x-y) #Subtraction
print(x*y) #Multiplication
print(x/y) #Division
print(x%y) #Modulus -- remainder after division
print(x**y) #Exponentiation
x = 9.191823
print(x//y) #Floor Divi... |
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
def formatRange(dates):
#We first extract the calendar day of the range
startingDay = days[dates[0].weekday()]... |
class LoginError(Exception):
""" Could not login to the server. """
pass
class NotLoggedInError(Exception):
""" Cannot properly interact with Fur Affinity unless you are logged in. """
pass
class MaturityError(Exception):
""" Cannot access that submission on this account because of maturity filt... |
class EmptyObject:
pass
EMPTY = EmptyObject() # sentinel object to represent empty node output
def is_empty(obj):
return isinstance(obj, EmptyObject)
|
"""
Structural pattern :
Proxy
Examples :
1. use in orm
"""
class Db:
def work(self):
print('you are admin so you can work with database...')
class Proxy:
admin_password = 'secret'
def check_admin(self, password):
if password == self.admin_password:
d1... |
'''
Input
The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).
Output
Print... |
# TODO: we will have to figure out a better way of generating this file
build_time_vars = {
"CC": "gcc -pthread",
"CXX": "g++ -pthread",
"OPT": "-DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes",
"CFLAGS": "-fno-strict-aliasing -g -O3 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes",... |
class Pizza:
def __init__(self, name, dough, toppings_capacity):
self.__name = name
self.__dough = dough
self.__toppings_capacity = toppings_capacity
self.__toppings = {}
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
... |
class ParsedGame:
def __init__(self, parsed_data):
if len(parsed_data) == 5:
self.time_left = parsed_data[0]
self.away_team = parsed_data[1]
self.away_score = parsed_data[2]
self.home_team = parsed_data[3]
self.home_score = parsed_data[4]
e... |
# Ex: 024 - Crie um programa que leia o nome de uma cidade e diga se ela começa
# ou não com o nome "SANTO".
print('''
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
--Seja bem-vindo!
--Exercício 024
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
''')
cidade = input('Em que cidade você nasceu? ').replace('-', ' ').lower().spli... |
# id mapping
# ssdb : redis
# kv
# key= ${table_name}`${item_id}
# val= ${type}`${content}
# 1. type=raw
# 2. type=b64
# 3. type=url
# k hash
# key = table_name
# field = item_id
# value = val
# import redis
# https://blog.csdn.net/u012851870/article/details/44754509
# http://ssdb.io/docs/zh_cn/redis-to-ssdb.ht... |
# -*- coding: utf-8 -*-
# Classe carro: Implemente uma classe chamada Carro com as seguintes propriedades:
# a. Um veículo tem um certo consumo de combustível (medidos em km/litro) e
# uma certa quantidade de combustível no tanque.
# b. O consumo é especificado no construtor e o nível de combustível inicia... |
class FlowException(Exception):
"""Internal exceptions for flow control etc.
Validation, config errors and such should use standard Python exception types"""
pass
class StopProcessing(FlowException):
"""Stop processing of single item without too much error logging"""
pass
|
#!/usr/bin/env python3
""" An attempt to solve Roaming Romans on Kattis """
MODERN_MILE_FEET = 5280.0
ROMAN_MILE_IN_FEET = 4854.0
miles = float(input().rstrip())
roman_paces = (1000 * (MODERN_MILE_FEET/ROMAN_MILE_IN_FEET)) * miles
print(round(roman_paces))
|
def adapt_to_ex(model):
self.conv_sections = conv_sections
self.glob_av_pool = torch.nn.AdaptiveAvgPool2d(output_size=1)
self.linear_sections = linear_sections
self.head = head
self.input_shape = input_shape
self.n_classes = head.out_elements
self.data_augment = DataAugmentation(n_class... |
class TaskAlreadyExistsError(Exception):
pass
class NoSuchTaskError(Exception):
pass |
# -*- coding: utf-8 -*-
"""
Event Module - Controllers
"""
module = request.controller
resourcename = request.function
# Options Menu (available in all Functions' Views)
shn_menu(module)
# -----------------------------------------------------------------------------
def index():
""" Module's Home Page """
... |
class NonTerminal:
def __init__(self, name, productions):
# Creates an instance of a NonTerminal that represents a set of
# grammar productions for a non-terminal.
#
# Keyword arguments:
# name -- the name of the non-terminal
# productions -- a list whose elements can... |
# 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 ... |
params_scenario = {
"n_agents_arrival": 1,
"p_split_threshold": int(1e10),
"r_t": 100,
"r_f": 100,
"gamma": 0, # 0
}
|
#
# PySNMP MIB module ENTERASYS-POLICY-PROFILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-POLICY-PROFILE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... |
# -*- coding: utf-8 -*-
"""Top-level package for Scopes."""
__author__ = """Louis Garman"""
__email__ = 'louisgarman@gmail.com'
__version__ = '0.1.1'
|
"""
def generate_list_books(filename):
book_list = []
file_in = open(filename, encoding='utf-8', errors='replace')
file_in.readline()
for line in file_in:
line = line.strip().split(",")
line[2] = float(line[2])
line[3] = int(line[3])
line[4] = int(line[4])
lin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
В данном упражнении вы должны написать программу, которая будет находить самое
длинное слово в файле. В качестве результата программа
должна выводить на экран длину самого длинного слова и все слова такой длины. Для
простоты принимайте за значимые буквы любые непробе... |
#First Example - try changing the value of phone_balance
phone_balance = 10
bank_balance = 50
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
#Second Example - try changing the value of number
number = 145
if number % 2 == 0:
print("Number " + str(n... |
#crie um programa que leia o nome de uma pessoa e diga
#se ela tem "SILVA" no nome.
n=str(input("Digite o seu nome completo: ")).strip()
n=n[0:].upper().count("SILVA")
print(n)
n=str(input("Digite o seu nome completo: ")).strip()
n=n.lower()
print("Seu nome tem \"Silva\"? {}".format("silva" in n))
n=str(input("Digi... |
#
# MIT License
#
# Copyright (c) 2020 Pablo Rodriguez Nava, @pablintino
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# t... |
{
"targets": [
{
"target_name": "tree_sitter_hack_binding",
"include_dirs": [
"<!(node -e \"require('nan')\")",
"src"
],
"sources": [
"src/parser.c",
"bindings/node/binding.cc",
"src/scanner.cc"
],
"cflags_c": [
"-std=c99",
... |
# -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
|
# Day 2: Compound Event Probability
__author__ = "Sanju Sci"
__email__ = "sanju.sci9@gmail.com"
__copyright__ = "Copyright 2019"
"""
Objective
In this challenge, we practice calculating the probability of a compound
event. We recommend you review today's Probability Tutorial before
attempting this challenge.
T... |
print(f'{(x := "awesome")!r:20}', x)
class A:
locals = 555
print(f'{(y := 666)}')
print(y)
print(f'''L1 -> {f"""L2 -> {f'L3 -> {f"L4 -> {(z := chr(77))!r} <- L4"} <- L3'} <- L2"""} <- L1''')
print(z)
print(f'see -> {"header " + f"{(w := chr(88))}" + " footer"} <- see')
print(w)
print(l... |
"""Module to store EnforceTyping exceptions."""
class EnforcedTypingError(TypeError):
"""Class to raise errors relating to static typing decorator."""
|
#! /usr/bin/python
# Filename: beepExec.py by Geoffrey Sessums
# Purpose:
# Provides functions that execute BEEP source code.
# Usage:
# python3 beepDriver.py beepInput.txt
# python3 beepDriver.py beepInput.txt -v
# Input:
# lineM - array of lines read from BEEP source code.
# labelD - dictionary... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
cur = head
node_list = []
while cur is not None:
node_list.append(cur)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.