text
stringlengths
8
6.05M
""" pytest configuration additions. """ from typing import final, Optional import numpy as np import pytest import sacc from firecrown.likelihood.gauss_family.statistic.statistic import ( Statistic, DataVector, TheoryVector, ) from firecrown import parameters from firecrown.parameters import ( Requir...
#standard import import pandas as pd import numpy as np import itertools from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, HashingVectorizer from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomFores...
#!/usr/bin/env python # -*-coding:utf-8 -*- # Author:Renkai dict1 = {'name':'wuya','age':18} dict2 = {'address':'xian'} # dict2 = dict1.copy() # print(dict2) # print(dict1.get('age')) # # for key in dict1.keys(): # print(key) # # for value in dict1.values(): # print(value) # # for key,value in dict1.items(): ...
#!/usr/bin/env python # See the argparse help further down or run [thisprogram] --help for a description of this program. # IDEAS # - Make it work for binary files (not using whole lines to calculate the ratio) # - Make it faster by using an index on the right tree, e.g. by putting 10-char snippets into a snippet-to-...
class EvenOddVendingMachine(int): def vending(x): if x % 2 == 0: print('Number is even') else: print('Number is odd') def find_range_stepwise(x, y, z): for i in range(x, y, z): print(i) if __name__ == '__main__': x = input('Enter a number: ') vending(int(x)) find_range_stepwise(int(x), int(9...
# -*- coding: utf-8 -*- ######################################################### # python import os import sys import logging import traceback import json import re import urllib import requests import threading # third-party # sjva 공용 # 패키지 from .plugin import logger, package_name from .model import ModelSetting, ...
import numpy from qiskit_shor import * from qiskit import QuantumCircuit, QuantumRegister from Qubit import * from qiskit import IBMQ from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import Shor def main(): print('################################################################') print('###...
from rv.readers.reader import Reader, ReaderFinished from rv.readers.sunsynth import SunSynthReader from rv.readers.sunvox import SunVoxReader class InitialReader(Reader): def process_SVOX(self, _): self.object = SunVoxReader(self.f).object def process_SSYN(self, _): self.object = SunSynthRea...
# File: configure_checker.py # Aim: Check the configuration from tools import Configure config = Configure() settings = config.getall() print(settings)
from datetime import datetime import time import os from get_db import db connection = db() c = connection.cursor() c.execute("SELECT * FROM sensor_data ORDER BY timestamp DESC LIMIT 10") res = c.fetchall() print("Latest Data:") for r in res: t = datetime.fromtimestamp(r[0]) print("Time: ", t, " TempC: ", r...
"""An evaluation defines how we go from trials per subject and session to a generalization statistic (AUC score, f-score, accuracy, etc) -- it can be either within-recording-session accuracy, across-session within-subject accuracy, across-subject accuracy, or other transfer learning settings.""" # flake8: noqa from .ev...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_bcrypt import Bcrypt from flask_bootstrap import Bootstrap import psycopg2 db = SQLAlchemy() bcrypt = Bcrypt() login_manager = LoginManager() # Import Blueprints Here from src.user.routes import upgrade_bl...
# -*- encoding: utf-8 -*- #from flask_sqlalchemy import SQLAlchemy #db = SQLAlchemy() from sqlalchemy import Column, Integer, Text from database import db from database import Base class Paste(Base): __tablename__ = 'paste' id = Column(Integer, primary_key = True) #hash = db.Column(db.String(32), unique =...
#!/usr/bin/python3 import spaceking.net as net import spaceking.server.net as sv_net import spaceking.common as com import spaceking.game as game import spaceking.log as log import spaceking.event as ev import asyncio import socket class GameServer(net.NetObserverMixin): """Game server""" def __init__(self...
# -*- coding: utf-8 -*- #!/usr/bin/env python import io import time import homie import logging import threading import json import base64 from PIL import Image import requests import websocket logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logging.getLogger("requests").setLevel(loggi...
from sublime_lib._util.named_value import NamedValue from unittest import TestCase class TestNamedValue(TestCase): def test_named_value(self): s = "Hello, World!" self.assertEqual( repr(NamedValue(s)), s )
import numpy as np from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import AdaBoostRegressor from sklearn import datasets from sklearn.metrics import mean_squared_error, explained_variance_score from sklearn.utils import shuffle import matplotlib.pyplot as plt # 1.9 估算房屋价格 # 1.9.2.02 加载房屋价格数据库 hou...
#!/usr/bin/env python import socket import time import sys import subprocess from multiprocessing import Process global clientName clientName = "" """ http://docs.python.org/2.7/library/socket.html """ """ returns socket s that is connected to port at ip_connect """ def connect_to(ip_connect, port): for res in so...
import os from day_9 import main current_dir = os.path.dirname(os.path.abspath(__file__)) test_input_file = os.path.join(current_dir, 'test_input.txt') def test_invalid_xmas(): test_preable_list, test_number_list = main.convert_input(test_input_file, 5) invalid_number = main.search_invalid_xmas(test_preable...
from datetime import datetime from pytz import timezone from flask import current_app from sqlalchemy.orm.exc import NoResultFound, FlushError from sqlalchemy.exc import IntegrityError from sqlalchemy import text import phonenumbers from phonenumbers import PhoneNumberFormat from twilio.rest import Client from .m...
#-*- coding:utf8 -*- import sys import time import datetime import json import urllib import pycurl from django.core.management import setup_environ import settings setup_environ(settings) from celery import group from shopapp.tmcnotify.models import TmcMessage,TmcUser,DEFAULT_GROUP_NAME from shopapp.tmcnotify.tasks ...
"""ST-Link Automation Example""" import stlink if __name__ == '__main__': print(f'List of ST-Link: {stlink.findall()}') print('Flashing:...', end='') status, checksum = stlink.flash('G:\\test.hex') print(status)
from django.apps import AppConfig class GameConnectionsConfig(AppConfig): name = 'game_connections'
import pyaudio import wave def record_for_time(audio_format,audio_channel,bitrate,chunk_size,record_time): pa = pyaudio.PyAudio() stream = pa.open(format=audio_format, channels=audio_channel,rate=bitrate,input=True,frames_per_buffer=chunk_size) audioframes = [] for i in range(0, int(bitrate / chunk_size * record_t...
# -*- coding: utf-8 -*- import abc """ Clase abstracta para piezas, las piezas (Torre, caballo, etc) herederán esta clase y deberán impletementar los métodos """ class Pieza(): __metaclass_ = abc.ABCMeta #no sé que es """Constructor para Pieza""" def __init__(self, _current, color): self._current = _current ...
# __author__ = 'cjweffort' # -*- coding: utf-8 -*- from numpy import * from numpy.linalg import * """ 5 Linear Algebra """ """ 5.1 Simple Array Operations """ a = array([[1.0, 2.0], [3.0, 4.0]]) a.transpose() u = eye(2) print u j = array([[0.0, -1.0], [1.0, 0.0]]) dot(j, j) print trace(u) #矩阵的迹 y = array([[5.], [7.]...
from orun.utils.deprecation import MiddlewareMixin from .shortcuts import get_current_site class CurrentSiteMiddleware(MiddlewareMixin): """ Middleware that sets `site` attribute to request object. """ def process_request(self, request): request.site = get_current_site(request)
import inspect, os, sys import shutil import subprocess import random, string import re from shutil import copyfile import base64 import json NODE_BIN = '../node/node' WALLET_BIN = '../wallet/wallet' VERBOSE = False def getCurrentDir(): return os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()...
from selenium import webdriver from selenium.webdriver.common.by import By from utilities.handy_wrappers import HandyWrappers import time class UsingWrappers(): def test(self): baseURL = "https://letskodeit.teachable.com/pages/practice" driver = webdriver.Firefox(executable_path=r"C:\Users\Federic...
import pandas as pd import crd_rbd # example 1 # example of data in list data_ = [ [20, 16, 26, 26, 34, 28, 20, 18], [26, 22, 26, 24, 38, 30, 24, 29], [32, 28, 32, 24, 36, 48, 36, 24], [48, 42, 34, 36, 42, 54, 50, 45], ] # give the data unique rows and column labeling and convert to dataframe data_ = ...
import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset('tips') print(tips.head()) sns.distplot(tips['total_bill']) plt.show() sns.distplot(tips['total_bill'],kde=False,bins=30) plt.show() sns.jointplot(x='total_bill',y='tip',data=tips,kind='scatter') plt.show() sns.jointplot(x...
#!/usr/bin/python # -*- coding: UTF-8 -*- from django.forms import ModelForm from django import forms from coddy.models import * class DonateForm(ModelForm): class Meta: model = Donate fields = ['name', 'surname', 'email', 'tel'] labels = { 'name' : 'Имя', 'surname...
__version__ = '7.0.0a1'
""" Django settings for myproject project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) ...
#Algorithm To implement First Come First Serve n=int(input('Enter the Number of Process : ')) process=[int(x) for x in input('Enter the Process Number : ').split()] burst_time=[int(x) for x in input('Enter the burst time of the Process : ').split()] total_waiting_time=0 for ith_process in range(n): pri...
hour = int(input()) minutes = int(input()) minutes += 15 if minutes >= 60: hour += 1 minutes -= 60 if hour >= 24: hour -= 24 print("{0}:{1:02d}".format(hour, minutes))
import pytest import pdb from fhireval.test_suite.concept_map import example_code_system_source, reset_testdata from fhirwood.parameters import ConceptMapParameter test_id = f"{'2.8.2':<10} - ConceptMap Translate" test_weight = 2 def test_codemap_translate(host): reset_testdata(host) result = host.post('Conc...
#!/usr/bin/python #\file scipy_solve_1d_eq.py #\brief Comparing method for solving 1d variable equation. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Jan.21, 2021 import scipy.optimize import time f= lambda x: x+x**2+x**3 - 2.5 bounds= [-1.0,1.0] #bounds= [-1.0,0.5] #NOTE: Setup where t...
#!/usr/bin/env python """ this fabric supposed to speed things up when doing parallel rsync but in our case it actually slowed things down. But i decided to leave it for mems :) Maybe someday i'll make it work as expected. """ from fabric.api import * from fabric.contrib import files, project from fabric.cont...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019 shady <shady@MrRobot.local> # import datetime from peewee import MySQLDatabase from peewee import ( Model, CharField, IntegerField, BooleanField, FloatField, DateTimeField, PrimaryKeyField, ) from config imp...
"""Xonsh AST tests.""" from nose.tools import assert_equal from xonsh import ast from xonsh.ast import Tuple, Name, Store def test_gather_names_name(): node = Name(id='y', ctx=Store()) exp = {'y'} obs = ast.gather_names(node) assert_equal(exp, obs) def test_gather_names_tuple(): node = Tuple(el...
#-*- encoding=utf8 -*- #!/usr/bin/env python import re, sys, operator, string path_to_stop_words = './BasicData/stop_words.txt' path_to_text = './BasicData/Pride_And_Prejudice.txt' class WordFrequencyFrameWork: _load_event_handlers = [] _dowork_event_handlers = [] _end_event_handlers = [] def regist...
from onegov.activity import Occasion, OccasionNeed from onegov.core.security import Secret from onegov.feriennet import FeriennetApp, _ from onegov.feriennet.exports.base import FeriennetExport from onegov.feriennet.forms import PeriodExportForm from sqlalchemy.orm import joinedload, undefer @FeriennetApp.export( ...
from django.db import models from django.contrib.auth import get_user_model from products.models import Product User = get_user_model() class Deal(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='Пользователь', rela...
from __future__ import print_function class Unit(object): def __init__(self, name, id, team, jsonData): self.name = name self.id = id self.team = team self.health = jsonData['Health'] self.max_health = jsonData['MaxHealth'] self.location...
x = 10 # odd if x % 2 == 0: print('odd') else: print('evan') # x equals 10 if x > 10: print('x bigger than 10') elif x < 10: print('x less than 10') else: print('x equals 10') ACTUALLY_RELEASE_YEAR = 1991 inputYear = int(input("please guess the python release year:")) if inputYear > ACTUALLY_REL...
import threading class InstanceHealth(object): """Thread safe object to communicate between the worker thread and the API thread.""" def __init__(self): self._errors = {} self._lock = threading.Lock() def add_degraded(self, key, error): """ Args: key (str) ...
import csv # imports the csv module import sys # imports the sys module #import MySQLdb header_year = [ 'Ter', '01', '02', '03', '04']; header_gender = ['M', 'F', 'T'] def readCountriesData(): f = open('01-04.csv', 'rb') # opens the csv fil rownum = 0 try: reader = csv.reader(f ,delimite...
n =int(input()) all=[] for i in range(n): a = int(input()) if(not (a in all)): all.append(a) print(len(all))
import pandas as pd df = pd.read_csv('stock-data.csv') print(df.head(),'\n',df.info(),'\n') print("#문자열 데이터(시리즈 객체)를 판다스 Timestamp로 변환 및 데이터 내용 및 자료형 확인") df['new_Date']=pd.to_datetime(df['Date']) print(df,'\n') print(df.info(),'\n') print(type(df['new_Date'][0]), '\n') # 시계열 값으로 변환된 열을 새로운 행 인덱스로 지정. 기존 날짜 열은 삭제 d...
import pandas as pd import matplotlib.pyplot as plt import numpy as np import joblib from sklearn.model_selection import StratifiedShuffleSplit from sklearn.impute import SimpleImputer from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHo...
#import sys #input = sys.stdin.readline from collections import deque def main(): N, M, K = map( int, input().split()) H = list( map( int, input().split())) C = list( map( lambda x: int(x)-1, input().split())) AB = [ tuple( map( lambda x: int(x)-1, input().split())) for _ in range(M)] E = [[] for _...
# Attributes and Methods for fallback_mode # Auto-execute numpy method when corresponding cupy method is not found # "NOQA" to suppress flake8 warning from cupyx.fallback_mode.fallback import numpy # NOQA
""" Contains upgrade tasks that are executed when the application is being upgraded on the server. See :class:`onegov.core.upgrade.upgrade_task`. """ from onegov.core.upgrade import upgrade_task from onegov.core.orm.types import UTCDateTime from sqlalchemy import Column from typing import TYPE_CHECKING if TYPE_CHECK...
def _makeHexStr(a): return format(a, '#04x') def _generateTenAccounts(): prefixes = [_makeHexStr(i) for i in range(10)] postfix = "195c933ff445314e667112ab22f4a7404bad7f9746564eb409b9bb8c6aed32" return [prefix + postfix for prefix in prefixes] tenAccounts = _generateTenAccounts()
#!/usr/bin/python # coding: utf-8 # Copyright 2013 The Font Bakery 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...
import re from itertools import permutations text_file = open('Day 21\\Input.csv') test_file = open('Day 21\\Test.csv') lines = text_file.read().split('\n') test_lines = test_file.read().split('\n') inp_p1 = 'abcdefgh' inp_p2 = 'fbgdceah' test_inp = 'abcde' def swap_pos(inp, line): string = '' ...
import string from selenium import webdriver from wordcloud import WordCloud from Read import getUser, getMessage from Socket import openSocket, sendMessage from Initialize import joinRoom import time time1 = int(time.time()) time2 = int(time.time())+300 s = openSocket() joinRoom(s) readbuffer = "" messageList = [] #d...
""" Author: Nicholas Baron 830278807 Date: 3/25/2018 Description: This is a class that will allow the operator to communicate and write speeds to Robosub's ESCs axialy. """ import sys sys.path.append("/home/nick/python_driver/Adafruit_Python_PCA9685") sys.path.append("/home/nick/github/Controls/RaspberryPi/") import Ad...
import cv2 face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") img=cv2.imread("news.jpg") img_g =cv2.imread("news.jpg",0) faces=face_cascade.detectMultiScale(img_g,scaleFactor=1.1,minNeighbors=5) for x,y,w,h in faces: img_updated=cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),5) print(fa...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^match/(?P<match_pk>[0-9]+)/$', views.match, name='match'), url(r'^benchmark/(?P<benchmark_pk>[0-9]+)/$', views.benchmark, name='benchmark'), url(r'^(?P<tour_name>[^/]+)/$', views.submit, ...
list1 = ["Derbes", "Azamat", "Dauren","Dana","Derbes", "Derbes","Dias"] set1 = set(list1) for i in set1: if list1.count(i) > 1: print(i)
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2018-03-13 10:38 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('nova', '0078_permission'), ] operations = [ migrations.AlterModelOptions( ...
from Cases.Takeaway.Codes.TakeawayCase import PreProcessingTakeaway import pandas as pd import matplotlib.pyplot as plt from matplotlib.pyplot import figure import numpy as np import nltk #nltk.download('punkt') #one-time download #nltk.download('stopwords') #one-time download from nltk.tokenize import word_tok...
from flask import Flask, request, jsonify, json from cassandra.cluster import Cluster import requests import sys cluster = Cluster(['cassandra']) session = cluster.connect() app = Flask(__name__) base_url = "http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline" @app.route('/') def hello(): name =...
# (c) 2012 Urban Airship and Contributors from django.test import TestCase from mithril.models import Whitelist from mithril.tests.utils import fmt_ip import random import netaddr class WhitelistTestCase(TestCase): def test_netaddr_integration(self): # just a tiny range, here test_ip = random.ra...
import numpy as np import pandas as pd data = pd.read_csv('../data/computer-configuration.csv') cores = data['cores'] frenquecy_per_core = data['frenquecy.per.core'] video_mem = data['video.mem'] ram = data['ram'] print 'Percentile Results - 50%' print '* *' print 'CORES -> {r}'.format(r = np.p...
import pygame class Score: def __init__(self, app): self.screen = app.screen self.score = 0 def draw(self): self.screen.blit(self.score_letters, self.score_rect) def update(self): self.font=pygame.font.Font("assets/fonts/HyliaSerif.ttf", 32) s...
import datetime import jwt import bcrypt from server.flask_app import app, db from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() work_tag_table = db.Table('work_tag_table', db.Column('tag_id', db.Integer, db.ForeignKey('tags.id'), primary_key=True), db.Column('work_id', db.Int...
#!/usr/bin/env python # encoding: utf-8 import numpy as np from pandas import read_csv from sklearn.model_selection import KFold from pandas import DataFrame import sys from sklearn import preprocessing class logistic_regression: def __init__(self, eta, optimizer): self.eta = eta self.optimizer ...
def rotate(nums, k): """ Do not return anything, modify nums in-place instead. """ def numReverse(start, end): while start < end: nums[start], nums[end] = nums[end], nums[start] start += 1 end -= 1 k = k%len(nums) if k: numReverse(0, len(nu...
# # Copyright 2008,2009 Free Software Foundation, Inc. # # SPDX-License-Identifier: GPL-3.0-or-later # # The presence of this file turns this directory into a Python package ''' This is the GNU Radio AMR module. Place your Python package description here (python/__init__.py). ''' import os # import pybind11 generate...
import time import praw #identifies the bot to reddit r = praw.Reddit('Dogecoin giveaway tipper') #input username and password the bot will use here. r.login("USERNAME","PASSWORD") already_done = set() words = ['Giveaway', 'giveaway'] def find_giveaway(): print 'Starting...' subreddit = r.get_subredd...
from django.contrib import admin # Register your models here. from domain.models import UrlModel class UrlAdmin(admin.ModelAdmin): list_display = ['url_name', 'url'] admin.site.register(UrlModel, UrlAdmin)
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-07-23 01:06 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('metodo', '0003_auto_20180720_1544'), ] operations = [ migrations.AddField( ...
from typing import List from daos.book_dao import BookDAO from entities.book import Book from exceptions.book_unavailable_error import BookUnavailableError from exceptions.not_found_exception import ResourceNotFoundError from services.book_service import BookService import time class BookServiceImpl(BookService): ...
import json import urllib2 class NYTimesScraper(): def __init__(self, apikey): # Creates a new NYTimesScraper Object using the apikey that was included. self.key = apikey self.url = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?' def _build_params(self, params): if no...
# 처음 생각했던 방법이 맞네 # 두가지 테스트케이스에서 시간 초과 # mid를 예외로 두지 않는 풀이는 시간 초과가 나지 않았음, 두 코드 비교 분석하기 def solution(n, times): start, end = times[0], times[-1] * n while True: mid = (start + end) // 2 man_cnt, answer = 0, 0 for t in times: each = mid // t man_cnt += each ...
#_*_coding:utf-8_*_ from django.conf.urls import patterns, include, url from django.views.generic import TemplateView urlpatterns = patterns('', url(r'^$','apps.accounts.views.login',name='login'), url(r'^register/?$','apps.accounts.views.register',name='register'), url(r'^register/invate_code/(.+)$','app...
# Generated by Django 2.2.7 on 2019-11-20 21:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0044_auto_20191121_0302'), ] operations = [ migrations.AlterField( model_name='product', name='name', ...
# input the photo in datas to faceset, set ID as its dir name import os from os import path import face_API as face import pre_process as pp data_path = '/Users/xander/Documents/code/classroom_recognization_system/datas' def updateall(): pp.small_datas() face.clear_faceset() os.chdir(data_path) pa = os.getcwd...
from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Student(models.Model): puid = models.PositiveIntegerField(primary_key = True) name = models.CharField(max_length = 200) email = models.EmailField(blank = True) phone = PhoneNumberF...
from __future__ import print_function import sys import sgf from pyspark import SparkContext#, HiveContext from pyspark.sql import SQLContext, Row, DataFrame #,SparkSession from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils def getSparkSessionInstance(): if ('sparkSessi...
from collections import deque import sys input = sys.stdin.readline ########################################################## ######################## 전역 변수 ######################## ########################################################## actions = [lambda x: x+1, lambda x: x-1, lambda x: x*2] ####################...
# ----------------------------------------------------------------------------- # 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. # ------------------------------------------------...
#!/usr/bin/env python3 # coding=utf-8 from Functions import * import multiprocessing from multiprocessing import Process import sys def ShowIcon(): 状态栏及通知().run() def AlwaysCheck(pid): 开始登陆=执行() 开始登陆.登陆() while 1: 开始登陆.检查网络() time.sleep(3) pid=int(pid) if CheckProcess(pid...
# Generated by Django 2.0.6 on 2018-06-28 09:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('sale', '0007_auto_20180628_1632'), ] operations = [ migrations.AlterField( model_name='transfer...
from flask import Flask, render_template, request, redirect from flask_mysqldb import MySQL import yaml app = Flask(__name__) # config db conf = yaml.load(open("config.yaml")) app.config["MYSQL_HOST"] = conf['mysql_host'] app.config["MYSQL_USER"] = conf['mysql_name'] app.config["MYSQL_PASSWORD"] = conf['mysql_passwo...
from PyQt4.QtGui import * from . import editconnectiondialog class TStandardConnectionDialog(QDialog): def __init__(self,p_connections,parent=None): QDialog.__init__(self,parent) l_top=QVBoxLayout(self) l_buttonTopBox=QDialogButtonBox(self) l_top.addWidget(l_buttonTopBox) l_addButton=l_buttonTopBox...
#!/usr/bin/env python # coding: utf-8 # Copyright 2013 The Font Bakery 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/LIC...
import requests, json r = requests.get('https://kmuin.com/api/v1/notices/') print(r.text)
import boto3 from botocore.client import Config ID = 'xxxx' #AWS access ID SECRET = 'xxx' #AWS secret access key BUCKET_NAME = 'xxxxx' #s3 Bucket name data = open('agne.jpg', 'rb') s3 = boto3.resource( 's3', aws_access_key_id=ID, aws_secret_access_key=SECRET, config=Config(signature_version='s3v4') ...
from django.urls import path from sign import views_if urlpatterns = [ path('test/', views_if.test, name='test'), path('add_event/', views_if.add_event, name='add_event'), path('get_event_list/', views_if.get_event_list, name='get_event_list'), ]
from . import base, launch, util from .base import config_for_dir
# Generated by Django 3.0.7 on 2020-10-09 08:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cl_app', '0002_auto_20201009_0613'), ('cl_table', '0016_postaud'), ] operations = [ migrations.AddF...
from django.shortcuts import render,redirect, get_object_or_404, get_list_or_404 from django.views.decorators import gzip from django.http import StreamingHttpResponse, HttpResponseServerError import cv2, time, operator, datetime from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.image i...
class Student: def __init__(self, name, age): self.name = name self.age = age def study(self, couser_name): print("%s正在学习%s." % (self.name,couser_name)) def main(): stu1 = Student('sherlock', 18) stu1.study('Python') if __name__ == '__main__': main()
n = 3 m = 4 a = [0] * n for idx in range(n): a[idx] = [0] * m a[0][0] = 5 print(a[1][0])
from flask import Flask, abort, request import json from file_functions import crear_archivo, dar_archivos, eliminar_archivos from last_files import get_last_files app = Flask(__name__) @app.route('/archivos', methods=['POST']) def crear(): cont_json = request.get_json(silent=False, force=True) ...
import sys import math from fractions import Fraction memo = {} saved = 0 def p(i: Fraction, n: Fraction) -> Fraction: global saved assert i >= 1 and n >= 0 key = (i, n) if key in memo: saved += 1 return memo[key] res = None if n == 0: return Fraction(1) # no ...