text
stringlengths
38
1.54M
"""__author__ == ChiAo""" from datetime import datetime from flask_sqlalchemy import SQLAlchemy # 生成数据访问对象 db = SQLAlchemy() class Admin(db.Model): # 定义id主键,自增字段 id = db.Column(db.Integer, primary_key=True, autoincrement=True) # 管理员账号 admin_id = db.Column(db.String(10), unique=True, nullable=False...
""" A Recurrent Neural Network model using Word embedding training for sentiment analysis. Embedding layer is trained on full set of 1.6M tweets and 10k word vocabulary. Model uses two LSTM layers-> Dense layer Accuracies are pretty good. Training ~ 81.5% Validation ~ 81.62% Test ~ 81.49% Achievement: Model was able...
import os os.chdir("..") import pandas as pd from chip2probe.modeler.cooptrain import CoopTrain from chip2probe.modeler.bestmodel import BestModel import chip2probe.modeler.plotlib as pl import pickle from sklearn import ensemble, tree import subprocess import chip2probe.modeler.features.sequence as seq if __name_...
# -*- coding: utf-8; -*- # # (c) 2007-2010 Mandriva, http://www.mandriva.com/ # # $Id: beam_consts.py 53 2010-02-11 09:30:08Z nicolas $ # # This file is part of BeaM # # BeaM is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softwar...
# Generated by Django 3.0.2 on 2020-05-06 19:22 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('analysis', '0001_initial'), ('image', '0001_initial'), ] operations = [ migrati...
from flask import Flask,render_template,request import json # 将Python文件变成flask应用 # 通过flask构建一个对象,构件对象的时候将模块名传进去 app=Flask(__name__) # @app.route('/') # def blog_view(): # return render_template('./index.html') @app.route('/') @app.route('/index') def index_view(): return render_template('index.html') ...
import pandas as pd df = pd.read_csv('data.csv') print(df.head(10)) #print(df.head()) #print(df.tail(3)) #Get info print(df.info())
# from richard lin import shlex, subprocess from collections import namedtuple import os import warnings env = dict() if 'STANZA_CONFIG' in os.environ: stanza_config_dir = os.environ['STANZA_CONFIG'] else: stanza_config_dir = os.path.expanduser('~') stanza_config_file = open(os.path.join(stanza_config_dir, '.stan...
# Given an integer, n , print its first 10 multiples. # Each multiple n x i (where 1 <= i <= 10) should be printed on a new line in the form: n x i = result. # Input Format # A single integer, n. # Constraints # 2 <= n <= 20 # Output Format # Print 10 lines of output; each line i (where 1 <= i <= 10) contains the ...
import numpy as np import pandas as pd CITY_DATA = {'Chicago': 'chicago.csv', 'New York City': 'new_york_city.csv', 'Washington': 'washington.csv'} #define functions def load_data(city, month, day): print('Preparing dataframe!...', flush=True) df = pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_da...
''' Given a base Givenn another base Given n Given n numbers in the first base Return if they're palindromes in the second ''' import math def palindromeBases(): b1 = int(input("Base 1:")) b2 = int(input("Base 2:")) n = int(input("Number:")) # Find the two bases of the number and check i...
# -*- coding: utf-8 -*- import time import logging from mock import MagicMock, patch from . import unittest from kafka.common import TopicAndPartition, FailedPayloadsError, RetryOptions from kafka.common import AsyncProducerQueueFull from kafka.producer.base import Producer from kafka.producer.base import _send_upst...
import math x = 1 x = 1.1 x = 1 + 2j # a+ bi print(10 + 3) # addition operator print(10 - 3) # subtraction operator print(10 * 3) # multiplication operator print(10 / 3) # division operator returns the quotient with floating number print(10 // 3) # division operator returns the quotient with integer number prin...
from turtle import * from time import sleep colors = ['red', 'black', 'yellow', 'green', 'blue', 'pink'] turtles = [Turtle() for _ in range(6)] for i, t in enumerate(turtles): t.seth(360 / 6 * i) t.color(colors[i]) t.speed(10) t.width(20) for t in turtles: t.forward(200) for t in turt...
from collections import OrderedDict # 创建双向链表 class Node: def __init__(self, key, val): self.key = key self.val = val self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): # 构建首尾节点, 使之相连 self.head = Node(0, 0) self.tail = ...
from discord import Member from discord.ext.commands import Cog, BucketType from discord.ext.commands import command, cooldown from discord.utils import get from ..db import db class SideEvents(Cog): def __init__(self, bot): self.bot = bot @command(name='add') async def add_playe...
import unittest from main.resource_item import ResourceItem class ResourceItemTest(unittest.TestCase): def test_no_title(self): with self.assertRaises(Exception): ResourceItem("", "https://google.com") def test_no_url(self): with self.assertRaises(Exception): ResourceItem("title", "") def...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
# 管理文件 from flask_migrate import MigrateCommand, Migrate from flask_script import Manager import logging from app import create_app, db app = create_app('default') manager = Manager(app) Migrate(app, db) manager.add_command('db', MigrateCommand) @app.route('/', methods=['get']) def index(): return 'This is BBS...
xlist = [] ylist = [] xset = set() yset = set() def numDuplicates(l,n): return len([1 for x in l if x==n]) for i in range(3): a,b = input().strip().split(' ') xlist.append(a) ylist.append(b) xset.add(a) yset.add(b) xset = list(xset) yset = list(yset) ans = [] ans.append(xset[1]) if (numDuplic...
import numpy as np def find_top_n(array_data, top_k): """ 对array_data进行排序,前top_k个元素是最大值。 :param array_data: :param top_k: :return: """ for i in range(1, top_k): for j in range(i, 0, -1): if array_data[j][0] > array_data[j - 1][0]: array_data[j][0], arra...
from bottle import template import json from operator import itemgetter JSON_FOLDER = './data' AVAILABE_SHOWS = ["7", "66", "73", "82", "112", "143", "175", "216", "1371", "1871", "2993", "305"] def getVersion(): return "0.0.1" def getJsonFromFile(showName): try: return template("...
import numpy as np class DHCPRecord(object): def __init__(self, slot_id=None, slot_width=None, mac=None, desc=None, isiot=None, ethlen=None, hostname=None, vendor_class=None, req_lst=None, mds=None, msg_t = None, client_id = None): if slot_id is None: return self.slot_id = slot_id ...
import logging from . import GnuAbiCheckBase from .._logging import make_logger from ..cache.package_version_maps import DebianGlibcVersionsCache, UbuntuGlibcVersionsCache from ..models import AppImage from ..services import GnuLibVersionSymbolsFinder class LibkeyfileABICheck(GnuAbiCheckBase): def __init__(self,...
import concurrent.futures import time as cpytime from datetime import datetime from glob import glob from os import makedirs from os.path import exists, join import numpy as np import pandas as pd import pygrib from pyproj import Proj import sys class RTMALoader(object): """Handles data I/O and map projections ...
# Taken from https://github.com/geohot/twitchchess import base64 import traceback import time import os import chess import chess.svg from flask import Flask, Response, request from engine.value_functions import * from engine.engines import * app = Flask(__name__, static_folder="../static") board = chess.Board() e...
from django.shortcuts import render, HttpResponse, redirect from django.contrib import messages from .models import Show # Create your views here. def allShows(request): context = { 'all_shows': Show.objects.all() } return render(request, "shows.html", context) def addingShow(request): ...
class OpenMarket: borrowers = {} investors = {} loans = {} loan_requests = {} def generate_id(): return uuid.uuid4() # creates a borrower and adds to the borrowers dictionary # returns the id of the created borrower def create_borrower(self, name): new_borrower = Borrower(name) new_borrower_id = id(n...
# -*- coding: utf8 -*- import os.path import torch import torch.utils.data as data from data.image_folder import make_dataset from PIL import Image import random import nibabel as nib from abc import ABC, abstractmethod import numpy as np from util.myutils import normalizationminmax1 from util.myutils import...
from Interface import Interface import SocketServer import threading import socket import time import sys import RNS class UdpInterface(Interface): def __init__(self, owner, name, bindip=None, bindport=None, forwardip=None, forwardport=None): self.IN = True self.OUT = False self.transmit_...
import cv2 import numpy as np import TigerDetector as td cv2.namedWindow("Raw") cv2.namedWindow("Tiger Mask") detector = td.TigerDetector() video_in = cv2.VideoCapture("./demo_vid.avi") got_f, frame = video_in.read() while got_f == True: img_thresh = detector.textureMatch(np.array(frame)) cv2.imshow("Tig...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='BaseUnit', fields=[ ('id', models.AutoField(ver...
""" 【问题描述】 输入一组整数a,而后输入一个整数k,把k加入到数组a的尾部,然后输出整数数组。 【输入形式】 第一行。是一组整数a。用空格隔开。 第二行。是一个整数k。 【输出形式】 输出一行,即整数数组a。用1个空格隔开。 【样例输入】 1 2 3 4 5 【样例输出】 1 2 3 4 5 """ a = input().split() k = input() a.append(k) for r in a: print(r, end=" ")
import sys from sklearn.externals import joblib logreg = joblib.load('./Model/nhl.logistic_model.joblib') x = [0]*64 home = int(sys.argv[1]) away = int(sys.argv[2]) if home < 11: x[home-1] = 1 elif home < 31: x[home-2] = 1 else: x[home-23] = 1 if away < 11: x[away+31] = 1 elif away < 31: x[away+...
""" the merge-sort algorithm proceeds as follows: 1. Divide: If S has zero or one element, return S immediately; it is already sorted. Otherwise (S has at least two elements), remove all the elements from S and put them into two sequences, S1 and S2 , each containing about half of the elements of S; that is, S1 contain...
#!/usr/bin/env python import sys ''' - add version command - add help command - add sub command e.g: run_test.py run_demo1 ''' Version = ' Version:1.0.0 Time: 2018/09/07' def get_name(): print "print name..." def get_age(): print "print age..." if __name__== "__main__": if sys.argv[1].startsw...
import argparse from executor import Executor import minatar import lavaworld.environment if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--run-id', type=str, default=None) parser.add_argument('--process-index', type=int, default=0) parser.add_argument('--machine-na...
import numpy as np import matplotlib.pyplot as plt def convolution(in_data, response): '''Basic algorithm When h having m data, x having p data, then y[ni] = x[ni-(m-1)]h[m-1] + x[ni-m]h[m-2] + ... + x[ni-1]h[1] + x[ni]h[0] where ni is 0 to m+p-2 ''' # In the following calculation, ...
#sys library """ import sys def readFile(filename): f=open(filename) while True: line = f.readline() if(len(line) == 0): break print(line) f.close() if len(sys.argv) < 2: print("No action specified.") sys.exit() if sys.argv[1].startswith('--'): option=sys.ar...
import settingsJson class bcolors: HEADER = '\033[95m' BLUE = '\033[1;34m' CYAN = '\033[0;36m' YELLOW = '\033[0;33m' GREEN = '\033[1;32m' RED = '\033[1;31m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def printRedString( stringToPrint ): if set...
from flask_table import Table, Col from datetime import datetime from track_records import * # Declare your table class DailyTable(Table): classes = ['table', 'table-striped'] date = Col('Date') duration = Col('Duration') total_balls = Col('Total Balls') total_hits= Col('Total Hits') average_hi...
#Method 1: class Solution: def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ from collections import defaultdict n1 = defaultdict(int) for i in nums1: n1[i...
from levels.Level import Level from src.Platform import Platform class GrassLevel(Level): def __init__(self, screen, handler): super().__init__(screen, "media/Levels/field_map.png", handler) self.plat1 = Platform(screen, 0, 650, 1100, 150) self.plat2 = Platform(screen, 350, 400, 400, 50) ...
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten cnn = Sequential() cnn.add(Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1))) cnn.add(MaxPooling2D((2,2))) cnn.add(Conv2D(64, (3,3), activation='relu')) cnn.add(MaxPooling2D((2,2))) cnn.ad...
x = [3,1,2] y = [] min_ = None for i in x: if min_ == None: min_ = i elif i < min_: min_ = i print(min_) #chce zamienić miejscami 3 i 1 print(x.index(3)) print(x.index(1)) y = x[x.index (1)] y = x[x.index (3)] x[x.index(1)] = z x[x.index(3)] = y
import pandas as pd import numpy as np from resources import selection from src import plot_scatter, plot_bubble_map country_list = ["BRA", "CHN", "IND", "RUS", "ZAF"] # country_list = ["PAK", "PHL", "THA", "TUR", "ZWE"] # country_list = ["AFG", "COL", "PAK", "TUR", "ZWE"] # comment PPP and NFI generation # country...
""" Some support function for tkinter """ import logging import tkinter import cv2 import numpy as np from PIL import Image, ImageTk LOGGER = logging.getLogger(__name__) class TkConverter(object): def __init__(self): super().__init__() @staticmethod def read(image_path): img = Image.open...
from django.conf.urls import url from .views import ( CompanyListAPIView, CompanyCreateAPIView, CompanyUpdateAPIView, CompanyDeleteAPIView ) urlpatterns = [ url(r'^$', CompanyListAPIView.as_view(), name='list'), url(r'^create/$', CompanyCreateAPIView.as_view(), name='create'), url(r'^(?P<name>...
from __future__ import annotations import decimal import json import os from typing import List import boto3 from boto3.dynamodb.conditions import Attr, Key from flask import abort from flask_login import UserMixin from webapp import app, login_manager # Helper class to convert a DynamoDB item to JSON. class Decim...
from django.http import HttpResponse from datetime import datetime from django.views.generic import View from django.template.loader import get_template from .utils import render_to_pdf #created in step 4 from persona.views import Personal class GeneratePDF(View): def get(self, request, *args, **kwargs): temp...
#!/usr/bin/python from StatusFfc import statusFfc import json as json class parkingResponse(object): def __init__(self): self.status = statusFfc() self.response = None def getSuccessResponse(self): self.status = self.status.getSuccessStatus() self.response = None ...
# from django.test import TestCase # # # Create your tests here. # import datetime # # from django.utils import timezone # from .models import School # # # class QuestionMethodTests(TestCase): # # def test_q(self): # """ # query count test # """ # s=School(code="001",name="jy") ...
import sys from PyQt5 import QtWidgets from ui_process import PortScanner # 主程序入口 if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QMainWindow() ui = PortScanner() ui.setupUi(window) window.show() sys.exit(app.exec_())
import configparser class ConfigSettings: def __init__(self, cfg_path): self.cfg = configparser.ConfigParser() self.cfg.read(cfg_path) def getConfigSetting(self, section, key): try: ret = self.cfg.get(section,key) except configparser.NoOptionError: ret =...
# -*- coding: utf-8 -*- #!/usr/bin/env python import pygame from random import shuffle ncelx = 5 ncely = 4 cellsize = 80 set_ = list("abcdefghijkl") verde = pygame.Color("green") gris = pygame.Color("grey20") negro = pygame.Color("black") blanco = pygame.Color("white") def play_again(): texto = police...
def solve(): t = int(input()) for i in range(1, t+1): n,p = [int(s) for s in input().split(' ')] students = [] students.extend([int(s) for s in input().split(' ')]) students.sort(reverse=True) # Calculate remain = p - 1 j = 0 k = j + p - 1 arr_sum = sum(students[j+1:k+1]) min_hours = (students[j]...
import numpy as np import pandas as pd from math import floor import matplotlib.pyplot as plt # from statsmodels.stats.outliers_influence import variance_inflation_factor def load_data(path = "linearRegression_carPrice.csv"): data = pd.read_csv(path) dataset = data.values return dataset def int_encoder(da...
# -*- coding: utf-8 -*- import json import logging from urllib.parse import urlencode, urlparse from lncrawl.core.crawler import Crawler logger = logging.getLogger(__name__) class MTLNation(Crawler): base_url = [ "https://mtlnation.com/", "https://www.mtlnation.com/", ] has_mtl = True ...
#!/bin/python3 import sys import os args=sys.argv[1:] if args[0]=='-a': data=input("Enter data to be write :") with open('todo.text','w') as f: f.write("\n"+data+" ".join(args[1:])) if args[0]=='-v': contents=None with open('todo.text','r') as f: contents=f.read() print(contents) if args[0]=='-d': da...
import os import imp from setuptools import setup dirname = os.path.dirname(__file__) path_version = os.path.join(dirname, 'vaex/ml/_version.py') version = imp.load_source('version', path_version) name = 'vaex' author = 'Jovan Veljanoski' author_email= 'jovan.veljanoski@gmail.com' license = 'MIT' vers...
from anoky.common.errors import CodeGenerationError from anoky.generation.domain import StatementDomain as SDom, ExpressionDomain from anoky.generation.generation_context import GenerationContext from anoky.special_forms.special_form import SpecialForm from anoky.syntax import Element class NotInIsolation(SpecialForm...
# -*-coding:utf-8 -*- def hello_world(): print('hello world!') 込込込限込gh hahajhfak agjaklgjaljhal、 ajgkajklgjakgjakhgakh'
from flask import Flask, render_template, abort from jinja2 import Template app = Flask(__name__) app.debug = True app.jinja_env.line_statement_prefix = '#' app.jinja_env.line_comment_prefix = "##" files = ["favicon.ico", "style.css"] @app.route('/') def landing(): return render_template("landing.html", pythoncod...
import sys def memory_count(lst): memory = 0 for var in lst: print('***********') print(f'Переменная: {var}') print('Весит: ', sys.getsizeof(var)) spam = sys.getsizeof(var) if hasattr(var, '__iter__') and not isinstance(var, str): #Если объект итерируемый, но не строк...
from model_mommy import mommy from model_mommy.recipe import Recipe, seq import pytest from migraine.migrators import ValidationError from polls.models import OldPoll, NewPoll import migrators.polls as mp @pytest.mark.django_db def test_polls_migrator(): old_polls = mommy.make(OldPoll, _quantity=3) migrator ...
# Generated by Django 2.2.7 on 2019-11-25 18:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('agendapp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='agenda', ...
import requests import json import config language = "en" query = "covid" startDate = "2021-10-01" sortBy = "relevancy" # can be: popularity, publishedAt, relevancy searchUrl = f"https://newsapi.org/v2/everything?q={query}&from={startDate}&sortBy={sortBy}&apiKey={config.newsKey}&language={language}" country = "gb" #s...
from pdu import PDU from parallel_pdu import ParallelPDU from base_model import BaseModel from pipeline_test import PipelineTest from echo_pdu import EchoPDU from dau import DAU
#!/usr/bin/env python3 ######################################################################## # Filename : RPi-1-blink.py # Description : Prende y apaga un LED por [n] veces. # Author : jcondea # modification: 2020/10/06 ######################################################################## import time imp...
# -*- coding: utf-8 -*- import pandas as pd import numpy as np n, p=50,4 na_size=10 np.random.seed(96) X=np.random.randn(n,p) na_ind = np.random.randint(n*p, size=na_size) rows, cols = np.unravel_index(na_ind,(n,p)) X[rows,cols] = np.nan np.mean(X, axis=0) df=pd.DataFrame(X, columns=['X%d'%(i) for i in range(1,1+p...
import string ''' text="The narwhal bacons at midnight." print ' '.join(str(ord(c) - 96) for c in text.lower() if c.isalpha()) ''' text=text.replace(" ","") let=[] text=text.translate(None,string.punctuation) text=text.lower() for i in text: letter=string.lowercase.index(i)+1 let.append(letter) ...
from sys import intern from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, SubmitField, PasswordField, \ IntegerField, FloatField, ValidationError from wtforms.validators import DataRequired, Length, Email, EqualTo class ContactForm(FlaskForm): """Contact form to get feedback about the...
def print_rectangle(a, b, file): with open(file[1:-1], 'w') as f: for i in range(b): if i == 0 or i == b - 1: f.write(a * "*" + "\n") else: f.write(f"*{(a-2)*' '}*\n") def print_square(a, file): print_rectangle(a, a, file)
import json from django.http import HttpResponse from django.shortcuts import render import shanxi_tourism.models as models from django.http import HttpResponseNotFound from django.db.models import Q def get_attraction(request): """处理获取某个景点的请求 0.调用check_login()函数验证登录 1.首先从request中获取传递的参数: attract...
""" 该demo无任何意义,仅供测试使用 """ import pymysql houseCode_s = set() db = pymysql.Connection(host="localhost", port=3306, user="root", password="", database="lianjia", charset="utf8") cursor = db.cursor() sql = "select * from resblocksell;" cursor.execute(sql) results = cursor.fetchall() print(len(results)) ...
class Excepcion: def __init__(self,tipo,descripcion,fila,columna): self.tipo=tipo self.descripcion=descripcion self.fila=fila self.columna=columna def toString(self): return self.tipo+" - "+self.descripcion+" [ "+str(self.fila)+" - "+str(self.columna)+"]" ...
#!/usr/bin/env python # _ _ _ # ___ __ __ __ ___ (_) ___ | |_ ___ (_) _ _ # |_ / \ V V / / -_) | | (_-< | _| / -_) | | | ' \ # _/__| \_/\_/ \___| _|_|_ /__/_ _\__| \___| _|_|_ |_||_| # . # |\ Co...
class Computer: def config(self): print ("i5, 16gb, 1TB") com1 = Computer() Computer.config(com1) com1.config()
#!/bin/python3 import math import os import random import re import sys # Complete the jumpingOnClouds function below. def jumpingOnClouds(c): current = 0 end = n - 1 jumps = 0 while current < end: if ((current + 2) <= end) and (c[current + 2] == 0): current += 2 jumps ...
from django.conf import settings from .models import Client_Auth, Client from django.shortcuts import get_object_or_404 import random import datetime from obp.smsc_api import * class Auth(object): def __init__(self, request): self.session = request.session self.session.set_expiry(0) #reque...
import os from time import sleep from random import randint from random import choice import copy def cls(): os.system(['clear','cls'][os.name == 'nt']) def imprimir(tab,n): for i in range(n): for k in range(n): if tab[k][i] == 1: print(" O ",end="") else: ...
import math print math.pi print math.e print math.ceil(1.5) print math.floor(1.5) print math.pow(2,4) print math.log(10) print math.log(10,10) print math.sqrt(81) print math.fabs(-3) def root_quadratic(a,b,c): r1= (-b+math.sqrt(math.pow(b,2)-4*a*c))/(2*a) r2= (-b-math.sqrt(math.pow(b,2)-4*a*c))/(2*a) ...
import numpy as np from dao.anjuke_dao import process_anjuke_new_community_raw_data, process_anjuke_second_hand_community_raw_data import pandas as pd city_name = '重庆' name_list_to_add_into_new_community_data = ['community_id', 'community_address', ...
"""CLI commands of the application.""" import click from click import Context import scrywarden.database as db from scrywarden.curator import Curator from scrywarden.investigator.base import parse_investigators from scrywarden.profile.base import sync_profiles from scrywarden.profile.config import parse_profiles from...
# Generated by Django 2.1.7 on 2019-04-25 14:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('carrier', '0001_initial'), migrations.swappable_dependency(sett...
# -*- coding:utf-8 -*- # ----------------------------------------------------- # Project Name: pfm # Name: pfm # Author: mbegma # Create data: 28.03.2018 # Description: # Copyright: (c) Дата+, 2018 # ----------------------------------------------------- # Параметры запуска: # set FLASK_APP=pfm.py # set FLASK_DEBUG=1 #...
#!/usr/bin/env python # encoding: utf-8 """ """ import web import sys __author__ = 'adonis' def create_db_pool(host, port, user, passwd, db, pool_size=20, dbn='mysql', params=None): import web # Create DB pool ms = mc = pool_size # DB connection is thread safe, can not be used in multi-p...
from .reset import PasswordResetViewTest # noqa from .reset_digit import PasswordResetDigitViewTest # noqa from .reset_email import PasswordResetEmailViewTest # noqa
#!/usr/bin/python3 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] def selection_function(user_d): less_then = [] for i in a: if i < int(user_d): less_then.append(i) else: continue print(less_then) userDigit = input("Print smaller numbers than: ") selection_function(us...
# File: create-oracle-datasource.py # Author: hongxi@rancher.com # Set the variables # ====================================================================== import os dsname1 = os.environ.get('DATASOURCE_NAME') jndiname1 = os.environ.get('JNDI_NAME') #dbhost should be something like oracle.abc.com:1521:db dbhost1 = o...
import fnmatch import os def is_dir(path: str) -> bool: return isinstance(path, str) and os.path.exists(path) and os.path.isdir(path) def is_file(path: str) -> bool: return isinstance(path, str) and os.path.exists(path) and os.path.isfile(path) def get_file_extension(path: str) -> str: return os.path.splitext(...
#!/usr/bin/python3 # SEMI-IT Agriculture Support TOOLs Recorder # Ver. 1.0.6 2021/03/23 # Auther F.Takahashi # ###### Logging import logging logging.basicConfig(format='%(asctime)s %(message)s',level=logging.INFO) ## import from bluepy import btle from libCloud import sent_Ambient, sent_GAS from libMachineInfo impo...
# -*-coding:utf8-*- import MySQLdb import sys reload(sys) sys.setdefaultencoding('utf-8') def run(): conn = MySQLdb.connect( host='localhost', port=3306, user='root', passwd='454647', db='college_info', charset="utf8" ) cur = conn.cursor() sql_safe = '...
# -*- coding: utf-8 -*- GEPHI_HOST = '127.0.0.1' GEPHI_PORT = 8080 MONGODB_HOST = '127.0.0.1' MONGODB_PORT = 27080 MONGODB_DBNAME = 'test_database'
from app import app,db from flask_report_system_models import FlaskReport,FlaskReportParameter,FlaskParameter,FlaskReportDataColor from flask import render_template,request,url_for,redirect,make_response import json from sqlalchemy.sql import expression, functions from sqlalchemy import types from datetime import datet...
import requests from fandogh_cli.fandogh_client import base_url, get_exception from fandogh_cli.fandogh_client import get_stored_token base_domains_url = '%sdomains' % base_url def add_domain(name): token = get_stored_token() request = { 'name': name } response = requests.post(base_domains_u...
#coding=utf-8 # @lc app=leetcode.cn id=20 lang=python3 # # [20] 有效的括号 # # @lc code=start class Solution: def isValid(self, s: str) -> bool: if not s: return True if len(s) % 2 == 1: return False arr = list() chars = {')': '(', '}': '{', ']': '['} fo...
from django.urls import path from .views import home_page, rankings_page, search_page urlpatterns = [ path('', home_page, name='home_page'), path('search/<str:wanted>/', search_page, name='search_page'), path('rankings/', rankings_page, name='rankings_page'), ]
""" this module is mainly used to train our corpus according to UDpipe pre-train modules Remember: working directory needed to be set to wordfinder! """ # third-party modules import string import re import argparse from corpy.udpipe import Model from typing import List from src.train.base_model import ITrain from ...
from bisect import bisect_left, bisect_right n, x = map(int, input().split()) data = list(map(int, input().split())) def count_by_range(a, left_value, right_value): left = bisect_left(a, left_value, right_value) right = bisect_right(a, left_value, right_value) return right - left print(count_by_range(d...