content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Runtime: 328 ms, faster than 44.59% of Python3 online submissions for 4Sum II.
# Memory Usage: 34 MB, less than 86.63% of Python3 online submissions for 4Sum II.
class Solution:
def fourSumCount(self, A, B, C, D):
ab = {}
for i in A:
for j in B:
ab[i + j] = ab.get(i+j, ... | class Solution:
def four_sum_count(self, A, B, C, D):
ab = {}
for i in A:
for j in B:
ab[i + j] = ab.get(i + j, 0) + 1
res = 0
for i in C:
for j in D:
res += ab.get(-i - j, 0)
return res |
# This problem was recently asked by Amazon:
# Given a string, return the first recurring letter that appears. If there are no recurring letters, return None.
def first_recurring_char(s):
# Fill this in.
stack = []
for i in s:
if i in stack:
return i
else:
stack.ap... | def first_recurring_char(s):
stack = []
for i in s:
if i in stack:
return i
else:
stack.append(i)
return None
print(first_recurring_char('qwertty'))
print(first_recurring_char('qwerty')) |
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
tweets['lang'] = map(lambda tweet: tweet['lang'], tweets_data)
tweets['country'] = map(lambda tweet: tweet['place']['country']
if tweet['place'] != None else None, tweets_data)
tweets_by_lang = tweets['lang'].value_counts()
fig, ax = plt.subplots(fi... | tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
tweets['lang'] = map(lambda tweet: tweet['lang'], tweets_data)
tweets['country'] = map(lambda tweet: tweet['place']['country'] if tweet['place'] != None else None, tweets_data)
tweets_by_lang = tweets['lang'].value_counts()
(fig, ax) = plt.subplots(figsize=... |
def readFile(filename):
try:
with open(filename,"r") as f:
print(f.read())
except FileNotFoundError:
print(f"File {filename} is not Found in this Directory.")
readFile("01_i.txt")
readFile("01_ii.txt")
readFile("01_iii.txt")
# ---------------------------------------
... | def read_file(filename):
try:
with open(filename, 'r') as f:
print(f.read())
except FileNotFoundError:
print(f'File {filename} is not Found in this Directory.')
read_file('01_i.txt')
read_file('01_ii.txt')
read_file('01_iii.txt') |
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
r = len(matrix)
c= len(matrix[0])
rows0 = set()
cols0 = set()
for i in range(r):
for j in range(c):
... | class Solution:
def set_zeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
r = len(matrix)
c = len(matrix[0])
rows0 = set()
cols0 = set()
for i in range(r):
for j in range(c):
... |
level = 3
name = 'Cilengkrang'
capital = 'Jatiendah'
area = 30.12
| level = 3
name = 'Cilengkrang'
capital = 'Jatiendah'
area = 30.12 |
## \namespace cohereModels
"""
This is the PyTurbSim 'coherence models' package.
For more information or to use this module import the cohereModels.api
package, e.g.:
import pyts.cohereModels.api as cm
"""
| """
This is the PyTurbSim 'coherence models' package.
For more information or to use this module import the cohereModels.api
package, e.g.:
import pyts.cohereModels.api as cm
""" |
# Display the DataFrame hours using print
print(hours)
# Create a bar plot from the DataFrame hours
plt.bar(hours.officer, hours.avg_hours_worked)
# Display the plot
plt.show()
# Display the DataFrame hours using print
print(hours)
# Create a bar plot from the DataFrame hours
plt.bar(hours.officer, h... | print(hours)
plt.bar(hours.officer, hours.avg_hours_worked)
plt.show()
print(hours)
plt.bar(hours.officer, hours.avg_hours_worked, yerr=hours.std_hours_worked)
plt.show()
plt.bar(hours.officer, hours.desk_work, label='Desk Work')
plt.show()
plt.bar(hours.officer, hours.desk_work, label='Desk Work')
plt.bar(hours.office... |
class Dice_loss(nn.Module):
def __init__(self,type_weight=None,weights=None,ignore_index=None):
super(Dice_loss,self).__init__()
self.type_weight = type_weight
self.weights=weights
self.ignore_index=ignore_index
def forward(output, target):
"""
output : ... | class Dice_Loss(nn.Module):
def __init__(self, type_weight=None, weights=None, ignore_index=None):
super(Dice_loss, self).__init__()
self.type_weight = type_weight
self.weights = weights
self.ignore_index = ignore_index
def forward(output, target):
"""
output : ... |
assert gradient('red', 'blue') == gradient('red', 'blue')
assert gradient('red', 'blue', start='center') == gradient('red', 'blue')
assert gradient('red', 'blue', start='left') == gradient('red', 'blue', start='left')
assert gradient('red', 'blue') != gradient('red', 'blue', start='left')
assert gradient('red', 'blue'... | assert gradient('red', 'blue') == gradient('red', 'blue')
assert gradient('red', 'blue', start='center') == gradient('red', 'blue')
assert gradient('red', 'blue', start='left') == gradient('red', 'blue', start='left')
assert gradient('red', 'blue') != gradient('red', 'blue', start='left')
assert gradient('red', 'blue',... |
class GlobalStorage:
storage = {'design style': 'dark std',
'debugging': False}
def debug(*args):
s = ''
for arg in args:
s += ' '+str(arg)
if GlobalStorage.storage['debugging']:
print(' --> DEBUG:', s)
# yyep, that's it....
# you m... | class Globalstorage:
storage = {'design style': 'dark std', 'debugging': False}
def debug(*args):
s = ''
for arg in args:
s += ' ' + str(arg)
if GlobalStorage.storage['debugging']:
print(' --> DEBUG:', s) |
"""
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
Output:... | """
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
Output:... |
#!/usr/bin/env python3
def calculate():
I = 10**16
subsets = [0] * 250
subsets[0] = 1
for i in range(1, 250250 +1):
offset = pow(i, i, 250)
subsets = [(val + subsets[(j - offset) % 250]) % I
for (j, val) in enumerate(subsets)]
answer = (subsets[0] - 1) % I
ret... | def calculate():
i = 10 ** 16
subsets = [0] * 250
subsets[0] = 1
for i in range(1, 250250 + 1):
offset = pow(i, i, 250)
subsets = [(val + subsets[(j - offset) % 250]) % I for (j, val) in enumerate(subsets)]
answer = (subsets[0] - 1) % I
return str(answer)
if __name__ == '__main__... |
#
# PySNMP MIB module ADTRAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:13:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) ... |
## Regex validate PIN code
## 7 kyu
## https://www.codewars.com/kata/55f8a9c06c018a0d6e000132
def validate_pin(pin):
#return true or false
if pin.isdigit():
if len(pin) == 4 or len(pin) ==6:
return True
else:
return False
else:
return False
... | def validate_pin(pin):
if pin.isdigit():
if len(pin) == 4 or len(pin) == 6:
return True
else:
return False
else:
return False |
#
# PySNMP MIB module DOCS-SUBMGT3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-SUBMGT3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:28:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) ... |
max_personal_participations = 5
team_size = 3
number_of_students, min_team_participations = map(int, input().split())
personal_participations = map(int, input().split())
eligible_personal_participations = len(list(filter(lambda n: n <= max_personal_participations - min_team_participations,
... | max_personal_participations = 5
team_size = 3
(number_of_students, min_team_participations) = map(int, input().split())
personal_participations = map(int, input().split())
eligible_personal_participations = len(list(filter(lambda n: n <= max_personal_participations - min_team_participations, personal_participations)))
... |
"""
moth.py
Copyright 2013 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af 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 version 2 of the License.
w3af is distributed in the hope that it wil... | """
moth.py
Copyright 2013 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af 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 version 2 of the License.
w3af is distributed in the hope that it wil... |
def add(x,y):
'''Add two numbers'''
return(x+y)
def subtract(x,y):
'''Subtract y from x'''
return(x-y)
def multiply(x,y):
'''Multiply x and y'''
return(x*y)
def divide(x,y):
'''Divide x by y'''
if y == 0:
raise ValueError('Cannot divide by 0')
return(x/y)
| def add(x, y):
"""Add two numbers"""
return x + y
def subtract(x, y):
"""Subtract y from x"""
return x - y
def multiply(x, y):
"""Multiply x and y"""
return x * y
def divide(x, y):
"""Divide x by y"""
if y == 0:
raise value_error('Cannot divide by 0')
return x / y |
#
# PySNMP MIB module AtiSwitch-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AtiSwitch-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:17:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
name = "Positional Encoding"
description = """
The positional encoding is a data augmentation strategy first developed in the natural language processing literature.
It has gained widespread adoption as a simple and effective strategy to improve the performance of neural networks in
modelling spatially resolved funct... | name = 'Positional Encoding'
description = '\nThe positional encoding is a data augmentation strategy first developed in the natural language processing literature. \nIt has gained widespread adoption as a simple and effective strategy to improve the performance of neural networks in \nmodelling spatially resolved func... |
# -*- coding: utf-8 -*-
class ExtendDict(dict):
def __getattr__(self, name):
return self.get(name)
| class Extenddict(dict):
def __getattr__(self, name):
return self.get(name) |
# Created by MechAviv
# Quest ID :: 34915
# Not coded yet
sm.setSpeakerID(3001508)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
if sm.sendAskAccept("#face2#You're gonna go save Mar? It's ... | sm.setSpeakerID(3001508)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
if sm.sendAskAccept("#face2#You're gonna go save Mar? It's really dangerous! Are you sure you want to go?\r\n\r\n ... |
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = {}
self.blocked=[]
def add_edge(self, src, dest,weight):
if self.graph.get(src) == None:
self.graph[src]=[(dest,weight)]
else:
self.graph[src]=self.graph.ge... | class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = {}
self.blocked = []
def add_edge(self, src, dest, weight):
if self.graph.get(src) == None:
self.graph[src] = [(dest, weight)]
else:
self.graph[src] = self.graph.get(src) +... |
# Consider this dictionary.
square_dict = {num: num * num for num in range(11)}
# .items() gives a list of tuple, so if we have a list of tuple
# We should be able to convert it to a dict.
print(square_dict.items())
# list of player and scores
players = ["XXX", "YYY", "ZZZ"]
scores = [100, 98, 45]
# Players and Scor... | square_dict = {num: num * num for num in range(11)}
print(square_dict.items())
players = ['XXX', 'YYY', 'ZZZ']
scores = [100, 98, 45]
score_card = zip(players, scores)
print(score_card)
for item in score_card:
print(item)
for (name, score) in zip(players, scores):
print(name, score)
score_list = [f'Name {name} ... |
#!/usr/bin/env python3.10
FILE='test_s1.txt' # in: C200B40A82 sol: 3
FILE='test_s2.txt' # in: 04005AC33890 sol: 54
FILE='test_s3.txt' # in: 880086C3E88112 sol: 7
FILE='test_s4.txt' # in: CE00C43D881120 sol: 9
FILE='test_s5.txt' # in: D8005AC2A8F0 sol: 1
FILE='test_s6.txt' # in: F600BC2D8F sol: 0
FILE='test_s7.txt' # in... | file = 'test_s1.txt'
file = 'test_s2.txt'
file = 'test_s3.txt'
file = 'test_s4.txt'
file = 'test_s5.txt'
file = 'test_s6.txt'
file = 'test_s7.txt'
file = 'test_s8.txt'
file = 'input.txt'
def parse_input(file):
with open(file, 'r') as f:
line = f.readline().rstrip()
print(f'line: {line}')
bi... |
"""caracteristicas gerais."""
a = 7
b = 'eduardo'
def func(x, y):
return x + y
print(func(7, 7))
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
def __repr__(self):
return f'Pessoa(nome="{self.nome}", idade={self.idade})'
| """caracteristicas gerais."""
a = 7
b = 'eduardo'
def func(x, y):
return x + y
print(func(7, 7))
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
def __repr__(self):
return f'Pessoa(nome="{self.nome}", idade={self.idade})' |
class _ResourceMap:
"""
A class to represent a set of resources that a rank maps to.
This is a combination of hardware threads, cores, gpus, memory.
A rank may map to multiple cores and gpus.
"""
def __init__(self):
self.core_ids = None
self.gpu_ids = None
class _RANKMap:
"... | class _Resourcemap:
"""
A class to represent a set of resources that a rank maps to.
This is a combination of hardware threads, cores, gpus, memory.
A rank may map to multiple cores and gpus.
"""
def __init__(self):
self.core_ids = None
self.gpu_ids = None
class _Rankmap:
"... |
def soma(a, b):
x = a + b
y = 'qualquer coisa'
if x > 5:
return x
else:
return y
def soma(a, b):
x = a + b
y = 'qualquer coisa'
yield x
yield y
def soma(a, b):
x = a + b
y = 'qualquer coisa'
return (x, y)
#https://pt.stackoverflow.com/q/331155/101
| def soma(a, b):
x = a + b
y = 'qualquer coisa'
if x > 5:
return x
else:
return y
def soma(a, b):
x = a + b
y = 'qualquer coisa'
yield x
yield y
def soma(a, b):
x = a + b
y = 'qualquer coisa'
return (x, y) |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
best_sum=nums[0]
current_sum=nums[0]
for i in (nums[1:]):
current_sum= max(i, current_sum + i)
best_sum=max(best_sum,current_sum)
return best_sum
| class Solution:
def max_sub_array(self, nums: List[int]) -> int:
best_sum = nums[0]
current_sum = nums[0]
for i in nums[1:]:
current_sum = max(i, current_sum + i)
best_sum = max(best_sum, current_sum)
return best_sum |
class ArrayCodec(object):
"""
This is a default encoding to pack the data. Designed for best storage in ascii.
You can use a custom encoder for eg. larger data sizes, more felxibility, etc.
Currently, this handles arrays with no keys, and max 2**8 ids and 62**4 counts.
Originally used base64 encodi... | class Arraycodec(object):
"""
This is a default encoding to pack the data. Designed for best storage in ascii.
You can use a custom encoder for eg. larger data sizes, more felxibility, etc.
Currently, this handles arrays with no keys, and max 2**8 ids and 62**4 counts.
Originally used base64 encodi... |
# this function will return a number depending on the balance of parentheses
def is_balanced(text):
count = 0
# loops through inputted text
for char in text:
# adds one to count if there is an open paren
if char == '(':
count += 1
# subtracts one if there is a closed pa... | def is_balanced(text):
count = 0
for char in text:
if char == '(':
count += 1
if char == ')':
count -= 1
if count == -1:
return count
if count > 0:
return 1
return count |
class ConstraintTypesEnum(object):
PRIMARY_KEY = "PRIMARY KEY"
FOREIGN_KEY = "FOREIGN KEY"
UNIQUE = "UNIQUE"
types = [
PRIMARY_KEY,
FOREIGN_KEY,
UNIQUE,
]
@classmethod
def get_types_str(cls):
return ", ".join(cls.types)
@classmethod
def get_types_co... | class Constrainttypesenum(object):
primary_key = 'PRIMARY KEY'
foreign_key = 'FOREIGN KEY'
unique = 'UNIQUE'
types = [PRIMARY_KEY, FOREIGN_KEY, UNIQUE]
@classmethod
def get_types_str(cls):
return ', '.join(cls.types)
@classmethod
def get_types_comma(cls):
return ', '.jo... |
# Name:
# Date:
# proj01: A Simple Program
# Part I:
# This program asks the user for his/her name and grade.
#Then, it prints out a sentence that says the number of years until they graduate.
name = input("What is your name? ")
name = name[0].upper() + name[1:]
grade = int(input("That is a cool name. What grade are... | name = input('What is your name? ')
name = name[0].upper() + name[1:]
grade = int(input('That is a cool name. What grade are you in? '))
years = str(13 - grade)
print(name + ', you will graduate in ' + years + ' years!')
bmonth = int(input('What month were you born in, ' + name + '? '))
bday = int(input('What day were ... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list
@param x: An integer
@return: A ListNode
"""
def partition(self, head, x):
if not... | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list
@param x: An integer
@return: A ListNode
"""
def partition(self, head, x):
if no... |
#
# PySNMP MIB module CISCO-OAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:51:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) ... |
n=str(input("Enter the mail id"))
le=len(n)
st=""
for i in range(le):
if n[i]=='@':
break
else:
st+=n[i]
print(st)
| n = str(input('Enter the mail id'))
le = len(n)
st = ''
for i in range(le):
if n[i] == '@':
break
else:
st += n[i]
print(st) |
class Account:
__accNumber = 0
__balance = 0
def __init__(self, accNumber, balance = 1000):
self.setAccNumber(accNumber) # self.__accNumber = accNumber # the double underscore hides the info
self.setBalance(balance)
def getAccountNumber(self):
return self.__accNumber
def s... | class Account:
__acc_number = 0
__balance = 0
def __init__(self, accNumber, balance=1000):
self.setAccNumber(accNumber)
self.setBalance(balance)
def get_account_number(self):
return self.__accNumber
def set_acc_number(self, accNumber):
if len(accNumber) != 10 or no... |
#
# PySNMP MIB module CABH-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CABH-QOS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:44:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, constraints_union, value_size_constraint, single_value_constraint) ... |
#1->groundBlock
groundBlock=(48,0,16,16)
#2->supriseBlock
supriseBlock=(96,16,16,16)
#3->floatingBlock
floatingBlock=(0,0,16,16)
#4->obstacleBlock
obstacleBlock=(80,0,16,16)
#5->pipes
pipes=(256,96,32,32) | ground_block = (48, 0, 16, 16)
suprise_block = (96, 16, 16, 16)
floating_block = (0, 0, 16, 16)
obstacle_block = (80, 0, 16, 16)
pipes = (256, 96, 32, 32) |
#
# @lc app=leetcode id=292 lang=python3
#
# [292] Nim Game
#
# @lc code=start
class Solution:
def canWinNim(self, n: int) -> bool:
"""
time: O(1)
space: O(1)
"""
return n % 4 != 0
# @lc code=end
| class Solution:
def can_win_nim(self, n: int) -> bool:
"""
time: O(1)
space: O(1)
"""
return n % 4 != 0 |
"""
.. Dstl (c) Crown Copyright 2019
"""
class Report:
"""Report class, stores the noisified data with the faults and ground truth
for future use. Delegates all methods and attribute_readers to the observed item."""
def __init__(self, identifier, truth, triggered_faults, observed):
self.identifier... | """
.. Dstl (c) Crown Copyright 2019
"""
class Report:
"""Report class, stores the noisified data with the faults and ground truth
for future use. Delegates all methods and attribute_readers to the observed item."""
def __init__(self, identifier, truth, triggered_faults, observed):
self.identifier... |
letter ='''Dear <|NAME|>
Greetings from VITian student. I am verry happy to tell you about your selection in our club
You are selecteed
Have a great day aheas!
Thanks and regards.
Bill
Date: <|DATE|>
'''
name = input("Enter Your Name\n")
date = input("Enter Date\n")
letter=letter.replace("<|NAME|>", name)
le... | letter = 'Dear <|NAME|>\nGreetings from VITian student. I am verry happy to tell you about your selection in our club\nYou are selecteed\nHave a great day aheas!\nThanks and regards.\nBill\nDate: <|DATE|>\n'
name = input('Enter Your Name\n')
date = input('Enter Date\n')
letter = letter.replace('<|NAME|>', name)
letter ... |
def clip_bbox(dataset_bounds, bbox):
"""
Clips the bbox so it is no larger than the dataset bounds.
Parameters
----------
dataset_bounds: list of lon / lat bounds. E.g., [[-108, -104], [40, 42]]
represents the extent bounded by:
* -108 deg longitude on the west
... | def clip_bbox(dataset_bounds, bbox):
"""
Clips the bbox so it is no larger than the dataset bounds.
Parameters
----------
dataset_bounds: list of lon / lat bounds. E.g., [[-108, -104], [40, 42]]
represents the extent bounded by:
* -108 deg longitude on the west
... |
"""
Get input for the following scenarios. Make sure the data is manipulatable.
1. The name of the user
2. How many children to they have?
3. How old is there oldest child, if N/A input 0
4. Are they married?
5. What is their hourly wage?
"""
name = input("What is your name?")
children = int(input("How many children d... | """
Get input for the following scenarios. Make sure the data is manipulatable.
1. The name of the user
2. How many children to they have?
3. How old is there oldest child, if N/A input 0
4. Are they married?
5. What is their hourly wage?
"""
name = input('What is your name?')
children = int(input('How many children do... |
def main() -> None:
N = int(input())
A = list(map(int, input().split()))
assert 1 <= N <= 100
assert len(A) == N
assert 2 <= A[0]
assert A[-1] <= 10**18
for i in range(1, N):
assert A[i - 1] < A[i]
if __name__ == '__main__':
main()
| def main() -> None:
n = int(input())
a = list(map(int, input().split()))
assert 1 <= N <= 100
assert len(A) == N
assert 2 <= A[0]
assert A[-1] <= 10 ** 18
for i in range(1, N):
assert A[i - 1] < A[i]
if __name__ == '__main__':
main() |
"""Static variables used in the module"""
# Using integers because it shouldn't be matchable to anything in the config
ANY = 0
NAME_TO_UPPER = 1
NAME_AS_IS = 2
| """Static variables used in the module"""
any = 0
name_to_upper = 1
name_as_is = 2 |
def request_resolver(func):
def _wrapped_view(request, *args, **kwargs):
if 'dev' in request.path:
kwargs['report_type'] = 'dummy'
return func(request, *args, **kwargs)
else:
kwargs['report_type'] = 'status'
return func(request, *args, **kwargs)
return _wrapped_view | def request_resolver(func):
def _wrapped_view(request, *args, **kwargs):
if 'dev' in request.path:
kwargs['report_type'] = 'dummy'
return func(request, *args, **kwargs)
else:
kwargs['report_type'] = 'status'
return func(request, *args, **kwargs)
r... |
"""
Unmerged conflicts in status, which are one of:
DD unmerged, both deleted
AU unmerged, added by us
UD unmerged, deleted by them
UA unmerged, added by them
DU unmerged, deleted by us
AA unmerged, both added
UU unmerged, both modified
"""
MERGE_CONFLICT_PORCELAIN_STAT... | """
Unmerged conflicts in status, which are one of:
DD unmerged, both deleted
AU unmerged, added by us
UD unmerged, deleted by them
UA unmerged, added by them
DU unmerged, deleted by us
AA unmerged, both added
UU unmerged, both modified
"""
merge_conflict_porcelain_stat... |
def return_value(status, message, data=None, status_code=200):
return_object = dict()
return_object['status'] = status
return_object['message'] = message
if data:
return_object['data'] = data
return return_object, status_code
| def return_value(status, message, data=None, status_code=200):
return_object = dict()
return_object['status'] = status
return_object['message'] = message
if data:
return_object['data'] = data
return (return_object, status_code) |
class TxtFile:
def read_file(self,PATH_FILE):
fd = open(PATH_FILE, mode='r')
data = fd.read()
fd.close()
return data
| class Txtfile:
def read_file(self, PATH_FILE):
fd = open(PATH_FILE, mode='r')
data = fd.read()
fd.close()
return data |
a=8
b=28
i=0
while(b>=0):
b=b-a
i=i+1
b=b+a
print(b,i) | a = 8
b = 28
i = 0
while b >= 0:
b = b - a
i = i + 1
b = b + a
print(b, i) |
words = input().split(", ")
input_string = input()
list_new = [i for i in words if i in input_string]
print(list_new)
| words = input().split(', ')
input_string = input()
list_new = [i for i in words if i in input_string]
print(list_new) |
with open('input', 'r') as raw:
i = sorted(raw.read().strip().split('\n'))
guard = None
sleeping = False
start = None
change = False
guards = {}
for line in i:
minute = int(line[15:17])
if line[19] == 'f':
sleeping = True
start = minute
elif line[19] == 'w':
sleeping = False
... | with open('input', 'r') as raw:
i = sorted(raw.read().strip().split('\n'))
guard = None
sleeping = False
start = None
change = False
guards = {}
for line in i:
minute = int(line[15:17])
if line[19] == 'f':
sleeping = True
start = minute
elif line[19] == 'w':
sleeping = False
... |
bind = "0.0.0.0:8000"
workers = 10
pythonpath = "/home/box/web/ask"
errorlog = "/home/box/web/etc/ask-error.log"
loglevel = "debug"
| bind = '0.0.0.0:8000'
workers = 10
pythonpath = '/home/box/web/ask'
errorlog = '/home/box/web/etc/ask-error.log'
loglevel = 'debug' |
# Link to the problem: https://www.hackerrank.com/challenges/common-child/problem
def commonChild(s1, s2, n):
prev_lcs = [0]*(n+1)
curr_lcs = [0]*(n+1)
for c1 in s1:
curr_lcs, prev_lcs = prev_lcs, curr_lcs
for i, c2 in enumerate(s2, 1):
curr_lcs[i] = (
1 + prev_l... | def common_child(s1, s2, n):
prev_lcs = [0] * (n + 1)
curr_lcs = [0] * (n + 1)
for c1 in s1:
(curr_lcs, prev_lcs) = (prev_lcs, curr_lcs)
for (i, c2) in enumerate(s2, 1):
curr_lcs[i] = 1 + prev_lcs[i - 1] if c1 == c2 else max(prev_lcs[i], curr_lcs[i - 1])
return curr_lcs[-1]
s... |
"""
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:... | """
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:... |
class database:
def __init__(self, conn):
self.conn = conn
@staticmethod
def db_schema(db_conn):
db_conn.execute('''CREATE TABLE "computers" (
"id" integer PRIMARY KEY,
"ip" text,
"hostname" text,
"domain" text,
"os" text,
... | class Database:
def __init__(self, conn):
self.conn = conn
@staticmethod
def db_schema(db_conn):
db_conn.execute('CREATE TABLE "computers" (\n "id" integer PRIMARY KEY,\n "ip" text,\n "hostname" text,\n "domain" text,\n "os" text,\n ... |
class Entry:
def __init__(self):
self.image_path = ""
self.image_small = ""
self.image_full = ""
self.source = ""
self.tags = []
self.score = -1
self.headers = {}
self.title = None
def as_dict(self):
return {'path': self.image_path,
... | class Entry:
def __init__(self):
self.image_path = ''
self.image_small = ''
self.image_full = ''
self.source = ''
self.tags = []
self.score = -1
self.headers = {}
self.title = None
def as_dict(self):
return {'path': self.image_path, 'url'... |
def mergeIntervals(arr):
new = list()
arr.sort(key=lambda x:x[0])
for i in range(0, len(arr)):
if not new or new[-1][1] < arr[i][0]:
new.append(arr[i])
else:
new[-1][1] = max(new[-1][1], arr[i][1])
return new
arr = [[2,3],[4,5],[6,7],[8,9],[1,10]]
new = m... | def merge_intervals(arr):
new = list()
arr.sort(key=lambda x: x[0])
for i in range(0, len(arr)):
if not new or new[-1][1] < arr[i][0]:
new.append(arr[i])
else:
new[-1][1] = max(new[-1][1], arr[i][1])
return new
arr = [[2, 3], [4, 5], [6, 7], [8, 9], [1, 10]]
new =... |
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
assert isinstance(candidates, list) and isinstance(target, int)
if not candidates:
return
def dfs(l,r,target,rst):
if r+1<l or target < 0:
retur... | class Solution:
def combination_sum2(self, candidates: List[int], target: int) -> List[List[int]]:
assert isinstance(candidates, list) and isinstance(target, int)
if not candidates:
return
def dfs(l, r, target, rst):
if r + 1 < l or target < 0:
retur... |
'''
Convert English miles to Roman paces
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
paces = 5280000 * float(input()) / 4854
result = int(paces)
if paces - result >= 0.5:
result += 1
pr... | """
Convert English miles to Roman paces
Status: Accepted
"""
def main():
"""Read input and print output"""
paces = 5280000 * float(input()) / 4854
result = int(paces)
if paces - result >= 0.5:
result += 1
print(result)
if __name__ == '__main__':
main() |
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
ans = []
for i in range(2**len(nums)):
bitmask = bin(i)[2:]
bitmask = '0'*(len(nums)-len(bitmask)) + bitmask
ans.append([nums[j] for j in range(len(nums)) if bitmask[j] == '1'])
... | class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
ans = []
for i in range(2 ** len(nums)):
bitmask = bin(i)[2:]
bitmask = '0' * (len(nums) - len(bitmask)) + bitmask
ans.append([nums[j] for j in range(len(nums)) if bitmask[j] == '1'])
... |
"""Metadata for the FastAPI instance"""
# Main
TITLE = "Hive Global Notification System (API)"
DESCRIPTION = """
Global notification system for dApps on the Hive Blockchain.
"""
VERSION = "1.0"
CONTACT = {
"name": "imwatsi",
"url": "https://hive.blog/@imwatsi",
"email": "imwatsi@outlook.com",
}
LI... | """Metadata for the FastAPI instance"""
title = 'Hive Global Notification System (API)'
description = '\n Global notification system for dApps on the Hive Blockchain.\n'
version = '1.0'
contact = {'name': 'imwatsi', 'url': 'https://hive.blog/@imwatsi', 'email': 'imwatsi@outlook.com'}
license = {'name': 'MIT License'... |
ACTIVATED_TEXT = 'ACTIVATED'
ACTIVATION_DAYS = 7
REMEMBER_ME_DAYS = 30
LOGIN_REDIRECT_URL = 'home'
DEFAULT_AVATAR_URL = 'files/no_image/avatar.jpg'
| activated_text = 'ACTIVATED'
activation_days = 7
remember_me_days = 30
login_redirect_url = 'home'
default_avatar_url = 'files/no_image/avatar.jpg' |
list = ['gilbert', 'cuerbo', 'defante', 'exam']
# for loop
for name in list:
print(f' - { name }')
for i in range(0, 5):
print(f' * { i }')
# while loop
index = 0
while index < len(list):
print(f' # {list[index]}')
index = index + 1 | list = ['gilbert', 'cuerbo', 'defante', 'exam']
for name in list:
print(f' - {name}')
for i in range(0, 5):
print(f' * {i}')
index = 0
while index < len(list):
print(f' # {list[index]}')
index = index + 1 |
class BlastLine(object):
__slots__ = ('query', 'subject', 'pctid', 'hitlen', 'nmismatch', 'ngaps', \
'qstart', 'qstop', 'sstart', 'sstop', 'eval', 'score')
def __init__(self, sline):
args = sline.split("\t")
self.query =args[0]
self.subject = args[1]
self.pcti... | class Blastline(object):
__slots__ = ('query', 'subject', 'pctid', 'hitlen', 'nmismatch', 'ngaps', 'qstart', 'qstop', 'sstart', 'sstop', 'eval', 'score')
def __init__(self, sline):
args = sline.split('\t')
self.query = args[0]
self.subject = args[1]
self.pctid = float(args[2])
... |
class hosp_features():
def __init__(self):
self.P_GOLD = '#FFD700'
self.P_ORANGE = "#F08000"
self.P_BLU = "#0000FF"
self.P_DARK_BLU = "#000080"
self.P_GREEN = "#66ff99"
self.P_DARK_GREEN = "#026b2c"
self.P_FUCHSIA = "#FF00FF"
self.P_PURPLE = "#cf0... | class Hosp_Features:
def __init__(self):
self.P_GOLD = '#FFD700'
self.P_ORANGE = '#F08000'
self.P_BLU = '#0000FF'
self.P_DARK_BLU = '#000080'
self.P_GREEN = '#66ff99'
self.P_DARK_GREEN = '#026b2c'
self.P_FUCHSIA = '#FF00FF'
self.P_PURPLE = '#cf03fc'
... |
'''
This problem was asked by Apple.
Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it.
'''
class FIFOQueue:
def __init__(self):
self.in_stack = ... | """
This problem was asked by Apple.
Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it.
"""
class Fifoqueue:
def __init__(self):
self.in_stack =... |
class FileType(object):
"""The MIME type of the content you are attaching to an Attachment."""
def __init__(self, file_type=None):
"""Create a FileType object
:param file_type: The MIME type of the content you are attaching
:type file_type: string, optional
"""
self._fi... | class Filetype(object):
"""The MIME type of the content you are attaching to an Attachment."""
def __init__(self, file_type=None):
"""Create a FileType object
:param file_type: The MIME type of the content you are attaching
:type file_type: string, optional
"""
self._fi... |
class Fee(object):
def __init__(self):
self.default_fee = 10
self.fee_cushion = 1.2
def calculate_fee(self):
return int(self.default_fee * self.fee_scale * self.load_scale)
def set_fee_scale(self, tx):
fee_base = float(tx['fee_base'])
fee_ref = float(tx['fee_ref'])
fee_scale = fee_base / fee_ref
... | class Fee(object):
def __init__(self):
self.default_fee = 10
self.fee_cushion = 1.2
def calculate_fee(self):
return int(self.default_fee * self.fee_scale * self.load_scale)
def set_fee_scale(self, tx):
fee_base = float(tx['fee_base'])
fee_ref = float(tx['fee_ref'])... |
# O(n) solution, check all elements
class Solution:
def isPeak(self, arr, n):
if n==0:
if arr[n] > arr[n+1]:
return True
else:
return False
if n == len(arr)-1:
if arr[n] > arr[n-1]:
return True
... | class Solution:
def is_peak(self, arr, n):
if n == 0:
if arr[n] > arr[n + 1]:
return True
else:
return False
if n == len(arr) - 1:
if arr[n] > arr[n - 1]:
return True
else:
return False
... |
def cls():
while(i<=15):
print('\n')
i=i+1
| def cls():
while i <= 15:
print('\n')
i = i + 1 |
class DurationTrackingListener(object):
ROBOT_LISTENER_API_VERSION = 3
# The following will measure the duration of each test. This listener will fail each test if they run beyond the maximum run time (max_seconds).
def __init__(self, max_seconds=10):
self.max_milliseconds = float(max_seconds) * 1000
... | class Durationtrackinglistener(object):
robot_listener_api_version = 3
def __init__(self, max_seconds=10):
self.max_milliseconds = float(max_seconds) * 1000
def end_test(self, data, test):
if test.status == 'PASS' and test.elapsedtime > self.max_milliseconds:
test.status = 'FAI... |
class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
# pick each ele to be maximum ele
# Then sliding windows
res = 0
for ind,num in enumerate(nums):
# num itself is in or not
if left <= num <= right:
... | class Solution:
def num_subarray_bounded_max(self, nums: List[int], left: int, right: int) -> int:
res = 0
for (ind, num) in enumerate(nums):
if left <= num <= right:
res += 1
(p1, p2) = (ind - 1, ind + 1)
while p1 > -1 and nums[p1] < num:... |
class Simulation:
def __init__(self, blocks):
self._blocks = blocks
self._finished = False
def run(self):
while not self._finished:
self._step()
def _step(self):
visited = set()
queue = [b for b in self._blocks if not b.inputs]
nothing_changed = ... | class Simulation:
def __init__(self, blocks):
self._blocks = blocks
self._finished = False
def run(self):
while not self._finished:
self._step()
def _step(self):
visited = set()
queue = [b for b in self._blocks if not b.inputs]
nothing_changed =... |
def plus(arr):
p, n, z = 0, 0, 0
for i in arr:
if i>0:
p+=1
elif i<0:
n+=1
else:
z+=1
print(format(p/len(arr), '.6f'))
print(format(n/len(arr), '.6f'))
print(format(z/len(arr), '.6f'))
arr = list(map(int, input().rstrip().split()))
plus(a... | def plus(arr):
(p, n, z) = (0, 0, 0)
for i in arr:
if i > 0:
p += 1
elif i < 0:
n += 1
else:
z += 1
print(format(p / len(arr), '.6f'))
print(format(n / len(arr), '.6f'))
print(format(z / len(arr), '.6f'))
arr = list(map(int, input().rstrip(... |
# Mary McHale, 14th April 2018
# Project based on Iris Data, Working out the mean
# https://docs.python.org/3/tutorial/floatingpoint.html?highlight=significant%20digits for reducing the number of decimal places in the mean
f = open('data/iris.csv' , 'r')
# This opens the file called iris.csv
print("Means are bel... | f = open('data/iris.csv', 'r')
print('Means are below')
print(' pl pw sl sw')
c = 0
totpl = 0
totpw = 0
totsl = 0
totsw = 0
record = ''
while c < 100000:
record = f.readline()
if record == '':
temp1 = format(totpl / c, ' .1f')
temp2 = format(totpw / c, ' .1f')
temp3 = format(totsl ... |
numbers = [4,2,7,1,8,3,6]
f = 0
x = int(input("Enter the number to be found out: "))
for i in range(len(numbers)):
if (x==numbers[i]):
print(" Successful search, the element is found at position", i)
f = 1
break
if(f==0):
print("Oops! Search unsuccessful") | numbers = [4, 2, 7, 1, 8, 3, 6]
f = 0
x = int(input('Enter the number to be found out: '))
for i in range(len(numbers)):
if x == numbers[i]:
print(' Successful search, the element is found at position', i)
f = 1
break
if f == 0:
print('Oops! Search unsuccessful') |
"""Variant 3"""
current_day = float(10)
percent = 1.1
summa = 0
for i in range(7):
summa += current_day
current_day *= percent
print("Ran in 7 days: %.3f" % summa)
| """Variant 3"""
current_day = float(10)
percent = 1.1
summa = 0
for i in range(7):
summa += current_day
current_day *= percent
print('Ran in 7 days: %.3f' % summa) |
a_binary_string = "110000 1100110 1011111"
binary_values = a_binary_string.split()
ascii_string = ""
for binary_value in binary_values:
an_integer = int(binary_value, 2)
ascii_character = chr(an_integer)
ascii_string += ascii_character
print(ascii_string) | a_binary_string = '110000 1100110 1011111'
binary_values = a_binary_string.split()
ascii_string = ''
for binary_value in binary_values:
an_integer = int(binary_value, 2)
ascii_character = chr(an_integer)
ascii_string += ascii_character
print(ascii_string) |
n= str(input('Qual seu nome completo?')).lower()
print ('No seu nome tem Silva?','silva'in n)
n1= str(input('Digite um numero:'))
print ('Existe o numero 1?','1' in n1)
| n = str(input('Qual seu nome completo?')).lower()
print('No seu nome tem Silva?', 'silva' in n)
n1 = str(input('Digite um numero:'))
print('Existe o numero 1?', '1' in n1) |
data = (
'Qiao ', # 0x00
'Chou ', # 0x01
'Bei ', # 0x02
'Xuan ', # 0x03
'Wei ', # 0x04
'Ge ', # 0x05
'Qian ', # 0x06
'Wei ', # 0x07
'Yu ', # 0x08
'Yu ', # 0x09
'Bi ', # 0x0a
'Xuan ', # 0x0b
'Huan ', # 0x0c
'Min ', # 0x0d
'Bi ', # 0x0e
'Yi ', # 0x0f
'Mian ', # 0x10
'Yon... | data = ('Qiao ', 'Chou ', 'Bei ', 'Xuan ', 'Wei ', 'Ge ', 'Qian ', 'Wei ', 'Yu ', 'Yu ', 'Bi ', 'Xuan ', 'Huan ', 'Min ', 'Bi ', 'Yi ', 'Mian ', 'Yong ', 'Kai ', 'Dang ', 'Yin ', 'E ', 'Chen ', 'Mou ', 'Ke ', 'Ke ', 'Yu ', 'Ai ', 'Qie ', 'Yan ', 'Nuo ', 'Gan ', 'Yun ', 'Zong ', 'Sai ', 'Leng ', 'Fen ', '[?] ', 'Kui ', ... |
[[0,3],[2,7],[3,4],[4,6]]
[0,6]
def find_min_intervals(intervals, target):
intervals.sort()
res = 0
cur_target = target[0]
i = 0
max_step = 0
while i < len(intervals) and cur_target < target[1]:
while i < len(intervals) and intervals[i][0] <= cur_target:
max_step = max(max_... | [[0, 3], [2, 7], [3, 4], [4, 6]]
[0, 6]
def find_min_intervals(intervals, target):
intervals.sort()
res = 0
cur_target = target[0]
i = 0
max_step = 0
while i < len(intervals) and cur_target < target[1]:
while i < len(intervals) and intervals[i][0] <= cur_target:
max_step = m... |
class TaskHandler():
def __init__(self, tasks=[]):
self.tasks = tasks
def add(self):
pass
def delete(self):
pass
def clear_all(self):
pass
def show_info(self):
pass
class Task():
def __init__(self, task_name, sub_tasks, date):
self.task_name ... | class Taskhandler:
def __init__(self, tasks=[]):
self.tasks = tasks
def add(self):
pass
def delete(self):
pass
def clear_all(self):
pass
def show_info(self):
pass
class Task:
def __init__(self, task_name, sub_tasks, date):
self.task_name = t... |
BOT_NAME = 'czech_political_parties'
SPIDER_MODULES = ['czech_political_parties.spiders']
USER_AGENT = 'czech-political-parties (+https://github.com/honzajavorek/czech-political-parties)'
FEED_EXPORTERS = {
'sorted_json': 'czech_political_parties.exporters.SortedJsonItemExporter',
}
FEEDS = {
'items.json': ... | bot_name = 'czech_political_parties'
spider_modules = ['czech_political_parties.spiders']
user_agent = 'czech-political-parties (+https://github.com/honzajavorek/czech-political-parties)'
feed_exporters = {'sorted_json': 'czech_political_parties.exporters.SortedJsonItemExporter'}
feeds = {'items.json': {'format': 'sort... |
class Document(object):
"""Output of pipeline"""
def __init__(self):
self.sentences = [] # List of sentence objects
def __iter__(self):
return iter(self.sentences)
@property
def stuples(self):
"""Semantic tuples from every sentences"""
return [stuple for sent in s... | class Document(object):
"""Output of pipeline"""
def __init__(self):
self.sentences = []
def __iter__(self):
return iter(self.sentences)
@property
def stuples(self):
"""Semantic tuples from every sentences"""
return [stuple for sent in self.sentences for stuple in ... |
#
# This file contains the Python code from Program 7.20 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm07_20.txt
#
class Polynomial(C... | class Polynomial(Container):
def __init__(self):
super(Polynomial, self).__init__()
def add_term(self, term):
pass
add_term = abstractmethod(addTerm)
def differentiate(self):
pass
differentiate = abstractmethod(differentiate)
def __add__(self, polynomial):
pas... |
"""https://github.com/stevecshanks/lift-kata/blob/master/tests/SmallControllerTest.php"""
class Person:
def __init__(self, name, current_floor, destination):
pass
class SmallLift:
def __init__(self, floor):
pass
def getTotalNumberOfVisits(self):
return 0
class SmallControlle... | """https://github.com/stevecshanks/lift-kata/blob/master/tests/SmallControllerTest.php"""
class Person:
def __init__(self, name, current_floor, destination):
pass
class Smalllift:
def __init__(self, floor):
pass
def get_total_number_of_visits(self):
return 0
class Smallcontroll... |
class JWTExtendedException(Exception):
"""
Base except which all flask_graphql_auth errors extend
"""
pass
class JWTDecodeError(JWTExtendedException):
"""
An error decoding a JWT
"""
pass
class NoAuthorizationError(JWTExtendedException):
"""
An error raised when no authoriz... | class Jwtextendedexception(Exception):
"""
Base except which all flask_graphql_auth errors extend
"""
pass
class Jwtdecodeerror(JWTExtendedException):
"""
An error decoding a JWT
"""
pass
class Noauthorizationerror(JWTExtendedException):
"""
An error raised when no authorizatio... |
def minion_game(s):
ls = 'AEIOU'
a = 0
b = 0
n = len(s)
for i in range(0,n):
val = n - i
if ls.find(s[i]) == -1:
a += val
else:
b += val
if a > b:
print('Stuart',a)
elif b > a:
print('Kevin',b)
else:
print('Draw')
s = input()
minion_game(s) | def minion_game(s):
ls = 'AEIOU'
a = 0
b = 0
n = len(s)
for i in range(0, n):
val = n - i
if ls.find(s[i]) == -1:
a += val
else:
b += val
if a > b:
print('Stuart', a)
elif b > a:
print('Kevin', b)
else:
print('Draw')... |
"""*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... | """*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... |
n = 500
# This is the final formula after lots of counting.
# First notice how squares are on the upper right diagonal,
# then work you way towards the total.
print(int(1 + 2 / 3 * n * (8 * n ** 2 + 15 * n + 13)))
| n = 500
print(int(1 + 2 / 3 * n * (8 * n ** 2 + 15 * n + 13))) |
a = int(input('Digete um valor: '))
print(type(a))
b = bool(input('Digete um valor: '))
print(type(b))
c = float(input('Digete um valor: '))
print(type(c))
d = str(input('Digete um valor: '))
print(type(d))
| a = int(input('Digete um valor: '))
print(type(a))
b = bool(input('Digete um valor: '))
print(type(b))
c = float(input('Digete um valor: '))
print(type(c))
d = str(input('Digete um valor: '))
print(type(d)) |
# -*- coding: utf-8 -*-
# Helper functions
def return_sublist(main_list, indices ):
sublist = [[item[i] for i in indices] for item in main_list]
return sublist | def return_sublist(main_list, indices):
sublist = [[item[i] for i in indices] for item in main_list]
return sublist |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def github_archive(org, repo, version, ext):
return "https://github.com/{org}/{repo}/archive/{version}.{ext}".format(
org=org, repo=repo, version=version, ext=ext)
def github_prefix(repo, version):
return "{repo}-{version}".format(... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def github_archive(org, repo, version, ext):
return 'https://github.com/{org}/{repo}/archive/{version}.{ext}'.format(org=org, repo=repo, version=version, ext=ext)
def github_prefix(repo, version):
return '{repo}-{version}'.format(repo=repo, ... |
# -*- coding: utf-8 -*-
A = input()
B = input()
X = A + B
print ("X = %i" %X) | a = input()
b = input()
x = A + B
print('X = %i' % X) |
"""
'a1m' is the boiler and everything around that.
Example:
{
"SlaveId": 1,
"BaudRate": 3,
"Parity": 0,
"FirmwareVersion": 30012,
"DetectedSystemType": 1,
"FaultCode": 8000,
"SystemState": 1,
"OperatingMode": 0,
"OperatingModeDHW": 1,
... | """
'a1m' is the boiler and everything around that.
Example:
{
"SlaveId": 1,
"BaudRate": 3,
"Parity": 0,
"FirmwareVersion": 30012,
"DetectedSystemType": 1,
"FaultCode": 8000,
"SystemState": 1,
"OperatingMode": 0,
"OperatingModeDHW": 1,
... |
# -*- coding: utf-8 -*-
# ____________________________________________________________________ BaseModel
class BaseEstimator():
"""The base class that every model used for :class:`skassist` must inherit
from. It defines the interface through which the module trains the model
and makes predictions. It also ... | class Baseestimator:
"""The base class that every model used for :class:`skassist` must inherit
from. It defines the interface through which the module trains the model
and makes predictions. It also defines a few mandatory properties that must
be set. Those are used by the module to identify the model ... |
class UnwrapError(Exception):
pass
class RedisProtocolFormatError(Exception):
pass
class ExceptionWithReplyError(Exception):
def __init__(self, reply="ERR", *args):
super().__init__(*args)
self.reply = reply
class NoPasswordError(ExceptionWithReplyError):
pass
class WrongComman... | class Unwraperror(Exception):
pass
class Redisprotocolformaterror(Exception):
pass
class Exceptionwithreplyerror(Exception):
def __init__(self, reply='ERR', *args):
super().__init__(*args)
self.reply = reply
class Nopassworderror(ExceptionWithReplyError):
pass
class Wrongcommand(Exc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.