text stringlengths 8 6.05M |
|---|
class Morph(object):
def __init__(self, surface, base, pos, pos1):
self.surface = surface
self.base = base
self.pos = pos
self.pos1 = pos1
doc = []
skip_empty_line = False
with open("neko.txt.cabocha") as f:
lines = f.readlines()
sentense = []
for line in lines:
... |
def course_grader(test_scores):
# Your code here
total_score = 0
for test_score in test_scores:
if test_score < 50:
return "fail"
else:
total_score += test_score
return "pass" if total_score/len(test_scores) >= 70 else "fail"
def main():
print(co... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.PostListView.as_view(), name='home'),
path('blog/<int:pk>', views.PostDetailView.as_view(), name='blog_page'),
path('blog/new/', views.PostCreateView.as_view(), name='blog_new'),
path('blog/<int:pk>/edit', views.PostUpdateV... |
from .base_page import BasePage
from .locators import LoginPageLocators
class LoginPage(BasePage):
def should_be_login_page(self):
"""Method for checking the existence of registration forms and login on the login page
:return None
"""
self.should_be_login_url()
self.shoul... |
import numpy as np
# --------------------------------------------------------------
# I/O Functions
# --------------------------------------------------------------
def readNValues(handle, N, dtype, binary=False, sep=" "):
"""Read N values of dtype 'float' or 'int' from file handle"""
if binar... |
result1= 0
result2= 0
class Calculator:
def __init__(self)
self.result = 0
def adder(self, num):
self.result += num
return self.result
|
#!/usr/bin/python3
import rospy
import math
import sys
import time
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
class Wander_bot(object):
#ctor
def __init__(self, forward_speed, rotation_speed, min_scan_angle, max_scan_angle, min_dist_from_obstacle):
self.forward_speed = f... |
import hmac
import hashlib
from typing import Dict, Any
from hummingbot.connector.exchange.bitmax.bitmax_utils import get_ms_timestamp
class BitmaxAuth():
"""
Auth class required by bitmax API
Learn more at https://bitmax-exchange.github.io/bitmax-pro-api/#authenticate-a-restful-request
"""
def __... |
class ResourceContainer:
def __init__(self):
self.resources = {}
def setResource(self, name, value):
self.resources[name] = value
|
from django.conf import settings # type: ignore
from django.db import migrations, models # type: ignore
import django.db.models.deletion # type: ignore
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("carts_api", "0007_auto_20... |
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape, y_train.shape) # (60000, 28, 28), (60000,)
print(x_test.shape, y_test.shape) # (10000, 28, 28), (10000,)
print(x_train[0])
print(y_t... |
from peewee import Model, ForeignKeyField
from app.models.base import database
from app.models.user import User
from app.models.review import Review
class ReviewUser(Model):
user = ForeignKeyField(User)
review = ForeignKeyField(Review)
class Meta:
database = database
|
#!/usr/bin/python
# Title: check_device_online.py
# Author: Chopper_Rob
# Date: 25-02-2015
# Info: Checks the presence of the given device on the network and reports back to domoticz
# URL : https://www.chopperrob.nl/domoticz/5-report-devices-online-status-to-domoticz
# Version : 1.6.2
import sys
import da... |
# 116. Populating Next Right Pointers in Each Node
#
# Populate each next pointer to point to its next right node.
# If there is no next right node, the next pointer should be set to NULL.
#
# Initially, all next pointers are set to NULL.
#
# Note:
#
# You may only use constant extra space.
# Recursive approach is... |
from tkinter import *
import math as m
root = Tk()
root.title("Simple Calculator")
e = Entry(root, width=50, borderwidth=5, relief=RIDGE, fg="white", bg="Black")
e.grid(row=0, column=0, columnspan=5, padx=10, pady=15)
# e.insert(0, "")
def button_click(to_print):
# e.delete(0, END)
current = e.get()
e.de... |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
# author:罗徐 time:2019/7/3
#对于超大的图像做出图像二值化的操作
import cv2 as cv
import tensorflow as tf
import pandas as pd
import numpy as np
def big_image_bindary(image):
print(image.shape)
cw=256
ch=256
h,w=image.shape[:2]
gray=cv.cvtColor(image,cv.COLOR_B... |
import numpy as np
import matplotlib.pyplot as plt
import random
from func3 import *
a = 1 # границы отрезка
X = np.linspace(-a, a, num=3)
x = np.linspace(-a, a, num=200)
X_Ch = Ch(3, a)
plt.plot(x, [f(_) for _ in x], 'r', label='f(x)')
plt.plot(x, [PolynomialDegN(_, X, f) for _ in x], 'b', label='3d degree equidi... |
from bs4 import BeautifulSoup as bs
import re
import urllib
import random
import shutil
import requests
import os
import MySQLdb
def download_and_set_wallpaper(url):
filename = re.findall('.+\/(.+)', url)[0]
if filename not in os.listdir(os.getcwd()):
print('Downloading your wallpaper....')
response... |
# -*- coding: utf-8 -*-
import time
from lxml import etree
import openerp.addons.decimal_precision as dp
from openerp import netsvc
from openerp import pooler
from openerp.osv import fields, osv, orm
from openerp.tools.translate import _
class account_invoice_tax(osv.osv):
_inherit = "account.invoice.tax"
... |
import json
from flask import render_template, request, make_response, abort, jsonify
from . import api
from server.flask_app.work import views as work
from server.flask_app.bookmark import logic as bookmark
from server.flask_app.message import logic as message
from server.flask_app.tag import logic as tag
from server... |
import cv2 as cv
import matplotlib.pyplot as plt
filename = r'/Users/loujieming/Downloads/season.JPG'
img = cv.imread(filename)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
plt.figure()
plt.subplot(2,4,1)
plt.imshow(img[:, :, [2, 1, 0]]) # 转化成RGB
plt.title("img")
pl... |
# Создать классы
# 1) Прямоугольная площадка (пример: комната) (свойства: две стороны).
# Методы:
# • вычисляем площадь,
# • вычисляем периметр.
class Room:
def __init__(self, a=0, b=0):
self.a = a
self.b = b
def square(self, a, b):
self.a = a * b
return self.a
def per... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot = True)
import numpy as np
from matplotlib import pyplot as plt
first_image = mnist.train.images[0]
first_image = np.array(first_image,dtype='float')
first_image = first_image.resh... |
'''
Created on Apr 11, 2020
@author1: leyu_lin(Jack)
@author2: Parth_Thummar
backtracking search
'''
from csp_lib.backtrack_util import (first_unassigned_variable,
unordered_domain_values,
no_inference)
def backtracking_search(csp,
... |
import random
import string
ip1 = '142.4.106.' #65-69
ip2 = '107.149.61.' #65-125
ip3 = '108.186.69.' #65-125
ip4 = '108.186.8.' #1-61
ip5 = '107.148.136.' #45-125
def log(code):
with open('iplist.txt', 'a', encoding='utf-8') as f:
# 通过 file 参数可以把输出写入到文件 f 中
# 需要注意的是 **kwargs ... |
from app import db
ass = db.Table('ass',
db.Column('teacher_id',db.Integer,db.ForeignKey('teacher.id')),
db.Column('student_id', db.Integer, db.ForeignKey('student.id'))
)
class Student(db.Model):
id = db.Column(db.In... |
from .N2D import AutoEncoder
from .N2D import UmapGMM
from .N2D import n2d
from .N2D import save_n2d
from .N2D import load_n2d
from . import datasets
from .generators import manifold_cluster_generator
from .generators import autoencoder_generator
from . import linear_assignment
|
from collections import Counter
from math import log10
doc1 = open("./docs/document1.txt", "r")
doc2 = open("./docs/document2.txt", "r")
doc3 = open("./docs/document3.txt", "r")
doc1_content = doc1.read()
doc2_content = doc2.read()
doc3_content = doc3.read()
doc1_tokens = [s.lower().strip() for s in doc1_content.spl... |
from debianbts.debianbts import * # noqa
from debianbts.version import __version__ as __version__ # noqa
|
from onegov.core.security import Public
from onegov.form import FormCollection
from onegov.org.views.form_collection import view_form_collection
from onegov.town6 import TownApp
from onegov.town6.layout import FormCollectionLayout
@TownApp.html(model=FormCollection, template='forms.pt', permission=Public)
def town_v... |
from django.urls import path
from adminapp import views
app_name='adminapp'
urlpatterns = [
path('regest/',views.rigster,name='regest'),
path('create/', views.create, name='create'),
path('regest_logic/', views.rigster_logic, name='regest_logic'),
path('user/', views.user, name='user'),
path('login/... |
from odoo import models, fields, api, _
class AccountJournal(models.Model):
_inherit = 'account.journal'
payment_subtype = fields.Selection([('issue_check', _('Issued Checks')), ('rece_check', _('Received Checks'))],
string="Payment Subtype")
|
from django.db import models
from django.contrib.auth.models import User
class User123(models.Model):
user_name = models.OneToOneField(User)
position = models.CharField(max_length=200)
hours_needed = models.PositiveIntegerField(default=80)
def __unicode__(self):
return self.user_name.username... |
city = str(input('Cidade: '))
santo = city.split()
print(santo[0].find('Santo'))
|
import socket
import sys
import argparse
import select
import threading
PROMP = "> "
# ---------------------- CHAT CLIENT ---------------------
# Descripcion: Cliente echo que replica todo lo que envia
# mensajes al servidor y espera como respues-
# ta lo enviado.
#
# Funcionamiento:
# python echoclient.... |
d={'a':1,'b':2,'c':3}
for key in d:
print(key)
for value in d.values():
print(value)
for ch in 'ABC':
print(ch)
from collections import Iterable
print(isinstance('abc',Iterable))
print(isinstance([1,2,3],Iterable))
print(isinstance(123,Iterable))
for i,value in enumerate(['A','B','C']):
print(i,value)
f... |
from components import Utils
from config import STUDENTS_COLLECTION_NAME
class Student:
def __init__(self, sdk, payload, data=None, chat=None):
self.sdk = sdk
self.chat = None
self.id = None
self.name = None
self.scores = None
self.collection = Utils.create_collect... |
# from .main import MainPage
|
from flask import Flask,render_template, request,jsonify,Response, redirect,url_for
import requests
import json
import sys
import time
import numpy as np
from filestore.k8.ner_service.ner_predict import prepare_model
from filestore.k8.ner_service.ner_predict import make_prediction
from filestore.k8.ner_service.flask_pr... |
# python 2.7.3
import sys
import math
n = 15
data = [0] * n
for i in range(n):
data[i] = [None] * n
for j in range(n):
data[i][j] = 0
data[2][1] = 1
data[2][2] = 2
for row in range(2, 10):
for col in range(1, row + 1):
# 2 * col + 1
data[row + 1][col] += data[row][col] * col
... |
from stdmodandoption import *
import plot_setup as PS
import collections
def calrhog(runtodo,wanted,startno,Nsnap,snapsep,fmeat):
nested_dict = lambda: collections.defaultdict(nested_dict)
plotdict = nested_dict()
if wanted=='crez' or wanted=='rhog':
def func(x, a, b, c):
return a+... |
import os, sys, urllib, copy
import numpy as np
def hash_check(hash1, hash2):
if hash1 != hash2:
print 'ERROR: HASHCHECK FAIL'
print 'hash1 = ', hash1
print 'hash2 = ', hash2
assert(0)
def bl_gauss(fwhm, lmax):
ls = np.arange(0, lmax+1)
c = (fwhm * np.pi/180./60.)**2 / (16... |
age = eval(input("Enter age? : "))
print(age > 10)
print(age >= 10)
print(age < 10)
print(age <= 10)
print(age == 10)
list_of_age = [11,13,18]
print("Check with list: ",age in list_of_age) |
import pandas as pd
import numpy as np
import utils as util
from lr import LogisticRegressor
from svm import SVM
from nbc import NaiveBayesClassifier
from discretize import continuousToBinConverter
import sys
def lr(trainingSet, testSet, step_size=0.01, reg_param=0.01, max_iter=500, tol=1e-7):
model = LogisticReg... |
# -*- coding: utf-8 -*-
__author__ = """WebLion <support@weblion.psu.edu>"""
__docformat__ = 'plaintext'
from AccessControl import ClassSecurityInfo
from Products.Archetypes import atapi
from Products.FacultyStaffDirectory import config
from Products.FacultyStaffDirectory.interfaces.specialtyinformation import ISpec... |
# Estás encargado de un servidor con millones de usuarios.
# Se te pide escribir un programa que lea el email y contraseña del usuario y se fije si existe el usuario y si coincide la contraseña.
# Se tienen datos encolumnados en formato JSON que nos llegan del siguiente formato:
# {
# "usuarios": ["mica@mail.co"... |
import ROOT
ROOT.gROOT.LoadMacro("$CMSSW_BASE/src/TopEFT/Tools/scripts/niceColorPalette.C")
def niceColorPalette(n=255):
ROOT.niceColorPalette(n)
def redColorPalette(n=255):
ROOT.redColorPalette(n)
def newColorPalette(n=255):
ROOT.newColorPalette(n)
|
def Buble_sort(alist):
for i in range(0,len(alist)):
for j in range(0,len(alist)-1-i):
if alist[j]>alist[j+1]:
alist[j],alist[j+1] = alist[j+1], alist[j]
return alist
chaine=[1,5,0,9,4,6,3,10,45,23]
print Buble_sort(chaine) |
#!/usr/kai/anaconda3/python
# -*- coding: utf-8 -*-
# Supervised and then Reinforcement Learning mit PyTorch
# für Go9x9
# Supervised learning der gespeicherten best practices sgf
# # für Gewinner: Input = alle Board Positionen in denen Gewinner am Zug. Label = sein Zug
# # Lösung mit 1 Convolution, 2 Res und 1 FullyC... |
import sys
import cv2
print(cv2.__version__)
# Get user supplied values
imagePath = sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml"
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# D... |
from scraper.challonge import ChallongeScraper
import unittest
import iso8601
TOURNAMENT_ID = "TNE_Singles"
scraper = ChallongeScraper(TOURNAMENT_ID)
class IntTestChallongeScraper(unittest.TestCase):
def test_get_raw(self):
raw = scraper.get_raw()
self.assertTrue('tournament' in raw)
self.... |
#! /usr/bin/env python
"""
Author: John Stupak (jstupak@fnal.gov)
Date: 5-2-15
Usage: ./checkPretest.py <input dir>
"""
import ROOT
#ROOT.gErrorIgnoreLevel = ROOT.kWarning
from ROOT import *
gStyle.SetOptStat(0)
import math
import os
from config import *
from fnmatch import fnmatch
c=TCanvas('c','',1000,850)
refPad=... |
def main():
print 'haha'
if __name__ == '__main__':
main() |
"""Funcitions to load datasets.
"""
from .base import load_dataset
from .base import load_toy_example
__all__ = [
'load_dataset',
'load_toy_example'
] |
def searcher():
myfile = input('Type in the location of the file: ')
file = open(myfile,'r')
search_for = input('What do you want to find: ')
count = 0
for line in file:
if search_for in line:
print(line.strip('\n'), end="")
print(" which is on line #", str(c... |
import logging
from flask import Response
import sqlalchemy
from sqlalchemy import MetaData, Table, Column, String, select
# // Depending on which database you are using, you'll set some variables differently.
# // In this code we are inserting only one field with one value.
# // Feel free to change the insert state... |
# -*- coding: cp1252 -*-
import csv
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
i=0
... |
#Snake Case
n = input().strip()
print(n.count('_') + 1)
|
l=input().split()
m=int(l[0])
n=int(l[1])
for num in range(m,n):
temp=num
sum=0
while temp>0:
digit=temp%10
sum=sum+digit**3
temp=temp//10
if sum==num:
print (num)
|
from google.transit import gtfs_realtime_pb2
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import time
import requests
import folium
import os.path
from sense_hat import SenseHat
BASE_DIR = '/var/www/html/'
db_path = os.path.join(BASE_DIR, "testTable")
map_path = os.path.jo... |
# coding=utf-8
from threading import *
import json
import time
import socket
import sys
import RPi.GPIO as gpio
controlJson = {}
lock = Lock()
lock2 = Lock()
pararC = False
def socketCommunication():
global controlJson
global pararC
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM... |
def split(lista):
prueba = []
prueba.extend([i for i in lista if i % 2 != 0])
print(prueba)
return prueba
|
import math
import numpy as np
from save_svg import *
import noise
import copy
from geometry_primitives import *
from grow_lines import *
from obj import *
from topography import *
def noise_mesh():
lines = []
for i in range(100):
lines += [noise_line(i/100.,200)]
for i in range(0):
lines += [circle_points(75+i... |
# USAGE
# python realtime_stitching.py
# https://www.pyimagesearch.com/2016/01/25/real-time-panorama-and-image-stitching-with-opencv/
# This is going to be primary method of configuring when using two cameras for kite flying
# and given current hardware two cameras looks like how we will try and move forward for now
# ... |
"""
Copyright Matt DeMartino (Stravajiaxen)
Licensed under MIT License -- do whatever you want with this, just don't sue me!
This code attempts to solve
Project Euler (projecteuler.net) Problem #2 Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting... |
#!/usr/bin/env python
from baselines.common import set_global_seeds, tf_util as U
from baselines import bench
import gym, logging
from baselines import logger
def train(env_id, num_timesteps, seed):
from baselines.ppo1 import mlp_policy, pposgd_simple
U.make_session(num_cpu=1).__enter__()
set_global_seeds... |
def checkio(matrix):
setM = set()
for l in matrix:
setM = setM | set(l)
print(setM, len(matrix))
checkedList = []
treslutList = []
def spiderlist(x, y):
resultn = matrix[x][y]
n = len(checkedList)
checkedList.append(str(x) + str(y))
tempList = [str(x) + s... |
'''
Control statements:
if
if else
elif
'''
import math
n = -16
# n = int(input('enter:'))
if n < 0 :
n = abs(n)
print(math.sqrt(n)) # 4
print('=====================')
a = 5
if True:
a = 6
print(a) # 6
print('=====================')... |
############### PYTEX UTILS ###############
import sublime, sublime_plugin, sys, re, os, imp
# Caminho para módulos
paths = (
# Laptop - Linux
# ----
# Apto Bauru - Linux
'/home/andre/.config/sublime-text-3/Packages/User',
# Triata - Windows
'C:\\Users\\Triata\\AppData\\Roaming\\Sublime Text 3\\Packag... |
from flask_restx import Api
from src.api.ping import ping_namespace
from src.api.users.views import users_namespace
from src.api.places.views import places_namespace
from src.api.reviews.views import reviews_namespace
api = Api(version="1.0", title="Geo Flask API", doc="/doc")
api.add_namespace(ping_namespa... |
__version__ = "0.2.1"
import os
import csv
import subprocess
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input_directory")
parser.parse_args()
args = parser.parse_args()
cwd = args.input_directory
if cwd.endswith("/"):
bname = cwd.split("/")[-2]
else:
bname = cwd.split("/")[-1]
c... |
# Write a program that prompts for an integer and prints the integer, but if something other than an integer is input, the program keeps asking for an integer. Here is a sample session:
# Input an integer: abc
# Error: try again. Input an integer: 4a Error: try again. Input an integer: 2.5 Error: try again. # Input an ... |
# overrides for pipe_tasks ChiSquaredCoaddTask.ConfigClass
from lsst.obs.sdss.selectSdssImages import SelectSdssImagesTask
config.select.retarget(SelectSdssImagesTask)
|
from intent_handling.signal import Signal
class PrereqsForClassIntent:
NAME = 'CLASS_WHAT_PREREQS'
def __init__(self, parameters):
self.parameters = parameters
def execute(self, db):
sql = 'SELECT prereqs from main_courses WHERE intent_name="{}"'.format(self.parameters.class_name)
... |
from utility import *
from random import random
from rhyme_metric import rhyme_similarity
def basic_clustering():
content = read_file('vocab.txt')
lines = content.split("\n")
words = [l.split(' ')[0] for l in lines]
vocab_size = len(words)
clusters = []
chosen = []
while len(clusters) < 1... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import pandas as pd
import requests
import os
import csv
import numpy as np
import shutil, os
import random
from shutil import copy2
#Download the images to each subsets
def create_subset_categories_list(categories,subsets):
with open('ImageInfo.csv', 'r')... |
############################
#
# Name: pythonmidas
#
# Author: Aaron Gallant, Summer 2013
#
# Description:
# Pythonmidas is a class to control a midas session. The commands
# are based on the 'perlmidas' subroutines, ported to python.
#
############################
import subprocess as MidasSP
"Midas contains member... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
class InstagramProfileItems(Item):
is_private = Field()
posts = Field()
username = Field()
profile_picture = Field()
... |
#!/usr/bin/env python
"""
_SetLocationForWorkQueue_
Oracle implementation of Files.SetLocationForWorkQueue
For WorkQueue only
"""
from WMCore.WMBS.MySQL.Files.SetLocationForWorkQueue import SetLocationForWorkQueue as MySQLSetLocationForWorkQueue
class SetLocationForWorkQueue(MySQLSetLocationForWorkQueue):
"""
... |
import random
from typing import Union
import discord
from discord.ext import commands
from potato_bot.cog import Cog
from potato_bot.utils import run_process
from potato_bot.checks import is_admin
from potato_bot.context import Context
class Fun(Cog):
"""Commands without practival use"""
THROWABLE_ITEMS... |
'''
Input: family data (emails,names, relationship status)
Output: secret santa assignments where married couples can't have each other and you don't get the same person
you got last year
'''
import json
import random
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
... |
# dp 알고리즘 - 문제는 ㅗ가 구현이 안됨
vis = []
direction = [(1, 0), (-1, 0), (0, 1), (0, -1)] # 4 방향
def find_max(x, y, r, s): # x, y, remained_block, sum
global mat # map
global vis # visited ?
global direction
if r <= 0: # 블록 4개 다 사용했다면 return
return s
max_v = 0
for direc in direction:
n... |
# -*- coding=utf-8 -*-
# author: dongrixinyu
# contact: dongrixinyu.89@163.com
# blog: https://github.com/dongrixinyu/
# file: processor.py
# time: 2020-06-12 11:27
import pdb
import copy
import json
import collections
import logging
import operator
from typing import List, Optional, Union, Dict, Any
import numpy a... |
import os
def create_folder(path):
if not os.path.exists(path):
print("SETUP: se ha creado el directorio ", path)
os.makedirs(path)
def todict(obj):
return [dict(item) for item in obj]
|
from aqt import mw
config = mw.addonManager.getConfig(__name__)
# Separator used between hierarchies
SEPARATOR = config["separator"]
DEPTH = config["default_depth"]
from . import echelon
|
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from regression_model.processing import preprocessors as pp
from regression_model.config import config
price_pipe = Pipeline(
[
('categorical_imputer',
pp.... |
def standards_maker():
#your code here
for (i) in range (301):
a = print ("I will write questions if I am stuck")
return a
#remember to call the function outside (here)
standards_maker() |
#! /usr/bin/env python
# Runs a cleaning function on a set of pages,
# and produces patches with the changes made.
import difflib
import os
def process_page(page, cleaner):
before = page.splitlines(True)
after = cleaner(page).splitlines(True)
patch = difflib.unified_diff(before, after)
html = difflib.... |
import random
import requests
import re
class proxyMiddleware:
def __init__(self):
self.ip_pool = [] # 装入代理成功的IP
self.url = "http://www.66ip.cn/nmtq.php?getnum=5&isp=0&anonymoustype=0&start=&ports=&export=&ipaddress=&area=1&proxytype=1&api=66ip"
def getIP(self):
html = requests.get(se... |
#CTI-110
#P3HW2- Shipping Charges
#Javonte Woods
#11-26-2018
# Write a program that asks the user to enter the weight of a package and then displays the shipping charges.
#Weight of package| 2pounds<= Rate per pound, $1.50, (Over 2pounds>=6,$3.00, over 6pounds>=10,$4.00, over 10 > , $4.75
print("Please input weight o... |
import bluetooth
import socket
import threading
import queue
import bluetooth
import time
class ConnectToServer:
def __init__(self, input_queue, output_queue):
threading.Thread.__init__(self)
self.input_queue = input_queue
self.output_queue = output_queue
self.HOST = ''
self.POR... |
from cheroot import wsgi
from cheroot.ssl.pyopenssl import pyOpenSSLAdapter
def create_server(app):
server_config = app.config.opsy['server']
server = wsgi.Server((server_config['host'], server_config['port']), app,
numthreads=server_config['threads'])
if server_config['ssl_enable... |
#!/usr/bin/env python3
# encoding: utf-8
"""
@version: 0.1
@author: lyrichu
@license: Apache Licence
@contact: 919987476@qq.com
@site: http://www.github.com/Lyrichu
@file: test_SGA.py
@time: 2018/06/06 08:00
@description:
test for SGA
"""
from time import time
import sys
sys.path.append("..")
from sopt.SGA.SGA import ... |
n=int(input("enter the no. :-"))
for i in range(n):
print("*"*(n-i) + " "*(i+1) + "*"*(n-i))
for i in range(2,n+1):
print("*"*i + " "*((n-i)+1) + "*"*i)
|
VTABLE(_Math) {
<empty>
Math
}
VTABLE(_Main) {
<empty>
Main
}
FUNCTION(_Math_New) {
memo ''
_Math_New:
_T8 = 4
parm _T8
_T9 = call _Alloc
_T10 = VTBL <_Math>
*(_T9 + 0) = _T10
return _T9
}
FUNCTION(_Main_New) {
memo ''
_Main_New:
_T11 = 4
parm _T11
_T12 = call _A... |
class Human():
#The least point count of any attribute is 50 points, there is no cap on the max amount of points.
#The base for any human is 50 points.
def __init__(self):
hunger = int(50)
stamina = int(50)
motivation = int(50)
self.hunger = hunger
self.stamina = stamina
... |
#!/usr/bin/env python
"""
Write a program that finds all files with a given suffix, such as spam001.txt,
spam002.txt, and so on, in a single folder and locates any gaps in the
numbering (such as if there is a spam001.txt but no spam002.txt). Have the
program rename all the later files to close this gap.
"""
import... |
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .adminsResources import OrderItemResource
from .models import OrderItem
class OrderItemAdmin(ImportExportModelAdmin):
list_display = ['id','order_name', 'slug', 'item', 'quantity']
resource_class = OrderItemResource
a... |
#import logging
import csv
import requests
import json
import time
'''
logger = logging.getLogger("root")
logger.setLevel(logging.DEBUG)
# create console handler
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
'''
def dataStruct():
result = {}
result['latitude'] = None
result['longi... |
#Character Picture grid
'''
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
'''
#we have to print the given list 'grid' in above format
#we define a function to print in the desired format
def characterPictureGrid(changedGrid):
#looping over each row
for i in range(len(changedGrid[0])... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.