content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
fd = open('Sales.txt','a')
fd.write("1111,Ashish,63278648732,1001,5 Star,5,4,20 \n")
fd.close()
| fd = open('Sales.txt', 'a')
fd.write('1111,Ashish,63278648732,1001,5 Star,5,4,20 \n')
fd.close() |
"""
Longest Palindromic Subsequence
Given a sequence, find the length of the longest palindromic subsequence in it.
Example :
Input:"bbbab"
Output:4
"""
def lps(s):
r = s[::-1]
n = len(s)
dp = [[0 for _ in range(n+1)] for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, n+1):
... | """
Longest Palindromic Subsequence
Given a sequence, find the length of the longest palindromic subsequence in it.
Example :
Input:"bbbab"
Output:4
"""
def lps(s):
r = s[::-1]
n = len(s)
dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):... |
def compact(lst):
return list(filter(bool,lst))
print(compact([0,1,False,True,2,'',3,'a','s',34]))
| def compact(lst):
return list(filter(bool, lst))
print(compact([0, 1, False, True, 2, '', 3, 'a', 's', 34])) |
class Solution:
"""
@param list: The coins
@param k: The k
@return: The answer
"""
def takeCoins(self, list, k):
# Write your code here
n = len(list)
presum = [0] * (1 + n)
for i in range(n):
presum[i + 1] = presum[i] + list[i]
ret... | class Solution:
"""
@param list: The coins
@param k: The k
@return: The answer
"""
def take_coins(self, list, k):
n = len(list)
presum = [0] * (1 + n)
for i in range(n):
presum[i + 1] = presum[i] + list[i]
return max((presum[i] + presum[n] - presum[n ... |
class Solution:
def uniqueMorseRepresentations(self, words: List[str]) -> int:
morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
transformations = set()... | class Solution:
def unique_morse_representations(self, words: List[str]) -> int:
morse = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..']
transformations = set()... |
def test_example_silver():
assert 567 == seat_id("BFFFBBFRRR")
assert 119 == seat_id("FFFBBBFRRR")
assert 820 == seat_id("BBFFBBFRLL")
def test_silver():
with open("input.txt") as file:
seats = file.read().split("\n")
assert 842 == max([seat_id(seat) for seat in seats])
def test_gold():... | def test_example_silver():
assert 567 == seat_id('BFFFBBFRRR')
assert 119 == seat_id('FFFBBBFRRR')
assert 820 == seat_id('BBFFBBFRLL')
def test_silver():
with open('input.txt') as file:
seats = file.read().split('\n')
assert 842 == max([seat_id(seat) for seat in seats])
def test_gold():
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def in_order_traverse_2(self, root, last_val) -> bool:
if root.left is None:
last_val.append(root.val)
else:... | class Solution:
def in_order_traverse_2(self, root, last_val) -> bool:
if root.left is None:
last_val.append(root.val)
else:
self.in_order_traverse_2(root.left, last_val)
last_val.append(root.val)
if root.right is None:
pass
else:
... |
hangman_txt = ("""
_________
|/
|
|
|
|
|
========""", """
_________
|/ |
|
|
|
|
|
... | hangman_txt = ('\n _________\n |/ \n | \n | \n | \n | \n | \n ========', '\n _________\n |/ | \n | \n | \n | \n | \n | ... |
"""Define battery utilities."""
BATTERY_STATE_OFF = "off"
BATTERY_STATE_ON = "on"
def calculate_binary_battery(value: float) -> str:
"""Calculate a "binary battery" value (OK/Low)."""
if value == 0:
return BATTERY_STATE_OFF
return BATTERY_STATE_ON
| """Define battery utilities."""
battery_state_off = 'off'
battery_state_on = 'on'
def calculate_binary_battery(value: float) -> str:
"""Calculate a "binary battery" value (OK/Low)."""
if value == 0:
return BATTERY_STATE_OFF
return BATTERY_STATE_ON |
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
size = len(s)
dp = [False] * (size + 1)
dp[0] = True
for i in range(1, size + 1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
... | class Solution:
def word_break(self, s: str, wordDict: List[str]) -> bool:
size = len(s)
dp = [False] * (size + 1)
dp[0] = True
for i in range(1, size + 1):
for j in range(i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
... |
# https://adventofcode.com/2018/day/3
total_overlaps = 0
fabric = {}
with open('./data.txt', 'r') as ffile:
data = ffile.read().strip().split('\n')
for data_row in data:
parts = data_row.split('@')
parts2 = parts[1].split(':')
left, top = parts2[0].split(',')
width, height = par... | total_overlaps = 0
fabric = {}
with open('./data.txt', 'r') as ffile:
data = ffile.read().strip().split('\n')
for data_row in data:
parts = data_row.split('@')
parts2 = parts[1].split(':')
(left, top) = parts2[0].split(',')
(width, height) = parts2[1].split('x')
width = i... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
def TicTacDraw(board):
n=len(board)
d={'0':'O','1':'X','2':' '}
for i in range(n):
s=' '
for j in range(n):
if j == (len(board[i])-1):
s=s+d[str(board[i][j])]
else:
s=s+d[str(board[i][j]... | def tic_tac_draw(board):
n = len(board)
d = {'0': 'O', '1': 'X', '2': ' '}
for i in range(n):
s = ' '
for j in range(n):
if j == len(board[i]) - 1:
s = s + d[str(board[i][j])]
else:
s = s + d[str(board[i][j])] + ' | '
if i == le... |
#import matplotlib.pyplot as plt
# import torch
# from torchvision import datasets, transforms
# import helper
# image = Image.open('new_digit.png')
# image = image.resize((400, 400))
# new_image.save('image_400.jpg')
results = ['a','b']
for ite, (brackets) in results:
print(ite)
print(brackets)
#print(c... | results = ['a', 'b']
for (ite, brackets) in results:
print(ite)
print(brackets) |
CONST_TIMED_ROTATING_FILE_HANDLER = 'TimedRotatingFileHandler'
CONST_SOCKET_HANDLER = 'SocketHandler'
CONST_FILE_HANDLER = 'FileHandler'
CONST_ROTATING_FILE_HANDLER = 'RotatingFileHandler'
CONST_STREAM_HANDLER = 'StreamHandler'
CONST_NULL_HANDLER = 'NullHandler'
CONST_WATCHED_FILE_HANDLER = 'WatchedFileHandler'
CONST_... | const_timed_rotating_file_handler = 'TimedRotatingFileHandler'
const_socket_handler = 'SocketHandler'
const_file_handler = 'FileHandler'
const_rotating_file_handler = 'RotatingFileHandler'
const_stream_handler = 'StreamHandler'
const_null_handler = 'NullHandler'
const_watched_file_handler = 'WatchedFileHandler'
const_d... |
def calc_pos(dna, temp):
n = len(dna)
m = len(temp)
pos = []
for i in range(n-m+1):
if dna[i:i+m] == temp:
pos.append(i+1)
return pos
fin = open('rosalind_subs.txt')
dna = fin.readline().strip()
temp = fin.readline().strip()
pos = calc_pos(dna, temp)
for i in pos:
print (i, end = " ")
print()
fin.close() | def calc_pos(dna, temp):
n = len(dna)
m = len(temp)
pos = []
for i in range(n - m + 1):
if dna[i:i + m] == temp:
pos.append(i + 1)
return pos
fin = open('rosalind_subs.txt')
dna = fin.readline().strip()
temp = fin.readline().strip()
pos = calc_pos(dna, temp)
for i in pos:
pri... |
fitbitSettings = {
'ClientID': '',
'ClientSecret':'',
'CallbackUrl': '',
'OAuthAuthorizeUri':'',
'OAuthAccessRefreshTokenRequestUri': '',
'LoggingApp':'FitbitDataImporter',
'LoggingDirectory':'',
'LogFileName': 'FitbitDataImport.log'
}
fitbitDataConfigSettings = []
HEART_RATE_SETTINGS = ... | fitbit_settings = {'ClientID': '', 'ClientSecret': '', 'CallbackUrl': '', 'OAuthAuthorizeUri': '', 'OAuthAccessRefreshTokenRequestUri': '', 'LoggingApp': 'FitbitDataImporter', 'LoggingDirectory': '', 'LogFileName': 'FitbitDataImport.log'}
fitbit_data_config_settings = []
heart_rate_settings = {'PrefixIndexName': 'fitbi... |
# -*- coding: utf-8 -*-
"""Untitled1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1c4ELojr5RJIgfRft7MhpjXDLvmoQLe-A
"""
R = 4
C = 4
# Function to print the required traversal
def counterClockspiralPrint(m, n, matrix) :
k = 0; l = 0
... | """Untitled1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1c4ELojr5RJIgfRft7MhpjXDLvmoQLe-A
"""
r = 4
c = 4
def counter_clockspiral_print(m, n, matrix):
k = 0
l = 0
count = 0
total = m * n
while k < m and l < n:
if ... |
"""Atomistic ToolKit (ATK)
Some useful tools in the daily life of atomistic simulations.
Maintained by Leopold Talirz (leopold.talirz@gmail.com)
"""
| """Atomistic ToolKit (ATK)
Some useful tools in the daily life of atomistic simulations.
Maintained by Leopold Talirz (leopold.talirz@gmail.com)
""" |
class UserResponse:
_raw_input = ""
_split_input = []
def __init__(self, prompt=""):
# get input with prompt
self._raw_input = input(prompt)
def get_key(self):
if self._raw_input == "":
return None
# if input is not null then slit it by space-characters an... | class Userresponse:
_raw_input = ''
_split_input = []
def __init__(self, prompt=''):
self._raw_input = input(prompt)
def get_key(self):
if self._raw_input == '':
return None
self._split_input = self._raw_input.split()
return self._split_input[0]
def get... |
def getMinimumUniqueSum(arr):
n = len(arr)
arr = sorted(arr)
unique = list(set(arr))
i = 0
if len(arr) != len(unique):
while len(arr) != len(unique):
temp = arr[i]
print(temp)
for j, item in enumerate(unique):
if temp == item:
... | def get_minimum_unique_sum(arr):
n = len(arr)
arr = sorted(arr)
unique = list(set(arr))
i = 0
if len(arr) != len(unique):
while len(arr) != len(unique):
temp = arr[i]
print(temp)
for (j, item) in enumerate(unique):
if temp == item:
... |
class Complex(object):
def __init__(self, real, image):
self.real = real
self.image = image
def __mul__(self, other):
return Complex(
self.real * other.real - self.image * other.image,
self.real * other.image + self.image * other.real
)
def __str__(s... | class Complex(object):
def __init__(self, real, image):
self.real = real
self.image = image
def __mul__(self, other):
return complex(self.real * other.real - self.image * other.image, self.real * other.image + self.image * other.real)
def __str__(self):
return '%d+%di' % (... |
# -*- coding: utf-8 -*-
__version__ = "1.0"
__author__ = "Kacper Kowalik"
| __version__ = '1.0'
__author__ = 'Kacper Kowalik' |
"""
URIs templates for resources exposed by the Weather API 2.5
"""
ICONS_BASE_URL = 'http://openweathermap.org/img/w/%s.png'
| """
URIs templates for resources exposed by the Weather API 2.5
"""
icons_base_url = 'http://openweathermap.org/img/w/%s.png' |
"""
PASSENGERS
"""
numPassengers = 26795
passenger_arriving = (
(4, 8, 6, 6, 2, 1, 1, 5, 5, 0, 0, 2, 0, 12, 5, 4, 3, 5, 7, 4, 0, 3, 4, 0, 1, 0), # 0
(12, 11, 10, 11, 6, 5, 4, 4, 3, 1, 0, 0, 0, 8, 5, 6, 5, 4, 4, 1, 2, 2, 1, 1, 0, 0), # 1
(5, 10, 9, 10, 2, 3, 5, 2, 3, 2, 1, 0, 0, 14, 11, 5, 1, 8, 3, 4, 1, 4, 4, 1... | """
PASSENGERS
"""
num_passengers = 26795
passenger_arriving = ((4, 8, 6, 6, 2, 1, 1, 5, 5, 0, 0, 2, 0, 12, 5, 4, 3, 5, 7, 4, 0, 3, 4, 0, 1, 0), (12, 11, 10, 11, 6, 5, 4, 4, 3, 1, 0, 0, 0, 8, 5, 6, 5, 4, 4, 1, 2, 2, 1, 1, 0, 0), (5, 10, 9, 10, 2, 3, 5, 2, 3, 2, 1, 0, 0, 14, 11, 5, 1, 8, 3, 4, 1, 4, 4, 1, 2, 0), (6, 9, ... |
# --------------------------------------------------------------------------
# Basic generation of the Fibonacci number sequence written in Python
# link: https://www.mycompiler.io/view/6S2zX4i
# author: milk
# --------------------------------------------------------------------------
# python fibonacci.py # to ... | count = 100
a = 0
b = 0
c = 1
i = 0
while i <= count:
print(c)
a = b
b = c
c = a + b
i += 1 |
#!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the f... | def outlier_cleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth... |
MATCHING_TICKETS_KEYS = ['id', 'category', 'status', 'date', 'price_id', 'quantity',
'section', 'row', 'remarks', 'user_id', 'username', 'updated_at']
MATCHING_TICKETS = '''
SELECT src.id, src.category, src.status, src.`date`, src.price_id, src.quantity, src.section, src.row, src.remarks, src.u... | matching_tickets_keys = ['id', 'category', 'status', 'date', 'price_id', 'quantity', 'section', 'row', 'remarks', 'user_id', 'username', 'updated_at']
matching_tickets = '\nSELECT src.id, src.category, src.status, src.`date`, src.price_id, src.quantity, src.section, src.row, src.remarks, src.user_id, src.username, src.... |
description = 'Beam limiter at position 1'
group = 'lowlevel'
display_order = 25
pvprefix = 'SQ:ICON:board1:'
devices = dict(
bl1left = device('nicos_ess.devices.epics.motor.HomingProtectedEpicsMotor',
epicstimeout = 3.0,
description = 'Beam limiter 1 -X',
motorpv = pvprefix + 'B1nX',
... | description = 'Beam limiter at position 1'
group = 'lowlevel'
display_order = 25
pvprefix = 'SQ:ICON:board1:'
devices = dict(bl1left=device('nicos_ess.devices.epics.motor.HomingProtectedEpicsMotor', epicstimeout=3.0, description='Beam limiter 1 -X', motorpv=pvprefix + 'B1nX', errormsgpv=pvprefix + 'B1nX-MsgTxt', precis... |
class Counter:
def __init__(self,low,high):
self.current = low
self.last = high
def __iter__(self):
return self #instead of: return iter("...") - this way 'self' here is set up with 'next' below
def __next__(self): # here we define __next__ because the 'self' returned from the __iter__ above is not an iterat... | class Counter:
def __init__(self, low, high):
self.current = low
self.last = high
def __iter__(self):
return self
def __next__(self):
if self.current < self.last:
num = self.current
self.current += 1
return num
raise StopIteratio... |
""" Asked by: Flipkart [Medium].
Snakes and Ladders is a game played on a 10 x 10 board, the goal of which is get from square 1 to square 100.
On each turn players will roll a six-sided die and move forward a number of spaces equal to the result.
If they land on a square that represents a snake or ladder, they will ... | """ Asked by: Flipkart [Medium].
Snakes and Ladders is a game played on a 10 x 10 board, the goal of which is get from square 1 to square 100.
On each turn players will roll a six-sided die and move forward a number of spaces equal to the result.
If they land on a square that represents a snake or ladder, they will ... |
test = { 'name': 'q3c',
'points': 2,
'suites': [ { 'cases': [ {'code': '>>> independents_with_ratings.num_rows == 91\nTrue', 'hidden': False, 'locked': False},
{ 'code': ">>> independents_with_ratings.labels == ('Rank', 'Restaurant', 'Sales', 'Average Check', 'City',... | test = {'name': 'q3c', 'points': 2, 'suites': [{'cases': [{'code': '>>> independents_with_ratings.num_rows == 91\nTrue', 'hidden': False, 'locked': False}, {'code': ">>> independents_with_ratings.labels == ('Rank', 'Restaurant', 'Sales', 'Average Check', 'City', 'State', 'Meals Served', 'Rating')\nTrue", 'hidden': Fals... |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """Utilities for testing Apple rules."""
def apple_multi_shell_test(name, src, configurations={}, **kwargs):
"""Creates test targets for an Apple shell integration test script.
This macro allows for the easy creation of multiple test targets that each
run the given test script, but with different configuratio... |
def test_assert_false():
assert False, 'The assert should fail' # xfail
def test_assert_passed():
assert True, 'The assert should pass'
| def test_assert_false():
assert False, 'The assert should fail'
def test_assert_passed():
assert True, 'The assert should pass' |
#Dictionary:
Dict={1:'Hi','name': 'Hello',3:'how are you?'}
#accessing a element using key
print(f'Accessing a element using a key: {Dict["name"]}')
#accessing a element using key
print(f'Accessing an element using a key: {Dict[1]}')
#accessing a element using get()
print(f'Accessing an element using get()... | dict = {1: 'Hi', 'name': 'Hello', 3: 'how are you?'}
print(f"Accessing a element using a key: {Dict['name']}")
print(f'Accessing an element using a key: {Dict[1]}')
print(f'Accessing an element using get(): {Dict.get(3)}')
dict = {'Dict1': {1: 'Hey'}, 'Dict2': {1: "What's up?", 2: "Yo, let's party"}}
print(f'Nested Dic... |
class AumbryError(Exception):
def __init__(self, message):
self.message = message
super(AumbryError, self).__init__(message)
class LoadError(AumbryError):
pass
class SaveError(AumbryError):
pass
class ParsingError(AumbryError):
pass
class DependencyError(AumbryError):
def __i... | class Aumbryerror(Exception):
def __init__(self, message):
self.message = message
super(AumbryError, self).__init__(message)
class Loaderror(AumbryError):
pass
class Saveerror(AumbryError):
pass
class Parsingerror(AumbryError):
pass
class Dependencyerror(AumbryError):
def __ini... |
# Creamos un objeto como si fuese JSON
{
# targets son los objetivos donde va a tener que hacer la complilacion, como son mas de uno los ponemos en un array por ahroa un elemento!
"targets": [
{
# le ponemos el nombr que deseemos a nuestro modulo
"target_name" : "addon",
... | {'targets': [{'target_name': 'addon', 'sources': ['hola.cc']}]} |
"""Custom exceptions classes"""
class CoatiException(Exception):
pass
class CLIException(CoatiException):
pass
| """Custom exceptions classes"""
class Coatiexception(Exception):
pass
class Cliexception(CoatiException):
pass |
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
try:
return nums.index(target)
except:
return -1
| class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
try:
return nums.index(target)
except:
return -1 |
@kernel
def sample(device, data, samples, wait):
for i in range(samples):
try:
device.sample_mu(data[i])
delay(wait)
except RTIOUnderflow:
continue
@kernel(flags={"fast-math"})
def ramp(board, channels, starts, stops, steps, duration, now):
at_mu(now)
dt ... | @kernel
def sample(device, data, samples, wait):
for i in range(samples):
try:
device.sample_mu(data[i])
delay(wait)
except RTIOUnderflow:
continue
@kernel(flags={'fast-math'})
def ramp(board, channels, starts, stops, steps, duration, now):
at_mu(now)
dt ... |
# Version is set for releases by our build system.
# Be extremely careful when modifying.
version = 'SNAPSHOT'
"""DC/OS version"""
| version = 'SNAPSHOT'
'DC/OS version' |
# Copyright (c) 2018-Present Advanced Micro Devices, Inc. See LICENSE.TXT for terms.
#!/usr/bin/evn python3
# tvals = [8, 16, 32, 64, 128, 256]
# nw_args = {f'-s {s} -t {t}':[] for s in [16384, 32768] for t in tvals}
# lud_args = {f'-s {s} -t {t}':[] for s in [16384, 8192] for t in tvals}
gEnvVars = {
'ATMI_D... | g_env_vars = {'ATMI_DEVICE_GPU_WORKERS': {'full': [1, 4, 8, 16, 24, 32], 'default': [1]}, 'ATMI_DEPENDENCY_SYNC_TYPE': {'full': ['ATMI_SYNC_CALLBACK', 'ATMI_SYNC_BARRIER_PKT'], 'default': ['ATMI_SYNC_CALLBACK']}, 'ATMI_MAX_HSA_SIGNALS': {'full': [32, 64, 128, 256, 512, 1024, 2048, 4096], 'default': [1024]}}
benchmarks ... |
#!/usr/bin/env python3
def fibonacci(n):
fib = [1, 1]
if n <= 2:
return fib
for num in range(2, n):
x = fib[num-1] + fib[num-2]
fib.append(x)
return fib
if __name__ == "__main__":
print(fibonacci(10))
| def fibonacci(n):
fib = [1, 1]
if n <= 2:
return fib
for num in range(2, n):
x = fib[num - 1] + fib[num - 2]
fib.append(x)
return fib
if __name__ == '__main__':
print(fibonacci(10)) |
number = float(input())
intervalos = ["[0,25]", "(25,50]", "(50,75]", "(75,100]"]
if(number < 0 or number > 100):
print("Fora de intervalo")
else:
if(number <= 25):
print("Intervalo", intervalos[0])
else:
if(number <= 50):
print("Intervalo", intervalos[1])
else:
if(number <= 75):
print("Intervalo", i... | number = float(input())
intervalos = ['[0,25]', '(25,50]', '(50,75]', '(75,100]']
if number < 0 or number > 100:
print('Fora de intervalo')
elif number <= 25:
print('Intervalo', intervalos[0])
elif number <= 50:
print('Intervalo', intervalos[1])
elif number <= 75:
print('Intervalo', intervalos[2])
elif ... |
input = """
a v b.
:- b.
a v x v y :- x.
x v y :- y.
:- not x, not y.
"""
output = """
"""
| input = '\na v b.\n:- b.\n\na v x v y :- x.\nx v y :- y.\n\n:- not x, not y.\n'
output = '\n' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: b.lin@mfm.tu-darmstadt.de
"""
def WriteMesh(num_f,name):
inp=open("SaveSurfaceMesh.geo",'w+')
val = str("SaveSurfaceMesh")
for i in range(int(num_f)):
inp.write(" Merge \"%s_%i.stl\"; \n" %(val,i+1))
for i in range(int(num_f)):
... | """
@author: b.lin@mfm.tu-darmstadt.de
"""
def write_mesh(num_f, name):
inp = open('SaveSurfaceMesh.geo', 'w+')
val = str('SaveSurfaceMesh')
for i in range(int(num_f)):
inp.write(' Merge "%s_%i.stl"; \n' % (val, i + 1))
for i in range(int(num_f)):
inp.write('Surface Loop' + '(' + str(i ... |
"""Solution to 1.6: String Compression."""
def compress(string):
"""Creates a compressed string using repeat characters.
Args:
string_one: any string to be compressed.
Returns:
A compressed version of the input based on repeat occurences
Raises:
ValueError: string input ... | """Solution to 1.6: String Compression."""
def compress(string):
"""Creates a compressed string using repeat characters.
Args:
string_one: any string to be compressed.
Returns:
A compressed version of the input based on repeat occurences
Raises:
ValueError: string input i... |
{
"targets": [
{
"target_name": "iow_sht7x",
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"sources": [ "./src/iow_sht7x.cpp", "./src/sht7x.cpp" ],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")",
"./src/",
"/usr... | {'targets': [{'target_name': 'iow_sht7x', 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'sources': ['./src/iow_sht7x.cpp', './src/sht7x.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")', './src/', '/usr/include'], 'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS'], 'link_settings... |
# Default config_dict
default_config_dict = {"MAIN": {}, "GUI": {}, "PLOT": {}}
default_config_dict["MAIN"]["MACHINE_DIR"] = ""
default_config_dict["MAIN"]["MATLIB_DIR"] = ""
default_config_dict["GUI"]["UNIT_M"] = 1 # length unit: 0 for m, 1 for mm
default_config_dict["GUI"]["UNIT_M2"] = 1 # Surface unit: 0 for m^2... | default_config_dict = {'MAIN': {}, 'GUI': {}, 'PLOT': {}}
default_config_dict['MAIN']['MACHINE_DIR'] = ''
default_config_dict['MAIN']['MATLIB_DIR'] = ''
default_config_dict['GUI']['UNIT_M'] = 1
default_config_dict['GUI']['UNIT_M2'] = 1
default_config_dict['PLOT']['COLOR_DICT_NAME'] = 'pyleecan_color.json'
default_confi... |
"""
File: hailstone.py
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, as defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
"""
Calculate the num... | """
File: hailstone.py
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, as defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
"""
Calculate the numb... |
# 1. --------------------------------------
# 1. 1.1 * radiance = 1.1
# 2. 1.1 - 0.5 = 0.6
# 3. min(randiance, 0.6) = 0.6
# 4. 2.0 + 0.6 = 2.6
# 5. max(2.1, 2.6) = 2.6
# 2. --------------------------------------
radiance = 1.0
radiance = max(2.1, 2.0 + min(radiance, 1.1 * radiance - 0.5))
print(radiance) | radiance = 1.0
radiance = max(2.1, 2.0 + min(radiance, 1.1 * radiance - 0.5))
print(radiance) |
class Solution:
def bubble_sort(self, arr):
bub_flag = 1 # bubbling will occur until finished i.e. until flag not set
while bub_flag == 1:
bub_flag = 0 # reset flag on each pass
for i in range(0, len(arr)-1): # iterate over all elements
j = i+1
if arr[j] < arr[i]: # IF not in ascending order
... | class Solution:
def bubble_sort(self, arr):
bub_flag = 1
while bub_flag == 1:
bub_flag = 0
for i in range(0, len(arr) - 1):
j = i + 1
if arr[j] < arr[i]:
(arr[i], arr[j]) = (arr[j], arr[i])
bub_flag = 1
... |
class Singleton( type ) :
_instances = {}
def __call__( aClass , * aArgs , **kwargs ) :
if aClass not in aClass._instances:
aClass._instances[aClass] = super(Singleton , aClass).__call__(*aArgs , **kwargs)
return aClass._instances[aClass] | class Singleton(type):
_instances = {}
def __call__(aClass, *aArgs, **kwargs):
if aClass not in aClass._instances:
aClass._instances[aClass] = super(Singleton, aClass).__call__(*aArgs, **kwargs)
return aClass._instances[aClass] |
# Krishan Patel
# Bank Account Class
"""Chaper 14: Objects
From Hello World! Computer Programming for Kids and Beginners
Copyright Warren and Carter Sande, 2009-2013
"""
# Chapter 14 - Try it out
class BankAccount:
"""Creates a bank account"""
def __init__(self, name, account_number):
self.name = name... | """Chaper 14: Objects
From Hello World! Computer Programming for Kids and Beginners
Copyright Warren and Carter Sande, 2009-2013
"""
class Bankaccount:
"""Creates a bank account"""
def __init__(self, name, account_number):
self.name = name
self.account_number = account_number
self.bala... |
mark = float(input("Inserire voto: "))
if mark < .35:
print("F")
elif mark < .85:
print("D-")
elif mark < 1.15:
print("D")
elif mark < 1.50:
print("D+")
elif mark < 1.85:
print("C-")
elif mark < 2.15:
print("C")
elif mark < 2.50:
print("C+")
elif mark < 2.85:
print("B-")
elif mark < 3.1... | mark = float(input('Inserire voto: '))
if mark < 0.35:
print('F')
elif mark < 0.85:
print('D-')
elif mark < 1.15:
print('D')
elif mark < 1.5:
print('D+')
elif mark < 1.85:
print('C-')
elif mark < 2.15:
print('C')
elif mark < 2.5:
print('C+')
elif mark < 2.85:
print('B-')
elif mark < 3.15... |
class Solution:
def reverseStr(self, s: str, k: int) -> str:
s = list(s)
head = 0
jump = 2*k
while head < len(s):
start, end = head, min(head + k-1, len(s)-1)
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
... | class Solution:
def reverse_str(self, s: str, k: int) -> str:
s = list(s)
head = 0
jump = 2 * k
while head < len(s):
(start, end) = (head, min(head + k - 1, len(s) - 1))
while start < end:
(s[start], s[end]) = (s[end], s[start])
... |
class Solution:
def multiply(self, num1: str, num2: str) -> str:
n1 = len(num1)
n2 = len(num2)
if not n1 or not n2:
return ""
if n1 == 1 and num1[0] == '0':
return "0"
if n2 == 1 and num2[0] == '0':
return "0"
# arr_num1 = list(reve... | class Solution:
def multiply(self, num1: str, num2: str) -> str:
n1 = len(num1)
n2 = len(num2)
if not n1 or not n2:
return ''
if n1 == 1 and num1[0] == '0':
return '0'
if n2 == 1 and num2[0] == '0':
return '0'
arr_num1 = list(map(l... |
c=1
menor = 9999
while True:
numero =int(input())
#condicion para obtener el menor
if numero < menor and numero != 0:
menor = numero
#condicion para detener el bucle
if numero ==0:
break
c=c+1
print("Menor:",menor) | c = 1
menor = 9999
while True:
numero = int(input())
if numero < menor and numero != 0:
menor = numero
if numero == 0:
break
c = c + 1
print('Menor:', menor) |
#!/usr/bin/python3
"""
Say my name module
"""
def say_my_name(first_name, last_name=""):
""" Prints name """
if not isinstance(first_name, str):
raise TypeError("first_name must be a string")
if not isinstance(last_name, str):
raise TypeError("last_name must be a string")
try:
... | """
Say my name module
"""
def say_my_name(first_name, last_name=''):
""" Prints name """
if not isinstance(first_name, str):
raise type_error('first_name must be a string')
if not isinstance(last_name, str):
raise type_error('last_name must be a string')
try:
print('My name is ... |
class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
raise Exception("Empty Array")
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
# loop arr[0:N - 1]
dp_0 = [0] * len(nums)
dp_0[0]... | class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
raise exception('Empty Array')
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
dp_0 = [0] * len(nums)
dp_0[0] = nums[0]
dp_0[1] =... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class FreeObject(object):
pass
class Solution:
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def addTwoNumbers(self, l1, l2):
bk = l3... | class Freeobject(object):
pass
class Solution:
def add_two_numbers(self, l1, l2):
bk = l3 = free_object()
rest = 0
while l1 or l2 or rest:
su = (l1.val if l1 else 0) + (l2.val if l2 else 0) + rest
l3.next = list_node(su % 10)
rest = (0, 1)[su >= 10]
... |
# from adventofcode._2020.day11.challenge import main
def test_input():
pass
| def test_input():
pass |
def largest_prime_factor(number):
factor = 2
while number != 1:
if number % factor == 0:
number /= factor
else:
factor += 1
return factor
| def largest_prime_factor(number):
factor = 2
while number != 1:
if number % factor == 0:
number /= factor
else:
factor += 1
return factor |
class TempAndHumidityData:
""" Captures temperature and humidity data """
def __init__(self, temperature, humidity):
self.temperature = temperature
self.humidity = humidity
def __str__(self):
return 'temperature={}, humidity={}'.format(self.temperature, self.humidity)
| class Tempandhumiditydata:
""" Captures temperature and humidity data """
def __init__(self, temperature, humidity):
self.temperature = temperature
self.humidity = humidity
def __str__(self):
return 'temperature={}, humidity={}'.format(self.temperature, self.humidity) |
class Solution:
def coinChange(self, coins, amount):
if amount == 0:
return 0
dp = [2 << 63] * (amount + 1)
for coin in coins:
if coin <= amount:
dp[coin] = 1
for i in range(1, amount + 1):
for j in range(len(coins)):
... | class Solution:
def coin_change(self, coins, amount):
if amount == 0:
return 0
dp = [2 << 63] * (amount + 1)
for coin in coins:
if coin <= amount:
dp[coin] = 1
for i in range(1, amount + 1):
for j in range(len(coins)):
... |
val = input()
matsubi = val[-1:]
if matsubi == "s":
val2 = val + "es"
else:
val2 = val + "s"
print(val2)
| val = input()
matsubi = val[-1:]
if matsubi == 's':
val2 = val + 'es'
else:
val2 = val + 's'
print(val2) |
"""
Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
Sample String : 'General12'
Expected Result : 'Ge12'
Sample String : 'Ka'
Expected Result : 'KaKa'
Sample String : 'K'... | """
Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
Sample String : 'General12'
Expected Result : 'Ge12'
Sample String : 'Ka'
Expected Result : 'KaKa'
Sample String : 'K'... |
begin_unit
comment|'# Copyright 2010 United States Government as represented by the'
nl|'\n'
comment|'# Administrator of the National Aeronautics and Space Administration.'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); ... | begin_unit
comment | '# Copyright 2010 United States Government as represented by the'
nl | '\n'
comment | '# Administrator of the National Aeronautics and Space Administration.'
nl | '\n'
comment | '# All Rights Reserved.'
nl | '\n'
comment | '#'
nl | '\n'
comment | '# Licensed under the Apache License, Version 2.0... |
# -*- coding: utf-8 -*-
# @Time : 2020/8/26-19:48
# @Author : TuringEmmy
# @Email : yonglonggeng@163.com
# @WeChat : csy_lgy
# @File : height_weight.py
# @Project : Happy-Algorithm
def first():
times = int(input())
height = input().split()
weight = input().split()
heights = [int(i) ... | def first():
times = int(input())
height = input().split()
weight = input().split()
heights = [int(i) for i in height]
weights = [int(i) for i in weight]
data_list = [[i + 1, heights[i], weights[i]] for i in range(times)]
sor = lambda x: x[0]
sor(data_list)
print(data_list)
def seco... |
# Turtle topic name and type key constant
KEY_TOPIC_MSG_TYPE = 'msg_type'
KEY_TOPIC_NAME = 'name'
# Logging frequency in seconds
LOG_FREQUENCY = 10
# Publisher/Subscriber Queue size
QUEUE_SIZE = 10
# Set angle and distance thresholds
ANGULAR_DIST_THRESHOLD = 0.05
LINEAR_DIST_THRESHOLD = 0.05
| key_topic_msg_type = 'msg_type'
key_topic_name = 'name'
log_frequency = 10
queue_size = 10
angular_dist_threshold = 0.05
linear_dist_threshold = 0.05 |
config = {
"interfaces": {
"google.cloud.websecurityscanner.v1alpha.WebSecurityScanner": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": [],
},
"retry_params": {
"default": {
... | config = {'interfaces': {'google.cloud.websecurityscanner.v1alpha.WebSecurityScanner': {'retry_codes': {'idempotent': ['DEADLINE_EXCEEDED', 'UNAVAILABLE'], 'non_idempotent': []}, 'retry_params': {'default': {'initial_retry_delay_millis': 100, 'retry_delay_multiplier': 1.3, 'max_retry_delay_millis': 60000, 'initial_rpc_... |
infile=open('baublesin.txt','r').readline()
ro,bo,s,rp,bp=map(int,infile.split())
answer=0
r=ro-rp
b=bo-bp
if s==0:
if r<0 or b<0:
answer=0
elif r>=b:
if bo==0 or bp==0:
answer+=r+1
else:
answer+=b+1
elif b>r:
if ro==0 or rp==0:
... | infile = open('baublesin.txt', 'r').readline()
(ro, bo, s, rp, bp) = map(int, infile.split())
answer = 0
r = ro - rp
b = bo - bp
if s == 0:
if r < 0 or b < 0:
answer = 0
elif r >= b:
if bo == 0 or bp == 0:
answer += r + 1
else:
answer += b + 1
elif b > r:
... |
# Symbol of circle required to show Celsius degree on display.
circle = [
[0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
... | circle = [[0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] |
#
# PySNMP MIB module SONUS-NODE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONUS-NODE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:09:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) ... |
r"""
Crystals
========
Quickref
--------
.. TODO:: Write it!
Introductory material
---------------------
- :ref:`sage.combinat.crystals.crystals`
- The `Lie Methods and Related Combinatorics <../../../../../thematic_tutorials/lie.html>`_ thematic tutorial
Catalogs of crystals
--------------------
- :ref:`sage.com... | """
Crystals
========
Quickref
--------
.. TODO:: Write it!
Introductory material
---------------------
- :ref:`sage.combinat.crystals.crystals`
- The `Lie Methods and Related Combinatorics <../../../../../thematic_tutorials/lie.html>`_ thematic tutorial
Catalogs of crystals
--------------------
- :ref:`sage.comb... |
# Lesson2: Operators with strings
# source: code/strings_operators.py
a = 'hello'
b = 'class'
c = ''
c = a + b
print(c)
c = a * 5
print(c)
c = 10 * b
print(c) | a = 'hello'
b = 'class'
c = ''
c = a + b
print(c)
c = a * 5
print(c)
c = 10 * b
print(c) |
# CPU: 0.05 s
instructions = input()
nop_count = 0
idx = 0
for char in instructions:
if char.isupper() and idx % 4 != 0:
add = 4 * (idx // 4 + 1) - idx
idx += add
nop_count += add
idx += 1
print(nop_count)
| instructions = input()
nop_count = 0
idx = 0
for char in instructions:
if char.isupper() and idx % 4 != 0:
add = 4 * (idx // 4 + 1) - idx
idx += add
nop_count += add
idx += 1
print(nop_count) |
#
# PySNMP MIB module BayNetworks-AHB-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BayNetworks-AHB-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:25:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint, constraints_union) ... |
a = [1, 2, 3]
a.append(4)
a
a.extend(5)
a
a.extend([5])
a
a.insert(10, 3)
a
a.insert(3, 10)
a
a = [1, 2, 3]
a
a.append(4)
a
a.append(5)
a
a.extend([6, 7])
a
a.extend(8)
help(a.insert)
a.insert(0, 10)
a
a.insert(2, 12)
a
a.remove(10)
a
a.remove(12)
a
a.append(1)
a
a.remove(1)
a
a.remove(1)
a
a.pop(0)
a
a.pop(1)
a
a = [1... | a = [1, 2, 3]
a.append(4)
a
a.extend(5)
a
a.extend([5])
a
a.insert(10, 3)
a
a.insert(3, 10)
a
a = [1, 2, 3]
a
a.append(4)
a
a.append(5)
a
a.extend([6, 7])
a
a.extend(8)
help(a.insert)
a.insert(0, 10)
a
a.insert(2, 12)
a
a.remove(10)
a
a.remove(12)
a
a.append(1)
a
a.remove(1)
a
a.remove(1)
a
a.pop(0)
a
a.pop(1)
a
a = [1... |
# *****************************************************************************
# Copyright 2004-2008 Steve Menard
#
# 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
#
# htt... | class Windowadapter(object):
def __init__(self, *mth, **kw):
object.__init__(self)
for (i, j) in kw.items():
setattr(self, i, j)
def window_activated(self, e):
pass
def window_closed(self, e):
pass
def window_closing(self, e):
pass
def window_... |
def run():
@_core.listen('test')
def _():
print('a test 2')
@_core.on('test')
def _():
print('a test')
_emit('test')
_emit('test')
_emit('test')
| def run():
@_core.listen('test')
def _():
print('a test 2')
@_core.on('test')
def _():
print('a test')
_emit('test')
_emit('test')
_emit('test') |
class TestingToolError(Exception):
""" Base exception for all kind of error in the testing tool."""
pass
########################################################################
# Level 2
########################################################################
class UnknownTestError(TestingToolError):
"... | class Testingtoolerror(Exception):
""" Base exception for all kind of error in the testing tool."""
pass
class Unknowntesterror(TestingToolError):
""" The test is not defined in the testing platform."""
pass
class Testfailerror(TestingToolError):
"""General exception thrown in case of a test failu... |
# Python3 program to generate pythagorean
# triplets smaller than a given limit
# Function to generate pythagorean
# triplets smaller than limit
def pythagoreanTriplets(limits) :
c, m = 0, 2
# Limiting c would limit
# all a, b and c
while c < limits :
# Now loop on n from 1 to m-1
for n in range(1... | def pythagorean_triplets(limits):
(c, m) = (0, 2)
while c < limits:
for n in range(1, m):
a = m * m - n * n
b = 2 * m * n
c = m * m + n * n
if c > limits:
break
print(a, b, c)
m = m + 1
if __name__ == '__main__':
lim... |
# 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, software
# distributed under t... | """Constants for use in the keystone.conf package.
These constants are shared by more than one module in the keystone.conf
package.
"""
_default_auth_methods = ['external', 'password', 'token', 'oauth1', 'mapped']
_certfile = '/etc/keystone/ssl/certs/signing_cert.pem'
_keyfile = '/etc/keystone/ssl/private/signing_key... |
# https://www.acmicpc.net/problem/2580
def init():
for row in range(N):
for col in range(N):
if data[row][col] == 0:
continue
row_sets[row].add(data[row][col])
for col in range(N):
for row in range(N):
if data[row][col] == 0:
... | def init():
for row in range(N):
for col in range(N):
if data[row][col] == 0:
continue
row_sets[row].add(data[row][col])
for col in range(N):
for row in range(N):
if data[row][col] == 0:
continue
col_sets[col].add(da... |
# https://leetcode.com/problems/letter-case-permutation/
# Given a string s, we can transform every letter individually to be lowercase or
# uppercase to create another string.
# Return a list of all possible strings we could create. You can return the output
# in any order.
#########################################... | class Solution:
def letter_case_permutation(self, S: str) -> List[str]:
if not S:
return []
self.n = len(S)
self.S = S
self.ans = []
self.holder = []
self.dfs(0)
return self.ans
def dfs(self, pos):
if len(self.holder) == self.n:
... |
def sockMerchant(n, ar):
# Write your code here
dict_count = {i:ar.count(i) for i in ar}
pairs = 0
for v in dict_count.values():
pairs+=v//2 #to get the quotient, % is used for remainder
#print(pairs, dict_count)
return pairs
a = 9
ar= [10, 20, 20, 10, 10, 30, 50, 10, 20]
print(sockMer... | def sock_merchant(n, ar):
dict_count = {i: ar.count(i) for i in ar}
pairs = 0
for v in dict_count.values():
pairs += v // 2
return pairs
a = 9
ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
print(sock_merchant(a, ar)) |
#
# Copyright 2018 Red Hat | Ansible
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | class Moduledocfragment(object):
documentation = '\noptions:\n resource_definition:\n description:\n - "Provide a valid YAML definition (either as a string, list, or dict) for an object when creating or updating. NOTE: I(kind), I(api_version), I(name),\n and I(namespace) will be overwritten by correspon... |
"""Apply a simple test to see if the user is old enough to rent a car."""
answer = input('Hello, who are you?\n')
while not all(word.isalpha() for word in answer.split()):
answer = input(
"Names usually contain letters. Let's try this again.\n"
"Hello, who are you?\n"
)
name = answer.title().s... | """Apply a simple test to see if the user is old enough to rent a car."""
answer = input('Hello, who are you?\n')
while not all((word.isalpha() for word in answer.split())):
answer = input("Names usually contain letters. Let's try this again.\nHello, who are you?\n")
name = answer.title().strip()
answer = input(f'W... |
"""Errors."""
class ProxyError(Exception):
pass
class NoProxyError(Exception):
pass
class ResolveError(Exception):
pass
class ProxyConnError(ProxyError):
errmsg = 'connection_failed'
class ProxyRecvError(ProxyError):
errmsg = 'connection_is_reset'
class ProxySendError(ProxyError):
er... | """Errors."""
class Proxyerror(Exception):
pass
class Noproxyerror(Exception):
pass
class Resolveerror(Exception):
pass
class Proxyconnerror(ProxyError):
errmsg = 'connection_failed'
class Proxyrecverror(ProxyError):
errmsg = 'connection_is_reset'
class Proxysenderror(ProxyError):
errmsg =... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# CISCO-PPPOE-MIB
# Compiled MIB
# Do not modify this file directly
# Run ./noc mib make_cmib instead
# ----------------------------------------------------------------------
# Copyright (C) 2007-2014 The NOC Proje... | name = 'CISCO-PPPOE-MIB'
last_updated = '2011-04-25'
compiled = '2014-11-21'
mib = {'CISCO-PPPOE-MIB::ciscoPppoeMIB': '1.3.6.1.4.1.9.9.194', 'CISCO-PPPOE-MIB::ciscoPppoeMIBObjects': '1.3.6.1.4.1.9.9.194.1', 'CISCO-PPPOE-MIB::cPppoeSystemSessionInfo': '1.3.6.1.4.1.9.9.194.1.1', 'CISCO-PPPOE-MIB::cPppoeSystemCurrSessions... |
rows, cols = [int(x) for x in input().split(' ')]
matrix = [input().split() for _ in range(rows)]
cmd = input()
while cmd != 'END':
cmd_args = cmd.split()
if cmd_args[0] != 'swap' or len(cmd_args) != 5:
print('Invalid input!')
cmd = input()
continue
row1, col1 = int(cmd_args[1]), ... | (rows, cols) = [int(x) for x in input().split(' ')]
matrix = [input().split() for _ in range(rows)]
cmd = input()
while cmd != 'END':
cmd_args = cmd.split()
if cmd_args[0] != 'swap' or len(cmd_args) != 5:
print('Invalid input!')
cmd = input()
continue
(row1, col1) = (int(cmd_args[1])... |
# #1
# def last(*args):
# last = args[-1]
# try:
# return last[-1]
# except TypeError:
# return last
#2
def last(*args):
try:
return args[-1][-1]
except:
return args[-1]
| def last(*args):
try:
return args[-1][-1]
except:
return args[-1] |
def setup():
size(500, 500)
smooth()
noLoop()
def draw():
background(100)
stroke(142,36,197)
strokeWeight(110)
line(100, 150, 400, 150)
stroke(203,29,163)
strokeWeight(60)
line(100, 250, 400, 250)
stroke(204,27,27)
strokeWeight(110)
line(100, 350, ... | def setup():
size(500, 500)
smooth()
no_loop()
def draw():
background(100)
stroke(142, 36, 197)
stroke_weight(110)
line(100, 150, 400, 150)
stroke(203, 29, 163)
stroke_weight(60)
line(100, 250, 400, 250)
stroke(204, 27, 27)
stroke_weight(110)
line(100, 350, 400, 350) |
class BadGrammarError(Exception):
pass
class EmptyGrammarError(BadGrammarError):
pass
| class Badgrammarerror(Exception):
pass
class Emptygrammarerror(BadGrammarError):
pass |
# exceptions.py - exceptions for SQLAlchemy
# Copyright (C) 2005, 2006, 2007 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
class SQLAlchemyError(Exception):
"""Generic error class."""
pa... | class Sqlalchemyerror(Exception):
"""Generic error class."""
pass
class Sqlerror(SQLAlchemyError):
"""Raised when the execution of a SQL statement fails.
Includes accessors for the underlying exception, as well as the
SQL and bind parameters.
"""
def __init__(self, statement, params, orig... |
# Tutorial: http://www.learnpython.org/en/Loops
# Loops
# There are two types of loops in Python, for and while.
# The "for" loop
# For loops iterate over a given sequence. Here is an example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
# For loops can iterate over a sequence of numbers using th... | primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
for x in range(5):
print(x)
for x in range(3, 6):
print(x)
for x in range(3, 8, 2):
print(x)
count = 0
while count < 5:
print(count)
count += 1
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
for x in ... |
"""
Autogenerated by Django - used for admin site settings
"""
# uncomment when needed
# from django.contrib import admin
# Register your models here.
| """
Autogenerated by Django - used for admin site settings
""" |
with open('recovered/arc/clusters/6.0.0_r1_acdc_clustered.rsf', encoding="utf8") as data_file:
data = data_file.readlines()
cluster = set()
for line in data:
cluster.add(line.split(" ")[1])
print(len(cluster)) | with open('recovered/arc/clusters/6.0.0_r1_acdc_clustered.rsf', encoding='utf8') as data_file:
data = data_file.readlines()
cluster = set()
for line in data:
cluster.add(line.split(' ')[1])
print(len(cluster)) |
# Find square of a number without using multiplication and division operator
def main():
a = -10
if a < 0:
a = abs(a)
square = 0
for i in range(0, a):
square += a
print(square)
if __name__ == '__main__':
main()
| def main():
a = -10
if a < 0:
a = abs(a)
square = 0
for i in range(0, a):
square += a
print(square)
if __name__ == '__main__':
main() |
#!/usr/bin/python3
#from node import Node # From node package import class Node
class Node(object):
"""Represent a singly linked node."""
def __init__(self, data, next = None):
self.data = data
self.next = next
head = None
for count in range(1, 6):
head = Node(count, head) #... | class Node(object):
"""Represent a singly linked node."""
def __init__(self, data, next=None):
self.data = data
self.next = next
head = None
for count in range(1, 6):
head = node(count, head)
while head != None:
print(head.data)
head = head.next |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.