content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Block:
def __init__(self):
self.statements = []
def add_statement(self, statement):
self.statements.append(statement)
| class Block:
def __init__(self):
self.statements = []
def add_statement(self, statement):
self.statements.append(statement) |
# TODO: Just change this to CSS
colors = {
"text" : "#aaaaaa",
"background" : "#222221",
"plot_background" : "#222221",
"plot_gridlines" : "#777776",
"page_background" : "#222221"
} | colors = {'text': '#aaaaaa', 'background': '#222221', 'plot_background': '#222221', 'plot_gridlines': '#777776', 'page_background': '#222221'} |
clang_env = {
"ASAN_SYMBOLIZER_PATH": "/usr/local/bin/llvm-symbolizer",
"CC": "/usr/local/bin/clang",
"GCOV": "/dev/null",
"LD_LIBRARY_PATH": "/usr/local/lib",
"MSAN_SYMBOLIZER_PATH": "/usr/local/bin/llvm-symbolizer",
"TSAN_SYMBOLIZER_PATH": "/usr/local/bin/llvm-symbolizer",
"UBSAN_SYMBOLIZE... | clang_env = {'ASAN_SYMBOLIZER_PATH': '/usr/local/bin/llvm-symbolizer', 'CC': '/usr/local/bin/clang', 'GCOV': '/dev/null', 'LD_LIBRARY_PATH': '/usr/local/lib', 'MSAN_SYMBOLIZER_PATH': '/usr/local/bin/llvm-symbolizer', 'TSAN_SYMBOLIZER_PATH': '/usr/local/bin/llvm-symbolizer', 'UBSAN_SYMBOLIZER_PATH': '/usr/local/bin/llvm... |
# Task 03. Special Numbers
num = int(input())
digits = [x for x in range(1,num+1)]
is_special = False
for digit in digits:
digit_iter = [int(x) for x in str(digit)]
if sum(digit_iter) == 5 or sum(digit_iter) == 7 or sum(digit_iter) == 11:
is_special = True
else:
is_special = False
pri... | num = int(input())
digits = [x for x in range(1, num + 1)]
is_special = False
for digit in digits:
digit_iter = [int(x) for x in str(digit)]
if sum(digit_iter) == 5 or sum(digit_iter) == 7 or sum(digit_iter) == 11:
is_special = True
else:
is_special = False
print(f'{digit} -> {is_special... |
__version__ = '0.11.2'
# import importlib
# import logging
# from pathlib import Path
# importlib.reload(logging)
# logpath = Path.home() / 'p4reduction.log'
# logging.basicConfig(filename=str(logpath), filemode='w',
# format='%(asctime)s %(levelname)s: %(message)s',
# datefmt='... | __version__ = '0.11.2' |
def binario(n):
num = []
while(n>1):
if(n==2 or n==3):
resto = n % 2
n //= 2
num.append(resto)
num.append(n)
else:
resto = n % 2
n //= 2
num.append(resto)
return num
n = int(input('digite um numero: '))
n... | def binario(n):
num = []
while n > 1:
if n == 2 or n == 3:
resto = n % 2
n //= 2
num.append(resto)
num.append(n)
else:
resto = n % 2
n //= 2
num.append(resto)
return num
n = int(input('digite um numero: '))
n... |
#
#
# Package libApp in directory source
#
#
print("Loaded libApp")
#
# This file can be left empty, but its presence informs the import mechanism
#
| print('Loaded libApp') |
EXPECTED_DAILY_WEBSITE_GENERATE_SAMPLES_QUERIES_SIZE = """delimiter //
DROP PROCEDURE IF EXISTS get_daily_samples_size_websites;
CREATE PROCEDURE get_daily_samples_size_websites (
IN id INT,
OUT entry0 FLOAT,
OUT entry1 FLOAT,
OUT entry2 FLOAT,
OUT entry3 FLOAT,
OUT entry4 FLOAT,
OUT entry5 ... | expected_daily_website_generate_samples_queries_size = 'delimiter //\nDROP PROCEDURE IF EXISTS get_daily_samples_size_websites;\nCREATE PROCEDURE get_daily_samples_size_websites (\n IN id INT,\n OUT entry0 FLOAT,\n OUT entry1 FLOAT,\n OUT entry2 FLOAT,\n OUT entry3 FLOAT,\n OUT entry4 FLOAT,\n OUT ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Corwin Brown <corwin@corwinbrown.com>
# Copyright: (c) 2017, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | ansible_metadata = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'}
documentation = '\n---\nmodule: win_uri\nversion_added: \'2.1\'\nshort_description: Interacts with webservices\ndescription:\n- Interacts with FTP, HTTP and HTTPS web services.\n- Supports Digest, Basic and WSSE HTTP auth... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if... | debug = True
template_debug = DEBUG
admins = ()
managers = ADMINS
databases = {'default': {'ENGINE': 'django.db.backends.', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': ''}}
time_zone = 'America/Detroit'
media_root = ''
media_url = ''
static_root = ''
static_url = '/static/'
secret_key = 't76+zh&*@(p... |
VERSION = "3.6.dev1"
SERIES = '.'.join(VERSION.split('.')[:2])
| version = '3.6.dev1'
series = '.'.join(VERSION.split('.')[:2]) |
cookie = {
'ipb_member_id': '',
'ipb_pass_hash': '',
'igneous': '',
} | cookie = {'ipb_member_id': '', 'ipb_pass_hash': '', 'igneous': ''} |
"""
TASK: Find the edit distance between two given strings.
The edit distance between two strings refers to the minimum number of character insertions,
deletions, and substitutions required to change one string to the other
"""
def edit_distance(str1: str, str2: str) -> int:
print("->edit_distance: str1={}, str2... | """
TASK: Find the edit distance between two given strings.
The edit distance between two strings refers to the minimum number of character insertions,
deletions, and substitutions required to change one string to the other
"""
def edit_distance(str1: str, str2: str) -> int:
print('->edit_distance: str1={}, str2=... |
class UserTarget:
@staticmethod
def get_response():
return "Response by UserTarget"
| class Usertarget:
@staticmethod
def get_response():
return 'Response by UserTarget' |
class ATM:
def __init__(self, balance, bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def calcul(self,request):
self.withdrawals_list.append(request)
self.balance -= request
notes =[100,50,10,5]
for note in notes :... | class Atm:
def __init__(self, balance, bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def calcul(self, request):
self.withdrawals_list.append(request)
self.balance -= request
notes = [100, 50, 10, 5]
for note in ... |
#
# @lc app=leetcode id=53 lang=python3
#
# [53] Maximum Subarray
#
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if all([x < 0 for x in nums]):
return max(nums)
running_sum = 0
ans = 0
for x in nums:
running_sum += x
... | class Solution:
def max_sub_array(self, nums: List[int]) -> int:
if all([x < 0 for x in nums]):
return max(nums)
running_sum = 0
ans = 0
for x in nums:
running_sum += x
if running_sum < 0:
running_sum = 0
continue
... |
#include inc/node.py
class Example(Node):
def __init__(self, selector):
self.dom_bind_to_node_by_selector(selector)
print(self._node)
self.dom_set_classes(['blue'])
# some raw js...
# RawJS("""/* foo */""")
| class Example(Node):
def __init__(self, selector):
self.dom_bind_to_node_by_selector(selector)
print(self._node)
self.dom_set_classes(['blue']) |
# flake8: NOQA: E501
# This proves that the given key (which is an account) exists on the trie rooted at this state
# root. It was obtained by querying geth via the LES protocol
state_root = b'Gu\xd8\x85\xf5/\x83:e\xf5\x9e0\x0b\xce\x86J\xcc\xe4.0\xc8#\xdaW\xb3\xbd\xd0).\x91\x17\xe8'
key = b'\x9b\xbf\xc3\x08Z\xd0\xd47\x... | state_root = b'Gu\xd8\x85\xf5/\x83:e\xf5\x9e0\x0b\xce\x86J\xcc\xe4.0\xc8#\xdaW\xb3\xbd\xd0).\x91\x17\xe8'
key = b'\x9b\xbf\xc3\x08Z\xd0\xd47\x84\xe6\xe4S4ndG|\xac\xa3\x0f^7\xd5nv\x14\x9e\x98\x84\xe7\xc2\x97'
proof = ([b'\x01\xb2\xcf/\xa7&\xef{\xec9c%\xed\xeb\x9b)\xe9n\xb5\xd5\x0e\x8c\xa9A\xc1:-{<2$)', b'\xa2\xbab\xe5J\... |
#!/usr/bin/python
#
# This file is part of PyRQA.
# Copyright 2015 Tobias Rawald, Mike Sips.
"""
Custom exceptions.
"""
class UnsupportedNeighbourhoodException(Exception):
""" Neighbourhood chosen is not supported. """
def __init__(self, message):
super(UnsupportedNeighbourhoodException, self).__init... | """
Custom exceptions.
"""
class Unsupportedneighbourhoodexception(Exception):
""" Neighbourhood chosen is not supported. """
def __init__(self, message):
super(UnsupportedNeighbourhoodException, self).__init__(message)
class Noopenclplatformdetectedexception(Exception):
""" No OpenCL platform co... |
# Minizip library
unz = StaticLibrary( 'unz', sources = ['ioapi.c', 'mztools.c', 'unzip.c', 'zip.c'] )
# minizip
minizip = Executable( 'minizip', libs = [ unz, 'z' ], sources = ['minizip.c'] )
# miniunz
miniunz = Executable( 'miniunz', libs = [ unz, 'z' ], sources = ['miniunz.c'] )
# Platform specific setti... | unz = static_library('unz', sources=['ioapi.c', 'mztools.c', 'unzip.c', 'zip.c'])
minizip = executable('minizip', libs=[unz, 'z'], sources=['minizip.c'])
miniunz = executable('miniunz', libs=[unz, 'z'], sources=['miniunz.c'])
if platform == 'MacOS':
project.define('unix')
elif platform == 'iOS':
project.define(... |
_base_ = [
'./coco_resize.py'
]
data = dict(
train=dict(classes=('person',)),
val=dict(classes=('person',)),
test=dict(classes=('person',))
)
| _base_ = ['./coco_resize.py']
data = dict(train=dict(classes=('person',)), val=dict(classes=('person',)), test=dict(classes=('person',))) |
class DFS:
def __init__(self):
self.visited_node_counter = 0
def visitor(self):
self.visited_node_counter += 1
def visit(self, node):
node.accept_visitor(self.visitor)
for child in node.children: self.visit(child)
class Node:
def __init__(self):
self.children = []
def add_child(self,... | class Dfs:
def __init__(self):
self.visited_node_counter = 0
def visitor(self):
self.visited_node_counter += 1
def visit(self, node):
node.accept_visitor(self.visitor)
for child in node.children:
self.visit(child)
class Node:
def __init__(self):
s... |
n=int(input())
l=[1 for i in range(n)]
for i in range(1,n):
for x in range(n):
if x==0:
continue
else:
l[x]=l[x]+l[x-1]
print(l[-1])
| n = int(input())
l = [1 for i in range(n)]
for i in range(1, n):
for x in range(n):
if x == 0:
continue
else:
l[x] = l[x] + l[x - 1]
print(l[-1]) |
android = 70 # percents of people using nova poshta on android
ios = 30 # percents of people using nova poshta on ios
people_count = 5000000
ios_people = people_count/ 100 * ios
print (ios_people, " people using nova poshta on ios.") | android = 70
ios = 30
people_count = 5000000
ios_people = people_count / 100 * ios
print(ios_people, ' people using nova poshta on ios.') |
class Profile:
'''
Example
my = Profile('Rob')
my.company = 'CPF'
my.hobby = ['Reading','Sleeping','Eating']
print(my.name)
my.show_email()
my.show_myart()
my.show_hobby()
'''
def __init__(self,name):
self.name = name
self.company = ''
self.hobby = []
self.art = '''
|\ _... | class Profile:
"""
Example
my = Profile('Rob')
my.company = 'CPF'
my.hobby = ['Reading','Sleeping','Eating']
print(my.name)
my.show_email()
my.show_myart()
my.show_hobby()
"""
def __init__(self, name):
self.name = name
self.company = ''
self.hobby = []
self.art = "\n\t\... |
def format_duration(seconds):
years = int(seconds/(365*24*60*60))
days = int((seconds-(years*365*24*60*60))/(24*60*60))
hours = int((seconds-(years*365*24*60*60)-(days*24*60*60)) / (60*60))
mins = int((seconds-(years*365*24*60*60)-(days*24*60*60) - hours*60*60)/60)
sec = (seconds -(years*365*24*60*... | def format_duration(seconds):
years = int(seconds / (365 * 24 * 60 * 60))
days = int((seconds - years * 365 * 24 * 60 * 60) / (24 * 60 * 60))
hours = int((seconds - years * 365 * 24 * 60 * 60 - days * 24 * 60 * 60) / (60 * 60))
mins = int((seconds - years * 365 * 24 * 60 * 60 - days * 24 * 60 * 60 - hou... |
# "range(1,11)" just provides us a list of numbers 1-10 (the last number isn't included).
# The list in this case would look like this: [1,2,3,4,5,6,7,8,9,10].
# For loop
## This takes each number inside "range", and saves it as a variable "i". It does whatever is in the loop with that variable, then moves to the next... | for i in range(1, 11):
print(i)
do_loop = True
while do_loop:
user_input = input('Should I do the loop again? ')
if user_input == 'no':
do_loop = False
print('Ok, exiting loop') |
def merge_sort(sorted_l1, sorted_l2):
""" Merge sorting two sorted array """
result = []
i = 0
j = 0
while i < len(sorted_l1) and j < len(sorted_l2):
if sorted_l1[i] < sorted_l2[j]:
result.append(sorted_l1[i])
i += 1
else:
result.append(sorted_l2... | def merge_sort(sorted_l1, sorted_l2):
""" Merge sorting two sorted array """
result = []
i = 0
j = 0
while i < len(sorted_l1) and j < len(sorted_l2):
if sorted_l1[i] < sorted_l2[j]:
result.append(sorted_l1[i])
i += 1
else:
result.append(sorted_l2[j... |
math_str = input("please input a number: ")
math = int(math_str)
math6 = 6
if math == math6:
print("Yes, it is 6!")
elif math < math6:
print("That's less than 6!")
else:
print("That's more than 6!")
| math_str = input('please input a number: ')
math = int(math_str)
math6 = 6
if math == math6:
print('Yes, it is 6!')
elif math < math6:
print("That's less than 6!")
else:
print("That's more than 6!") |
a = arr = [[False for i in range(100)] for j in range(100)]
ans = 0
sl = 0
block= []
def findLargestRectangle(blockNumber):
global sl
global block
block = blockNumber
for i in block: sl += i
for i in range(1,9):
find(i, 1)
return ans
def find(r,n):
global ans
global a
# ca... | a = arr = [[False for i in range(100)] for j in range(100)]
ans = 0
sl = 0
block = []
def find_largest_rectangle(blockNumber):
global sl
global block
block = blockNumber
for i in block:
sl += i
for i in range(1, 9):
find(i, 1)
return ans
def find(r, n):
global ans
globa... |
def rook_cells_under_attack(p, width=8, height=8):
cells = []
for i in range(height):
cells.append((p[0], i))
for i in range(width):
cells.append((i, p[1]))
return cells
# TODO: add width and height parameters
def bishop_cells_under_attack(p, width=8, height=8):
cells = []
for ... | def rook_cells_under_attack(p, width=8, height=8):
cells = []
for i in range(height):
cells.append((p[0], i))
for i in range(width):
cells.append((i, p[1]))
return cells
def bishop_cells_under_attack(p, width=8, height=8):
cells = []
for k in range(max(width, height)):
i... |
nome = str(input("Digite seu nome completo: ")).strip()
nome = nome.lower()
#verifica = nome.find('silva') > 0
print("Seu nome tem Silva? ")
#print("{}".format(verifica))
print("{}".format("silva" in nome))
| nome = str(input('Digite seu nome completo: ')).strip()
nome = nome.lower()
print('Seu nome tem Silva? ')
print('{}'.format('silva' in nome)) |
# Solution
# O(n*l) time / O(c) space
# n - number of words
# l - length of the longest word
# c - number of unique characters across all words
def minimumCharactersForWords(words):
maximumCharacterFrequencies = {}
for word in words:
characterFrequencies = countCharacterFrequencies(word)
updateMax... | def minimum_characters_for_words(words):
maximum_character_frequencies = {}
for word in words:
character_frequencies = count_character_frequencies(word)
update_maximum_frequencies(characterFrequencies, maximumCharacterFrequencies)
return make_array_from_character_frequencies(maximumCharacter... |
a = map(int, input().split())
b = map(int, input().split())
c = map(int, input().split())
d = map(int, input().split())
e = map(int, input().split())
_a, _b, _c, _d, _e = sum(a), sum(b), sum(c), sum(d), sum(e)
m = max(_a, _b, _c, _d, _e)
if m == _a:
print(1, _a)
elif m == _b:
print(2, _b)
elif m == _c:
pr... | a = map(int, input().split())
b = map(int, input().split())
c = map(int, input().split())
d = map(int, input().split())
e = map(int, input().split())
(_a, _b, _c, _d, _e) = (sum(a), sum(b), sum(c), sum(d), sum(e))
m = max(_a, _b, _c, _d, _e)
if m == _a:
print(1, _a)
elif m == _b:
print(2, _b)
elif m == _c:
... |
L=[23,45,88,23,56,78,96]
Temp=L[0]
L[0]=L[-1]
L[-1]=Temp
print(L)
| l = [23, 45, 88, 23, 56, 78, 96]
temp = L[0]
L[0] = L[-1]
L[-1] = Temp
print(L) |
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {integer} s
# @param {integer[]} nums
# @return {integer}
def minSubArrayLen(self, s, nums):
start = 0
sum = 0
min_size = float("inf")
for i in xrange(len(nums)):
sum += nums[i]
... | class Solution(object):
def min_sub_array_len(self, s, nums):
start = 0
sum = 0
min_size = float('inf')
for i in xrange(len(nums)):
sum += nums[i]
while sum >= s:
min_size = min(min_size, i - start + 1)
sum -= nums[start]
... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
'TEST_NAME': 'test1.db',
}
}
ROOT_URLCONF='testapp.urls'
SITE_ID = 1
SECRET_KEY = "not very secret in tests"
ALLOWED_HOSTS = (
'testserver',
'*'
)
INSTALLED_APPS = (
"rest_framework",
... | databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.db', 'TEST_NAME': 'test1.db'}}
root_urlconf = 'testapp.urls'
site_id = 1
secret_key = 'not very secret in tests'
allowed_hosts = ('testserver', '*')
installed_apps = ('rest_framework', 'testapp')
middleware_classes = ('django.middleware.comm... |
#Write a Python program that reads your height in cms and converts your height to feet and inches.
heightCM = float(input('Enter the height in CM: '))
totalInch = heightCM * 0.393701
heightInch = (totalInch % 12)
heightFeet = (totalInch - heightInch)*0.0833333
print('The height is : ',heightFeet,' feet AND 163',... | height_cm = float(input('Enter the height in CM: '))
total_inch = heightCM * 0.393701
height_inch = totalInch % 12
height_feet = (totalInch - heightInch) * 0.0833333
print('The height is : ', heightFeet, ' feet AND 163', heightInch, ' inch') |
"""Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True."""
class Solution:
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
check = set()
for c in s:
... | """Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True."""
class Solution:
def can_permute_palindrome(self, s):
"""
:type s: str
:rtype: bool
"""
check = set()
for c in s:
... |
#!/usr/bin/env python3.7
rules = {}
with open('input.txt') as fd:
for line in fd:
words = line[:-1].split()
this_bag = words[0]+ " " + words[1]
rules[this_bag] = []
b = line[:-1].split('contain')
bags = b[1].split(',')
for bag in bags:
words = bag.split()... | rules = {}
with open('input.txt') as fd:
for line in fd:
words = line[:-1].split()
this_bag = words[0] + ' ' + words[1]
rules[this_bag] = []
b = line[:-1].split('contain')
bags = b[1].split(',')
for bag in bags:
words = bag.split()
count = 0
... |
ordered_params = ['vmax', 'km', 'k_synt_s', 'k_deg_s', 'k_deg_p']
n_vars = 2
def model(y, t, yout, p):
#---------------------------------------------------------#
#Parameters#
#---------------------------------------------------------#
vmax = p[0]
km = p[1]
k_synt_s = p[2]
k_deg_s = p[3]
... | ordered_params = ['vmax', 'km', 'k_synt_s', 'k_deg_s', 'k_deg_p']
n_vars = 2
def model(y, t, yout, p):
vmax = p[0]
km = p[1]
k_synt_s = p[2]
k_deg_s = p[3]
k_deg_p = p[4]
_s = y[0]
_p = y[1]
yout[0] = (-_s * vmax + (_s + km) * (-_s * k_deg_s + k_synt_s)) / (_s + km)
yout[1] = (-_p *... |
"""
Purpose: Stakoverflow question finding first and last coordinates for values in matrix
Date created: 2019-12-28
URI: https://stackoverflow.com/questions/59511521/how-to-get-start-and-end-of-subsection-of-2d-array-where-a-condition-holds/59511652#59511652
Contributor(s):
Mark M.
"""
a = [[0, 0, 0, 0],
... | """
Purpose: Stakoverflow question finding first and last coordinates for values in matrix
Date created: 2019-12-28
URI: https://stackoverflow.com/questions/59511521/how-to-get-start-and-end-of-subsection-of-2d-array-where-a-condition-holds/59511652#59511652
Contributor(s):
Mark M.
"""
a = [[0, 0, 0, 0], [0, 1, 0... |
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
ls=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
ls.append(b)
print("Max number in the list is:",max_num_in_list(ls))
| def max_num_in_list(list):
max = list[0]
for a in list:
if a > max:
max = a
return max
ls = []
n = int(input('Enter number of elements:'))
for i in range(1, n + 1):
b = int(input('Enter element:'))
ls.append(b)
print('Max number in the list is:', max_num_in_list(ls)) |
iter_num = 0
def fib(num):
global iter_num
iter_num += 1
print("Iteration number {0}. num = {1}".format(iter_num, num))
# Base class for fibonnaci series
if num==0 or num==1:
return 1
# Recursive call
else:
return fib(num-1)+fib(num-2)
if __name__ == '__main__':
num =... | iter_num = 0
def fib(num):
global iter_num
iter_num += 1
print('Iteration number {0}. num = {1}'.format(iter_num, num))
if num == 0 or num == 1:
return 1
else:
return fib(num - 1) + fib(num - 2)
if __name__ == '__main__':
num = int(input('Enter a number: '))
ans = fib(num)
... |
class Solution:
@staticmethod
def _encode(word):
enc = []
idx = 0
repeat = 0
prev = None
while idx < len(word):
if word[idx] == prev:
idx += 1
repeat += 1
else:
if prev:
... | class Solution:
@staticmethod
def _encode(word):
enc = []
idx = 0
repeat = 0
prev = None
while idx < len(word):
if word[idx] == prev:
idx += 1
repeat += 1
else:
if prev:
enc.appen... |
def getNext(instr):
count=0
curch=instr[0]
outstr=[]
for ch in instr:
if ch != curch:
outstr.append(str(count)+curch)
curch=ch
count=1
else:
count+=1
outstr.append(str(count)+curch)
return ''.join(outstr)
a=['1']
for i in range(31)... | def get_next(instr):
count = 0
curch = instr[0]
outstr = []
for ch in instr:
if ch != curch:
outstr.append(str(count) + curch)
curch = ch
count = 1
else:
count += 1
outstr.append(str(count) + curch)
return ''.join(outstr)
a = ['1']
... |
# coding=utf-8
__author__ = 'Gareth Coles'
class BaseAlgorithm(object):
def hash(self, value, salt):
pass
def check(self, hash, value, salt):
return hash == self.hash(value, salt)
def gen_salt(self):
pass
| __author__ = 'Gareth Coles'
class Basealgorithm(object):
def hash(self, value, salt):
pass
def check(self, hash, value, salt):
return hash == self.hash(value, salt)
def gen_salt(self):
pass |
description = ''
pages = ['header',
'my_account']
def setup(data):
pass
def test(data):
navigate('http://store.demoqa.com/')
click(header.my_account)
verify_is_not_selected(my_account.remember_me)
capture('Remember me is not selected')
def teardown(data):
pass
| description = ''
pages = ['header', 'my_account']
def setup(data):
pass
def test(data):
navigate('http://store.demoqa.com/')
click(header.my_account)
verify_is_not_selected(my_account.remember_me)
capture('Remember me is not selected')
def teardown(data):
pass |
# Vamos a convertir un numero entero en una lista de sus digitos
numero = int(input('Dime tu numero\n'))
digitos =[]
while numero !=0:
digitos.insert(0,numero%10)
numero //= 10
print('Los digitos de su numero son',digitos)
| numero = int(input('Dime tu numero\n'))
digitos = []
while numero != 0:
digitos.insert(0, numero % 10)
numero //= 10
print('Los digitos de su numero son', digitos) |
def main():
input = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1... | def main():
input = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1... |
n=int(input().strip())
b=input().strip()
step=0
for i in range(0,n-2):
if(b[i]+b[i+1]+b[i+2]=='010'):
step+=1
print(step)
| n = int(input().strip())
b = input().strip()
step = 0
for i in range(0, n - 2):
if b[i] + b[i + 1] + b[i + 2] == '010':
step += 1
print(step) |
# -*- coding: utf-8 -*-
"""
View and Model base classes used to control access permissions for CRUD requests.
"""
__version__ = '0.1' | """
View and Model base classes used to control access permissions for CRUD requests.
"""
__version__ = '0.1' |
"""Dummy technologies
"""
def insert_dummy_technologies(technologies, tech_p_by, all_specified_tech_enduse_by):
"""Define dummy technologies
Where no specific technologies are assigned for an enduse
and a fueltype, dummy technologies are generated. This is
necessary because the model needs a technolog... | """Dummy technologies
"""
def insert_dummy_technologies(technologies, tech_p_by, all_specified_tech_enduse_by):
"""Define dummy technologies
Where no specific technologies are assigned for an enduse
and a fueltype, dummy technologies are generated. This is
necessary because the model needs a technolog... |
SHOWNAMES = [
"ap1/product-id",
"ap1/adc0",
"ap1/adc1",
"ap1/adc2",
"ap1/din0",
"ap1/din1",
"ap1/din2",
"ap1/din3",
"ap1/led1",
"ap1/led2",
"ap1/device-id",
"ap1/vendor-id",
"ap1/dout0",
"ap1/dout1",
"ap1/dout2",
"ap1/dout3",
"ap1/reset",
"ap1/dout... | shownames = ['ap1/product-id', 'ap1/adc0', 'ap1/adc1', 'ap1/adc2', 'ap1/din0', 'ap1/din1', 'ap1/din2', 'ap1/din3', 'ap1/led1', 'ap1/led2', 'ap1/device-id', 'ap1/vendor-id', 'ap1/dout0', 'ap1/dout1', 'ap1/dout2', 'ap1/dout3', 'ap1/reset', 'ap1/dout-enable', 'ap1/hw-version', 'capability/adc', 'capability/din', 'capabili... |
def merge(left, right, sorted_lst):
i, j, k = 0, 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
sorted_lst[k] = left[i]
i += 1
else:
sorted_lst[k] = right[j]
j += 1
k += 1
while i < len(left):
sorted_lst... | def merge(left, right, sorted_lst):
(i, j, k) = (0, 0, 0)
while i < len(left) and j < len(right):
if left[i] <= right[j]:
sorted_lst[k] = left[i]
i += 1
else:
sorted_lst[k] = right[j]
j += 1
k += 1
while i < len(left):
sorted_ls... |
# vestlus:admin:actions
def make_read(model, request, queryset):
queryset.update(read=True)
make_read.short_description = "Mark as read"
def make_unread(model, request, queryset):
queryset.update(read=False)
make_unread.short_description = "Mark as unread"
def make_private(model, request, queryset):
... | def make_read(model, request, queryset):
queryset.update(read=True)
make_read.short_description = 'Mark as read'
def make_unread(model, request, queryset):
queryset.update(read=False)
make_unread.short_description = 'Mark as unread'
def make_private(model, request, queryset):
queryset.update(is_private=Tr... |
def find(key, dictionary):
"""
Generator to extract items from complex nested data structures
source: https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-python-dictionaries-and-lists
:param key: Key to look for
:param dictionary: Object with nested dicts and lists
... | def find(key, dictionary):
"""
Generator to extract items from complex nested data structures
source: https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-python-dictionaries-and-lists
:param key: Key to look for
:param dictionary: Object with nested dicts and lists
... |
class FeedMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
if self.is_atom_feed(environ['PATH_INFO']):
def _start_response(status, headers, exc_info=None):
return start_response(status, self.set_charset(headers... | class Feedmiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
if self.is_atom_feed(environ['PATH_INFO']):
def _start_response(status, headers, exc_info=None):
return start_response(status, self.set_charset(header... |
var = 0
print("Hello!")
while var < 10:
print(10 - var, end="\n")
var += 2 | var = 0
print('Hello!')
while var < 10:
print(10 - var, end='\n')
var += 2 |
def main():
# input
ABCs = [*map(int, input().split())]
# compute
# output
print(2 * sum([ABCs[i-1]*ABCs[i] for i in range(3)]))
if __name__ == '__main__':
main()
| def main():
ab_cs = [*map(int, input().split())]
print(2 * sum([ABCs[i - 1] * ABCs[i] for i in range(3)]))
if __name__ == '__main__':
main() |
async def async_value(value):
"""
Gives an object which can be used in .thenReturn for methods that are coroutines
:param value: what should be returned after coroutine is awaited
:return: coroutine that can be awaited
"""
return value
# noinspection PyPep8Naming
class async_iter:
"""
... | async def async_value(value):
"""
Gives an object which can be used in .thenReturn for methods that are coroutines
:param value: what should be returned after coroutine is awaited
:return: coroutine that can be awaited
"""
return value
class Async_Iter:
"""
Object that can be used in as... |
def get_larger(x, y):
if x > y:
return x
else:
return y
larger_value = get_larger(23, 32)
print(larger_value)
def add_numbers(x, y):
total = x + y
return total
print("This won't be printed")
print(add_numbers(4, 5))
#Comment and doc string
# few variables below
x = 10
y = 5
# m... | def get_larger(x, y):
if x > y:
return x
else:
return y
larger_value = get_larger(23, 32)
print(larger_value)
def add_numbers(x, y):
total = x + y
return total
print("This won't be printed")
print(add_numbers(4, 5))
x = 10
y = 5
z = x + y
print(z)
def greet(word):
"""
Print... |
class Worker:
""" An abstraction of a worker. """
def __init__(self, worker_id: str):
""" Create a worker instance.
Args:
worker_id: the id that uniquely identifies the user.
"""
self._worker_id = worker_id
def worker_id(self) -> str:
... | class Worker:
""" An abstraction of a worker. """
def __init__(self, worker_id: str):
""" Create a worker instance.
Args:
worker_id: the id that uniquely identifies the user.
"""
self._worker_id = worker_id
def worker_id(self) -> str:
... |
"""
imutils/ml/aug/image/__init__.py
"""
| """
imutils/ml/aug/image/__init__.py
""" |
#Q.1 Convert tuples to list.
tup=(5,4,2,'a',16,'ram') #this is a tuples.
l=[] #this is empty list.
lenght=len(tup)
for i in (tup):
l.append(i)
print("list converted form tuples is :",l)
| tup = (5, 4, 2, 'a', 16, 'ram')
l = []
lenght = len(tup)
for i in tup:
l.append(i)
print('list converted form tuples is :', l) |
#A particularly hard problem to solve
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
#Suppose we have two arrays that are sorted
#l1 = [1,2,3]
#l2 = [4,5,6]
#L1 + L2 = [1,2,3,4,5,6]
#The median 3.5.
#Notice that the ind... | class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
x = len(nums1)
y = len(nums2)
if y < x:
return self.findMedianSortedArrays(nums2, nums1)
start = 0
end = x
while start <= end:
pivotx = int((star... |
epsilon = 0.001
def sqr_root(low,high,n,const_value):
mid = (low+high)/2.0
mid_2 = mid
for _i in range(n-1):
mid_2*=mid
dif = mid_2 - const_value
if abs(dif) <= epsilon:
return mid
elif mid_2 > const_value:
return sqr_root(low,mid,n,const_value)
elif mid_2 < const_value:
return sqr... | epsilon = 0.001
def sqr_root(low, high, n, const_value):
mid = (low + high) / 2.0
mid_2 = mid
for _i in range(n - 1):
mid_2 *= mid
dif = mid_2 - const_value
if abs(dif) <= epsilon:
return mid
elif mid_2 > const_value:
return sqr_root(low, mid, n, const_value)
elif mi... |
#! /usr/bin/python3
# seesway.py -- This script counts from -10 to 10 and then back from 10 to -10
# Author -- Prince Oppong Boamah<regioths@gmail.com>
# Date -- 27th August 2015
for i in range(-10, 11): print(i)
for i in range(9, -1, -1): print(i)
for i in range(-10, 0): print(i)
| for i in range(-10, 11):
print(i)
for i in range(9, -1, -1):
print(i)
for i in range(-10, 0):
print(i) |
#WAP to input marks of 5 subject and find average and assign grade
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the ... | sub1 = int(input('Enter marks of the first subject: '))
sub2 = int(input('Enter marks of the second subject: '))
sub3 = int(input('Enter marks of the third subject: '))
sub4 = int(input('Enter marks of the fourth subject: '))
sub5 = int(input('Enter marks of the fifth subject: '))
total = sub1 + sub2 + sub3 + sub4 + su... |
"""Kata url: https://www.codewars.com/kata/5803c0c6ab6c20a06f000026."""
def swap_vowel_case(st: str) -> str:
return ''.join(
x.swapcase() if x.lower() in 'aeoui' else x for x in st
)
| """Kata url: https://www.codewars.com/kata/5803c0c6ab6c20a06f000026."""
def swap_vowel_case(st: str) -> str:
return ''.join((x.swapcase() if x.lower() in 'aeoui' else x for x in st)) |
class Solution:
def thirdMax(self, nums: List[int]) -> int:
maxs = [-float('inf'),-float('inf'),-float('inf')]
m = 0
for i in range(len(nums)):
if nums[i] not in maxs:
if m < 3 :
maxs[m] = nums[i]
m += 1
... | class Solution:
def third_max(self, nums: List[int]) -> int:
maxs = [-float('inf'), -float('inf'), -float('inf')]
m = 0
for i in range(len(nums)):
if nums[i] not in maxs:
if m < 3:
maxs[m] = nums[i]
m += 1
... |
VERSION = '0.2'
TYPE = 'type'
LIBRML = 'libRML'
ITEM = 'item'
ID = 'id'
ACTIONS = 'actions'
RESTRICTIONS = 'restrictions'
PERMISSION = 'permission'
TENANT = 'tenant'
MENTION = 'mention'
SHARE = 'sharealike'
USAGEGUIDE = 'usageguide'
TEMPLATE = 'template'
#XML
XRESTRICTION = 'restriction'
XACTION = 'action'
XPART = '... | version = '0.2'
type = 'type'
librml = 'libRML'
item = 'item'
id = 'id'
actions = 'actions'
restrictions = 'restrictions'
permission = 'permission'
tenant = 'tenant'
mention = 'mention'
share = 'sharealike'
usageguide = 'usageguide'
template = 'template'
xrestriction = 'restriction'
xaction = 'action'
xpart = 'part'
xg... |
def factorial(n):
if(n == 0):
return 1
else:
return n*factorial(n-1)
if __name__ == "__main__":
number = int(input("Enter number:"))
print(f'Factorial of {number} is {factorial(number)}')
| def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
if __name__ == '__main__':
number = int(input('Enter number:'))
print(f'Factorial of {number} is {factorial(number)}') |
A = True
B = False
C = A and B
D = A or B
if C == True:
print("A and B is True.")
else:
print("A and B is False.")
if D == True:
print("A or B is True.")
else:
print("A or B is False.")
| a = True
b = False
c = A and B
d = A or B
if C == True:
print('A and B is True.')
else:
print('A and B is False.')
if D == True:
print('A or B is True.')
else:
print('A or B is False.') |
instr = [
"""Digit-symbol coding, part 1 (practice)
At the top of the screen you will see a row of symbols and
a row of numbers. Each symbol is paired with the number below
it.
You will also see one symbol and one number in the middle of
the screen. Your task is to decide whether they make a
correct pair. Respond... | instr = ["Digit-symbol coding, part 1 (practice)\n\nAt the top of the screen you will see a row of symbols and\na row of numbers. Each symbol is paired with the number below\nit.\n\nYou will also see one symbol and one number in the middle of\nthe screen. Your task is to decide whether they make a\ncorrect pair. Respon... |
class Tile():
def __init__(self,bomb=False):
self.bomb = False
self.revealed = False
self.nearBombs = 0
def isBomb(self):
return self.bomb
def isRevealed(self):
return self.revealed
def setBomb(self):
self.bomb=True
def setNearBombs(self,... | class Tile:
def __init__(self, bomb=False):
self.bomb = False
self.revealed = False
self.nearBombs = 0
def is_bomb(self):
return self.bomb
def is_revealed(self):
return self.revealed
def set_bomb(self):
self.bomb = True
def set_near_bombs(self, ne... |
OCTICON_FILE = """
<svg class="octicon octicon-file" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M3.75 1.5a.25.25 0 00-.25.25v11.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V6H9.75A1.75 1.75 0 018 4.25V1.5H3.75zm5.75.56v2.19c0 .138.112.25.25.25h2.19L9.5 2.... | octicon_file = '\n<svg class="octicon octicon-file" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M3.75 1.5a.25.25 0 00-.25.25v11.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V6H9.75A1.75 1.75 0 018 4.25V1.5H3.75zm5.75.56v2.19c0 .138.112.25.25.25h2.19L9.5 2.06... |
### CONFIGS ###
dataset = 'cora'
model = 'VGAE'
input_dim = 10
hidden1_dim = 32
hidden2_dim = 16
use_feature = True
num_epoch = 2000
learning_rate = 0.01 | dataset = 'cora'
model = 'VGAE'
input_dim = 10
hidden1_dim = 32
hidden2_dim = 16
use_feature = True
num_epoch = 2000
learning_rate = 0.01 |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a=[*open(0)][1].split()
a,b=[a.count('100'),a.count('200')]
print('YNEOS'[(a+2*b)%2 or b%2 and a<2::2]) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a = [*open(0)][1].split()
(a, b) = [a.count('100'), a.count('200')]
print('YNEOS'[(a + 2 * b) % 2 or (b % 2 and a < 2)::2]) |
# clut.py.
#
# clut.py Teletext colour lookup table
# Maintains colour lookups
#
# Copyright (c) 2020 Peter Kwan
#
# 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, includi... | class Clut:
def __init__(self):
print('Clut loaded')
self.clut0 = [0] * 8
self.clut1 = [0] * 8
self.clut2 = [0] * 8
self.clut3 = [0] * 8
self.reset()
def remap_colour_table(self, colourIndex, remap, foreground):
if type(colourIndex) != int:
p... |
# record all kinds of type
# pm type
LINKEDIN_TYPE = 1
PM_LANG_ITEM_TYPE = 0
PM_CITY_ITEM_TYPE = 1
PM_SERVICE_ITEM_TYPE = 2
REALTOR_MESSAGE_TYPE = 3
#quiz type
PM_QUIZ_TYPE = 0
#pm inspection report note type
PM_INSPECTION_REPORT_TYPE = 3
PM_EXPENSE_TYPE = 4
#user progress bar
USER_PROGRESS_BAR_TYPE = 0
HOME_PROGRES... | linkedin_type = 1
pm_lang_item_type = 0
pm_city_item_type = 1
pm_service_item_type = 2
realtor_message_type = 3
pm_quiz_type = 0
pm_inspection_report_type = 3
pm_expense_type = 4
user_progress_bar_type = 0
home_progress_bar_type = 1
pm_income_type = 0
pic_avatar_type = 0
pic_url_type = 1
file_s3_type = 0
status_log_use... |
if request.isInit:
lastVal = 0
else:
if lastVal == 0:
lastVal = 1
else:
lastVal = (lastVal << 1) & 0xFFFFFFFF
request.value = lastVal
| if request.isInit:
last_val = 0
else:
if lastVal == 0:
last_val = 1
else:
last_val = lastVal << 1 & 4294967295
request.value = lastVal |
# Copyright 2009, UCAR/Unidata
# Enumerate the kinds of Sax Events received by the SaxEventHandler
STARTDOCUMENT = 1
ENDDOCUMENT = 2
STARTELEMENT = 3
ENDELEMENT = 4
ATTRIBUTE = 5
CHARACTERS = 6
# Define printable output
_MAP = {
STARTDOCUMENT: "STARTDOCUMENT",
ENDDOCUMENT: "ENDDOCUMENT",
STARTELEMENT: "STARTELEMENT"... | startdocument = 1
enddocument = 2
startelement = 3
endelement = 4
attribute = 5
characters = 6
_map = {STARTDOCUMENT: 'STARTDOCUMENT', ENDDOCUMENT: 'ENDDOCUMENT', STARTELEMENT: 'STARTELEMENT', ENDELEMENT: 'ENDELEMENT', ATTRIBUTE: 'ATTRIBUTE', CHARACTERS: 'CHARACTERS'}
def tostring(t):
return _MAP[t] |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | """
Defines some constants used in chemical calculations.
"""
n_a = 6.02214129e+23
kcal_per_mol_to_j_per_molecule = 6.947695e-21
hartree_to_kcal_per_mol = 627.509474
hartree_to_j_per_mol = 2625499.63922
hartree_to_kj_per_mol = 2625.49963922
hartree_to_per_cm = 219474.63
j_per_mol_to_per_cm = 0.08359347178
cal_to_j = 4.... |
def select_k_items(stream, n, k):
reservoir = []
for i in range(k):
reservoir.append(stream[i])
if __name__ == '__main__':
stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
n = len(stream)
k = 5
select_k_items(stream, n, k) | def select_k_items(stream, n, k):
reservoir = []
for i in range(k):
reservoir.append(stream[i])
if __name__ == '__main__':
stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
n = len(stream)
k = 5
select_k_items(stream, n, k) |
#! python3
"""A printing shop runs 16 batches (jobs) every week and each batch requires a
sheet of special colour-proofing paper of size A5.
Every Monday morning, the foreman opens a new envelope, containing a large
sheet of the special paper with size A1.
He proceeds to cut it in half, thus getting two sheets of siz... | """A printing shop runs 16 batches (jobs) every week and each batch requires a
sheet of special colour-proofing paper of size A5.
Every Monday morning, the foreman opens a new envelope, containing a large
sheet of the special paper with size A1.
He proceeds to cut it in half, thus getting two sheets of size A2.
Then ... |
class Solution:
def majorityElement(self, nums: list[int]) -> list[int]:
candidate1, candidate2 = 0, 0
count1, count2 = 0, 0
for num in nums:
if candidate1 == num:
count1 += 1
continue
if candidate2 == num:
count2 += 1... | class Solution:
def majority_element(self, nums: list[int]) -> list[int]:
(candidate1, candidate2) = (0, 0)
(count1, count2) = (0, 0)
for num in nums:
if candidate1 == num:
count1 += 1
continue
if candidate2 == num:
cou... |
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def GetNumSuffixes(start_state):
"""Compute number of minimal suffixes automaton accepts from each state.
For each state reachable from given s... | def get_num_suffixes(start_state):
"""Compute number of minimal suffixes automaton accepts from each state.
For each state reachable from given state, compute number of paths in the
automaton that start from that state, end in the accepting state and do not
pass through accepting states in between.
It is ... |
memo=[0, 1]
def fib_digits(n):
if len(memo)==2:
for i in range(2, 100001):
memo.append(memo[i-1]+memo[i-2])
num=str(memo[n])
res=[]
for i in range(0,10):
check=num.count(str(i))
if check:
res.append((check, i))
return sorted(res, reverse=True) | memo = [0, 1]
def fib_digits(n):
if len(memo) == 2:
for i in range(2, 100001):
memo.append(memo[i - 1] + memo[i - 2])
num = str(memo[n])
res = []
for i in range(0, 10):
check = num.count(str(i))
if check:
res.append((check, i))
return sorted(res, reve... |
# Question 1: Write a program that asks the user to enter a string. The program should then print the following:
# a) The total number of characters in the string
# b) The string repeated 10 times
# c) The first character of the string
# d) The first three characters of the string
# e) The last three ... | string = input('enter a string')
print(len(string))
print(string * 10)
print(string[0])
print(string[0:3])
print(string[-3:])
print(string[::-1])
if len(string) >= 7:
print(string[7])
else:
print('the string is shorter than 7 charecters')
print(string[1:-1])
print(string.upper())
print(string.replace('a', 'e'))... |
_base_ = [
'../swin/cascade_mask_rcnn_swin_small_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py'
]
model = dict(
backbone=dict(
type='CBSwinTransformer',
),
neck=dict(
type='CBFPN',
),
test_cfg = dict(
rcnn=dict(
score_thr=0.001,
nms... | _base_ = ['../swin/cascade_mask_rcnn_swin_small_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py']
model = dict(backbone=dict(type='CBSwinTransformer'), neck=dict(type='CBFPN'), test_cfg=dict(rcnn=dict(score_thr=0.001, nms=dict(type='soft_nms'))))
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.... |
def test_index(man):
errors = []
G = man.writeTest()
G.addIndex("Person", "name")
G.addVertex("1", "Person", {"name": "marko", "age": "29"})
G.addVertex("2", "Person", {"name": "vadas", "age": "27"})
G.addVertex("3", "Software", {"name": "lop", "lang": "java"})
G.addVertex("4", "Person"... | def test_index(man):
errors = []
g = man.writeTest()
G.addIndex('Person', 'name')
G.addVertex('1', 'Person', {'name': 'marko', 'age': '29'})
G.addVertex('2', 'Person', {'name': 'vadas', 'age': '27'})
G.addVertex('3', 'Software', {'name': 'lop', 'lang': 'java'})
G.addVertex('4', 'Person', {'n... |
DEFAULT_CHUNK_SIZE = 1000
def chunked_iterator(qs, size=DEFAULT_CHUNK_SIZE):
qs = qs._clone()
qs.query.clear_ordering(force_empty=True)
qs.query.add_ordering('pk')
last_pk = None
empty = False
while not empty:
sub_qs = qs
if last_pk:
sub_qs = sub_qs.filter(pk__gt=la... | default_chunk_size = 1000
def chunked_iterator(qs, size=DEFAULT_CHUNK_SIZE):
qs = qs._clone()
qs.query.clear_ordering(force_empty=True)
qs.query.add_ordering('pk')
last_pk = None
empty = False
while not empty:
sub_qs = qs
if last_pk:
sub_qs = sub_qs.filter(pk__gt=las... |
indent = 3
key = "foo"
print('\n%s%*s' % (indent, len(key)+3, 'Hello')) # ok: variable length
print("%.*f" % (indent, 1.2345))
def myprint(x, *args):
print("%.3f %.4f %10.3f %1.*f" % (x, x, x, 3, x))
myprint(3)
| indent = 3
key = 'foo'
print('\n%s%*s' % (indent, len(key) + 3, 'Hello'))
print('%.*f' % (indent, 1.2345))
def myprint(x, *args):
print('%.3f %.4f %10.3f %1.*f' % (x, x, x, 3, x))
myprint(3) |
class Admin_string_literal:
def __init__(self):
Admin_string_literal.admin_menu_string = """
Select the operation to perfrom:
1. Create a Topic
2. Remove a Topic
3. Restrict a Topic
4. Purge a Topic
5. Edit a Message
6. Delete a... | class Admin_String_Literal:
def __init__(self):
Admin_string_literal.admin_menu_string = '\n Select the operation to perfrom:\n 1. Create a Topic\n 2. Remove a Topic\n 3. Restrict a Topic\n 4. Purge a Topic\n 5. Edit a Message\n 6. De... |
def max_sum_of_increasing_subseq(seq: list[int]) -> int:
"""
O(n^2) time, O(n) extra space
"""
if not seq:
return 0
max_sum = [0 for _ in seq] # the answer to the question if you have end on index i
# max sum ending on index i is seq[i] + prev biggest sum, corresponding to some j < i
... | def max_sum_of_increasing_subseq(seq: list[int]) -> int:
"""
O(n^2) time, O(n) extra space
"""
if not seq:
return 0
max_sum = [0 for _ in seq]
for i in range(len(seq)):
for j in range(i):
if seq[j] <= seq[i]:
max_sum[i] = max(max_sum[i], max_sum[j])
... |
class TextXLSError(Exception):
"""Indicates a generic textX-LS-core error."""
pass
class GenerateExtensionError(TextXLSError):
"""Indicates an error while generating an extension."""
def __init__(self, target, cmd_args):
super().__init__(
"Failed to generate the extension for '{}... | class Textxlserror(Exception):
"""Indicates a generic textX-LS-core error."""
pass
class Generateextensionerror(TextXLSError):
"""Indicates an error while generating an extension."""
def __init__(self, target, cmd_args):
super().__init__("Failed to generate the extension for '{}' with followin... |
class Floodfill:
"""abstract floodfill class, must specify _is_in_region() condition and
_fill() operation"""
def __init__(self):
pass
def floodfill(self, x, y):
Q = []
if not self._is_in_region(x,y):
return
Q.append([x,y])
while Q != []:
... | class Floodfill:
"""abstract floodfill class, must specify _is_in_region() condition and
_fill() operation"""
def __init__(self):
pass
def floodfill(self, x, y):
q = []
if not self._is_in_region(x, y):
return
Q.append([x, y])
while Q != []:
... |
PAGES_FOLDER = 'pages'
PUBLIC_FOLDER = 'public'
STATIC_FOLDER = 'static'
TEMPLATE_NAME = 'template.mustache'
| pages_folder = 'pages'
public_folder = 'public'
static_folder = 'static'
template_name = 'template.mustache' |
teisuu = 1
suuji_kous = 3
aru = 2
zenn = 0
for ai in range(suuji_kous):
zenn += teisuu*aru**ai
print(zenn)
| teisuu = 1
suuji_kous = 3
aru = 2
zenn = 0
for ai in range(suuji_kous):
zenn += teisuu * aru ** ai
print(zenn) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.