text
stringlengths
38
1.54M
import math import heapq def find_min(d, check): u = max(d, key=d.get); m = d[u] for k in d.keys(): if d[k] < m and k not in check: m = d[k] u = k return u def dijkstra(adj_list, S, E, node_to_block): print("Dijstra's\n---------") n_iters = 0 # all nodes unvisi...
turno = input('Qual turno você estuda? Digite M-matutino ou V-Vespertino ou N- Noturno: ') resposta = turno if resposta == 'M': print(' Bom dia!' ) elif resposta == 'V' : print(' Boa tarde!' ) elif resposta == 'N' : print(' Boa noite!' ) else: print('Valor invalido!')
import matplotlib.pyplot as plt import numpy as np import wave from sklearn.decomposition import NMF def get_audio_signal(wav_file): wav = wave.open(wav_file, 'r') signal = wav.readframes(-1) return np.frombuffer(signal, dtype=np.int32) def print_wav_details(wav_file): wav = wave.open(wav_file, 'r')...
import enum import logging from anisub.processors import SubtitlesProcessor from anisub.providers import AnimeInformationProvider class NameOrder(enum.Enum): eastern = 0 western = 1 def __str__(self): return self.name class NameOrderProcessor(SubtitlesProcessor): def __init__(self, anime_...
""" Class for storing apiVersions, which are the best method for comparing versions. :: >>> from pymel import versions >>> if versions.current() >= versions.v2008: ... print "The current version is later than Maya 2008" The current version is later than Maya 2008 """ from maya.OpenMaya ...
import cv2 import numpy as np from PIL import Image import libpreviewer def clip(v, minv, maxv): return max(min(v, maxv), minv) class BaseGenerator(object): def _setup(self, image_size, fov=50.0, latitude=0.0, longitude=0.0, preview_size=(1000, 750)): self.image_size = tuple(map(int, image_size)) ...
#!/usr/bin/env python3 import yaml import argparse import subprocess import sys parser = argparse.ArgumentParser(description='Argparse example') parser.add_argument('-y','--yaml', help='Some YAML file', required=True) args = parser.parse_args() with open(args.yaml, 'r') as f: doc = yaml.safe_load(f) if doc['bucke...
""" Pipeline Actions Provide infrastructure for creating and scheduling celery tasks. Action is a container for a task, to provide some syntactic sugar without messing around with Task class internals. To register actions, define a task function and a TaskAction subclass that refers to it, or (preferably) use the @ac...
from django.urls import path from basket import views urlpatterns = [ path('', views.index, name="player"), path('list', views.index, name="list"), path('rosters', views.general, name="rosters"), path('list_player', views.listplayer, name="player_list"), path('list_coach', views.listcoach, name="c...
import os if os.environ.get('PRODUCTION') == 'False': REALM_URL = 'http://localhost:8000/' RETURN_URL = 'http://localhost:8000/users/login' else: REALM_URL = 'http://nanoproblems-dev.elasticbeanstalk.com/' RETURN_URL = 'http://nanoproblems-dev.elasticbeanstalk.com/users/login'
from urllib.request import urlopen from urllib.error import HTTPError from tkinter import messagebox import urllib.parse import tkinter as tk import os @@ -13,6 +15,10 @@ "highTemp": "", } data = {} key = os.environ.get("OPENWEATHER_API") def kelvin_to_farenheit_conversion(temperature): converte...
# Copyright (c) 2016, the Cap authors. # # This file is subject to the Modified BSD License and may not be distributed # without copyright and license information. Please refer to the file LICENSE # for the text and further information on this license. from pycap import PropertyTree, EnergyStorageDevice from pycap im...
# Enter your code here. Read input from STDIN. Print output to STDOUT import math t = int(input()) for i in range(t): n = int(input()) f = 0 if n==1: f=1 else: for j in range(2,int(math.sqrt(n))+1): if n%j==0: f=1 break if f==0: pri...
import numpy as np import copy def MED_DP(i,j): # initializing cache cache = np.zeros([i+1,j+1],dtype=int) for row in range(i+1): cache[row][0] = row for column in range(j+1): cache[0][column] = column # filling cache with answers for row in range(1,i+1): for column in...
from mlagents_envs.environment import UnityEnvironment from mlagents_envs.base_env import ActionTuple from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel from mlagents_envs.registry import default_registry import random import numpy as np import matplotlib.pyplot as pl...
import nltk import random import string from nn import NN from jd import Normal from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() k=NN() n = Normal() class NLP: def __init__(self): self.symptoms=set() self.sentence='' self.greeting_input = ("hello", "hi", "greetings", "...
import os script_dir = os.path.dirname(__file__) def solve(data): for i, n1 in enumerate(data): for j, n2 in enumerate(data): for k, n3 in enumerate(data): if i == j or i == k or j == k: continue if n1 + n2 + n3 == 2020: ...
import requests url="https://finans.truncgil.com/today.json" resp=requests.get(url) read=resp.json() date=read["Update_Date"] dolarSatis=read["USD"]["Satış"] message="Hello, Current dollar as of {} \nDollar:{} TL\nHave a good day".format(date, dolarSatis) print(message)
from django.contrib import admin from django.urls import path, include from .views import LatestPosts, UserProfile, UserProfileForPublic, PostAPIView, SearchEngine, CommentAPIView, LikePost, FollowUser, Reportpost urlpatterns = [ path('userdetail', UserProfile.as_view()), path('user', UserProfileForPublic.as_v...
#label: line sweep difficulty: medium class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: from typing import List size = len(intervals) if size < 2: return size intervals.sort(key=lambda x: x[0]) remove_count = 0 max_rig...
# # Copyright 2017 Google Inc. # # 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...
import os import io import sys import re # wrapper for print def printw( message ): print( message ) try: import Crypto from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA from Crypto.PublicKey import RSA except Exception as e: printw( "Missing required module: "+str(e) ) s...
# -*- coding: utf-8 -*- # import the necessary packages from timecoverspider.items import MagazineCover import datetime import scrapy import traceback class CoverSpider(scrapy.Spider): name = "brickset_spider" start_urls = ["http://brickset.com/sets/year-2016"] def parse(self, response): try: ...
import folium from folium import Choropleth, Circle, Marker, Icon, Map from folium.plugins import HeatMap, MarkerCluster def sf_coordinates(): """ Gives the coordinates of San Francisco Returns: The coordinates as a point """ return {'type': 'Point', 'coordinates': [37.773972, -122.431297]...
from __future__ import division cols = ['delay', 'month', 'day', 'dow', 'hour', 'distance', 'carrier', 'dest', 'days_from_holiday'] col_types = {'delay': int, 'month': int, 'day': int, 'dow': int, 'hour': int, 'distance': int, 'carrier': str, 'dest': str, 'days_from_holiday': int} data_2011 = read_csv_f...
from distutils.core import setup setup( name='pyimcompare', author='Ryan-Saklad', install_requires=['opencv-python', 'pyautogui'], packages=['pyimcompare'], url='https://github.com/Ryan-Saklad/pyimcompare', version='0.1' )
from bs4 import BeautifulSoup from urllib.request import urlopen page = urlopen("https://www.cnet.com/pictures/video-games-mario-zelda-nintendo-switch/") soup = BeautifulSoup(page) games = soup.findAll('h2') captions = soup.findAll('p') top_games = {} games2 = [] url = 'https://www.cnet.com/pictures/vid...
# Required Libraries from flask import Flask, render_template, request, make_response import jsonify import requests import json from requests.sessions import Request import joblib import numpy as np # Importing the model model = joblib.load('xgb_modelfinal.joblib') app = Flask(__name__) # Templa...
#!/usr/bin/env python # @Author # Chloe-Agathe Azencott # chloe-agathe.azencott@mines-paristech.fr # August 2018 """ Utilities for scm-gwas. """ import argparse import numpy as np import os import sys def _minimum_uint_size(max_value): """ Find the minimum size unsigned integer type that can store values ...
'''pymysql基本流程演示''' import pymysql #链接数据库 db = pymysql.connect(host='localhost',port=3306,user='root',passwd='123456',database='stu',charset='utf8') #获取游标 cur = db.cursor() #数据操作 cur.execute("insert into myclass values(2,'zhangsan',12,'w',87)") db.commit() #关闭游标和数据库连接 cur.close() db.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Xiang Wang @ 2016-09-18 11:36:43 import datetime from datetime import date class Week(object): """ this first monday of a year starts the firt week. Every week starts from monday and end in sunday. """ _FIRST_ISOWEEKDAY = 1 # the isoweekda...
from APP.Apis.CheckEmailApi import CheckEmailR from APP.Apis.CheckNameApi import CheckNameR from APP.Apis.EmailActiveCheckApi import CheckEmailActiveR from APP.Apis.ForgetPasswordApi import CheckPasswordR from APP.Apis.IndexApi import IndexR from APP.Apis.LogoutApi import LogoutR from APP.Apis.RegisterApi import Regis...
def f(m): for i in range(len(m)): for j in range(len(m[i])): m[i][j] += 1 m = [[0,0], [0, 1]]
from numpy import * faltas = array(eval(input("Faltas: "))) n = zeros(6) for x in faltas: if(x == 2): n[0] = n[0] + 1 elif(x == 3): n[1] = n[1] + 1 elif(x == 4): n[2] = n[2] + 1 elif(x == 5): n[3] = n[3] + 1 elif(x == 6): n[4] = n[4] + 1 else: n[5] = n[5] + 1 for i in range(size(n)): if(n[i] > 0):...
# Function implementing Selection Sort def selection_sort(arr): arr_len = len(arr) for i in range(0, arr_len): min_idx = i for j in range(i + 1, arr_len): if arr[j] < arr[min_idx]: min_idx = j if min_idx != i: arr[min_idx], arr[i] = arr[i], arr[min...
from django.db import models from .doctors import Doctors class Patient(models.Model): p_surname = models.CharField(max_length=20, blank=True, null=True) doctor = models.ManyToManyField(Doctors, through="PatentDoctorTb", null=True, blank=True) p_fullname = models.CharField(max_length=20, blank=True, null...
from django.shortcuts import render from .forms import CommentForm from django.contrib.auth.decorators import login_required from .services import ( add_profile_photo_service, change_profile_photo_service, add_work_service, get_all_current_user_works, home_page_service, comment_view_service, ...
""" Solution for Algorithms #253: Meeting Rooms II - N: Number of intervals - Space Complexity: O(N) - The `timestamps` list. - Time Complexity: O(N log N) - Sorting `timestamps` take O(N log N). Runtime: 48 ms, faster than 76.49% of Python3 online submissions for Meeting Rooms II. Memory Usage: 16.5 MB, less tha...
''' Problem set: https://www.spoj.com/problems/CANDY/ Status: Accepted ''' n=input() while n != -1: a=[] s =0 for i in range(0,n): d=input() s += d a.append(d) avg = int(s/n) if avg*n != s: print -1 else: r=0 for i in range(0,n): if a...
from collections import defaultdict from .iterator import Iterator class Container(object): """Contrain""" def __init__(self, *args, **kwargs): self.objects = kwargs.get('objects', list()) assert isinstance(self.objects, list) self.parent = kwargs.get('parent', None) self.iter...
import cv2 import numpy as np import glob import matplotlib.pyplot as plt # selected threshold to highlight yellow lines yellowLinesThMin = np.array([0, 70, 70]) yellowLinesThMax = np.array([50, 255, 255]) def applyThresholdOnHSV(frame, thMin, thMax, verbose=False): HSV = cv2.cvtColor(frame, cv2.COL...
import unittest from lup_factor import Matrix class MatrixTests(unittest.TestCase): def setUp(self): a = [ [2, 1, 3], [4, -1, 3], [-2, 5, 5] ] b = [17, 31, -5] self.m = Matrix(a, b) def test_y(self): self.assertEqual(self.m.y[0], 17) self.ass...
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> #importing library >>> from tkinter import * >>> from tkinter import ttk >>> window =Tk() >>> #Declaring Window Title >>> window.title('Regis...
# Generated by Django 2.0.2 on 2018-08-28 09:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('navigation', '0009_auto_20180828_0951'), ] operations = [ migrations.RenameField( model_name='main', old_name='address', ...
""" Visualisation utilities for working with alphaMELTS table outputs. Todo ------- * Pull out mineral compostional trends """ from pyrolite.util.plot import proxy_line from ..tables.load import import_tables from .style import phase_color, phaseID_linestyle
# -*- coding: utf-8 -*- """ Created on Mon Dec 31 14:39:35 2018 @author: milli script to generate a wordcloud a free ebook """ import sys import os currentdir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(currentdir) import pdfParser as pp import matplotlib.pyplot as plt import matplotlib import nump...
# Generated by Django 2.2.3 on 2020-03-10 13:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0004_userprofile_name'), ] operations = [ migrations.AddField( model_name='userprofile', name='starred', ...
# Generated by Django 3.2.3 on 2021-06-16 11:23 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ('main', '0004_auto_20210616_1015'), ] operations = [ ...
# 2. Объявите класс Rectangle, хранящий координаты верхней левой и правой нижней точек. # Создайте дескрипторы для записи и считывания этих значений в классе (атрибуты с данными координат должны быть приватными). class Rectangle: def __init__(self, x = 0, y = 0): # объявлен один конструктор ...
from flask import Flask import os from flask_login import LoginManager from flask_admin import Admin from flask_mongoengine import MongoEngine from flask_socketio import SocketIO # settings.py from dotenv import load_dotenv from mongoengine import connect, disconnect load_dotenv() app = Flask(__name__) app.secret_key...
""" Script that computes the regulation trajectory of the rotor and the annual energy production Nikhar J. Abbas, Pietro Bortolotti January 2020 """ import logging import numpy as np from openmdao.api import Group, ExplicitComponent from scipy.optimize import brentq, minimize, minimize_scalar from scipy.interpolate ...
import traceback import os from flask import request, send_file from flask_restful import Resource from flask_uploads import UploadNotAllowed from flask_jwt_extended import ( jwt_refresh_token_required, get_jwt_identity, create_access_token, create_refresh_token, get_raw_jwt, jwt_required ) fro...
# -*- coding: utf-8 -*- import datetime import logging from google.appengine.api.labs import taskqueue from google.appengine.api import mail from google.appengine.ext import db from google.appengine.api import urlfetch from google.appengine.api.urlfetch_errors import DownloadError from google.appengine.ext import web...
players=['Charlie','Charles','Billy','Jimmy'] print("here are the players that won the game") for player in players[:3]: print(player.title())
# 000560_03_02_FUNCTIONS.py print() print("000560_03_02_ex01_functions_example") # Функция, три раза выводящая "spam" def my_function(): print('spam') print('spam') print('spam') my_function() print() print("000560_03_02_task01_functions_hello") # заполнить пропуски, с тем, чтобы функция выводила "h...
#!/usr/bin/env python """Short docstring Long Docstring """ import math import logging import networkx as nx import numpy as np import csv from ..BaseClasses import * from ..Events.Event import Event from ..Node.Patch import Patch __author__ = "Michael Pitcher" __copyright__ = "Copyright 2017" __credits__ = ["Mic...
""" Django settings for website project. Generated by 'django-admin startproject' using Django 1.9.8. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os fro...
import random import matplotlib.pyplot as plt sample_size=10000 sampleS=[0]*sample_size s_n=0 Y=0 for i in range(sample_size): sampleS[i]=random.random() s_n+=sampleS[i] print("Theoretical mean= 0.5, simulated mean=%f"%(s_n/sample_size)) x=[1+i for i in range(100)] y=[sampleS[i] for i in range(100)] ...
# visualizes data import matplotlib.pyplot as plt import json #takes the number of users wanted, and then prints a pi plot based on the most texts def top_text_pi_plot(num, users): # Data to plot sizes = [] labels = [] user_tups = [] message_total = 0 for user in users.keys(): new_t...
import numpy as np from src.region import Region class Rectangle(Region): def __init__(self, shape=np.array([[0, 0], [0, 1], [1, 1], [1, 0]])): super().__init__(shape) self.x_int = [shape[:, 0].min(), shape[:, 0].max()] self.y_int = [shape[:, 1].min(), shape[:, 1].max()] def _flatten...
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter from scrapy.pipelines.images import ImagesPipe...
def prime_num(num): if num == 1: return False elif num == 2: return True else: for i in range(2, num): if num % i == 0: return False return True while True: print("********************") ent_num = input("Bir Sayı Giriniz:") if ent_n...
import socket import time import sys import sqlite3 as lite # Each zombie registers its address and an open port to send attack to PORT = 15000 TIMEOUT = 300 TARGET = "108.179.184.95" TARGET_PORT = 7 if len(sys.argv) < 4: print print "USAGE: {attack type} {target address} {timeout (seconds)} {# threads} {port...
import numpy as np import pandas as pd def trainvaltest_split_by (df, dfstring, trainsize, valsize, seed = 42): uniqueids = df[dfstring].unique() np.random.RandomState(seed) np.random.shuffle(uniqueids) train_ids, val_ids, test_ids = np.split(uniqueids, [int(trainsize*len(uniqueids)), int((trainsize+v...
import pandas import pandas as pd import os import tensorflow as tf from methodology.preprocessing.StopWordsFilter import StopWordsFilter swf = StopWordsFilter() def preprocess_text(x): for punctuation in '"!&?.,}-/<>#$%\()*+:;=?@[\\]^_`|\~': x = x.replace(punctuation, ' ') x = ' '.join(x.split()) ...
from scapy.all import * def scan_port(port): status = 'OPEN' synPacket= sr1(IP(dst="23 192.168.3.0/24")/TCP(dport=(port), flags="S")) if (synPacket[TCP].flags != 18): status = 'CLOSED' print(synPacket.sprintf(str(port) + '\t %TCP.sport% \t %TCP.flags% ' + status)) scan_port(23)
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # Licensed under the Apache License, Version 2.0 (t...
S = 'abcdefghijklmnopqrstuvwxyz' class Solution(object): def __init__(self): S = 'abcdefghijklmnopqrstuvwxyz' self.S = S f= {} for i in range(len(S)): f[S[i]] = i self.f= f def replaceDigits(self, s): """ :type s: str :rtype: str ...
import pandas as pd # pandas is a data manipulation library import numpy as np # provides numerical arrays and functions to manipulate the arrays efficiently import random import matplotlib.pyplot as plt # data visualization library import operator from os import path # import turicreate as tc from datetime import ...
from operations import * from pip._vendor.msgpack.fallback import newlist_hint def add_ui(transList,param,undoList): if len(param)!=3: print("Invalid syntax") else: try: param[0]=int(param[0]) if param[1]!="out" and param[1]!="in": print("Invalid command"...
# -*- coding: utf-8 -*- from model.assistance.assistanceDao import AssistanceDAO from model.users.users import UserDAO from model.assistance.justifications.justifications import SingleDateJustification from model.assistance.justifications.status import Status from model.assistance.justifications.status import StatusD...
import os import sys from os import path from datetime import datetime, timedelta APP_NAME = 'Simple Chat App' BASEDIR = os.path.abspath(os.path.dirname(__file__)) # DEBUG DEBUG = True SECRET_KEY = 'ca2b84ac72a91a20cbda8be2d1f2c1fb7521' # telegram configs TELEGRAM_BOT_TOKEN = os.getenv(TELEGRAM_BOT_TOKEN, '')...
from Cucnewsflask.settings import db class Cucnews(db.Model): __tablename__ = 'cucnews' id = db.Column(db.Integer, primary_key=True, unique=True, nullable=False) url = db.Column(db.String(255), nullable=False) title = db.Column(db.String(255), nullable=False) picurl = db.Column(db.String(255), null...
# -*- coding: utf-8 -*- """ Created on Tue Feb 7 22:19:21 2017 @author: Andrew """ # -*- coding: utf-8 -*- """ Created on Tue Feb 7 20:10:28 2017 @author: Andrew """ def days_diff(date1, date2): """ Find absolute diff in days between dates """ daysDiff = 0 jan = () feb = () feb2 = ...
'''This question is same as house robber one as but in this questions houses are in circle''' def houseRobber(houses): def stolen(nums): prev=curr=0 for num in nums: temp = prev prev = curr curr = max(num+temp,prev) return curr if not hou...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class CNN(nn.Module): def __init__(self, config): super().__init__() self.activation_fn = getattr(F, config.activation) self.convs = nn.ModuleList() d_prev = 3 d = config.conv_dim ...
def input_value(): is_not_valid = True while is_not_valid: try: value = int(input('Enter a natural number: ')) if value <= 0: print('You did not enter a natural number. Enter a number greater than zero!') continue return value ...
from django.contrib import admin from.models import Place,PlaceD # Register your models here. admin.site.register(Place) admin.site.register(PlaceD)
import matplotlib.pyplot as plt import numpy as np import time TRAIN_DATA1 = "E:\大三上\智能系统\LAB2\dataset\dataset1\\train.utf8" TRAIN_DATA2 = "E:\大三上\智能系统\LAB2\dataset\dataset2\\train.utf8" LABELS = "E:\大三上\智能系统\LAB2\dataset\dataset1\labels.utf8" TEMPLATES = "E:\源程序\PycharmProjects\lab2\\template.utf8" VALID_DATA = "E:\大...
example ={"city": "Москва", "temperature": "20"} print(example["city"]) example["temperature"] = str(int(example["temperature"]) - 5) print(example) print(example.get("country", "Россия")) example["date"] = "27.05.2019" print(len(example))
# -*- coding: utf8 -*- import logging import ocpnetsplit.main from ocs_ci.deployment.zones import are_zone_labels_present from ocs_ci.ocs import exceptions from ocs_ci.ocs.ocp import OCP logger = logging.getLogger(__name__) def get_netsplit_mc( tmp_path, master_zones, worker_zones, enable_split=...
#!/usr/bin/env python import time import sys from pysovo.comms import email from pysovo.comms.email import keys as acc_keys from pysovo.local import contacts import base64 from imbox import Imbox def make_imbox(account): imbox = Imbox('imap.gmail.com', account[acc_keys.username], ...
import re import time from openpyxl import Workbook from connect_mgr import ssh_manager store_dir = "C:/path_to_excel_output/" routers_list_file = 'C:/path_ro_routers_list_file' mgm_ip_router = {} routersList = [] # execute this list of commands, on the routers matching the name filter. # Save the output in an excel...
from opentera.db.models.TeraServerSettings import TeraServerSettings from opentera import OpenTeraServerVersion import json class ClientVersions: def __init__(self, **kwargs): self.name = kwargs.get('client_name', None) self.description = kwargs.get('client_description', None) self.version...
class Stack: def __init__(self): self.val = [] def isempty(self): ''' O(n) Checks if the list is empty Parameters: ---------- Takes no parameter Returns: ------- Bool:True if list is empty else returns False ''' ...
# 素因数分解 def prime_factorize(n): result = [] if n % 2 == 0: t = 0 while n % 2 == 0: n //= 2 t += 1 result.append((2, t)) for i in range(3, int(n ** 0.5) + 1, 2): if n % i != 0: continue t = 0 while n % i == 0: n /...
#coding:utf-8 from Tkinter import * from ScrolledText import ScrolledText import urllib import re import urllib2 import threading def get(ID): varl.set('已经获取到第%s本书'%ID) html = urllib.urlopen('https://read.douban.com/ebooks/tag/%E8%AE%A1%E7%AE%97%E6%9C%BA/?cat=book&sort=top&start='+str(ID)).read() reg = r'...
# Generated by Django 2.2.1 on 2019-06-20 11:23 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0003_auto_20190620_1035'), ] operations = [ migrations.CreateModel( name='Room', ...
# -*- coding: utf-8 -*- """ Created on Thu Nov 16 12:42:07 2017 @author: ddowl """ import pip package_name = "PyGithub" pip.main(['install', package_name]) #Github Instance from github import Github #authentication code used to access dowlind1 github g = Github('fa5a233f26308dc4cc996becb68681f9a766f01a') user = ...
import cv2 import numpy as np img = cv2.imread('asdf2.jpg', 0) print(img) cv2.imshow('before', img) for x in range(100, 150): img[x, range(100, 150)] = 10 cv2.imshow('after', img) cv2.waitKey(0) cv2.destroyAllWindows()
def nyx (a, b): print (a + b) print (a - b) print (a * b) print (a / b) nyx (4, 2) nyx (12, 6)
# Generated by Django 2.2.9 on 2020-02-05 16:10 import uuid from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proponentes', '0011_remove_proponente_meios_de_recebimento'), ] operations = [ migrations.CreateModel( name='TipoDoc...
import numpy as np from conversion import SAMPLES_PER_SECOND class AR: # freq of 0 is interpreted as rest def __init__(self, attack_seconds=0.1, release_seconds=0.1): self.set(attack_seconds, release_seconds) # uses simple linear ramps def set(self, attack_seconds, release_seconds): s...
#!/usr/bin/env python import roslib; roslib.load_manifest("corobot_localization") import rospy import sys import copy from sensor_msgs.msg import LaserScan from corobot_common.srv import GetCoMap from corobot_common.msg import Pose from corobot_common.srv import GetPixelOccupancyResponse #from corobot_map import map ...
import pickle def save_object(file_path, obj): with open(file_path, 'wb') as output: pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL) def load_object(file_path): with open(file_path, 'rb') as input: obj = pickle.load(input) return obj
def insert(self,head,data): if head is None: return Node(data) current = head while current.next: current = current.next current.next = Node(data) return head
import json import os from sklearn import svm import stnConverter import randomSchedule import torch import torch.nn.functional as F with open(os.path.abspath('./Data/' + 'ALL_OF_THE_DATA_30000' + '.json'), 'r') as fp: datastuff = json.load(fp) twoData = [] newData = [] walks = [] for i in range(30000): if datastu...
def my_fun( ): while (True): no = int(raw_input()) if(no == 42): return else: print no my_fun()
import pytesseract import numpy as np import cv2 import re import validation from PIL import Image, ImageEnhance from datetime import datetime import ftfy import base64 from image_morphing import process_image from flask import flash import os #provide ull path to your tesseract executable. pytesseract.pytesseract.tes...
from itertools import count, islice next(islice((x for x in count(1) if not any(i for i in range(2, x) if x % i is 0)), 10001, None), None)