content stringlengths 7 1.05M |
|---|
"""Exercise 2: Step Over, Step Into, Step Out"""
def calculate_sum(list_of_nums):
"""Calculates the sum of a list of numbers."""
total = 0
for num in list_of_nums:
total += num
return total
def calculate_average(list_of_nums):
"""Calculates the average of a list of numbers."""
average... |
class SetUp:
base = "http://localhost:8890/"
URL = "http://localhost:8890/notebooks/test/testing.ipynb"
kernel_link = "#kernellink"
start_kernel = "link=Restart & Run All"
start_confirm = "(.//*[normalize-space(text()) and normalize-space(.)='Continue Running'])[1]/following::button[1]"
title = ... |
d = {"Tisch": "table",
"Stuhl": "chair",
"Schreibtisch": "desk"}
# Ziel: Weiteres Wörterbuch aufbauen, das als Schlüssel englische Begriffe enthält
# 1 Ansatz:
l = []
for tupel in d.items():
l.append((tupel [1], tupel [0]))
# 2 Ansatz:
l = [(tupel [1], tupel[0]) for tupel in d.items()]
pri... |
# int object is immutable
age = 30
print(id(age)) # id is used to get a object reference id
age = 40
print(id(age))
# list is mutable
series1 = [1, 2, 3]
series2 = series1
print(id(series1))
print(id(series1))
series1[1] = 10
print(series1)
print(series2)
print(id(series1))
print(id(series1))
# i... |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
fast = head
slow = head
while slow != None and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False... |
__author__ = 'rene_esteves'
def factorial(input):
if input < 1: # base case
return 1
else:
return input * factorial(input - 1) # recursive call
def sum(input):
if input == 1: # base_case
return 1
else:
return input + sum(input - 1) # recursive call
def fibonacci... |
""""
2 shelves
5 books
5 nooks
5 books in each shelve MAX VALUE = 5
1 book comes out,
4 books at any shelf
1 space is there
1 user 10 0 clock
another user 12 0 clock returned
another user 01 clock returned
10 -> out
12 -> out
1 -> in
2 -> out
3 -> out
5 -> in
5 operations
a stack of 10... |
class MySQL:
def __init__(self, db):
self.__db = db
def pre_load(self):
# do nothing
return
def load(self, check_id, results):
for result in results:
responsetime = result.get('responsetime', None)
self.__db.query(
'REPLACE INTO pingd... |
#
# PySNMP MIB module OPT-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPT-IF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:26:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
"""Spotify response stated codes.
Reference:
https://developer.spotify.com/documentation/web-api/#response-status-codes
"""
RESPONSE_OK = 200
RESPONSE_CREATED = 201
RESPONSE_ACCEPTED = 202
RESPONSE_NO_CONTENT = 204
RESPONSE_NOT_MODIFIED = 304
RESPONSE_BAD_REQUEST = 400
RESPONSE_UNAUTHORIZED = 401
RESPONSE_FORBI... |
'''
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area ... |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
k %= length
self.reverse(0, length - 1, nums)
self.reverse(0, k - 1, nums)
self.reverse(k, leng... |
'''
Ao observar a curva de velocidade de um motor, o engenheiro Zé percebeu que sempre ocorria uma queda quando as medidas eram feitas em intervalos de 10 ms. Mas esta queda acontecia em medidas diferentes a cada novo teste do motor.
Zé ficou curioso com essa falta de padrão e quer saber, para cada teste do motor, qua... |
'''
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not b... |
def checkrootpos(root, params):
a, b, c, d = params
return a * root**3 + b * root**2 + c * root + d > 0
def checkrootneg(root, params):
a, b, c, d = params
return a * root**3 + b * root**2 + c * root + d < 0
def fbinsearch(l, r, eps, check, params):
while l + eps < r:
m = (l + r) / 2
... |
LOWER_BOUND = -2147483648
UPPER_BOUND = 2147483647
def solve(i: int) -> int:
base = 10
digit_arr = []
mult = 1 if i > 0 else -1
num = abs(i)
while num:
digit_arr.append(num % base)
num //= base
reverse_num = 0
for digit in digit_arr[::-1]:
reverse_num += mult * dig... |
class MultiSerializerMixin:
def get_serializer_class(self):
return self.serializer_classes[self.action]
|
# While loops practice
# PART A
ages = [5, 6, 24, 32, 21, 70]
counter = 0
while ages[counter] < 30:
print("Part A - The ages is : " +str(ages[counter]))
counter+=1
print("Part A - The value that caused the loop to stop : " +str(ages[counter]))
print("\n")
# PART B
counter = 0
while ages[counter] < 30:
... |
def out_red(text):
return "\033[31m {}" .format(text)
def out_yellow(text):
return "\033[33m {}" .format(text)
def out_green(text):
return "\033[32m {}" .format(text)
|
"""
Continuação kwargs3.py...
"""
# Entenda porquê é importante manter a ordem dos parâmetros na declaração
# Função com a ordem correta de Parâmetros
def mostra_info(a, b, *args, instrutor='Geek', **Kwargs):
return [a, b, args, instrutor, Kwargs]
print(mostra_info(1, 2, 3, sobrenome='University', carg... |
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
|
# set the path-to-files
TRAIN_FILE = "/home/luban/work_jupyter/point_rec_data/train.csv"
TEST_FILE = "/home/luban/work_jupyter/point_rec_data/test.csv"
SUB_DIR = "./output"
NUM_SPLITS = 3
RANDOM_SEED = 2017
# types of columns of the dataset dataframe
CATEGORICAL_COLS = [
'common.os',
'common.loc_provider',... |
# Copyright 2019 Xilinx Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
HIVE_CONFIG = {
"host": '127.0.0.1',
"port": 10000,
"username": 'username',
"password": 'password'
}
MYSQL_CONFIG = {
'test':
{
"host": "127.0.0.1",
"port": 3306,
"user": "username",
"password": "password",
"database": "default"},
... |
n = int(input("Digite o valor a ser avaliado:"))
ac1 = n%10
achouadjacente = False
n = n//10
while n !=0 and not(achouadjacente):
ac2 = n%10
if ac2 == ac1:
achouadjacente = True
n = n//10
ac1 = ac2
if achouadjacente:
print("Nesse número há dois números adjacentes!")
else:
print("Nesse ... |
def test_stats_filter(api, b2b_raw_config, utils):
"""
configure two flows f1 and f2
- Send 1000 packets from f1 of size 74B
- Send 2000 packets from f2 of size 1500B
Validation:
1) Get port statistics based on port name & column names and assert
each port & column has returned the values a... |
# Readable: can read during runtime/compile time
# Writeable: can write during runtime and compile time
"""
============
| Tuple |
============
Readable
Not writeable:
- cannot modify value, add or remove an element during the runtime.
"""
fooTuple = ("fooTupleItem", True, 123);
another... |
cor = {
'fim':'\033[m',
'amarelo':'\033[1;033m',
'amarelof':'\033[7;033m',
'vermelho':'\033[1;031m',
'vermelhof':'\033[7;031m',
'azul':'\033[1;034m',
'verde':'\033[1;32m',
'verdef':'\033[7;32m',
'branco':'\033[1;030m'
}
primo = int(input('\nInsira um{} NÙMERO... |
"""
Common constants.
"""
ALPH = list('abcdefghijklmnopqrstuvwxyz')
|
# mock.py
# Metadata
NAME = 'mock'
ENABLE = True
PATTERN = r'^!mock (?P<phrase>.*)'
USAGE = '''Usage: !mock <phrase>
Given a phrase, this translates the phrase into a mocking spongebob phrase.
Example:
> !mock it should work on slack and irc
iT ShOuLd wOrK On sLaCk aNd iRc
'''
# Command
async def mock... |
"""
To sum in a sorted array
Given:
l: a list of sorted arrays
s: integer
find unique pair of items in the list l where sum is 's'
Problems:
1. Not working when there is a duplicate item is the list - [2, 3, 5, 4, 2, 1, 0]
"""
def two_sum_sorted_array(l, sum):
l.sort()
print(l)
a = 0
z = len(l)-1
... |
# Check For Vowel in a sentence....
s = input("Enter String: ")
s = s.lower()
f = 0
for i in range(0, len(s)):
if(s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u'):
f = 2
break
else:
f = 1
if f > 1:
print("Yes, Present")
else:
print("No, Not Present")
|
"""Provides python helper functions."""
load("@pydeps//:requirements.bzl", _requirement = "requirement")
def filter_deps(deps = None):
if deps == None:
deps = []
return [dep for dep in deps if dep]
def py_library(deps = None, **kwargs):
return native.py_library(deps = filter_deps(deps), **kwargs)... |
class Crawler:
"""
This class handles the calling of the scraper.
"""
def __init__(self) -> None:
pass |
"""
Generators Expression
WE studied:
- List Comprehension
- Dictionary Comprehension
- Set Comprehension
Not use:
- Tuple Comprehension => because call Generators
# List Comprehension
names = ['Carlos', 'Camila', 'Carla', 'Cassino', 'Cristina', 'Vanessa']
print(any([name[0] == 'C' for name in names]... |
# Given a 2D grid, each cell is either a wall 'W',
# an enemy 'E' or empty '0' (the number zero),
# return the maximum enemies you can kill using one bomb.
# The bomb kills all the enemies in the same row and column from
# the planted point until it hits the wall since the wall is too strong
# to be destroyed.
# Note t... |
def insertion_sort(arr):
isSorted = None
while not isSorted:
isSorted = True
for x,val in enumerate(arr):
try:
if val>arr[x+1]:
temp = arr[x]
arr[x] = arr[x+1]
arr[x+1] = temp
isSorted = False
except IndexError:
x-=1
return arr
print(insertion_sort([5,3,1,2,10... |
#
# Copyright © 2022 Christos Pavlatos, George Rassias, Christos Andrikos,
# Evangelos Makris, Aggelos Kolaitis
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the “Software”), to deal in
# the Software without rest... |
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
a -= 1
b -= 1
n = 100
grid = [['.'] * n for _ in range(n // 2)]
for _ in range(n // 2):
grid.append(['#'] * n)
print(n, n)
for i in range(0, n // 2, 2):
for j in range(0, n, 2):
... |
# Constant values
IS_COLD_START = True
WARM_ACTION_INDENTIFIER = 'warm_up'
DEFAULT_WARM_METHOD = 'sleep'
|
def test_endpoint_with_var2(client):
response = client.get("/items2/2")
assert response.status_code == 200
assert response.json() == {"item_id": 2}
|
EXAMPLES = {
'Example 1 - Swedish': 'Glochidion gaudichaudii är en emblikaväxtart som först beskrevs av Johannes Müller Argoviensis , och fick sitt nu gällande namn av Jacob Gijsbert Boerlage . Glochidion gaudichaudii ingår i släktet Glochidion och familjen emblikaväxter . Inga underarter finns listade i Catalogue ... |
# -*- coding: utf-8 -*-
API_TOKEN = ""
DEFAULT_REPLY = "잘못된 명령어입니다. 고갱님"
PLUGINS = [
'eastbot.plugins.basic',
'eastbot.plugins.ethereum',
'eastbot.plugins.miner',
]
|
class SampleClass:
@staticmethod
def sample_method(a, b):
return a + b
|
name = "S - Density Squares"
description = "Trigger randomly placed squares"
knob1 = "Square Size"
knob2 = "Density"
knob3 = "Line Width"
knob4 = "Color"
released = "March 21 2017"
|
'''
Interface Genie Ops Object Outputs for IOSXR.
'''
class InterfaceOutput(object):
ShowInterfacesDetail = {
'GigabitEthernet0/0/0/0': {
'auto_negotiate': True,
'bandwidth': 768,
'counters': {'carrier_transitions': 0,
'drops': 0,
... |
viagem = float(input('Quantos km é a vigem?'))
custo1 = viagem * 0.50
custo2 = viagem * 0.45
if viagem <= 200.000:
print('O custo da sua viagem será de R${:.2f}!'.format(custo1))
elif viagem >= 201.000:
print('O custo da sua viagem será de R${}!'.format(custo2))
print('Boa viagem!')
|
# Least Recently Used Cache
#
# The LRU caching scheme remove the least recently used data when the cache is full and a new page is referenced which is not there in cache.
#
# We use two data structures to implement an LRU Cache:
# - Double Linked List: The maximum size of the queue will be equal to the total number of... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by shimeng on 17-8-17
# 爬虫名称
spider_name = 'get_ip'
# 日志设置
log_folder_name = '%s_logs' % spider_name
delete_existed_logs = True
# 请求参数设置
thread_num = 50
sleep_time = 0.5
retry_times = 10
time_out = 5
# 当use_proxy为True时,必须在请求的args中或者在配置文件中定义ip, eg: ip="120.52.7... |
# Tuenti Challenge Edition 8 Level 10
PROBLEM_SIZE = "submit"
# -- jam input/output ------------------------------------------------------- #
def parse_problems(lines):
""" Given a list of lines, parses them and returns a list of problems. """
i = 0
res = []
while i < len(lines):
P, G = map(int, lines[i].split(... |
#python 3.5.2
'''
With the Remained Methods first you count the number of elements you what to store. So the length of the
array will eaual the number of elements you want so each element will have place to be stored. When you
do the divide by array length the remainer will always to equal or less than the numbe... |
class Solution:
def minWindow(self, s: str, t: str) -> str:
"""
s = "ADOBECODEBANC", t = "ABC" t count = 3
^
^
010
s count = 0
Time O(N+M)
Space O(M)
"""
... |
"""color methods"""
def color(r, g, b):
assert 256 > r > -1, "expected integer in range 0-255"
assert 256 > g > -1, "expected integer in range 0-255"
assert 256 > b > -1, "expected integer in range 0-255"
return '#%02x%02x%02x' % (r, g, b)
def color_to_rgb(html_color):
if len(html_color) == 7 and html_color[0]... |
def secti(a, b):
return a + b
if __name__ == '__main__':
print(secti(1, 2))
# https://stackoverflow.com/questions/419163/what-does-if-name-main-do
|
weights_path = './weights'
#pre trained model
name_model = 'model_unet'
#directory where read noisy sound to denoise
audio_dir_prediction = './mypredictions/input/'
#directory to save the denoise sound
dir_save_prediction = './mypredictions/output/'
#Name noisy sound file to denoise
#audio_input_prediction = args.a... |
BOT_NAME = 'books_images'
SPIDER_MODULES = ['books_images.spiders']
NEWSPIDER_MODULE = 'books_images.spiders'
ROBOTSTXT_OBEY = True
ITEM_PIPELINES = {
'books_images.pipelines.BooksImagesPipeline': 1
}
FILES_STORE = r'downloaded'
# Change this to your path
DOWNLOAD_DELAY = 2
# Change to 0 for fastest crawl
|
print('Valida e corrige número de telefone')
numero = int(input('Telefone: '))
novoNumero = ''
if len(str(numero)) < 8:
diferenca = 8 - len(str(numero))
novoNumero = '3' * diferenca
numeroFormatado = novoNumero + str(numero)
numeroFormatado = numeroFormatado[0:4] + '-' + numeroFormatado[5:]
print('T... |
"""
Test uygulaması = uygulama01
NİHAT FURKAN ÇİFTÇİ 31/03/2019
"""
print("~~~~Kolay Matematik Testi~~~~")
print("Lütfen size doğru gelen şıkkı yazarak cevaplayınız")
sorular = ["4*4 A)16 B)8 C)12 = ", "3*3 A)13 B)9 C)15 =", "7*7 A)44 B)47 C)49 =", "9*9 A)81 B)88 C)78 =", "5*5 A)10 B)15 C)25 ="]
cevaplar = ["A... |
#punto1
def triangulo(a,b):
area = (b * a)/2
print(area)
triangulo(30,50)
|
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums)<3:
return False
found = []
n = len(nums)
for i in range(0, n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
... |
area = float(input())
kgInM = float(input())
badGrape = float(input())
allGrape = area * kgInM
restGrape = allGrape - badGrape
rakia = restGrape * 45 / 100
sell = restGrape * 55 / 100
lRakia = (rakia / 7.5) * 9.80
lSell = sell * 1.5
print('%.2f' % lRakia)
print('%.2f' % lSell) |
inputFile = open("input/day7.txt", "r")
inputLines = inputFile.readlines()
listBagsWithoutShinyGold = []
listBagsWithShinyGold = []
listUncertain = []
def goldMiner():
for line in inputLines:
splittedLine = line.split()
bagColor = splittedLine[0] + splittedLine[1]
childrenBags = []
... |
# Given an integer array nums, find the contiguous subarray (containing at least one number)
# which has the largest sum and return its sum.
# Example:
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
# Follow up:
# If you have figured out the O(n) solution, try codin... |
def sum2(nums):
if len(nums) >= 2 :
return (nums[0] + nums[1])
elif len(nums) == 1 :
return nums[0]
else :
return 0 |
#!/usr/bin/env python
"""
@package ion.agents.platform.util.network
@file ion/agents/platform/util/network.py
@author Carlos Rueda
@brief Supporting elements for convenient representation of a platform network
"""
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
class BaseNode(object):
"""
A con... |
''' r : It opens the file to read-only. The file pointer exists at the beginning. The file
is by default open in this mode if no access mode is passed. '''
''' w : It opens the file to write only. It overwrites the file if previously exists
or creates a new one if no file exists with the same name. The... |
# !/usr/bin/env python3
#############################################################################
# #
# Program purpose: Displays a histogram from list data #
# Program Author : Happi Yvan <ivensteinpoker@gmail.co... |
class Dice(object):
def __init__(self, labels):
self.stat = labels
def roll_e(self):
self.stat[0], self.stat[2], self.stat[5], self.stat[3] = self.stat[3], self.stat[0], self.stat[2], self.stat[5]
def roll_w(self):
self.stat[0], self.stat[2], self.stat[5], self.stat[3] = self.stat[... |
def sum(number1, number2):
total = number1 + number2
print(total)
print("suma de 1 + 50")
sum(1,50)
print("suma de 1 + 500")
sum(500,1)
print("programa terminado") |
class Solution:
def isUgly(self, n: int) -> bool:
while True:
k=n
if n%2==0:
n=n//2
if n%3==0:
n=n//3
if n%5==0:
n=n//5
if k==n:
break
if n==1:
return True
|
def factorial(n):
suma = 1
for i in range(n, 1, -1):
suma = suma * i
return suma
def triangulo(n, k):
temp_n = factorial(n)
temp_n_k = factorial(n - k)
temp_k = factorial(k)
formula = temp_n / (temp_n_k * temp_k)
return formula
def welcome():
try:
var_1 = inp... |
def palin(n):
if str(n) == str(n)[::-1]:
return True
return False
N, M = map(int, input().split())
mid = (N+M) // 2
mid1 = (N+M) // 2
mid2 = (N+M) // 2
mids = {}
while True:
mid1 += 1
if palin(mid1):
break
while True:
mid2 -= 1
if palin(mid2):
break
if abs(mid - ... |
#from .test_cluster_det import test_cluster_det
#from .train_cluster_det import train_cluster_det
#from .debug_cluster_det import debug_cluster_det
#from .get_cluster_det import get_cluster_det
__factory__ = { }
def build_handler(phase, stage):
key_handler = '{}_{}'.format(phase, stage)
if key_handler not in... |
# -*- coding: utf-8 -*-
def test_hello_world():
text = 'Hello World'
assert text == 'Hello World'
|
try:
1/0
except Exception as e:
print('e : ', e)
print(f"repr(e) : {repr(e)}")
|
#!/usr/bin/env python3
print("Welcome to the Binary/Hexadecimal Converter Application")
# User input
max_value = int(input("\nCompute binary and hexadecimal values up to the following decimal number: "))
decimal = list(range(1, max_value+1))
binary = []
hexadecimal = []
for num in decimal:
binary.append(bin(num)... |
#
# @lc app=leetcode id=989 lang=python3
#
# [989] Add to Array-Form of Integer
#
# https://leetcode.com/problems/add-to-array-form-of-integer/description/
#
# algorithms
# Easy (43.96%)
# Likes: 269
# Dislikes: 52
# Total Accepted: 34.1K
# Total Submissions: 77.4K
# Testcase Example: '[1,2,0,0]\n34'
#
# For a n... |
## datatypes demo
# a = 3
# b = '3'
# a + 3
# b + 3
# if else boolean values
# print(a,b)
# print(a+3)
# print(b+' cats')
# print(type(a))
# print(td)
# now lets say you want to go shopping and you need a collection of items
# shopping_list = ['oat milk', 'apples']
# shopping_list[1]
# phonebook = { 'noel a': '+44010'... |
#!/usr/bin/env python3
class Colors:
""" Colorized output during run """
red = "\033[91m"
green = "\033[92m"
yellow = "\033[93m"
reset = "\033[0m"
class Config:
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
... |
"""This module holds miscellaneous validator Mixin classes for validating the incoming YAML."""
class KeyExistsMixIn:
def __init__(self, payload, *args, _key, _exception, _elem, **kwargs):
"""Raise an error if _key is not in the payload."""
try:
_ = payload[_key]
except (KeyErr... |
def solve_poly_reg(x, y, max_order):
"""Fit a polynomial regression model for each order 0 through max_order.
Args:
x (ndarray): An array of shape (samples, ) that contains the input values
y (ndarray): An array of shape (samples, ) that contains the output values
max_order (scalar): The order of t... |
s = 'GTCGAAGCCATTTCGCCGTGGGGTTGCGCGTGATTCTACCATCAGTTCTTTTTACGGTTCATTTAAACCGGTAATCCAGTAGCGTCAACAAATACTACTCTATGGTTGACTGGAGACGGAACGGGCCCATCGGACGTAATTATGTGGTCTTTGCACGAGCCGGCTGATACAAGCACATGCATCGTGACCACACCGACAAAGTTGTATCTTGGTTCCCGATTTATAACGTCTGCAGAATGAGCCTGTGTGACTATTGTAGTAGGTCCGAATGCCATGTCGGGGCTCCCACCTACGCTGCCTGGCGTCTTTTTGTGC... |
# 15. 3Sum
# ttungl@gmail.com
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
# Find all unique triplets in the array which gives the sum of zero.
# For example, given array S = [-1, 0, 1, 2, -1, -4],
# --
# A solution set is:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ]
class S... |
expected_output = {
"route-information": {
"route-table": [
{
"table-name": "inet.0",
"destination-count": "60",
"total-route-count": "66",
"active-route-count": "60",
"holddown-route-count": "1",
"hi... |
if __name__ == '__main__':
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
l = [fruit.upper() for fruit in fruits if "n" in fruit]
print(l)
s = {fruit.upper() for fruit in fruits if "n" in fruit}
print(s)
d = {fruit.upper() : len(fruit) for fruit in fruits if "n" in fruit}
print(d)... |
class BaseClass:
def __init__(self):
pass
@staticmethod
def say_hi():
print("hi")
class MyClassOne(BaseClass):
def __init__(self):
pass
class MyClassTwo(BaseClass, MyClassOne):
def __init__(self):
pass
|
"""
django-amazon-price-monitor monitors prices of Amazon products.
"""
__version_info__ = {
'major': 0,
'minor': 7,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
version = ["{major:d}... |
class AndGate(BinaryGate):
def __init__(self,n):
super().__init__(n)
def performGateLogic(self):
a = self.getPinA()
b = self.getPinB()
if a==1 and b==1:
return 1
else:
return 0
|
'''Melhore o DESAFIO 61,
perguntando para o usuário se ele quer mostrar mais alguns termos.
O programa encerrará quando ele disser que quer mostrar 0 termos.'''
primeiro = int(input('Qual o termo? '))
progressao = int(input('Pular de quanto em quanto? '))
contador = 1
termo = primeiro
cont = 1
total = 0
mais = 10
... |
"""
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one down, pass it around
"""
def solution()... |
#
# Copyright (c) 2019, Infosys Ltd.
#
# 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 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def constant_aminoacid_code():
aa_dict = {
"R" : "ARG", "H" : "HIS", "K" : "LYS", "D" : "ASP", "E" : "GLU",
"S" : "SER", "T" : "THR", "N" : "ASN", "Q" : "GLN", "C" : "CYS",
"G" : "GLY", "P" : "PRO", "A" : "ALA", "V" : "VAL", "I" : "ILE",
... |
def head(n):
print(f"Calling the function head({n})")
# Base Case
if(n == 0):
print("**** Base Case **** \n")
return
# Recursive Function Call
head(n-1)
# Operation
print(n)
# head(5): -1006
# RecursionError: maximum recursion depth exceeded while pickli... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
fabrik
------------
:copyright: (c) 2014-2017 by Fröjd Interactive AB
:license: MIT, see LICENSE for more details.
"""
__title__ = "fabrik"
__version__ = "3.3.0"
__build__ = 330
__license__ = "MIT"
__copyright__ = "Copyright 2014-2017 Fröjd Interactive AB"
|
{
PDBConst.Name: "notetype",
PDBConst.Columns: [
{
PDBConst.Name: "ID",
PDBConst.Attributes: ["tinyint", "not null", "primary key"]
},
{
PDBConst.Name: "Type",
PDBConst.Attributes: ["varchar(128)", "not null"]
},
{
PDBConst.Name: "SID",
PDBCons... |
# -*- python -*-
{
'includes': [
'../../../build/common.gypi',
],
'target_defaults': {
'variables':{
'target_base': 'none',
},
'target_conditions': [
['target_base=="ripple_ledger_service"', {
'sources': [
'ripple_ledger_service.h',
'ripple_ledger_service.c'... |
# Задание 9.1b
def generate_access_config(access, psecurity = False):
'''
access - словарь access-портов,
для которых необходимо сгенерировать конфигурацию, вида:
{ 'FastEthernet0/12':10,
'FastEthernet0/14':11,
'FastEthernet0/16':17 }
psecurity - контролирует нужна ли настр... |
# This code is a partial mod of of the Adafruit PyPotal lib
# https://github.com/adafruit/Adafruit_CircuitPython_PyPortal/blob/master/adafruit_pyportal.py
def wrap_nicely(string, max_chars):
"""Wrap nicely function
A helper that will return a list of lines with word-break wrapping
Parameters
-------... |
# 140000000
LILIN = 1201000
sm.setSpeakerID(LILIN)
if sm.sendAskAccept("Shall we continue with your Basic Training? Before accepting, please make sure you have properly equipped your sword and your skills and potions are readily accessible."):
sm.startQuest(parentID)
sm.removeEscapeButton()
sm.sendNext("A... |
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
ress = []
locs = [-1] * n
checkarray = [[True] * n,
[True] * (2 * n - 1),
[True] * (2 * n - 1)]
def put(dep, checkarray):
if dep == n:
ress.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.