content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# https://www.facebook.com/hackercup/problem/169401886867367/
__author__ = "Moonis Javed"
__email__ = "monis.javed@gmail.com"
def numberOfDays(arr):
arr = sorted(arr)
n = 0
while len(arr) > 0:
k = arr[-1]
w = k
del arr[-1]
while w <= 50:
try:
del arr[0]
w += k
except:
break
if w > 50:
... | __author__ = 'Moonis Javed'
__email__ = 'monis.javed@gmail.com'
def number_of_days(arr):
arr = sorted(arr)
n = 0
while len(arr) > 0:
k = arr[-1]
w = k
del arr[-1]
while w <= 50:
try:
del arr[0]
w += k
except:
... |
class Robot:
def __init__(self, left="MOTOR4", right="MOTOR2", config=1):
print("init")
def forward(self):
print("forward")
def backward(self):
print("backward")
def left(self):
print("left")
def right(self):
print("right")
def stop(self):
pri... | class Robot:
def __init__(self, left='MOTOR4', right='MOTOR2', config=1):
print('init')
def forward(self):
print('forward')
def backward(self):
print('backward')
def left(self):
print('left')
def right(self):
print('right')
def stop(self):
pr... |
"""Exceptions."""
class OandaError(Exception):
""" Generic error class, catches oanda response errors
"""
def __init__(self, error_response):
self.error_response = error_response
msg = f"OANDA API returned error code {error_response['code']} ({error_response['message']}) "
super... | """Exceptions."""
class Oandaerror(Exception):
""" Generic error class, catches oanda response errors
"""
def __init__(self, error_response):
self.error_response = error_response
msg = f"OANDA API returned error code {error_response['code']} ({error_response['message']}) "
super(Oa... |
'''
Created on 1.12.2016
@author: Darren
''''''
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path... | """
Created on 1.12.2016
@author: Darren
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom i... |
#Represents an object
class Object:
def __init__(self,ID,name):
self.name = name
self.ID = ID
self.importance = 1
#keep track of the events in which this file was the object
self.modifiedIn = []
self.addedIn = []
self.deletedIn = []
def getName(self)... | class Object:
def __init__(self, ID, name):
self.name = name
self.ID = ID
self.importance = 1
self.modifiedIn = []
self.addedIn = []
self.deletedIn = []
def get_name(self):
return self.name
def get_id(self):
return self.ID
def get_impor... |
def uint(x):
# casts x to unsigned int (1 byte)
return x & 0xff
def chunkify(string, size):
# breaks up string into chunks of size
chunks = []
for i in range(0, len(string), size):
chunks.append(string[i:i + size])
return chunks
def gen_rcons(rounds):
# generates and returns round constants
# the round cons... | def uint(x):
return x & 255
def chunkify(string, size):
chunks = []
for i in range(0, len(string), size):
chunks.append(string[i:i + size])
return chunks
def gen_rcons(rounds):
rcons = []
for i in range(rounds):
value = 0
if i + 1 > 1:
if rcons[i - 1] >= 128... |
def modulus_three(n):
r = n % 3
if r == 0:
print("Multiple of 3")
elif r == 1:
print("Remainder 1")
else:
assert r == 2, "Remainder is not 2"
print("Remainder 2")
def modulus_four(n):
r = n % 4
if r == 0:
print("Multiple of 4")
elif r == 1:
p... | def modulus_three(n):
r = n % 3
if r == 0:
print('Multiple of 3')
elif r == 1:
print('Remainder 1')
else:
assert r == 2, 'Remainder is not 2'
print('Remainder 2')
def modulus_four(n):
r = n % 4
if r == 0:
print('Multiple of 4')
elif r == 1:
pr... |
""" Contains classes to handle batch data components """
class ComponentDescriptor:
""" Class for handling one component item """
def __init__(self, component, default=None):
self._component = component
self._default = default
def __get__(self, instance, cls):
try:
if ... | """ Contains classes to handle batch data components """
class Componentdescriptor:
""" Class for handling one component item """
def __init__(self, component, default=None):
self._component = component
self._default = default
def __get__(self, instance, cls):
try:
if ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 03:26:16 2019
@author: sodatab
MITx: 6.00.1x
"""
"""
03.6-Finger How Many
---------------------
Consider the following sequence of expressions:
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals... | """
Created on Mon Oct 7 03:26:16 2019
@author: sodatab
MITx: 6.00.1x
"""
"\n03.6-Finger How Many\n---------------------\n Consider the following sequence of expressions:\n\nanimals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}\n\nanimals['d'] = ['donkey']\nanimals['d'].append('dog')\nanimals['d'].append('... |
BASE_FILES = "C:\\Users\\Dani\\repos-git\\shexerp3\\test\\t_files\\"
BASE_FILES_GENERAL = BASE_FILES + "general\\"
G1 = BASE_FILES + "t_graph_1.ttl"
G1_NT = BASE_FILES + "t_graph_1.nt"
G1_TSVO_SPO = BASE_FILES + "t_graph_1.tsv"
G1_JSON_LD = BASE_FILES + "t_graph_1.json"
G1_XML = BASE_FILES + "t_graph_1.xml"
G1_N3 = B... | base_files = 'C:\\Users\\Dani\\repos-git\\shexerp3\\test\\t_files\\'
base_files_general = BASE_FILES + 'general\\'
g1 = BASE_FILES + 't_graph_1.ttl'
g1_nt = BASE_FILES + 't_graph_1.nt'
g1_tsvo_spo = BASE_FILES + 't_graph_1.tsv'
g1_json_ld = BASE_FILES + 't_graph_1.json'
g1_xml = BASE_FILES + 't_graph_1.xml'
g1_n3 = BAS... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def deps():
excludes = native.existing_rules().keys()
if "bazel_installer" not in excludes:
http_file(
name = "bazel_installer",
downloaded_file_path = "bazel-installer.sh",
sha256 = "bd7a3a583a18640f... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file')
def deps():
excludes = native.existing_rules().keys()
if 'bazel_installer' not in excludes:
http_file(name='bazel_installer', downloaded_file_path='bazel-installer.sh', sha256='bd7a3a583a18640f58308c26e654239d412adaa833b6b6a7b57a216ab62f... |
#!/usr/bin/python
def test_vars():
"""test variables in python"""
int_var = 5
string_var = "hah"
assert int_var == 5
assert string_var == 'hah'
print("test vars is done")
if __name__ == "__main__":
test_vars()
| def test_vars():
"""test variables in python"""
int_var = 5
string_var = 'hah'
assert int_var == 5
assert string_var == 'hah'
print('test vars is done')
if __name__ == '__main__':
test_vars() |
class Programmer:
def __init__(self, name, language, skills):
self.name = name
self.language = language
self.skills = skills
def watch_course(self, course_name, language, skills_earned):
if not self.language == language:
return f"{self.name} does not know {language}"... | class Programmer:
def __init__(self, name, language, skills):
self.name = name
self.language = language
self.skills = skills
def watch_course(self, course_name, language, skills_earned):
if not self.language == language:
return f'{self.name} does not know {language}... |
#returns the value to the variable #
x = 900
print(x)
#print will take the argument x as the value in the variable #
| x = 900
print(x) |
def add(tree, x):
if not tree:
tree.extend([x, None, None])
print('DONE')
return
key = tree[0]
if x == key:
print('ALREADY')
elif x < key:
left = tree[1]
if left == None:
tree[1] = [x, None, None]
print('DONE')
else:
... | def add(tree, x):
if not tree:
tree.extend([x, None, None])
print('DONE')
return
key = tree[0]
if x == key:
print('ALREADY')
elif x < key:
left = tree[1]
if left == None:
tree[1] = [x, None, None]
print('DONE')
else:
... |
batch_size, num_samples, sample_rate = 32, 32000, 16000.0
# A Tensor of [batch_size, num_samples] mono PCM samples in the range [-1, 1].
pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32)
# A 1024-point STFT with frames of 64 ms and 75% overlap.
stfts = tf.signal.stft(pcm, frame_length=1024, frame_ste... | (batch_size, num_samples, sample_rate) = (32, 32000, 16000.0)
pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32)
stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256, fft_length=1024)
spectrograms = tf.abs(stfts)
num_spectrogram_bins = stfts.shape[-1].value
(lower_edge_hertz, upper_edge_hertz,... |
"""Top-level package for mynlp."""
__author__ = """Suneel Dondapati"""
__email__ = 'dsuneel1@gmail.com'
__version__ = '0.1.0'
| """Top-level package for mynlp."""
__author__ = 'Suneel Dondapati'
__email__ = 'dsuneel1@gmail.com'
__version__ = '0.1.0' |
"""
User Get Key Value Input Dictionary Start
"""
dic = {
"google": "google is provide job and internship.",
"amezon": "amezon is e-commerce store and cloud computing provider.",
"zoom": "zoom is provide video call system to connecting meeating.",
"microsoft": "microsoft is owner of windows and office ... | """
User Get Key Value Input Dictionary Start
"""
dic = {'google': 'google is provide job and internship.', 'amezon': 'amezon is e-commerce store and cloud computing provider.', 'zoom': 'zoom is provide video call system to connecting meeating.', 'microsoft': 'microsoft is owner of windows and office software..'}
print... |
# Copyright 2016 Dave Kludt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | sample_product = {'title': 'Test', 'us_url': 'http://us.test.com', 'uk_url': 'http://uk.test.com', 'active': True, 'db_name': 'test', 'require_region': True, 'doc_url': 'http://doc.test.com', 'pitchfork_url': 'https://pitchfork/url'}
sample_limit = {'product': 'test', 'title': 'Test', 'uri': '/limits', 'slug': 'test', ... |
class Element:
dependencies = []
def __init__(self, name):
self.name = name
def add_dependencies(self, *elements):
for element in elements:
if not self.dependencies.__contains__(element):
self.dependencies.append(element)
def remove_dependencies(self, *elem... | class Element:
dependencies = []
def __init__(self, name):
self.name = name
def add_dependencies(self, *elements):
for element in elements:
if not self.dependencies.__contains__(element):
self.dependencies.append(element)
def remove_dependencies(self, *elem... |
# known contracts from protocol
CONTRACTS = [
# NFT - Meteor Dust
"terra1p70x7jkqhf37qa7qm4v23g4u4g8ka4ktxudxa7",
# NFT - Eggs
"terra1k0y373yxqne22pc9g7jvnr4qclpsxtafevtrpg",
# NFT - Dragons
"terra1vhuyuwwr4rkdpez5f5lmuqavut28h5dt29rpn6",
# NFT - Loot
"terra14gfnxnwl0yz6njzet4n33erq5n70w... | contracts = ['terra1p70x7jkqhf37qa7qm4v23g4u4g8ka4ktxudxa7', 'terra1k0y373yxqne22pc9g7jvnr4qclpsxtafevtrpg', 'terra1vhuyuwwr4rkdpez5f5lmuqavut28h5dt29rpn6', 'terra14gfnxnwl0yz6njzet4n33erq5n70wt79nm24el']
def handle(exporter, elem, txinfo, contract):
print(f'Levana! {contract}') |
def isPalindrome(string, i = 0):
j = len(string) - 1 -i
return True if i > j else string[i] == string[j] and isPalindrome(string, i+1)
def isPalindrome(string):
return string == string[::-1]
def isPalindromeUsingIndexes(string):
lIx = 0
rIdx = len(string) -1
while lIx < rIdx:
if(string... | def is_palindrome(string, i=0):
j = len(string) - 1 - i
return True if i > j else string[i] == string[j] and is_palindrome(string, i + 1)
def is_palindrome(string):
return string == string[::-1]
def is_palindrome_using_indexes(string):
l_ix = 0
r_idx = len(string) - 1
while lIx < rIdx:
... |
# coding=utf-8
# *** WARNING: this file was generated by crd2pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
SNAKE_TO_CAMEL_CASE_TABLE = {
"access_modes": "accessModes",
"api_group": "apiGroup",
"api_version": "apiVersion",
"app_protocol": "appProtocol",
... | snake_to_camel_case_table = {'access_modes': 'accessModes', 'api_group': 'apiGroup', 'api_version': 'apiVersion', 'app_protocol': 'appProtocol', 'association_status': 'associationStatus', 'available_nodes': 'availableNodes', 'change_budget': 'changeBudget', 'client_ip': 'clientIP', 'cluster_ip': 'clusterIP', 'config_re... |
# -*- coding: utf-8 -*-
# Importing Libraries
"""
# Commented out IPython magic to ensure Python compatibility.
import torch
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import torch.nn as nn
from tqdm import tqdm_notebook
from sklearn.preprocessing import MinMaxScaler... | """
# Commented out IPython magic to ensure Python compatibility.
import torch
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import torch.nn as nn
from tqdm import tqdm_notebook
from sklearn.preprocessing import MinMaxScaler
# %matplotlib inline
torch.manual_seed(0)
"""... |
# List of addresses within the Battle Animation Scripts for the following commands which cause screen flashes:
# B0 - Set background palette color addition (absolute)
# B5 - Add color to background palette (relative)
# AF - Set background palette color subtraction (absolute)
# B6 - Subtract color from backgroun... | battle_animation_flashes = {'Goner': [1048712, 1048716, 1048722, 1048728, 1048737, 1048739, 1048787, 1048799, 1048946], 'Final KEFKA Death': [1049146, 1049152, 1049160, 1049166], 'Atom Edge': [1049552, 1049565, 1049574, 1049675, 1049687], 'Boss Death': [1049718, 1049724, 1049732, 1049751], 'Transform into Magicite': [1... |
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
if not envelopes:
return 0
pairs = sorted(envelopes, key=lambda x: (x[0], -x[1]))
result = []
for pair in pairs:
height = pair[1]
if len(result) == 0 or height > result[-1]... | class Solution:
def max_envelopes(self, envelopes: List[List[int]]) -> int:
if not envelopes:
return 0
pairs = sorted(envelopes, key=lambda x: (x[0], -x[1]))
result = []
for pair in pairs:
height = pair[1]
if len(result) == 0 or height > result[-1... |
# -*- coding: utf-8 -*-
# This file is made to configure every file number at one place
# Choose the place you are training at
# AWS : 0, Own PC : 1
PC = 1
path_list = ["/jet/prs/workspace/", "."]
url = path_list[PC]
clothes = ['shirt',
'jeans',
'blazer',
'chino-pants',
'jacket'... | pc = 1
path_list = ['/jet/prs/workspace/', '.']
url = path_list[PC]
clothes = ['shirt', 'jeans', 'blazer', 'chino-pants', 'jacket', 'coat', 'hoody', 'training-pants', 't-shirt', 'polo-shirt', 'knit', 'slacks', 'sweat-shirt']
schedule = ['party', 'trip', 'sport', 'work', 'speech', 'daily', 'school', 'date']
weather = ['... |
def test_rm_long_opt_help(pycred):
pycred('rm --help')
def test_rm_short_opt_help(pycred):
pycred('rm -h')
def test_rm_none_existing_store_gives_exit_code_2(pycred, workspace):
with workspace():
pycred('rm non-existing-store user', expected_exit_code=2)
| def test_rm_long_opt_help(pycred):
pycred('rm --help')
def test_rm_short_opt_help(pycred):
pycred('rm -h')
def test_rm_none_existing_store_gives_exit_code_2(pycred, workspace):
with workspace():
pycred('rm non-existing-store user', expected_exit_code=2) |
# Application definition
INSTALLED_APPS = [
'django.contrib.staticfiles',
'django.contrib.sessions',
'authenticate',
]
ROOT_URLCONF = 'auth_service.urls'
WSGI_APPLICATION = 'auth_service.wsgi.application'
# Use a non database session engine
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookie... | installed_apps = ['django.contrib.staticfiles', 'django.contrib.sessions', 'authenticate']
root_urlconf = 'auth_service.urls'
wsgi_application = 'auth_service.wsgi.application'
session_engine = 'django.contrib.sessions.backends.signed_cookies'
session_cookie_secure = False |
s=[]
for i in range(int(input())):
s.append(input())
cnt=0
while s:
flag=True
for i in range(len(s)//2):
if s[i]<s[-(i+1)]:
print(s[0],end='')
s.pop(0)
flag=False
break
elif s[-(i+1)]<s[i]:
print(s[-1],end='')
s.pop()
flag=False
break
if flag:
print(s[-1],end='')
s.pop()
cnt+=1
if ... | s = []
for i in range(int(input())):
s.append(input())
cnt = 0
while s:
flag = True
for i in range(len(s) // 2):
if s[i] < s[-(i + 1)]:
print(s[0], end='')
s.pop(0)
flag = False
break
elif s[-(i + 1)] < s[i]:
print(s[-1], end='')
... |
cars=100
cars_in_space=5
drivers=20
pasengers=70
car_not_driven=cars-drivers
cars_driven=drivers
carpool_capacity=cars_driven*space_in_a_car
average_passengers_percar=passengers/cars_driven
print("There are", cars,"cars availble")
print("There are only",drivers,"drivers availble")
print("There will be",car_not_driven,"... | cars = 100
cars_in_space = 5
drivers = 20
pasengers = 70
car_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_percar = passengers / cars_driven
print('There are', cars, 'cars availble')
print('There are only', drivers, 'drivers availble')
print('There ... |
# AUTOGENERATED! DO NOT EDIT! File to edit: dataset.ipynb (unless otherwise specified).
__all__ = ['load_mp3', 'get_sample_label', 'preprocess_file', 'pad_by_zeros', 'split_file_by_window_size',
'wrapper_split_file_by_window_size', 'create_dataset_fixed_size', 'get_spectrogram', 'add_channel_dim']
# Cell
d... | __all__ = ['load_mp3', 'get_sample_label', 'preprocess_file', 'pad_by_zeros', 'split_file_by_window_size', 'wrapper_split_file_by_window_size', 'create_dataset_fixed_size', 'get_spectrogram', 'add_channel_dim']
def load_mp3(file):
sample = tf.io.read_file(file)
sample_audio = tfio.audio.decode_mp3(sample)
... |
# Copyright 2014-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
class mockData:
"""dictionary of mocking data for the mocking tests"""
# dictionary to hold the mock data
_data={}
# function to add mock data to the _mock_data dictionary
def _add(se... | class Mockdata:
"""dictionary of mocking data for the mocking tests"""
_data = {}
def _add(self, uri, status, payload):
self._data[uri] = {'status': status, 'payload': payload}
return
def get_payload(self, input):
return self._data[input]['payload']
def get_status_code(sel... |
a = int(input())
b = int(input())
if a >=b*12:
print("Buy it!")
else:
print("Try again")
| a = int(input())
b = int(input())
if a >= b * 12:
print('Buy it!')
else:
print('Try again') |
# [weight, value]
I = [[4, 8], [4, 7], [6, 14]]
k = 8
def knapRecursive(I, k):
return knapRecursiveAux(I, k, len(I) - 1)
def knapRecursiveAux(I, k, hi):
# final element
if hi == 0:
# too big for sack
if I[hi][0] > k:
return 0
# fits
else:
retur... | i = [[4, 8], [4, 7], [6, 14]]
k = 8
def knap_recursive(I, k):
return knap_recursive_aux(I, k, len(I) - 1)
def knap_recursive_aux(I, k, hi):
if hi == 0:
if I[hi][0] > k:
return 0
else:
return I[hi][1]
elif I[hi][0] > k:
return knap_recursive_aux(I, k, hi - 1)... |
class Piece(object):
def __init__(self,
is_tall: bool = True,
is_dark: bool = True,
is_square: bool = True,
is_solid: bool = True,
string: str = None):
if string:
self.is_tall = (string[0] == "1")
se... | class Piece(object):
def __init__(self, is_tall: bool=True, is_dark: bool=True, is_square: bool=True, is_solid: bool=True, string: str=None):
if string:
self.is_tall = string[0] == '1'
self.is_dark = string[1] == '1'
self.is_square = string[2] == '1'
self.is_... |
"""
# Utilities for interacting with NCBI EUtilities relating to PubMed
"""
__version__ = "0.0.1"
| """
# Utilities for interacting with NCBI EUtilities relating to PubMed
"""
__version__ = '0.0.1' |
x = int(input('Podaj pierwsza liczbe calkowita: '))
y = int(input('Podaj druga liczbe calkowita: '))
z = int(input('Podaj trzecia liczbe calkowita: '))
print()
if x > 10:
print(x)
if y > 10:
print(y)
if z > 10:
print(z) | x = int(input('Podaj pierwsza liczbe calkowita: '))
y = int(input('Podaj druga liczbe calkowita: '))
z = int(input('Podaj trzecia liczbe calkowita: '))
print()
if x > 10:
print(x)
if y > 10:
print(y)
if z > 10:
print(z) |
while True:
try:
dados = []
matriz = []
n = int(input())
for linha in range(0, n):
for coluna in range(0, n):
dados.append(0)
matriz.append(dados[:])
dados.clear()
# Numeros na diagonal
for diagonal_principal in rang... | while True:
try:
dados = []
matriz = []
n = int(input())
for linha in range(0, n):
for coluna in range(0, n):
dados.append(0)
matriz.append(dados[:])
dados.clear()
for diagonal_principal in range(0, n):
matriz[di... |
# query_strings.py
'''
Since Sqlite queries are inserted as string in Python code,
the queries can be stored here to save space in the modules
where they are used.
'''
delete_color_scheme = '''
DELETE FROM color_scheme
WHERE color_scheme_id = ?
'''
insert_color_scheme = '''
INSERT INT... | """
Since Sqlite queries are inserted as string in Python code,
the queries can be stored here to save space in the modules
where they are used.
"""
delete_color_scheme = '\n DELETE FROM color_scheme \n WHERE color_scheme_id = ?\n'
insert_color_scheme = '\n INSERT INTO color_scheme \n VALUES (null, ?, ?,... |
"""
HackerRank :: Reverse a singly-linked list
https://www.hackerrank.com/challenges/reverse-a-linked-list/problem
Complete the reverse function below.
For your reference:
SinglyLinkedListNode:
int data
SinglyLinkedListNode next
"""
def reverse(head):
# head node value can be null
# Keep track of p... | """
HackerRank :: Reverse a singly-linked list
https://www.hackerrank.com/challenges/reverse-a-linked-list/problem
Complete the reverse function below.
For your reference:
SinglyLinkedListNode:
int data
SinglyLinkedListNode next
"""
def reverse(head):
prev_node = None
cur_node = head
while cur_n... |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
'target_name': 'gfx',
'type': '<(component)',
'dependencies': [
... | {'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'gfx', 'type': '<(component)', 'dependencies': ['<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n', '<(DEPTH)/base/base.gyp:base_static', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '<(DEPTH)/... |
"""
113 / 113 test cases passed.
Runtime: 92 ms
Memory Usage: 16.4 MB
"""
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m, n = len(heights), len(heights[0])
def dfs(used, x, y):
used[x][y] = True
for xx, yy in [(x + 1, y), (x - 1, y),... | """
113 / 113 test cases passed.
Runtime: 92 ms
Memory Usage: 16.4 MB
"""
class Solution:
def pacific_atlantic(self, heights: List[List[int]]) -> List[List[int]]:
(m, n) = (len(heights), len(heights[0]))
def dfs(used, x, y):
used[x][y] = True
for (xx, yy) in [(x + 1, y), (... |
__all__ = (
'LIST',
'GET',
'CREATE',
'UPDATE',
'REPLACE',
'DELETE',
'ALL',
'get_http_methods'
)
LIST = 'list'
GET = 'get'
CREATE = 'create'
REPLACE = 'replace'
UPDATE = 'update'
DELETE = 'delete'
ALL = (LIST, GET, CREATE, UPDATE, REPLACE, DELETE)
_http_methods = {
LIST: ('get',),
GET: ('get',),
CREATE: (... | __all__ = ('LIST', 'GET', 'CREATE', 'UPDATE', 'REPLACE', 'DELETE', 'ALL', 'get_http_methods')
list = 'list'
get = 'get'
create = 'create'
replace = 'replace'
update = 'update'
delete = 'delete'
all = (LIST, GET, CREATE, UPDATE, REPLACE, DELETE)
_http_methods = {LIST: ('get',), GET: ('get',), CREATE: ('post',), REPLACE:... |
# -*- coding: utf-8 -*-
"""
Created on 2017/11/18
@author: MG
"""
| """
Created on 2017/11/18
@author: MG
""" |
"""
Rackspace Cloud Backup API
Test Suite
"""
| """
Rackspace Cloud Backup API
Test Suite
""" |
#!/usr/bin/env python3
if __name__ == '__main__':
# Python can represent integers. Here are a couple of ways to create an integer variable. Notice the truncation,
# rather than rounding, in the assignment of d.
a = 5
b = int()
c = int(4)
d = int(3.84)
print(a, b, c, d)
# Integers ha... | if __name__ == '__main__':
a = 5
b = int()
c = int(4)
d = int(3.84)
print(a, b, c, d)
print('\ndivision')
a = 10
b = 10 / 5
print(b, type(b))
print('\nInteger division')
a = 10
b = 10 // 5
print(b, type(b))
a = 10
b = 10 // 3
print(b, type(b))
n = 10
... |
def test():
obj = { 'xxx1': 1, 'xxx2': 2, 'xxx3': 4, 'xxx4': 4, 'foo': 123 }
i = 0
while i < 1e7:
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
ob... | def test():
obj = {'xxx1': 1, 'xxx2': 2, 'xxx3': 4, 'xxx4': 4, 'foo': 123}
i = 0
while i < 10000000.0:
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
obj['foo'] = 234
... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
"""
__author__ = 'joscha'
__date__ = '03.08.12'
| """
"""
__author__ = 'joscha'
__date__ = '03.08.12' |
counter_name = 'I0_PIN'
Size = wx.Size(1007, 726)
logfile = '/net/helix/data/anfinrud_1502/Logfiles/I0_PIN-2.log'
average_count = 1
max_value = 11
min_value = 0
start_fraction = 0.401
reject_outliers = False
outlier_cutoff = 2.5
show_statistics = True
time_window = 172800
| counter_name = 'I0_PIN'
size = wx.Size(1007, 726)
logfile = '/net/helix/data/anfinrud_1502/Logfiles/I0_PIN-2.log'
average_count = 1
max_value = 11
min_value = 0
start_fraction = 0.401
reject_outliers = False
outlier_cutoff = 2.5
show_statistics = True
time_window = 172800 |
print("I will now count my chickens:")
print ("Hens",25+30/6)
print ("Roosters",100-25*3%4)
print("How I will count the eggs:")
print(3+2+1-5+4%2-1/4+6)
print("Is it true that 3+2<5-7?")
print(3+2<5-7)
print("What is 3+2?", 3+2)
print("What is 5-7?", 5-7)
print("Oh,that's why it's false")
print("How about some... | print('I will now count my chickens:')
print('Hens', 25 + 30 / 6)
print('Roosters', 100 - 25 * 3 % 4)
print('How I will count the eggs:')
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print('Is it true that 3+2<5-7?')
print(3 + 2 < 5 - 7)
print('What is 3+2?', 3 + 2)
print('What is 5-7?', 5 - 7)
print("Oh,that's why it's fa... |
#! /usr/bin/env python
"""
Learning Series: Network Programmability Basics
Module: Programming Fundamentals
Lesson: Python Part 2
Author: Hank Preston <hapresto@cisco.com>
common_vars.py
Illustrate the following concepts:
- Code reuse
imported into other examples
"""
shapes = ["square", "triangle", "circle"]
books =... | """
Learning Series: Network Programmability Basics
Module: Programming Fundamentals
Lesson: Python Part 2
Author: Hank Preston <hapresto@cisco.com>
common_vars.py
Illustrate the following concepts:
- Code reuse
imported into other examples
"""
shapes = ['square', 'triangle', 'circle']
books = [{'title': 'War and Pea... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 18:48:24 2020
@author: Christopher Cheng
"""
class Stack(object):
def __init__ (self):
self.stack = []
def get_stack_elements(self):
return self.stack.copy()
def add_one(self, item):
self.stack.append(item)
def add_many(self,ite... | """
Created on Wed May 27 18:48:24 2020
@author: Christopher Cheng
"""
class Stack(object):
def __init__(self):
self.stack = []
def get_stack_elements(self):
return self.stack.copy()
def add_one(self, item):
self.stack.append(item)
def add_many(self, item, n):
for i... |
def wordPower(word):
num = dict(zip(string.ascii_lowercase, range(1,27)))
return sum([num[ch] for ch in word])
| def word_power(word):
num = dict(zip(string.ascii_lowercase, range(1, 27)))
return sum([num[ch] for ch in word]) |
"""
Profile ../profile-datasets-py/div83/027.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/027.py"
self["Q"] = numpy.array([ 1.51831800e+00, 2.02599600e+00, 2.94787100e+00,
3.99669400e+00, 4.71653800e+00, 4.89106600e+00,
5.1439... | """
Profile ../profile-datasets-py/div83/027.py
file automaticaly created by prof_gen.py script
"""
self['ID'] = '../profile-datasets-py/div83/027.py'
self['Q'] = numpy.array([1.518318, 2.025996, 2.947871, 3.996694, 4.716538, 4.891066, 5.143994, 5.672748, 6.023384, 6.098363, 6.083763, 6.011264, 5.918665, 5.... |
s = input().strip()
res = [c for c in set(s.lower()) if c.isalpha()]
if len(res) == 26:
print("pangram")
else:
print("not pangram")
| s = input().strip()
res = [c for c in set(s.lower()) if c.isalpha()]
if len(res) == 26:
print('pangram')
else:
print('not pangram') |
class DataStream:
async def create_private_listen_key(self) -> dict:
"""**Create a ListenKey (USER_STREAM)**
Notes:
``POST /fapi/v1/listenKey``
See Also:
https://binance-docs.github.io/apidocs/futures/en/#start-user-data-stream-user_stream
"""
retu... | class Datastream:
async def create_private_listen_key(self) -> dict:
"""**Create a ListenKey (USER_STREAM)**
Notes:
``POST /fapi/v1/listenKey``
See Also:
https://binance-docs.github.io/apidocs/futures/en/#start-user-data-stream-user_stream
"""
retur... |
x = input("Enter sentence: ")
count={"Uppercase":0, "Lowercase":0}
for i in x:
if i.isupper():
count["Uppercase"]+=1
elif i.islower():
count["Lowercase"]+=1
else:
pass
print ("There is:", count["Uppercase"], "uppercases.")
print ("There is:", count["Lowercase"], "lowercases.")
| x = input('Enter sentence: ')
count = {'Uppercase': 0, 'Lowercase': 0}
for i in x:
if i.isupper():
count['Uppercase'] += 1
elif i.islower():
count['Lowercase'] += 1
else:
pass
print('There is:', count['Uppercase'], 'uppercases.')
print('There is:', count['Lowercase'], 'lowercases.') |
input = """
f(X,1) :- a(X,Y),
g(A,X),g(B,X),
not f(1,X).
a(X,Y) :- g(X,0),g(Y,0).
g(x1,0).
g(x2,0).
"""
output = """
f(X,1) :- a(X,Y),
g(A,X),g(B,X),
not f(1,X).
a(X,Y) :- g(X,0),g(Y,0).
g(x1,0).
g(x2,0).
"""
| input = '\nf(X,1) :- a(X,Y),\n g(A,X),g(B,X),\n not f(1,X).\n\na(X,Y) :- g(X,0),g(Y,0).\n\ng(x1,0).\ng(x2,0).\n\n'
output = '\nf(X,1) :- a(X,Y),\n g(A,X),g(B,X),\n not f(1,X).\n\na(X,Y) :- g(X,0),g(Y,0).\n\ng(x1,0).\ng(x2,0).\n\n' |
file = open("13")
sum = 0
for numbers in file:
#print(numbers.rstrip())
numbers = int(numbers)
sum += numbers;
print(sum)
sum = str(sum)
print(sum[:10])
| file = open('13')
sum = 0
for numbers in file:
numbers = int(numbers)
sum += numbers
print(sum)
sum = str(sum)
print(sum[:10]) |
variable1 = "variable original"
def variable_global():
global variable1
variable1 = "variable global modificada"
print(variable1)
#variable original
variable_global()
print(variable1)
#variable global modificada
| variable1 = 'variable original'
def variable_global():
global variable1
variable1 = 'variable global modificada'
print(variable1)
variable_global()
print(variable1) |
TIMEOUT=100
def GenerateWriteCommand(i2cAddress, ID, writeLocation, data):
i = 0
TIMEOUT = 100
command = bytearray(len(data)+15)
while (i < 4):
command[i] = 255
i += 1
command[4] = i2cAddress
command[5] = TIMEOUT
command[6] = ID
command[7] = 2
command[... | timeout = 100
def generate_write_command(i2cAddress, ID, writeLocation, data):
i = 0
timeout = 100
command = bytearray(len(data) + 15)
while i < 4:
command[i] = 255
i += 1
command[4] = i2cAddress
command[5] = TIMEOUT
command[6] = ID
command[7] = 2
command[8] = writeL... |
class AveragingBucketUpkeep:
def __init__(self):
self.numer = 0.0
self.denom = 0
def add_cost(self, cost):
self.numer += cost
self.denom += 1
return self.numer / self.denom
def rem_cost(self, cost):
self.numer -= cost
self.denom -= 1
if self.... | class Averagingbucketupkeep:
def __init__(self):
self.numer = 0.0
self.denom = 0
def add_cost(self, cost):
self.numer += cost
self.denom += 1
return self.numer / self.denom
def rem_cost(self, cost):
self.numer -= cost
self.denom -= 1
if self... |
__version__ = "2.18"
def version():
"""Returns the version number of the installed workflows package."""
return __version__
class Error(Exception):
"""Common class for exceptions deliberately raised by workflows package."""
class Disconnected(Error):
"""Indicates the connection could not be establ... | __version__ = '2.18'
def version():
"""Returns the version number of the installed workflows package."""
return __version__
class Error(Exception):
"""Common class for exceptions deliberately raised by workflows package."""
class Disconnected(Error):
"""Indicates the connection could not be establish... |
sqlqueries = {
'WeatherForecast':"select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr, to_char(f.forecasted_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day, f.zipcode zip, min(f.temp_avg) low, max(f.temp_avg) high, max(f.wind_speed) wind, max(f.humid... | sqlqueries = {'WeatherForecast': "select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr, to_char(f.forecasted_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day, f.zipcode zip, min(f.temp_avg) low, max(f.temp_avg) high, max(f.wind_speed) wind, max(f.humidity)... |
mock_dbcli_config = {
'exports_from': {
'lpass': {
'pull_lastpass_from': "{{ lastpass_entry }}",
},
'lpass_user_and_pass_only': {
'pull_lastpass_username_password_from': "{{ lastpass_entry }}",
},
'my-json-script': {
'json_script': [
... | mock_dbcli_config = {'exports_from': {'lpass': {'pull_lastpass_from': '{{ lastpass_entry }}'}, 'lpass_user_and_pass_only': {'pull_lastpass_username_password_from': '{{ lastpass_entry }}'}, 'my-json-script': {'json_script': ['some-custom-json-script']}, 'invalid-method': {}}, 'dbs': {'baz': {'exports_from': 'my-json-scr... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def minDistance(self, height, width, tree, squirrel, nuts):
"""
:type height: int
:type width: int
:type tree: List[int]
:type squirrel: List[int]
:type nuts: List[List[int]]
:rtype: int
"""
... | class Solution(object):
def min_distance(self, height, width, tree, squirrel, nuts):
"""
:type height: int
:type width: int
:type tree: List[int]
:type squirrel: List[int]
:type nuts: List[List[int]]
:rtype: int
"""
def distance(a, b):
... |
# Copyright 2000-2004 Michael Hudson mwh@python.net
#
# All Rights Reserved
#
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose is hereby granted without fee,
# provided that the above copyright notice appear in all copies and
# that both ... | class Event:
"""An Event. `evt' is 'key' or somesuch."""
def __init__(self, evt, data, raw=''):
self.evt = evt
self.data = data
self.raw = raw
def __repr__(self):
return 'Event(%r, %r)' % (self.evt, self.data)
class Console:
"""Attributes:
screen,
height,
... |
with open('./8/input_a.txt', 'r') as f:
input = [[a.strip().split(' | ')[0].split(' '), a.strip().split(' | ')[1].split(' ')] for a in f]
num = sum([sum([1 if len(a) in {2,3,4,7} else 0 for a in o[1]]) for o in input ])
print(f'Part A: Number of 1,4,7 or 8s in output - {num}')
def getoutput(i):
nums = ['0','1... | with open('./8/input_a.txt', 'r') as f:
input = [[a.strip().split(' | ')[0].split(' '), a.strip().split(' | ')[1].split(' ')] for a in f]
num = sum([sum([1 if len(a) in {2, 3, 4, 7} else 0 for a in o[1]]) for o in input])
print(f'Part A: Number of 1,4,7 or 8s in output - {num}')
def getoutput(i):
nums = ['0', ... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def sumLinkedListNodes(list1, list2):
value1, value2 = "", ""
head1, head2 = list1, list2
while head1:
value1 += str(head1.data)
head1 = head1.next
while head2:
value2 += str(head2.dat... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def sum_linked_list_nodes(list1, list2):
(value1, value2) = ('', '')
(head1, head2) = (list1, list2)
while head1:
value1 += str(head1.data)
head1 = head1.next
while head2:
value2 += str(... |
class Stack:
def __init__(self):
self.array = []
self.top = -1
self.max = 100
def isEmpty(self):
if(self.top == -1):
return True
else:
return False
def isFull(self):
if(self.top == self.max -1):
return True
else:
... | class Stack:
def __init__(self):
self.array = []
self.top = -1
self.max = 100
def is_empty(self):
if self.top == -1:
return True
else:
return False
def is_full(self):
if self.top == self.max - 1:
return True
else:... |
#----------------------------------------------------------------------
# Basis Set Exchange
# Version v0.8.13
# https://www.basissetexchange.org
#----------------------------------------------------------------------
# Basis set: STO-3G
# Description: STO-3G Minimal Basis (3 functions/AO)
# Role: orbital
# ... | a_list = [3.425250914, 0.6239137298, 0.168855404]
d_list = [0.1543289673, 0.5353281423, 0.4446345422] |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "001887f2",
"metadata": {},
"outputs": [],
"source": [
"# import os modules to create path across operating system to load csv file\n",
"import os\n",
"# module for reading csv files\n",
"import csv"
]
},
{
... | {'cells': [{'cell_type': 'code', 'execution_count': null, 'id': '001887f2', 'metadata': {}, 'outputs': [], 'source': ['# import os modules to create path across operating system to load csv file\n', 'import os\n', '# module for reading csv files\n', 'import csv']}, {'cell_type': 'code', 'execution_count': null, 'id': '... |
class Solution:
"""
@param A : an integer array
@return : a integer
"""
def singleNumber(self, A):
# write your code here
return reduce(lambda x, y: x ^ y, A) if A != [] else 0
| class Solution:
"""
@param A : an integer array
@return : a integer
"""
def single_number(self, A):
return reduce(lambda x, y: x ^ y, A) if A != [] else 0 |
# Copyright 2018 Luddite Labs 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 applicable law or agreed to in writing... | """
Block Quotes
------------
Line blocks are groups of lines beginning with vertical bar ("|") prefixes.
Each vertical bar prefix indicates a new line, so line breaks are preserved.
Initial indents are also significant, resulting in a nested structure.
Inline markup is supported. Continuation lines are wrapped portio... |
# https://www.beecrowd.com.br/judge/en/problems/view/1017
car_efficiency = 12 # Km/L
time = int(input())
average_speed = int(input())
liters = (time * average_speed) / car_efficiency
print(f"{liters:.3f}") | car_efficiency = 12
time = int(input())
average_speed = int(input())
liters = time * average_speed / car_efficiency
print(f'{liters:.3f}') |
preference_list_of_user=[]
def give(def_list):
Def=def_list
global preference_list_of_user
preference_list_of_user=Def
return Def
def give_to_model():
return preference_list_of_user | preference_list_of_user = []
def give(def_list):
def = def_list
global preference_list_of_user
preference_list_of_user = Def
return Def
def give_to_model():
return preference_list_of_user |
def is_leap(year):
leap = False
# Write your logic here
# The year can be evenly divided by 4, is a leap year, unless:
# The year can be evenly divided by 100, it is NOT a leap year, unless:
# The year is also evenly divisible by 400. Then it is a leap year.
leap = (year % 4 == 0 and (year ... | def is_leap(year):
leap = False
leap = year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)
return leap
year = int(input())
print(is_leap(year)) |
# Set random number generator
np.random.seed(2020)
# Initialize step_end, n, t_range, v and i
step_end = int(t_max / dt)
n = 50
t_range = np.linspace(0, t_max, num=step_end)
v_n = el * np.ones([n, step_end])
i = i_mean * (1 + 0.1 * (t_max / dt)**(0.5) * (2 * np.random.random([n, step_end]) - 1))
# Loop for step_end ... | np.random.seed(2020)
step_end = int(t_max / dt)
n = 50
t_range = np.linspace(0, t_max, num=step_end)
v_n = el * np.ones([n, step_end])
i = i_mean * (1 + 0.1 * (t_max / dt) ** 0.5 * (2 * np.random.random([n, step_end]) - 1))
for step in range(1, step_end):
v_n[:, step] = v_n[:, step - 1] + dt / tau * (el - v_n[:, st... |
# ------------------------------
# 78. Subsets
#
# Description:
# Given a set of distinct integers, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
#
# For example,
# If nums = [1,2,3], a solution is:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3]... | class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return [[]]
result = []
for i in range(len(nums) + 1):
result += self.combine(nums, i)
return result
def c... |
class CompressedFastq( CompressedArchive ):
"""
Class describing an compressed fastq file
This class can be sublass'ed to implement archive filetypes that will not be unpacked by upload.py.
"""
file_ext = "fq.gz"
def set_peek( self, dataset, is_multi_byte=False ):
if not dataset... | class Compressedfastq(CompressedArchive):
"""
Class describing an compressed fastq file
This class can be sublass'ed to implement archive filetypes that will not be unpacked by upload.py.
"""
file_ext = 'fq.gz'
def set_peek(self, dataset, is_multi_byte=False):
if not dataset.dat... |
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | """Module containing the InsertableString class."""
class Insertablestring(object):
"""Class that accumulates insert and replace operations for a string and
later performs them all at once so that positions in the original string
can be used in all of the operations.
"""
def __init__(self, input_s... |
class PaginatorOptions:
def __init__(
self,
page_number: int,
page_size: int,
sort_column: str = None,
sort_descending: bool = None
):
self.sort_column = sort_column
self.sort_descending = sort_descending
self.page_number = page_number
self... | class Paginatoroptions:
def __init__(self, page_number: int, page_size: int, sort_column: str=None, sort_descending: bool=None):
self.sort_column = sort_column
self.sort_descending = sort_descending
self.page_number = page_number
self.page_size = page_size
assert page_number... |
property_setter = {
"dt": "Property Setter",
"filters": [
["name", "in", [
'Purchase Order-read_only_onload',
'Purchase Order-default_print_format',
'Purchase Invoice-naming_series-options',
'Purchase Invoice-naming_series-default',
'Delivery Note-naming_series-options',
'Delivery Note-naming_seri... | property_setter = {'dt': 'Property Setter', 'filters': [['name', 'in', ['Purchase Order-read_only_onload', 'Purchase Order-default_print_format', 'Purchase Invoice-naming_series-options', 'Purchase Invoice-naming_series-default', 'Delivery Note-naming_series-options', 'Delivery Note-naming_series-default', 'Sales Order... |
""" First class definition"""
class Cat:
pass
class RaceCar:
pass
cat1 = Cat()
cat2 = Cat()
cat3 = Cat() | """ First class definition"""
class Cat:
pass
class Racecar:
pass
cat1 = cat()
cat2 = cat()
cat3 = cat() |
# We can transition on native options using this
# //command_line_option:<option-name> syntax
_BUILD_SETTING = "//command_line_option:test_arg"
def _test_arg_transition_impl(settings, attr):
_ignore = (settings, attr)
return {_BUILD_SETTING: ["new arg"]}
_test_arg_transition = transition(
implementation ... | _build_setting = '//command_line_option:test_arg'
def _test_arg_transition_impl(settings, attr):
_ignore = (settings, attr)
return {_BUILD_SETTING: ['new arg']}
_test_arg_transition = transition(implementation=_test_arg_transition_impl, inputs=[], outputs=[_BUILD_SETTING])
def _test_transition_rule_impl(ctx):... |
balance = 700
papers=[100, 50, 10, 5,4,3,2,1]
def withdraw(balance, request):
if balance < request :
print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance))
else:
print ('your balance >>', balance)
orgnal_request = request
while request > ... | balance = 700
papers = [100, 50, 10, 5, 4, 3, 2, 1]
def withdraw(balance, request):
if balance < request:
print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance))
else:
print('your balance >>', balance)
orgnal_request = request
while reques... |
"""Top-level package for Feature Flag Server SDK."""
__author__ = """Enver Bisevac"""
__email__ = "enver@bisevac.com"
__version__ = "0.1.0"
| """Top-level package for Feature Flag Server SDK."""
__author__ = 'Enver Bisevac'
__email__ = 'enver@bisevac.com'
__version__ = '0.1.0' |
arr_1 = ["1","2","3","4","5","6","7"]
arr_2 = []
for n in arr_1:
arr_2.insert(0,n)
print(arr_2)
| arr_1 = ['1', '2', '3', '4', '5', '6', '7']
arr_2 = []
for n in arr_1:
arr_2.insert(0, n)
print(arr_2) |
"""Top-level package for z2z Metadata analysis."""
__author__ = """Isthmus // Mitchell P. Krawiec-Thayer"""
__email__ = 'project_z2z_metadata@mitchellpkt.com'
__version__ = '0.0.1'
| """Top-level package for z2z Metadata analysis."""
__author__ = 'Isthmus // Mitchell P. Krawiec-Thayer'
__email__ = 'project_z2z_metadata@mitchellpkt.com'
__version__ = '0.0.1' |
class Player(object):
"""Player class
Attributes:
name (str): Player name
"""
def __init__(self, name):
"""Initialize player
Args:
name (str): Player name
"""
self.name = name
def place_troops(self, board, n_troops):
"""Plac... | class Player(object):
"""Player class
Attributes:
name (str): Player name
"""
def __init__(self, name):
"""Initialize player
Args:
name (str): Player name
"""
self.name = name
def place_troops(self, board, n_troops):
"""Plac... |
n=int(input("Nhap vao mot so:"))
d=dict()
for i in range(1, n+1):
d[i]=i*i
print(d) | n = int(input('Nhap vao mot so:'))
d = dict()
for i in range(1, n + 1):
d[i] = i * i
print(d) |
#!/usr/bin/env python
# Copyright 2008-2010 Isaac Gouy
# Copyright (c) 2013, 2014, Regents of the University of California
# Copyright (c) 2017, 2018, Oracle and/or its affiliates.
# All rights reserved.
#
# Revised BSD license
#
# This is a specific instance of the Open Source Initiative (OSI) BSD license
# template h... | coins = [1, 2, 5, 10, 20, 50, 100, 200]
def _sum(iterable):
sum = None
for i in iterable:
if sum is None:
sum = i
else:
sum += i
return sum
def balance(pattern):
return _sum((COINS[x] * pattern[x] for x in range(0, len(pattern))))
def gen(pattern, coinnum, num)... |
# Problem: Student Attendance Record I
# Difficulty: Easy
# Category: String
# Leetcode 551: https://leetcode.com/problems/student-attendance-record-i/#/description
# Description:
"""
You are given a string representing an attendance record for a student.
The record only contains the following three characters:
'A' : ... | """
You are given a string representing an attendance record for a student.
The record only contains the following three characters:
'A' : Absent.
'L' : Late.
'P' : Present.
A student could be rewarded if his attendance record doesn't contain
more than one 'A' (absent) or more than two continuous 'L' (late).
You need t... |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: missingdata.py
#
# Tests: missing data
#
# Programmer: Brad Whitlock
# Date: Thu Jan 19 09:49:15 PST 2012
#
# Modifications:
#
# ------------------------------------------------------------... | def set_the_view():
v = get_view2_d()
v.viewportCoords = (0.02, 0.98, 0.25, 1)
set_view2_d(v)
def test0(datapath):
test_section('Missing data')
open_database(pjoin(datapath, 'earth.nc'))
add_plot('Pseudocolor', 'height')
draw_plots()
set_the_view()
test('missingdata_0_00')
chang... |
class SerialNumber:
def __init__(self, serialNumber):
if not (len(serialNumber) == 6):
raise ValueError('Serial Number must be 6 digits long')
self._serialNumber = serialNumber
def __str__(self):
return 'S/N: {}'.format(self._serialNumber)
def __repr__(self):
... | class Serialnumber:
def __init__(self, serialNumber):
if not len(serialNumber) == 6:
raise value_error('Serial Number must be 6 digits long')
self._serialNumber = serialNumber
def __str__(self):
return 'S/N: {}'.format(self._serialNumber)
def __repr__(self):
re... |
#
# BitBake Graphical GTK User Interface
#
# Copyright (C) 2012 Intel Corporation
#
# Authored by Shane Wang <shane.wang@intel.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundat... | class Hobcolors:
white = '#ffffff'
pale_green = '#aaffaa'
orange = '#eb8e68'
pale_red = '#ffaaaa'
gray = '#aaaaaa'
light_gray = '#dddddd'
slight_dark = '#5f5f5f'
dark = '#3c3b37'
black = '#000000'
pale_blue = '#53b8ff'
deep_red = '#aa3e3e'
khaki = '#fff68f'
ok = WHITE... |
'''input
4 8 3
4
5
6
7
8
3 8 2
3
4
7
8
2 9 100
2
3
4
5
6
7
8
9
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem B
if __name__ == '__main__':
a, b, k = list(map(int, input().split()))
if (b - a + 1) <= 2 * k:
for i in range(a, b + 1):
... | """input
4 8 3
4
5
6
7
8
3 8 2
3
4
7
8
2 9 100
2
3
4
5
6
7
8
9
"""
if __name__ == '__main__':
(a, b, k) = list(map(int, input().split()))
if b - a + 1 <= 2 * k:
for i in range(a, b + 1):
print(i)
else:
for j in range(a, a + k):
print(j)
for j in range(b - ... |
class Authenticator(object):
def authenticate(self, credentials):
raise NotImplementedError()
| class Authenticator(object):
def authenticate(self, credentials):
raise not_implemented_error() |
class Node():
def __init__(self, id: int, value = None, right: 'Node' = None, left: 'Node' = None):
self.id = id
self.value = value
self.right = right
self.left = left
self.parent: 'Node' = None
def add(self, node: 'Node'):
if not node:
raise ValueE... | class Node:
def __init__(self, id: int, value=None, right: 'Node'=None, left: 'Node'=None):
self.id = id
self.value = value
self.right = right
self.left = left
self.parent: 'Node' = None
def add(self, node: 'Node'):
if not node:
raise value_error('no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.