text
stringlengths
38
1.54M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 18 10:51:44 2020 @author: kerstin """ from influxdb import InfluxDBClient import datetime import pandas as pd #import numpy as np from config import Config #define storing time as timebase in influx and grafana storingtime = datetime.datetime.utc...
import cv2 as cv import pyautogui as win img = cv.VideoCapture(0) while True: isTrue, frame = img.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) haar_cascade = cv.CascadeClassifier('haar_face.xml') faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=4) pri...
import math import emoji n = int(input(emoji.emojize("Digite o valor de :heavy_multiplication_x: : ", use_aliases = True))) primos = list(range(2,n)) for i in range (2,int(math.sqrt(n) + 1)): if i in primos: for j in range(i**2, n , i): if j in primos: primos.remove(j) if primos == []: print(emoji.emojize("n...
from flask_testing import TestCase from app import app, db from app.config import app_config class BaseTestCase(TestCase): def create_app(self): config_name = 'testing' app.config.from_object(app_config[config_name]) return app def setUp(self): app = self.create_app() ...
from django.db import models from uuid import uuid4 from transBack.models.persona import Persona class Proovedor(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) persona = models.ForeignKey(Persona) class Meta: verbose_name = "Proovedor" verbose_name_...
# return value of nCr when n and r are passed to function. # --- --- --- import math m=math.factorial def f(n,r): if n<r: return(False) # undefined value. else: a=m(n)/(m(n-r)*m(r)) return(int(a)) # --- --- ---
# coidng=utf-8 import yaml, os cur = os.path.dirname(os.path.dirname(__file__)) def read_token(yamlName="token.yaml"): p = os.path.join(cur, "Data", yamlName) with open(p, 'r') as f: t = yaml.load(f.read()) return t["Cookie"] if __name__ == "__main__": print(read_token())
class InfluxDBQuery: def append_clause(self, name, clause=None): additional_param = [] if clause != None and len(clause) != 0: additional_param.append(name) additional_param.append(clause) return additional_param # TODO improve code # add where clause to...
from django.shortcuts import render, redirect, HttpResponse from .forms import Profilereg, Clgreg from .models import profile from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages # Create your views here. def Profdet(request): i...
import sys from PyQt5.QtWidgets import QApplication,QMainWindow #导入Ui文件 from Qt5_python_GUI.CalldemoCalendar.demoCalendar import * #继承UI父类Ui_MainWindow class MyMainWindow(QMainWindow,Ui_MainWindow): def __init__(self): super(MyMainWindow,self).__init__() #继承主类 self.setupUi(self) self....
# -*- coding: utf-8 -*- """ Created by Zhao Baoxin on 12/3/18 ------------------------------------------------- File Name: solution28 Description : Author : zhaobx date: 12/3/18 ------------------------------------------------- Change Activity: 12/3/18: -------------...
#!/usr/bin/env python3 # gfm - Github Flavored Markdown to HTML # # gfm.py input.md import sys import requests def get_html(f): h = { 'Content-Type': 'text/plain', } url = 'https://api.github.com/markdown/raw' r = requests.post(url, headers=h, data=f) return r.text if __name__ == '__main...
from experta import * class Num_hours_per_day(Fact): pass def print_detail(sets, exc): if exc == "": return "" temparray = exc.split('%') num = round(int(temparray[1]) * sets) if num == 0: return "" temparray[1] = str(num) return temparray current_fitness = -1 bmi = -1 ...
# Generated by Django 2.2.10 on 2020-11-07 05:44 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('enquiry_order', '0004_auto_20201107_0521'), ] operations = [ migrations.AlterField( model_name='orderupdate', ...
import random, time, datetime class InvalidMoveException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Piece: """A list of tuples that contain the coordinates of the blocks in a piece, in respect to the left most block in the ...
""" Plotting utility functions Author: Arkar Min Aung """ import matplotlib.pyplot as plt import numpy as np import PIL.Image as Image import os def plot_grid(rows, cols, figsize, image_root_path, labels, data_shape): f, axes = plt.subplots(rows, cols, sharex=True, sharey=True, figsize=figsize) for ...
from lxml import etree import os from os.path import join path = 'C:/Users/djpillen/GitHub/vandura/Real_Masters_all' for filename in os.listdir(path): tree = etree.parse(join(path,filename)) coll_title = tree.xpath('//archdesc/did/unittitle')[0] coll_title = etree.tostring(coll_title) extptrs = tree.x...
class ManageObject: def __init__(self, logger): self.lg = logger def dump(self): self.lg.info("DUMP: " + str(self.__dict__))
import sqlite3 import time, requests from pymodbus.client.sync import ModbusSerialClient as ModbusClient import datetime, calendar import Fault_Records DB_NAME = "database_files/database("+(datetime.datetime.now()).strftime("%d_%m")+").db" TOKEN = "BBFF-lvCLFYli6t042gOWnPST2SXp3sFsKS" DEVICE_LABEL = "demo" ur...
'''command line program usage example''' import math from unittest import TestCase import numpy as np import matplotlib.pyplot as plt from prettycolors import generate_colors, generate_color class TestGenerate(TestCase): def test_generate_colors(self): '''main function to run if ran as main''' ...
#!/usr/bin/python words = raw_input().split() spaces = [] def go_right( word ): print ''.join( spaces ) + word spaces.extend( [ " " for c in word[:-1] ] ) def go_left( word ): for c in word[:-1]: spaces.pop(-1) print ''.join( spaces ) + word[::-1] for i, word in enumerate( words ): if i % 4 == 0: if len(...
import math from model.battery_capacity_fade import CapacityFade class EnergyStorage: def __init__(self, max_p_mw, max_e_mwh, initial_power=0.0, initial_soc=0.0, soc_history=[]): self.max_p_mw = max_p_mw self.max_e_mwh = max_e_mwh self.capacity_fade = CapacityFade(soc_history) if...
from python_ottawa_transit import api from python_ottawa_transit.api import OCTransportApi __version__ = '0.2.0' __all__ = ["api", "cli"]
#!/usr/bin/env python # coding=utf-8 import feedparser import json import urllib import urllib2 from flask import Flask from flask import render_template from flask import request app = Flask(__name__) RSS_FEEDS = {'hacking': 'https://rss.packetstormsecurity.com/news/tags/hacking', 'dos': 'https://rss.pa...
# -*- coding: utf-8 -*- # author : anthony # version : python 3.6 ''' 主程序处理模块,处理所有用户交互的东西 ''' import time from core import auth from core import accounts from core import logger from core import accounts from core import transaction from core.auth import login_required # transaction logger 交易记录器 trans_logger = log...
import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import KFold import keras from keras.models import Sequential from keras.layers.core import Dense,Activation,Dropout from keras.optimizers import SGD,Adam from keras.utils import np_utils n_classes=4 n_epoch=20 n_sample=10000 learning_rat...
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('insert_new_form', views.insert_new_form), path('delete_new_form', views.delete_new_form), path('upadte_new_form', views.upadte_new_form), path('enable_disable',...
from pathlib import Path from shutil import copy from tempfile import TemporaryDirectory from pyshould import should, should_not from momos import cli EXAMPLE_PATH = Path(__file__).parent / '..' / 'examples' / 'basic' def test_cli_include(capsys): try: cli.include.main(['gtest']) except SystemExit ...
""" Uso básicos de: Casting, If, Inputs, Búcles """ menu = """ Bienvenido al conversor de divisas 💸 1: Dolar américano 2: Dolar canadiense 3: Peso colombiano Elige una opción: """ opcion = int(input(menu)) def convertir(nombre_divisa, valor_divisa): pesos = input("Escribe la cantidad de p...
import time from locust import HttpUser, task class QuickstartUser(HttpUser): @task def hello_world(self): self.client.get("/") @task(3) def view_item(self): self.client.post("/predict", json={"CHAS":{"0":0},"RM":{"0":6.575},"TAX":{"0":296.0},"PTRATIO":{"0":15.3},"B":{"0":396.9},"LSTAT...
""" value_type_extractor.py Alex Davis, January 2019 Chris Tordi, January 2019 Script for generating a list of all the enumerations/types from Siemens point description reports """ import csv import os import re POINT_DESCRIPTION_DIRECTORY = "/Volumes/Seven/Downloads/Siemens Point Descriptions/" ...
def compare(a,b,equal): dummy = "\0" for i in range(len(a),0,-1): if a[:i]==b[:i] and (a[:i] not in equal): #print("equal",m) return a[:i] return dummy def compare2(a,b,equal): dummy = "\0" for i in range(len(a)): if a[i:]==b[i:] and (a[i:] not in e): ...
import bagit import os import re import subprocess import shutil import sys from tqdm import tqdm def repackage_aips(AIPRepackager): doing_dir = os.path.join(AIPRepackager.aip_to_item_queue, "Doing") for uuid in tqdm(AIPRepackager.project_metadata["uuids"], desc="Repackaging AIPs"): name = AIPRepackag...
import pytest from selenium.common.exceptions import TimeoutException from pages.base_page import BasePage from pages.locators import MainPageLocators, PortfolioLocators class MainPage(BasePage): def open_portfolio(self): try: self.browser.find_element(*MainPageLocators.PARENT_ROLE).click() ...
########################################################################## # # Copyright (c) 2020, Cinesite VFX Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions ...
from django import forms from django.contrib.auth.models import User from django.forms import ModelChoiceField from .models import Profile, Project, Project_Avaliacao class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "{}".format(obj.user.username) class LoginForm(fo...
from django.db import models from users.models import User # Create your models here. class Notification(models.Model): """通知""" content = models.CharField(max_length=200) is_checked = models.BooleanField() user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import time import sys import io import re import math import itertools #sys.stdin=file('input.txt') #sys.stdout=file('output.txt','w') #10**9+7 mod=1000000007 #start = time.clock() n=int(raw_input()) l=map(int, raw_input().split()) d={} for i in l: if i in d: d...
import werkzeug werkzeug.cached_property = werkzeug.utils.cached_property # Import libraries from keras.preprocessing.image import img_to_array from keras.models import load_model from flask_restplus import Api, Resource, fields from flask import Flask, request, jsonify import numpy as np from werkzeug.datastructures ...
#!/usr/bin/python # -*- coding: utf-8 -*- from modules import TVResourceTemplate, research import re, logging logger = logging.getLogger(__name__) class TVResource(TVResourceTemplate): baseurl = 'http://tv-only.org' def __init__(self, baseurl=baseurl): super(TVResource, self).__init__(baseur...
#!/usr/bin/env python """ Print the GUANO metadata found in a file or files. usage:: $> guano_dump.py [--strict] WAVFILE... """ from __future__ import print_function import sys import os import os.path from guano import GuanoFile def dump(fname, strict=False): print() print(fname) gfile = GuanoFi...
''' print("hello world!world!") print("hello world! ") print("------------------------------") print(999*123456789) print("------------------------------") type(2.333) print(type(2.333)) Valuetype =type(2333) print(Valuetype) print("------------------------------") print(1==1) print("-----------------------...
MOD = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) #inplace Heap sort '''insert and removeMin functions of priority queue were used with a little modifi...
# Guess the secret number # 4/20/2018 # CTI-110 P5HW2-Random Number Guessing Game # Lafayette King # # use the random module import random def main(): guess = 1 again = "Y" secret_number = random.randint(1, 100) guess = 1 guesses = 1 print("Guess the secret number! ") whi...
N, T = [int(_) for _ in input().split()] CT = [[int(_) for _ in input().split()] for i in range(N)] cs = [c for c, t in CT if t <= T] if cs: print(min(cs)) else: print("TLE")
import os from dataclasses import dataclass from dotenv import load_dotenv from fastapi.security import OAuth2PasswordBearer from passlib.context import CryptContext load_dotenv() @dataclass class Settings: SECRET_KEY = os.getenv("SECRET_KEY", "mysecret") ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES ...
# dict of states and their abbreviation states = { 'Oregon' : 'OR', 'California' : 'CA', 'Florida' : 'FL', 'New York' : 'NY'} # dict of states and their cities cities = { 'CA' : 'San Fran', 'FL' : 'Orlando'} # add more to cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # print some cities print '...
hang = [0] card = [0] def hang_card(hang,card): hang_len = len(hang) #print hang #print hang_len if hang[-1] <= card: while hang[-1] < card: hang.append(1000000/(hang_len + 1) + hang[-1] + 1) hang_len += 1 return hang_len - 1 else: for i in range(han...
from django.http import Http404 from django.shortcuts import render from django.contrib.auth.decorators import login_required, permission_required from .models import * @permission_required('home.view_news', login_url="/login/") def yantar(request): admin = Adminyantar.objects.all() if request.method == 'POST...
while True: sentence = str(input('\nEnter any word or sentence:')) while True: character=str(input("Of which single charcter count you want?:")) character=character.lower() if len(character) !=1: ...
from django import forms from .models import * import datetime from django.core.exceptions import ValidationError class CustomerForm(forms.ModelForm): def __init__(self , *args , **kwargs): super ( CustomerForm , self ).__init__ ( *args , **kwargs ) name = forms.CharField(error_messages={'required...
import json from tqdm import tqdm from collections import Counter import operator import decimal import sklearn.model_selection from nltk.tokenize import RegexpTokenizer from nltk.stem.snowball import SnowballStemmer import numpy as np if __name__ == '__main__': file_data_set = {} data_set = [] classes = ...
def soma_elementos(lista): num = 0 # Numero para iniciar a contagem for i in lista: # Vai somar o número (num) padrão mais o i da lista. num += i return num
import logging from .logger import get_handler, get_logger, \ LOG_NOSET, LOG_DEBUG, LOG_INFO, \ LOG_ERROR, LOG_WARNING, LOG_CRITICAL, \ set_name, set_level, add_console_handler, \ add_loghub_handler, debug, info, warning, \ error, critical, oss, init_logger logging.getLogger = get_logger
#! usr/bin/env python from ryu.ofproto.ether import ETH_TYPE_IP, ETH_TYPE_ARP,ETH_TYPE_LLDP,ETH_TYPE_MPLS,ETH_TYPE_IPV6 from ryu.ofproto.inet import IPPROTO_ICMP, IPPROTO_TCP, IPPROTO_UDP,IPPROTO_SCTP from flow_addition import FlowAdd import logging class Construct(): """ Constructs Match object from suppl...
#!/usr/bin/python from random import * prob = "keys" cases = [ (100,200), (100,200), (100,200), (100,200), (5000,10000), (5000,10000), (5000,10000), (5000,10000), (5000,10000), (5000,10000), (5000,10000) ] cur = 0 for...
# # 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020) # LAB 5-5 반복을 이용하여 팩토리얼을 계산하기, 126쪽 # n = int(input("정수를 입력하시오: ")) fact = 1 for i in range(1, n+1): fact = fact * i print(n, "!은", fact, "이다.")
import tkinter as tk import shapes shapes.circle() shapes.triangle() shapes.hexagon() shapes.octagon() shapes.pentagon() shapes.square() shapes.star() tk.mainloop()
def bsearch(l, x): """ Returns the index of an element in a list using binary srach Returns -1 if the element cannot be found """ index = 0 while len(l) > 0: mid_index = len(l) // 2 pivot = l[mid_index] if pivot == x: return index + mid_index elif pivo...
from utils.startToTree import StartToTree from taskUtils import setupTableEnv from taskUtils import setupTableEnv import nodes.meta import nodes.robot from tableNodes.item2bin import Item2Bin from taskUtils import tableManip import numpy import random import math import rospkg, roslib objects_path = rospkg.RosPack...
import json import datetime import urllib.request, json import pulsar from pulsar.schema import * class Covid19(Record): date = String() confirmed = Integer() deaths = Integer() recovered = Integer() country = String() with urllib.request.urlopen("https://pomber.github.io/covid...
""" 课程表 链接:https://leetcode-cn.com/problems/course-schedule 你这个学期必须选修 numCourses 门课程,记为 0 到 numCourses - 1 。 在选修某些课程之前需要一些先修课程。 先修课程按数组 prerequisites 给出,其中 prerequisites[i] = [ai, bi] , 表示如果要学习课程 ai 则必须先学习课程 bi 。 例如,先修课程对 [0, 1] 表示:想要学习课程 0 ,你需要先完成课程 1 。 请你判断是否可能完成所有课程的学习?如果可以,返回 true ;否则,返回 false 。 示例 1: 输入:nu...
from decimal import Decimal from decimal import getcontext print('0.1 + 0.1 + 0.1 - 0.3 =', 0.1 + 0.1 + 0.1 - 0.3) print('Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3) =', Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')) print('Decimal(1) / Decimal(7) =', Decimal(1) / Decimal(7)) getcon...
"""Base case, provide cluster specific assertion and cluster facilities to make test easy to read. """ from . import cluster from docker import errors class ClusterTestCase: def __init__(self): self.cluster = cluster.Cluster() def assert_key_exists(self, key): """Make sure a key exists in th...
#!/usr/bin/env python3 # Filename: teireader.py """ # Script for reading selected text from TEI files. """ import re import os import glob from lxml import etree def teireader(inpath): """Script for reading selected text from TEI files.""" for file in glob.glob(inpath): with open(file, "r") as infile...
import os import yaml def load_config(configpath): with open(configpath) as f: cfg = yaml.safe_load(f) experiment_id = os.path.splitext(os.path.basename(configpath))[0] cfg['experiment_id'] = experiment_id model_dir = cfg['output']['model_dir'] if model_dir: model_dir = os.path.jo...
# Generated by Django 2.1.7 on 2019-06-25 18:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("small_small_hr", "0006_auto_20181209_0108")] operations = [ migrations.AlterField( model_name="annualleave", name="year", ...
from event_testing.resolver import SingleActorAndObjectResolver, PhotoResolver from event_testing.test_events import TestEvent, cached_test from event_testing.tests import TunableTestSet from interactions import ParticipantType from sims4.tuning.tunable import HasTunableSingletonFactory, AutoFactoryInit import event_te...
from django.db import models from customuser.models import Customuser # Create your models here. #name,gender,email,phno,birthdate,specilized_in,hospitalname,hospitaladdress,hospitalstate,hospitaldistrict,shift,address,city,state,pincode,country,photo,username,password class Doctor(models.Model): user=models.Forei...
from django.conf import settings from django.conf.urls import patterns, url urlpatterns = patterns('apps.userprofile.views', # Only user's requests. url(r'^(?P<id>\d+)/$', 'user_profile', {'template': 'user.html', 'profile': False}, name='user_requests'), # Show user's full profile (private if th...
"""This module contains all the elastic search field type mapped to django""" from elasticsearch_dsl import Object, Text, Date, DocType from elasticsearch_dsl.connections import connections from elasticsearch.helpers import bulk # collection has many items so collection field is repeated all over the item # Reuse thi...
animals = ["cat", "ant", "bat"] animals.sort() for animal in animals: print animal # Write a for-loop that iterates over start_list and .append()s each number squared (x ** 2) to square_list. # Then sort square_list! start_list = [5, 3, 1, 2, 4] square_list = [] # Your code here! for number in st...
__author__ = 'Dave', 'Ryan' #!/usr/bin/python # Import Tkinter for GUI #----------------------------------------------------------------------------------------------------------------------- try: from Tkinter import * except ImportError: from tkinter import * #----------------------------------------------...
from django.shortcuts import render from .models import Status from .serializers import StatusSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import generics,mixins,permissions from rest_framework.authentication import SessionAuthentication from acco...
import os from django.core.paginator import Paginator from django.core.files.storage import FileSystemStorage from django.shortcuts import redirect from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.urls import reverse from django.http import HttpResponse from django.vie...
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(16, GPIO.OUT) for x in range(10): GPIO.output(16, GPIO.LOW) time.sleep(0.25) GPIO.output(16, GPIO.HIGH) time.sleep(0.25) GPIO.output(16, GPIO.LOW) time.sleep(0.25)
import sys from tqdm import tqdm from glob import glob from utils import Node, traverse_label, traverse import numpy as np import pickle import os import torch from collections import Counter import re from os.path import abspath import nltk from transformers import * import warnings warnings.filterwarnings("ignore") ...
import tkinter from time import sleep from math import sin, cos, atan2, pi # Parameters for canvas appearance CANVAS_WIDTH = 600 CANVAS_HEIGHT = 300 CANVAS_BACKGROUND_COLOR = 'black' CANVAS_TITLE = 'Topological Defects' # Pause time in seconds between canvas update PAUSE = 1/100.0 # Parameters for arrow ap...
# Complete the jumpingOnClouds function below. def jumpingOnClouds(c): steps = 0 i = 0 l = len(c) print(c) while i < l: print(i, steps) if i+2 c[i+2] or c[i+1] == c[i+2] else 1 steps += 1 elif i+1 < l: i += 1 steps += 1 else: ...
import datetime import time from . import room_info_bp, new_room_info_bp, hot_room_bp, country_hp, room_hp, type_hp, personal_hp from flask import request, render_template from ...utils.mysql_db import db from ...utils.util import unix_time @room_info_bp.route("/room_info") def room_info(): try: page = ...
#!/usr/local/bin/python #encoding:utf8 ''' Classify goods by name and rules. Name: ../data/goods_name.kv Rules: ../data/catwords.tsv In catwords.tsv, group name \t must have words \t optional words ''' import sys import os man_woman_child_rule = { 'man':set('男 商务 绅士 新郎'.split()), 'woman':set('女 妇 软...
import requests import os import shutil import pandas import datetime import pickle from pandas_datareader import data as pd_data from pandas_datareader import base as pd_base from bs4 import BeautifulSoup from formats.price_history import Instruments, Indice from formats.fundamentals import Valuations, StackedValuat...
# t0pic - pic.t0.vc # MIT License import random import string from flask import abort, Flask, request, redirect from pathlib import Path from PIL import Image PICS = Path('data') MAX_SIZE = 1920 PORT = 5003 URL = 'https://pic.t0.vc' POST = 'pic' def help(): form = ( '<form action="{0}" method="POST" acc...
# /usr/bin/env python3.5 # -*- mode: python -*- # ============================================================================= # @@-COPYRIGHT-START-@@ # # Copyright (c) 2020, Qualcomm Innovation Center, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification,...
def count_words(arr): words = {} for word in arr: if word not in words: words[word] = 1 else: words[word] = words[word] + 1 return words
import time import random from FixedLightStrip import FixedLightStrip from ZenShiftLightStrip import ZenShiftLightStrip if __name__ == '__main__': light_strip = ZenShiftLightStrip() while True: light_strip.get_next_state() light_strip.update() time.sleep(0.1)
from datetime import timedelta, datetime import MySQLdb import numpy as np import pandas as pd import matplotlib.pyplot as plt import urllib3 def query_mysql(fecha_fin, minutos_antes): horizonte_temporal = datetime.strptime('2018-07-19T23:00:00', '%Y-%m-%dT%H:%M:%S') flag = False cont = 0 while not fl...
#!/usr/bin/env python import sys, os import urllib2, urllib, cookielib import socket, random import time import gzip try: from cStringIO import StringIO except Exception, e: from StringIO import StringIO class urllibUtil(object): def __init__(self): socket.setdefaulttimeout(10) def openUrl(self, url, data=N...
from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.template.loader import render_to_string from django.db.models import Max class Post(models.Model): post = models.CharField(max_length=42) user = models.ForeignKey(User,on_d...
# -*- coding: utf-8 -*- """ Created on Fri Jan 1 15:19:49 2021 @author: Qalbe """ import numpy as np import pandas as pd import matplotlib.pyplot as plt dataset = pd.read_csv('Poly_dataSet.csv') X = dataset.iloc[:, 0:1].values y = dataset.iloc[:, 1].values from sklearn.ensemble import RandomFo...
import requests from datetime import datetime from django.conf import settings from celery import shared_task from celery_progress.backend import ProgressRecorder from .models import Channel, Video @shared_task(bind=True) def get_video_stats(self): progress_recorder = ProgressRecorder(self) Video.objects...
from processamento import Processar_Strings # Bibliotecas de suporte à execução do programa import pandas as pd import numpy as np import math import random class NaiveBayes: def __init__(self): self.ficheiro = None # Inicialização da variável ficheiro, que contém os dados lidos de "spam.csv" ...
# -*- coding: utf-8 -*- import scrapy import re import datetime class FootballResultSpider(scrapy.Spider): name = 'football_result' allowed_domains = ['info.sporttery.cn'] edate = datetime.date.today() sdate = edate - datetime.timedelta(days=7) start_urls = [ 'http://info.sporttery.cn/foot...
# Copyright (c) 2020-2022, Manfred Moitzi # License: MIT License import pathlib import ezdxf from ezdxf import zoom CWD = pathlib.Path("~/Desktop/Outbox").expanduser() if not CWD.exists(): CWD = pathlib.Path(".") # ------------------------------------------------------------------------------ # This example shows...
from django.db import models # Create your models here. class Movie(models.Model) : title = models.CharField('title', max_length=20) genre = models.CharField('genre', max_length=10) year = models.CharField('year', max_length=5) date = models.CharField('date', max_length=10) rating = models.CharFie...
from PylabUtils.misc.normCols import normCols from PylabUtils.misc.normRows import normRows from PylabUtils.misc.timing import Timer, tic, toc from PylabUtils.misc.expecting import expecting from PylabUtils.misc.find2 import find2 from PylabUtils.misc.minimizedAngle import minimizedAngle from PylabUtils.misc.circularMe...
import csv import math import random age_group = {} jobs = {"admin.": 0,"blue-collar": 1,"entrepreneur": 2,"housemaid": 3,"management": 4,"retired": 5,"self-employed": 6,"services": 7,"student": 8,"technician": 9,"unemployed": 10} marital = {"single": 0, "married": 1, "divorced": 2} education = {"illiterate": 0, "basi...
# --*-- coding : utf-8 --*-- # Project : Python_app # Current file : app_01.py # Author : 大壮 # Create time : 2019-12-21 11:14 # IDE : PyCharm # TODO 成长很苦,进步很甜,加油! from appium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_...
from flask_wtf import FlaskForm from flask_babel import lazy_gettext as _l from flask_pagedown.fields import PageDownField from wtforms.fields import StringField,TextAreaField,SubmitField,PasswordField,BooleanField from wtforms.ext.sqlalchemy.fields import QuerySelectField from wtforms.validators import DataRequired,Le...
import os import requests import slackPostman as sp from bs4 import BeautifulSoup line_career_url = 'https://recruit.linepluscorp.com/lineplus/career/list?classId=148' base_url = 'https://recruit.linepluscorp.com/' def get_stored_seqs(): seqs = [] if os.path.isfile('line.txt'): file = open('line.txt', 'r', -1...