content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class RobotError(Error):
"""Exception raised for robot detection (solvable).
Attributes:
message -- explanation of the error
"""
def __init__(self):
self.message = "Robot Check Detected."
class AQErr... | class Error(Exception):
"""Base class for exceptions in this module."""
pass
class Roboterror(Error):
"""Exception raised for robot detection (solvable).
Attributes:
message -- explanation of the error
"""
def __init__(self):
self.message = 'Robot Check Detected.'
class Aqerr... |
lilly_dict = {"name": "Lilly",
"age": 18,
"pets": False,
"hair_color": 'Black'}
class Person(object):
def __init__(self, name, age, pets, hair_color):
self.name = name
self.age = age
self.pets = pets
self.hair_color = hair_color
self.hungry = True
... | lilly_dict = {'name': 'Lilly', 'age': 18, 'pets': False, 'hair_color': 'Black'}
class Person(object):
def __init__(self, name, age, pets, hair_color):
self.name = name
self.age = age
self.pets = pets
self.hair_color = hair_color
self.hungry = True
def eat(self, food):
... |
"""
Exercise 13 - Inventory Management
"""
def create_inventory (items):
"""
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""
return add_items ({}, items)
def add_items (inventory, items):
"""
:param inventory: dict - dictio... | """
Exercise 13 - Inventory Management
"""
def create_inventory(items):
"""
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""
return add_items({}, items)
def add_items(inventory, items):
"""
:param inventory: dict - dictionary ... |
startMsg = 'counting...'
endMsg = 'launched !'
count = 10
print (startMsg)
while count >= 0 :
print (count)
count -= 1
print (endMsg) | start_msg = 'counting...'
end_msg = 'launched !'
count = 10
print(startMsg)
while count >= 0:
print(count)
count -= 1
print(endMsg) |
def multiple_letter_count(string):
return {letter: string.count(letter) for letter in string}
print(multiple_letter_count('awesome'))
| def multiple_letter_count(string):
return {letter: string.count(letter) for letter in string}
print(multiple_letter_count('awesome')) |
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print("The animal at 1. ", animals[1])
print("The third (3rd) animal. ", animals[3-1])#This is the n - 1 trick
print("The first (1st) animal. ", animals[0])
print("The animal at 3. ", animals[3])
print("The fifth (5th) animal. ", animals[4])
print... | animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print('The animal at 1. ', animals[1])
print('The third (3rd) animal. ', animals[3 - 1])
print('The first (1st) animal. ', animals[0])
print('The animal at 3. ', animals[3])
print('The fifth (5th) animal. ', animals[4])
print('The animal at 2. ', ... |
__author__ = "Douglas Lassance"
__copyright__ = "2020, Douglas Lassance"
__email__ = "douglassance@gmail.com"
__license__ = "MIT"
__version__ = "0.1.0.dev5"
| __author__ = 'Douglas Lassance'
__copyright__ = '2020, Douglas Lassance'
__email__ = 'douglassance@gmail.com'
__license__ = 'MIT'
__version__ = '0.1.0.dev5' |
# Copyright (c) 2019 The DAML Authors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load("//bazel_tools:pkg.bzl", "pkg_tar")
# taken from rules_proto:
# https://github.com/stackb/rules_proto/blob/f5d6eea6a4528bef3c1d3a44d486b51a214d61c2/compile.bzl#L369-L393
def get_plugin_runfiles(tool, plugin_runfiles... | load('//bazel_tools:pkg.bzl', 'pkg_tar')
def get_plugin_runfiles(tool, plugin_runfiles):
"""Gather runfiles for a plugin.
"""
files = []
if not tool:
return files
info = tool[DefaultInfo]
if not info:
return files
if info.files:
files += info.files.to_list()
if i... |
'''
Unit Test Cases for JSON2HTML
Description - python wrapper for converting JSON to HTML Table format
(c) 2013 Varun Malhotra. MIT License
'''
__author__ = 'Varun Malhotra'
__version__ = '1.1.1'
__license__ = 'MIT'
| """
Unit Test Cases for JSON2HTML
Description - python wrapper for converting JSON to HTML Table format
(c) 2013 Varun Malhotra. MIT License
"""
__author__ = 'Varun Malhotra'
__version__ = '1.1.1'
__license__ = 'MIT' |
# bubble_sort
# Bubble_sort uses the technique of comparing and swapping
def bubble_sort(lst):
for passnum in range(len(lst) - 1, 0, -1):
for i in range(passnum):
if lst[i] > lst[i + 1]:
temp = lst[i]
lst[i] = lst[i + 1]
lst[i + 1] = temp
lst = ... | def bubble_sort(lst):
for passnum in range(len(lst) - 1, 0, -1):
for i in range(passnum):
if lst[i] > lst[i + 1]:
temp = lst[i]
lst[i] = lst[i + 1]
lst[i + 1] = temp
lst = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubble_sort(lst)
print('sorted %s' % ls... |
def tip(total, percentage):
tip = (total * percentage) / 100
return tip
print(tip(24, 13))
| def tip(total, percentage):
tip = total * percentage / 100
return tip
print(tip(24, 13)) |
""""""
"""
# Floyd's Tortoise and Hare
[Reference : wiki](https://en.wikipedia.org/wiki/Cycle_detection)
## Description
Floyd's cycle-finding algorithm is a pointer algorithm that uses only two pointers, which move through the sequence at
different speeds. It is also called the "tortoise and the hare algorithm"
Che... | """"""
'\n# Floyd\'s Tortoise and Hare\n[Reference : wiki](https://en.wikipedia.org/wiki/Cycle_detection)\n\n## Description \nFloyd\'s cycle-finding algorithm is a pointer algorithm that uses only two pointers, which move through the sequence at \ndifferent speeds. It is also called the "tortoise and the hare algorithm... |
class Solution:
def validPalindrome(self, s: str) -> bool:
return self.isValidPalindrome(s, False)
def isValidPalindrome(self, s: str, did_delete: bool) -> bool:
curr_left = 0
curr_right = len(s) - 1
while curr_left < curr_right:
# If left and right char... | class Solution:
def valid_palindrome(self, s: str) -> bool:
return self.isValidPalindrome(s, False)
def is_valid_palindrome(self, s: str, did_delete: bool) -> bool:
curr_left = 0
curr_right = len(s) - 1
while curr_left < curr_right:
if s[curr_left] == s[curr_right]:... |
# -*- coding: utf-8 -*-
SPELLINGS_MAP={
"accessorise":"accessorize",
"accessorised":"accessorized",
"accessorises":"accessorizes",
"accessorising":"accessorizing",
"acclimatisation":"acclimatization",
"acclimatise":"acclimatize",
"acclimatised":"acclimatized",
"acclimatises":"acclimatizes",
"acclimatising":"acclimatiz... | spellings_map = {'accessorise': 'accessorize', 'accessorised': 'accessorized', 'accessorises': 'accessorizes', 'accessorising': 'accessorizing', 'acclimatisation': 'acclimatization', 'acclimatise': 'acclimatize', 'acclimatised': 'acclimatized', 'acclimatises': 'acclimatizes', 'acclimatising': 'acclimatizing', 'accoutre... |
n = int(input())
while n != -1:
prev_time = 0
total = 0
for _ in range(n):
(speed, time) = map(int, input().split(" "))
total += (time - prev_time) * speed
prev_time = time
print(total, "miles")
n = int(input())
| n = int(input())
while n != -1:
prev_time = 0
total = 0
for _ in range(n):
(speed, time) = map(int, input().split(' '))
total += (time - prev_time) * speed
prev_time = time
print(total, 'miles')
n = int(input()) |
"""
URL: https://codeforces.com/problemset/problem/753/A
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: dp, greedy, math, *1000
"""
n = int(input())
count = 0
a = []
summ = 0
for i in range(1, n + 1):
summ += i
if summ > n:
break
count += 1
a.append(i)
if summ > n:
a[-1] += n - summ +... | """
URL: https://codeforces.com/problemset/problem/753/A
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: dp, greedy, math, *1000
"""
n = int(input())
count = 0
a = []
summ = 0
for i in range(1, n + 1):
summ += i
if summ > n:
break
count += 1
a.append(i)
if summ > n:
a[-1] += n - summ + ... |
"""Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def detect_cycle(h... | """Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
"""
class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
def detect_cycle(he... |
class Node:
_fields = []
def __init__(self, *args):
for key, value in zip(self._fields, args):
setattr(self, key, value)
def __repl__(self):
return self.__str__()
# literals...
class Bool(Node):
_fields = ["value"]
def __str__(self):
string = "Boolean=" + s... | class Node:
_fields = []
def __init__(self, *args):
for (key, value) in zip(self._fields, args):
setattr(self, key, value)
def __repl__(self):
return self.__str__()
class Bool(Node):
_fields = ['value']
def __str__(self):
string = 'Boolean=' + str(self.value)
... |
def enum(**enums):
return type('Enum', (), enums)
control = enum(CHOICE_BOX = 0,
TEXT_BOX = 1,
COMBO_BOX = 2,
INT_CTRL = 3,
FLOAT_CTRL = 4,
DIR_COMBO_BOX = 5,
CHECKLIST_BOX = 6,
LISTBOX_COMBO = 7,
... | def enum(**enums):
return type('Enum', (), enums)
control = enum(CHOICE_BOX=0, TEXT_BOX=1, COMBO_BOX=2, INT_CTRL=3, FLOAT_CTRL=4, DIR_COMBO_BOX=5, CHECKLIST_BOX=6, LISTBOX_COMBO=7, TEXTBOX_COMBO=8, CHECKBOX_GRID=9, GPA_CHECKBOX_GRID=10, SPIN_BOX_FLOAT=11)
dtype = enum(BOOL=0, STR=1, NUM=2, LBOOL=3, LSTR=4, LNUM=5, ... |
"""
Given a binary tree, return the zigzag level order traversal of its nodes'
values. (ie, from left to right, then right to left for the next level and
alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
... | """
Given a binary tree, return the zigzag level order traversal of its nodes'
values. (ie, from left to right, then right to left for the next level and
alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ 9 20
/ 15 7
return its zigzag level order traversal as:
[
[3],
[20,... |
'''
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-09-15 13:53:11
LastEditors: xiaoshuyui
LastEditTime: 2020-09-22 11:20:14
'''
__version__ = '0.0.0'
__appname__ = 'show and search'
| """
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-09-15 13:53:11
LastEditors: xiaoshuyui
LastEditTime: 2020-09-22 11:20:14
"""
__version__ = '0.0.0'
__appname__ = 'show and search' |
def contains_magic_number(list1, magic_number):
for i in list1:
if i == magic_number:
print("This list contains the magic number")
# if not add break , will run more meaningless loop
break
else:
print("This list does NOT contain the magic number")
if... | def contains_magic_number(list1, magic_number):
for i in list1:
if i == magic_number:
print('This list contains the magic number')
break
else:
print('This list does NOT contain the magic number')
if __name__ == '__main__':
contains_magic_number(range(10), 3) |
def dfs_inorder(tree):
if tree is None: return None
out = []
dfs_inorder(tree.left)
out.append(tree.value)
print(tree.value)
dfs_inorder(tree.right)
return out
def dfs_preorder(tree):
if tree is None: return None
out = []
out.append(tree.value)
print(tree.value)
dfs_... | def dfs_inorder(tree):
if tree is None:
return None
out = []
dfs_inorder(tree.left)
out.append(tree.value)
print(tree.value)
dfs_inorder(tree.right)
return out
def dfs_preorder(tree):
if tree is None:
return None
out = []
out.append(tree.value)
print(tree.val... |
def round_down(num, digits: int):
a = float(num)
if digits < 0:
b = 10 ** int(abs(digits))
answer = int(a * b) / b
else:
b = 10 ** int(digits)
answer = int(a / b) * b
assert not(not(-0.01 < num < 0.01) and answer == 0)
return answer
| def round_down(num, digits: int):
a = float(num)
if digits < 0:
b = 10 ** int(abs(digits))
answer = int(a * b) / b
else:
b = 10 ** int(digits)
answer = int(a / b) * b
assert not (not -0.01 < num < 0.01 and answer == 0)
return answer |
INPUT = {
2647: [
list("#....#####"),
list(".##......#"),
list("##......##"),
list(".....#..#."),
list(".........#"),
list(".....#..##"),
list("#.#....#.."),
list("#......#.#"),
list("#....##..#"),
list("...##....."),
],
1283: [... | input = {2647: [list('#....#####'), list('.##......#'), list('##......##'), list('.....#..#.'), list('.........#'), list('.....#..##'), list('#.#....#..'), list('#......#.#'), list('#....##..#'), list('...##.....')], 1283: [list('######..#.'), list('#.#..#.#..'), list('..#..#...#'), list('.#.##..#..'), list('#......#..... |
def solve(s):
if s==s[::-1]:
return 1
else:
return 0
s=str(input())
print(solve(s))
| def solve(s):
if s == s[::-1]:
return 1
else:
return 0
s = str(input())
print(solve(s)) |
"""Effects"""
class FxName:
"""FX name"""
def __init__(self, name):
self.name = name
BITCRUSHER = FxName('bitcrusher')
COMPRESSOR = FxName('compressor')
ECHO = FxName('echo')
FLANGER = FxName('flanger')
KRUSH = FxName('krush')
LPF = FxName('lpf')
PAN = FxName('pan')
PANSLICER = FxName('panslicer')
R... | """Effects"""
class Fxname:
"""FX name"""
def __init__(self, name):
self.name = name
bitcrusher = fx_name('bitcrusher')
compressor = fx_name('compressor')
echo = fx_name('echo')
flanger = fx_name('flanger')
krush = fx_name('krush')
lpf = fx_name('lpf')
pan = fx_name('pan')
panslicer = fx_name('panslic... |
# Copyright (c) 2017-2017 Cisco Systems, 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
#
# Unl... | path_get_nexus_type = 'api/mo/sys/ch.json'
path_vlan_all = 'api/mo.json'
body_vlan_all_beg = '{"topSystem": { "children": [ {"bdEntity":'
body_vlan_all_beg += ' { children": ['
body_vlan_all_incr = ' {"l2BD": {"attributes": {"fabEncap": "vlan-%s",'
body_vlan_all_incr += ' "pcTag": "1", "adminSt": "active"}}}'
body_vxl... |
message = [ 'e', 'k', 'a', 'c', ' ',
'd', 'n', 'u', 'o', 'p', ' ',
'l', 'a', 'e', 't', 's']
def reversed_words(message):
cur_pos = 0
end_pos = len(message)
current_word_start = cur_pos
while cur_pos < end_pos:
if message[cur_pos] == ' ':
message[current_word... | message = ['e', 'k', 'a', 'c', ' ', 'd', 'n', 'u', 'o', 'p', ' ', 'l', 'a', 'e', 't', 's']
def reversed_words(message):
cur_pos = 0
end_pos = len(message)
current_word_start = cur_pos
while cur_pos < end_pos:
if message[cur_pos] == ' ':
message[current_word_start:cur_pos] = reversed... |
class EquationClass:
def __init__(self):
pass
def calculation(self):
...
def info(self):
...
| class Equationclass:
def __init__(self):
pass
def calculation(self):
...
def info(self):
... |
class BufferFile:
def __init__(self, write):
self.write = write
def readline(self): pass
def writelines(self, l): map(self.append, l)
def flush(self): pass
def isatty(self): return 1
| class Bufferfile:
def __init__(self, write):
self.write = write
def readline(self):
pass
def writelines(self, l):
map(self.append, l)
def flush(self):
pass
def isatty(self):
return 1 |
# Class could be designed to be used in cooperative multiple inheritance
# so `super()` could be resolved to some non-object class that is able to receive passed arguments.
class Shape(object):
def __init__(self, shapename, **kwds):
self.shapename = shapename
# in case of ColoredShape the call below wil... | class Shape(object):
def __init__(self, shapename, **kwds):
self.shapename = shapename
super(Shape, self).__init__(**kwds)
class Colored(object):
def __init__(self, color, **kwds):
self.color = color
super(Colored, self).__init__(**kwds)
class Coloredshape(Shape, Colored):
... |
# Space Walk
# by Sean McManus
# www.sean.co.uk / www.nostarch.com
WIDTH = 800
HEIGHT = 600
player_x = 500
player_y = 550
def draw():
screen.blit(images.backdrop, (0, 0))
| width = 800
height = 600
player_x = 500
player_y = 550
def draw():
screen.blit(images.backdrop, (0, 0)) |
def countPaths(maze, rows, cols):
if (maze[0][0] == -1):
return 0
# Initializing the leftmost column
for i in range(rows):
if (maze[i][0] == 0):
maze[i][0] = 1
# If we encounter a blocked cell in
# leftmost row, there is no way of
# visiting any cell directly below it.
else:
break
# Si... | def count_paths(maze, rows, cols):
if maze[0][0] == -1:
return 0
for i in range(rows):
if maze[i][0] == 0:
maze[i][0] = 1
else:
break
for i in range(1, cols, 1):
if maze[0][i] == 0:
maze[0][i] = 1
else:
break
for i i... |
n,s,t=map(int,input().split())
w=c=0
for i in range(n):
w+=int(input())
c+=s<=w<=t
print(c) | (n, s, t) = map(int, input().split())
w = c = 0
for i in range(n):
w += int(input())
c += s <= w <= t
print(c) |
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
# find the factors of num using modulus operator
num = 600851475143
div = 2
highestFactor = 1
while num > 1:
if(num%div==0):
num = num/div
highestFactor = div
else:
di... | """
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
num = 600851475143
div = 2
highest_factor = 1
while num > 1:
if num % div == 0:
num = num / div
highest_factor = div
else:
div += 1
print(highestFactor) |
# Problem Statement: https://www.hackerrank.com/challenges/map-and-lambda-expression/problem
cube = lambda x: x**3
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i - 1] + fib[i - 2])
return fib[0:n] | cube = lambda x: x ** 3
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i - 1] + fib[i - 2])
return fib[0:n] |
def multiply_by(a, b=2, c=1):
return a * b + c
print(multiply_by(3, 47, 0)) # Call function using custom values for all parameters
print(multiply_by(3, 47)) # Call function using default value for c parameter
print(multiply_by(3, c=47)) # Call function using default value for b parameter
print(multiply_by(3)) ... | def multiply_by(a, b=2, c=1):
return a * b + c
print(multiply_by(3, 47, 0))
print(multiply_by(3, 47))
print(multiply_by(3, c=47))
print(multiply_by(3))
print(multiply_by(a=7))
def hello(subject, name='Max'):
print(f'Hello {subject}! My name is {name}')
hello('PyCharm', 'Jane')
hello('PyCharm') |
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | source('../../shared/qtcreator.py')
def main():
start_application('qtcreator' + SettingsPath)
if not started_without_plugin_error():
return
create_project__qt_gui(temp_dir(), 'DesignerTestApp')
select_from_locator('mainwindow.ui')
widget_index = "{container=':qdesigner_internal::WidgetBoxCa... |
# -*- coding: utf-8 -*-
# @Time : 2018/8/13 16:45
# @Author : Dylan
# @File : config.py
# @Email : wenyili@buaa.edu.cn
class Config():
train_imgs_path = "images/train/images"
train_labels_path = "images/train/label"
merge_path = ""
aug_merge_path = "deform/deform_norm2"
aug_train_path = "de... | class Config:
train_imgs_path = 'images/train/images'
train_labels_path = 'images/train/label'
merge_path = ''
aug_merge_path = 'deform/deform_norm2'
aug_train_path = 'deform/train/'
aug_label_path = 'deform/label/'
test_path = 'images/test'
npy_path = '../npydata'
result_np_save = '... |
tile_colors = {}
for _ in range(400):
path = input()
i = 0
pos_north = 0.0
pos_east = 0.0
while i < len(path):
if path[i] == 'e':
pos_east += 1.0
i += 1
elif path[i] == 'w':
pos_east -= 1.0
i += 1
elif path[i] == 'n' and path... | tile_colors = {}
for _ in range(400):
path = input()
i = 0
pos_north = 0.0
pos_east = 0.0
while i < len(path):
if path[i] == 'e':
pos_east += 1.0
i += 1
elif path[i] == 'w':
pos_east -= 1.0
i += 1
elif path[i] == 'n' and path[i ... |
# Copyright 2018 Inap.
#
# 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, softwa... | class Shellsession(object):
def __init__(self, command_processor):
self.command_processor = command_processor
self.command_processor.write('\n')
self.command_processor.show_prompt()
def receive(self, line):
self.command_processor.logger.debug('received: %s' % line)
try:... |
function_classes = {}
class RegisteringMetaclass(type):
def __new__(*args): # pylint: disable=no-method-argument
cls = type.__new__(*args)
if cls.name:
function_classes[cls.name] = cls
return cls
class Function(metaclass=RegisteringMetaclass):
name = None
min_args =... | function_classes = {}
class Registeringmetaclass(type):
def __new__(*args):
cls = type.__new__(*args)
if cls.name:
function_classes[cls.name] = cls
return cls
class Function(metaclass=RegisteringMetaclass):
name = None
min_args = None
max_args = None
def __ini... |
load("@bazel_skylib//lib:shell.bzl", "shell")
load("//:golink.bzl", "gen_copy_files_script")
def go_proto_link_impl(ctx, **kwargs):
print("Copying generated files for proto library %s" % ctx.attr.dep[OutputGroupInfo])
return gen_copy_files_script(ctx, ctx.attr.dep[OutputGroupInfo].go_generated_srcs.to_list())
... | load('@bazel_skylib//lib:shell.bzl', 'shell')
load('//:golink.bzl', 'gen_copy_files_script')
def go_proto_link_impl(ctx, **kwargs):
print('Copying generated files for proto library %s' % ctx.attr.dep[OutputGroupInfo])
return gen_copy_files_script(ctx, ctx.attr.dep[OutputGroupInfo].go_generated_srcs.to_list())
... |
# -*- coding: utf-8 -*-
"""Responses.
responses serve both testing purpose aswell as dynamic docstring replacement.
"""
responses = {
"_v3_HistoricalPositions": {
"url": "/openapi/hist/v3/positions/{ClientKey}",
"params": {
'FromDate': '2019-03-01',
'ToDate': '2019-03-10'
... | """Responses.
responses serve both testing purpose aswell as dynamic docstring replacement.
"""
responses = {'_v3_HistoricalPositions': {'url': '/openapi/hist/v3/positions/{ClientKey}', 'params': {'FromDate': '2019-03-01', 'ToDate': '2019-03-10'}, 'response': {'Data': [{'AccountId': '112209INET', 'AccountValueEndOfDay... |
#!/usr/bin/env python3
#!/usr/bin/env python
LIMIT = 32
dict1 = {}
def main():
squares()
a1 = 0
while a1 < LIMIT:
sums(a1)
a1 += 1
results()
def squares():
global dict1
for i1 in range(1, LIMIT * 2):
# print "%s" % str(i1)
s1 = i1 * i1
if not s1 in dic... | limit = 32
dict1 = {}
def main():
squares()
a1 = 0
while a1 < LIMIT:
sums(a1)
a1 += 1
results()
def squares():
global dict1
for i1 in range(1, LIMIT * 2):
s1 = i1 * i1
if not s1 in dict1:
dict1[s1] = []
dict1[s1].append(i1)
def results()... |
# -*-coding:utf-8-*-
__author__ = "Allen Woo"
DB_CONFIG = {
"redis": {
"host": [
"127.0.0.1"
],
"password": "<Your password>",
"port": [
"6379"
]
},
"mongodb": {
"web": {
"dbname": "osr_web",
"password": "<Your p... | __author__ = 'Allen Woo'
db_config = {'redis': {'host': ['127.0.0.1'], 'password': '<Your password>', 'port': ['6379']}, 'mongodb': {'web': {'dbname': 'osr_web', 'password': '<Your password>', 'config': {'fsync': False, 'replica_set': None}, 'host': ['127.0.0.1:27017'], 'username': 'root'}, 'user': {'dbname': 'osr_user... |
class NumArray:
def __init__(self):
self.__values = []
def __length_hint__(self):
print('__length_hint__', len(self.__values))
return len(self.__values)
n = NumArray()
print(len(n)) # TypeError: object of type 'NumArray' has no len()
| class Numarray:
def __init__(self):
self.__values = []
def __length_hint__(self):
print('__length_hint__', len(self.__values))
return len(self.__values)
n = num_array()
print(len(n)) |
#!/usr/bin/env python
'''XML Namespace Constants'''
#
# This should actually check for a value error
#
def xs_bool(in_string):
'''Takes an XSD boolean value and converts it to a Python bool'''
if in_string in ['true', '1']:
return True
return False
| """XML Namespace Constants"""
def xs_bool(in_string):
"""Takes an XSD boolean value and converts it to a Python bool"""
if in_string in ['true', '1']:
return True
return False |
''' teachers and centers are lists of Teacher objects and ExamCenter objects respectively
class Teacher and class ExamCentre and defined in locatable.py
Both are subclass of Locatable class
Link : https://github.com/aahnik/mapTeachersToCenters/blob/master/locatable.py '''
def sort(locatables, focal_cen... | """ teachers and centers are lists of Teacher objects and ExamCenter objects respectively
class Teacher and class ExamCentre and defined in locatable.py
Both are subclass of Locatable class
Link : https://github.com/aahnik/mapTeachersToCenters/blob/master/locatable.py """
def sort(locatables, focal_cent... |
list=[1,2,3.5,4,5]
print(list)
sum=0
for i in list:
sum=sum+i
sum/=i
print(sum)
| list = [1, 2, 3.5, 4, 5]
print(list)
sum = 0
for i in list:
sum = sum + i
sum /= i
print(sum) |
'''
PURPOSE
Analyze a string to check if it contains two of the same letter
in a row. Your function must return True if there are two identical
letters in a row in the string, and False otherwise.
EXAMPLE
The string "hello" has l twice in a row, while the string "nono"
does not have two identical ... | """
PURPOSE
Analyze a string to check if it contains two of the same letter
in a row. Your function must return True if there are two identical
letters in a row in the string, and False otherwise.
EXAMPLE
The string "hello" has l twice in a row, while the string "nono"
does not have two identical ... |
# Python Program to check if there is a
# negative weight cycle using Floyd Warshall Algorithm
# Number of vertices in the graph
V = 4
# Define Infinite as a large enough value. This
# value will be used for vertices not connected to each other
INF = 99999
# Returns true if graph has negative weig... | v = 4
inf = 99999
def neg_cyclefloyd_warshall(graph):
dist = [[0 for i in range(V)] for j in range(V)]
for i in range(4):
for j in range(V):
dist[i][j] = graph[i][j]
for item in dist:
print(item)
' Add all vertices one by one to the set of \n intermediate vertices.\n ... |
limit = int(input())
current = int(input())
multiply = int(input())
day = 0
total = current
while total <= limit:
day += 1
current *= multiply
total += current
# print('on day', day, ',', current, 'people are infected. and the total is', total)
print(day) | limit = int(input())
current = int(input())
multiply = int(input())
day = 0
total = current
while total <= limit:
day += 1
current *= multiply
total += current
print(day) |
train_sequence = ReportSequence(X_train, y_train)
validation_sequence = ReportSequence(X_valid, y_valid)
model = Sequential()
forward_layer = LSTM(300, return_sequences=True)
backward_layer = LSTM(300, go_backwards=True, return_sequences=True)
model.add(Bidirectional(forward_layer,
backward_l... | train_sequence = report_sequence(X_train, y_train)
validation_sequence = report_sequence(X_valid, y_valid)
model = sequential()
forward_layer = lstm(300, return_sequences=True)
backward_layer = lstm(300, go_backwards=True, return_sequences=True)
model.add(bidirectional(forward_layer, backward_layer=backward_layer, inpu... |
# Code generated by font-to-py.py.
# Font: dsmb.ttf
version = '0.26'
def height():
return 16
def max_width():
return 9
def hmap():
return True
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_ch():
return 126
_font =\... | version = '0.26'
def height():
return 16
def max_width():
return 9
def hmap():
return True
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_ch():
return 126
_font = b'\t\x00\x00\x00x\x00\x8c\x00\x0c\x00\x1c\x008\x000\x000\x000\x00\x00\x000\x00... |
orgM = cmds.ls(sl=1,fl=1)
newM = cmds.ls(sl=1,fl=1)
for nm in newM:
for om in orgM:
if nm.split(':')[0] == om.split(':')[0]+'1':
trans = cmds.xform(om,ws=1,piv=1,q=1)
rot = cmds.xform(om,ws=1,ro=1,q=1)
cmds.xform(nm,t=trans[0:3],ro=rot)
cmds.namespace(ren=((nm.split(':')[0]),(nm.split(':')[1])))
| org_m = cmds.ls(sl=1, fl=1)
new_m = cmds.ls(sl=1, fl=1)
for nm in newM:
for om in orgM:
if nm.split(':')[0] == om.split(':')[0] + '1':
trans = cmds.xform(om, ws=1, piv=1, q=1)
rot = cmds.xform(om, ws=1, ro=1, q=1)
cmds.xform(nm, t=trans[0:3], ro=rot)
cmds.name... |
class Solution:
def isValid(self, s: str):
count = 0
for i in s:
if i == '(':
count += 1
if i == ')':
count -=1
if count < 0:
return False
return count == 0
def removeInvalidParenthes... | class Solution:
def is_valid(self, s: str):
count = 0
for i in s:
if i == '(':
count += 1
if i == ')':
count -= 1
if count < 0:
return False
return count == 0
def remove_invalid_parentheses(self, s: str... |
"""
Let's reverse engineer the process.
Imagine you are standing at the last index i
index i-1 will need the value>=1 to go to i (step_need=1)
index i-2 will need the value>=2 to go to i (step_need=2)
...
At a certain index x, the value>=step_need
This means that, from x, we can go to i no problem.
Now we are standing... | """
Let's reverse engineer the process.
Imagine you are standing at the last index i
index i-1 will need the value>=1 to go to i (step_need=1)
index i-2 will need the value>=2 to go to i (step_need=2)
...
At a certain index x, the value>=step_need
This means that, from x, we can go to i no problem.
Now we are standing... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'chromium_tests',
'depot_tools/tryserver',
'recipe_engine/platform',
'recipe_engine/properties',
]
def RunSteps(api):
tests = []... | deps = ['chromium_tests', 'depot_tools/tryserver', 'recipe_engine/platform', 'recipe_engine/properties']
def run_steps(api):
tests = []
if api.properties.get('local_gtest'):
tests.append(api.chromium_tests.steps.LocalGTestTest('base_unittests'))
if api.properties.get('swarming_gtest'):
test... |
# -*- coding: utf-8 -*-
description = 'detectors'
group = 'lowlevel' # is included by panda.py
devices = dict(
mcstas = device('nicos_virt_mlz.panda.devices.mcstas.PandaSimulation',
description = 'McStas simulation',
),
timer = device('nicos.devices.mcstas.McStasTimer',
mcstas = 'mcstas... | description = 'detectors'
group = 'lowlevel'
devices = dict(mcstas=device('nicos_virt_mlz.panda.devices.mcstas.PandaSimulation', description='McStas simulation'), timer=device('nicos.devices.mcstas.McStasTimer', mcstas='mcstas', visibility=()), mon1=device('nicos.devices.mcstas.McStasCounter', type='monitor', mcstas='m... |
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
results = []
for i in range(len(lists)):
for j in range(len(lists[i])):
results.append(lists[i][j])
return results
print(flatten(n))
| n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for i in range(len(lists)):
for j in range(len(lists[i])):
results.append(lists[i][j])
return results
print(flatten(n)) |
age=int(input())
washing_machine_price=float(input())
toys_price=float(input())
toys_count = 0
money_amount = 0
for years in range(1,age+1):
if years % 2 == 0:
#price
money_amount += years / 2 * 10
money_amount-=1
else:
#toy
toys_count+=1
toys_price=toys_count*... | age = int(input())
washing_machine_price = float(input())
toys_price = float(input())
toys_count = 0
money_amount = 0
for years in range(1, age + 1):
if years % 2 == 0:
money_amount += years / 2 * 10
money_amount -= 1
else:
toys_count += 1
toys_price = toys_count * toys_price
total_amoun... |
#!/usr/bin/env python
"""Parse arguments for functions in the wmem package.
"""
def parse_common(parser):
parser.add_argument(
'-D', '--dataslices',
nargs='*',
type=int,
help="""
Data slices, specified as triplets of <start> <stop> <step>;
setting any <stop> to 0... | """Parse arguments for functions in the wmem package.
"""
def parse_common(parser):
parser.add_argument('-D', '--dataslices', nargs='*', type=int, help='\n Data slices, specified as triplets of <start> <stop> <step>;\n setting any <stop> to 0 or will select the full extent;\n provide triplets... |
#Ejercicio
precio = float(input("Ingrese el precio: "))
descuento = precio * 0.15
precio_final = precio - descuento
print (f"el precio final a pagar es: {precio_final:.2f}")
print (descuento)
| precio = float(input('Ingrese el precio: '))
descuento = precio * 0.15
precio_final = precio - descuento
print(f'el precio final a pagar es: {precio_final:.2f}')
print(descuento) |
# write your code here
user_field = input("Enter cells: ")
game_board = []
player_1 = "X"
player_2 = "O"
def print_field(field):
global game_board
coordinates = list()
game_board = [[field[0], field[1], field[2]],
[field[3], field[4], field[5]],
[field[6], field[7], fie... | user_field = input('Enter cells: ')
game_board = []
player_1 = 'X'
player_2 = 'O'
def print_field(field):
global game_board
coordinates = list()
game_board = [[field[0], field[1], field[2]], [field[3], field[4], field[5]], [field[6], field[7], field[8]]]
def printer(board):
print('---------')
... |
# takes two inputs and adds them together as ints;
# outputs solution
print(int(input()) + int(input()))
| print(int(input()) + int(input())) |
"""
PASSENGERS
"""
numPassengers = 2757
passenger_arriving = (
(3, 9, 6, 2, 3, 0, 9, 5, 3, 3, 1, 0), # 0
(2, 11, 10, 1, 1, 0, 2, 4, 2, 2, 0, 0), # 1
(1, 10, 5, 3, 2, 0, 5, 12, 6, 3, 1, 0), # 2
(5, 8, 7, 2, 1, 0, 6, 7, 5, 5, 1, 0), # 3
(3, 5, 5, 3, 2, 0, 9, 8, 4, 0, 1, 0), # 4
(1, 9, 11, 4, 1, 0, 7, 7, 6, ... | """
PASSENGERS
"""
num_passengers = 2757
passenger_arriving = ((3, 9, 6, 2, 3, 0, 9, 5, 3, 3, 1, 0), (2, 11, 10, 1, 1, 0, 2, 4, 2, 2, 0, 0), (1, 10, 5, 3, 2, 0, 5, 12, 6, 3, 1, 0), (5, 8, 7, 2, 1, 0, 6, 7, 5, 5, 1, 0), (3, 5, 5, 3, 2, 0, 9, 8, 4, 0, 1, 0), (1, 9, 11, 4, 1, 0, 7, 7, 6, 4, 0, 0), (3, 8, 5, 3, 0, 0, 6, 9,... |
triggers = {
'lumos': 'automation.potter_pi_spell_lumos',
'nox': 'automation.potter_pi_spell_nox',
'revelio': 'automation.potter_pi_spell_revelio'
} | triggers = {'lumos': 'automation.potter_pi_spell_lumos', 'nox': 'automation.potter_pi_spell_nox', 'revelio': 'automation.potter_pi_spell_revelio'} |
fh= open("romeo.txt")
lst= list()
for line in fh:
wds= line.split()
for word in wds:
if word in wds:
lst.append(word)
lst.sort()
print(lst)
| fh = open('romeo.txt')
lst = list()
for line in fh:
wds = line.split()
for word in wds:
if word in wds:
lst.append(word)
lst.sort()
print(lst) |
OEMBED_URL_SCHEME_REGEXPS = {
'slideshare' : r'https?://(?:www\.)?slideshare\.(?:com|net)/.*',
'soundcloud' : r'https?://soundcloud.com/.*',
'vimeo' : r'https?://(?:www\.)?vimeo\.com/.*',
'youtube' : r'https?://(?:(www\.)?youtube\.com|youtu\.be)/.*',
}
OEMBED_BASE_URLS = {
'slideshare' : 'https://w... | oembed_url_scheme_regexps = {'slideshare': 'https?://(?:www\\.)?slideshare\\.(?:com|net)/.*', 'soundcloud': 'https?://soundcloud.com/.*', 'vimeo': 'https?://(?:www\\.)?vimeo\\.com/.*', 'youtube': 'https?://(?:(www\\.)?youtube\\.com|youtu\\.be)/.*'}
oembed_base_urls = {'slideshare': 'https://www.slideshare.net/api/oembe... |
X, M = tuple(map(int,input().split()))
while X != 0 or M != 0:
print(X*M)
X, M = tuple(map(int,input().split()))
| (x, m) = tuple(map(int, input().split()))
while X != 0 or M != 0:
print(X * M)
(x, m) = tuple(map(int, input().split())) |
##HEADING: [PROBLEM NAME]
#PROBLEM STATEMENT:
"""
[PROBLEM STATEMENT LINE1]
[PROBLEM STATEMENT LINE1]
[PROBLEM STATEMENT LINE1]
"""
#SOLUTION-1: ([METHOD DESCRIPTION LIKE BRUTE_FORCE, DP_ALGORITHM, GREEDY_ALGORITHM, ITERATIVE_ALGORITHM, RECURSIVE_ALGORITHM]) --> [TIME COMPLEXITY LIKE O(n), O(log2(n)), O(n... | """
[PROBLEM STATEMENT LINE1]
[PROBLEM STATEMENT LINE1]
[PROBLEM STATEMENT LINE1]
"""
'\n [##DISCLAIMER: POINT TO BE NOTED BEFORE JUMPING INTO DESCRIPTION]\n [DESCRIPTION LINE1]\n [DESCRIPTION LINE2]\n [DESCRIPTION LINE3]\n [DESCRIPTION LINE4]\n [DESCRIPTION LINE5]\n [DESCRIPTION LINE6]... |
FLAG = 'QCTF{4e94227c6c003c0b6da6f81c9177c7e7}'
def check(attempt, context):
return Checked(attempt.answer == FLAG)
| flag = 'QCTF{4e94227c6c003c0b6da6f81c9177c7e7}'
def check(attempt, context):
return checked(attempt.answer == FLAG) |
'''
Created on Mar 3, 2014
@author: rgeorgi
'''
class EvalException(Exception):
'''
classdocs
'''
def __init__(self, msg):
'''
Constructor
'''
self.message = msg
class POSEvalException(Exception):
def __init__(self, msg):
Exception.__init__(self, msg)
| """
Created on Mar 3, 2014
@author: rgeorgi
"""
class Evalexception(Exception):
"""
classdocs
"""
def __init__(self, msg):
"""
Constructor
"""
self.message = msg
class Posevalexception(Exception):
def __init__(self, msg):
Exception.__init__(self, msg) |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
n=0
last=0
for c in s:
if c==" ":
last=n if n>0 else last
n=0
else:
n=n+1
return n if n>0 else last
| class Solution:
def length_of_last_word(self, s: str) -> int:
n = 0
last = 0
for c in s:
if c == ' ':
last = n if n > 0 else last
n = 0
else:
n = n + 1
return n if n > 0 else last |
# -*- coding: utf-8 -*-
# see LICENSE.rst
# ----------------------------------------------------------------------------
#
# TITLE : Data
# AUTHOR : Nathaniel and Qing and Vivian
# PROJECT : JAS1101FinalProject
#
# ----------------------------------------------------------------------------
"""Data Management.
Of... | """Data Management.
Often data is packaged poorly and it can be difficult to understand how
the data should be read.
DON`T PANIC.
This module provides functions to read the contained data.
Routine Listings
----------------
"""
__author__ = 'Nathaniel and Qing and Vivian' |
class BaseClause:
def __init__(self):
# call super as these classes will be used as mix-in
# and we want the init chain to reach all extended classes in the user of these mix-in
# Update: Its main purpose is to make IDE hint children constructors to call base one,
# as not calling it... | class Baseclause:
def __init__(self):
super().__init__() |
class RandomVariable:
"""
Basic class for random variable distribution
"""
def __init__(self):
"""
self.parameter is a dict for parameters in distribution
"""
self.parameter = {}
def fit(self):
pass
def ml(self):
pass
def map(self):
... | class Randomvariable:
"""
Basic class for random variable distribution
"""
def __init__(self):
"""
self.parameter is a dict for parameters in distribution
"""
self.parameter = {}
def fit(self):
pass
def ml(self):
pass
def map(self):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""This file is part of the Scribee project.
"""
__author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>'
__copyright__ = 'Copyright (c) 2011 Emanuele Bertoldi'
__version__ = '0.0.1'
def filter(block):
block.filtered = '\n'.join([l.strip().replace('/*', "").replace(... | """This file is part of the Scribee project.
"""
__author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>'
__copyright__ = 'Copyright (c) 2011 Emanuele Bertoldi'
__version__ = '0.0.1'
def filter(block):
block.filtered = '\n'.join([l.strip().replace('/*', '').replace('*/', '').strip(' *') for l in block.filter... |
"""
https://leetcode.com/problems/reverse-integer/description/
"""
class Solution:
def reverse(self, x: int) -> int:
# sign = -1 if x < 0 else 1
sign = [1, -1][x < 0]
num = sign * x
num_str = str(num)
out = 0
for i in range(len(num_str))[::-1]:
if out >... | """
https://leetcode.com/problems/reverse-integer/description/
"""
class Solution:
def reverse(self, x: int) -> int:
sign = [1, -1][x < 0]
num = sign * x
num_str = str(num)
out = 0
for i in range(len(num_str))[::-1]:
if out > 2 ** 31 - 1:
return ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Title """
__author__ = "Hiroshi Kajino <KAJINO@jp.ibm.com>"
__copyright__ = "Copyright IBM Corp. 2019, 2021"
MultipleRun_params = {
'DataPreprocessing_params': {
'in_dim': 50,
'train_size': 100,
'val_size': 100,
'test_size': 500},
... | """ Title """
__author__ = 'Hiroshi Kajino <KAJINO@jp.ibm.com>'
__copyright__ = 'Copyright IBM Corp. 2019, 2021'
multiple_run_params = {'DataPreprocessing_params': {'in_dim': 50, 'train_size': 100, 'val_size': 100, 'test_size': 500}, 'Train_params': {'model_kwargs': {'@alpha': [0.0001, 0.001, 0.01, 0.1], '@fit_intercep... |
# -*- coding: utf-8 -*-
"""
Name:LAVOE YAWA JENNIFER
Stud. ID: 20653245
"""
class Point ( object ):
def __init__ (self , x, y):
self .x = x
self .y = y
def __str__ ( self ):
return f"({ self .x},{ self .y})"
def __sub__ (self , other ):
dx = self... | """
Name:LAVOE YAWA JENNIFER
Stud. ID: 20653245
"""
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'({self.x},{self.y})'
def __sub__(self, other):
dx = self.x - other.x
dy = self.y - other.y
... |
def get_breadcrumb(cat3):
cat2 = cat3.parent
cat1 = cat3.parent.parent
cat1.url = cat1.goodschannel_set.all()[0].url
breadcrumb = {
'cat1': cat1,
'cat2': cat2,
'cat3': cat3,
}
return breadcrumb | def get_breadcrumb(cat3):
cat2 = cat3.parent
cat1 = cat3.parent.parent
cat1.url = cat1.goodschannel_set.all()[0].url
breadcrumb = {'cat1': cat1, 'cat2': cat2, 'cat3': cat3}
return breadcrumb |
class DynamicObjectSerializer:
def __init__(self, value, many=False):
self._objects = None
self._object = None
if many:
value = tuple(v for v in value)
self._objects = value
else:
self._object = value
@property
def objects(self):
... | class Dynamicobjectserializer:
def __init__(self, value, many=False):
self._objects = None
self._object = None
if many:
value = tuple((v for v in value))
self._objects = value
else:
self._object = value
@property
def objects(self):
... |
myTup = 0, 2, 4, 5, 6, 7
i1, *i2, i3 = myTup
print(i1)
print(i2, type(i2))
print(i3) | my_tup = (0, 2, 4, 5, 6, 7)
(i1, *i2, i3) = myTup
print(i1)
print(i2, type(i2))
print(i3) |
"""
Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).
Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuou... | """
Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).
Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuou... |
class Color:
BACKGROUND = 236
FOREGROUND = 195
BUTTON_BACKGROUND = 66
FIELD_BACKGROUND = 238 #241
SCROLL_BAR_BACKGROUND = 242
TEXT = 1
INPUT_FIELD = 2
SCROLL_BAR = 3
BUTTON = 4
# color.py
| class Color:
background = 236
foreground = 195
button_background = 66
field_background = 238
scroll_bar_background = 242
text = 1
input_field = 2
scroll_bar = 3
button = 4 |
def smallest_positive(arr):
# Find the smallest positive number in the list
min = None
for num in arr:
if num > 0:
if min == None or num < min:
min = num
return min
def when_offered(courses, course):
output = []
for semester in courses:
for course_n... | def smallest_positive(arr):
min = None
for num in arr:
if num > 0:
if min == None or num < min:
min = num
return min
def when_offered(courses, course):
output = []
for semester in courses:
for course_names in courses[semester]:
if course_names... |
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x | def my_abs(x):
if not isinstance(x, (int, float)):
raise type_error('bad operand type')
if x >= 0:
return x
else:
return -x |
while True:
a, b = map(int, input().split(" "))
if not a and not b:
break
print(a + b) | while True:
(a, b) = map(int, input().split(' '))
if not a and (not b):
break
print(a + b) |
class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
if x < 1:
return 0
l, r = 1, x//2 + 1
while r > l:
mid = (l + r) // 2
square = mid * mid
if square > x:
... | class Solution:
"""
@param x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
if x < 1:
return 0
(l, r) = (1, x // 2 + 1)
while r > l:
mid = (l + r) // 2
square = mid * mid
if square > x:
r = mid - 1
... |
class LetterFrequencyPair:
def __init__(self, letter: str, frequency: int):
self.letter: str = letter
self.frequency: int = frequency
def __str__(self):
return '{}:{}'.format(self.letter, self.frequency)
class HTreeNode:
pass
print(LetterFrequencyPair('A', 23))
| class Letterfrequencypair:
def __init__(self, letter: str, frequency: int):
self.letter: str = letter
self.frequency: int = frequency
def __str__(self):
return '{}:{}'.format(self.letter, self.frequency)
class Htreenode:
pass
print(letter_frequency_pair('A', 23)) |
class HashMap:
def __init__(self, size):
self.array_size = size
self.array = [None] * size
def hash(self, key, count_collisions = 0):
return sum(key.encode()) + count_collisions
def compressor(self, hash_code):
return hash_code % self.array_size
def ass... | class Hashmap:
def __init__(self, size):
self.array_size = size
self.array = [None] * size
def hash(self, key, count_collisions=0):
return sum(key.encode()) + count_collisions
def compressor(self, hash_code):
return hash_code % self.array_size
def assign(self, key, va... |
"""
Contains a collection of useful functions when working
with strings.
"""
def shorten_to(string: str, length: int, extension: bool = False):
"""
When a user uploaded a plugin with a pretty long file/URL name,
it is useful to crop this file name to avoid weird UI behavior.
This method takes a string... | """
Contains a collection of useful functions when working
with strings.
"""
def shorten_to(string: str, length: int, extension: bool=False):
"""
When a user uploaded a plugin with a pretty long file/URL name,
it is useful to crop this file name to avoid weird UI behavior.
This method takes a string (i... |
def solution(n):
n = str(n)
if len(n) % 2 != 0: return False
n = list(n)
a,b = n[:len(n)//2], n[len(n)//2:]
a,b = list(map(int, a)), list(map(int, b))
return sum(a) == sum(b)
| def solution(n):
n = str(n)
if len(n) % 2 != 0:
return False
n = list(n)
(a, b) = (n[:len(n) // 2], n[len(n) // 2:])
(a, b) = (list(map(int, a)), list(map(int, b)))
return sum(a) == sum(b) |
def number(lines):
"""
Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.
Write a function which takes a list of strings and returns each line prepended by the correct number.
The numbering starts at 1. The format is n: string. Notice the colon and ... | def number(lines):
"""
Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.
Write a function which takes a list of strings and returns each line prepended by the correct number.
The numbering starts at 1. The format is n: string. Notice the colon and ... |
# Copyright 2022 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.
"""A wrapper for common operations on a device with Cast capabilities."""
CAST_BROWSERS = [
'platform_app'
]
| """A wrapper for common operations on a device with Cast capabilities."""
cast_browsers = ['platform_app'] |
def main():
while True:
userinput = input("Write something (quit ends): ")
if(userinput == "quit"):
break
else:
tester(userinput)
def tester(givenstring="Too short"):
if(len(givenstring) < 10):
print("Too short")
else:
print(givenstring)
if ... | def main():
while True:
userinput = input('Write something (quit ends): ')
if userinput == 'quit':
break
else:
tester(userinput)
def tester(givenstring='Too short'):
if len(givenstring) < 10:
print('Too short')
else:
print(givenstring)
if __na... |
df = pd.read_csv(DATA, delimiter=';')
df[['EV1', 'EV2', 'EV3']] = df['Participants'].str.split(', ', expand=True)
df['Duration'] = pd.to_timedelta(df['Duration'])
result = (pd.concat([
df[['EV1', 'Duration']].rename(columns={'EV1': 'Astronaut'}),
df[['EV2', 'Duration']].rename(columns={'EV2': 'A... | df = pd.read_csv(DATA, delimiter=';')
df[['EV1', 'EV2', 'EV3']] = df['Participants'].str.split(', ', expand=True)
df['Duration'] = pd.to_timedelta(df['Duration'])
result = pd.concat([df[['EV1', 'Duration']].rename(columns={'EV1': 'Astronaut'}), df[['EV2', 'Duration']].rename(columns={'EV2': 'Astronaut'}), df[['EV3', 'D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.