content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Created on October 15, 2019
This file is subject to the terms and conditions defined in the
file 'LICENSE.txt', which is part of this source code package.
@author: David Moss
"""
# Task priorities
TASK_PRIORITY_DETAIL = 0
TASK_PRIORITY_INFO = 1
TASK_PRIORITY_WARNING = 2
TASK_PRIORITY_CRITICAL = 3
def update_tas... | """
Created on October 15, 2019
This file is subject to the terms and conditions defined in the
file 'LICENSE.txt', which is part of this source code package.
@author: David Moss
"""
task_priority_detail = 0
task_priority_info = 1
task_priority_warning = 2
task_priority_critical = 3
def update_task(botengine, locati... |
class Rectangle(object):
def __init__(self, x, y):
self._x = x # don't trigger _setSide prematurely
self.y = y # now trigger it, so area gets computed
def _setSide(self, attrname, value):
setattr(self, attrname, value)
self.area = self._x * ... | class Rectangle(object):
def __init__(self, x, y):
self._x = x
self.y = y
def _set_side(self, attrname, value):
setattr(self, attrname, value)
self.area = self._x * self._y
x = common_property('_x', fset=_setSide, fdel=None)
y = common_property('_y', fset=_setSide, fdel... |
orders = ["daisies", "periwinkle"]
print(orders)
orders.append("tulips")
orders.append("roses")
print(orders) | orders = ['daisies', 'periwinkle']
print(orders)
orders.append('tulips')
orders.append('roses')
print(orders) |
def test_parameters(api_client, api_prefix):
url = f"{api_prefix}/parameterset/"
response = api_client.get(url)
assert response.status_code == 200
json_dict = response.json
expected = {
"parameter_list_url": f"{api_prefix}/parameters/",
"parameter_set": {
"name": None,
... | def test_parameters(api_client, api_prefix):
url = f'{api_prefix}/parameterset/'
response = api_client.get(url)
assert response.status_code == 200
json_dict = response.json
expected = {'parameter_list_url': f'{api_prefix}/parameters/', 'parameter_set': {'name': None, 'parameters': [{'excluded': [], ... |
#! /usr/bin/python3
DATA_FILENAME = "data.txt"
data_file = open(DATA_FILENAME, 'r') # open the file for reading
date_string = data_file.readline()
date_string = date_string.strip()
year, month, day = tuple(date_string.split('-'))
year, month, day = int(year), int(month), int(day)
month_names = {1:'January', 2:'Februa... | data_filename = 'data.txt'
data_file = open(DATA_FILENAME, 'r')
date_string = data_file.readline()
date_string = date_string.strip()
(year, month, day) = tuple(date_string.split('-'))
(year, month, day) = (int(year), int(month), int(day))
month_names = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: ... |
# Version-specific constants - EDIT THESE VALUES
VERSION_NAME = "Version003 - Brute Force, Even Smarter Iteration"
VERSION_DESCRIPTION = """
A slightly more formulaic approach, but still iterative.
"""
def solution(resources, args):
"""Problem 1 - Version 3
Use a formula to determine the additional sum 15 int... | version_name = 'Version003 - Brute Force, Even Smarter Iteration'
version_description = '\nA slightly more formulaic approach, but still iterative.\n'
def solution(resources, args):
"""Problem 1 - Version 3
Use a formula to determine the additional sum 15 integers at a
time, then use the iterative approach... |
def handle_error_response(resp):
codes = {
-1: FATdAPIError,
-32600: InvalidRequest,
-32601: MethodNotFound,
-32602: InvalidParam,
-32603: InternalError,
-32700: ParseError,
-32800: TokenNotFound,
-32801: InvalidToken,
-32802: InvalidAddress,
... | def handle_error_response(resp):
codes = {-1: FATdAPIError, -32600: InvalidRequest, -32601: MethodNotFound, -32602: InvalidParam, -32603: InternalError, -32700: ParseError, -32800: TokenNotFound, -32801: InvalidToken, -32802: InvalidAddress, -32803: TransactionNotFound, -32804: InvalidTransaction, -32805: TokenSync... |
class Hitbox:
def __init__(self):
pass
def point_inside(self, obj, point):
return False
class Box(Hitbox):
def __init__(self, width, height):
Hitbox.__init__(self)
self.width = width
self.height = height
def point_inside(self, obj, pos):
x = obj.x
y = obj.y
xm = x + (self.width*obj.scale)
ym =... | class Hitbox:
def __init__(self):
pass
def point_inside(self, obj, point):
return False
class Box(Hitbox):
def __init__(self, width, height):
Hitbox.__init__(self)
self.width = width
self.height = height
def point_inside(self, obj, pos):
x = obj.x
... |
def Function(anumber):
if anumber == 1:
print ("One")
elif anumber == 2:
print ("Two")
elif anumber == 3:
print ("Three")
elif anumber == 4:
print ("Four")
elif anumber == 5:
print ("Five")
elif anumber == 6:
print ("Six")
elif anumber == 7:
... | def function(anumber):
if anumber == 1:
print('One')
elif anumber == 2:
print('Two')
elif anumber == 3:
print('Three')
elif anumber == 4:
print('Four')
elif anumber == 5:
print('Five')
elif anumber == 6:
print('Six')
elif anumber == 7:
... |
def disp(*txt, p):
print(*txt)
ask = lambda p : p.b(input())
functions = {">>":disp,"?":ask}
| def disp(*txt, p):
print(*txt)
ask = lambda p: p.b(input())
functions = {'>>': disp, '?': ask} |
'''
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.Return the decimal value of the number in the linked list.
Example :
1 ---> 0 ---> 1
Input: head = [1,0,1]
Output: 5
Explanation: (... | """
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.Return the decimal value of the number in the linked list.
Example :
1 ---> 0 ---> 1
Input: head = [1,0,1]
Output: 5
Explanation: (... |
val = int(input(print("Enter a number: ")))
option = {
"n":"Nae nigga nae \n", "c":"Uohhhhhh :sob::sob::sob: \n",
"i":"I am living in your walls, oomfie. \n"
}
userinput = input("Choose your poison: [N]iggas, [C]unny, [I]solation")
with open("outputtings.txt",'w') as f:
f.write(option[userinput.l... | val = int(input(print('Enter a number: ')))
option = {'n': 'Nae nigga nae \n', 'c': 'Uohhhhhh :sob::sob::sob: \n', 'i': 'I am living in your walls, oomfie. \n'}
userinput = input('Choose your poison: [N]iggas, [C]unny, [I]solation')
with open('outputtings.txt', 'w') as f:
f.write(option[userinput.lower()] * val)
pr... |
'''
Ganon's Tower
'''
__all__ = 'LOCATIONS',
LOCATIONS = {
"Ganon's Tower Entrance (I)": {
'type': 'interior',
'link': {
'Castle Tower Entrance (E)': [('settings', 'inverted')],
"Ganon's Tower Entrance (E)": [('nosettings', 'inverted')],
"Ganon's Tower Lobby": ... | """
Ganon's Tower
"""
__all__ = ('LOCATIONS',)
locations = {"Ganon's Tower Entrance (I)": {'type': 'interior', 'link': {'Castle Tower Entrance (E)': [('settings', 'inverted')], "Ganon's Tower Entrance (E)": [('nosettings', 'inverted')], "Ganon's Tower Lobby": [('and', [('or', [('settings', 'placement_advanced'), ('and'... |
class Codec:
def __init__(self):
self.codec_dict = dict()
self.codec_reversed = dict()
self.codec_len = 0
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
if longUrl not in self.codec_dict:
self.codec_dict[longUrl]=self.... | class Codec:
def __init__(self):
self.codec_dict = dict()
self.codec_reversed = dict()
self.codec_len = 0
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
if longUrl not in self.codec_dict:
self.codec_dict[longUrl] = se... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 22 17:54:15 2019
@author: Parikshith.H
"""
L1 = [10,20,30,40]
print(L1)
print(L1[0])
print(L1[3])
L1[3] = 50
print(L1)
#output:
# =============================================================================
# [10, 20, 30, 40]
# 10
# 40
# [10, 20, 30, 50]
# ===========... | """
Created on Wed May 22 17:54:15 2019
@author: Parikshith.H
"""
l1 = [10, 20, 30, 40]
print(L1)
print(L1[0])
print(L1[3])
L1[3] = 50
print(L1)
l2 = [10, 2.5, 'hello']
print(L2)
print(L2[2])
L2[1] = 'welcome'
print(L2)
l3 = [10, 20, 'hello', ['A', 'B']]
print(l3[3])
print(l3[2])
print(l3[3][0])
l4 = [[10, 20, 30], [2... |
def siOr(s0, s1):
'''Performs s0 | s1 where s0 and s1 are lists of sections or intervals'''
actSec = [False, False]
secs = []
k0 = [i for s in s0 for i in s]
k1 = [i for s in s1 for i in s]
keyPoints = list(sorted([(k, 0) for k in k0]
+ [(k, 1) for k in k1], key=lam... | def si_or(s0, s1):
"""Performs s0 | s1 where s0 and s1 are lists of sections or intervals"""
act_sec = [False, False]
secs = []
k0 = [i for s in s0 for i in s]
k1 = [i for s in s1 for i in s]
key_points = list(sorted([(k, 0) for k in k0] + [(k, 1) for k in k1], key=lambda x: x[0]))
x = None
... |
class Solution:
def numIslands(self, grid: 'List[List[str]]') -> 'int':
if not grid:
return 0
no_lines = len(grid)
no_cols = len(grid[0])
def solve(line_idx, col_idx):
grid[line_idx][col_idx] = '-1'
queue = [(line_idx, col_idx)]
idx =... | class Solution:
def num_islands(self, grid: 'List[List[str]]') -> 'int':
if not grid:
return 0
no_lines = len(grid)
no_cols = len(grid[0])
def solve(line_idx, col_idx):
grid[line_idx][col_idx] = '-1'
queue = [(line_idx, col_idx)]
idx ... |
a = [[3,],[]]
for x in a:
x.append(4)
# print (x)
print (a)
b= []
for x in b:
print (3)
print (x) | a = [[3], []]
for x in a:
x.append(4)
print(a)
b = []
for x in b:
print(3)
print(x) |
filename='pi_million_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string+=line.strip()
birthday=input("Enter your birthday, in the form mmddyy:")
if birthday in pi_string:
print("Your birthday appears in the first millions digits of pi!")
... | filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
birthday = input('Enter your birthday, in the form mmddyy:')
if birthday in pi_string:
print('Your birthday appears in the first millions digits ... |
"""
This module is used to define constants used throughout the code.
It should not depend on any other part of the globus-cli codebase.
(If you need to import something else, maybe it's not simple enough to be a constant...)
"""
__all__ = ["EXPLICIT_NULL"]
class _ExplicitNullClass:
"""
Magic sentinel value... | """
This module is used to define constants used throughout the code.
It should not depend on any other part of the globus-cli codebase.
(If you need to import something else, maybe it's not simple enough to be a constant...)
"""
__all__ = ['EXPLICIT_NULL']
class _Explicitnullclass:
"""
Magic sentinel value u... |
"""https://adventofcode.com/2021/day/21"""
class Die:
def __init__(self, sides=100):
self.sides = sides
self.value = 0
self.rolled = 0
def roll(self):
self.rolled += 1
self.value = self.value % self.sides + 1
return self.value
data = open("day-21/input.txt", ... | """https://adventofcode.com/2021/day/21"""
class Die:
def __init__(self, sides=100):
self.sides = sides
self.value = 0
self.rolled = 0
def roll(self):
self.rolled += 1
self.value = self.value % self.sides + 1
return self.value
data = open('day-21/input.txt', 'r... |
def outer():
def inner():
print(out_var)
out_var = 10
inner()
if "__main__" == __name__:
outer() | def outer():
def inner():
print(out_var)
out_var = 10
inner()
if '__main__' == __name__:
outer() |
# Copyright (c) Vera Galstyan Jan 2018
favorite_places ={
'vera': ['lyon','paris','london'],
'ofa':['berlin','madrid','milan'],
'karen':['dubai','barcelona']
}
for name,places in favorite_places.items():
print("\n" + name + "'s favorite places are:")
for place in places:
print(place) | favorite_places = {'vera': ['lyon', 'paris', 'london'], 'ofa': ['berlin', 'madrid', 'milan'], 'karen': ['dubai', 'barcelona']}
for (name, places) in favorite_places.items():
print('\n' + name + "'s favorite places are:")
for place in places:
print(place) |
number1 = 10
pi_number = 3.1415
img_number = -10+4j
first_name = 'kaveh'
last_name = "mehrbanian"
bio = """some description about me"""
is_sad = False
is_happy = True
initial_value = None
| number1 = 10
pi_number = 3.1415
img_number = -10 + 4j
first_name = 'kaveh'
last_name = 'mehrbanian'
bio = 'some description about me'
is_sad = False
is_happy = True
initial_value = None |
# -*- coding: utf-8 -*-
# See /usr/include/sysexits.h
EX_OK = 0
EX_USAGE = 64
EX_DATAERR = 65
EX_NOUSER = 67
EX_PROTOCOL = 76
EX_TEMPFAIL = 75
EX_CONFIG = 78
# Standard for Bash: <http://www.tldp.org/LDP/abs/html/exitcodes.html>
EX_CTRL_C = 130
exit_vals = {
'success': EX_OK,
'config_error': EX_CONFIG,
'url... | ex_ok = 0
ex_usage = 64
ex_dataerr = 65
ex_nouser = 67
ex_protocol = 76
ex_tempfail = 75
ex_config = 78
ex_ctrl_c = 130
exit_vals = {'success': EX_OK, 'config_error': EX_CONFIG, 'url_bung': EX_USAGE, 'communication_failure': EX_PROTOCOL, 'socket_error': EX_PROTOCOL, 'json_decode_error': EX_PROTOCOL, 'no_user': EX_NOUSE... |
class bidict(dict):
"""Bi-directional dictionary for label Lookup. Implementation by Basj
:param dict: dictionnary to be made bi-directional
:type dict: dict
"""
def __init__(self, *args, **kwargs):
super(bidict, self).__init__(*args, **kwargs)
self.inverse = {}
for key, va... | class Bidict(dict):
"""Bi-directional dictionary for label Lookup. Implementation by Basj
:param dict: dictionnary to be made bi-directional
:type dict: dict
"""
def __init__(self, *args, **kwargs):
super(bidict, self).__init__(*args, **kwargs)
self.inverse = {}
for (key, v... |
class Error:
def __init__(self, error_type: str, details: str, file: str, line: int, column: int):
self.error_type = error_type
self.details = details
self.file = file
self.line = line
self.column = column
def __repr__(self):
return "{} ERROR: '{}', fi... | class Error:
def __init__(self, error_type: str, details: str, file: str, line: int, column: int):
self.error_type = error_type
self.details = details
self.file = file
self.line = line
self.column = column
def __repr__(self):
return "{} ERROR: '{}', file {}, lin... |
#!/usr/bin/env python3
def main():
s = str(input('What country are you from? '))
print('I have heard that {0} is a beautiful country.'.format(s))
if __name__ == "__main__":
main()
| def main():
s = str(input('What country are you from? '))
print('I have heard that {0} is a beautiful country.'.format(s))
if __name__ == '__main__':
main() |
{
"targets": [
{
"target_name": "nodeNativeInput",
"sources": [
"src/nodeNativeInput.cpp",
"src/getOne/getOne.cpp",
"src/getTwo/getTwo.cpp",
"src/getThree/getThree.cpp"
],
"include_dirs": ["<!(node -e \"require('nan')\")"],
"conditions": [
["OS... | {'targets': [{'target_name': 'nodeNativeInput', 'sources': ['src/nodeNativeInput.cpp', 'src/getOne/getOne.cpp', 'src/getTwo/getTwo.cpp', 'src/getThree/getThree.cpp'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'conditions': [['OS == "win"', {'defines': ['Windows'], 'link_settings': {'libraries': []}}], ['OS ==... |
# -*- coding: utf-8 -*-
"""Test file."""
"""
>>> from pyrgg import *
>>> import pyrgg.params
>>> import random
>>> import os
>>> import json
>>> import yaml
>>> import pickle
>>> pyrgg.params.PYRGG_TEST_MODE = True
>>> get_precision(2)
0
>>> get_precision(2.2)
1
>>> get_precision(2.22)
2
>>> get_precision(2.223)
3
>>> ... | """Test file."""
'\n>>> from pyrgg import *\n>>> import pyrgg.params\n>>> import random\n>>> import os\n>>> import json\n>>> import yaml\n>>> import pickle\n>>> pyrgg.params.PYRGG_TEST_MODE = True\n>>> get_precision(2)\n0\n>>> get_precision(2.2)\n1\n>>> get_precision(2.22)\n2\n>>> get_precision(2.223)\n3\n>>> convert_s... |
message_decrypter=input("Votre message a decrypter:")
cle=int(input("Nombre de decalage ?:"))
longueur=len(message_decrypter)
i=0
alph=""
resultat=""
for i in range(longueur):
asc=ord(message_decrypter[i])
if asc>=65 or asc<=90:
asc=asc-cle
resultat=resultat+chr(asc)
print (resultat) | message_decrypter = input('Votre message a decrypter:')
cle = int(input('Nombre de decalage ?:'))
longueur = len(message_decrypter)
i = 0
alph = ''
resultat = ''
for i in range(longueur):
asc = ord(message_decrypter[i])
if asc >= 65 or asc <= 90:
asc = asc - cle
resultat = resultat + chr(asc)
print(... |
class VowelConsonant:
def __init__(self):
"""Heuristic strategy: place words that are have either more vowels of consonants based on the letters
remaining in the rack_tiles"""
# Row below not needed but given for refrence of constants
# constants ["b", "c", "d", "f", "g", "h", "j",... | class Vowelconsonant:
def __init__(self):
"""Heuristic strategy: place words that are have either more vowels of consonants based on the letters
remaining in the rack_tiles"""
self.vowel = ['a', 'o', 'i', 'u', 'e']
def determine_vowel_consonant_move(self, rack_tiles, all_words):
... |
class Kilobyte:
def __init__(self, value_kilobytes: int):
self._value_kilobytes = value_kilobytes
self.one_kilobyte_in_bits = 8000
self._value_bits = self._convert_into_bits(value_kilobytes)
self.id = "KB"
def _convert_into_bits(self, value_kilobytes: int) -> int:
return value_kilobytes * self.one_kilobyt... | class Kilobyte:
def __init__(self, value_kilobytes: int):
self._value_kilobytes = value_kilobytes
self.one_kilobyte_in_bits = 8000
self._value_bits = self._convert_into_bits(value_kilobytes)
self.id = 'KB'
def _convert_into_bits(self, value_kilobytes: int) -> int:
retur... |
class Credential:
"""
Class that generates new instances of Credentials .
"""
Credential_list = [] # Empty User list
def __init__(self,Account,user_name,password):
# docstring removed for simplicity
self.Account= Account
self.user_name = user_name
self.password ... | class Credential:
"""
Class that generates new instances of Credentials .
"""
credential_list = []
def __init__(self, Account, user_name, password):
self.Account = Account
self.user_name = user_name
self.password = password
def save__credential(self):
"""
... |
# Inheritance is used to share property and functionality across similar code.
# like car and 2 wheels
# It creates resuable code.
# Breaks code into hierarchy, more generics to more specific.
# Objects higher up in the hiearchy is more generics.
# Multiple inheritance is possible in Python.z
class Vehicle:
def _... | class Vehicle:
def __init__(self, make, model, fuel='gas'):
self.make = make
self.model = model
self.fuel = fuel
def is_eco_friendly(self):
if self.fuel == 'gas':
return True
else:
return False
class Car(Vehicle):
def __init__(self, make, m... |
"""Intialise the counter i=j=first element of array and pivot=last element of array
if array[j]< pivot swap array(i,j) and increment i
last swap array(i,pivot) element
this algorithm give in place 0(n) partitioning in 0(1) extra memory
"""
def pivot(array, a, b):
i = a
x = array[b - 1]
... | """Intialise the counter i=j=first element of array and pivot=last element of array
if array[j]< pivot swap array(i,j) and increment i
last swap array(i,pivot) element
this algorithm give in place 0(n) partitioning in 0(1) extra memory
"""
def pivot(array, a, b):
i = a
x = array[b - 1]
for j in ra... |
#########################################################
# Fred12 Setup the Head Servos
#########################################################
# We will be using the following services:
# Servo Service
#########################################################
# In Fred's head, we have a Servo to turn the head fr... | head_x = Runtime.createAndStart('headX', 'Servo')
headX.attach(head, 3)
headX.setMinMax(0, 180)
headX.map(0, 180, 1, 180)
headX.setRest(90)
headX.setInverted(True)
headX.setVelocity(60)
headX.setAutoDisable(True)
headX.rest()
jaw = Runtime.createAndStart('jaw', 'Servo')
jaw.attach(head, 2)
jaw.setMinMax(90, 165)
jaw.ma... |
# Done by Carlos Amaral (16/09/2020)
# SCU_2.7 - Modify a User-Defined Function
def my_function(x, y):
return (x+y)/2
x = 4
y = 5
print("The average is: ", my_function(x,y))
| def my_function(x, y):
return (x + y) / 2
x = 4
y = 5
print('The average is: ', my_function(x, y)) |
def fib(n):
if n < 0:
raise FibonacciError
elif n <= 2:
return 1
else:
return fib(n-1) + fib(n-2)
class FibonacciError(Exception):
pass
class FibTestClass:
pass
| def fib(n):
if n < 0:
raise FibonacciError
elif n <= 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
class Fibonaccierror(Exception):
pass
class Fibtestclass:
pass |
class Solution:
"""
@param A: an array
@return: divide the array into 3 non-empty parts
"""
def threeEqualParts(self, A):
total = A.count(1)
if total == 0:
return [0, 2]
if total % 3:
return [-1, -1]
k = total // 3
count = ... | class Solution:
"""
@param A: an array
@return: divide the array into 3 non-empty parts
"""
def three_equal_parts(self, A):
total = A.count(1)
if total == 0:
return [0, 2]
if total % 3:
return [-1, -1]
k = total // 3
count = 0
... |
"""Custom synapse-related classes."""
# Copyright 2020-2021 Blue Brain Project / EPFL
# 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
# Unle... | """Custom synapse-related classes."""
class Synapsemixin:
"""Class containing the synapse-related methods."""
def set_random_nmb_generator(self, sim, icell, sid):
"""Sets the random number generator.
Args:
sim (bluepyopt.ephys.NrnSimulator): neuron simulator
icell (neu... |
COLLECTION_NAME = "types"
TYPE_NAME_KEY = "name"
TYPE_VERSION_KEY = "version"
DEFAULT_TYPE_VERSION = 1
TYPE_COLLECTION_KEY = "collection"
TYPE_PRIMITIVE_VALUE = "primitive"
DEFAULT_TYPE_COLLECTION = TYPE_PRIMITIVE_VALUE
STRING_VALUE = "String"
NUMBER_VALUE = "Number"
def make_app_stack_type(type_name, **kwargs):
... | collection_name = 'types'
type_name_key = 'name'
type_version_key = 'version'
default_type_version = 1
type_collection_key = 'collection'
type_primitive_value = 'primitive'
default_type_collection = TYPE_PRIMITIVE_VALUE
string_value = 'String'
number_value = 'Number'
def make_app_stack_type(type_name, **kwargs):
a... |
# Autonr : Biswadeep Roy
# import os
''' thiple single quote is used to
do multiple line comments'''
print("Hello world")
| """ thiple single quote is used to
do multiple line comments"""
print('Hello world') |
class Box:
def __init__(self, xmin, xmax, ymin, ymax):
assert xmax > xmin >= 0, ("Got invalid box with xmin: {0} and xmax {1}".format(xmin, xmax))
assert ymax > ymin >= 0, ("Got invalid box with ymin: {0} and ymax {1}".format(ymin, ymax))
self._xmin = xmin
self._xmax = xmax
s... | class Box:
def __init__(self, xmin, xmax, ymin, ymax):
assert xmax > xmin >= 0, 'Got invalid box with xmin: {0} and xmax {1}'.format(xmin, xmax)
assert ymax > ymin >= 0, 'Got invalid box with ymin: {0} and ymax {1}'.format(ymin, ymax)
self._xmin = xmin
self._xmax = xmax
self... |
"""Session 2
Class, object, instance
Attributes, methods
Constructor, destructor
"""
class Object:
"""Object only has a defined attribute `name`
"""
def __init__(self, name='anonymous python object'):
"""Constructor performs initialization of the instances
of Object class.
"""
... | """Session 2
Class, object, instance
Attributes, methods
Constructor, destructor
"""
class Object:
"""Object only has a defined attribute `name`
"""
def __init__(self, name='anonymous python object'):
"""Constructor performs initialization of the instances
of Object class.
"""
... |
class FindShortestID:
__slots__ = 'short_id', 'new_id'
def __init__(self):
self.short_id = ''
self.new_id = None
def step(self, other_id, new_id):
self.new_id = new_id
for i in range(len(self.new_id)):
if other_id[i] != self.new_id[i]:
if i > len... | class Findshortestid:
__slots__ = ('short_id', 'new_id')
def __init__(self):
self.short_id = ''
self.new_id = None
def step(self, other_id, new_id):
self.new_id = new_id
for i in range(len(self.new_id)):
if other_id[i] != self.new_id[i]:
if i > l... |
BLACK_HEX = '000'
WHITE_HEX = 'fff'
IMG_BLUEHAT = "https://assets.imgix.net/examples/bluehat.jpg"
IMG_PINE = "https://sherwinski.imgix.net/pineneedles.jpg"
BROKEN_URL = "https://assets.imgix.net/examples/invalid"
INVALID_URL = "https://google.com"
CSS_BLUEHAT = """.image-fg-1 { color:#0d0c10 !important; } .image-bg-1 ... | black_hex = '000'
white_hex = 'fff'
img_bluehat = 'https://assets.imgix.net/examples/bluehat.jpg'
img_pine = 'https://sherwinski.imgix.net/pineneedles.jpg'
broken_url = 'https://assets.imgix.net/examples/invalid'
invalid_url = 'https://google.com'
css_bluehat = '.image-fg-1 { color:#0d0c10 !important; } .image-bg-1 { b... |
class PradamClass(object):
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, val):
if val.lower() == 'pradam':
print('Corrent Name.')
else:
rai... | class Pradamclass(object):
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, val):
if val.lower() == 'pradam':
print('Corrent Name.')
else:
raise ... |
'''MongoExceptions'''
class MongoExceptions(Exception):
def __init__(self, *args):
self.args = args
class NoDatabaseException(MongoExceptions):
def __init__(self, message = 'No such Database!', code = 422, args = ('No such Database!',)):
self.args = args
self.message = message
... | """MongoExceptions"""
class Mongoexceptions(Exception):
def __init__(self, *args):
self.args = args
class Nodatabaseexception(MongoExceptions):
def __init__(self, message='No such Database!', code=422, args=('No such Database!',)):
self.args = args
self.message = message
self... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
# Runtime: 1036 ms
... | class Solution(object):
def is_palindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
half1_ptr = head
half2_ptr = head
while half1_ptr.next is not None and half1_ptr.next.next is not None:
half1_ptr = half1_ptr.next.next
ha... |
# cook your dish here
test = int(input())
while test > 0 :
n = int(input())
l = list(map(int,input().split()))
l.sort()
count = 0
for i in range(n - 1) :
if l[i] == l[i + 1] :
print("NO")
break
else :
count += 1
if count == n - 1 :
prin... | test = int(input())
while test > 0:
n = int(input())
l = list(map(int, input().split()))
l.sort()
count = 0
for i in range(n - 1):
if l[i] == l[i + 1]:
print('NO')
break
else:
count += 1
if count == n - 1:
print('YES')
test -= 1 |
"""Binary Exponentiation."""
# Author : Junth Basnet
# Time Complexity : O(logn)
def binary_exponentiation(a, n):
if (n == 0):
return 1
elif (n % 2 == 1):
return binary_exponentiation(a, n - 1) * a
else:
b = binary_exponentiation(a, n / 2)
return b * b
if __name__ == ... | """Binary Exponentiation."""
def binary_exponentiation(a, n):
if n == 0:
return 1
elif n % 2 == 1:
return binary_exponentiation(a, n - 1) * a
else:
b = binary_exponentiation(a, n / 2)
return b * b
if __name__ == '__main__':
try:
base = int(input('Enter Base : ').... |
def mean(u):
if type(u) == dict:
the_mean = sum(u.values())/len(u)
else:
the_mean = sum(u) / len(u)
return the_mean
student_grades = {"Marry":9.8, "jhon":2.1, "Kayle":6.5}
mondey_temparature = [2,3,54,48,48,57]
print('This is a mean of a Dictonary',mean(student_grades))
print('This is a m... | def mean(u):
if type(u) == dict:
the_mean = sum(u.values()) / len(u)
else:
the_mean = sum(u) / len(u)
return the_mean
student_grades = {'Marry': 9.8, 'jhon': 2.1, 'Kayle': 6.5}
mondey_temparature = [2, 3, 54, 48, 48, 57]
print('This is a mean of a Dictonary', mean(student_grades))
print('Thi... |
#Filter Fucntion Example 2
def isVow(x):
if x=='a' or x=='e' or x=='i' or x=='o' or x=='u':
return True
def isCons(x):
if x!='a' and x!='e' and x!='i' and x!='o' and x!='u':
return True
print("Enter the letters:")
lst = [x for x in input().split()]
print('-'*40)
vowlist = list(f... | def is_vow(x):
if x == 'a' or x == 'e' or x == 'i' or (x == 'o') or (x == 'u'):
return True
def is_cons(x):
if x != 'a' and x != 'e' and (x != 'i') and (x != 'o') and (x != 'u'):
return True
print('Enter the letters:')
lst = [x for x in input().split()]
print('-' * 40)
vowlist = list(filter(isV... |
print(2**3)
print(2**3.)
print(2.**3)
print(2.**3.)
print(5//2)
print(2**2**3)
print(2*4)
print(2**4)
print(2.*4)
print(2**4.)
print(2/4)
print(2//4)
print(-2/4)
print(-2//4)
print(2%4)
print(2%-4) | print(2 ** 3)
print(2 ** 3.0)
print(2.0 ** 3)
print(2.0 ** 3.0)
print(5 // 2)
print(2 ** 2 ** 3)
print(2 * 4)
print(2 ** 4)
print(2.0 * 4)
print(2 ** 4.0)
print(2 / 4)
print(2 // 4)
print(-2 / 4)
print(-2 // 4)
print(2 % 4)
print(2 % -4) |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-AtmNetworkingMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-AtmNetworkingMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:29:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, value_range_constraint, constraints_intersection) ... |
class Agent(object):
"""Keeps relevant data of NPC and handles behavior."""
def __init__(self, name, hitpoints, strenght):
self.name = name
self.hitpoints = hitpoints
self.strenght = strenght
def move(self):
pass
def talk(self):
pass
def give_item(self):
... | class Agent(object):
"""Keeps relevant data of NPC and handles behavior."""
def __init__(self, name, hitpoints, strenght):
self.name = name
self.hitpoints = hitpoints
self.strenght = strenght
def move(self):
pass
def talk(self):
pass
def give_item(self):
... |
input = """
p(2) | f.
-p(1) :- true.
true.
:- f.
"""
output = """
p(2) | f.
-p(1) :- true.
true.
:- f.
"""
| input = '\np(2) | f.\n-p(1) :- true.\n\ntrue.\n:- f.\n'
output = '\np(2) | f.\n-p(1) :- true.\n\ntrue.\n:- f.\n' |
DIRECT_LINK_SCHEMA = {
"type": "object",
"properties": {
"local_file": {
"type": ["string", "null"],
"description": "local zip file path"
}
}
}
IMAGE_SCHEMA = {
"type": "object",
"properties": {
"original": {
"type": "file"
},
... | direct_link_schema = {'type': 'object', 'properties': {'local_file': {'type': ['string', 'null'], 'description': 'local zip file path'}}}
image_schema = {'type': 'object', 'properties': {'original': {'type': 'file'}, 'size': {'type': 'array', 'items': {'type': 'number'}}, 'custom_size': {'type': 'file', 'processors': [... |
#!/usr/bin/python3
""" BaseCaching module."""
class BaseCaching():
""" BaseCaching defines:
- constants of your caching system
- where your data are stored (in a dictionary)
"""
MAX_ITEMS = 4
def __init__(self):
"""Initiliaze."""
self.cache_data = {}
def print_cache(... | """ BaseCaching module."""
class Basecaching:
""" BaseCaching defines:
- constants of your caching system
- where your data are stored (in a dictionary)
"""
max_items = 4
def __init__(self):
"""Initiliaze."""
self.cache_data = {}
def print_cache(self):
""" Prin... |
# by usingt he above trick we see that kidney_data.gsms is a dictionary (you can validate this)
type(kidney_data.gsms)
# a dict is a container of key,value pairs. The values in this case are of the class GEOparse.GEOTypes.GSM
# e.g.
print(type(list(kidney_data.gsms.values())[0]))
## to get the available methods:
f... | type(kidney_data.gsms)
print(type(list(kidney_data.gsms.values())[0]))
fst = list(kidney_data.gsms.values())[0]
dir(fst)
fst.metadata |
def remove_smallest(n, lst):
if n <= 0:
return lst
elif n > len(lst):
return []
dex = [b[1] for b in sorted((a, i) for i, a in enumerate(lst))[:n]]
return [c for i, c in enumerate(lst) if i not in dex]
| def remove_smallest(n, lst):
if n <= 0:
return lst
elif n > len(lst):
return []
dex = [b[1] for b in sorted(((a, i) for (i, a) in enumerate(lst)))[:n]]
return [c for (i, c) in enumerate(lst) if i not in dex] |
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
rows = defaultdict(set)
cols = defaultdict(set)
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j]:
rows[i].add(j)
... | class Solution:
def count_servers(self, grid: List[List[int]]) -> int:
rows = defaultdict(set)
cols = defaultdict(set)
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j]:
rows[i].add(j)
... |
#https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/880/
#%%
input=-123
output=321
class Solution:
def reverse(self, x: int) -> int:
string=list(str(abs(x)))
string.reverse()
if x>=0:
temp=int(''.join(string)... | input = -123
output = 321
class Solution:
def reverse(self, x: int) -> int:
string = list(str(abs(x)))
string.reverse()
if x >= 0:
temp = int(''.join(string))
if temp > 2 ** 31 - 1:
return 0
else:
return temp
if x ... |
#py_list_comp_1.py
print([str(x)+"!" for x in [y for y in range(10)]])
| print([str(x) + '!' for x in [y for y in range(10)]]) |
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
max_index = 0
for index, num in enumerate(nums):
if num > nums[max_index]:
max_index = index
for index, num in enumerate(nums):
if index == max_index:
co... | class Solution:
def dominant_index(self, nums: List[int]) -> int:
max_index = 0
for (index, num) in enumerate(nums):
if num > nums[max_index]:
max_index = index
for (index, num) in enumerate(nums):
if index == max_index:
continue
... |
SCRIPT=r'''
import sys,time
fi=open(sys.argv[1])
time.sleep(8)
fo=open(sys.argv[2],'w')
fo.write(fi.read())
fi.close()
fo.close()
'''
| script = "\nimport sys,time\nfi=open(sys.argv[1])\ntime.sleep(8)\nfo=open(sys.argv[2],'w')\nfo.write(fi.read())\nfi.close()\nfo.close()\n" |
# SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries LLC
# SPDX-FileCopyrightText: 2021 James Carr
#
# SPDX-License-Identifier: MIT
"""
`adafruit_simplemath`
================================================================================
Math utility functions
* Author(s): Dan Halbert, J... | """
`adafruit_simplemath`
================================================================================
Math utility functions
* Author(s): Dan Halbert, James Carr
Implementation Notes
--------------------
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://gith... |
def dot(n,m):
r=['+'+'---+'*n]
for _ in range(m):
r.append('|'+' o |'*n)
r.append('+'+'---+'*n)
return '\n'.join(r) | def dot(n, m):
r = ['+' + '---+' * n]
for _ in range(m):
r.append('|' + ' o |' * n)
r.append('+' + '---+' * n)
return '\n'.join(r) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverTree(self, root: TreeNode) -> None:
# there are two nodes to find
self.nodes = []
self.inorder(root)
... | class Solution:
def recover_tree(self, root: TreeNode) -> None:
self.nodes = []
self.inorder(root)
(t1, t2) = (None, None)
for i in range(len(self.nodes) - 1):
if self.nodes[i + 1] < self.nodes[i]:
t1 = self.nodes[i + 1]
if t2 == None:
... |
def biggest_cycle_before(limit):
num = longest = 1
for n in range(3, limit, 2):
if n % 5 == 0:
continue
p = 1
while (10 ** p) % n != 1:
p += 1
if p > longest:
num, longest = n, p
print(num)
if __name__ == "__main__":
biggest_cycle_... | def biggest_cycle_before(limit):
num = longest = 1
for n in range(3, limit, 2):
if n % 5 == 0:
continue
p = 1
while 10 ** p % n != 1:
p += 1
if p > longest:
(num, longest) = (n, p)
print(num)
if __name__ == '__main__':
biggest_cycle_bef... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__version__ = "2.0.3"
__author__ = "Amir Zeldes"
__copyright__ = "Copyright 2015-2018, Amir Zeldes"
__license__ = "MIT License"
| __version__ = '2.0.3'
__author__ = 'Amir Zeldes'
__copyright__ = 'Copyright 2015-2018, Amir Zeldes'
__license__ = 'MIT License' |
t = int(input())
answer = []
for a in range(t):
n = int(input())
count = [0 for i in range(26)]
for j in range(n):
line = list(input())
for k in line:
count[ord(k)-97] += 1
ans = True
for k in count:
if(k%n != 0):
ans = False
break
... | t = int(input())
answer = []
for a in range(t):
n = int(input())
count = [0 for i in range(26)]
for j in range(n):
line = list(input())
for k in line:
count[ord(k) - 97] += 1
ans = True
for k in count:
if k % n != 0:
ans = False
break
... |
class LogSystem:
def __init__(self):
self.time_position_dict = {"Year": 0, "Month": 1,
"Day": 2, "Hour": 3,
"Minute": 4, "Second": 5}
self.logs = {}
def put(self, id, timestamp):
self.logs[timestamp] = id
def r... | class Logsystem:
def __init__(self):
self.time_position_dict = {'Year': 0, 'Month': 1, 'Day': 2, 'Hour': 3, 'Minute': 4, 'Second': 5}
self.logs = {}
def put(self, id, timestamp):
self.logs[timestamp] = id
def retrieve(self, s, e, gra):
retrieve_logs = []
need_lengt... |
a = 'AJisa'
a = a.upper()
print(a)
a = a.lower()
print(a)
n = "89*"
print(n.isnumeric())
print(n.isalpha()) | a = 'AJisa'
a = a.upper()
print(a)
a = a.lower()
print(a)
n = '89*'
print(n.isnumeric())
print(n.isalpha()) |
# pylint: skip-file
class GitRebase(GitCLI):
''' Class to wrap the git merge line tools
'''
# pylint: disable=too-many-arguments
def __init__(self,
path,
branch,
rebase_branch,
ssh_key=None):
''' Constructor for GitPush '''
... | class Gitrebase(GitCLI):
""" Class to wrap the git merge line tools
"""
def __init__(self, path, branch, rebase_branch, ssh_key=None):
""" Constructor for GitPush """
super(GitRebase, self).__init__(path, ssh_key=ssh_key)
self.path = path
self.branch = branch
self.re... |
"""Common values used for testing.
"""
SYSTEM_RAM_GB_MAIN = 64
SYSTEM_RAM_GB_SMALL = 2
SYSTEM_RAM_GB_TOO_SMALL = 1
OSM_PBF_GB_US = 10.4
OSM_PBF_GB_CO = 0.2
# Scaled below the 2GB threshold...
OSM_PBF_GB_USWEST = 1.99
# Should always use flat file, even w/out SSD
OSM_PBF_GB_ALWAYS_FLAT_FILE = 30.1 | """Common values used for testing.
"""
system_ram_gb_main = 64
system_ram_gb_small = 2
system_ram_gb_too_small = 1
osm_pbf_gb_us = 10.4
osm_pbf_gb_co = 0.2
osm_pbf_gb_uswest = 1.99
osm_pbf_gb_always_flat_file = 30.1 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: tag
short_description: Manage Tag objects of Tag
description:
- Returns the Tags for given filter criteria.
- Cre... | documentation = "\n---\nmodule: tag\nshort_description: Manage Tag objects of Tag\ndescription:\n- Returns the Tags for given filter criteria.\n- Creates Tag with specified Tag attributes.\n- Updates a Tag specified by id.\n- Deletes a Tag specified by id.\n- Returns Tag specified by Id.\n- Returns Tag count.\nversion_... |
# Acorn 2.0: Cocoa Butter
# Booleans are treated as integers
# Allow hex
#Number meta class
class N():
def __init__(self,n):
try:
self.n = float(n)
if(self.n.is_integer()):
self.n = int(n)
except:
self.n = int(n,16)
def N(self):
retur... | class N:
def __init__(self, n):
try:
self.n = float(n)
if self.n.is_integer():
self.n = int(n)
except:
self.n = int(n, 16)
def n(self):
return self.n
def __repr__(self):
return 'N(%s)' % self.n
class B:
def __init__... |
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
G = [0 for _ in range(n+1)]
G[0] = G[1] = 1
# 2...n
for i in range(2, n+1):
# 0...i
for j in range(1, i+1):
G[i] += G[j-1]*G[i-j]
r... | class Solution:
def num_trees(self, n):
"""
:type n: int
:rtype: int
"""
g = [0 for _ in range(n + 1)]
G[0] = G[1] = 1
for i in range(2, n + 1):
for j in range(1, i + 1):
G[i] += G[j - 1] * G[i - j]
return G[n] |
input = """
dummy.
c(0,0).
d :- c(_,a_long__but_still_nice_constant), dummy.
"""
output = """
dummy.
c(0,0).
d :- c(_,a_long__but_still_nice_constant), dummy.
"""
| input = '\ndummy.\nc(0,0).\n\nd :- c(_,a_long__but_still_nice_constant), dummy.\n'
output = '\ndummy.\nc(0,0).\n\nd :- c(_,a_long__but_still_nice_constant), dummy.\n' |
COM = ['wink', 'double blink', 'close your eyes', 'jump']
def commands(binary_str):
handshake = []
for couple in zip(binary_str[::-1],COM):
if couple[0] == '1':
handshake.append(couple[1])
if binary_str[0] == '1':
handshake = handshake[::-1]
return handshake
... | com = ['wink', 'double blink', 'close your eyes', 'jump']
def commands(binary_str):
handshake = []
for couple in zip(binary_str[::-1], COM):
if couple[0] == '1':
handshake.append(couple[1])
if binary_str[0] == '1':
handshake = handshake[::-1]
return handshake |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
u = set("abcdefghijklmnopqrstuvwxyz")
a = {"a", "b", "d", "i", "x"}
b = {"d", "e", "h", "i", "n", "u"}
c = {"e", "f", "m", "n"}
d = {"a", "c", "h", "k", "r", "s", "w", "x"}
bu = u.difference(b)
x = (a.difference(c)... | if __name__ == '__main__':
u = set('abcdefghijklmnopqrstuvwxyz')
a = {'a', 'b', 'd', 'i', 'x'}
b = {'d', 'e', 'h', 'i', 'n', 'u'}
c = {'e', 'f', 'm', 'n'}
d = {'a', 'c', 'h', 'k', 'r', 's', 'w', 'x'}
bu = u.difference(b)
x = a.difference(c).intersection(bu)
print(f'x = {x}')
ba = u.d... |
#List of constants accessed in our main transit_tracker.py script
#URL for downloading data
URL = 'https://www.psrc.org/sites/default/files/2014-hhsurvey.zip'
#list of age ranges used to make labels
AGE_RANGE_LIST = list(range(0,12))
#List of education ranges used to make labels
EDU_RANGE_LIST = list(range(0,7))
#Tool... | url = 'https://www.psrc.org/sites/default/files/2014-hhsurvey.zip'
age_range_list = list(range(0, 12))
edu_range_list = list(range(0, 7))
tools = 'pan,wheel_zoom,reset,poly_select,box_select,tap,box_zoom,save'
used_zips_psrc = ['98101', '98102', '98103', '98104', '98105', '98106', '98107', '98108', '98109', '98112', '9... |
class DestinationDirectoryError(Exception):
pass
def add_ssh_prefix(cmd: list[str], remote_host: str) -> list:
"""
Prefix a command with "ssh <remote_address>" for remote use
:param cmd: Command to be run remotely
:param remote_host: Remote machine address
:return: Command with prefix
"""
... | class Destinationdirectoryerror(Exception):
pass
def add_ssh_prefix(cmd: list[str], remote_host: str) -> list:
"""
Prefix a command with "ssh <remote_address>" for remote use
:param cmd: Command to be run remotely
:param remote_host: Remote machine address
:return: Command with prefix
"""
... |
SHARES = [
0.5, 0.6, 0.7, 0.8, 0.9,
0.91, 0.92, 0.93, 0.94,
0.95, 0.96, 0.97, 0.98,
0.99, 1.0
]
def pop(items):
return items[0], items[1:]
def get_quantiles(records, shares=SHARES):
if not shares:
return
counts = [count for _, count in records]
total = sum(counts)
acc... | shares = [0.5, 0.6, 0.7, 0.8, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0]
def pop(items):
return (items[0], items[1:])
def get_quantiles(records, shares=SHARES):
if not shares:
return
counts = [count for (_, count) in records]
total = sum(counts)
accumulator = 0
sha... |
'''
Probem Task : A number is said to be Harshad if it's exactly divisible by
the sum of its digits. Create a function that determines whether a number
is a Harshad or not.
Problem Link : https://edabit.com/challenge/Rrauvu8afRbjqPM8L
'''
sum=0
def harshad(n):
global sum
if(n>0):
rem=... | """
Probem Task : A number is said to be Harshad if it's exactly divisible by
the sum of its digits. Create a function that determines whether a number
is a Harshad or not.
Problem Link : https://edabit.com/challenge/Rrauvu8afRbjqPM8L
"""
sum = 0
def harshad(n):
global sum
if n > 0:
r... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 09:34:42 2018
@author: Manu
TYPES OF VARIABLES
"""
#***********STRINGS*******************
#%%
#Use formate in order to crate a template
name= "Manuel"
city= "Avila (Spain)"
template = "I'm {}, I live in {}".format(name,city)
print(template)
#%... | """
Created on Thu Aug 2 09:34:42 2018
@author: Manu
TYPES OF VARIABLES
"""
name = 'Manuel'
city = 'Avila (Spain)'
template = "I'm {}, I live in {}".format(name, city)
print(template)
str1 = "i'm programming in PYTHON"
print(str1.upper())
print(str1.lower())
print(str1.capitalize())
str2 = 'use split in order to se... |
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php or see LICENSE file.
# Copyright 2007-2008 Brisa Team <brisa-develop@garage.maemo.org>
""" Facilities for python properties generation.
"""
def gen_property_with_default(name, fget=None, fset=None, doc=""):
""" Generates a property... | """ Facilities for python properties generation.
"""
def gen_property_with_default(name, fget=None, fset=None, doc=''):
""" Generates a property of a name either with a default fget or a default
fset.
@param name: property name
@param fget: default fget
@param fset: default fset
@param doc: do... |
a,b = 10,20
print(a+b) #Output: 30
print(a*b) #Output: 200
print(b/a) #Output: 2.0
print(b%a) #Output: 0 | (a, b) = (10, 20)
print(a + b)
print(a * b)
print(b / a)
print(b % a) |
# -*- coding: utf-8 -*-
MSG_DATE_SEP = ">>>:"
END_MSG = "THEEND"
ALLOWED_KEYS = [
'q',
'e',
's',
'z',
'c',
'',
]
| msg_date_sep = '>>>:'
end_msg = 'THEEND'
allowed_keys = ['q', 'e', 's', 'z', 'c', ''] |
# coding: utf-8
class Service:
pass
| class Service:
pass |
""" https://adventofcode.com/2018/day/11 """
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return int(f.read())
def getPowerlevel(x, y, serial):
rackId = x + 10
powerLevel = (rackId * y + serial) * rackId
return (int(powerLevel / 100) % 10) - 5
def createGrid(... | """ https://adventofcode.com/2018/day/11 """
def read_file():
with open(f"{__file__.rstrip('code.py')}input.txt", 'r') as f:
return int(f.read())
def get_powerlevel(x, y, serial):
rack_id = x + 10
power_level = (rackId * y + serial) * rackId
return int(powerLevel / 100) % 10 - 5
def create_gr... |
class View(dict):
"""A View contains the content displayed in the main window."""
def __init__(self, d=None):
"""
View constructor.
Keyword arguments:
d=None: Initial keys and values to initialize the view with.
Regardless of the value of d, keys 'songs', 'artists' an... | class View(dict):
"""A View contains the content displayed in the main window."""
def __init__(self, d=None):
"""
View constructor.
Keyword arguments:
d=None: Initial keys and values to initialize the view with.
Regardless of the value of d, keys 'songs', 'artists' an... |
def search(list, platform):
for i in range(len(list)):
if list[i] == platform:
return True
return False
fruit = ['banana', 'grape', 'apple', 'plam']
print(fruit)
frut = input('input to see if it exists: ')
if search(fruit, frut):
print("fruit is found")
else:
print("fruiit does no... | def search(list, platform):
for i in range(len(list)):
if list[i] == platform:
return True
return False
fruit = ['banana', 'grape', 'apple', 'plam']
print(fruit)
frut = input('input to see if it exists: ')
if search(fruit, frut):
print('fruit is found')
else:
print('fruiit does not f... |
# -*- coding: utf-8 -*-
def theaudiodb_albumdetails(data):
if data.get('album'):
item = data['album'][0]
albumdata = {}
albumdata['album'] = item['strAlbum']
if item.get('intYearReleased',''):
albumdata['year'] = item['intYearReleased']
if item.get('strStyle','')... | def theaudiodb_albumdetails(data):
if data.get('album'):
item = data['album'][0]
albumdata = {}
albumdata['album'] = item['strAlbum']
if item.get('intYearReleased', ''):
albumdata['year'] = item['intYearReleased']
if item.get('strStyle', ''):
albumdata... |
class State:
state = {}
@staticmethod
def init():
State.state = {
"lowres_frames": None,
"highres_frames": None,
"photopath": "",
"frame": 0,
"current_photo": None,
"share_code": "",
"preview_image_width": 0,
... | class State:
state = {}
@staticmethod
def init():
State.state = {'lowres_frames': None, 'highres_frames': None, 'photopath': '', 'frame': 0, 'current_photo': None, 'share_code': '', 'preview_image_width': 0, 'photo_countdown': 0, 'reset_time': 0, 'upload_url': '', 'photo_url': '', 'api_key': ''}
... |
#!/usr/bin/env python3
"""Making a Box.
Create a function that creates a box based on dimension n.
Source:
https://edabit.com/challenge/dy3WWJr34gSGRPLee
"""
def make_box(n: int, character: str = '#') -> list:
"""Create a box on dimension n using character."""
box = []
for i in range(n):
if i i... | """Making a Box.
Create a function that creates a box based on dimension n.
Source:
https://edabit.com/challenge/dy3WWJr34gSGRPLee
"""
def make_box(n: int, character: str='#') -> list:
"""Create a box on dimension n using character."""
box = []
for i in range(n):
if i in (0, n - 1):
b... |
expected_output = {
'tracker_name': {
'tcp-10001': {
'status': 'UP',
'rtt_in_msec': 2,
'probe_id': 2
},
'udp-10001': {
'status': 'UP',
'rtt_in_msec': 1,
'probe_id': 3
}
}
}
| expected_output = {'tracker_name': {'tcp-10001': {'status': 'UP', 'rtt_in_msec': 2, 'probe_id': 2}, 'udp-10001': {'status': 'UP', 'rtt_in_msec': 1, 'probe_id': 3}}} |
"""
coax.exceptions
~~~~~~~~~~~~~~~
"""
class InterfaceError(Exception):
"""An interface error occurred."""
class ReceiveError(Exception):
"""A receive error occurred."""
class InterfaceTimeout(Exception):
"""The interface timed out."""
class ReceiveTimeout(Exception):
"""The receive operation timed... | """
coax.exceptions
~~~~~~~~~~~~~~~
"""
class Interfaceerror(Exception):
"""An interface error occurred."""
class Receiveerror(Exception):
"""A receive error occurred."""
class Interfacetimeout(Exception):
"""The interface timed out."""
class Receivetimeout(Exception):
"""The receive operation timed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.