content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
"""
@param matrix: the given matrix
@return: True if and only if the matrix is Toeplitz
"""
def isToeplitzMatrix(self, matrix):
# Write your code here
col=len(matrix[0])
row=len(matrix)
for i in range(1, row):
for j in range(1, col):
... | class Solution:
"""
@param matrix: the given matrix
@return: True if and only if the matrix is Toeplitz
"""
def is_toeplitz_matrix(self, matrix):
col = len(matrix[0])
row = len(matrix)
for i in range(1, row):
for j in range(1, col):
if matrix[i][j... |
_base_ = './retinanet_r50_fpn_1x_cityscapes.py'
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(type='Pretrained',
checkpoint='checkpoints/resnet101-63fe2227.pth')))
# load_from="checkpoints/retinanet_r101_fpn_mstrain_3x_coco_20210720_214650-7ee888e0.pth" | _base_ = './retinanet_r50_fpn_1x_cityscapes.py'
model = dict(backbone=dict(depth=101, init_cfg=dict(type='Pretrained', checkpoint='checkpoints/resnet101-63fe2227.pth'))) |
# Title : Multiply all odd number
# Author : Kiran Raj R.
# Date : 06:11:2020
def multiply_odd(num):
""" Return sum of multiple of all odd number
below user specified range """
result = 1
for i in range(1,num, 2):
result*=i
return result
print(multiply_odd(10))
def multiply_even(num):... | def multiply_odd(num):
""" Return sum of multiple of all odd number
below user specified range """
result = 1
for i in range(1, num, 2):
result *= i
return result
print(multiply_odd(10))
def multiply_even(num):
""" Return sum of multiple of all even number
below user specified range... |
class Player:
def __init__(self, name, life_value, attack_value):
self.name = name
self.life_value = life_value
self.attack_value = attack_value
def attack(self, enemy_player: 'Player'):
enemy_player.life_value = enemy_player.life_value - self.attack_value
def is_alive(self... | class Player:
def __init__(self, name, life_value, attack_value):
self.name = name
self.life_value = life_value
self.attack_value = attack_value
def attack(self, enemy_player: 'Player'):
enemy_player.life_value = enemy_player.life_value - self.attack_value
def is_alive(sel... |
# Define physical constants
P0 = 1000. # Ground pressure level. Unit: hPa
SCALE_HEIGHT = 7000. # Unit: m
CP = 1004. # specific heat at constant pressure for air (cp) = 1004 J/kg-K
DRY_GAS_CONSTANT = 287.
EARTH_RADIUS = 6.378e+6 # Unit: m
EARTH_OMEGA = 7.29e-5
| p0 = 1000.0
scale_height = 7000.0
cp = 1004.0
dry_gas_constant = 287.0
earth_radius = 6378000.0
earth_omega = 7.29e-05 |
with open('./input.txt') as input:
lines = [int(s.strip()) for s in input.readlines()]
last = 999999999999
counter = 0
for (a, b, c) in zip(lines[0:-2], lines[1:-1], lines[2:]):
current = a + b + c
if (current > last):
counter += 1
last = current
print(counter) # ... | with open('./input.txt') as input:
lines = [int(s.strip()) for s in input.readlines()]
last = 999999999999
counter = 0
for (a, b, c) in zip(lines[0:-2], lines[1:-1], lines[2:]):
current = a + b + c
if current > last:
counter += 1
last = current
print(counter) |
fileName = input("What's the name of the file? ../logs/")
results = list(map(lambda e: e.split(" "), open(
'../logs/' + fileName, 'r').readlines()))
"""
Interesting statistics:
- Average score of all runs
- Worst score
- Best score
- Average of worst 20% of scores
- Average of best 20% of scor... | file_name = input("What's the name of the file? ../logs/")
results = list(map(lambda e: e.split(' '), open('../logs/' + fileName, 'r').readlines()))
'\nInteresting statistics:\n - Average score of all runs\n - Worst score\n - Best score\n - Average of worst 20% of scores\n - Average of best 20% of scores... |
# This program saves a list of numbers to a file.
def main():
# Create a list of numbers.
numbers = [1, 2, 3, 4, 5, 6, 7]
# Open a file for writing.
outfile = open('numberlist.txt', 'w')
# Write the list to the file.
for item in numbers:
outfile.write(str(item) + '\n')
... | def main():
numbers = [1, 2, 3, 4, 5, 6, 7]
outfile = open('numberlist.txt', 'w')
for item in numbers:
outfile.write(str(item) + '\n')
outfile.close()
main() |
x = int(input('Enter your Age: '))
print('****************')
for i in range(0, 1):
if x >= 18:
print('You can watch content with R-rating')
elif x >= 13:
print('You can watch movies under parental guidance ')
else:
print('Cartoons permitted')
print(' Thanks! ')
| x = int(input('Enter your Age: '))
print('****************')
for i in range(0, 1):
if x >= 18:
print('You can watch content with R-rating')
elif x >= 13:
print('You can watch movies under parental guidance ')
else:
print('Cartoons permitted')
print(' Thanks! ') |
def internal_consistency_check(Reports_dict, reportnos=None):
return_dict = {}
if reportnos:
search_list = reportnos
else:
search_list = list(Reports_dict.keys())
for reportno in search_list:
rdf = pd.DataFrame()
rdf = Reports_dict[reportno].copy()
print('REPORT',... | def internal_consistency_check(Reports_dict, reportnos=None):
return_dict = {}
if reportnos:
search_list = reportnos
else:
search_list = list(Reports_dict.keys())
for reportno in search_list:
rdf = pd.DataFrame()
rdf = Reports_dict[reportno].copy()
print('REPORT',... |
N = int(input())
X = 1
K = 0
while X <= N:
X *= 2
K += 1
print(max(0, K - 1)) | n = int(input())
x = 1
k = 0
while X <= N:
x *= 2
k += 1
print(max(0, K - 1)) |
data_in = [3.0,
1.0,
0.0,
0.0,
1.0,
6.0,
1.0,
0.0,
1.0,
0.0,
3280.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
... | data_in = [3.0, 1.0, 0.0, 0.0, 1.0, 6.0, 1.0, 0.0, 1.0, 0.0, 3280.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0... |
# Parsers
# Parse initial fields name to normalized form.
parse_name = lambda name: str(name).replace(' ', '_').lower()
| parse_name = lambda name: str(name).replace(' ', '_').lower() |
"""
# IMPLEMENT POW(X, N)
Implement pow(x, n), which calculates x raised to the power n (i.e. xn).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints... | """
# IMPLEMENT POW(X, N)
Implement pow(x, n), which calculates x raised to the power n (i.e. xn).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints... |
# Oct 2021
# Class for extraction.py
class FoundExpression:
def __init__(self, expression: str,
file: str,
language: str,
line_no: int):
self.expression = expression
self.language = language
self.file = file
self.line_no = line_no | class Foundexpression:
def __init__(self, expression: str, file: str, language: str, line_no: int):
self.expression = expression
self.language = language
self.file = file
self.line_no = line_no |
"""
@author: magician
@date: 2019/12/24
@file: rotate_array.py
"""
def rotate(nums, k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# nums = nums[k + 1:] + nums[:k + 1]
for i in range(k):
nums.insert(0, nums[-1])
nums.pop()
return nu... | """
@author: magician
@date: 2019/12/24
@file: rotate_array.py
"""
def rotate(nums, k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(k):
nums.insert(0, nums[-1])
nums.pop()
return nums
if __name__ == '__main__':
assert rot... |
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
ans = n
nums = sorted(set(nums))
for i, start in enumerate(nums):
end = start + n - 1
index = bisect_right(nums, end)
uniqueLength = index - i
ans = min(ans, n - uniqueLength)
return ans
| class Solution:
def min_operations(self, nums: List[int]) -> int:
n = len(nums)
ans = n
nums = sorted(set(nums))
for (i, start) in enumerate(nums):
end = start + n - 1
index = bisect_right(nums, end)
unique_length = index - i
ans = min... |
"""
git-flow -- A collection of Git extensions to provide high-level
repository operations for Vincent Driessen's branching model.
"""
#
# This file is part of `gitflow`.
# Copyright (c) 2010-2011 Vincent Driessen
# Copyright (c) 2012 Hartmut Goebel
# Distributed under a BSD-like license. For full terms see the file LI... | """
git-flow -- A collection of Git extensions to provide high-level
repository operations for Vincent Driessen's branching model.
"""
version = (0, 6, 3)
__version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:])
__author__ = 'Vincent Driessen, Hartmut Goebel'
__contact__ = 'vincent@datafox.nl, h.goebel@goe... |
data = (
'jun', # 0x00
'junj', # 0x01
'junh', # 0x02
'jud', # 0x03
'jul', # 0x04
'julg', # 0x05
'julm', # 0x06
'julb', # 0x07
'juls', # 0x08
'jult', # 0x09
'julp', # 0x0a
'julh', # 0x0b
'jum', # 0x0c
'jub', # 0x0d
'jubs', # 0x0e
'jus', # 0x0f
'juss', #... | data = ('jun', 'junj', 'junh', 'jud', 'jul', 'julg', 'julm', 'julb', 'juls', 'jult', 'julp', 'julh', 'jum', 'jub', 'jubs', 'jus', 'juss', 'jung', 'juj', 'juc', 'juk', 'jut', 'jup', 'juh', 'jweo', 'jweog', 'jweogg', 'jweogs', 'jweon', 'jweonj', 'jweonh', 'jweod', 'jweol', 'jweolg', 'jweolm', 'jweolb', 'jweols', 'jweolt'... |
def calculate_area(side_length=10):
print(f"The area of a square with sides of length {side_length} is {side_length**2}.")
length=int(input("Enter side length: "))
if length<=0:
calculate_area(10)
else:
calculate_area(length) | def calculate_area(side_length=10):
print(f'The area of a square with sides of length {side_length} is {side_length ** 2}.')
length = int(input('Enter side length: '))
if length <= 0:
calculate_area(10)
else:
calculate_area(length) |
def find_max(num1, num2):
max_num=-1
if num2> num1:
data = range(num1,num2+1)
main_list = []
for x in data:
b = str(x)
if x < 0:
b = str(x*-1)
sx = list(map(int,list(b)))
if len(sx)==2 and sum(sx)%3==0 and x%5==0:
... | def find_max(num1, num2):
max_num = -1
if num2 > num1:
data = range(num1, num2 + 1)
main_list = []
for x in data:
b = str(x)
if x < 0:
b = str(x * -1)
sx = list(map(int, list(b)))
if len(sx) == 2 and sum(sx) % 3 == 0 and (x ... |
def calc():
numOne = int(input("What is the first number of your problem?"))
numTwo = int(input("What is the second number of your problem?"))
numThree = input("What type of Math Problem is it, Addition, Subtraction, Multiplication, Division, Remainder, or Exponents? Type exactly.")
if numThree == 'Addition':
... | def calc():
num_one = int(input('What is the first number of your problem?'))
num_two = int(input('What is the second number of your problem?'))
num_three = input('What type of Math Problem is it, Addition, Subtraction, Multiplication, Division, Remainder, or Exponents? Type exactly.')
if numThree == 'A... |
class Solution:
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
primes, indices = [2, 3, 5], [0, 0, 0]
ugly_numbers = [1]
for _ in range(n):
next_numbers = list(map(lambda x: x[0] * x[1], zip(primes, map(lambda x: ugly_numbers[x], indi... | class Solution:
def nth_ugly_number(self, n):
"""
:type n: int
:rtype: int
"""
(primes, indices) = ([2, 3, 5], [0, 0, 0])
ugly_numbers = [1]
for _ in range(n):
next_numbers = list(map(lambda x: x[0] * x[1], zip(primes, map(lambda x: ugly_numbers[x... |
"""Codewars problem to find even index."""
def find_even_index(arr):
"""Return the index where sum of both sides are equal."""
if len(arr) == 0:
return 0
for i in range(0, len(arr)):
sum1 = 0
sum2 = 0
for j in range(0, i):
sum1 += arr[j]
for k in range... | """Codewars problem to find even index."""
def find_even_index(arr):
"""Return the index where sum of both sides are equal."""
if len(arr) == 0:
return 0
for i in range(0, len(arr)):
sum1 = 0
sum2 = 0
for j in range(0, i):
sum1 += arr[j]
for k in range(i ... |
def read_pwscf_in(filepath):
"""
Note: read parameters from pwscf input template
"""
with open(filepath, 'r') as fin:
lines = fin.readlines()
control = {}
system = {}
electrons = {}
ions = {}
cell = {}
for i in range(len(lines)):
if li... | def read_pwscf_in(filepath):
"""
Note: read parameters from pwscf input template
"""
with open(filepath, 'r') as fin:
lines = fin.readlines()
control = {}
system = {}
electrons = {}
ions = {}
cell = {}
for i in range(len(lines)):
if lines[i].split()[0].lower() == ... |
x_min = -2
y_min = (-(modelparams['weights'][0] * x_min) / modelparams['weights'][1] -
(modelparams['bias'][0] / model_params['weights'][1]))
x_max = 2
y_max = (-(modelparams['weights'][0] * x_max) / modelparams['weights'][1] -
(modelparams['bias'][0] / modelparams['weights'][1]))
fig, ax = plt.sub... | x_min = -2
y_min = -(modelparams['weights'][0] * x_min) / modelparams['weights'][1] - modelparams['bias'][0] / model_params['weights'][1]
x_max = 2
y_max = -(modelparams['weights'][0] * x_max) / modelparams['weights'][1] - modelparams['bias'][0] / modelparams['weights'][1]
(fig, ax) = plt.subplots(1, 2, sharex=True, fi... |
for i in range(0, 201, 2):
print(i)
for i in range(0, 100, 3):
print(i)
| for i in range(0, 201, 2):
print(i)
for i in range(0, 100, 3):
print(i) |
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
r"""A defined list of constants available to QuickRelease users.
The are some important difference between QuickRelease's L{config items<quickrelease.config>} and C{constants}:
1. C{constants} may be accessed without a L{Confi... | """A defined list of constants available to QuickRelease users.
The are some important difference between QuickRelease's L{config items<quickrelease.config>} and C{constants}:
1. C{constants} may be accessed without a L{ConfigSpec<quickrelease.config.ConfigSpec>} reference. This makes them useful in places where it... |
def reverse_number(n: int) -> int:
""" This function takes in input 'n' and returns 'n' with all digits reversed. """
if len(str(n)) == 1:
return n
k = abs(n)
reversed_n = []
while k != 0:
i = k % 10
reversed_n.append(i)
k = (k - i) // 10
return int(''.join(map(st... | def reverse_number(n: int) -> int:
""" This function takes in input 'n' and returns 'n' with all digits reversed. """
if len(str(n)) == 1:
return n
k = abs(n)
reversed_n = []
while k != 0:
i = k % 10
reversed_n.append(i)
k = (k - i) // 10
return int(''.join(map(st... |
# This is all about using strings
stg_1 = "this is the first message without a tab"
print(stg_1)
stg_2 = "\t this is the second message with a tab"
print(stg_2)
stg_3 = "this is another message with a newline\n"
print(stg_3)
| stg_1 = 'this is the first message without a tab'
print(stg_1)
stg_2 = '\t this is the second message with a tab'
print(stg_2)
stg_3 = 'this is another message with a newline\n'
print(stg_3) |
#!/usr/bin/python
# unicode.py
text = u'\u041b\u0435\u0432 \u041d\u0438\u043a\u043e\u043b\u0430\
\u0435\u0432\u0438\u0447 \u0422\u043e\u043b\u0441\u0442\u043e\u0439: \n\
\u0410\u043d\u043d\u0430 \u041a\u0430\u0440\u0435\u043d\u0438\u043d\u0430'
print (text)
| text = u'Лев Николаевич Толстой: \nАнна Каренина'
print(text) |
#to have some interaction
#we need an loop to look for actions
def setup():
size(400, 400)
#executed once
println("This is the setup. Executed once. Initiate things here")
#executed all the time waiting for infos
def draw():
#do the bakcground color transformation
noStroke()
fill(map(mouseX, w... | def setup():
size(400, 400)
println('This is the setup. Executed once. Initiate things here')
def draw():
no_stroke()
fill(map(mouseX, width, 0, 0, width), 100)
rect(0, 0, width, height)
fill(mouseX)
ellipse(mouseX, mouseY, 10, 10)
println('Frame number: ' + frameCount)
print('mouse... |
##########################################################################
# NSAp - Copyright (C) CEA, 2013
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########... | options = (('documentation_folder', {'type': 'string', 'default': None, 'help': 'the folder containing the documentation of the project.', 'group': 'piws', 'level': 1}), ('show_user_status', {'type': 'yn', 'default': True, 'help': 'Show or not the user status link on the website.', 'group': 'piws', 'level': 1}), ('ldap... |
class Command:
def __init__(self, name, desc="", args=[]):
self.name = name
self.desc = desc
self.args = args
| class Command:
def __init__(self, name, desc='', args=[]):
self.name = name
self.desc = desc
self.args = args |
"""
Return nth catalan number.
Recursive Formula of Catalan Numbers says:
C of (n+1) = summation of C of i* C of n-i, for range i=0 to i=n
Therefore, for C of n formula becomes
C of (n) = summation of C of i* C of n-1-i, for range i=0 to i=n-1
"""
def getCatalan(n,dp_arr):
# Lookup
if (dp_arr[n] is not Non... | """
Return nth catalan number.
Recursive Formula of Catalan Numbers says:
C of (n+1) = summation of C of i* C of n-i, for range i=0 to i=n
Therefore, for C of n formula becomes
C of (n) = summation of C of i* C of n-1-i, for range i=0 to i=n-1
"""
def get_catalan(n, dp_arr):
if dp_arr[n] is not None:
re... |
class SSLUnavailable(Exception):
"""If you haven't verified a CNAME zone within the grace period (a week),
it can't be verified any more.
"""
pass
class CustomHostnameNotFound(Exception):
pass
| class Sslunavailable(Exception):
"""If you haven't verified a CNAME zone within the grace period (a week),
it can't be verified any more.
"""
pass
class Customhostnamenotfound(Exception):
pass |
n1,n2=map(int,input().split())
a=[]
for i in range(n2):
a.append(list(map(float,input().split())))
for i in zip(*a):
print(sum(i)/n2) | (n1, n2) = map(int, input().split())
a = []
for i in range(n2):
a.append(list(map(float, input().split())))
for i in zip(*a):
print(sum(i) / n2) |
def read_txt_file_str(filename):
f=open('text_files/'+filename, "r")
contents=f.read()
f.close()
return contents
def read_txt_file_list(filename):
f=open('text_files/'+filename, "r")
contents=f.readlines()
f.close()
return contents | def read_txt_file_str(filename):
f = open('text_files/' + filename, 'r')
contents = f.read()
f.close()
return contents
def read_txt_file_list(filename):
f = open('text_files/' + filename, 'r')
contents = f.readlines()
f.close()
return contents |
# Author: Jocelino F.G.
n = int(input())
vetor = [n]
dobro = n
for i in range(0, 10):
dobro = dobro * 2
vetor.append(dobro)
print("N[{}] = {}".format(i, vetor[i]))
| n = int(input())
vetor = [n]
dobro = n
for i in range(0, 10):
dobro = dobro * 2
vetor.append(dobro)
print('N[{}] = {}'.format(i, vetor[i])) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# rule_engine/errors.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... | class _Undefined(object):
def __bool__(self):
return False
__name__ = 'UNDEFINED'
__nonzero__ = __bool__
def __repr__(self):
return self.__name__
undefined = _undefined()
'\nA sentinel value to specify that something is undefined. When evaluated, the\nvalue is falsy.\n\n.. versionadded... |
def is_even(number):
return number % 2 == 0
| def is_even(number):
return number % 2 == 0 |
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if len(nums)*len(nums[0]) != r*c:
return nums
kek = []
nums = [item for sublist in nu... | class Solution(object):
def matrix_reshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if len(nums) * len(nums[0]) != r * c:
return nums
kek = []
nums = [item for sublist... |
class InvalidOperationError(BaseException):
pass
class Node():
def __init__(self, value, next=None):
self.value = value
self.next = next
class Stack():
def __init__(self, node=None):
self.top = node
def __len__(self):
count = 0
curr = self.top
while ... | class Invalidoperationerror(BaseException):
pass
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self, node=None):
self.top = node
def __len__(self):
count = 0
curr = self.top
while curr:... |
"""
The file provides default secret parameters used as a reference for creating your
own secret.py or in testing.
Make sure to create your own secret.py (in the same folder) with appropriate values for when deploying
the website!
"""
SECRET_KEY = "2r4-$a^!rs=^glu=a8m=e5a$5*wg2uxjjob!diff-z*wzdx+4y"
"""
Set these if ... | """
The file provides default secret parameters used as a reference for creating your
own secret.py or in testing.
Make sure to create your own secret.py (in the same folder) with appropriate values for when deploying
the website!
"""
secret_key = '2r4-$a^!rs=^glu=a8m=e5a$5*wg2uxjjob!diff-z*wzdx+4y'
'\nSet these if my... |
# Given
x = 10000.0
y = 3.0
print(x / y)
print(10000 / 3)
# What is happening?
# Given
print(x - 1 / y)
print((x - 1) / y)
# What is happening?
# Given
x = 'foo'
y = 'bar'
# Create 'foobar' using x and y
s = x + y
print(s)
# Create 'foo -> bar' using x and y
print(x + " -> " + y)
# Given
x = 'hello world'
# from x ... | x = 10000.0
y = 3.0
print(x / y)
print(10000 / 3)
print(x - 1 / y)
print((x - 1) / y)
x = 'foo'
y = 'bar'
s = x + y
print(s)
print(x + ' -> ' + y)
x = 'hello world'
print(x.upper())
print(x.replace('o', 'X'))
x = 10000.0
y = 3.0
print('{x} / {y} = {z}'.format(x=x, y=y, z=x / y))
s = ['hello', 'world']
print(s[0] + s[1]... |
class Config:
def __init__(self):
self.data_dir = './data/'
self.data_path = self.data_dir + 'peot.txt'
self.pickle_path = self.data_dir + 'tang.npz'
self.load_path = './checkpoints/peot9.pt'
self.save_path = './checkpoints/peot9.pt'
self.do_train = False
sel... | class Config:
def __init__(self):
self.data_dir = './data/'
self.data_path = self.data_dir + 'peot.txt'
self.pickle_path = self.data_dir + 'tang.npz'
self.load_path = './checkpoints/peot9.pt'
self.save_path = './checkpoints/peot9.pt'
self.do_train = False
sel... |
# Copyright 2011 Google Inc. 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 a... | """Base class for Indexer objects.
The choice to add the bug to the function rather than to the object was that
the indexer may be run on many bugs/items/etc so I didn't want the object to
become dependent on the bug it was manipulating.
"""
__author__ = 'jason.stredwick@gmail.com (Jason Stredwick)'
class Error(Excep... |
'''
@Author: Ofey Chan
@Date: 2020-03-03 19:23:15
@LastEditors: Ofey Chan
@LastEditTime: 2020-03-03 20:07:31
@Description: General permutation group class.
@Reference:
'''
| """
@Author: Ofey Chan
@Date: 2020-03-03 19:23:15
@LastEditors: Ofey Chan
@LastEditTime: 2020-03-03 20:07:31
@Description: General permutation group class.
@Reference:
""" |
# Forcing recursion for no good reason. But it passed so....
def solution_r(n):
if n <= 0:
return n
else:
if not n%3 or not n%5:
return n + solution_r(n-1)
else:
return solution_r(n-1)
def solution(number):
if not number:
return 0
return solutio... | def solution_r(n):
if n <= 0:
return n
elif not n % 3 or not n % 5:
return n + solution_r(n - 1)
else:
return solution_r(n - 1)
def solution(number):
if not number:
return 0
return solution_r(number - 1)
assert solution(10) == 23, 'Oops, recursion is the devil' |
class Solution:
def minJumps(self, arr: List[int]) -> int:
graph = defaultdict(list)
for i in range(len(arr)):
graph[arr[i]].append(i)
visited = set()
src, dest = 0, len(arr) - 1
queue = deque()
queue.append((src, 0))
visited.add(src)
whil... | class Solution:
def min_jumps(self, arr: List[int]) -> int:
graph = defaultdict(list)
for i in range(len(arr)):
graph[arr[i]].append(i)
visited = set()
(src, dest) = (0, len(arr) - 1)
queue = deque()
queue.append((src, 0))
visited.add(src)
... |
def transitions(y,x):
yield y+1,x
yield y,x+1
yield y-1,x
yield y,x-1
def valid_transitions(arr):
# print(arr)
Y = len(arr)
X = len(arr[0])
def _f(y0,x0):
for y,x in transitions(y0,x0):
if 0 <= y < Y and 0 <= x < X and arr[y][x] != "-":
yield y,x
... | def transitions(y, x):
yield (y + 1, x)
yield (y, x + 1)
yield (y - 1, x)
yield (y, x - 1)
def valid_transitions(arr):
y = len(arr)
x = len(arr[0])
def _f(y0, x0):
for (y, x) in transitions(y0, x0):
if 0 <= y < Y and 0 <= x < X and (arr[y][x] != '-'):
yi... |
#
# Copyright (c) 2020 Xilinx, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
#
# Mandatory Common Configuration required
sharedWs = "{buildDir}/shared_ws"
XSCT_BUILD_SOURCE = "" # build source type whether to be used XSCT default or git source (i.e. XSCT_BUILD_SOURCE="git")
version = "2020.2" # Vitis vers... | shared_ws = '{buildDir}/shared_ws'
xsct_build_source = ''
version = '2020.2'
vitis_path = ''
outoftreebuild = True
parallel_make = 20
deploy_artifacts = '{buildDir}/{machine}/deploy/'
rootfs_path = '{ROOT}/build/{machine}/deploy/rootfs.cpio.gz.u-boot'
boot_scr_path = ''
deploy_dir = '{ROOT}/build/{machine}/deploy'
'\nT... |
def insertShiftArray(arr, value):
mid = len(arr) // 2
new_arr = []
for i in range(0, mid):
new_arr.append(arr[i])
new_arr.append(value)
for i in range(mid, len(arr)):
new_arr.append(arr[i])
return new_arr
test = [1, 2, 3, 4, 5]
print(test)
print(insertSh... | def insert_shift_array(arr, value):
mid = len(arr) // 2
new_arr = []
for i in range(0, mid):
new_arr.append(arr[i])
new_arr.append(value)
for i in range(mid, len(arr)):
new_arr.append(arr[i])
return new_arr
test = [1, 2, 3, 4, 5]
print(test)
print(insert_shift_array(test, 8))
tes... |
"""
callfunc.py
The Frog Programming Language Operation & Keyword: call (func)
Development Leader: @RedoC
"""
class CALLFUNC:
"""
CALLFUNC is the multi class
>> example
run foo(boo)
run print("")
"""
def __init__(self, funcname: str, param: list):
self.funcname = funcname
... | """
callfunc.py
The Frog Programming Language Operation & Keyword: call (func)
Development Leader: @RedoC
"""
class Callfunc:
"""
CALLFUNC is the multi class
>> example
run foo(boo)
run print("")
"""
def __init__(self, funcname: str, param: list):
self.funcname = funcname
... |
class Hamming:
def distance(self, first, second):
num_of_errors = 0
if type(first) != str or type(second) != str:
return "Wrong type of strands"
if len(first) != len(second):
return "Strands should be the same length"
for i in range(len(first)):
if... | class Hamming:
def distance(self, first, second):
num_of_errors = 0
if type(first) != str or type(second) != str:
return 'Wrong type of strands'
if len(first) != len(second):
return 'Strands should be the same length'
for i in range(len(first)):
i... |
conditons = True
alcool = 0
gas = 0
disel = 0
while conditons :
T = int(input())
if T == 4:
conditons = False;
else:
if T == 1:
alcool +=1
if T == 2:
gas +=1
if T == 3:
disel +=1
print("MUITO OBRIGADO")
print(f"Alcool: {alcool}")
print(... | conditons = True
alcool = 0
gas = 0
disel = 0
while conditons:
t = int(input())
if T == 4:
conditons = False
else:
if T == 1:
alcool += 1
if T == 2:
gas += 1
if T == 3:
disel += 1
print('MUITO OBRIGADO')
print(f'Alcool: {alcool}')
print(f'G... |
def estimator(data):
output = {'data':data, 'impact': {}, 'severeImpact': {}}
output['impact']['currentlyInfected'] = data['reportedCases'] * 10
output['severeImpact']['currentlyInfected'] = data['reportedCases'] * 50
if data['periodType'] == 'weeks':
data['timeToElapse'] = data['timeToElapse'] ... | def estimator(data):
output = {'data': data, 'impact': {}, 'severeImpact': {}}
output['impact']['currentlyInfected'] = data['reportedCases'] * 10
output['severeImpact']['currentlyInfected'] = data['reportedCases'] * 50
if data['periodType'] == 'weeks':
data['timeToElapse'] = data['timeToElapse']... |
# -*- coding: utf-8 -*-
"""Top-level package for Temp Monitor."""
__author__ = """Goncalo Magno"""
__email__ = 'goncalo@gmagno.dev'
__version__ = '0.4.0'
| """Top-level package for Temp Monitor."""
__author__ = 'Goncalo Magno'
__email__ = 'goncalo@gmagno.dev'
__version__ = '0.4.0' |
class TwitterSearchException(Exception):
"""
This class handles all exceptions directly based on TwitterSearch.
"""
# HTTP status codes are stored in TwitterSearch.exceptions due to possible on-the-fly modifications
_error_codes = {
1000 : 'Neither a list nor a string',
1001 : 'Not a... | class Twittersearchexception(Exception):
"""
This class handles all exceptions directly based on TwitterSearch.
"""
_error_codes = {1000: 'Neither a list nor a string', 1001: 'Not a list object', 1002: 'No ISO 6391-1 language code', 1003: 'No valid result type', 1004: 'Invalid number', 1005: 'Invalid un... |
# -*- python -*-
load("@drake//tools/workspace:os.bzl", "determine_os")
def _impl(repository_ctx):
os_result = determine_os(repository_ctx)
if os_result.error != None:
fail(os_result.error)
if os_result.is_macos:
repository_ctx.symlink(
"/usr/local/opt/double-conversion/inclu... | load('@drake//tools/workspace:os.bzl', 'determine_os')
def _impl(repository_ctx):
os_result = determine_os(repository_ctx)
if os_result.error != None:
fail(os_result.error)
if os_result.is_macos:
repository_ctx.symlink('/usr/local/opt/double-conversion/include', 'include')
repositor... |
def linear_search(array, y):
for i in range(len(array)):
if array[i] == y:
return i
return -1
arrSize=int(input("Enter Array Size"))
array=[]
print("Enter Array Elements")
for i in range(arrSize):
array.append(int(input()))
y = int(input("Enter Number you want to find =:... | def linear_search(array, y):
for i in range(len(array)):
if array[i] == y:
return i
return -1
arr_size = int(input('Enter Array Size'))
array = []
print('Enter Array Elements')
for i in range(arrSize):
array.append(int(input()))
y = int(input('Enter Number you want to find =:-'))
result ... |
""" Driver args """
data_path = '/Users/aa56927-admin/Desktop/NLP_Done_Right/sentiment_classification/data/Rotten_Tomatoes/'
output_path = 'test-blind.output.txt'
model = 'RNN' # RNN, FFNN
run_on_test_flag = True
run_on_manual_flag = True
seq_max_len = 60 # also can be computed more systematically looking at length... | """ Driver args """
data_path = '/Users/aa56927-admin/Desktop/NLP_Done_Right/sentiment_classification/data/Rotten_Tomatoes/'
output_path = 'test-blind.output.txt'
model = 'RNN'
run_on_test_flag = True
run_on_manual_flag = True
seq_max_len = 60
model_path = './model.pt'
if model == 'FFNN':
no_classes = 2
epochs... |
# https://atcoder.jp/contests/abc194/tasks/abc194_b
N = int(input())
job_list = []
a_min_idx, b_min_idx = 0, 0
a_2nd, b_2nd = 0, 0
for i in range(N):
a, b = list(map(int, input().split()))
job_list.append([a, b])
if job_list[a_min_idx][0] > a:
a_2nd = a_min_idx
a_min_idx = i
if job_list[... | n = int(input())
job_list = []
(a_min_idx, b_min_idx) = (0, 0)
(a_2nd, b_2nd) = (0, 0)
for i in range(N):
(a, b) = list(map(int, input().split()))
job_list.append([a, b])
if job_list[a_min_idx][0] > a:
a_2nd = a_min_idx
a_min_idx = i
if job_list[b_min_idx][1] > b:
b_2nd = b_min_i... |
# https://practice.geeksforgeeks.org/problems/get-minimum-element-from-stack/1#
# Approach is to store an array containing stack elements and minEle in separate variable
# For push
# if minEle is None add element to s and assign minEle - element
# if minEle <= element add element to s
# else add 2*x-minEle in s ... | class Stack:
def __init__(self):
self.s = []
self.minEle = None
def push(self, x):
if self.minEle is None:
self.minEle = x
self.s.append(x)
elif self.minEle <= x:
self.s.append(x)
else:
self.s.append(2 * x - self.minEle)
... |
class ListaMultimedia():
archivos = []
contar = 0
def __init__(self,archivos=[]):
self.archivos = archivos
def agregar(self,p):
self.archivos.append(p)
self.contar += 1
def mostrar(self):
for p in self.archivos:
print(p)
def cantidad(self):
return"""Total de objetos en la lista: {}""".fo... | class Listamultimedia:
archivos = []
contar = 0
def __init__(self, archivos=[]):
self.archivos = archivos
def agregar(self, p):
self.archivos.append(p)
self.contar += 1
def mostrar(self):
for p in self.archivos:
print(p)
def cantidad(self):
... |
# MIT License
#
# Copyright (c) 2017 Matt Boyer
#
# 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, modify, merge, p... | valid_page_sizes = (1, 512, 1024, 2048, 4096, 8192, 16384, 32768)
sqlite_table_columns = {'sqlite_master': ('type', 'name', 'tbl_name', 'rootpage', 'sql'), 'sqlite_sequence': ('name', 'seq'), 'sqlite_stat1': ('tbl', 'idx', 'stat'), 'sqlite_stat2': ('tbl', 'idx', 'sampleno', 'sample'), 'sqlite_stat3': ('tbl', 'idx', 'nE... |
def test_login_redirect(client):
"""
Test that all requests redirect to the login page
"""
URLS = [
"/web-ui/overview/",
"/web-ui/rq/create_sip",
"/api/list-frozen-objects"
]
for url in URLS:
result = client.get(url)
assert result.status_code == 302
... | def test_login_redirect(client):
"""
Test that all requests redirect to the login page
"""
urls = ['/web-ui/overview/', '/web-ui/rq/create_sip', '/api/list-frozen-objects']
for url in URLS:
result = client.get(url)
assert result.status_code == 302
assert '/web-ui/login?' in r... |
# #### We create a function cleanQ so we can do the cleaning and preperation of our data
# #### INPUT: String
# #### OUTPUT: Cleaned String
def cleanQ(query):
query = query.lower()
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(query)
stemmer=[ps.stem(i) for i in tokens]
filtered... | def clean_q(query):
query = query.lower()
tokenizer = regexp_tokenizer('\\w+')
tokens = tokenizer.tokenize(query)
stemmer = [ps.stem(i) for i in tokens]
filtered_q = [w for w in stemmer if not w in stopwords.words('english')]
return filtered_Q
def compute_tf(doc_words):
bow = 0
for (k, ... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# OpneWinchPy : a library for controlling the Raspberry Pi's Winch
# Copyright (c) 2020 Mickael Gaillard <mick.gaillard@gmail.com>
__version__ = "0.1.0"
| __version__ = '0.1.0' |
lst = []
count_of_elements = int(input("How many elements want to store in list?"))
for i in range(count_of_elements):
element = input("Enter the element:")
lst.append(element)
print(lst)
| lst = []
count_of_elements = int(input('How many elements want to store in list?'))
for i in range(count_of_elements):
element = input('Enter the element:')
lst.append(element)
print(lst) |
"""
ende nose tests
project : Ende
version : 0.1.0
status : development
modifydate : 2015-05-06 19:30:00 -0700
createdate : 2015-05-05 05:36:00 -0700
website : https://github.com/tmthydvnprt/ende
author : tmthydvnprt
email : tmthydvnprt@users.noreply.github.com
maintainer : tmthydvnprt
license ... | """
ende nose tests
project : Ende
version : 0.1.0
status : development
modifydate : 2015-05-06 19:30:00 -0700
createdate : 2015-05-05 05:36:00 -0700
website : https://github.com/tmthydvnprt/ende
author : tmthydvnprt
email : tmthydvnprt@users.noreply.github.com
maintainer : tmthydvnprt
license ... |
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = []
one_hot = {}
for word in strs:
mapping = [0 for _ in range(26)]
for char in word:
representation = ord(char)
mapping[representation % 26] += 1
... | class Solution:
def group_anagrams(self, strs: List[str]) -> List[List[str]]:
ans = []
one_hot = {}
for word in strs:
mapping = [0 for _ in range(26)]
for char in word:
representation = ord(char)
mapping[representation % 26] += 1
... |
# -*- coding: utf-8 -*-
__author__ = 'Tommy Stallings'
__email__ = 'tommy.stallings2@gmail.com'
__version__ = '1.0'
| __author__ = 'Tommy Stallings'
__email__ = 'tommy.stallings2@gmail.com'
__version__ = '1.0' |
def GetChargeLevel():
return {'data': 42, 'error': 'NO_ERROR'}
def GetBatteryTemperature():
return {'data': 25.4, 'error': 'NO_ERROR'}
def GetBatteryVoltage():
return {'data': 3111, 'error': 'NO_ERROR'}
def GetBatteryCurrent():
return {'data': 800, 'error': 'NO_ERROR'}
def GetIoVoltage():
re... | def get_charge_level():
return {'data': 42, 'error': 'NO_ERROR'}
def get_battery_temperature():
return {'data': 25.4, 'error': 'NO_ERROR'}
def get_battery_voltage():
return {'data': 3111, 'error': 'NO_ERROR'}
def get_battery_current():
return {'data': 800, 'error': 'NO_ERROR'}
def get_io_voltage():
... |
def message_replier(messages):
for message in messages:
userid = message.from_user.id
banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid))
if banlist:
return
if userid in messanger_list:
bot.reply_to(message, MESSANGER_LEAVE_MSG, parse_mode="Markdown")
messanger_lis... | def message_replier(messages):
for message in messages:
userid = message.from_user.id
banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid))
if banlist:
return
if userid in messanger_list:
bot.reply_to(message, MESSANGER_LEAVE_MSG, parse_mode='... |
"""
import time
import redis
from flask import render_template, request, current_app, jsonify, redirect, session
from init import app
from utils.interceptors import loginOptional, jsonRequest, loginRequiredJSON
from utils.jsontools import *
from utils.logger import log
from scraper.video import dispatch... | """
import time
import redis
from flask import render_template, request, current_app, jsonify, redirect, session
from init import app
from utils.interceptors import loginOptional, jsonRequest, loginRequiredJSON
from utils.jsontools import *
from utils.logger import log
from scraper.video import dispatch
from scrape... |
def maior_E_menor(x, y):
if x > y:
return x, y
return y, x
x = int(input())
y = int(input())
if(x == y):
print("0")
else:
maior, menor = maior_E_menor(x, y)
soma = 0
menor +=1
while(menor < maior):
if menor % 2 != 0:
soma += menor
menor += 1
print(s... | def maior_e_menor(x, y):
if x > y:
return (x, y)
return (y, x)
x = int(input())
y = int(input())
if x == y:
print('0')
else:
(maior, menor) = maior_e_menor(x, y)
soma = 0
menor += 1
while menor < maior:
if menor % 2 != 0:
soma += menor
menor += 1
print... |
def match(key, value):
return {"match": {key: value}}
def exists(field):
return {"exists": {"field": field}}
def add_to_dict(dict, key, value):
dict.update({key: value})
def build_more_like_this_query(count, content, language):
query_body = {"size": count, "query": {"bool": {}}} # initial empty q... | def match(key, value):
return {'match': {key: value}}
def exists(field):
return {'exists': {'field': field}}
def add_to_dict(dict, key, value):
dict.update({key: value})
def build_more_like_this_query(count, content, language):
query_body = {'size': count, 'query': {'bool': {}}}
must = []
if ... |
# Want to extract domain hotmail.com
data = 'From ritchie_ng@hotmail.com Tues May 31'
at_position = data.find('@')
print(at_position)
space_position = data.find(' ', at_position)
# Starting from at_position, where's the next space
print(space_position)
host = data[at_position + 1: space_position]
print(host) | data = 'From ritchie_ng@hotmail.com Tues May 31'
at_position = data.find('@')
print(at_position)
space_position = data.find(' ', at_position)
print(space_position)
host = data[at_position + 1:space_position]
print(host) |
def stable_sorted_copy(alist, _indices=xrange(sys.maxint)):
# the 'decorate' step: make a list such that each item
# is the concatenation of sort-keys in order of decreasing
# significance -- we'll sort this auxiliary-list
decorated = zip(alist, _indices)
# the 'sort' step: just builtin-sort the au... | def stable_sorted_copy(alist, _indices=xrange(sys.maxint)):
decorated = zip(alist, _indices)
decorated.sort()
return [item for (item, index) in decorated]
def stable_sort_inplace(alist):
alist[:] = stable_sorted_copy(alist) |
def wellbracketed(s):
c=0
for i in range(0, len(s)):
if s[i] == "(":
c = c + 1
elif s[i] == ")":
c = c - 1
if c == 0:
return(True)
else:
return(False) | def wellbracketed(s):
c = 0
for i in range(0, len(s)):
if s[i] == '(':
c = c + 1
elif s[i] == ')':
c = c - 1
if c == 0:
return True
else:
return False |
class UCOMIMoniker:
""" Use System.Runtime.InteropServices.ComTypes.IMoniker instead. """
def BindToObject(self, pbc, pmkToLeft, riidResult, ppvResult):
"""
BindToObject(self: UCOMIMoniker,pbc: UCOMIBindCtx,pmkToLeft: UCOMIMoniker,riidResult: Guid) -> (Guid,object)
Uses the moniker t... | class Ucomimoniker:
""" Use System.Runtime.InteropServices.ComTypes.IMoniker instead. """
def bind_to_object(self, pbc, pmkToLeft, riidResult, ppvResult):
"""
BindToObject(self: UCOMIMoniker,pbc: UCOMIBindCtx,pmkToLeft: UCOMIMoniker,riidResult: Guid) -> (Guid,object)
Uses the moniker to bind ... |
# https://www.tutorialspoint.com/python_data_structure/python_binary_tree.htm
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(self, data):
if self.data:
if data < self.data:
if not sel... | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(self, data):
if self.data:
if data < self.data:
if not self.left:
self.left = node(data)
else:
... |
#!/usr/bin/env python3
# Get superior triangular matrix a)
n = 3
A = [[1, 1/2, 1/3], [1/2, 1/3, 1/4], [1/3, 1/4, 1/5]]
b = [-1, 1, 1]
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i+1, n):
times = A[j][i]
b[j] -= times * b[... | n = 3
a = [[1, 1 / 2, 1 / 3], [1 / 2, 1 / 3, 1 / 4], [1 / 3, 1 / 4, 1 / 5]]
b = [-1, 1, 1]
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###
# Name: Benjamin Seeley
# Student ID: 2262810
# Email: seele105@mail.chapman.edu
# Course: PHYS220/MATH220/CPSC220 Fall 2018
# Assignment: CW03
###
"""Contains helper functions that return lists of sequences.
"""
def fibonacci(n):
"""Returns n fibonacci numbers
... | """Contains helper functions that return lists of sequences.
"""
def fibonacci(n):
"""Returns n fibonacci numbers
Args:
n: number of fibonacci numbers to return
Returns:
List that contains n fibonacci numbers
Raises:
ValueError when n is not a positive integer
... |
class CustomerAddWebsitePermissionDenied(Exception):
pass
class ObjectDoesNotExist(Exception):
pass
| class Customeraddwebsitepermissiondenied(Exception):
pass
class Objectdoesnotexist(Exception):
pass |
"""
Handle
A wrapper meant to collect the python object belonging to a blizzard 'handle'.
"""
class Handle:
handles = {}
def __init__(self, handle):
# constructorfunc can be a function that returns a handle, or a handle directly
self._handle = handle
if Handle.get(handle) != N... | """
Handle
A wrapper meant to collect the python object belonging to a blizzard 'handle'.
"""
class Handle:
handles = {}
def __init__(self, handle):
self._handle = handle
if Handle.get(handle) != None:
print('Warning: secondary object created for handle ', handle, 'objec... |
#!/bin/python3
def main(person_list):
users = []
for name, email in person_list:
if email.endswith('@gmail.com'):
users.append(name)
print(*sorted(users), sep='\n')
if __name__ == '__main__':
N = int(input())
persons = []
for N_itr in range(N):
firstName, emailID ... | def main(person_list):
users = []
for (name, email) in person_list:
if email.endswith('@gmail.com'):
users.append(name)
print(*sorted(users), sep='\n')
if __name__ == '__main__':
n = int(input())
persons = []
for n_itr in range(N):
(first_name, email_id) = input().spl... |
# basic example
class MetaSpam(type):
# notice how the __new__ method has the same arguments
# as the type function we used earlier.
def __new__(metaclass, name, bases, namespace):
name = 'SpamCreateByMeta'
bases = (int,) + bases
namespace['eggs'] = 1
return type.__new... | class Metaspam(type):
def __new__(metaclass, name, bases, namespace):
name = 'SpamCreateByMeta'
bases = (int,) + bases
namespace['eggs'] = 1
return type.__new__(metaclass, name, bases, namespace)
class Spam(object):
pass
print(Spam.__name__)
print(issubclass(Spam, int))
try:
... |
"""
232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
... | """
232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
... |
S = input()
for i in range(len(S)):
print(i + 1)
| s = input()
for i in range(len(S)):
print(i + 1) |
def c_to_f(c):
Farhenheite=(c*9/5)+32
return Farhenheite
n=int(input("Celcius="))
f=c_to_f(n)
print(f,"'F")
| def c_to_f(c):
farhenheite = c * 9 / 5 + 32
return Farhenheite
n = int(input('Celcius='))
f = c_to_f(n)
print(f, "'F") |
"""
Write a function that returns the lesser of two given numbers if both numbers are even,
but returns the greater if one or both numbers are odd.
Example 1:
lesser_of_two_evens(2, 4) output: 2
explanation:
the two parameters 2 and 4 are even numbers, therefore, we'll return the smallest even number
Example 2:
les... | """
Write a function that returns the lesser of two given numbers if both numbers are even,
but returns the greater if one or both numbers are odd.
Example 1:
lesser_of_two_evens(2, 4) output: 2
explanation:
the two parameters 2 and 4 are even numbers, therefore, we'll return the smallest even number
Example 2:
les... |
class QueueOverflow(BaseException):
pass
# Node of a doubly linkedlist
class Node:
# constructor
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
# method for setting the data field of the node
def setData(self, data):
self.data = d... | class Queueoverflow(BaseException):
pass
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def set_next(self, nextOne):
sel... |
#!/usr/bin/python
'''
Copyright 2016 Aaron Stephens <aaron@icebrg.io>, ICEBRG
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 app... | """
Copyright 2016 Aaron Stephens <aaron@icebrg.io>, ICEBRG
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... |
text = """
//------------------------------------------------------------------------------
// Explicit instantiation.
//------------------------------------------------------------------------------
#include "Geometry/Dimension.hh"
#include "GSPH/Limiters/SuperbeeLimiter.cc"
namespace Spheral {
template class Super... | text = '\n//------------------------------------------------------------------------------\n// Explicit instantiation.\n//------------------------------------------------------------------------------\n#include "Geometry/Dimension.hh"\n#include "GSPH/Limiters/SuperbeeLimiter.cc"\n\nnamespace Spheral {\n template class... |
class ProfilePage:
BACK_TO_USERS = "Back to members"
EDIT_USER_BUTTON = "Change role"
USER_EMAIL = "Email"
USER_FIRST_NAME = "First name"
USER_LAST_NAME = "Last name"
USER_ROLE = "Role"
USER_STATUS = "Status"
USER_PENDING = "Pending"
USER_DEACTIVATE = "Deactivate member"
USER_REA... | class Profilepage:
back_to_users = 'Back to members'
edit_user_button = 'Change role'
user_email = 'Email'
user_first_name = 'First name'
user_last_name = 'Last name'
user_role = 'Role'
user_status = 'Status'
user_pending = 'Pending'
user_deactivate = 'Deactivate member'
user_rea... |
'''Program to find the factorial of a number using recursion'''
def factorial_of_a_number(n):
if n<=1:
return 1
else:
return n * factorial_of_a_number(n-1)
#Taking number from user and passing it to the function
n = int(input())
print(factorial_of_a_number(n)) | """Program to find the factorial of a number using recursion"""
def factorial_of_a_number(n):
if n <= 1:
return 1
else:
return n * factorial_of_a_number(n - 1)
n = int(input())
print(factorial_of_a_number(n)) |
class EN:
START_TEXT = """
Hello {},
I am ROBOT.
"""
| class En:
start_text = '\nHello {},\nI am ROBOT.\n' |
def dec_to_bin(n):
if n < 0:
return bin(n * -1)[2:]
return bin(n)[2:]
def trim_to(number, length):
zeroes = ''
for i in range(int(length) - len(number)):
zeroes += '0'
return zeroes + number
def bit_not(number):
negated = ''
for bit in number:
if bit == '1':
negated += '... | def dec_to_bin(n):
if n < 0:
return bin(n * -1)[2:]
return bin(n)[2:]
def trim_to(number, length):
zeroes = ''
for i in range(int(length) - len(number)):
zeroes += '0'
return zeroes + number
def bit_not(number):
negated = ''
for bit in number:
if bit == '1':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.