text stringlengths 8 6.05M |
|---|
#camel-banana problem
total: int=int(input('Enter no. of bananas at starting :'))
distance=int(input('Enter distance you want to cover :'))
load_capacity=int(input('Enter max load capacity of your camel :'))
lose=0
start=total
for i in range(distance):
while start>0:
start=start-load_capacity
#Here... |
from urllib import request
class spider():
url = 'https://www.panda.tv/cate/lol'
def __fetch_content(self):
r = request.urlopen(spider.url)
htmls = r.read()
def go(self):
self.__fetch_content()
spider = spider()
spider.go()
# |
__author__ = "Narwhale"
import random
def insert_sort(li):
for i in range(1,len(li)):
tem = li[i]
j = i - 1
while j >=0 and li[j] > tem:
li[j+1] = li[j]
j = j-1
li[j+1] = tem
data = list(range(1000))
random.shuffle(data)
insert_sort(data)
print(data) |
#!/usr/local/bin/python3
import sys
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from math import ceil
import os
# Geometry variables
# Width
W = 148.5
# Height
H = 112.5
# Depth
D = 112.5
# Triangle leg length
a = 12.7
l = (a ** 2 - 0.25 * a ** 2) ** 0.5 # Triangle height, do not change
# ... |
from taiga.requestmaker import RequestMaker
from taiga.models import Severity, Severities
import unittest
from mock import patch
class TestSeverities(unittest.TestCase):
@patch('taiga.models.base.ListResource._new_resource')
def test_create_severity(self, mock_new_resource):
rm = RequestMaker('/api/v... |
"""This module visualizes the data by Borough and over all of NYC."""
#author: Matthew Dunn
#netID: mtd368
#date: 12/12/2015
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class retaurantGradeAnalyzer (object):
def __init__(self, allrestaurantsData, listofBoros):
self.allrestauran... |
"""Helpers stuff"""
import yaml
base_configuration = [
{
'application': {
'name': 'Flaskbox API',
}
},
{
'route': {
'name': 'users',
'fields': [
{'name': 'string'},
{'last_name': 'string'},
{'users'... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'users/last_synced', views.UserLastSyncedItemview.as_view(), name="User Last sync time"),
url(r'users/have_tokens', views.HaveTokens.as_view(), name="have_tokens"),
url(r'users/userrequestbackfill', views.UserBackfillRequestView.as_view(),nam... |
from time import sleep
import random
import os
import time
import sys
import json
import re
from urllib import request, parse
import name_get
import Chrome_driver
import email_imap as imap
import re
from pyrobot import Robot
import Submit_handle
from selenium.webdriver.support.ui import Select
'''
Adsmain health
Auto... |
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
#import hdbscan as hdb
from sklearn.cluster import KMeans, Birch
from wordcloud import WordCloud
from big_picture.clusters import Cluster
from big_picture.pre_processor import pre_process
from big_picture.vectorizers import tf_idf, embeddin... |
# -*- coding:utf-8 -*-
# Created by LuoJie at 11/16/19
import os
import pathlib
# 获取项目根目录
root = pathlib.Path(os.path.abspath(__file__)).parent.parent
# 训练数据路径
train_data_path = os.path.join(root, 'data', 'AutoMaster_TrainSet.csv')
# 测试数据路径
test_data_path = os.path.join(root, 'data', 'AutoMaster_TestSet.csv')
# 停用词路径... |
import math
def area_of_a_triangle(a,b,c):
semiperimeter = (a + b + c)/2
area = math.sqrt(semiperimeter*(semiperimeter-a)*(semiperimeter-b)*(semiperimeter-c))
return area
print(area_of_a_triangle(3,4,5)) |
from Tkinter import *
import serial
import thread
#{forward:0,backward:1,left:2,right:3,submerge:4,emerge:5}
arduino = serial.Serial('/dev/ttyACM0',9600)
input_count = 0
pwms_dictionary = {"forward":0,"backward":1,"left":2,"right":3,"submerge":4,"emerge":5}
top = Tk()
top.configure(bg="#353839")
top.wm_title("CSLAU... |
# -*- coding: utf-8 -*-
import cookielib
import datetime
import json
import os
import sys
import urllib
import urllib2
import urlparse
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
#######################################
# global constants
url_base = 'http://api.rtvslo.si/ava/'
client_id = '82013fb3... |
import web
import db
import json
urls = (
"/trains", "trains",
"/trains/(\d+)", "train"
)
app = web.application(urls, globals())
class trains:
def GET(self):
trains = db.get_trains().list()
return json.dumps(trains)
class train:
def GET(self, id):
t = db.get_train(id)
... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import sys
"""
Create argv[1] iff it doesn't already exist.
"""
outfile = sys.argv[1]
if os.path.exists(outfile):
sys.exit()
o... |
x = 3
x += 2
print(x)
y = 20
y -= 3
print(y)
z = 30
z %= 10
print(z)
a = 2
a **= 3
print(a)
b = 40
b //= 4
print(b) |
# import the necessary packages
from __future__ import print_function
from imutils.object_detection import non_max_suppression
from imutils import paths
import numpy as np
import argparse
import imutils
import cv2
# import the necessary packages
from collections import deque
import numpy as np
import argparse
import i... |
#!/usr/bin/python
import os, re, random
from bs4 import BeautifulSoup
totalFiles = int(open('parameters.txt', 'r').readlines()[0].strip())
testCount = min(5, totalFiles*1/100)
test = set(random.sample(list(xrange(totalFiles)), testCount))
filenumber = 0
for root, dirs, files in os.walk("./dataset/duc_2007"):
for fil... |
class Pessoa:
def __init__(self, nome, idade, cpf):
self.nome = nome
self.idade = idade
self.cpf = cpf
self.acordado = True
def fazNiver(self):
self.idade = self.idade + 1
def dormir(self):
self.acordado = False
print(self.nome + 'esta dormindo')
... |
# Copyright (c) Members of the EGEE Collaboration. 2004.
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# 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
#... |
"""
Script to create log summary of all .csv log files in folder db_testing
"""
import os
import csv
from Constants import LOG_SUMMARY_PATH, DB_TESTING_FOLDER, DB_2A_FOLDER, LOG_SUMMARY_2A_PATH, \
LOG_TOTAL_DB_2A_PATH, LOG_TOTAL_PARAM_2A_PATH, SPLIT_COMPUTATION
def create_log_summary(log_summary_path, db_te... |
from django.urls import path
from .views import (
AuthorListAPIView,
AuthorDetailAPIView,
BookListAPIView,
BookDetailAPIView,
)
urlpatterns = [
path("author", AuthorListAPIView.as_view()),
path("author/<int:pk>", AuthorDetailAPIView.as_view()),
path("book", BookListAPIView.as_view()),
p... |
import numpy as np
from TwoLayerNet import TwoLayerNet
# 5.7.4 ---------------------------
from DataSet.mnist import load_mnist
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
train_loss_list = []
iters_num = 1000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 元组的方法,元组只有两个方法
# count(x) 查询x在元组中出现的次数
# index(x) 查询x在孕足中第一次出现的位置
# 元组不可变,但是元组中嵌套的内容可以改变
list1 = [2, 3]
print('这里有个一列表:\n\t', list1)
t = (1, list1, 4)
print('将列表作为元组的元素t = (1, list1, 4)\n\t', t)
list1[1] = 99
print('修改列表内的元素list1[1] = 99\n\t', list1)
print('此时元组t的内容为:\n\... |
def _filter_attribute(attr: str):
return not attr.startswith('_') and attr != 'to_dict'
class SysConfig:
# system
DEBUG = False
TESTING = False
ENVIRONMENT = 'default'
SECRET_KEY = ''
JWT_SECRET = ''
APP_NAME = ''
# kernel
AUTH_BACKENDS = []
MAX_CONTENT_LENGTH = 1048576
... |
import click
import colorama
from sdcli.src.lib import info
from sdcli.src.lib import generator as creator
from sdcli.src.lib.error import print_output_error
@click.group()
def cli():
'''
CLI create by Streamelopers for generate our configuration on OBS.
'''
pass
@cli.command(help='For generate new... |
# -*- coding: utf-8 -*-
from heapq import heappop, heappush
from typing import List
class MaxHeap:
def __init__(self):
self.count = 0
self.els = []
def __len__(self):
return self.count
def _max(self):
_, el = self.els[0]
return el
def pop(self):
self... |
#!/usr/bin/env python3
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.hazmat.primitives import hashes
from cryptog... |
from web.services.notion_service.read import get_all_documents
|
import paho.mqtt.client as mqtt
import pymysql
import json
import threading
import time
import datetime
mqttc = mqtt.Client("subscriber_uji", clean_session=False)
class connectDB:
def __init__(self, id_rfid, pub_waktu_ctime, pub_waktu_datetime, sub_waktu_ctime, sub_waktu_datetime):
self.id_rfid... |
#!/usr/bin/python
import sys
import subprocess
import pandas as pd
import csv
dataset = open('dataset_S350.csv', 'r')
test_file = csv.reader(dataset, delimiter=',')
i = 0
classes = []
for line in test_file:
if(i == 0):
i = 1
continue
if(float(line[11]) >= 0):
classes.append(1)
else... |
import json
import math
import os
import cv2
from PIL import Image
import numpy as np
from keras import layers
from keras.applications import DenseNet121
from keras.applications import inception_resnet_v2
from keras.callbacks import Callback, ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
fro... |
from molecularfunctionsOOP import particleClass
#set global constants
Np=108
deltat=.004
mass = 1
dens = 0.85
temp = 0.9
particles = particleClass(Np, dens, temp,mass)
particles.changeForces()
print "Begin:"
particles.checkEnergy ()
particles.checkMomenta()
for i in range(10000):
#print "i= ",i
particles.update(... |
from . import stereo
|
#!/usr/bin/env python26
# -*- coding: utf-8 -*-
__author__="superwen"
__date__ ="$2013-08-07 17:19:10$"
from TvProgramBot.db.myStringFilter import getFilterTitle
s = [
['雄风剧场:读心专家 17', '读心专家'],
['法治时空 1194', '法治时空'],
['海豚万家剧场:爱在旅途Ⅱ 20', '爱在旅途2'],
['前情提要《花木兰传奇》37', '花木兰传奇'],
['非常6+1(1)', '非常6+1'],... |
#!/usr/bin/env python3
# Created by Marlon Poddalgoda
# Created on December 2020
# This program is an updated guessing game
import random
def main():
# this function compares an integer to a random number
print("Today we will play a guessing game.")
# random number generation
random_number = rando... |
from sqlalchemy import *
from migrate import *
meta = MetaData()
meetup_tbl = Table('meetup', meta)
meetupcom_id_col = Column('meetupcom_eventid', String, nullable=True)
def upgrade(migrate_engine):
meta.bind = migrate_engine
meetup_tbl.create_column(meetupcom_id_col)
pass
def downgrade(migrate_engine):... |
from django.urls import path
from . import views
#from .views import UserList, UserDetail
urlpatterns = [
#path('', views.index, name="index"),
path('register', views.register, name='register'),
path('register/visitor', views.visitor_register.as_view(), name='visitor_register'),
path('register/staff',... |
#!venv/bin/python
import os
import sys
from io import BytesIO
from PIL import Image
from mutagen.mp3 import MP3
from mutagen.mp4 import MP4
walk_dir = sys.argv[1]
wrongBitRate = set()
for root, subdirs, files in os.walk(walk_dir):
for file in files:
fileName, fileExt = os.path.splitext(file)
if f... |
s = input('Nhap chuoi: ')
if len(s) > 2 :
s_n = s[:2] + s[len(s)-2:]
else :
s_n = ''
print(s_n)
|
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
import geopandas as gpd
# import pysal as ps
import seaborn as sns
from pyproj import Proj, transform
from shapely.geometry import Point
import pandas as pd
import numpy
# from pysal.contrib.viz import mapping as maps
from classes.classDBOperatio... |
n, k = map(int, input().split())
remaining_time = 240 - k
# print(remaining_time)
for i in range(n, 0, -1):
# print(i)
if (5 * i * (i + 1)) / 2 <= remaining_time:
print(i)
exit()
print(0)
|
#!/usr/bin/env python3
#
import os, sys, json
import argparse
from nltk.tokenize import sent_tokenize
from tqdm import tqdm
import pdb
class Preprocess(object):
"""docstring for Preprocess"""
def __init__(self, args):
super(Preprocess, self).__init__()
self.data_path = args.data_path
... |
class Stats(object):
# For the moment, lets define this as raw stats from gear + race; AP is
# only AP bonuses from gear and level. Do not include multipliers like
# Vitality and Sinister Calling; this is just raw stats. See calcs page
# rows 1-9 from my WotLK spreadsheets to see how these are typica... |
from django.apps import AppConfig
class RouteCollectorConfig(AppConfig):
name = 'route_collector'
|
import numpy as np
import cv2
from keras.layers import Input
from keras.layers.convolutional import Conv2D
from keras.models import Model
from os.path import dirname as up_one_dir
from os import listdir
from os.path import isfile, join, abspath
def create_model(img, img_txt, dir_of_images, dir_save_to):... |
from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import os
import numpy as np
import time
import sys
import torch
from torch import nn
from torch.backends import cudnn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision.transforms imp... |
class NeweggDL:
APP_ID = ''
def check_for_listings(self, keyword):
return [{
"title": "MSI AMD Radeon RX 480 Armor 8GB OC Video Card GPU",
"url": "https://www.newegg.com/Product/Product.aspx?Item=9SIADFR7C82795&cm_re=rx_480-_-9SIADFR7C82795-_-Product",
"price": 329.99... |
#JTSK-350112
# student.py
# Taiyr Begeyev
# t.begeyev@jacobs-university.de
"""
File: student.py
Resources to manage a student's name and test scores.
"""
class Student(object):
"""Represents a student."""
def __init__(self, name, number):
"""All scores are initially 0."""
# print Constructor being ... |
# coding=utf-8
""""" 运行 “.” (当前)目录下的所有测试用例,并生成HTML测试报告 """""
import unittest
from src.lib import HTMLTestReportCN
class RunAllTests(object):
def __init__(self):
self.test_case_path = "."
self.title = "自动化测试报告"
self.description = "测试报告"
def run(self):
test_suite = unittest.T... |
from openerp.osv import fields, osv
import logging
from logging import getLogger
_logger = getLogger(__name__)
class claim_type(osv.osv):
_name = 'claim.type'
_description = "Type of program"
_columns = {
'claim_type': fields.selection([('1', 'Sickle Cell'), ('2', 'Bed Grant')], 'Claim Type'),
... |
#!usr/bin/env python
# -*- coding: utf-8 -*-
"""
Model class for all entries
"""
import src.DB.DAL as DAL
# governing class for all entries. this is a dict
class Model(dict):
table = None
fields = None
index = None
# get key, vales from **args
def __init__(self, **args):
super(Model, se... |
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class Fejkbiljett(App):
def build(self):
gen_btn = Button(text='Generera',
size_hint=(.90, .10),
pos=(5, 5),
font_size=21)
... |
from django.contrib import admin
# Register your models here.
from mezzanine.pages.admin import PageAdmin
from .models import Person, Project
admin.site.register(Person, PageAdmin)
admin.site.register(Project, PageAdmin) |
from ._interface import SmqtkRepresentation
from .classification_element import ClassificationElement, \
get_classification_element_impls
from .data_element import DataElement, get_data_element_impls
from .data_set import DataSet, get_data_set_impls
from .descriptor_element import DescriptorElement, get_descriptor... |
import numpy as np
singleDimArray = [1, 2, 3]
numpyArray = np.array(singleDimArray)
print("---Single Dimension Array---")
print(singleDimArray, type(singleDimArray))
print(numpyArray, type(numpyArray))
tenArray = np.arange(-10, 10)
print("range:", tenArray)
print("zeros:", np.zeros((3, 4))) # Forms 3 rows x 4 column... |
#!/usr/bin/env python
import collections
import functools
import webbrowser
import click
import requests
import termcolor
from . import client
from . import config
from . import filters
from . import output
from . import utils
DEFAULT_AGE_OF_ISSUES_TO_RESOLVE = 30 # days
DEFAULT_AGE_OF_ISSUES_TO_MARK_AS_SEEN = 7 #... |
from bs4 import BeautifulSoup
import uuid
from datetime import datetime, timedelta
class DataManager():
def create_data_file(self, elaborationDirectory, elaborationDate):
dataFile = open(elaborationDirectory + 'full_' + elaborationDate + '_data' + '.json', 'a+')
return dataFile
def create... |
"""
Invisible Objects
Vanilla Evennia does not allow true hidden objects by default.
The 'view' lock will prevent the object being displayed in a room's description
and stop the look command with "Could not view 'object(#9)'", where as
attempting to look at a non-existant object returns 'Could not find '<object>''.
... |
def swapsVarsInArray(array, i, j):
temp = array[i]
array[i] = array[j]
array[j] = temp
|
#!/usr/bin/env python
# coding: utf-8
# # Resnet
#
# ## Please watch Ng C4W2L01-C4W2L04, the first of which is found [here](https://www.youtube.com/watch?v=-bvTzZCEOdM&list=PLkDaE6sCZn6Gl29AoE31iwdVwSG-KnDzF&index=12).
#
# The convolutional neural network that we developed and ran was adequate for use on a small pro... |
# -*- coding:utf-8 -*-
import pandas as pd
from sklearn.preprocessing import LabelEncoder, StandardScaler, Imputer
from sklearn.preprocessing import OneHotEncoder
# from nltk.corpus import stopwords
# import nltk
from sklearn.manifold import TSNE
from sklearn.decomposition import TruncatedSVD
import codecs
import nump... |
from django.apps import AppConfig
class TastingsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tastings'
|
try:
from Tkinter import *
except ImportError:
from tkinter import *
class QuantityFrame(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.grid(row=1, column=2, padx=10, pady=10, sticky=N)
self.newq_label = Label(self, text = 'New Quantity:')
self.newq_label.grid(row=0, column=0, sticky=NW)... |
"""
у вас есть список элементов [1, 2, 3, 4, 5, 6, 7, 8]. Перебрать список используя foreach цыкл.
Элемент с нечетным индексом поместить в новый список кортежей где первый элемент это индекс а второй это значение. [(index, value)].
соответственно элементы с четным индексом поместить в другой список кортежей с тем же фо... |
from django.shortcuts import render
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
import requests
import os
import platform
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
def call_url(url... |
from responses.models import SurveyResponse
from responses.serializers import SurveyResponseSerializer, SurveyResponseAgeDepressionSerializer
from django.http import Http404
from rest_framework.views import APIView
from django.views import generic
from rest_framework import generics
from rest_framework.response import ... |
import grequests
urls = ['http://www.heroku.com','http://www.hackerschool.com','http://www.bbc.com']
def do_something(response, **kwargs):
print response.text
def req(urls):
rs = (grequests.get(u, hooks = {'response':do_something}) for u in urls)
x = grequests.map(rs)
return x
print req(urls) |
"""
TableEntry é uma classe que possui os seguintes campos:
- lexema
- tipo
- ponteiro para o valor
- num da linha
"""
class SymbolTable(object):
def __init__(self):
self.symbolTable = {}
def insertEntry(self, lexema, entry):
self.symbolTable[lexema] = ent... |
from redis import Redis
rd = Redis('119.3.170.97', port=6379, db=3, decode_responses=True)
if __name__ == '__main__':
print(rd.keys('*')) |
#!/usr/bin/env python3
# coding=utf-8
import json
import os
import sys
import time
class Context():
def __getattr__(self,name):
return self.__dict__[name]
def __setattr__(self,name,value):
self.__dict__[name] = value
def get(self,name,default=None):
try:
return self.__g... |
a = int(input("Enter no of rows:"))
myList = []
for i in range(a+1):
myList.append("*"*i)
print("",i)
print("\n".join(myList)) |
populationGrowthA = int(
input("Digite a ordem de habitantes da população do país A: "))
populationGrowthB = int(
input("Digite a ordem de habitantes da população do país B: "))
annualGrowthRateA = float(
input("Informe a taxa anual de crescimento da população do país A: "))
annualGrowthRateA = annualGrowt... |
import pymongo
import pandas
import bs4 as bs
import urllib.request
import re
from socket import error as SocketError
import errno
import pandas as pd
import requests
from datetime import datetime
period1 = 319579200
period2 = 1505145600
def get_historical_price(stock_id, start_date, end_date):
headers = {
... |
#!/usr/bin/env python
#coding:utf8
from . import editor
from models import NodeUtils, LinkUtils, GraphUtils
from flask import render_template, request, json, jsonify
from analysis.views import calculateCommunities
import sys
# 防止中文编译不过
reload(sys)
sys.setdefaultencoding("utf-8")
nodeUtils = NodeUtils()
linkUtils = L... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-30 15:23
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalogues', '0009_auto_20170830_1705'),
]
operations = [
migrations.RenameModel(
... |
Using Git
Git is a collaboration tool that is universally used by programmers
Below are the commands in git we will be using the most:
git init - initialize a connection between that folder and git
git add - show off your updates / differences between the repos
git commit -m "message here" - add a message to this inst... |
import json
import unittest
import responses
import pyyoutube
class ApiMembersTest(unittest.TestCase):
BASE_PATH = "testdata/apidata/members/"
MEMBERS_URL = "https://www.googleapis.com/youtube/v3/members"
MEMBERSHIP_LEVEL_URL = "https://www.googleapis.com/youtube/v3/membershipsLevels"
with open(BASE... |
def stray(arr):
return reduce(lambda prev, curr: prev ^ curr, arr)
|
from django.db import models
from django.contrib.auth import get_user_model
from gdstorage.storage import GoogleDriveStorage
gd_storage = GoogleDriveStorage()
class Run(models.Model):
id = models.AutoField(primary_key=True)
submitting_user = models.ForeignKey(get_user_model(), on_delete=models.SET_NULL, null... |
from django.contrib import admin
from polls import models
admin.site.register(models.Vote)
admin.site.register(models.VoteOption)
|
# coding:utf-8
def script(s, player=None):
from NaoQuest.objective import Objective
from NaoSensor.plant import Plant
import NaoCreator.SGBDDialogue.creer as bd
import NaoCreator.Tool.speech_move as sm
if not player:
print("Error in execution of post_script \"testobj1_post\": player is Non... |
numero_del_usuario = int(input("deci un numero del 1 al 10 ameo"))
numero_a_adivinar = 11
wea = 1
while numero_del_usuario != numero_a_adivinar and wea != 5:
numero_del_usuario = int(input("trata devuelta intento #" + str(wea)))
wea = wea + 1
if numero_a_adivinar == numero_del_usuario:
print("le pegaste ame... |
from django.shortcuts import render
# Create your views here.
#Контролер - функция
def index (request):
return render(request, 'index.html')
def products(request):
return render(request, 'products.html') |
from typing import List, Dict
import toml
import pandas as pd
import boto3
# small trick (hack) so that imports work for both pytest and aws lambda
try:
from .helpers import gen_checkup_id, get_filename, \
RULE_SUMMARY, get_date_as_string
except ImportError:
from helpers import gen_checkup_id, get_filenam... |
from common.run_method import RunMethod
import allure
@allure.step("极客数学帮(家长APP)/用户行课班帖/获取未读班贴数量")
def classfeedback_student_unread_note_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环... |
from mod_base import *
class DelAccount(Command):
"""Permanently delete an existing account.
Usage: delaccount username
"""
def run(self, win, user, data, caller=None):
args = self.args
if args.Empty():
win.Send("Please provide account to delete.")
return False
... |
from rest_framework import serializers
from .models import Deputy, PoliticalParty
class DeputySerializer(serializers.ModelSerializer):
class Meta:
fields = (
'id',
'name',
'party_name',
'declaration_id',
'workplace',
'incomes',
... |
'''
日历模块
'''
import calendar
# 返回指定某年某月的日历
print(calendar.month(2019,5))
# 返回指定年份的日历
# print(calendar.calendar(2018))
# 判断是否是闰年,是返回True;否则返回False
print(calendar.isleap(2008))
# 返回某个月的第一天的weekday(0~6)和当月天数
print(calendar.monthrange(2019,5))
# 返回每个月以每周为元素的列表
print(calendar.monthcalendar(2019,5))
|
'''
如何設計使用上下左右鍵來移動物件,按鍵會移動方向
by Ching-Shoei Chiang
'''
import random, pygame, sys
from pygame.locals import *
pygame.init()
FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()
# set up the window
screen = pygame.display.set_mode((800, 800), 0, 32)
pygame.display.set_caption('object moving')... |
""" Init file. """
from .base import BaseController #pylint: disable=import-error
from .horizon import HorizonController
from .faults import FaultController
from .interpolator import Interpolator
from .enhancer import Enhancer
from .extender import Extender
from .extractor import Extractor
from .best_practices import *... |
import pyowm
import time
import datetime
from datetime import datetime
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
#rpi pin config
RST = 24
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
# 128x32 display with hardware SPI:
disp = Adafruit_SSD1... |
#!/usr/local/bin/python3
# Test Modules
import sys
import pytest
from pytest import approx
from os import path
# Import module under test
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from python_package_template.constants import *
# Other imports
import math
def test_constants():
asse... |
import math
class Robot:
class Servo:
def __init__(self, angle, geometry):
self.deg = angle
self.rad = self._get_rad(self.deg)
self.geometry = geometry
self.max, self.min = self._get_max_min()
self.previous_servos = None
self.total_an... |
import numpy as np
import tensorflow as tf
from tensorflow.python.layers import core as layers_core
import RAKE, math, random
from zpar import ZPar
from data import array_data
import torch, sys,os
import pickle as pkl
from copy import copy
from bert.bertinterface import BertEncoding, BertSimilarity
from utils import ge... |
#!/usr/bin/env python
import redis
import re
import settings
import hashlib
r = settings.r
class Timeline:
def page(self,page):
pageStart = (page-1)*10
pageEnd = (page)*10
return [Post(post_id) for post_id in r.lrange('timeline',pageStart,pageEnd)]
class Model(object):
def __init__(self,id):
self.__dic... |
class SimulationResult:
def __init__(self, lowest_fitness: int, highest_fitness: int, avg_fitness: int, generation: int):
self.lowest_fitness: int = lowest_fitness
self.highest_fitness: int = highest_fitness
self.avg_fitness: int = avg_fitness
self.generation: int = generation
def get_distance_lowest(self) ... |
from django.conf.urls import url
from views import *
urlpatterns = [
url(r'^$', home, name = 'home'),
url(r'add_members$', add_members, name = 'add_members'),
url(r'show$', show, name = 'show'),
url(r'show_updated$', show_by_updated, name = 'show_by_updated'),
url(r'show_stale$', show_stale, name =... |
import imgpr as ip
import numpy as np
image = ip.image.openImage("example.png")
height, width = image.shape[:2]
cut = 150
init_energy = np.zeros(shape=(height, width), dtype=int)
init_energy[520:,:] -= 14
x = ip.placeholder(shape=(height, width))
s = ip.layers.seam(x, iters=cut, init_energy=init_energy, direction=i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.