content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
... | """
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
... |
class Solution:
ops = ['*', '/', '+', '-']
def clumsy(self, N: int) -> int:
answer = [N]
i = N - 1
j = 0
while i > 0:
op = self.ops[j % 4]
j += 1
if op == '*':
n = answer.pop(-1)
val = n * i
a... | class Solution:
ops = ['*', '/', '+', '-']
def clumsy(self, N: int) -> int:
answer = [N]
i = N - 1
j = 0
while i > 0:
op = self.ops[j % 4]
j += 1
if op == '*':
n = answer.pop(-1)
val = n * i
answ... |
s = input()
s = s[::-1]
ans = 0
b = 0
for i in range(len(s)):
if s[i] == "B":
ans += i
ans -= b
b += 1
print(ans)
| s = input()
s = s[::-1]
ans = 0
b = 0
for i in range(len(s)):
if s[i] == 'B':
ans += i
ans -= b
b += 1
print(ans) |
"""This py describe the class the could be accessed by other."""
__author__ = "Gustavo Figueiredo"
__copyright__ = "CASA"
__version__ = "1.0.1"
__maintainer__ = "Gustavo Figueiredo"
__email__ = "gustavodsf1@gmail.com"
__status__ = "Development"
| """This py describe the class the could be accessed by other."""
__author__ = 'Gustavo Figueiredo'
__copyright__ = 'CASA'
__version__ = '1.0.1'
__maintainer__ = 'Gustavo Figueiredo'
__email__ = 'gustavodsf1@gmail.com'
__status__ = 'Development' |
class PongError(Exception):
pass
class RoomError(PongError):
def __init__(self, room, msg, **kwargs):
err_msg = '{} room info : {}'.format(msg, room)
super().__init__(err_msg, **kwargs)
class PlayerError(PongError):
def __init__(self, player, msg, **kwargs):
err_msg = '{} player ... | class Pongerror(Exception):
pass
class Roomerror(PongError):
def __init__(self, room, msg, **kwargs):
err_msg = '{} room info : {}'.format(msg, room)
super().__init__(err_msg, **kwargs)
class Playererror(PongError):
def __init__(self, player, msg, **kwargs):
err_msg = '{} player ... |
BASE_HELIX_URL = "https://api.twitch.tv/helix/"
# token url will return a 404 if trailing slash is added
BASE_AUTH_URL = "https://id.twitch.tv/oauth2/token"
TOKEN_VALIDATION_URL = "https://id.twitch.tv/oauth2/validate"
WEBHOOKS_HUB_URL = "https://api.twitch.tv/helix/webhooks/hub"
| base_helix_url = 'https://api.twitch.tv/helix/'
base_auth_url = 'https://id.twitch.tv/oauth2/token'
token_validation_url = 'https://id.twitch.tv/oauth2/validate'
webhooks_hub_url = 'https://api.twitch.tv/helix/webhooks/hub' |
def main():
t = int(input())
# t = 1
for _ in range(t):
n, m = sorted(map(int, input().split()))
# n, m = 5, 7
if n % 3 == 0 or m % 3 == 0:
print(n * m // 3)
continue
if n % 3 == 1 and m % 3 == 1:
print((m // 3) * n + n // 3 + 1)
... | def main():
t = int(input())
for _ in range(t):
(n, m) = sorted(map(int, input().split()))
if n % 3 == 0 or m % 3 == 0:
print(n * m // 3)
continue
if n % 3 == 1 and m % 3 == 1:
print(m // 3 * n + n // 3 + 1)
continue
if n % 3 == 2 a... |
numbers = range(1, 10)
for number in numbers:
if number == 1:
print (str(number) + 'st')
elif number == 2:
print (str(number) + 'nd')
elif number == 3:
print (str(number) + 'rd')
else:
print (str(number) + 'th')
| numbers = range(1, 10)
for number in numbers:
if number == 1:
print(str(number) + 'st')
elif number == 2:
print(str(number) + 'nd')
elif number == 3:
print(str(number) + 'rd')
else:
print(str(number) + 'th') |
# 107
# Open the Names.txt file and display the data in Python.
with open('Names.txt', 'r') as f:
names = f.readlines()
for index, name in enumerate(names): # To remove /n
names[index] = name[:-1]
print(names)
| with open('Names.txt', 'r') as f:
names = f.readlines()
for (index, name) in enumerate(names):
names[index] = name[:-1]
print(names) |
__all__ = ['jazBegin', 'jazEnd', 'jazReturn', 'jazCall', 'jazStackInfo']
class jazBegin:
def __init__(self):
self.command = "begin";
def call(self, interpreter, arg):
interpreter.BeginSubroutine()
return None
class jazEnd:
def __init__(self):
self.command = "end";
de... | __all__ = ['jazBegin', 'jazEnd', 'jazReturn', 'jazCall', 'jazStackInfo']
class Jazbegin:
def __init__(self):
self.command = 'begin'
def call(self, interpreter, arg):
interpreter.BeginSubroutine()
return None
class Jazend:
def __init__(self):
self.command = 'end'
def... |
# New tokens can be found at https://archive.org/account/s3.php
DOI_FORMAT = '10.70102/fk2osf.io/{guid}'
DATACITE_USERNAME = ''
DATACITE_PASSWORD = ''
DATACITE_URL = 'https://doi.test.datacite.org/'
DATACITE_PREFIX = '10.70102' # Datacite's test DOI prefix -- update in production
CHUNK_SIZE = 1000
PAGE_SIZE = 100
O... | doi_format = '10.70102/fk2osf.io/{guid}'
datacite_username = ''
datacite_password = ''
datacite_url = 'https://doi.test.datacite.org/'
datacite_prefix = '10.70102'
chunk_size = 1000
page_size = 100
osf_collection_name = 'cos-dev-sandbox'
osf_bearer_token = ''
ia_access_key = ''
ia_secret_key = ''
osf_api_url = 'http://... |
b, br, bs, a, ass = map(int, input().split())
bobMoney = (br - b) * bs
aliceMoney = 0
while aliceMoney <= bobMoney:
aliceMoney += ass
a += 1
print(a) | (b, br, bs, a, ass) = map(int, input().split())
bob_money = (br - b) * bs
alice_money = 0
while aliceMoney <= bobMoney:
alice_money += ass
a += 1
print(a) |
# This is a config file for CCI data and CMIP5 sea surface temperature diagnostics
# generell flags
regionalization = True
shape = "Seas_v"
shapeNames = 1 #column of the name values
# flags for basic diagnostics
globmeants = False
mima_globmeants=[255,305]
cmap_globmeants='jet'
mima_ts=[288,292]
mima_mts=[270,310]
p... | regionalization = True
shape = 'Seas_v'
shape_names = 1
globmeants = False
mima_globmeants = [255, 305]
cmap_globmeants = 'jet'
mima_ts = [288, 292]
mima_mts = [270, 310]
portrait = True
globmeandiff = True
mima_globmeandiff = [-10, 10]
mima_globmeandiff_r = [-0.03, 0.03]
trend = False
anomalytrend = False
trend_p = Fa... |
#
# Created on Fri Apr 10 2020
#
# Title: Leetcode - Middle of the Linked List
#
# Author: Vatsal Mistry
# Web: mistryvatsal.github.io
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ... | class Solution:
def middle_node(self, head: ListNode) -> ListNode:
p1 = p2 = head
while p1 != None and p1.next != None:
(p1, p2) = (p1.next.next, p2.next)
return p2 |
async def f():
return 0
def f():
return 0
async for x in test:
print(x)
for x in test:
print(x)
for (x, y, z) in test:
print(x)
with test as f:
print(x)
async with test as f:
print(x)
if (x):
print(x)
x = [1, 2, 3]
try:
raise x
except D:
print(x)
except C:
print(x)
e... | async def f():
return 0
def f():
return 0
async for x in test:
print(x)
for x in test:
print(x)
for (x, y, z) in test:
print(x)
with test as f:
print(x)
async with test as f:
print(x)
if x:
print(x)
x = [1, 2, 3]
try:
raise x
except D:
print(x)
except C:
print(x)
except B:
... |
tabs = int(input())
salary = float(input())
for tab in range(tabs):
current_tab = input()
if current_tab == "Facebook":
salary -= 150
elif current_tab == "Instagram":
salary -= 100
elif current_tab == "Reddit":
salary -= 50
if salary <= 0:
print("You have lost your s... | tabs = int(input())
salary = float(input())
for tab in range(tabs):
current_tab = input()
if current_tab == 'Facebook':
salary -= 150
elif current_tab == 'Instagram':
salary -= 100
elif current_tab == 'Reddit':
salary -= 50
if salary <= 0:
print('You have lost your sa... |
while True:
try:
a=input()
except:
break
while "BUG" in a:
a=a.replace("BUG","")
print(a) | while True:
try:
a = input()
except:
break
while 'BUG' in a:
a = a.replace('BUG', '')
print(a) |
class Solution:
"""
@param a: The first integer
@param b: The second integer
@return: The sum of a and b
"""
# Actually both of these methods fail to work in Python
# because Python supports infinite integer
# Non-recursive
def aplusb(self, a, b):
# write your code here, try... | class Solution:
"""
@param a: The first integer
@param b: The second integer
@return: The sum of a and b
"""
def aplusb(self, a, b):
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
def aplusb(self, a, b):
carry = a ... |
class Stack:
def __init__(self):
self.items = []
self.head = -1
def push(self, x):
self.head+=1
self.items.insert(self.head, x)
def pop(self):
if self.isEmpty():
print("Stack is empty !!!")
else:
x = self.items[self.head]
self.items.pop(self.head)
self.head-=1
return x
def size(sel... | class Stack:
def __init__(self):
self.items = []
self.head = -1
def push(self, x):
self.head += 1
self.items.insert(self.head, x)
def pop(self):
if self.isEmpty():
print('Stack is empty !!!')
else:
x = self.items[self.head]
... |
class AttribDesc:
def __init__(self, name, default, datatype = 'string', params = {}):
self.name = name
self.default = default
self.datatype = datatype
self.params = params
def getName(self):
return self.name
def getDefaultValue(self):
return self.default
... | class Attribdesc:
def __init__(self, name, default, datatype='string', params={}):
self.name = name
self.default = default
self.datatype = datatype
self.params = params
def get_name(self):
return self.name
def get_default_value(self):
return self.default
... |
print ("Em que classe o seu terreno se encaixa?")
largura = float (input("Insira aqui a largura do seu terreno :"))
comprimento = float (input("Insira aqui o comprimento do seu terreno :"))
m2 = largura*comprimento
if m2 <=100:
print ("Terreno Popular")
elif m2 <= 500:
print ("Terreno Master")
if m2 >= 500:
... | print('Em que classe o seu terreno se encaixa?')
largura = float(input('Insira aqui a largura do seu terreno :'))
comprimento = float(input('Insira aqui o comprimento do seu terreno :'))
m2 = largura * comprimento
if m2 <= 100:
print('Terreno Popular')
elif m2 <= 500:
print('Terreno Master')
if m2 >= 500:
... |
def mortgage_calculator(P,r,N):
if r == 0:
return P / N
else:
return ((r * P) / (1 - (1 + r)**-N))
if __name__ == '__main__':
P = float(input('Enter the amount borrowed: '))
R = float(input('Enter the interest rate: '))
N = int(input("Enter the number of monthly payments: "))
r ... | def mortgage_calculator(P, r, N):
if r == 0:
return P / N
else:
return r * P / (1 - (1 + r) ** (-N))
if __name__ == '__main__':
p = float(input('Enter the amount borrowed: '))
r = float(input('Enter the interest rate: '))
n = int(input('Enter the number of monthly payments: '))
r... |
{
"target_defaults": {
"make_global_settings": [
[ "CC", "echo" ],
[ "LD", "echo" ],
],
},
"targets": [{
"target_name": "test",
"type": "executable",
"sources": [
"main.c",
],
}],
}
| {'target_defaults': {'make_global_settings': [['CC', 'echo'], ['LD', 'echo']]}, 'targets': [{'target_name': 'test', 'type': 'executable', 'sources': ['main.c']}]} |
#
# PySNMP MIB module SNMP-USM-HMAC-SHA2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNMP-USM-HMAC-SHA2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:00:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
#
# PySNMP MIB module XEDIA-FRAME-RELAY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-FRAME-RELAY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:42:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, constraints_union, single_value_constraint) ... |
def num():
a=int(input('input a : '))
b=int(input('input b : '))
return a, b
def func(a,b):
add = a+b
multi = a*b
devi = a/b
return add, multi, devi
if __name__=='__main__':
try:
a, b=num()
add,_,_=func(a,b)
_,multi,_=func(a,b)
_,_,devi=func(a,b)
ex... | def num():
a = int(input('input a : '))
b = int(input('input b : '))
return (a, b)
def func(a, b):
add = a + b
multi = a * b
devi = a / b
return (add, multi, devi)
if __name__ == '__main__':
try:
(a, b) = num()
(add, _, _) = func(a, b)
(_, multi, _) = func(a, b)
... |
#############################################################
# FILE : additional_file.py
# WRITER : Nadav Weisler , Weisler , 316493758
# EXERCISE : intro2cs ex1 2019
# DESCRIPTION: include function called "secret_function"
# that print "My username is weisler and I read the submission response."
###################... | def secret_function():
print('My username is weisler and I read the submission response.') |
def subsetsum(array,num):
if num == 0 or num < 1:
return None
elif len(array) == 0:
return None
else:
if array[0].marks == num:
return [array[0]]
else:
x = subsetsum(array[1:],(num - array[0].marks))
if x:
return [array[0]... | def subsetsum(array, num):
if num == 0 or num < 1:
return None
elif len(array) == 0:
return None
elif array[0].marks == num:
return [array[0]]
else:
x = subsetsum(array[1:], num - array[0].marks)
if x:
return [array[0]] + x
else:
re... |
# File: imap_consts.py
#
# Copyright (c) 2016-2022 Splunk Inc.
#
# 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 applic... | imap_json_use_ssl = 'use_ssl'
imap_json_date = 'date'
imap_json_files = 'files'
imap_json_bodies = 'bodies'
imap_json_from = 'from'
imap_json_mail = 'mail'
imap_json_subject = 'subject'
imap_json_to = 'to'
imap_json_start_time = 'start_time'
imap_json_extract_attachments = 'extract_attachments'
imap_json_extract_urls =... |
"""
1792. Maximum Average Pass Ratio
Medium
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of stude... | """
1792. Maximum Average Pass Ratio
Medium
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of stude... |
# The SavingsAccount class represents a
# savings account.
class SavingsAccount:
# The __init__ method accepts arguments for the
# account number, interest rate, and balance.
def __init__(self, account_num, int_rate, bal):
self.__account_num = account_num
self.__interest_rate = in... | class Savingsaccount:
def __init__(self, account_num, int_rate, bal):
self.__account_num = account_num
self.__interest_rate = int_rate
self.__balance = bal
def set_account_num(self, account_num):
self.__account_num = account_num
def set_interest_rate(self, int_rate):
... |
class memoize(object):
"""
Memoize wrapper for python
Usage:
@memoize
def fib(n):
pass
"""
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args):
try:
return self.memoized[args]
except KeyError:
self.memoized[args] = self.function(*ar... | class Memoize(object):
"""
Memoize wrapper for python
Usage:
@memoize
def fib(n):
pass
"""
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args):
try:
return self.memoized[args]
except KeyError:... |
with open("input_9.txt", "r") as f:
lines = f.readlines()
nums = [int(line.strip()) for line in lines]
# for i, num in enumerate(nums[25:]):
# preamble = set(nums[i:25 + i])
# found_pair = False
# for prenum in preamble:
# diff = num - prenum
# if diff in preamble:
# found_p... | with open('input_9.txt', 'r') as f:
lines = f.readlines()
nums = [int(line.strip()) for line in lines]
invalid_num = 29221323
start_idx = 0
end_idx = -1
expand_upper = True
cur_sum = 0
while True:
if expand_upper:
end_idx += 1
cur_sum += nums[end_idx]
else:
cur_sum -= nums[start_idx]... |
__VERSION__ = "0.0.1"
__AUTHOR__ = "helloqiu"
__LICENSE__ = "MIT"
__URL__ = "https://github.com/helloqiu/SillyServer"
| __version__ = '0.0.1'
__author__ = 'helloqiu'
__license__ = 'MIT'
__url__ = 'https://github.com/helloqiu/SillyServer' |
"""
Python solution for CCC '17 S1 - Sum Game
"""
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
k = 0
a_sum = 0
b_sum = 0
for i in range(n):
a_sum += a[i]
b_sum += b[i]
if a_sum == b_sum:
k = i + 1
print(k)
| """
Python solution for CCC '17 S1 - Sum Game
"""
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
k = 0
a_sum = 0
b_sum = 0
for i in range(n):
a_sum += a[i]
b_sum += b[i]
if a_sum == b_sum:
k = i + 1
print(k) |
""" Created by Chantal Worp, 24/01/2017
Solution to Problem Set 1
Introduction to Computer Science and
Programming using Python (EDX)
Problem Set 1:
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabeti... | """ Created by Chantal Worp, 24/01/2017
Solution to Problem Set 1
Introduction to Computer Science and
Programming using Python (EDX)
Problem Set 1:
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabeti... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021, SkyFoundry LLC
# Licensed under the Academic Free License version 3.0
#
# History:
# 07 Dec 2021 Matthew Giannini Creation
#
class Ref:
@staticmethod
def make_handle(handle):
time = (handle >> 32) & 0xffff_ffff
rand = handle & 0xffff_ffff
... | class Ref:
@staticmethod
def make_handle(handle):
time = handle >> 32 & 4294967295
rand = handle & 4294967295
return ref(f"{format(time, '08x')}-{format(rand, '08x')}")
def __init__(self, id, dis=None):
self._id = id
self._dis = dis
def id(self):
return... |
class Solution:
def getMaximumGenerated(self, n: int) -> int:
if n < 2:
return n
ans = [None for _ in range(n + 1)]
ans[0] = 0
ans[1] = 1
for i in range(1, n // 2 + 1):
ans[2 * i] = ans[i]
if 2 * i + 1 < n + 1:
ans[2 * i + 1... | class Solution:
def get_maximum_generated(self, n: int) -> int:
if n < 2:
return n
ans = [None for _ in range(n + 1)]
ans[0] = 0
ans[1] = 1
for i in range(1, n // 2 + 1):
ans[2 * i] = ans[i]
if 2 * i + 1 < n + 1:
ans[2 * i ... |
echo = "echo"
gcc = "gcc"
gpp = "g++"
emcc = "emcc"
empp = "em++"
cl = "cl"
clang = "clang"
clangpp = "clang++"
| echo = 'echo'
gcc = 'gcc'
gpp = 'g++'
emcc = 'emcc'
empp = 'em++'
cl = 'cl'
clang = 'clang'
clangpp = 'clang++' |
# Accept the marks of 5 subjects
m1 = input(" Enter the Marks of first subject: ")
m2 = input(" Enter the Marks of second subject: ")
m3 = input(" Enter the Marks of third subject: ")
m4 = input(" Enter the Marks of forth subject: ")
m5 = input(" Enter the Marks of fifth subject: ")
# Total Marks
Total = int(m1)+int(m... | m1 = input(' Enter the Marks of first subject: ')
m2 = input(' Enter the Marks of second subject: ')
m3 = input(' Enter the Marks of third subject: ')
m4 = input(' Enter the Marks of forth subject: ')
m5 = input(' Enter the Marks of fifth subject: ')
total = int(m1) + int(m2) + int(m3) + int(m4) + int(m5)
percentage = ... |
h = int(input())
w = int(input())
no_paint = int(input())
litres_paint = input()
space = round((h * w * 4) * ((100 - no_paint) / 100))
while not litres_paint == "Tired!":
space -= int(litres_paint)
if space <= 0:
break
litres_paint = input()
if space < 0:
print(f"All walls are painted and you h... | h = int(input())
w = int(input())
no_paint = int(input())
litres_paint = input()
space = round(h * w * 4 * ((100 - no_paint) / 100))
while not litres_paint == 'Tired!':
space -= int(litres_paint)
if space <= 0:
break
litres_paint = input()
if space < 0:
print(f'All walls are painted and you have... |
media_stats = {
'type': 'object',
'properties': {
'count': {'type': 'integer', 'minimum': 0},
'download_size': {'type': 'integer', 'minimum': 0},
'total_size': {'type': 'integer', 'minimum': 0},
'duration': {'type': 'number', 'minimum': 0},
},
}
| media_stats = {'type': 'object', 'properties': {'count': {'type': 'integer', 'minimum': 0}, 'download_size': {'type': 'integer', 'minimum': 0}, 'total_size': {'type': 'integer', 'minimum': 0}, 'duration': {'type': 'number', 'minimum': 0}}} |
#!/usr/bin/env python3
#
# vsim_defines.py
# Francesco Conti <f.conti@unibo.it>
#
# Copyright (C) 2015-2017 ETH Zurich, University of Bologna
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
#
# templates for vcompile.csh ... | vsim_preamble = '#!/bin/tcsh\nsource ${PULP_PATH}/%s/vcompile/setup.csh\n\n##############################################################################\n# Settings\n##############################################################################\n\nset IP=%s\n\n##########################################################... |
class Solution:
# my solution
def numPairsDivisibleBy60(self, time: List[int]) -> int:
dct = {}
res = 0
for i, n in enumerate(time):
dct[n % 60] = dct.get(n%60, []) + [i]
print(dct)
for left in dct.keys():
if left % 60 == 0 or... | class Solution:
def num_pairs_divisible_by60(self, time: List[int]) -> int:
dct = {}
res = 0
for (i, n) in enumerate(time):
dct[n % 60] = dct.get(n % 60, []) + [i]
print(dct)
for left in dct.keys():
if left % 60 == 0 or left % 60 == 30:
... |
def glyphs():
return 96
_font =\
b'\x00\x4a\x5a\x08\x4d\x57\x52\x46\x52\x54\x20\x52\x52\x59\x51'\
b'\x5a\x52\x5b\x53\x5a\x52\x59\x05\x4a\x5a\x4e\x46\x4e\x4d\x20'\
b'\x52\x56\x46\x56\x4d\x0b\x48\x5d\x53\x42\x4c\x62\x20\x52\x59'\
b'\x42\x52\x62\x20\x52\x4c\x4f\x5a\x4f\x20\x52\x4b\x55\x59\x55'\
b'\x1a\x48\x5c\x50\x42\x5... | def glyphs():
return 96
_font = b'\x00JZ\x08MWRFRT RRYQZR[SZRY\x05JZNFNM RVFVM\x0bH]SBLb RYBRb RLOZO RKUYU\x1aH\\PBP_ RTBT_ RYIWGTFPFMGKIKKLMMNOOUQWRXSYUYXWZT[P[MZKX\x1fF^[FI[ RNFPHPJOLMMKMIKIIJGLFNFPGSHVHYG[F RWTUUTWTYV[X[ZZ[X[VYTWT"E_\\O\\N[MZMYNXPVUTXRZP[L[JZIYHWHUISJRQNRMSKSIRGPFNGMIMKNNPQUXWZY[[[\\Z\\Y\x07MWRH... |
'''
Time: 2015.10.2
Author: Lionel
Content: Company
'''
class Company(object):
def __init__(self, name=None):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
| """
Time: 2015.10.2
Author: Lionel
Content: Company
"""
class Company(object):
def __init__(self, name=None):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name |
#!/usr/bin/env python
class Solution:
def nearestPalindromic(self, n):
mid = len(n) // 2
if len(n) % 2 == 0:
s1 = n[0:mid] + n[0:mid][::-1]
else:
s1 = n[0:mid+1] + n[0:mid][::-1]
s2, s3, s2_list, s3_list = '0', '9'*len(n), list(s1), list(s1)
# This is... | class Solution:
def nearest_palindromic(self, n):
mid = len(n) // 2
if len(n) % 2 == 0:
s1 = n[0:mid] + n[0:mid][::-1]
else:
s1 = n[0:mid + 1] + n[0:mid][::-1]
(s2, s3, s2_list, s3_list) = ('0', '9' * len(n), list(s1), list(s1))
for i in range(mid, le... |
new_model = tf.keras.models.load_model('my_first_model.h5')
cap = cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
while 1:
# get a frame
ret, frame = cap.read()
# show a frame
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fac... | new_model = tf.keras.models.load_model('my_first_model.h5')
cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
while 1:
(ret, frame) = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gra... |
JWT_SECRET_KEY = "e75a9e10168350b2a8869a8eb8a0f946a15eec8452048c0b51923f98ea9ea43b"
JWT_ALGORITHM = "HS256"
JWT_EXPIRATION_TIME_MINUTES = 60 * 24 * 5
TOKEN_DESCRIPTION = "It checks username and password if they are true, it returns JWT token to you."
TOKEN_SUMMARY = "It returns JWT Token."
ISBN_DESCRIPTION = "It is u... | jwt_secret_key = 'e75a9e10168350b2a8869a8eb8a0f946a15eec8452048c0b51923f98ea9ea43b'
jwt_algorithm = 'HS256'
jwt_expiration_time_minutes = 60 * 24 * 5
token_description = 'It checks username and password if they are true, it returns JWT token to you.'
token_summary = 'It returns JWT Token.'
isbn_description = 'It is uni... |
load(":rollup_js_result.bzl", "RollupJsResult")
def _impl(ctx):
node_executable = ctx.attr.node_executable.files.to_list()[0]
rollup_script = ctx.attr.rollup_script.files.to_list()[0]
module_name = ctx.attr.module_name
node_modules_path = rollup_script.path.split("/node_modules/")[0] + "/node_modules"
... | load(':rollup_js_result.bzl', 'RollupJsResult')
def _impl(ctx):
node_executable = ctx.attr.node_executable.files.to_list()[0]
rollup_script = ctx.attr.rollup_script.files.to_list()[0]
module_name = ctx.attr.module_name
node_modules_path = rollup_script.path.split('/node_modules/')[0] + '/node_modules'
... |
'''
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not c... | """
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not c... |
class Pattern_Seven:
'''Pattern seven
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
'''
def __init__(self, strings='*', steps=10):
self.steps = st... | class Pattern_Seven:
"""Pattern seven
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
"""
def __init__(self, strings='*', steps=10):
self.steps = st... |
# Example 1:
# Input: haystack = "hello", needle = "ll"
# Output: 2
# Example 2:
# Input: haystack = "aaaaa", needle = "bba"
# Output: -1
# Example 3:
# Input: haystack = "", needle = ""
# Output: 0
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
| class Solution:
def str_str(self, haystack: str, needle: str) -> int:
return haystack.find(needle) |
#!/usr/bin/env python3
for file_name in ['file_ignored_by_git_included_explicitly',
'file_managed_by_git']:
with open(file_name) as f:
print(f.read(), end='')
for file_name in ['file_managed_by_git_excluded',
'file_ignored_by_git']:
try:
with open(file_name)... | for file_name in ['file_ignored_by_git_included_explicitly', 'file_managed_by_git']:
with open(file_name) as f:
print(f.read(), end='')
for file_name in ['file_managed_by_git_excluded', 'file_ignored_by_git']:
try:
with open(file_name) as f:
raise exception(f"File {file_name} shouldn... |
# https://leetcode.com/problems/ugly-number/
#
# Write a program to check whether a given number is an ugly number.
#
# Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
# For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
#
# Note that 1 is typically tre... | class Solution(object):
def is_ugly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
def defactor(num, n):
while num % n == 0:
num = num / n
return num
num = defactor(num, 2)
... |
#! usr/bin/python3
"""
This is the python script used to download few codechef questions from the website.
Put them in the correct place as the structure demands like beginner questions in beginner and so on.
Add the question statement as a Readme.md for each question and the link to the question.
<Add the features o... | """
This is the python script used to download few codechef questions from the website.
Put them in the correct place as the structure demands like beginner questions in beginner and so on.
Add the question statement as a Readme.md for each question and the link to the question.
<Add the features of @SuperCodeBot on t... |
captcha="4281224989975872839961169513979579335691369498483794171253625322698694611857431137339923313798564463624821296465562866115437565642757153598749248981134244727829747894643486262785329362288817862735862788865758282393667944292233174767223374243992399861536752759241133225618738143644513391869188134516852631928916... | captcha = '428122498997587283996116951397957933569136949848379417125362532269869461185743113733992331379856446362482129646556286611543756564275715359874924898113424472782974789464348626278532936228881786273586278886575828239366794429223317476722337424399239986153675275924113322561873814364451339186918813451685263192891... |
class Metric:
def __init__(self):
pass
def update(self, outputs, target):
raise NotImplementedError
def value(self):
raise NotImplementedError
def name(self):
raise NotImplementedError
def reset(self):
pass
| class Metric:
def __init__(self):
pass
def update(self, outputs, target):
raise NotImplementedError
def value(self):
raise NotImplementedError
def name(self):
raise NotImplementedError
def reset(self):
pass |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com).
{
'name': 'Peru - Accounting',
'description': """
Peruvian accounting chart and tax localization. According the PCGE 2010.
==================... | {'name': 'Peru - Accounting', 'description': '\nPeruvian accounting chart and tax localization. According the PCGE 2010.\n========================================================================\n\nPlan contable peruano e impuestos de acuerdo a disposiciones vigentes de la\nSUNAT 2011 (PCGE 2010).\n\n ', 'author': [... |
"""Proper parenthetics."""
def lisp_parens_with_count(parens):
"""Output with count to see whether parens are open(1), broken(-1), or balanced(0)."""
open_count = 0
for par in parens:
if par == '(':
open_count
elif par == ')':
open_count -= 1
if open_count <... | """Proper parenthetics."""
def lisp_parens_with_count(parens):
"""Output with count to see whether parens are open(1), broken(-1), or balanced(0)."""
open_count = 0
for par in parens:
if par == '(':
open_count
elif par == ')':
open_count -= 1
if open_count < ... |
## Local ems economic dispatch computing format
# Diesel generator set
PG = 0
RG = 1
# Utility grid set
PUG = 2
RUG = 3
# Bi-directional convertor set
PBIC_AC2DC = 4
PBIC_DC2AC = 5
# Energy storage system set
PESS_C = 6
PESS_DC = 7
RESS = 8
EESS = 9
# Neighboring MG set
PMG = 10
# Emergency curtailment or shedding set
... | pg = 0
rg = 1
pug = 2
rug = 3
pbic_ac2_dc = 4
pbic_dc2_ac = 5
pess_c = 6
pess_dc = 7
ress = 8
eess = 9
pmg = 10
ppv = 11
pwp = 12
pl_ac = 13
pl_uac = 14
pl_dc = 15
pl_udc = 16
nx = 17 |
def find(n):
l = [''] * (n + 1)
size = 1
m = 1
while (size <= n):
i = 0
while(i < m and (size + i) <= n):
l[size + i] = "1" + l[size - m + i]
i += 1
i = 0
while(i < m and (size + m + i) <= n):
l[size + m + i] = "2" + l[size - m + i]
... | def find(n):
l = [''] * (n + 1)
size = 1
m = 1
while size <= n:
i = 0
while i < m and size + i <= n:
l[size + i] = '1' + l[size - m + i]
i += 1
i = 0
while i < m and size + m + i <= n:
l[size + m + i] = '2' + l[size - m + i]
... |
# -*- coding: utf-8 -*-
class warehouse:
def __init__(self, location, product):
self.location = location
self.deliveryPoints = list()
self.allProducts = product
self.wishlist = list()
self.excessInventory = []
self.allProducts = self.convertInv(self.allProducts)
... | class Warehouse:
def __init__(self, location, product):
self.location = location
self.deliveryPoints = list()
self.allProducts = product
self.wishlist = list()
self.excessInventory = []
self.allProducts = self.convertInv(self.allProducts)
def take(self, item):
... |
# dummy variables for flake8
# see: https://github.com/patrick-kidger/torchtyping/blob/master/FURTHER-DOCUMENTATION.md
batch = None
channels = None
time = None
behavior = None
annotator = None
classes = None
| batch = None
channels = None
time = None
behavior = None
annotator = None
classes = None |
T = input()
soma = 0
matriz = []
for i in range(0,12,+1):
linha = []
for j in range(0,12,+1):
numeros = float(input())
linha.append(numeros)
matriz.append(linha)
contagem = 0
pegaNum = 0
for i in range(1, 12,+1): #linha
for j in range(0, i, +1):
pegaNum = float(matriz[i][j])
... | t = input()
soma = 0
matriz = []
for i in range(0, 12, +1):
linha = []
for j in range(0, 12, +1):
numeros = float(input())
linha.append(numeros)
matriz.append(linha)
contagem = 0
pega_num = 0
for i in range(1, 12, +1):
for j in range(0, i, +1):
pega_num = float(matriz[i][j])
... |
"""A library to help interacting with omegaUp.
This is composed of two modules:
- [**`omegaup.api`**](./omegaup/api/) helps interacting with [omegaUp's
API](https://github.com/omegaup/omegaup/blob/master/frontend/server/src/Controllers/README.md)
and is auto-generated with correct types and the docstrings straigh... | """A library to help interacting with omegaUp.
This is composed of two modules:
- [**`omegaup.api`**](./omegaup/api/) helps interacting with [omegaUp's
API](https://github.com/omegaup/omegaup/blob/master/frontend/server/src/Controllers/README.md)
and is auto-generated with correct types and the docstrings straigh... |
# -*- coding: utf-8 -*-
"""
cli structs module.
"""
class CLIGroups:
"""
cli groups class.
each cli handler group will be registered with its relevant group name.
usage example:
`python cli.py alembic upgrade --arg value`
`python cli.py babel extract --arg value`
`python cli.py template... | """
cli structs module.
"""
class Cligroups:
"""
cli groups class.
each cli handler group will be registered with its relevant group name.
usage example:
`python cli.py alembic upgrade --arg value`
`python cli.py babel extract --arg value`
`python cli.py template package`
`python cli... |
#!/usr/bin/env python3
def word_frequencies(filename="src/alice.txt"):
with open(filename, "r") as f:
lines = f.readlines()
d = {}
for line in lines:
words = line.split()
for word in words:
word = word.strip("""!"#$%&'()*,-./:;?@[]_""")
if d.get(word) !=... | def word_frequencies(filename='src/alice.txt'):
with open(filename, 'r') as f:
lines = f.readlines()
d = {}
for line in lines:
words = line.split()
for word in words:
word = word.strip('!"#$%&\'()*,-./:;?@[]_')
if d.get(word) != None:
d[word] +... |
class REQUEST_MSG(object):
TYPE_FIELD = "type"
GET_ID = "get-id"
CONNECT_NODE = "connect-node"
AUTHENTICATE = "authentication"
HOST_MODEL = "host-model"
RUN_INFERENCE = "run-inference"
LIST_MODELS = "list-models"
DELETE_MODEL = "delete-model"
DOWNLOAD_MODEL = "download-model"
SYF... | class Request_Msg(object):
type_field = 'type'
get_id = 'get-id'
connect_node = 'connect-node'
authenticate = 'authentication'
host_model = 'host-model'
run_inference = 'run-inference'
list_models = 'list-models'
delete_model = 'delete-model'
download_model = 'download-model'
syf... |
valid_passwords = 0
with open('input.txt', 'r') as f:
for line in f:
min_max, letter_colon, password = line.split()
pmin, pmax = [int(c) for c in min_max.split('-')]
letter = letter_colon[0:1] # remove colon
password = ' ' + password # account for 1-indexing
matching_chars = 0
... | valid_passwords = 0
with open('input.txt', 'r') as f:
for line in f:
(min_max, letter_colon, password) = line.split()
(pmin, pmax) = [int(c) for c in min_max.split('-')]
letter = letter_colon[0:1]
password = ' ' + password
matching_chars = 0
if password[pmin] == lette... |
class Globee404NotFound(Exception):
def __init__(self):
super().__init__()
self.message = 'Payment Request returned 404: Not Found'
def __str__(self):
return self.message
class Globee422UnprocessableEntity(Exception):
def __init__(self, errors):
super().__init__()
... | class Globee404Notfound(Exception):
def __init__(self):
super().__init__()
self.message = 'Payment Request returned 404: Not Found'
def __str__(self):
return self.message
class Globee422Unprocessableentity(Exception):
def __init__(self, errors):
super().__init__()
... |
class BaseExchangeContactService(object):
def __init__(self, service, folder_id):
self.service = service
self.folder_id = folder_id
def get_contact(self, id):
raise NotImplementedError
def new_contact(self, **properties):
raise NotImplementedError
class BaseExchangeContac... | class Baseexchangecontactservice(object):
def __init__(self, service, folder_id):
self.service = service
self.folder_id = folder_id
def get_contact(self, id):
raise NotImplementedError
def new_contact(self, **properties):
raise NotImplementedError
class Baseexchangecontac... |
# coding: utf-8
n, t = [int(i) for i in input().split()]
queue = list(input())
for i in range(t):
queue_new = list(queue)
for j in range(n-1):
if queue[j]=='B' and queue[j+1]=='G':
queue_new[j], queue_new[j+1] = queue_new[j+1], queue_new[j]
queue = list(queue_new)
print(''.join(queue))
| (n, t) = [int(i) for i in input().split()]
queue = list(input())
for i in range(t):
queue_new = list(queue)
for j in range(n - 1):
if queue[j] == 'B' and queue[j + 1] == 'G':
(queue_new[j], queue_new[j + 1]) = (queue_new[j + 1], queue_new[j])
queue = list(queue_new)
print(''.join(queue)) |
### global constants ###
hbar = None
### dictionary for hbar ###
hbars = {'ev': 0.658229,
'cm': 5308.8,
'au': 1.0
}
### energy units ###
conv = {'ev': 0.0367493,
'cm': 4.556e-6,
'au': 1.0,
'fs': 41.3413745758,
'ps': 41.3413745758*1000.}
### mass units ###
me2... | hbar = None
hbars = {'ev': 0.658229, 'cm': 5308.8, 'au': 1.0}
conv = {'ev': 0.0367493, 'cm': 4.556e-06, 'au': 1.0, 'fs': 41.3413745758, 'ps': 41.3413745758 * 1000.0}
me2au = 0.00054858
ang2bohr = 1.88973
def convert_to(unit):
"""
"""
return conv[unit]
def convert_from(unit):
"""
"""
return 1.0... |
# Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This
# provides a helpful message to anyone still trying to use port 8000.
# Based upon
# https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#the-first-wsgi-application
html_response = b'''
<html>
<head><title>System configuration e... | html_response = b'\n<html>\n<head><title>System configuration error</title></head>\n<body>\n<h1>System configuration error</h1>\n<p>Please contact the administrator of this server.</p>\n<p style="border: 0.1em solid black; padding: 0.5em">If you are the\nadministrator of this server: KoBoCAT received this request on po... |
class Action:
def __init__(self, num1: float, num2: float):
self.num1 = num1
self.num2 = num2
class History:
def __init__(self, goldenNums: list, userActs: dict):
self.goldenNums = goldenNums
self.userActs = userActs
class Game:
def __init__(self):
self.goldenNums... | class Action:
def __init__(self, num1: float, num2: float):
self.num1 = num1
self.num2 = num2
class History:
def __init__(self, goldenNums: list, userActs: dict):
self.goldenNums = goldenNums
self.userActs = userActs
class Game:
def __init__(self):
self.goldenNum... |
PORT = 8050
DEBUG = True
DASH_TABLE_PAGE_SIZE = 5
DEFAULT_WAVELENGTH_UNIT = "angstrom"
DEFAULT_FLUX_UNIT = "F_lambda"
LOGS = { "do_log":True, "base_logs_directory":"/base/logs/directory/" }
MAX_NUM_TRACES = 30
CATALOGS = {
"sdss": {
"base_data_path":"/base/data/path/",
... | port = 8050
debug = True
dash_table_page_size = 5
default_wavelength_unit = 'angstrom'
default_flux_unit = 'F_lambda'
logs = {'do_log': True, 'base_logs_directory': '/base/logs/directory/'}
max_num_traces = 30
catalogs = {'sdss': {'base_data_path': '/base/data/path/', 'api_url': 'http://skyserver.sdss.org/public/SkySer... |
def show_urls( urllist, depth=0 ):
for entry in urllist:
if ( hasattr( entry, 'namespace' ) ):
print( "\t" * depth, entry.pattern.regex.pattern,
"[%s]" % entry.namespace )
else:
print( "\t" * depth, entry.pattern.regex.pattern,
"[%s]" % e... | def show_urls(urllist, depth=0):
for entry in urllist:
if hasattr(entry, 'namespace'):
print('\t' * depth, entry.pattern.regex.pattern, '[%s]' % entry.namespace)
else:
print('\t' * depth, entry.pattern.regex.pattern, '[%s]' % entry.name)
if hasattr(entry, 'url_pattern... |
class DictToObject(object):
def __init__(self, dictionary):
def _traverse(key, element):
if isinstance(element, dict):
return key, DictToObject(element)
else:
return key, element
objd = dict(_traverse(k, v) for k, v in dictionary.items())
... | class Dicttoobject(object):
def __init__(self, dictionary):
def _traverse(key, element):
if isinstance(element, dict):
return (key, dict_to_object(element))
else:
return (key, element)
objd = dict((_traverse(k, v) for (k, v) in dictionary.ite... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
MAX_SEQUENCE_LENGTH = 800
MAX_NB_WORDS = 20000
EMBEDDING_DIM = 50 #300
VALIDATION_SPLIT = 0.2
TEST_SPLIT = 0.10
K=10 #10
EPOCHES=100 #100
OVER_SAMPLE_NUM = 800
UNDER_SAMPLE_NUM = 500
ACTIVATION_M = 'sigmoid'
LOSS_M = 'binary_crossentropy'
OPTIMIZER_M = 'adam'
ACTIVATI... | max_sequence_length = 800
max_nb_words = 20000
embedding_dim = 50
validation_split = 0.2
test_split = 0.1
k = 10
epoches = 100
over_sample_num = 800
under_sample_num = 500
activation_m = 'sigmoid'
loss_m = 'binary_crossentropy'
optimizer_m = 'adam'
activation_s = 'softmax'
loss_s = 'categorical_crossentropy'
optimizer_... |
{"tablejoin_id": 204,
"matched_record_count": 156,
"layer_join_attribute": "TRACT",
"join_layer_id": "641",
"worldmap_username": "rp",
"unmatched_records_list": "",
"layer_typename": "geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1",
"join_layer_url": "/data/geonode:join_boston_census_blocks_0zm_bo... | {'tablejoin_id': 204, 'matched_record_count': 156, 'layer_join_attribute': 'TRACT', 'join_layer_id': '641', 'worldmap_username': 'rp', 'unmatched_records_list': '', 'layer_typename': 'geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1', 'join_layer_url': '/data/geonode:join_boston_census_blocks_0zm_boston_in... |
"""
network-structure of vgg16 excludes fully-connection layer
date: 9/17
author: arabian9ts
"""
# structure of convolution and pooling layer up to fully-connection layer
"""
size-format:
[ [ convolution_kernel ], [ bias ] ]
[ [ f_h, f_w, in_size, out_size ], [ out_size ] ]
"""... | """
network-structure of vgg16 excludes fully-connection layer
date: 9/17
author: arabian9ts
"""
'\nsize-format:\n [ [ convolution_kernel ], [ bias ] ]\n [ [ f_h, f_w, in_size, out_size ], [ out_size ] ]\n'
structure = {'conv1_1': [[3, 3, 3, 64], [64]], 'conv1_2': [[3, 3, 64, 64], ... |
"""
Set of tools to work with different observations.
"""
__all__ = ["hinode", "iris"]
| """
Set of tools to work with different observations.
"""
__all__ = ['hinode', 'iris'] |
def wiki_json(name):
name = name.strip().title()
url = 'https://en.wikipedia.org/w/api.php?action=query&titles={0}&continue=&prop=categories&format=json'.format(name)
return url
def categories(response):
return response.json()["query"]["pages"].values()[0]["categories"]
def is_ambiguous(dic):
for ite... | def wiki_json(name):
name = name.strip().title()
url = 'https://en.wikipedia.org/w/api.php?action=query&titles={0}&continue=&prop=categories&format=json'.format(name)
return url
def categories(response):
return response.json()['query']['pages'].values()[0]['categories']
def is_ambiguous(dic):
for ... |
class ValidationError(Exception):
pass
class MaxSizeValidator:
def __init__(self, max_size):
self.so_far = 0
self.max_size = max_size
def __call__(self, chunk):
self.so_far += len(chunk)
if self.so_far > self.max_size:
raise ValidationError(
'S... | class Validationerror(Exception):
pass
class Maxsizevalidator:
def __init__(self, max_size):
self.so_far = 0
self.max_size = max_size
def __call__(self, chunk):
self.so_far += len(chunk)
if self.so_far > self.max_size:
raise validation_error('Size must not be g... |
#
# JSON Output
#
def GenerateJSONArray(list, startIndex=0, endIndex=None, date=False): # Generate a json array string from a list
# ASSUMPTION: All items are of the same type / if one is list all are list
if(len(list) > 0 and type(list[0]) == type([])): # If the list has entries and... | def generate_json_array(list, startIndex=0, endIndex=None, date=False):
if len(list) > 0 and type(list[0]) == type([]):
acc = '['
for i in range(0, len(list)):
acc += generate_json_array(list[i])
if not i == len(list) - 1:
acc += ','
return acc + ']'
... |
#!/usr/bin/python3
def target_in(box, position):
xs, xe = min(box[0]), max(box[0])
ys, ye = min(box[1]), max(box[1])
if position[0] >= xs and position[0] <= xe and position[1] >= ys and position[1] <= ye:
return True
return False
def do_step(pos, v):
next_pos = (pos[0] + v[0], pos[1] + v[1... | def target_in(box, position):
(xs, xe) = (min(box[0]), max(box[0]))
(ys, ye) = (min(box[1]), max(box[1]))
if position[0] >= xs and position[0] <= xe and (position[1] >= ys) and (position[1] <= ye):
return True
return False
def do_step(pos, v):
next_pos = (pos[0] + v[0], pos[1] + v[1])
n... |
# login.py
#
# Copyright 2011 Joseph Lewis <joehms22@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at yo... | user_pass = {'admin': '21232f297a57a5a743894a0e4a801fc3'}
if SESSION and 'login' in SESSION.keys() and SESSION['login']:
self.redirect('index.py')
elif POST_DICT:
try:
if POST_DICT['password'] == user_pass[POST_DICT['username']]:
SESSION['login'] = True
SESSION['username'] = POST... |
def print_line():
print("-" * 60)
def print_full_header(build_step_name):
print_line()
print(" Build Step /// {}".format(build_step_name))
def print_footer():
print_line()
def log(level, data):
print("{0}: {1}".format(level, data))
| def print_line():
print('-' * 60)
def print_full_header(build_step_name):
print_line()
print(' Build Step /// {}'.format(build_step_name))
def print_footer():
print_line()
def log(level, data):
print('{0}: {1}'.format(level, data)) |
def partition(lst,strt,end):
pindex = strt
for i in range(strt,end-1):
if lst[i] <= lst[end-1]:
lst[pindex],lst[i] = lst[i],lst[pindex]
pindex += 1
lst[pindex],lst[end-1] = lst[end-1],lst[pindex]
return pindex
def quickSort(lst,strt=0,end=0):
if strt >= end:
... | def partition(lst, strt, end):
pindex = strt
for i in range(strt, end - 1):
if lst[i] <= lst[end - 1]:
(lst[pindex], lst[i]) = (lst[i], lst[pindex])
pindex += 1
(lst[pindex], lst[end - 1]) = (lst[end - 1], lst[pindex])
return pindex
def quick_sort(lst, strt=0, end=0):
... |
class Encapsulation:
def __init__(self):
self.__my_price = 10
def sell(self):
print("my selling price is {}".format(self.__my_price))
def setprice(self, price):
self.__my_price = price
encap = Encapsulation()
encap.sell()
encap.__my_price = 20
encap.sell()
encap.setprice(20)
encap... | class Encapsulation:
def __init__(self):
self.__my_price = 10
def sell(self):
print('my selling price is {}'.format(self.__my_price))
def setprice(self, price):
self.__my_price = price
encap = encapsulation()
encap.sell()
encap.__my_price = 20
encap.sell()
encap.setprice(20)
encap... |
#Code that can be used to calculate the total cost of room makeover in a house
def room_area(width, length):
return width*length
def room_name():
print("What is the name of the room?")
return input()
def price(name,area):
if name == "bathroom":
return 20*area
elif name == "kitchen":
return 10*area
e... | def room_area(width, length):
return width * length
def room_name():
print('What is the name of the room?')
return input()
def price(name, area):
if name == 'bathroom':
return 20 * area
elif name == 'kitchen':
return 10 * area
elif name == 'bedroom':
return 5 * area
... |
epochs=300
batch_size=16
latent=10
lr=0.0002
weight_decay=5e-4
encode_dim=[3200, 1600, 800, 400]
decode_dim=[]
print_interval=10
| epochs = 300
batch_size = 16
latent = 10
lr = 0.0002
weight_decay = 0.0005
encode_dim = [3200, 1600, 800, 400]
decode_dim = []
print_interval = 10 |
def histogram(data, n, b, h):
# data is a list
# n is an integer
# b and h are floats
# Write your code here
# return the variable storing the histogram
# Output should be a list
pass
def addressbook(name_to_phone, name_to_address):
#name_to_phone and name_to_addre... | def histogram(data, n, b, h):
pass
def addressbook(name_to_phone, name_to_address):
pass |
class Solution:
def countStudents(self, students: List[int], sandwiches: List[int]) -> int:
count = {0:0, 1:0}
for el in students:
count[el] += 1
i = 0
while i < len(students) and count[sandwiches[i]]:
count[sandwiches[i]] -= 1
i += 1
... | class Solution:
def count_students(self, students: List[int], sandwiches: List[int]) -> int:
count = {0: 0, 1: 0}
for el in students:
count[el] += 1
i = 0
while i < len(students) and count[sandwiches[i]]:
count[sandwiches[i]] -= 1
i += 1
r... |
streetlights = [
{
"_id": "5c33cb90633a6f0003bcb38b",
"latitude": 40.109356050955824,
"longitude": -88.23546712954632,
},
{
"_id": "5c33cb90633a6f0003bcb38c",
"latitude": 40.10956288950609,
"longitude": -88.23546931624688,
},
{
"_id": "5c33cb90... | streetlights = [{'_id': '5c33cb90633a6f0003bcb38b', 'latitude': 40.109356050955824, 'longitude': -88.23546712954632}, {'_id': '5c33cb90633a6f0003bcb38c', 'latitude': 40.10956288950609, 'longitude': -88.23546931624688}, {'_id': '5c33cb90633a6f0003bcb38d', 'latitude': 40.11072693111868, 'longitude': -88.23548184676547}, ... |
def contador(*num):
for valor in num:
print(num)
contad
contador(1, 2, 3,) | def contador(*num):
for valor in num:
print(num)
contad
contador(1, 2, 3) |
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
def t():
for i in range(len(a)):
a[i][i] = a[i][i]*2
t()
print(a)
| a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
def t():
for i in range(len(a)):
a[i][i] = a[i][i] * 2
t()
print(a) |
# Vipul Patel Hectoberfest
def fun1(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 != 0:
print("Fizz")
elif i % 5 == 0 and i % 3 != 0:
print("Buzz")
elif i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
else:
print(i)
num = 100
# ... | def fun1(n):
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 != 0:
print('Fizz')
elif i % 5 == 0 and i % 3 != 0:
print('Buzz')
elif i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
else:
print(i)
num = 100
fun1(num) |
# Find the first n ugly numbers
# Ugly numbers are the numbers whose prime factors are 2,3 or 5.
# Normal Approach :
# Run a loop till n and check if it has 2,3 or 5 as the only prime factors
# if yes, then print the number. It is in-efficient but has constant extra space.
# DP approach :
# As we know, every other n... | def ugly_numbers(n):
ugly = [1]
(index_of_2, index_of_3, index_of_5) = (0, 0, 0)
while len(ugly) < n:
ugly.append(min(ugly[index_of_2] * 2, min(ugly[index_of_3] * 3, ugly[index_of_5] * 5)))
if ugly[-1] == ugly[index_of_2] * 2:
index_of_2 += 1
if ugly[-1] == ugly[index_of_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.