content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Contact:
def __init__(self, first_name, last_name, nickname, address, mobile, email):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.address = address
self.mobile = mobile
self.email = email
| class Contact:
def __init__(self, first_name, last_name, nickname, address, mobile, email):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.address = address
self.mobile = mobile
self.email = email |
count = int(input())
title = 0
while count > 0:
title += 1
if '666' in str(title):
count -= 1
print(title)
| count = int(input())
title = 0
while count > 0:
title += 1
if '666' in str(title):
count -= 1
print(title) |
#!/usr/bin/env python3
USER = r'server\user'
PASSWORD = 'server_password'
HOSTNAME = 'hostname.goes.here.com'
DOMAIN = 'domain.goes.here.com'
FROM_ADDR = 'emailyouwanttosendmessagesfrom@something.com'
| user = 'server\\user'
password = 'server_password'
hostname = 'hostname.goes.here.com'
domain = 'domain.goes.here.com'
from_addr = 'emailyouwanttosendmessagesfrom@something.com' |
def createKafkaSecurityGroup(ec2, vpc):
sec_group_kafka = ec2.create_security_group(
GroupName='kafka', Description='kafka sec group', VpcId=vpc.id)
sec_group_kafka.authorize_ingress(
IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
... | def create_kafka_security_group(ec2, vpc):
sec_group_kafka = ec2.create_security_group(GroupName='kafka', Description='kafka sec group', VpcId=vpc.id)
sec_group_kafka.authorize_ingress(IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp... |
# STRAND SORT
# It is a recursive comparison based sorting technique which sorts in increasing order.
# It works by repeatedly pulling sorted sub-lists out of the list to be sorted and merging them
# with a result array.
# Algorithm:
# Create a empty strand (list) and append the first element to it popping it from th... | def merge(arr1, arr2):
merged_list = []
while len(arr1) and len(arr2):
if arr1[0] < arr2[0]:
merged_list.append(arr1.pop(0))
else:
merged_list.append(arr2.pop(0))
merged_list += arr1
merged_list += arr2
return merged_list
def strand(arr):
s = [arr.pop(0)]... |
class Proceso:
def __init__(self,tiempo_de_llegada,t,id):
self.t=t
self.tiempo_de_llegada=tiempo_de_llegada
self.id=id
self.inicio=0
self.fin=0
self.T=0
self.E=0
self.P=0
self.tRestantes = t
| class Proceso:
def __init__(self, tiempo_de_llegada, t, id):
self.t = t
self.tiempo_de_llegada = tiempo_de_llegada
self.id = id
self.inicio = 0
self.fin = 0
self.T = 0
self.E = 0
self.P = 0
self.tRestantes = t |
# Time: sum(O(l * 2^l) for l in range(1, 11)) = O(20 * 2^10) = O(1)
# Space: O(1)
class Solution(object):
def findInteger(self, k, digit1, digit2):
"""
:type k: int
:type digit1: int
:type digit2: int
:rtype: int
"""
MAX_NUM_OF_DIGITS = 10
INT_MAX = ... | class Solution(object):
def find_integer(self, k, digit1, digit2):
"""
:type k: int
:type digit1: int
:type digit2: int
:rtype: int
"""
max_num_of_digits = 10
int_max = 2 ** 31 - 1
if digit1 < digit2:
(digit1, digit2) = (digit2, di... |
def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
list_before = db.get_contact_list()
contact.id_contact = app.contact.get_next_id(list_before)
app.contact.create(contact)
assert len(list_before) + 1 == len(db.get_contact_list())
list_after = db.get_contact_list()
... | def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
list_before = db.get_contact_list()
contact.id_contact = app.contact.get_next_id(list_before)
app.contact.create(contact)
assert len(list_before) + 1 == len(db.get_contact_list())
list_after = db.get_contact_list()
... |
# solution 1: Brute Force
# time complexity: O(n^2)
# space complexity: O(1)
def twoNumberSum(arr, n):
for i in range(len(arr) - 1):
firstNum = arr[i]
for j in range(i + 1, len(arr)):
secondNum = arr[j]
if firstNum + secondNum == n:
return [first... | def two_number_sum(arr, n):
for i in range(len(arr) - 1):
first_num = arr[i]
for j in range(i + 1, len(arr)):
second_num = arr[j]
if firstNum + secondNum == n:
return [firstNum, secondNum]
return []
print(two_number_sum([3, 5, -4, 8, 11, 1, -1, 6], 10)) |
class InvalidMovementException(Exception):
pass
class InvalidMovementTargetException(InvalidMovementException):
pass
class InvalidMovimentOriginException(InvalidMovementException):
pass | class Invalidmovementexception(Exception):
pass
class Invalidmovementtargetexception(InvalidMovementException):
pass
class Invalidmovimentoriginexception(InvalidMovementException):
pass |
FORM_CONTENT_TYPES = [
'application/x-www-form-urlencoded',
'multipart/form-data'
]
| form_content_types = ['application/x-www-form-urlencoded', 'multipart/form-data'] |
"""
Simulation parameters.
"""
SIMULATION_TIME_STEPS = 300
| """
Simulation parameters.
"""
simulation_time_steps = 300 |
def numb_of_char(a):
d = {}
for char in set(a):
d[char] = a.count(char)
return d
a = numb_of_char(str(input("Input the word please: ")))
print(a)
| def numb_of_char(a):
d = {}
for char in set(a):
d[char] = a.count(char)
return d
a = numb_of_char(str(input('Input the word please: ')))
print(a) |
class Vector2D:
def __init__(self, v: List[List[int]]):
def getIt():
for row in v:
for val in row:
yield val
self.it = iter(getIt())
self.val = next(self.it, None)
def next(self) -> int:
result = self.val
... | class Vector2D:
def __init__(self, v: List[List[int]]):
def get_it():
for row in v:
for val in row:
yield val
self.it = iter(get_it())
self.val = next(self.it, None)
def next(self) -> int:
result = self.val
self.val = nex... |
def plot_3D_Data(
self,
*arg_list,
is_norm=False,
unit="SI",
component_list=None,
save_path=None,
x_min=None,
x_max=None,
y_min=None,
y_max=None,
z_min=None,
z_max=None,
z_range=None,
is_auto_ticks=True,
is_auto_range=False,
is_2D_view=False,
is_same_s... | def plot_3_d__data(self, *arg_list, is_norm=False, unit='SI', component_list=None, save_path=None, x_min=None, x_max=None, y_min=None, y_max=None, z_min=None, z_max=None, z_range=None, is_auto_ticks=True, is_auto_range=False, is_2D_view=False, is_same_size=False, N_stem=100, fig=None, ax=None, is_show_fig=None, is_logs... |
def elo(winner_rank, loser_rank, weighting):
"""
:param winner: The Player that won the match.
:param loser: The Player that lost the match.
:param weighting: The weighting factor to suit your comp.
:return: (winner_new_rank, loser_new_rank) Tuple.
This follows the ELO ranking method.
"""
... | def elo(winner_rank, loser_rank, weighting):
"""
:param winner: The Player that won the match.
:param loser: The Player that lost the match.
:param weighting: The weighting factor to suit your comp.
:return: (winner_new_rank, loser_new_rank) Tuple.
This follows the ELO ranking method.
"""
... |
n = int(input())
line = list(map(int, input().split()))
l = {}
res = ""
for i, j in enumerate(line):
l[j] = i+1
for k in range(n):
res += str(l[k+1]) + " "
print(res.rstrip()) | n = int(input())
line = list(map(int, input().split()))
l = {}
res = ''
for (i, j) in enumerate(line):
l[j] = i + 1
for k in range(n):
res += str(l[k + 1]) + ' '
print(res.rstrip()) |
valor = int(input())
for i in range(valor+1):
if(i%2 != 0):
print(i) | valor = int(input())
for i in range(valor + 1):
if i % 2 != 0:
print(i) |
# https://leetcode.com/problems/delete-and-earn/
class Solution:
def deleteAndEarn(self, nums: list[int]) -> int:
num_profits = dict()
for num in nums:
num_profits[num] = num_profits.get(num, 0) + num
sorted_nums = sorted(num_profits.keys())
second_last_profit = 0
... | class Solution:
def delete_and_earn(self, nums: list[int]) -> int:
num_profits = dict()
for num in nums:
num_profits[num] = num_profits.get(num, 0) + num
sorted_nums = sorted(num_profits.keys())
second_last_profit = 0
last_profit = num_profits[sorted_nums[0]]
... |
class BaseStorage(object):
def get_rule(self, name):
raise NotImplementedError()
def get_ruleset(self, name):
raise NotImplementedError()
| class Basestorage(object):
def get_rule(self, name):
raise not_implemented_error()
def get_ruleset(self, name):
raise not_implemented_error() |
class Solution:
# dictionary keys are tuples, storing results
# structure of the tuple:
# (level, prev_sum, val_to_include)
# value is number of successful tuples
def fourSumCount(self, A, B, C, D, prev_sum=0, level=0, sums={}):
"""
:type A: List[int]
:type B: List[int]
... | class Solution:
def four_sum_count(self, A, B, C, D, prev_sum=0, level=0, sums={}):
"""
:type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int
"""
sums = {} if level == 3 else sums
if level == 3:
to... |
# https://projecteuler.net/problem=19
def is_leap(year):
if year%4 != 0:
return False
if year%100 == 0 and year%400 != 0:
return False
return True
def year_days(year):
if is_leap(year):
return 366
return 365
def month_days(month, year):
if month == 4 or month == 6 or m... | def is_leap(year):
if year % 4 != 0:
return False
if year % 100 == 0 and year % 400 != 0:
return False
return True
def year_days(year):
if is_leap(year):
return 366
return 365
def month_days(month, year):
if month == 4 or month == 6 or month == 9 or (month == 11):
... |
class Config:
ngram = 2
train_set = "data/rmrb.txt"
modified_train_set = "data/rmrb_modified.txt"
test_set = ""
model_file = ""
param_file = ""
word_max_len = 10
proposals_keep_ratio = 1.0
use_re = 1
subseq_num = 15 | class Config:
ngram = 2
train_set = 'data/rmrb.txt'
modified_train_set = 'data/rmrb_modified.txt'
test_set = ''
model_file = ''
param_file = ''
word_max_len = 10
proposals_keep_ratio = 1.0
use_re = 1
subseq_num = 15 |
def execucoes():
return int(input())
def entradas():
return input().split(' ')
def imprimir(v):
print(v)
def tamanho_a(a):
return len(a)
def tamanho_b(b):
return len(b)
def diferenca_tamanhos(a, b):
return (len(a) <= len(b))
def analisar(e, i, s):
a, b = e
if(diferenca_tamanhos(a, ... | def execucoes():
return int(input())
def entradas():
return input().split(' ')
def imprimir(v):
print(v)
def tamanho_a(a):
return len(a)
def tamanho_b(b):
return len(b)
def diferenca_tamanhos(a, b):
return len(a) <= len(b)
def analisar(e, i, s):
(a, b) = e
if diferenca_tamanhos(a, ... |
class Solution:
def allPossibleFBT(self, N):
def constr(N):
if N == 1: yield TreeNode(0)
for i in range(1, N, 2):
for l in constr(i):
for r in constr(N - i - 1):
m = TreeNode(0)
m.left = l
... | class Solution:
def all_possible_fbt(self, N):
def constr(N):
if N == 1:
yield tree_node(0)
for i in range(1, N, 2):
for l in constr(i):
for r in constr(N - i - 1):
m = tree_node(0)
... |
"""
How to set up virtual environment
pip install virtualenv
pip install virtualenvwrapper
# export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
# To activate virtualenv and set up flask
1. mkvirtualenv my-venv
###2. workon my-venv
3. pip install Flask
4. pip freeze
5. #... | """
How to set up virtual environment
pip install virtualenv
pip install virtualenvwrapper
# export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
# To activate virtualenv and set up flask
1. mkvirtualenv my-venv
###2. workon my-venv
3. pip install Flask
4. pip freeze
5. #... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... | def find_decision(obj):
if obj[7] > 0:
if obj[6] <= 5:
if obj[2] <= 1:
if obj[10] <= 13:
if obj[3] > 0:
if obj[16] <= 2:
return 'False'
elif obj[16] > 2:
if... |
macs_response = '''<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org... | macs_response = '<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/w... |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
VERIFIED_OP_REFERENCES = [
'Abs-1',
'Acos-1',
'Add-1',
'Asin-1',
'Asinh-3',
'Assign-6',
'AvgPool-1',
'BatchNormInference-5',
'BatchToSpace-2',
'BinaryConvolution-1',
'Broadcast-1',
'Broadcast-3'... | verified_op_references = ['Abs-1', 'Acos-1', 'Add-1', 'Asin-1', 'Asinh-3', 'Assign-6', 'AvgPool-1', 'BatchNormInference-5', 'BatchToSpace-2', 'BinaryConvolution-1', 'Broadcast-1', 'Broadcast-3', 'Bucketize-3', 'Ceiling-1', 'CTCGreedyDecoder-1', 'CTCGreedyDecoderSeqLen-6', 'Concat-1', 'Convert-1', 'ConvertLike-1', 'Conv... |
# Copyright 2015 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.
# This dictionary of GPU information was captured from a run of
# Telemetry on a Linux workstation with NVIDIA GPU. It helps test
# telemetry.internal.platfo... | fake_gpu_info = {'feature_status': {'flash_stage3d': 'enabled', 'gpu_compositing': 'enabled', 'video_decode': 'unavailable_software', 'flash_3d': 'enabled', 'webgl': 'enabled', 'video_encode': 'enabled', 'multiple_raster_threads': 'enabled_on', '2d_canvas': 'unavailable_software', 'rasterization': 'disabled_software', ... |
for i in range(int(input())):
number_of_candies = int(input())
candies_weights = list(map(int, input().split()))
bob_pos = number_of_candies - 1
alice_pos = 0
bob_current_weight = 0
alice_current_weight = 0
last_equal_candies_total_number = 0
while alice_pos <= bob_pos:
if al... | for i in range(int(input())):
number_of_candies = int(input())
candies_weights = list(map(int, input().split()))
bob_pos = number_of_candies - 1
alice_pos = 0
bob_current_weight = 0
alice_current_weight = 0
last_equal_candies_total_number = 0
while alice_pos <= bob_pos:
if alice_... |
# --------------
# Code starts here
# Create the lists
class_1 = ['geoffrey hinton', 'andrew ng', 'sebastian raschka', 'yoshu bengio']
class_2 = ['hilary mason', 'carla gentry', 'corinna cortes']
# Concatenate both the strings
new_class = class_1+class_2
print(new_class)
# Append the list
new_class.append('p... | class_1 = ['geoffrey hinton', 'andrew ng', 'sebastian raschka', 'yoshu bengio']
class_2 = ['hilary mason', 'carla gentry', 'corinna cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('peter warden')
print(new_class)
new_class.remove('carla gentry')
print(new_class)
courses = {'math': 65, 'english'... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:31:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) ... |
samples = {
"2_brother_plays": {
"question_parts": [range(1, 13), range(13, 17)],
"sp_parts": [range(20, 43), range(50, 60)]
}
}
| samples = {'2_brother_plays': {'question_parts': [range(1, 13), range(13, 17)], 'sp_parts': [range(20, 43), range(50, 60)]}} |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzag_level_order(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
... |
def insert_metatable():
"""SQL query to insert records from table insert into a table on a DB
"""
return """
INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES
('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0... | def insert_metatable():
"""SQL query to insert records from table insert into a table on a DB
"""
return "\n INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES \n ('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0][... |
#
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 in the top-level directory
# of this distribution and at:
#
# http:... | class Irmadependencyerror(Exception):
"""Error caused by a missing dependency."""
pass
class Irmamachinemanagererror(Exception):
"""Error on a machine manager."""
pass
class Irmamachineerror(Exception):
"""Error on a machine."""
pass
class Irmaadminerror(Exception):
"""Error in admin part... |
def save_form(form, actor=None):
"""Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require
this to be passed (is not handled by middleware), you can use this to replace form.save().
Requires you to use the audit.Model model as the actor is passed to th... | def save_form(form, actor=None):
"""Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require
this to be passed (is not handled by middleware), you can use this to replace form.save().
Requires you to use the audit.Model model as the actor is passed to th... |
# coding = utf-8
# Create date: 2018-11-05
# Author :Hailong
def test_sysctl(ros_kvm_with_paramiko, cloud_config_url):
command = 'sudo cat /proc/sys/kernel/domainname'
feed_back = 'test'
client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url))
stdin, stdout, st... | def test_sysctl(ros_kvm_with_paramiko, cloud_config_url):
command = 'sudo cat /proc/sys/kernel/domainname'
feed_back = 'test'
client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url))
(stdin, stdout, stderr) = client.exec_command(command, timeout=10)
output = ... |
#Datos de entrada
num=int(input("Ingrese un numero: "))
# Proceso
if num==10:
print("Calificacion: A")
elif num==9:
print("Calificacion: B")
elif num==8:
print("Calificacion: C")
elif num==7 and num==6:
print("Calificacion: D")
elif num<=5 and num>=0:
print("Calificacion: F")
| num = int(input('Ingrese un numero: '))
if num == 10:
print('Calificacion: A')
elif num == 9:
print('Calificacion: B')
elif num == 8:
print('Calificacion: C')
elif num == 7 and num == 6:
print('Calificacion: D')
elif num <= 5 and num >= 0:
print('Calificacion: F') |
ribbon_needed = 0
with open("input.txt", "r") as puzzle_input:
for line in puzzle_input:
length, width, height = [int(item) for item in line.split("x")]
dimensions = [length, width, height]
smallest_side = min(dimensions)
dimensions.remove(smallest_side)
second_smallest_side = min(dimensions)
ribbon_n... | ribbon_needed = 0
with open('input.txt', 'r') as puzzle_input:
for line in puzzle_input:
(length, width, height) = [int(item) for item in line.split('x')]
dimensions = [length, width, height]
smallest_side = min(dimensions)
dimensions.remove(smallest_side)
second_smallest_sid... |
"""
# refactoring
Refactoring is the key to successfull projects.
Refactor:
1) annuity_factor such that:
conversion to integer is handled,
no extra printing
2) policy_book into a class such that:
a function generates the book and the premium
stats and visualizations functions are avalaible
3) book_report su... | """
# refactoring
Refactoring is the key to successfull projects.
Refactor:
1) annuity_factor such that:
conversion to integer is handled,
no extra printing
2) policy_book into a class such that:
a function generates the book and the premium
stats and visualizations functions are avalaible
3) book_report su... |
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance += 1
xor = xor >> 1
return distance
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor =... | class Solution:
def hamming_distance(self, x: int, y: int) -> int:
xor = x ^ y
distance = 0
while xor:
if xor & 1:
distance += 1
xor = xor >> 1
return distance
class Solution:
def hamming_distance(self, x: int, y: int) -> int:
xo... |
"""
Visual Genome Python API wrapper, models
"""
class Image:
"""
Image.
ID int
url hyperlink string
width int
height int
"""
def __init__(self, id, url, width, height, coco_id, flickr_id):
self.id = id
self.url = url
self.width ... | """
Visual Genome Python API wrapper, models
"""
class Image:
"""
Image.
ID int
url hyperlink string
width int
height int
"""
def __init__(self, id, url, width, height, coco_id, flickr_id):
self.id = id
self.url = url
self.width =... |
def setIntersectionCount(group):
return len(set.intersection(*group))
groupList = []
tempGroup = []
with open("./6/input.txt") as inputFile:
for line in inputFile:
line = line.replace("\n","")
if len(line) > 0:
tempGroup.append(set(line))
else:
groupList.append(tempGroup)
tempGroup = []
if len(tempGr... | def set_intersection_count(group):
return len(set.intersection(*group))
group_list = []
temp_group = []
with open('./6/input.txt') as input_file:
for line in inputFile:
line = line.replace('\n', '')
if len(line) > 0:
tempGroup.append(set(line))
else:
groupList.app... |
"""Errors module."""
__all__ = [
'Error',
'AddressError',
'AuthenticationError',
'TransportError',
'ValidationError',
'RegisterError',
'MessageError',
'DBusError',
'SignatureError',
'TooLongError',
]
class Error(Exception):
"""Base class."""
class AddressError(Error):
... | """Errors module."""
__all__ = ['Error', 'AddressError', 'AuthenticationError', 'TransportError', 'ValidationError', 'RegisterError', 'MessageError', 'DBusError', 'SignatureError', 'TooLongError']
class Error(Exception):
"""Base class."""
class Addresserror(Error):
"""Raised for errors in server addresses."""... |
# If you're new to file handling, be sure to check out with_open.py first!
# You'll also want to check out read_text.py before this example. This one is a bit more advanced.
with open('read_csv.csv', 'r') as states_file:
# Instead of leaving the file contents as a string, we're splitting the file into a list... | with open('read_csv.csv', 'r') as states_file:
states = states_file.read().split('\n')
for (index, state) in enumerate(states):
states[index] = state.split(',')
for state in states[1:]:
print('\n---{0}---'.format(state[0]))
for (index, info) in enumerate(state[1:]):
print('{0}:\t{1}'.for... |
class Student:
studentLevel = 'first year computer science 2020/2021 session'
studentCounter = 0
registeredCourse='csc102'
def __init__(self, thename, thematricno, thesex,thehostelname,theage,thecsc102examscore):
self.name = thename
self.matricno = thematricno
self.sex = thesex
... | class Student:
student_level = 'first year computer science 2020/2021 session'
student_counter = 0
registered_course = 'csc102'
def __init__(self, thename, thematricno, thesex, thehostelname, theage, thecsc102examscore):
self.name = thename
self.matricno = thematricno
self.sex =... |
def say_hi(name,age):
print("Hello " + name + ", you are " + age)
say_hi("Mike", "35")
def cube(num): # function
return num*num*num
result = cube(4) # variable
print(result)
| def say_hi(name, age):
print('Hello ' + name + ', you are ' + age)
say_hi('Mike', '35')
def cube(num):
return num * num * num
result = cube(4)
print(result) |
MUTATION = '''mutation {{
{mutation}
}}'''
def _verify_additional_type(additionaltype):
"""Check that the input to additionaltype is a list of strings.
If it is empty, raise ValueError
If it is a string, convert it to a list of strings."""
if additionaltype is None:
return None
if isins... | mutation = 'mutation {{\n {mutation}\n}}'
def _verify_additional_type(additionaltype):
"""Check that the input to additionaltype is a list of strings.
If it is empty, raise ValueError
If it is a string, convert it to a list of strings."""
if additionaltype is None:
return None
if isinstanc... |
#
# PySNMP MIB module CXConsoleDriver-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXConsoleDriver-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:32:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
# written by abraham on aug 24
def dyear2date(dyear):
year = int(dyear)
month_lengths = [31,28,31,30,31,30,31,31,30,31,30,31]
days_before_months = [0,31,59,90,120,151,181,212,243,273,304,334]
days_into_year_f = (dyear-year)*365
days_into_year_i = int(days_into_year_f)
for i in range(12):
if days_before_mo... | def dyear2date(dyear):
year = int(dyear)
month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days_before_months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
days_into_year_f = (dyear - year) * 365
days_into_year_i = int(days_into_year_f)
for i in range(12):
if d... |
class Camera:
"""docstring for ."""
def __init__(self, brand, sensor, lens, battery):
self.brand = brand
self.sensor = sensor
self.lens = lens
self.battery = battery
def __str__(self):
return self.brand + ' ' + self.sensor + ' ' + self.lens + ' ' + self.battery
... | class Camera:
"""docstring for ."""
def __init__(self, brand, sensor, lens, battery):
self.brand = brand
self.sensor = sensor
self.lens = lens
self.battery = battery
def __str__(self):
return self.brand + ' ' + self.sensor + ' ' + self.lens + ' ' + self.battery
... |
#!/usr/bin/python3
"""
Good morning! Here's your coding interview problem for today.
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can ... | """
Good morning! Here's your coding interview problem for today.
This problem was recently asked by Google.
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one ... |
# file = open('C:\\Users\\dks10\\OneDrive\\Desktop\\Projects\\Code\\Python\\PythonCrypto\\Module_3\\eye.png', 'rb')
file = open('encrypt_eye.png', 'rb')
image = file.read()
file.close()
image = bytearray(image)
key = 48
for index, value in enumerate(image):
image[index] = value^key
file = open('2eye.png','wb')
... | file = open('encrypt_eye.png', 'rb')
image = file.read()
file.close()
image = bytearray(image)
key = 48
for (index, value) in enumerate(image):
image[index] = value ^ key
file = open('2eye.png', 'wb')
file.write(image)
file.close() |
n=int(input())
c = 1
while c**2 < n:
print(c**2)
c += 1
| n = int(input())
c = 1
while c ** 2 < n:
print(c ** 2)
c += 1 |
class BSTNode:
def __init__(self, data = None) -> None:
self.data = data
self.left = None
self.right = None
def __repr__(self) -> str:
return(f"BSTNode({self.data})")
def __str__(self) -> str:
return str(self.data)
def __eq__(self, o: object) -> ... | class Bstnode:
def __init__(self, data=None) -> None:
self.data = data
self.left = None
self.right = None
def __repr__(self) -> str:
return f'BSTNode({self.data})'
def __str__(self) -> str:
return str(self.data)
def __eq__(self, o: object) -> bool:
pas... |
'''
Given an array of intervals, merge all overlapping intervals,
and return an array of the non-overlapping intervals that cover all the intervals in the input.
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].... | """
Given an array of intervals, merge all overlapping intervals,
and return an array of the non-overlapping intervals that cover all the intervals in the input.
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].... |
# CPU: 0.06 s
possessed, found, condition = map(int, input().split())
possessed += found
count = 0
while possessed >= condition:
div, mod = divmod(possessed, condition)
count += div
possessed = div + mod
print(count)
| (possessed, found, condition) = map(int, input().split())
possessed += found
count = 0
while possessed >= condition:
(div, mod) = divmod(possessed, condition)
count += div
possessed = div + mod
print(count) |
print(18 * 1234)
print(18 * 1234 * 2)
print(0 * 1)
print(1 * 0)
print(0.0 * 1.0)
print(1.0 * 0.0)
| print(18 * 1234)
print(18 * 1234 * 2)
print(0 * 1)
print(1 * 0)
print(0.0 * 1.0)
print(1.0 * 0.0) |
"""
The roseguarden project
Copyright (C) 2018-2020 Marcus Drobisch,
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This pr... | """
The roseguarden project
Copyright (C) 2018-2020 Marcus Drobisch,
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This pr... |
class Dummy():
def __init__(self, data):
self.name = data['name']
self.age = data['age']
self.city = data['city']
class DummyData():
def __init__(self):
self.results = [
Dummy({
'name': 'PA',
'age': 29,
'city': 'Paris'... | class Dummy:
def __init__(self, data):
self.name = data['name']
self.age = data['age']
self.city = data['city']
class Dummydata:
def __init__(self):
self.results = [dummy({'name': 'PA', 'age': 29, 'city': 'Paris'}), dummy({'name': 'Cairo', 'age': 0, 'city': 'Muizenberg'}), dum... |
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... | class Cloudifyclienterror(Exception):
def __init__(self, message, server_traceback=None, status_code=-1, error_code=None, response=None):
super(CloudifyClientError, self).__init__(message)
self.status_code = status_code
self.error_code = error_code
self.server_traceback = server_tra... |
array = []
for _ in range(int(input())):
command = input().strip().split(" ")
cmd_type = command[0]
if (cmd_type == "print"):
print(array)
elif (cmd_type == "sort"):
array.sort()
elif (cmd_type == "reverse"):
array.reverse()
elif (cmd_type == "pop"):
array.pop()
... | array = []
for _ in range(int(input())):
command = input().strip().split(' ')
cmd_type = command[0]
if cmd_type == 'print':
print(array)
elif cmd_type == 'sort':
array.sort()
elif cmd_type == 'reverse':
array.reverse()
elif cmd_type == 'pop':
array.pop()
elif ... |
# -*- coding: utf-8 -*-
"""
mundiapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class UpdatePlanRequest(object):
"""Implementation of the 'UpdatePlanRequest' model.
Request for updating a plan
Attributes:
name (string): Plan's n... | """
mundiapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Updateplanrequest(object):
"""Implementation of the 'UpdatePlanRequest' model.
Request for updating a plan
Attributes:
name (string): Plan's name
description (string): Descripti... |
class AuthError(Exception):
pass
class JsonError(Exception):
pass
| class Autherror(Exception):
pass
class Jsonerror(Exception):
pass |
# 3. Define a function to check whether a number is even
def even(num):
if num%2 == 0:
return True
else:
return False
print(even(4))
print(even(-5))
| def even(num):
if num % 2 == 0:
return True
else:
return False
print(even(4))
print(even(-5)) |
class OverlapResult:
def __init__(self, overlap_map: dict[tuple[float, float], int]):
self._overlap_map = overlap_map
self._overlaps = overlap_map_to_overlaps(overlap_map)
@property
def overlaps(self) -> int:
return self._overlaps
@property
def overlap_map(self) -> dict[tu... | class Overlapresult:
def __init__(self, overlap_map: dict[tuple[float, float], int]):
self._overlap_map = overlap_map
self._overlaps = overlap_map_to_overlaps(overlap_map)
@property
def overlaps(self) -> int:
return self._overlaps
@property
def overlap_map(self) -> dict[tu... |
class Config:
def __init__(self, config_file_name):
self.config_file_name = config_file_name
| class Config:
def __init__(self, config_file_name):
self.config_file_name = config_file_name |
""" module logging"""
# logging
| """ module logging""" |
# @AUTHOR : lonsty
# @DATE : 2020/3/28 18:01
class CookiesExpiredException(Exception):
pass
class NoImagesException(Exception):
pass
class ContentParserError(Exception):
pass
class UserNotFound(Exception):
pass
| class Cookiesexpiredexception(Exception):
pass
class Noimagesexception(Exception):
pass
class Contentparsererror(Exception):
pass
class Usernotfound(Exception):
pass |
"""Errors."""
class ProxyError(Exception):
pass
class NoProxyError(Exception):
pass
class ResolveError(Exception):
pass
class ProxyConnError(ProxyError):
pass
class ProxyRecvError(ProxyError): # connection_is_reset
pass
class ProxySendError(ProxyError): # connection_is_reset
pass
... | """Errors."""
class Proxyerror(Exception):
pass
class Noproxyerror(Exception):
pass
class Resolveerror(Exception):
pass
class Proxyconnerror(ProxyError):
pass
class Proxyrecverror(ProxyError):
pass
class Proxysenderror(ProxyError):
pass
class Proxytimeouterror(ProxyError):
pass
class... |
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"WorldArea",
"VoxelLight",
"VoxelLightNode",
"VoxelLevelGenerator",
"VoxelLevelGeneratorFlat",
"VoxelSurfaceMerger",
"VoxelSurfaceSimple",
... | def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return ['WorldArea', 'VoxelLight', 'VoxelLightNode', 'VoxelLevelGenerator', 'VoxelLevelGeneratorFlat', 'VoxelSurfaceMerger', 'VoxelSurfaceSimple', 'VoxelSurface', 'VoxelLibraryMerger', 'VoxelLibrarySimple', 'VoxelLib... |
# The Pokemon class should receive a name (string) and health (int) upon initialization.
# It should also have a method called pokemon_details that returns the information about the pokemon:
# "{pokemon_name} with health {pokemon_health}"
class Pokemon:
def __init__(self, name: str, health: int) -> None:
... | class Pokemon:
def __init__(self, name: str, health: int) -> None:
self.name = name
self.health = health
def pokemon_details(self) -> str:
return f'{self.name} with health {self.health}' |
{
"includes": [
"../common.gypi"
],
"targets": [
{
"target_name": "libgdal_ogr_mem_frmt",
"type": "static_library",
"sources": [
"../gdal/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp",
"../gdal/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp",
"../gdal/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp"
],
"include... | {'includes': ['../common.gypi'], 'targets': [{'target_name': 'libgdal_ogr_mem_frmt', 'type': 'static_library', 'sources': ['../gdal/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp', '../gdal/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp', '../gdal/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp'], 'include_dirs': ['../gdal/ogr/ogrsf_frmts/mem']}]... |
_base_ = ['./tracktor_faster-rcnn_r50_fpn_4e_mot17-public-half.py']
model = dict(
pretrains=dict(
detector= # noqa: E251
'https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-ffa52ae7.pth' # noqa: E501
))
data_root = 'data/MOT17/'
test_set = 'test'
data = dict... | _base_ = ['./tracktor_faster-rcnn_r50_fpn_4e_mot17-public-half.py']
model = dict(pretrains=dict(detector='https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-ffa52ae7.pth'))
data_root = 'data/MOT17/'
test_set = 'test'
data = dict(train=dict(ann_file=data_root + 'annotations/train_coco... |
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that ... | class Moduledocfragment(object):
documentation = '\n\noptions:\n docker_host:\n description:\n - "The URL or Unix socket path used to connect to the Docker API. To connect to a remote host, provide the\n TCP connection string. For example, \'tcp://192.0.2.23:2376\'. If TLS is used ... |
DEFAULT_MIRRORS = {
"bitbucket": [
"https://bitbucket.org/{repository}/get/{commit}.tar.gz",
],
"buildifier": [
"https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}",
],
"github": [
"https://github.com/{repository}/archive/{commit}.tar.gz",
],
... | default_mirrors = {'bitbucket': ['https://bitbucket.org/{repository}/get/{commit}.tar.gz'], 'buildifier': ['https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}'], 'github': ['https://github.com/{repository}/archive/{commit}.tar.gz'], 'pypi': ['https://files.pythonhosted.org/packages/source/{... |
#!/usr/bin/env python3.4
# coding: utf-8
class Drawable:
"""
Base class for drawable objects.
"""
def draw(self):
"""
Returns a Surface object.
"""
raise NotImplementedError(
"Method `draw` is not implemented for {}".format(type(self)))
| class Drawable:
"""
Base class for drawable objects.
"""
def draw(self):
"""
Returns a Surface object.
"""
raise not_implemented_error('Method `draw` is not implemented for {}'.format(type(self))) |
def integrate_exponential(a, x0, dt, T):
"""Compute solution of the differential equation xdot=a*x with
initial condition x0 for a duration T. Use time step dt for numerical
solution.
Args:
a (scalar): parameter of xdot (xdot=a*x)
x0 (scalar): initial condition (x at time 0)
dt (scalar): timeste... | def integrate_exponential(a, x0, dt, T):
"""Compute solution of the differential equation xdot=a*x with
initial condition x0 for a duration T. Use time step dt for numerical
solution.
Args:
a (scalar): parameter of xdot (xdot=a*x)
x0 (scalar): initial condition (x at time 0)
dt (scalar): times... |
class Animal():
edad:int
patas:int
ruido:str
nombre: str
kgComida: float = 0
def __init__(self, edad, patas, ruido, nombre):
self.edad =edad
self.patas = patas
self.ruido = ruido
self.nombre = nombre
def comer(self, alimento):
self.kgComida += alimento... | class Animal:
edad: int
patas: int
ruido: str
nombre: str
kg_comida: float = 0
def __init__(self, edad, patas, ruido, nombre):
self.edad = edad
self.patas = patas
self.ruido = ruido
self.nombre = nombre
def comer(self, alimento):
self.kgComida += ali... |
maxWeight = 30
value = [15, 7, 10, 5, 8, 17]
weight = [15, 3, 2, 5, 9, 20]
def bag(pos, selected):
# calcula o total
totalValue = 0
pesoTotal = 0
for i in selected:
totalValue += value[i]
pesoTotal += weight[i]
if pesoTotal > maxWeight:
return (0,0)
if pos >= len(weight):
return (totalValue, pesoT... | max_weight = 30
value = [15, 7, 10, 5, 8, 17]
weight = [15, 3, 2, 5, 9, 20]
def bag(pos, selected):
total_value = 0
peso_total = 0
for i in selected:
total_value += value[i]
peso_total += weight[i]
if pesoTotal > maxWeight:
return (0, 0)
if pos >= len(weight):
return... |
def fibo(n):
return n <= 1 or fibo(n-1) + fibo(n-2)
def fibo_main():
for n in range(1,47):
res = fibo(n)
print("%s\t%s" % (n, res))
fibo_main()
# profiling result for 47 numbers
# profile: python -m profile fibo.py
"""
-1273940835 function calls (275 primitive calls) in 18966.707 seconds
Ordered... | def fibo(n):
return n <= 1 or fibo(n - 1) + fibo(n - 2)
def fibo_main():
for n in range(1, 47):
res = fibo(n)
print('%s\t%s' % (n, res))
fibo_main()
"\n -1273940835 function calls (275 primitive calls) in 18966.707 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall ... |
#!/usr/bin/env python3
# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
"""
* Wiki table for `leathers` C++ project
Expected format:
### Main table
Name | Clang | GCC | MSVC |
-----------------------------|----------|----------|------|
static-ctor-not-thread-safe | *no* ... | """
* Wiki table for `leathers` C++ project
Expected format:
### Main table
Name | Clang | GCC | MSVC |
-----------------------------|----------|----------|------|
static-ctor-not-thread-safe | *no* | *no* | 4640 |
switch | **same** | **same** | 4062 |
... |
# Copyright (C) 2014 VA Linux Systems Japan K.K.
# Copyright (C) 2014 YAMAMOTO Takashi <yamamoto at valinux co jp>
# 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... | class Ofport(object):
def __init__(self, port_name, ofport):
self.port_name = port_name
self.ofport = ofport
@classmethod
def from_ofp_port(cls, ofp_port):
"""Convert from ryu OFPPort."""
return cls(port_name=ofp_port.name, ofport=ofp_port.port_no)
port_name_len = 14
port_n... |
ADDED_KARMA_TO_MEMBER = "Gave {} karma to {}, their karma is now at {}."
REMOVED_KARMA_FROM_MEMBER = "Removed {} karma from {}, their karma is now at {}."
LIST_KARMA_OWN = "You currently have {} karma."
LIST_KARMA_OBJECT = "\"{}\" currently has {} karma."
LIST_KARMA_MEMBER = "{} currently has {} karma."
KARMA_TOP_STA... | added_karma_to_member = 'Gave {} karma to {}, their karma is now at {}.'
removed_karma_from_member = 'Removed {} karma from {}, their karma is now at {}.'
list_karma_own = 'You currently have {} karma.'
list_karma_object = '"{}" currently has {} karma.'
list_karma_member = '{} currently has {} karma.'
karma_top_start =... |
# simple test function that uses python 3 features (e.g., f-strings)
# see https://github.com/localstack/localstack/issues/264
def handler(event, context):
# the following line is Python 3.6+ specific
msg = f"Successfully processed {event}" # noqa This code is Python 3.6+ only
return event
| def handler(event, context):
msg = f'Successfully processed {event}'
return event |
def decimal_to_binary_fraction(x=0.5):
"""
Input: x, a float between 0 and 1
Returns binary representation of x
"""
p = 0
while ((2 ** p) * x) % 1 != 0:
# print('Remainder = ' + str((2**p)*x - int((2**p)*x)))
p += 1
num = int(x * (2 ** p))
result = ''
if num == 0:
... | def decimal_to_binary_fraction(x=0.5):
"""
Input: x, a float between 0 and 1
Returns binary representation of x
"""
p = 0
while 2 ** p * x % 1 != 0:
p += 1
num = int(x * 2 ** p)
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num % 2) + r... |
def deco1(func):
print("before myfunc() called.")
func()
print("after myfunc() called.")
def myfunc():
print("myfunc() called.")
deco1(myfunc)
| def deco1(func):
print('before myfunc() called.')
func()
print('after myfunc() called.')
def myfunc():
print('myfunc() called.')
deco1(myfunc) |
class ShoppingCart(object):
def __init__(self):
self.total = 0
self.items = dict()
def add_item(self, item_name, quantity, price):
if item_name != None and quantity >= 1:
self.items.update({item_name: quantity})
if quantity and price >= 1:
self.total += (quantity * price)
def re... | class Shoppingcart(object):
def __init__(self):
self.total = 0
self.items = dict()
def add_item(self, item_name, quantity, price):
if item_name != None and quantity >= 1:
self.items.update({item_name: quantity})
if quantity and price >= 1:
self.total += ... |
def solution(bridge_length, weight, truck_weights):
answer = 0
# { weight, time }
wait = truck_weights[:]
bridge = []
passed = 0
currWeight = 0
while True:
if passed == len(truck_weights) and len(wait) == 0: return answer
answer += 1
# sth needs to be passed
... | def solution(bridge_length, weight, truck_weights):
answer = 0
wait = truck_weights[:]
bridge = []
passed = 0
curr_weight = 0
while True:
if passed == len(truck_weights) and len(wait) == 0:
return answer
answer += 1
if bridge:
if bridge[0]['t'] + b... |
"""Holds the device gemoetry parameters (Table 5), taken from Wu et al.,
>> A Predictive 3-D Source/Drain Resistance Compact Model and the Impact on 7 nm and Scaled FinFets<<, 2020, with interpolation for 4nm. 16nm is taken from PTM HP.
"""
node_names = [16, 7, 5, 4, 3]
GP = [64, 56, 48, 44, 41]
FP = [40, 30, 28, 24, ... | """Holds the device gemoetry parameters (Table 5), taken from Wu et al.,
>> A Predictive 3-D Source/Drain Resistance Compact Model and the Impact on 7 nm and Scaled FinFets<<, 2020, with interpolation for 4nm. 16nm is taken from PTM HP.
"""
node_names = [16, 7, 5, 4, 3]
gp = [64, 56, 48, 44, 41]
fp = [40, 30, 28, 24, 2... |
def check_difference():
pass
def update_benchmark():
pass
| def check_difference():
pass
def update_benchmark():
pass |
# while True:
# # ejecuta esto
# print("Hola")
real = 7
print("Entre un numero entre el 1 y el 10")
guess = int(input())
# =/=
while guess != real:
print("Ese no es el numero")
print("Entre un numero entre el 1 y el 10")
guess = int(input())
# el resto
print("Yay! Lo sacastes!")
| real = 7
print('Entre un numero entre el 1 y el 10')
guess = int(input())
while guess != real:
print('Ese no es el numero')
print('Entre un numero entre el 1 y el 10')
guess = int(input())
print('Yay! Lo sacastes!') |
class Foo:
def bar(self):
return "a"
if __name__ == "__main__":
f = Foo()
b = f.bar()
print(b) | class Foo:
def bar(self):
return 'a'
if __name__ == '__main__':
f = foo()
b = f.bar()
print(b) |
'''
Speed: 95.97%
Memory: 24.96%
Time complexity: O(n)
Space complexity: O(n)
'''
class Solution(object):
def longestValidParentheses(self, s):
ans=0
stack=[-1]
for i in range(len(s)):
if(s[i]=='('):
stack.append(i)
else:
stack.pop()
... | """
Speed: 95.97%
Memory: 24.96%
Time complexity: O(n)
Space complexity: O(n)
"""
class Solution(object):
def longest_valid_parentheses(self, s):
ans = 0
stack = [-1]
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack... |
def greet():
print("Hi")
def greet_again(message):
print(message)
def greet_again_with_type(message):
print(type(message))
print(message)
greet()
greet_again("Hello Again")
greet_again_with_type("One Last Time")
greet_again_with_type(1234)
# multiple types
def multiple_types(x):
if x < 0:
... | def greet():
print('Hi')
def greet_again(message):
print(message)
def greet_again_with_type(message):
print(type(message))
print(message)
greet()
greet_again('Hello Again')
greet_again_with_type('One Last Time')
greet_again_with_type(1234)
def multiple_types(x):
if x < 0:
return -1
el... |
# Authentication & API Keys
# Many APIs require an API key. Just as a real-world key allows you to access something, an API key grants you access to a particular API. Moreover, an API key identifies you to the API, which helps the API provider keep track of how their service is used and prevent unauthorized or maliciou... | api_key = 'string' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 18 08:40:11 2020
@author: krishan
"""
def funny_division2(anumber):
try:
if anumber == 13:
raise ValueError("13 is an unlucky number")
return 100 / anumber
except (ZeroDivisionError, TypeError):
return "E... | """
Created on Thu Jun 18 08:40:11 2020
@author: krishan
"""
def funny_division2(anumber):
try:
if anumber == 13:
raise value_error('13 is an unlucky number')
return 100 / anumber
except (ZeroDivisionError, TypeError):
return 'Enter a number other than zero'
def funny_divi... |
class BackupUnit(object):
def __init__(self, name, password=None, email=None):
"""
BackupUnit class initializer.
:param name: A name of that resource (only alphanumeric characters are acceptable)"
:type name: ``str``
:param password: The password associated ... | class Backupunit(object):
def __init__(self, name, password=None, email=None):
"""
BackupUnit class initializer.
:param name: A name of that resource (only alphanumeric characters are acceptable)"
:type name: ``str``
:param password: The password associated... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.