content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
_ = 1 < 3
_ = 1 <= 3
_ = 1 < input() and input() > 3
_ = 1 < input() and input() >= 3
_ = 1 < input() and 1 <= input() and input() >= 3
| _ = 1 < 3
_ = 1 <= 3
_ = 1 < input() and input() > 3
_ = 1 < input() and input() >= 3
_ = 1 < input() and 1 <= input() and (input() >= 3) |
def get_input(filename):
data = []
with open(filename, 'r') as i:
for x in i.readlines():
data.append(int(x))
return data
def count_increases(measurements):
previous = measurements[0]
increases = 0
for measurement in measurements[1:]:
if measurement > previous:
... | def get_input(filename):
data = []
with open(filename, 'r') as i:
for x in i.readlines():
data.append(int(x))
return data
def count_increases(measurements):
previous = measurements[0]
increases = 0
for measurement in measurements[1:]:
if measurement > previous:
... |
def stockmax(p):
ind_max = p.index(max(p)) #find the max price
inv = sum(p[:ind_max]) #split the array before and after max price
pf = len(p[:ind_max])*p[ind_max] - inv #buy all stocks before max price
if len(p[ind_max+1:]) > 0:
pf += stockmax(p[ind_max+1:]) #then sell them at max price
ret... | def stockmax(p):
ind_max = p.index(max(p))
inv = sum(p[:ind_max])
pf = len(p[:ind_max]) * p[ind_max] - inv
if len(p[ind_max + 1:]) > 0:
pf += stockmax(p[ind_max + 1:])
return pf |
"""
Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
cl... | """
Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
cl... |
def multiply(m, n):
if n > m:
m, n = n, m
if n == 0:
return 0
return m + multiply(m, n - 1)
# print(multiply(3, 5))
def rec(x, y): # x ^ y
if y > 0:
return x * rec(x, y - 1)
return 1
# print(rec(3, 5))
def hailstone(n):
# n is even: n = n / 2
# n is odd: n =... | def multiply(m, n):
if n > m:
(m, n) = (n, m)
if n == 0:
return 0
return m + multiply(m, n - 1)
def rec(x, y):
if y > 0:
return x * rec(x, y - 1)
return 1
def hailstone(n):
if n == 1:
return 1
if n % 2 == 0:
return 1 + hailstone(n // 2)
return 1 ... |
"""
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
// 4 -> 5 -> 6
//prev cur nextTemp
// 4 -> 5 -> 6
// prev cur nextTemp
"""
class Solution206:
pass
| """
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
// 4 -> 5 -> 6
//prev cur nextTemp
// 4 -> 5 -> 6
// prev cur nextTemp
"""
class Solution206:
pass |
# Utility functions
def mk_param_summary(hyperparams):
return '__'.join([hpname + '_' + val for hpname, val in hyperparams.items()])
def insert_param_summary(filename, param_summary):
basename, extn = filename.rsplit('.', 1)
return basename + '__' + param_summary + '.' + extn
def combinations(ll):
... | def mk_param_summary(hyperparams):
return '__'.join([hpname + '_' + val for (hpname, val) in hyperparams.items()])
def insert_param_summary(filename, param_summary):
(basename, extn) = filename.rsplit('.', 1)
return basename + '__' + param_summary + '.' + extn
def combinations(ll):
last_pass = []
... |
side = 1080
thickness = side*0.4
frames = 84
def skPts():
points = []
for i in range(360):
x = cos(radians(i))
y = sin(radians(i))
points.append((x, y))
return points
def shape(step, var):
speed = var/step
fill(1, 1, 1, 0.05)
stroke(None)
shape = BezierPath()
... | side = 1080
thickness = side * 0.4
frames = 84
def sk_pts():
points = []
for i in range(360):
x = cos(radians(i))
y = sin(radians(i))
points.append((x, y))
return points
def shape(step, var):
speed = var / step
fill(1, 1, 1, 0.05)
stroke(None)
shape = bezier_path()
... |
#EJERCICIO PRACTICO NUMERO 5
print("===========================")
print("EJERCICIO PRACTICO NUMERO 5")
print("===========================\n")
print("=====================")
print("SUCESION DE FIBONACC1")
print("=====================\n")
x, y= 0, 1
while y <= 1597:
print(x, y, end = " ")
x = x + y
y = x ... | print('===========================')
print('EJERCICIO PRACTICO NUMERO 5')
print('===========================\n')
print('=====================')
print('SUCESION DE FIBONACC1')
print('=====================\n')
(x, y) = (0, 1)
while y <= 1597:
print(x, y, end=' ')
x = x + y
y = x + y
print('\nFin.') |
"""Helps manage notes stored as plain files in the filesystem.
If you installed via ``pip``, run ``notesdir -h` to get help.
Or, run ``python3 -m notesdir -h``.
To use the Python API, look at :class:`notesdir.api.Notesdir`
"""
| """Helps manage notes stored as plain files in the filesystem.
If you installed via ``pip``, run ``notesdir -h` to get help.
Or, run ``python3 -m notesdir -h``.
To use the Python API, look at :class:`notesdir.api.Notesdir`
""" |
class MaxBoxGen():
def findMaxRect(data):
"""http://stackoverflow.com/a/30418912/5008845"""
nrows, ncols = data.shape
w = np.zeros(dtype=int, shape=data.shape)
h = np.zeros(dtype=int, shape=data.shape)
skip = 1
area_max = (0, [])
for r in range(nrows):
... | class Maxboxgen:
def find_max_rect(data):
"""http://stackoverflow.com/a/30418912/5008845"""
(nrows, ncols) = data.shape
w = np.zeros(dtype=int, shape=data.shape)
h = np.zeros(dtype=int, shape=data.shape)
skip = 1
area_max = (0, [])
for r in range(nrows):
... |
'''
need to be very calm to solve this kind of problem
should never confuse yourself, keep clear mind
there is only 2 cases:
1. there is idle: using Counter to solve this case
2. there is no idle: len(tasks)
'''
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
if not task... | """
need to be very calm to solve this kind of problem
should never confuse yourself, keep clear mind
there is only 2 cases:
1. there is idle: using Counter to solve this case
2. there is no idle: len(tasks)
"""
class Solution:
def least_interval(self, tasks: List[str], n: int) -> int:
if not ta... |
print ("Hello \
world")
# Backslash(\) is a special character that creates whitespace
| print('Hello world') |
"""Test the TcEx Utils Module."""
# pylint: disable=no-self-use
class TestBool:
"""Test the TcEx Utils Module."""
def test_utils_encrypt(self, tcex):
"""Test writing a temp file to disk.
Args:
tcex (TcEx, fixture): An instantiated instance of TcEx object.
"""
key ... | """Test the TcEx Utils Module."""
class Testbool:
"""Test the TcEx Utils Module."""
def test_utils_encrypt(self, tcex):
"""Test writing a temp file to disk.
Args:
tcex (TcEx, fixture): An instantiated instance of TcEx object.
"""
key = 'ajfmuyodhscwegea'
pl... |
s = 'nothyp_onan@'
l = [1,2,3,4,5,6,7,8,9]
print(s[::-1])
print(l[::-1])
print(reversed(l))
l1 = l.reverse
print(l1) | s = 'nothyp_onan@'
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(s[::-1])
print(l[::-1])
print(reversed(l))
l1 = l.reverse
print(l1) |
class BaseContest(object):
'''BaseContest is an abstract class for contest-specific modifications to
Marathoner.
'''
def __init__(self, project):
self.project = project
self.maximize = project.maximize
def extract_score(self, visualizer_stdout, solution_stderr):
'''Extract r... | class Basecontest(object):
"""BaseContest is an abstract class for contest-specific modifications to
Marathoner.
"""
def __init__(self, project):
self.project = project
self.maximize = project.maximize
def extract_score(self, visualizer_stdout, solution_stderr):
"""Extract ... |
def slices(series: str, length: int) -> list[str]:
size = len(series)
if length > size or length < 1:
raise ValueError("Invalid Input")
return [series[i:i + length] for i in range(size - length + 1)]
| def slices(series: str, length: int) -> list[str]:
size = len(series)
if length > size or length < 1:
raise value_error('Invalid Input')
return [series[i:i + length] for i in range(size - length + 1)] |
#!/usr/bin/env python3
input = '52554437147555553177771524418267843219182859995942215316362429449983637161192948458385799435625432472399695557917723926815678834498379821192395363253412635244153971238243584678919637629487233277745457158515424298321191791399144715235153322473174417191845568913621792673683254866423766856... | input = '52554437147555553177771524418267843219182859995942215316362429449983637161192948458385799435625432472399695557917723926815678834498379821192395363253412635244153971238243584678919637629487233277745457158515424298321191791399144715235153322473174417191845568913621792673683254866423766856577596238768549587216365... |
#Time Complexity: O(n)
#Space Complexity: O(1)
#Speed: 84.65%
#Memory: 84.34%
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token.isdigit() or token[1:].isdigit():
stack.append(int(token))
else:
... | class Solution:
def eval_rpn(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token.isdigit() or token[1:].isdigit():
stack.append(int(token))
else:
y = stack.pop()
x = stack.pop()
if token ==... |
#
# PySNMP MIB module SNA-SDLC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNA-SDLC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:52:15 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')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) ... |
"""
## Questions: MEDIUM
### 1845. [Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/)
Design a system that manages the reservation state of n seats that are numbered from 1 to n.
Implement the SeatManager class:
SeatManager(int n) Initializes a SeatManager object that will manage n s... | """
## Questions: MEDIUM
### 1845. [Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/)
Design a system that manages the reservation state of n seats that are numbered from 1 to n.
Implement the SeatManager class:
SeatManager(int n) Initializes a SeatManager object that will manage n s... |
class MyWorkflow(object):
def __init__(self):
pass
def step3(self, session_time = None):
print("Step3 of session {0}".format(session_time))
| class Myworkflow(object):
def __init__(self):
pass
def step3(self, session_time=None):
print('Step3 of session {0}'.format(session_time)) |
#Criando o teste de convergencia 2 (Criterio de Sessenfeld):
def convergencia_2(matriz, num):
print('\n\nCriterio de Sessenfeld:')
beta = list()
for i in range(0, num):
beta.append(1)
for l in range(0, num):
soma = 0;
for c in range(0, dimensao):
if c != l:
soma = soma + (math.fabs(mat... | def convergencia_2(matriz, num):
print('\n\nCriterio de Sessenfeld:')
beta = list()
for i in range(0, num):
beta.append(1)
for l in range(0, num):
soma = 0
for c in range(0, dimensao):
if c != l:
soma = soma + math.fabs(matriz[l][c]) * beta[c]
... |
def flatten(myList):
newList = []
for item in myList:
if type(item) == list:
newList.extend(flatten(item))
else:
newList.append(item)
return newList
def main():
myList1 = [1,2,3,[1,2],5,[3,4,5,6,7]]
print(flatten(myList1))
myList2 = [1,[2,[3,[4,[5,[6,[7,[... | def flatten(myList):
new_list = []
for item in myList:
if type(item) == list:
newList.extend(flatten(item))
else:
newList.append(item)
return newList
def main():
my_list1 = [1, 2, 3, [1, 2], 5, [3, 4, 5, 6, 7]]
print(flatten(myList1))
my_list2 = [1, [2, [... |
#
# This file is part of the profilerTools suite (see
# https://github.com/mssm-labmmol/profiler).
#
# Copyright (c) 2020 mssm-labmmol
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software withou... | class Cmdlineopts(object):
n_procs = 1
traj_files = []
stp_files = []
wei_files = []
ref_files = []
input_file = ''
out_prefix = 'profopt'
dihspec_files = None
debug_emm = False
class Optopts(object):
n_tors = 1
b_opt_phase = False
opt_tors = [1, 2, 3, 4, 5, 6]
lj_ma... |
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
x=[]
for i,j in enumerate(mat):
x.append(j[i])
x.append(j[len(mat)-(i+1)])
if len(mat)%2==0:
return sum(x)
else:
y=mat[len(mat)//2]
z=y[len(mat)//2]
... | class Solution:
def diagonal_sum(self, mat: List[List[int]]) -> int:
x = []
for (i, j) in enumerate(mat):
x.append(j[i])
x.append(j[len(mat) - (i + 1)])
if len(mat) % 2 == 0:
return sum(x)
else:
y = mat[len(mat) // 2]
z = y... |
# The MIT License (MIT)
#
# Copyright (c) 2018 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... | class Ordereddict(object):
"""
This class implements a dictionary that can treat non-hashable
datatypes as keys. It is implemented as a list of key/value pairs,
thus it is very slow compared to a traditional hash-based dictionary.
Access times are:
==== ======= =====
Best Average Worst
==== ======= ... |
class Node:
def __init__(self, data) -> None:
self.data = data
self.right = self.down = None
class LinkedList:
def __init__(self) -> None:
self.head = self.rear = None
def insert(self, item, location):
temp = Node(item)
if self.rear == None:
... | class Node:
def __init__(self, data) -> None:
self.data = data
self.right = self.down = None
class Linkedlist:
def __init__(self) -> None:
self.head = self.rear = None
def insert(self, item, location):
temp = node(item)
if self.rear == None:
self.head ... |
#continue dan break bisa digunakan di For-Loop dan While-Loop
#Belajar Continue --> Men-skip proses looping sehingga melanjutkan looping selanjutnya
#definisi menurut aris --> digunakan utk menolak data range
for i in range(1,10):
if (i) % 2 == 1: #artinya ganjil
continue #statment TRUE di atas a... | for i in range(1, 10):
if i % 2 == 1:
continue
print(i)
for io in range(1, 10):
if io % 2 == 0:
continue
print(io)
print('====BREAK====')
for io in range(1, 100):
if io % 45 == 0:
break
print(io)
while True:
data = input('Masukkan pengulangan :')
if data == 'x':
... |
# define a function that finds the truth by shifting the letter by the specified amount
def lassoLetter( letter, shiftAmount ):
# invoke the ord function to translate the letter to its ASCII code
# and save it to the variable called letterCode
letterCode = ord(letter.lower())
# the ASCII number re... | def lasso_letter(letter, shiftAmount):
letter_code = ord(letter.lower())
a_ascii = ord('a')
alphabet_size = 26
true_letter_code = aAscii + (letterCode - aAscii + shiftAmount) % alphabetSize
decoded_letter = chr(trueLetterCode)
return decodedLetter
def lasso_word(word, shiftAmount):
decoded_... |
t=int(input())
if t>=1:
print("bigger than 1")
else:
print("smaller than 1") | t = int(input())
if t >= 1:
print('bigger than 1')
else:
print('smaller than 1') |
# Copyright 2015 Jason T Clark
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | def pre_compile(S, E, N, D, M, O, R, Y):
return D + 10 * N + 100 * E + 1000 * S + (E + 10 * R + 100 * O + 1000 * M) == Y + 10 * E + 100 * N + 1000 * O + 10000 * M
lambda S, E, N, D, M, O, R, Y: D + 10 * N + 100 * E + 1000 * S + (E + 10 * R + 100 * O + 1000 * M) == Y + 10 * E + 100 * N + 1000 * O + 10000 * M |
for i in range(1,101):
if(i%3==0 and i%5==0):
print("FizzBuzz")
if(i%3==0):
print("Fizz")
if(i%5==0):
print("Buzz")
else:
print(i) | for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
if i % 3 == 0:
print('Fizz')
if i % 5 == 0:
print('Buzz')
else:
print(i) |
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
l = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
elem = []
elem.append(i)
elem.append(j)
elem.... | if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
l = []
for i in range(x + 1):
for j in range(y + 1):
for k in range(z + 1):
elem = []
elem.append(i)
elem.append(j)
e... |
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 101020400
# East Forest :: Magician Association
KINESIS = 1531000
NERO = 1531003
THREE_MOON = 1531004
sm.setNpcOverrideBoxChat(NERO)
sm.sendNext("#face1#Good job! See, you're getting faster every time.")
sm.completeQuest(parentID)
sm.giveExp(11500)
| kinesis = 1531000
nero = 1531003
three_moon = 1531004
sm.setNpcOverrideBoxChat(NERO)
sm.sendNext("#face1#Good job! See, you're getting faster every time.")
sm.completeQuest(parentID)
sm.giveExp(11500) |
kwargs = {"a": 1, "b": 2, "c": 3}
print(kwargs.pop("d"))
| kwargs = {'a': 1, 'b': 2, 'c': 3}
print(kwargs.pop('d')) |
#!/usr/bin/env python3
class Interface:
""" Defines the interface of the padding oracle. """
def oracle(self, ciphertext):
""" This function expects a ciphertext and returns true if there is
no padding error and false otherwise.
Args:
ciphertext (bytes): the ciphertext tha... | class Interface:
""" Defines the interface of the padding oracle. """
def oracle(self, ciphertext):
""" This function expects a ciphertext and returns true if there is
no padding error and false otherwise.
Args:
ciphertext (bytes): the ciphertext that should be checked
... |
#!/usr/bin/env python3
def reverse_str(name: str) -> str:
""" Reverses a string """
name_lst = list(name)
name_lst.reverse()
ret = ''
for i in range(len(name_lst)):
ret += name_lst[i]
return ret
| def reverse_str(name: str) -> str:
""" Reverses a string """
name_lst = list(name)
name_lst.reverse()
ret = ''
for i in range(len(name_lst)):
ret += name_lst[i]
return ret |
print("Printing n fibonacci numbers")
i=1
x=0
y=1
p=int(input("How many numbers would you like to have displayed: "))
while(i<=p):
print(x,end=' ')
s=x+y
x=y
y=s
i=i+1
print("\n\nEnd of Program\n")
print("Press \"Enter key\" to exit")
u=input()
| print('Printing n fibonacci numbers')
i = 1
x = 0
y = 1
p = int(input('How many numbers would you like to have displayed: '))
while i <= p:
print(x, end=' ')
s = x + y
x = y
y = s
i = i + 1
print('\n\nEnd of Program\n')
print('Press "Enter key" to exit')
u = input() |
# Write your solutions for 1.5 here!
class Superheros:
def __init__(self, name,superpower, strengh):
self.name = name
self.superpower = superpower
self.strengh = strengh
def name_strengh(self):
print("the name of the superhero is: " + self.name +",his strengh level is: "+str(self.strengh))
def save_civilian(... | class Superheros:
def __init__(self, name, superpower, strengh):
self.name = name
self.superpower = superpower
self.strengh = strengh
def name_strengh(self):
print('the name of the superhero is: ' + self.name + ',his strengh level is: ' + str(self.strengh))
def save_civili... |
A=[[1,2, 8], [3, 7,4]]
B=[[5,6, 9], [7,6 ,0]]
c=[]
for i in range(len(A)): #range of len gives me indecesc.
c.append([])
for j in range(len(A[i])):
sum = A[i][j]+B[i][j]
c[i].append(sum)
print(c)
# for i in range(len(A)): #range of len gives me indeces
# for j in range(len(A[i])): #again ind... | a = [[1, 2, 8], [3, 7, 4]]
b = [[5, 6, 9], [7, 6, 0]]
c = []
for i in range(len(A)):
c.append([])
for j in range(len(A[i])):
sum = A[i][j] + B[i][j]
c[i].append(sum)
print(c) |
# output shape openpose keypoints for body, hands, and face
body_keypoints_num = 25
left_hand_keyp_num = 21
right_hand_keyp_num = 21
face_keyp_num = 51
face_contour_keyp_num = 17
| body_keypoints_num = 25
left_hand_keyp_num = 21
right_hand_keyp_num = 21
face_keyp_num = 51
face_contour_keyp_num = 17 |
class Hello:
def __init__(self, name):
self.name = name
def say(self):
print('Hello!,', self.name) | class Hello:
def __init__(self, name):
self.name = name
def say(self):
print('Hello!,', self.name) |
class A:
def __init__(self):
super().__init__()
print("A")
class B(A):
def __init__(self):
super().__init__()
print("B")
class C:
def __init__(self):
super().__init__()
print("C")
class D(B, C):
def __init__(self):
super().__init__()
... | class A:
def __init__(self):
super().__init__()
print('A')
class B(A):
def __init__(self):
super().__init__()
print('B')
class C:
def __init__(self):
super().__init__()
print('C')
class D(B, C):
def __init__(self):
super().__init__()
... |
class ServiceError(Exception):
pass
class LicenceError(Exception):
pass
class AccountError(Exception):
pass
class RateLimited(Exception):
pass
codeToError = {
0: "There was an error contacting the ProfanityBlocker service. Please try again later.",
104: "There was an error with your licence ... | class Serviceerror(Exception):
pass
class Licenceerror(Exception):
pass
class Accounterror(Exception):
pass
class Ratelimited(Exception):
pass
code_to_error = {0: 'There was an error contacting the ProfanityBlocker service. Please try again later.', 104: 'There was an error with your licence for Prof... |
with open("../pokemon_type_relations.csv", "r") as reader:
header = reader.readline().split(",") # Read header
while True:
line = reader.readline()
if not line:
break
line = line.split(",")
attacker = line[0]
weak = []
... | with open('../pokemon_type_relations.csv', 'r') as reader:
header = reader.readline().split(',')
while True:
line = reader.readline()
if not line:
break
line = line.split(',')
attacker = line[0]
weak = []
strong = []
immune = []
for i i... |
N = int(input())
vals1 = [int(a) for a in input().split()]
vals2 = [int(a) for a in input().split()]
total = 0
for i in range(N):
h1, h2 = vals1[i], vals1[i + 1]
width = vals2[i]
h_dif = abs(h1 - h2)
min_h = min(h1, h2)
total += min_h * width
total += (h_dif * width) / 2
print(total) | n = int(input())
vals1 = [int(a) for a in input().split()]
vals2 = [int(a) for a in input().split()]
total = 0
for i in range(N):
(h1, h2) = (vals1[i], vals1[i + 1])
width = vals2[i]
h_dif = abs(h1 - h2)
min_h = min(h1, h2)
total += min_h * width
total += h_dif * width / 2
print(total) |
WIDTH = 16
HEIGHT = 32
FIRST = 0
LAST = 255
_FONT = \
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x0... | width = 16
height = 32
first = 0
last = 255
_font = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x... |
record_list=[]
y=int(input('Enter no.of records to be entered'))
for x in range(1,y+1,1):
name=input('Enter name: ')
roll_num=int(input("Enter roll number: "))
sub=input("Enter subject: ")
score=float(input("Enter score: "))
record_list.append([name,roll_num,sub,score])
print(record_list)
q=1
f... | record_list = []
y = int(input('Enter no.of records to be entered'))
for x in range(1, y + 1, 1):
name = input('Enter name: ')
roll_num = int(input('Enter roll number: '))
sub = input('Enter subject: ')
score = float(input('Enter score: '))
record_list.append([name, roll_num, sub, score])
print(reco... |
# Copyright 2020 The Monogon Project Authors.
#
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... | load('@bazel_gazelle//:deps.bzl', 'go_repository')
load('@io_bazel_rules_go//go:def.bzl', 'GoLibrary', 'go_context', 'go_library')
def _bindata_impl(ctx):
out = ctx.actions.declare_file('bindata.go')
arguments = ctx.actions.args()
arguments.add_all(['-pkg', ctx.attr.package, '-prefix', ctx.label.workspace_... |
names = [
'John',
'Mary',
'Joe',
'Matt',
'David',
'Matt',
'John'
]
results = []
for name in names:
if name in results:
continue
results.append(name)
print(results) | names = ['John', 'Mary', 'Joe', 'Matt', 'David', 'Matt', 'John']
results = []
for name in names:
if name in results:
continue
results.append(name)
print(results) |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'chromium',
'chromium_android',
'recipe_engine/path',
]
def RunSteps(api):
api.chromium.set_config('chromium')
api.chromium_android.stac... | deps = ['chromium', 'chromium_android', 'recipe_engine/path']
def run_steps(api):
api.chromium.set_config('chromium')
api.chromium_android.stackwalker(api.path['checkout'], [api.chromium.output_dir.join('lib.unstripped', 'libchrome.so')])
def gen_tests(api):
yield api.test('basic') |
# For Keystone Engine. AUTO-GENERATED FILE, DO NOT EDIT [systemz_const.py]
KS_ERR_ASM_SYSTEMZ_INVALIDOPERAND = 512
KS_ERR_ASM_SYSTEMZ_MISSINGFEATURE = 513
KS_ERR_ASM_SYSTEMZ_MNEMONICFAIL = 514
| ks_err_asm_systemz_invalidoperand = 512
ks_err_asm_systemz_missingfeature = 513
ks_err_asm_systemz_mnemonicfail = 514 |
#!/usr/bin/env python
NAME = 'Citrix NetScaler'
def is_waf(self):
"""
First checks if a cookie associated with Netscaler is present,
if not it will try to find if a "Cneonction" or "nnCoection" is returned
for any of the attacks sent
"""
# NSC_ and citrix_ns_id come from David S. Langlands <... | name = 'Citrix NetScaler'
def is_waf(self):
"""
First checks if a cookie associated with Netscaler is present,
if not it will try to find if a "Cneonction" or "nnCoection" is returned
for any of the attacks sent
"""
if self.matchcookie('^(ns_af=|citrix_ns_id|NSC_)'):
return True
if ... |
# Copyright 2015 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# GYP file to build experimental directory.
{
'targets': [
{
'target_name': 'experimental',
'type': 'static_library',
'include_dirs': [
'../include/config'... | {'targets': [{'target_name': 'experimental', 'type': 'static_library', 'include_dirs': ['../include/config', '../include/core'], 'sources': ['../experimental/SkSetPoly3To3.cpp', '../experimental/SkSetPoly3To3_A.cpp', '../experimental/SkSetPoly3To3_D.cpp'], 'direct_dependent_settings': {'include_dirs': ['../experimental... |
class NodeCapacity:
def __init__(self, json):
self.cpu = json['cpu']
self.memory = self.__convert_mem_str_to_int__(json['memory'])
self.pods = json['pods']
def __convert_mem_str_to_int__(self, mem_str):
''' unit of retrurned value is Mi '''
value = float(mem_str[0:-2])
... | class Nodecapacity:
def __init__(self, json):
self.cpu = json['cpu']
self.memory = self.__convert_mem_str_to_int__(json['memory'])
self.pods = json['pods']
def __convert_mem_str_to_int__(self, mem_str):
""" unit of retrurned value is Mi """
value = float(mem_str[0:-2])
... |
class nloptSolver( optwSolver ):
def solve( self ):
algorithm = solver[6:]
if( algorithm == "" or algorithm == "MMA" ):
#this is the default
opt = nlopt.opt( nlopt.LD_MMA, self.n )
elif( algorithm == "SLSQP" ):
opt = nlopt.opt( nlopt.LD_SLSQP, self.n )
... | class Nloptsolver(optwSolver):
def solve(self):
algorithm = solver[6:]
if algorithm == '' or algorithm == 'MMA':
opt = nlopt.opt(nlopt.LD_MMA, self.n)
elif algorithm == 'SLSQP':
opt = nlopt.opt(nlopt.LD_SLSQP, self.n)
elif algorithm == 'AUGLAG':
o... |
class Solution:
def trap(self, height: List[int]) -> int:
res = 0
# build memos
max_height_left = [0] * len(height)
max_height_left[0] = height[0]
for i in range(1, len(height)):
max_height_left[i] = max(max_height_left[i-1], height[i])
max_height_right = ... | class Solution:
def trap(self, height: List[int]) -> int:
res = 0
max_height_left = [0] * len(height)
max_height_left[0] = height[0]
for i in range(1, len(height)):
max_height_left[i] = max(max_height_left[i - 1], height[i])
max_height_right = [0] * len(height)
... |
# Copyright esse.io 2016 All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | class Member(object):
"""Fabric Member object
A member is an entity that transacts on a chain.
Types of members include end users, peers, etc.
"""
def __init__(self, chain, **kwargs):
"""Constructor for a member.
:param chain (Chain): the chain instance that the member belong to
... |
"""
Fosdick SDK configuration
"""
# Used for puling information
FOSDICK_API_USERNAME = '<YOUR_API_USERNAME>'
FOSDICK_API_PASSWORD = '<YOUR_API_PASSWORD>'
# Used for order posting.
CLIENT_CODE = '<YOUR_CLIENT_CODE>'
CLIENT_NAME = '<YOUR_CLIENT_NAME>'
# To denote test order.
TESTFLAG = 'y'
# Url's used for pulling in... | """
Fosdick SDK configuration
"""
fosdick_api_username = '<YOUR_API_USERNAME>'
fosdick_api_password = '<YOUR_API_PASSWORD>'
client_code = '<YOUR_CLIENT_CODE>'
client_name = '<YOUR_CLIENT_NAME>'
testflag = 'y'
url = 'https://www.customerstatus.com/fosdickapi/'
place_order_url = 'https://www.unitycart.com/iPost/'
url_ma... |
'''
*
***
*****
*******
*********
*******
*****
***
*
'''
n = int(input())
i = 0
while i < (n//2) + 1:
j = 1
while j <= (n//2) - i:
print(' ', end='')
j += 1
k = 0
while k <= i:
print('*', end='')
k += 1
l = i
while l >= 1:
print('*', ... | """
*
***
*****
*******
*********
*******
*****
***
*
"""
n = int(input())
i = 0
while i < n // 2 + 1:
j = 1
while j <= n // 2 - i:
print(' ', end='')
j += 1
k = 0
while k <= i:
print('*', end='')
k += 1
l = i
while l >= 1:
print('*', e... |
# -*- coding: utf8 -*-
"""
Storage backend definition
Author: Romary Dupuis <romary@me.com>
Copyright (C) 2017 Romary Dupuis
"""
class Backend(object):
""" Basic backend class """
def __init__(self, prefix, secondary_indexes):
self._prefix = prefix
self._secondary_indexes = secondary_indexes... | """
Storage backend definition
Author: Romary Dupuis <romary@me.com>
Copyright (C) 2017 Romary Dupuis
"""
class Backend(object):
""" Basic backend class """
def __init__(self, prefix, secondary_indexes):
self._prefix = prefix
self._secondary_indexes = secondary_indexes
def prefixed(self... |
def take_List(li,Qu_st):
r=[]
for i in range(len(li)):
if(Qu_st in li[i] ):
r.append(li[i])
print(r)
li=['sser','ser','song']
q='ss'
take_List(li,q)
| def take__list(li, Qu_st):
r = []
for i in range(len(li)):
if Qu_st in li[i]:
r.append(li[i])
print(r)
li = ['sser', 'ser', 'song']
q = 'ss'
take__list(li, q) |
_base_ = "./ss_mlBCE_MaskFull_PredDouble_PBR05_woCenter_edgeLower_refinePM10_01_02MasterChefCan.py"
OUTPUT_DIR = "output/self6dpp/ssYCBV/ss_mlBCE_MaskFull_PredDouble_PBR05_woCenter_edgeLower_refinePM10/13_24Bowl"
DATASETS = dict(
TRAIN=("ycbv_024_bowl_train_real_aligned_Kuw",),
TRAIN2=("ycbv_024_bowl_train_pbr"... | _base_ = './ss_mlBCE_MaskFull_PredDouble_PBR05_woCenter_edgeLower_refinePM10_01_02MasterChefCan.py'
output_dir = 'output/self6dpp/ssYCBV/ss_mlBCE_MaskFull_PredDouble_PBR05_woCenter_edgeLower_refinePM10/13_24Bowl'
datasets = dict(TRAIN=('ycbv_024_bowl_train_real_aligned_Kuw',), TRAIN2=('ycbv_024_bowl_train_pbr',))
model... |
class Solution:
def isHappy(self, n: int) -> bool:
l = set()
while True:
s = 0
while n > 0:
s += (n % 10) ** 2
n = n // 10
if s == 1:
return True
if s in l:
return False
n = s
... | class Solution:
def is_happy(self, n: int) -> bool:
l = set()
while True:
s = 0
while n > 0:
s += (n % 10) ** 2
n = n // 10
if s == 1:
return True
if s in l:
return False
n = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Problem 076
Integers Come In All Sizes
Source : https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes/problem
"""
a, b, c, d = (int(input()) for _ in range(4))
print(a**b + c**d)
| """Problem 076
Integers Come In All Sizes
Source : https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes/problem
"""
(a, b, c, d) = (int(input()) for _ in range(4))
print(a ** b + c ** d) |
try:
fd = file("/srv/www/htdocs/index.html")
_head = ""
buf = fd.readline()
while buf:
if buf.startswith("<!-- end header -->"):
break
_head += buf
buf = fd.readline()
except IOError:
_head="""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E... | try:
fd = file('/srv/www/htdocs/index.html')
_head = ''
buf = fd.readline()
while buf:
if buf.startswith('<!-- end header -->'):
break
_head += buf
buf = fd.readline()
except IOError:
_head = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><h... |
DATABASE_ENGINE = 'sqlite3'
SECRET_KEY = 'abcd123'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': './example.db',
}
}
INSTALLED_APPS = (
'django_bouncy',
)
BOUNCY_TOPIC_ARN = ['arn:aws:sns:us-east-1:250214102493:Demo_App_Unsubscribes']
TEST_RUNNER = 'django_n... | database_engine = 'sqlite3'
secret_key = 'abcd123'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': './example.db'}}
installed_apps = ('django_bouncy',)
bouncy_topic_arn = ['arn:aws:sns:us-east-1:250214102493:Demo_App_Unsubscribes']
test_runner = 'django_nose.NoseTestSuiteRunner'
nose_args = ['-... |
while 1:
a = int(input("please input a: "))
b = int(input("please input b: "))
print(a+b)
| while 1:
a = int(input('please input a: '))
b = int(input('please input b: '))
print(a + b) |
name = "pybah"
version = "5"
requires = ["python-2.5"]
| name = 'pybah'
version = '5'
requires = ['python-2.5'] |
def test_user_can_register_and_then_login_then_logout(simpy_test_container, firefox_browser):
# Edith has heard about a new app to help manage her invoices
# She opens a browser and navigates to the registration page
firefox_browser.get('http://127.0.0.1:5000/')
# She notices that the name of the app i... | def test_user_can_register_and_then_login_then_logout(simpy_test_container, firefox_browser):
firefox_browser.get('http://127.0.0.1:5000/')
assert 'SimpyInvoice' in firefox_browser.title
assert 'Login' in firefox_browser.title
register_link = firefox_browser.find_element_by_id('register')
register_l... |
# -*- coding: utf-8 -*-
# Coded by Sungwook Kim
# 2020-12-14
# IDE: Jupyter Notebook
N = int(input())
def num(N):
b = N
while True:
if b >= 10:
b = b - 10
else:
break
return b
k = -1
res = 0
trig = False
while True:
if trig == False:
b = num(N)
... | n = int(input())
def num(N):
b = N
while True:
if b >= 10:
b = b - 10
else:
break
return b
k = -1
res = 0
trig = False
while True:
if trig == False:
b = num(N)
a = int((N - b) / 10)
c = a + b
d = num(c)
k = b * 10 + d
... |
d = {
0: ["a", "f", "g", "l", "q", "r", "w"],
2: ["b", "m", "x"],
6: ["h", "s"],
12: ["c", "n", "y"],
20: ["i", "t"],
30: ["d", "o", "z"],
42: ["j", "u"],
56: ["e", "p"],
72: ["k", "v"]
}
def dinf_cipher(inp):
inp = inp.split(".")
x = []
for i in inp:
... | d = {0: ['a', 'f', 'g', 'l', 'q', 'r', 'w'], 2: ['b', 'm', 'x'], 6: ['h', 's'], 12: ['c', 'n', 'y'], 20: ['i', 't'], 30: ['d', 'o', 'z'], 42: ['j', 'u'], 56: ['e', 'p'], 72: ['k', 'v']}
def dinf_cipher(inp):
inp = inp.split('.')
x = []
for i in inp:
x.append(i)
final = []
for i in x:
... |
[n, budget] = [int(x) for x in input().split()]
pow2 = [ [ [int(x) for x in input().split() ] for _ in range(n) ] ]
power = 0
while True:
power += 1
pow2.append( [ [ min(budget+1, min(pow2[power-1][i][k] + pow2[power-1][k][j] for k in range(n))) for j in range(n)] for i in range(n)] )
if min(pow2[power][0]) > budg... | [n, budget] = [int(x) for x in input().split()]
pow2 = [[[int(x) for x in input().split()] for _ in range(n)]]
power = 0
while True:
power += 1
pow2.append([[min(budget + 1, min((pow2[power - 1][i][k] + pow2[power - 1][k][j] for k in range(n)))) for j in range(n)] for i in range(n)])
if min(pow2[power][0]) ... |
def is_intersect(box1, box2):
len_x = abs((box1[0] + box1[2]) / 2 - (box2[0] + box2[2]) / 2)
len_y = abs((box1[1] + box1[3]) / 2 - (box2[1] + box2[3]) / 2)
box1_x = abs(box1[0] - box1[2])
box2_x = abs(box2[0] - box2[2])
box1_y = abs(box1[1] - box1[3])
box2_y = abs(box2[1] - box2[3])
... | def is_intersect(box1, box2):
len_x = abs((box1[0] + box1[2]) / 2 - (box2[0] + box2[2]) / 2)
len_y = abs((box1[1] + box1[3]) / 2 - (box2[1] + box2[3]) / 2)
box1_x = abs(box1[0] - box1[2])
box2_x = abs(box2[0] - box2[2])
box1_y = abs(box1[1] - box1[3])
box2_y = abs(box2[1] - box2[3])
if len_x... |
#
# PySNMP MIB module CISCO-MMAIL-DIAL-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-MMAIL-DIAL-CONTROL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:07:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ... |
"""
File: anagram.py
Name: Jasmine Tsai
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for ea... | """
File: anagram.py
Name: Jasmine Tsai
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for ea... |
"""This modules provides strng formatting functions
prepare_data_for_db insert:
formatting data to be inserted in database table
concat_list:
concatenate list elements in a string w/wo separator
to_str:
transform value to str
is_str:
test if value is str
concat_key_value:
concatenate key values of ... | """This modules provides strng formatting functions
prepare_data_for_db insert:
formatting data to be inserted in database table
concat_list:
concatenate list elements in a string w/wo separator
to_str:
transform value to str
is_str:
test if value is str
concat_key_value:
concatenate key values of ... |
class Solution:
def isPalindrome(self, x: int) -> bool:
if(x<0):
return False
elif(x==0):
return True
else:
reverse = 0
divi = x
while(divi!=0):
rem = divi%10
reverse = reverse*10 + rem
... | class Solution:
def is_palindrome(self, x: int) -> bool:
if x < 0:
return False
elif x == 0:
return True
else:
reverse = 0
divi = x
while divi != 0:
rem = divi % 10
reverse = reverse * 10 + rem
... |
"""
Java dependencies
"""
load("@rules_jvm_external//:defs.bzl", "maven_install")
def maven_fetch_remote_artifacts():
"""
Fetch maven artifacts
"""
maven_install(
artifacts = [
"com.fasterxml.jackson.core:jackson-core:2.11.2",
"com.fasterxml.jackson.core:jackson-databin... | """
Java dependencies
"""
load('@rules_jvm_external//:defs.bzl', 'maven_install')
def maven_fetch_remote_artifacts():
"""
Fetch maven artifacts
"""
maven_install(artifacts=['com.fasterxml.jackson.core:jackson-core:2.11.2', 'com.fasterxml.jackson.core:jackson-databind:2.11.2', 'org.apache.pdfbox:pdfbox:... |
# -*- coding: utf-8 -*-
"""Main module."""
def hello_world():
"""Say hello to world.
:returns: Nothing
:rtype: NoneType
"""
print("Hello world")
| """Main module."""
def hello_world():
"""Say hello to world.
:returns: Nothing
:rtype: NoneType
"""
print('Hello world') |
#
# @lc app=leetcode.cn id=461 lang=python3
#
# [461] hamming-distance
#
None
# @lc code=end | None |
# Can you do it with a conditional statement (if / if-else) instead?
x1 = float(input("number? "))
x2 = float(input("number? "))
#if x1 > x2:
# mx = x1
#elif x2 > x1:
# mx = x2
#else:
# mx = x1
print("Maximum:", x1 if x1 > x2 else x2)
| x1 = float(input('number? '))
x2 = float(input('number? '))
print('Maximum:', x1 if x1 > x2 else x2) |
#!/usr/bin/env python3
'''
TITLE:
[2018-09-04] Challenge #367 [Easy] Subfactorials - Another Twist on Factorials
LINK:
https://www.reddit.com/r/dailyprogrammer/comments/9cvo0f/20180904_challenge_367_easy_subfactorials_another/
DERIVATION:
Start with n numbers 1...n, and n slots #1...#n. Take the number 1 and place i... | """
TITLE:
[2018-09-04] Challenge #367 [Easy] Subfactorials - Another Twist on Factorials
LINK:
https://www.reddit.com/r/dailyprogrammer/comments/9cvo0f/20180904_challenge_367_easy_subfactorials_another/
DERIVATION:
Start with n numbers 1...n, and n slots #1...#n. Take the number 1 and place it
in some slot #x, there... |
def run():
my_list = ["Hello", 1, True, 4.5]
my_dict = { "firstname": "Sebastian", "lastname": "Granda" }
super_list = [
{ "firstname": "Valentina", "lastname": "Mora" },
{ "firstname": "Sebastian", "lastname": "Granda" },
{ "firstname": "Isaac", "lastname": "Hincapie" },
{ "firstname": "Camilo",... | def run():
my_list = ['Hello', 1, True, 4.5]
my_dict = {'firstname': 'Sebastian', 'lastname': 'Granda'}
super_list = [{'firstname': 'Valentina', 'lastname': 'Mora'}, {'firstname': 'Sebastian', 'lastname': 'Granda'}, {'firstname': 'Isaac', 'lastname': 'Hincapie'}, {'firstname': 'Camilo', 'lastname': 'Romero'... |
# -*- coding: utf-8 -*-
{
"name": "WeCom HRM",
"author": "RStudio",
"sequence": 607,
"installable": True,
"application": True,
"auto_install": False,
"category": "WeCom/WeCom",
"website": "https://gitee.com/rainbowstudio/wecom",
"version": "15.0.0.1",
"summary": """
... | {'name': 'WeCom HRM', 'author': 'RStudio', 'sequence': 607, 'installable': True, 'application': True, 'auto_install': False, 'category': 'WeCom/WeCom', 'website': 'https://gitee.com/rainbowstudio/wecom', 'version': '15.0.0.1', 'summary': '\n \n ', 'description': '\n\n ', 'depends': [], 'data': ['da... |
#Reference for basic numerical operations and comparisons
x = 9
y = 3
#Arithmetic Operators
print(x+y) #Addition
print(x-y) #Subtraction
print(x*y) #Multiplication
print(x/y) #Division
print(x%y) #Modulus -- remainder after division
print(x**y) #Exponentiation
x = 9.191823
print(x//y) #Floor Divi... | x = 9
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
print(x ** y)
x = 9.191823
print(x // y)
x = 9
x += 3
print(x)
x = 9
x -= 3
print(x)
x *= 3
print(x)
x /= 3
print(x)
x **= 3
print(x)
x = 9
y = 3
print(x == y)
print(x != y)
print(x > y)
print(x < y)
print(x >= y)
print(x <= y) |
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
def formatRange(dates):
#We first extract the calendar day of the range
startingDay = days[dates[0].weekday()]... | days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
def format_range(dates):
starting_day = days[dates[0].weekday()]
ending_day = days[dates[1].w... |
class LoginError(Exception):
""" Could not login to the server. """
pass
class NotLoggedInError(Exception):
""" Cannot properly interact with Fur Affinity unless you are logged in. """
pass
class MaturityError(Exception):
""" Cannot access that submission on this account because of maturity filt... | class Loginerror(Exception):
""" Could not login to the server. """
pass
class Notloggedinerror(Exception):
""" Cannot properly interact with Fur Affinity unless you are logged in. """
pass
class Maturityerror(Exception):
""" Cannot access that submission on this account because of maturity filter... |
class EmptyObject:
pass
EMPTY = EmptyObject() # sentinel object to represent empty node output
def is_empty(obj):
return isinstance(obj, EmptyObject)
| class Emptyobject:
pass
empty = empty_object()
def is_empty(obj):
return isinstance(obj, EmptyObject) |
"""
Structural pattern :
Proxy
Examples :
1. use in orm
"""
class Db:
def work(self):
print('you are admin so you can work with database...')
class Proxy:
admin_password = 'secret'
def check_admin(self, password):
if password == self.admin_password:
d1... | """
Structural pattern :
Proxy
Examples :
1. use in orm
"""
class Db:
def work(self):
print('you are admin so you can work with database...')
class Proxy:
admin_password = 'secret'
def check_admin(self, password):
if password == self.admin_password:
d1 ... |
'''
Input
The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).
Output
Print... | """
Input
The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).
Output
Print... |
# TODO: we will have to figure out a better way of generating this file
build_time_vars = {
"CC": "gcc -pthread",
"CXX": "g++ -pthread",
"OPT": "-DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes",
"CFLAGS": "-fno-strict-aliasing -g -O3 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes",... | build_time_vars = {'CC': 'gcc -pthread', 'CXX': 'g++ -pthread', 'OPT': '-DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes', 'CFLAGS': '-fno-strict-aliasing -g -O3 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes', 'CCSHARED': '-fPIC', 'LDSHARED': 'gcc -pthread -shared', 'SO': '.pyston.so', 'AR': 'ar', 'ARFLAGS': 'rc'} |
class Pizza:
def __init__(self, name, dough, toppings_capacity):
self.__name = name
self.__dough = dough
self.__toppings_capacity = toppings_capacity
self.__toppings = {}
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
... | class Pizza:
def __init__(self, name, dough, toppings_capacity):
self.__name = name
self.__dough = dough
self.__toppings_capacity = toppings_capacity
self.__toppings = {}
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
... |
class ParsedGame:
def __init__(self, parsed_data):
if len(parsed_data) == 5:
self.time_left = parsed_data[0]
self.away_team = parsed_data[1]
self.away_score = parsed_data[2]
self.home_team = parsed_data[3]
self.home_score = parsed_data[4]
e... | class Parsedgame:
def __init__(self, parsed_data):
if len(parsed_data) == 5:
self.time_left = parsed_data[0]
self.away_team = parsed_data[1]
self.away_score = parsed_data[2]
self.home_team = parsed_data[3]
self.home_score = parsed_data[4]
... |
# id mapping
# ssdb : redis
# kv
# key= ${table_name}`${item_id}
# val= ${type}`${content}
# 1. type=raw
# 2. type=b64
# 3. type=url
# k hash
# key = table_name
# field = item_id
# value = val
# import redis
# https://blog.csdn.net/u012851870/article/details/44754509
# http://ssdb.io/docs/zh_cn/redis-to-ssdb.ht... | __all__ = ['hset', 'hmget', 'del_table']
def hset(client, table, item_id, val):
client.hset(table, item_id, val)
def hget(client, table, item_id):
v = client.hget(table, item_id)
s = ''
if v:
s = v.decode('utf-8')
return s
def hmget(client, table, item_id_arr):
"""
:return map{k,v... |
class FlowException(Exception):
"""Internal exceptions for flow control etc.
Validation, config errors and such should use standard Python exception types"""
pass
class StopProcessing(FlowException):
"""Stop processing of single item without too much error logging"""
pass
| class Flowexception(Exception):
"""Internal exceptions for flow control etc.
Validation, config errors and such should use standard Python exception types"""
pass
class Stopprocessing(FlowException):
"""Stop processing of single item without too much error logging"""
pass |
#!/usr/bin/env python3
""" An attempt to solve Roaming Romans on Kattis """
MODERN_MILE_FEET = 5280.0
ROMAN_MILE_IN_FEET = 4854.0
miles = float(input().rstrip())
roman_paces = (1000 * (MODERN_MILE_FEET/ROMAN_MILE_IN_FEET)) * miles
print(round(roman_paces))
| """ An attempt to solve Roaming Romans on Kattis """
modern_mile_feet = 5280.0
roman_mile_in_feet = 4854.0
miles = float(input().rstrip())
roman_paces = 1000 * (MODERN_MILE_FEET / ROMAN_MILE_IN_FEET) * miles
print(round(roman_paces)) |
def adapt_to_ex(model):
self.conv_sections = conv_sections
self.glob_av_pool = torch.nn.AdaptiveAvgPool2d(output_size=1)
self.linear_sections = linear_sections
self.head = head
self.input_shape = input_shape
self.n_classes = head.out_elements
self.data_augment = DataAugmentation(n_class... | def adapt_to_ex(model):
self.conv_sections = conv_sections
self.glob_av_pool = torch.nn.AdaptiveAvgPool2d(output_size=1)
self.linear_sections = linear_sections
self.head = head
self.input_shape = input_shape
self.n_classes = head.out_elements
self.data_augment = data_augmentation(n_classes=s... |
class TaskAlreadyExistsError(Exception):
pass
class NoSuchTaskError(Exception):
pass | class Taskalreadyexistserror(Exception):
pass
class Nosuchtaskerror(Exception):
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.