text stringlengths 8 6.05M |
|---|
from unittest import TestCase
from entidades.climatizador import *
from entidades.ambiente import *
class TestClimatizador(TestCase):
def setUp(self) -> None:
self._climatizador = Climatizador()
self._ambiente = Ambiente()
def test__inicializar_maquina_estado(self):
self.assertEqual(... |
from functools import lru_cache
import re
class frozendict(dict):
"""A hashable dictionary."""
def __key(self):
return tuple((k, self[k]) for k in sorted(self))
def __hash__(self):
return hash(self.__key())
def __eq__(self, other):
return self.__key() == other.__key()
def __ne__(self, other):... |
from lxml import etree
html_str = """
<div id="box1">this from blog.csdn.net/lncxydjq , DO NOT COPY!
<div id="box2">*****
<!--can u get me, bitch?-->
</div>
</div>
"""
html = etree.HTML(html_str)
print(html.xpath('//div[@id="box1"]/div/node()')[1])
print(type(html.xpath('//div[@id="box1"]/div/node... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
try, except, else, finally
ref:
- https://docs.python.org/3/reference/compound_stmts.html#the-try-statement
- http://www.cnblogs.com/windlazio/archive/2013/01/24/2874417.html
"""
try:
# Normal code block
pass
except TypeError:
# Exception 1 handle
pa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license, see LICENSE.
import os.path
from setuptools import setup, find_packages
with open('README.md') as readme_file:
readme = readme_file.read()
def get_version():
g = {}
exec(open(os.path.join("skhep_testdata", "vers... |
import re
def getUserInput():
return input("Ingrese una expresion: ")
def comprobarCoincidencia(userInput):
expresionInstruccionAttack = '\s*?attack\s*?\(\s*?\d*\s*?\)\s*?'
expresionInstruccionMove = '\s*?move\s*?\(\s*?\d*\s*?\)\s*?'
expresionInstruccionTurnLeft = '\s*?turnLeft\s*?\(\s... |
"""
https://www.json.org/json-pt.html
https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/
https://gist.github.com/stupidbodo/614b6e77d54fb5870f3a
"""
import json
import os
from time import gmtime, strftime
def inicializarPastas():
try:
os.mkdir('json')
os.mkdir('./jso... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileRequired
from wtforms.fields.html5 import EmailField
from wtforms.fields import PasswordField, StringField, HiddenField, SelectField, TextField, FileField, TextAreaField
from wtforms_components import ColorField
from wtforms import validators
from urllib.pa... |
from flask import Flask, request
from cleaner_data import Predictions
import pickle
import matplotlib.pyplot as plt
from flask_caching import Cache
config = {"CACHE_TYPE": "null"}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
with open('data/predictions.pkl', 'rb') as f:
pred = pickl... |
import os
from datetime import datetime
from .utils import env as ENV
from .utils.logger import Logger
from kratos.apps.log.serializers import LogSerializer
from kratos.apps.log.models import Log
from .tasks import *
def run(pipeline, envs = {}):
ENV._init(envs)
ENV.SET('name', pipeline['appinfo']['name'... |
factorial = [1]
for i in range(1,1001):
factorial.append(factorial[i-1]*i)
while True:
try:
n = int(input())
print("{}!".format(n))
print("{}".format(factorial[n]))
except:
break;
|
"""
API endpoints for the courses app.
"""
from django.utils.translation import gettext as _
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, ViewSet
from .lms import LMSHandler
from .models import Cou... |
#!/usr/bin/python3
num = 1
decimal = 10.3
texto = "Valor em texto"
# concatenação de variáveis
print("O valor numerico é: " + str(num) \
+" e valor decimal é: " + str(decimal))
# concatenação de variáveis com f string
print(f"O valor é: {num}")
print(f"O valor é: {num} e o valor da decimal é: {decimal}")
print("O... |
# ==================================================================================================
# Copyright 2014 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 9 09:59:04 2020
@author: baxcruiser
"""
def solve(n):
if n==1:
return [1,1]
l=[1,n]
for i in range (2,(n//2)+1):
res=1
res2=1
z=i
x=n
while (z>0):
res=res*x
res2... |
# Generated by Django 2.1.5 on 2019-02-14 08:41
from django.db import migrations
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('library', '0004_auto_20190208_0927'),
]
operations = [
migrations.AlterModelManagers(
name='booklend',
... |
print("Electricity bill estimator 2.0")
print()
tariff = {11: 0.244618, 31: 0.136928}
choice = int(input("Which tariff? 11 or 31: "))
while choice != tariff.keys():
print("Incorrect. Enter again")
choice = int(input("Which tariff? 11 or 31: "))
daily_kwh = float(input("Enter daily use in kWh: "))
bi... |
class STATUS_PHASE:
"""
Different values that the status phase should have. The frontend will be
expecting only these values.
"""
READY = "ready"
WAITING = "waiting"
WARNING = "warning"
ERROR = "error"
UNINITIALIZED = "uninitialized"
UNAVAILABLE = "unavailable"
TERMINATING =... |
import sys
rdl = sys.stdin.readline
n = int(rdl())
target = int(rdl())
l = [[0]*n for _ in range(n)]
x = n//2
y = n//2
_n = 1
ans = [0, 0]
if _n == target:
ans[0], ans[1] = x, y
l[y][x] = _n
_n += 1
y -= 1
for i in range(n//2):
for dx in range(1 + 2*i):
if _n == target:
ans[0], ans[1] = ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Gusseppe Bravo <gbravor@uni.pe>
# License: BSD 3 clause
"""
Helper functions
"""
from pyspark.sql.functions import col, rand, randn, when
def generate_dataframe(spark_session, n_samples, n_features, seed=42):
'''
Generate a binary labeled dataframe for ... |
import pickle
class Config(object):
def __init__(self):
# train
self.img_dim = 2048
self.hidden_dim = 512
self.embed_dim = 1024
self.lr = 0.001
self.batch_size = 16
self.keep_prob = 0.75
self.layers = 1
self.use_pretrained = False
sel... |
s = input()
first = s[0]
end = s[-1]
cnt = len(s)-2
print(first + str(cnt) + end)
|
import logging
from collections import deque
from importlib import import_module
from os import path
from lakesuperior.dictionaries.namespaces import ns_collection as nsc
RES_CREATED = '_create_'
"""A resource was created."""
RES_DELETED = '_delete_'
"""A resource was deleted."""
RES_UPDATED = '_update_'
"""A resour... |
import re
import shelve
import subprocess
from datetime import datetime, timedelta
from operator import itemgetter
import arrow
import requests
from bs4 import BeautifulSoup
from gevent.pool import Pool
from humanize import naturalsize
from requests.adapters import HTTPAdapter
from terminaltables import AsciiTable
fro... |
from networkz.algorithms.flow.maxflow import *
from networkz.algorithms.flow.mincost import *
|
import logging
from collections import namedtuple
from datetime import datetime, date
from decimal import Decimal
from xlrd import open_workbook, xldate_as_tuple
import csv
from schwifty import IBAN
from ccp2qif.model import QIFTransaction, AccountInfo, TransactionList
LOG = logging.getLogger(__name__)
DataRow = ... |
#!/usr/bin/env python3
""" Starts application, displays GUI Page components on window"""
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from app_gui import ApplicationGUI
''
__author__ = 'Curtis McAllister'
__maintainer__ = 'Curtis McAllister'
__email__ = 'mcallister_c20@ulster.ac.uk'
__status__ = 'D... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 14 16:44:42 2021
@author: Eric Born
!!! TODO !!!
create room class which stores description text and inventory list for items
to be taken by player
Find_Item # looks for item of same class
Killed
ShowDeathScreen
Restart
"""
#import inspect
import random as r... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-27 09:49
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... |
from random import randint
# Here we have algorithms with time complexity - O(n log(n))
def merge_sort(inp_list):
if len(inp_list) <= 1:
return inp_list
middle = len(inp_list) // 2
left_list = inp_list[:middle]
right_list = inp_list[middle:]
left_list = merge_sort(left_list)
right_l... |
def slovar():
file = open('slovar.txt', 'r')
a = []
b = {}
for i in range(4):
c = file.readline()
d = c.split(":")
b["first"] = d[0]
b["second"] = d[1]
a.append(b.copy())
file.close()
return a
def func_2(array, string):
result = []
for i in arra... |
#!/usr/bin/env python
import rospy
import math
from andrewbot_msgs.msg import RobotCommand
from geometry_msgs.msg import Twist
from head_driver import HeadDriver
from andrewbot_utils.math_utils import map_values
robot_head_pub = rospy.Publisher('andrewbot/RobotCommand', RobotCommand, queue_size=1)
robot_head = HeadDri... |
#!/usr/bin/python3
def add_integer(a, b=98):
"""Sums a pair of ints or floats"""
if not isinstance(a, (int, float)):
raise TypeError("a must be an integer")
if not isinstance(b, (int, float)):
raise TypeError("b must be an integer")
if a == float(9e999) or a != a or a == float(-9e999):
... |
import rdflib
from rdflib import Graph
from rdflib.namespace import Namespace, NamespaceManager
from lakesuperior.config_parser import config
# Core namespace prefixes. These add to and override any user-defined prefixes.
# @TODO Some of these have been copy-pasted from FCREPO4 and may be deprecated.
core_namespaces... |
# None keyword
i = None
def func(a): # a = 10
if a is None:
return 'There is no value.'
else:
return a * 2
print(func(10))
print(func(i))
|
from flask import Flask
import time
server = Flask(__name__) # Flask必须创建程序实例,Flask类只有一个必须指定的参数,即程序主模块或者包的名字,__name__是系统变量,该变量指的是本py文件的文件名
@server.route('/time', methods=['post', 'get']) # 文件路径/time,方法post和get
def get_time():
now = time.strftime('%Y-%m-%d %H:%M:%S')
print(now)
return '当前时间是:%s' % now
... |
import numpy as np
import re
class Basic:
def __call__(self, doc, budget=100):
scores = np.array([x.sum() for x in doc.annotations['exact_match']])
indices = np.argsort(scores)[::-1]
summary_indices = []
size = 0
for idx in indices:
utt = doc.ut... |
from .resnet_features import resnet101_features |
from cky.ckyParser import CKYParser
from yap.yapParser import parse
class Tagger:
def tag_eng_sentences(self, eng_sentences):
eng_parser = CKYParser()
parsed_sentences = []
for sent in eng_sentences:
parsed_sentences.append(eng_parser.parseSentence(sent))
return pa... |
from math import floor
n = int(input())
cards_s = input().split()
cards = [int(s) for s in cards_s]
cards = sorted(cards, reverse = True)
m = floor(n/2)
cards_a = cards[::2]
cards_b = cards[1::2]
print("{}".format(sum(cards_a)-sum(cards_b)))
|
import gym
import gym_maze
import matplotlib.pyplot as plt
import numpy as np
import random
import os
maze_size = 10
action_num = 4
EPISODES = 200
class SARSA():
def __init__(self, state_list, action_size):
self.state_list = state_list
self.action_size = action_size
self.gamma = 0.95
... |
from Log_Writer.logger import App_Logger
from Preprocessing.null_imputer import null_value_imputer
from Preprocessing.categ_encoding import encode
import pandas as pd
class Preprocessor:
def __init__(self):
self.log_writer=App_Logger()
self.original_data=pd.read_csv('Cleaned_insurance_claim.csv')
... |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
if self == None:
return str(None)
return f"TreeNode: {{val: {self.val}, Left: {str(self.left)}, Right: {str(self.right)}}}" |
""" A view containing the contents of a Python shell namespace. """
# Enthought library imports.
from envisage.plugins.python_shell.api import IPythonShell
from envisage.plugins.ipython_shell.api import INamespaceView
from pyface.workbench.api import View
from traits.api import Property, implements, Instance, \
St... |
# -*- coding: utf-8 -*-
"""
@author: Duy Anh Philippe Pham
@date: 11/06/2021
@version: 1.20
@Recommandation: Python 3.7
@révision:14/06/21
@But : Barycentre glissant
"""
import numpy as np
import sys
sys.path.insert(1,'../../libs')
import pandas as pd
from sklearn.manifold import Isomap
import matplotlib.pylab as plt... |
from callbacks.callback import Callback
class LogCallback(Callback):
def __init__(self, frequency):
super().__init__(frequency=frequency, before=False, after=True)
def __call__(self, trainer):
trainer.state.log_train()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
File Name: example-02.py
Description:
Created_Time: 2016-09-27 11:30:57
Last modified: 2016-09-27 14时18分33秒
'''
_author = 'arron'
_email = 'fsxchen@gmail.com'
# Futures,类似于Defer和Promise
# Tasks,使用future封装,返回一个Task的对象
# 例子: 监控文件的改变。
import asyncio
try:
from s... |
import logging
from BoschShcPy.base import Base
from BoschShcPy.client import ErrorException
from BoschShcPy.base_list import BaseList
from BoschShcPy.device import Device, status_rx
_LOGGER = logging.getLogger(__name__)
state_rx = {'ON': True, 'OFF': False}
state_tx = {True: 'ON', False: 'OFF'}
state1_rx = {'ENABLE... |
import zmq
import sys
class client:
def __init__(self):
self.port = "5556"
self.context = zmq.Context()
self.socket = self.context.socket(zmq.SUB)
print "Connecting to server..."
self.socket.connect("tcp://localhost:%s" % self.port)
self.socket.setsockopt(zmq.SUBSCRIBE,'')
|
class InvalidTokenError(Exception):
pass
class InvalidParamsError(Exception):
pass
|
import os.path
from unittest import TestCase
from sportsdirect.fetch import FilesystemFetcher
import sportsdirect.playbyplay
TEST_DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'test_data')
class PlayByPlayTestCase(TestCase):
def test_get_plays(self):
... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
import requests, random
from time import sleep
import urllib.request
import colorama
"""
Kod ile yapacağınız herhangi bir işlemden ben sorumlu değilim. Bu riski göz önüne alarak kullanın.
Discord : .J#8781 BY KRAMPUS
This application is for private or educational purposes only.
Do not use it on other people wit... |
# RMMV convert to Tiled
import os
from PIL import Image
path = './png/'
savepath = './convert/'
tilesize = 16
if not(os.path.exists(path) or os.path.exists(savepath)):
print('pngpath or savepath no exist.')
exit(1)
tw = 16*4
th = 16*6
filelist = os.listdir(path)
for item in filelist:
im = Image.open(path... |
#!/usr/bin/python3
"""Unittest for BaseModel class.
16/02/2021
"""
import os
import pep8
import unittest
import datetime
from models import storage
from models import base_model
from models.base_model import BaseModel
class TestBaseModel_init(unittest.TestCase):
"""Class to add Unittest for a BaseModel class.... |
#-*- coding: utf-8 -*-
#########################################################################
# Author: Johnny Shi
# Created Time: 2014-08-28 23:21:56
# File Name: offerwall_daily_report_types.py
# Description:
#########################################################################
"""
比较trick的方式,Summary成员变量中,需要环... |
import copy
def checkio(cells):
startP = [cells[0], int(cells[1])]
endP = [cells[3], int(cells[4])]
resultList = [[startP]]
print("===", startP, endP, resultList)
result = 0
n = 0
while result == 0:
newresultList = []
for r in resultList:
currentL = r
... |
from unittest import TestCase
from ckan_meta_tester.ckan_install import CkanInstall
from ckan_meta_tester.game_version import GameVersion
from ckan_meta_tester.game import Ksp1
class TestCkanInstall(TestCase):
def test_ckan_install(self) -> None:
# Arrange
cki = CkanInstall(contents="""{
... |
import sys
def square_root(x):
return x ** 0.5
parameter = int(sys.argv[1])
print(square_root(parameter))
|
# -*- coding: utf-8 -*-
from irc3.testing import BotTestCase
class TestUptime(BotTestCase):
def test_uptime(self):
bot = self.callFTU(includes=['irc3.plugins.uptime'])
bot.notify('connection_made')
bot.dispatch(':gawel!u@h PRIVMSG #chan :!uptime')
self.assertSent(
[('... |
class person:
country = "india"
def takebreath(self):
print("i m breathing... ")
class Employee(person):
company = "honda "
def getsalary(self):
print(f"salary is {self.salary}")
def takebreath(self):
print("i am employee ")
class Programmer(Employee):
company = "fib... |
from flask_login.utils import login_required, login_user, logout_user
from db import get_user
from flask import Flask, render_template, request, redirect
from flask.helpers import url_for
from flask_socketio import SocketIO, join_room, leave_room
from flask_login import LoginManager, current_user
from user import User
... |
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
#This test is used to check if the engine can run if maxDocs, IndexType, Maximum Memory, mergeEveryNSeconds, mergeEveryMWrites paramters are absent by querying the engine.
import sys, urllib2, json, time, subprocess, os, commands, signal
sys.path.insert(0, 'srch2lib')
import test_lib
#wrongAuthKey='Hey'
authKey='bla... |
import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
LR = 1e-3
TEST_DIR = "C:\\Users\\gvadakku\\tensorflo... |
#042: Reversal Distance
#http://rosalind.info/problems/rear/
#Given: A collection of at most 5 pairs of permutations, all of which have length 10.
#Return: The reversal distance between each permutation pair.
import math
f = open('rosalind_rear.txt', 'r')
contents = f.read()
f.close()
contents = content... |
import sys
from PyQt5.QtWidgets import (QWidget, QApplication, QLabel,
QFileDialog)
from PyQt5.QtGui import QPixmap
from PyQt5.Qt import *
class HandlerWindow(QWidget):
def __init__(self, parent=None):
super(HandlerWindow, self).__init__()
self.resize(300,350)
se... |
# Utilities related to syllables, e.g. counting number of syllables in a word, or splitting a word into syllables
import nltk
class Syllabizer:
def __init__(self):
self.cmudict = nltk.corpus.cmudict.dict()
def word_to_phonemes(self, s):
"""
TODO: Replace cmudict with trained g2p model
"""
return self.cmu... |
from Scapy_Control import *
from scapy.all import *
from NBSession import *
class Create_Close(NBSession):
#SMB2_CREATE_REQUEST_LEASE
def RqLs_Chain(self,
Req = True):
raw = ''
if Req:
raw += HexCodeInteger(0, HexCodes=4) # whole size offset
raw += H... |
#!/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
from PIL import Image
import os
i = 0
for fn in os.listdir("./start"):
i += 1
im = Image.open("./start/{}".format(fn))
new_im = im.rotate(90).resize((480, 411)).copy().save(fp = "./end/{}{}.jpeg".format("new_image", str(i)))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Сведения о погоде на сегодняшний день по данным с OpenWeatherMap.org.
from pyowm.owm import OWM
from pyowm.utils.config import get_default_config
from rhvoice_tools.scripts import get_time, get_date, get_weekday, get_greeting
from rhvoice_tools import rhvoice_say
def ... |
'''
Created on 05.09.2018
@author: FM
'''
import unittest
import unittest.mock as mock
from FileSet import FileSet
from CLI import move, CLIRuntimeError, SpotExpansionError,\
RangeExpansionError, ArgumentAmountError, InputProcessingError
from test.testing_tools import mock_assert_msg, KeywordArgTuple
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Customer)
admin.site.register(Cleaner)
admin.site.register(Booking)
admin.site.register(City) |
"""Realy simple yes/no Dialog example.
Uses 2 versions of the yes/no dialog.
BUT! The two versions do not return the same kind of answer!
"""
import wx
def Evaluate_answer(ans):
if ans == wx.ID_YES :
print 'first kind of "yes"', ans
elif ans == wx.YES:
print 'second kind of "yes"', ans
... |
import psycopg2
import datetime
import random
def randf(min, max, precision=2):
return round(random.uniform(min, max), precision)
# 风机信息
wfid = 140802
wtids = [140802200, 140802201, 140802202, 140802203]
# 数据条数,请自行计算
num = 60 * 24 * 28
# 延续性造数据开关
goon = False
# 数据起始时间,当goon为True且风机存在底量数据时,此项无效
first_time = '201... |
import rospy
import time
import numpy as np
from ackermann_msgs.msg import AckermannDriveStamped
from sensor_msgs.msg import LaserScan
from ar_track_alvar_msgs.msg import AlvarMarkers
class finalProgram():
def __init__(self):
rospy.Subscriber("ackermann_cmd_mux/output", AckermannDriveStamped,self.ackerman... |
import spotify
import threading
import time
import copy
import random
import alsaaudio
queuelist = ['q', 'Q', 'queue', 'Queue']
playlistlist = ['p', '$', 'playlists', 'Playlists']
class SpotifyPlayer():
def __init__(self):
self.logged_in_event = threading.Event()
self.queue = []
self.queue... |
#!env python3
# -*- coding: utf-8 -*-
import csv
import sqlite3
import os
import sqlalchemy as sa
test1 = 'This is a test of the emergency text system'
with open('test.txt', 'wt') as fh:
fh.write(test1)
with open('test.txt', 'rt') as fh:
for line in fh:
print(line)
csv_text1 = '''author,book
J R R To... |
import Contour
import Process
from Simple import Point
from IO import Reader
from Plot import Core as pl
from Utils import Utils
list_of_points = Point.CreateListOfPoints(Reader.contour_points)
contour = Contour.Contour(Utils.createContour())
init_flow_len = Reader.init_flow_len
x_max = Reader.x_max
y_max = Reader.y_m... |
import sys
import unittest
from pathlib import Path
try:
from test.const import PROJECT_PATH, TEST_PATH, TEST_DB_URL
except:
test_dir = str(Path(__file__).absolute().parent.parent)
if test_dir not in sys.path:
sys.path.append(test_dir)
from const import PROJECT_PATH, TEST_PATH, TEST_DB_URL
src... |
from django.urls import path
from .views import TaskStatusDetailView, ImageScrapeView, TextScrapeView, WebPageDetailView, WebPageListView
urlpatterns = [
path("scrape/text/", TextScrapeView.as_view(), name="scrape-text"),
path("scrape/images/", ImageScrapeView.as_view(), name="scrape-images"),
path("web... |
# 问题描述
#
# 小明今天生日,他有n块蛋糕要分给朋友们吃,这n块蛋糕(编号为1到n)的重量分别为a1, a2, …, an。小明想分给每个朋友至少重量为k的蛋糕。小明的朋友们已经排好队准备领蛋糕,对于每个朋友,小明总是先将自己手中编号最小的蛋糕分给他,当这个朋友所分得蛋糕的重量不到k时,再继续将剩下的蛋糕中编号最小的给他,直到小明的蛋糕分完或者这个朋友分到的蛋糕的总重量大于等于k。
# 请问当小明的蛋糕分完时,总共有多少个朋友分到了蛋糕。
#
# 输入格式
#
# 输入的第一行包含了两个整数n, k,意义如上所述。
# 第二行包含n个正整数,依次表示a1, a2, …, an。
#
# 输出格式
#
# 输... |
#!/usr/bin/python3
""" node.py: Contains the node class which is used in the simple database and binary trees
"""
class Node:
"""Node: Simple node class used in the binary trees
"""
def __init__(self, value):
self.value = value[0]
self.owner = value[1]
self.parent = None
se... |
from ED6ScenarioHelper import *
def main():
# 封印区域
CreateScenaFile(
FileName = 'C4303 ._SN',
MapName = 'Grancel',
Location = 'C4303.x',
MapIndex = 216,
MapDefaultBGM = "ed60035",
Flags = 0,
... |
#!/usr/bin/python3
"""Module to fill a simple web form with an id and vote
clicking on a button.
"""
import requests
payload = {'id': '1610', 'holdthedoor': 'submit'}
for i in range(1, 1025):
requests.post('http://158.69.76.135/level0.php', data=payload)
i += 1
print("Hodor holds the door {:d} times!".format(i... |
# Generated by Django 3.1.5 on 2021-01-26 06:43
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('main', '0003_logos'),
]
operations = [
m... |
# --------
# Note
# --------
# while
i = 1
while i <= 5:
print(i)
i += 1
print('Done')
|
from ED6ScenarioHelper import *
def main():
# 巴伦诺灯塔
CreateScenaFile(
FileName = 'C2209_1 ._SN',
MapName = 'Rolent',
Location = 'C2200.x',
MapIndex = 84,
MapDefaultBGM = "ed60031",
Flags = 0,
... |
x = (1,2,3,4,5)
print(x)
print(x.__len__())
x = list(range(1,11))
y = tuple(x)
print(y)
y =(1,)
print(type(y)) |
#uses python module random to generate random password of length 8
import random
import string
def random_password():
random_source = string.ascii_letters + string.digits + string.punctuation
pas = random.choice(string.ascii_lowercase)
pas += random.choice(string.ascii_uppercase)
pas += random.choice... |
from django.core.management.base import BaseCommand
from line.einstein_vision import EinsteinVisionApi
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
self.einstein = EinsteinVisionApi()
super(Command, self).__init__(*args, **kwargs)
def handle(self, *args, **options):
... |
# Generated by Django 2.2 on 2019-04-15 02:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('onlclass', '0003_day_memo'),
]
operations = [
migrations.RemoveField(
model_name='day',
name='memo',
),
... |
from flask import Flask, jsonify, request
from flask_cors import CORS
NUMBERS = []
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
@app.route('/numbers', methods=['GET'])
def get_result():
global NUMBERS
response_object = {'status': 'succes... |
'''
Message Serializers
-------------------
Instead of having every message derive from a protocol that
decides how to encode/decode it, we instead are pulling the
relevant code outside of the class.
Since we can introspect each message and we know what our
messages look like, we an serialize from the outside just as... |
import datetime
import pytest
from freshdesk.v2.models import Group
@pytest.fixture
def group(api):
return api.groups.get_group(1)
def test_list_groups(api, group):
groups = api.groups.list_groups()
assert isinstance(groups, list)
assert len(groups) == 2
assert groups[0].id == group.id
def t... |
from flask import Flask
from healthcheck import HealthCheck
import logging
from src.settings import BASE_PATH
log = logging.getLogger('werkzeug')
log.disabled = True
app = Flask(__name__)
health = HealthCheck()
def app_available():
return True, "application ok"
health.add_check(app_available)
app.add_url_rul... |
from math import ceil
if __name__ == "__main__":
T = int(input())
for _ in range(T):
N = int(input())
print(ceil(N / 2))
|
from Gaudi.Configuration import *
from GaudiKernel.SystemOfUnits import *
from Configurables import DaVinci
from Configurables import GaudiSequencer
simulation=True
if simulation:
from Configurables import EventNodeKiller
from StrippingConf.Configuration import StrippingConf, StrippingStream
f... |
import re
import time
from datetime import datetime, timedelta
import os
import json
import requests
from configure import Config
since = datetime.strptime(Config.date_conf()['since'], "%Y%m%d")
if Config.date_conf()['until']:
until = since + timedelta(days=Config.date_conf()['until'])
else:
until = since + ... |
from django.db import models
class Article(models.Model):
file_obj = models.ImageField(upload_to='media/')
class coordinate(models.Model):
x = models.TextField()
def __str__(self):
return self.x
class Y_coordinate(models.Model):
y = models.TextField()
def __str__(self):
return sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.