text stringlengths 8 6.05M |
|---|
#coding=utf-8
#第一种方式引入
# from _02python_basicknowledge._18_01sendmessage import test1,test2
# from _02python_basicknowledge._18_01sendmessage import * #这种方式虽说可以引入所有的方法,但是不安全,如果其他的模块也有test1方法会覆盖前面的导入
# import _02python_basicknowledge._18_01sendmessage
# _02python_basicknowledge._18_01sendmessage.run1()
# _02python_basi... |
def iter_indeices(batch, batch_size, dataset_size):
batch_start = batch * batch_size
batch_end = (batch + 1) * batch_size
if batch_end > dataset_size:
batch_end = dataset_size-1
return batch_start, batch_end |
{
PDBConst.Name: "notetag",
PDBConst.Columns: [
{
PDBConst.Name: "ID",
PDBConst.Attributes: ["tinyint", "not null", "primary key"]
},
{
PDBConst.Name: "Tag",
PDBConst.Attributes: ["varchar(128)", "not null"]
},
{
PDBConst.Name: "SID",
PDBConst.... |
from django.db import models
from django.contrib.auth.models import AbstractUser, PermissionsMixin
from datetime import datetime
SEAT_CLASS = (
('economy', 'Economy'),
('first', 'First')
)
TICKET_STATUS =(
('Pending', 'Pending'),
('Confirmed', 'Confirmed'),
('Cancelled', 'Cancelled')
... |
#! /usr/bin/env python
## Simple ROS node that:
## -subscribes to state_image topic
## -displays the image portion of the message
## -if user clicks in the image window
## -write image to all_targets folder
## -write state data to all_state_data.txt
import rospy
from sniper_cam.msg import stateImage
from std_msgs.m... |
""" The parentheses have to be "balanced" to be valid. For example, ()(()) is balanced, but ()()) is not balanced.
Also, )((()) is not balanced. (Think mathematics.)
Write a function that takes a string and returns True if the string's parentheses are balanced, False if they are not."""
def check_balance(my_string):
... |
import discord
import redisInterface
import re
from discord.ext import commands
class CustomItems():
def __init__(self, bot):
self.bot = bot
@commands.group(pass_context=True)
async def item(self, ctx):
if ctx.invoked_subcommand is None:
await bot.say('Invalid item command ... |
#Figure 4 has our fiducial chain, non-tomographic constraints,
#pseudo Cls, Cl bandpowers, and Planck
from cosmosis.postprocessing import plots
from cosmosis.postprocessing import lazy_pylab as pylab
from cosmosis.postprocessing import statistics
from cosmosis.plotting.kde import KDE
from cosmosis.postprocessing.elem... |
from CountyFireLandHelpers import intersectOrIn
from shapely.geometry import Polygon
class County:
def __init__(self, xmlOutput):
self.fires = []
self.name = xmlOutput[1]['name']
self.points = xmlOutput[0]
self.poly = Polygon(self.points)
def findFiresInCounty(self, fire_list)... |
class DtoDependencyLoader:
# session has to be set before load_if_none is called
# session has to be closed later
session = None
@classmethod
def load_if_none(cls, instance, instance_id, clazz):
if instance is None:
return cls.session.query(clazz).filter(clazz.id == instance_id)... |
"""
Make gridcells based on outercorners of the shape of the inputfile and specified resolution (e.g. 0.1 degrees).
Inputs:
- df = inputfile containing shape
- height = resolution in degrees
@Author: Elco Koks & Sadhana Nirandjan - Institute for Environmental studies, VU University Amsterdam
"""
import pygeos
im... |
# -*- coding: utf-8 -*-
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from app import create_app
app = WSGIContainer(create_app("config.config.ProdConfig"))
http_server = HTTPServer(app)
http_server.listen(8008)
IOLoop.instance().start()
|
import tensorflow as tf
from tensorflow import keras
import numpy as np
import itertools
import random
import matplotlib.pyplot as plt
def gen_rnd_dna_string(N, alphabet='ACGT'):
return ''.join([random.choice(alphabet) for i in range(N)])
def gen_all_dna_strings(L):
return (''.join(p) for p in itertools.pro... |
# __author__ = 'cjweffort'
# -*- coding: utf-8 -*-
import os
import sys
import time
import numpy
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv
rng = numpy.random.RandomState(23455)
dataset = 'mnist.pkl.gz'
data_dir, data_file = os.path.split(d... |
from django.db import models
class Country(models.Model):
country_text = models.CharField(max_length=200)
country_code = models.CharField(max_length=200, primary_key=True)
def __str__(self):
return self.country_text
|
from flask import Response
from flask import json
from org.chula.courseville.model import Video
from org.chula.courseville.processor.YoutubeProcessor import searchKeyword
def youtubeListResponseBuilder(videoList):
js = json.dumps({"items":[video.__dict__ for video in videoList]})
resp = Response(js, status... |
import os
import sys
import logging
import logging.config
import warnings
import random
from typing import Optional
import numpy as np
import torch
# Initiate Logger
logger = logging.getLogger(__name__)
def setup_logging(log_path: Optional[str] = None, level: str = "DEBUG"):
handlers_dict = {
"console_h... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import logging
import re
import yattag
import uuid
import markdown
from pygiftparser import i18n
from pygiftparser.answer import *
from pygiftparser.utils import *
_ = i18n.language.gettext
############ Questions ################
class Question:
""" Question class.
... |
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django_facebook.utils import clear_persistent_graph_cache
from django.db.models.signals import post_save, m2m_changed
from django.db.models import F
from guardian.shortcuts import assign
from useren... |
from ._config_parser import ConfigParser
from ._common import ConfigurationException
from ._tabulation_factories import TABULATION_FACTORIES
import logging
class Configuration(object):
"""Factory class that allows Tabulation objects to be built from .ini files"""
def __init__(self):
self._tabulation_factor... |
from django.shortcuts import render
from django.utils import timezone
from .models import Post
from accounts.forms import RegistrationForm
from django.contrib.auth.models import User
from django.shortcuts import render, get_object_or_404
from .forms import PostForm
from django.shortcuts import redirect
from django.cont... |
import os
import json
from PIL import Image, ImageDraw, ImageFont
def the_name(data):
sizee = 150
if len(data)>12:
sizee= sizee - (120)
fnt = ImageFont.truetype('../../../Documents/Templates/Fonts/fonts/truetype/ubuntu/UbuntuMono-R.ttf', sizee)
return str(len(data))
return "ss"+data
# for filename in os.listd... |
#!/usr/bin/python
import numpy as np
from random import randint
import matplotlib.pyplot as plt
import sys
def generate_random_points(minX, maxX, minY, maxY, num_points):
data = []
for _ in range(num_points):
data.append([float(randint(minX, maxX)), float(randint(minY, maxY))])
return data
def gen... |
from rv.modules import Behavior as B
from rv.modules import Module
from rv.modules.base.fm import BaseFm
class Fm(BaseFm, Module):
behaviors = {B.receives_notes, B.sends_audio}
|
# Copyright 2013 Dany Qumsiyeh (dany@qhex.org)
#
# This program 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 Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This... |
import torch
import torch.nn as nn
import torch.optim as optim
from dataset.cifar10 import Cifar10
from models.lenet import LeNet
BATCH_SIZE = 128
INIT_LR = 1e-2
MOMENTUM = 0.9
L2_REG = 5e-4
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# def imshow(img):
# img = img/... |
#-*- coding: utf-8 -*-
import json
from uuid import uuid4
import utm
from openpyxl import load_workbook
import random
class GraphModel(object):
session = None
driver = None
def __init__(self, session, driver):
self.driver = driver
self.session = session
def translate_coords(self, x, ... |
''' Telegram user module '''
import time
import logging
from telethon import TelegramClient
from pymongo import MongoClient
from utils import pack_model, unpack_model
LOGGER = logging.getLogger(__name__)
DELAY = 1.0
DB_URL = 'mongodb://mongo:27017'
DB_NAME = 'testing_setup'
MAX_TIMEOUT_MS = 1000
def read_user()... |
import happybase
import sqlite3
def loadDjangoModel(car_list):
conn = sqlite3.connect('../../db.sqlite3')
c = conn.cursor()
## Just dropping and recreating table. This is intentional
##c.execute('DROP TABLE IF EXISTS car_list;')
##c.execute('CREATE TABLE car_list (car_make VARCHAR NOT NULL, car... |
#!/usr/bin/env python
import sys
f = open( sys.argv[1] )
count = 0
linecount = 0
chromos = []
for line in f:
if line.startswith( "@" ):
continue
id = line.split('\t')
if id[2] != '*':
chromos.append(id[2])
else:
pass
print chromos[:10] |
class retcode(int):
name = None
re = None
RPL_TRACELINK = retcode(200)
RPL_TRACELINK.name = "RPL_TRACELINK"
RPL_TRACELINK.re = (
r"^:(?P<srv>\S+) 200 (?P<me>\S+) "
r"(?P<next_server>\S+)")
RPL_TRACELINK.tpl = (
':{c.srv} 200 {c.nick} '
'{next_server}')
RPL_TRACELINK.params = ['srv', 'me', 'nex... |
from multiprocessing import Pool
from time import sleep
def f(x):
sleep(1000) # simulate some computation
return x*x
if __name__ == '__main__':
with Pool(8) as p:
print(p.map(f, range(8)))
|
# Copyright (c) 2018 Javier M. Mellid <jmunhoz@igalia.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... |
import os
import httplib
import urllib
STATIC_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'static')
def filter_text(unicode_text):
return (
unicode_text
.encode('ascii', errors='ignore')
.replace('\n', '')
.replace('\r', '')
)
def fetch_article_body(... |
# Generated by Django 3.2.5 on 2021-09-11 09:28
import datetime
import django.core.validators
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('app_order', '0020_auto_20210911_1216'),
]
operations = [
... |
import unittest
from db_connection_part.mysql_main import DataFetcher
class TestDataFetcher(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.fetcher = DataFetcher()
rows = [
dict(text='test_1', number=10, invalid=0),
dict(text='test_2', number=20, invalid=1)... |
"""
_InsertComponent_
MySQL implementation of Block.New
"""
__all__ = []
from WMCore.Database.DBFormatter import DBFormatter
from WMCore.Agent.Database.CouchDB.CouchService import CouchService
class InsertComponent(DBFormatter):
def execute(self, name, pid, update_threshold = 6000,
conn = None,... |
# Generated by Django 2.0.1 on 2018-02-09 07:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('message', '0005_auto_20180209_1605'),
]
operations = [
migrations.AlterField(
model_name='message',
name='read_time'... |
from torch.optim.lr_scheduler import _LRScheduler
import math
import warnings
class CosineAnnealingWithWarmUp(_LRScheduler):
def __init__(self, optimizer, T_max, W_steps, eta_min=0, last_epoch=-1, verbose=False):
self.T_max = T_max
self.W_steps = W_steps
self.eta_min = eta_min
supe... |
class BinaryIndexedTree(object):
def __init__(self, n):
self.tree = [0] * (n + 1)
def update(self, idx, val):
while idx < len(self.tree):
self.tree[idx] += val
idx += idx & -idx
def get(self, idx):
s = 0
while idx:
s += self.tree[... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^api/add_person',views.AddPersonView.as_view(),name = 'add_person_view'),
url(r'^api/add_relation',views.AddRelationView.as_view(),name = 'add_relation_view'),
url(r'^api/display_mentees',views.DisplayMenteesView.as_view(),name = 'show_view... |
from flask import Flask, jsonify, request
from functools import wraps
from flask_cors import CORS, cross_origin
from werkzeug.contrib.cache import SimpleCache
import pyen
cache = SimpleCache(threshold=20000)
app = Flask(__name__)
#Allowed origins
ORIGINS = ['*']
app.config['CORS_HEADERS'] = "Content-Type"
app.conf... |
import numpy as np
import pandas as pd
df = pd.read_csv('Data/Clean_Real_Estate_With_Crime.csv')
df.drop(df[df['Average School Rating'] == 'No Schools'].index, inplace=True)
df.astype({'Average School Rating': 'category', 'ZIP OR POSTAL CODE':'object','LATITUDE':'object','LONGITUDE':'object', 'BATHS':'int64'}).dtype... |
import os
import gslab_scons.misc as misc
from gslab_scons import log_timestamp
def build_r(target, source, env):
'''Build SCons targets using an R script
This function executes an R script to build objects specified
by target using the objects specified by source.
Parameters
----------
targe... |
import numpy as np
import matplotlib.pyplot as plt
with open("log.txt") as f:
data = f.read()
data = data.split('\n')
del data[-1]
x = [row.split('\t')[0] for row in data]
del x[-1]
y0 = [row.split('\t')[1] for row in data]
del y0[-1]
y1 = [row.split('\t')[2] for row in data]
del y1[-1]
y2 = [row.split('\t')[3] f... |
import pandas as pd
import argparse
import os
import app.views as MI # MapperInteractive
from app import kmapper as km
from app import cover as km_cover
from sklearn.cluster import DBSCAN, MeanShift, AgglomerativeClustering
import json
import itertools
import numpy as np
from os.path import join
from tqdm import tqdm
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#@Time : 2021/2/24 21:46
#@Author: 李明特
#@File : AutomaticFormFilling.py
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditi... |
from urllib.parse import urlencode
import requests
api_key ='APY_KEY here'
def gmaps(address, data_type = 'json'):
endpoint = f'https://maps.googleapis.com/maps/api/geocode/{data_type}'
params = {'address': address, 'key': api_key, 'language': 'de'}
url_params = urlencode(params)
url = f'{endpoint}?{u... |
import matplotlib.pyplot as plt
def create_bar_chart(data, labels):
num_bars = len(data)
positions = range(1, num_bars+1)
plt.barh(positions, data, align='center')
plt.yticks(positions, labels)
plt.xlabel('Dollars')
plt.ylabel('Expense')
plt.title('Monthly expenses')
plt.grid()
plt.show()
if __name__ == '__... |
"""
Module for managing a remote temperature value.
DPT 9.001.
"""
from __future__ import annotations
from xknx.dpt import DPTArray, DPTBinary, DPTTemperature
from .remote_value import RemoteValue
class RemoteValueTemp(RemoteValue[DPTArray, float]):
"""Abstraction for remote value of KNX 9.001 (DPT_Value_Temp)... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from superlists import settings
import unittest
class NewVisitorTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.q... |
import questionary
import finnhubIO as fh
import polygonIO as pg
import pandas as pd
import concurrent.futures
market_list = ['stock', 'crypto']
def build_portfolio(dict):
while(questionary.confirm("Add a product?").ask()):
product_dict = {}
market = choose_market()
product_dict['market'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 15/03/2019 14:12
# @Author : karl wang
# @Email: karl.wang.1991@gmail.com
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from s... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 14:52:40 2020
@author: Likhit
"""
import numpy as np
import sys
def similarList(list):
return all(x == list[0] for x in list)
def goalCheck(arr, player):
for l in range(n):
kk = []
if (t[l] == player).all() and ("*" not in kk):
#Ho... |
#basamaklarındaki rakamların 5.kuvveti şeklinde yazılabilen tüm sayıların toplamı
toplam = 0
for i in range(1000,354294): # max 6bas kadar bakabileceğimiz için
kontrol = 0 # 6*9**5 = 354294
for j in str(i):
kontrol += int(j)**5
if(i==kontrol):
toplam += kontrol
print(toplam)
|
import math
finalA= 1
finalB= 41
consecPrimes = 40
primeCheck = [True] * 1000
primes = []
# I needa function to mark multiples as composite
def seiveAlg(prime):
for d in range(2*prime,len(primeCheck),prime):
primeCheck[d] = False
for x in range(2,int(1000**0.5)): # i've used this algorith so mu... |
def kth_multiple(k):
array_s=[1,3, 5, 7]
array=[3, 5, 7]
count=4
last_ref=1
index=0
value=7
if k<=4:
return array_s[k-1]
while(count<k):
array_s.append(array[index%3]*array_s[last_ref])
index+=1
value=array_s[-1]
if index%3==0:
last_ref+=1
count+=1
return value
print... |
# pipeline 生產線
# 裝載著所有步驟
from yt_concate.pipeline.steps.step import StepException
class Pipeline:
def __init__(self, steps):
self.steps = steps
def run(self, inputs, utils):
transporter = None # 運輸車,把生產線的東西一個一個傳給亞一個生產線,初始為None代表沒有東西。
for work in self.steps:
try:
... |
'''
Created on Jun 15, 2016
@author: Dayo
'''
from dateutil.relativedelta import relativedelta
import arrow
import logging
import django_rq
from django.template import Context, Template, loader
from django.apps import apps
from django.utils import timezone
from django.conf import settings
from djang... |
import tokenizer
import requests
import importers.txt_importer as i
import fnmatch
import logging
# This function adds all indexing data for a particular document to the
# database. It uses the data_access, so this code does not directly touch the
# database (i.e. database manipulation is abstracted from this function... |
def candies(n, arr):
if len(arr) < 1:
return 0
candies_sum = 1
last_peak_index = 0
last_peak_candy = 1
last_candy_amount = 1
for i in range(1,len(arr)):
# 3 2 / 5 3 2 1
if arr[i-1] > arr[i]:
last_candy_amount = 1
candies_sum+=i-last_peak_index
... |
from grid import Grid
from actions import Plots
import matplotlib.pyplot as plt
import random
import math
import copy
from batteries import Battery
class Algorithm():
"""
Class containing algorithms.
"""
def __init__(self, district, setting):
"""
Loading the grid information.
... |
class BoundingBox:
class InvalidBox(Exception):
pass
def __init__(box,x1=-1,y1=-1,x2=-1,y2=-1):
box.min_x = float(x1)
box.min_y = float(y1)
box.max_x = float(x2)
box.max_y = float(y2)
@staticmethod
def from_tuple_wh(t):
if len(t) <> 4:
print 'from_tuple_wh: requires 4-tuple!'
else:
min_x = fl... |
import sys
import requests
from bs4 import BeautifulSoup
'''
Used as a quick way to translate a word in english to Japanese using Webscraping
'''
def main():
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36",}
... |
# from contextlib import contextmanager
# def func():
# print("hello")
|
def nanrate(train, valname):
train[valname+"_na"] = pd.isnull(train[valname])
book_rate=[]
click_rate=[]
c_summary=[]
b_summary=[]
cond = []
for i, gb in train.groupby(valname+"_na"):
if i:
cond.append(1)
else:
cond.append(0)
book_rate.append(g... |
import os
import sys
main_dir = os.path.split(os.getcwd())[0]
result_dir = main_dir + '/results'
sys.path.append(main_dir)
from data import fmri_data_cv as fmril
from data import fmri_data_cv_rh as fmrir
from data import meg_data_cv as meg
from model import procedure_function as fucs
from sklearn.externals import jo... |
from flask_restful import Resource
from flask_restful import abort
from flask_restful import marshal_with
from flask_restful import fields
from flask_restful import reqparse
from app.db import dbs
from app.models.boulder import Boulder, BoulderGrading, v_scale, fb_scale
from auth import validate_login_jwt
area_fields ... |
#import sys
#input = sys.stdin.readline
from bisect import bisect_left
def main():
N = int( input())
A = list( map( int, input().split()))
B = list( map( int, input().split()))
ANS = [0]*30
for i in range(30):
t = pow(2,i)
D = sorted([ b%(t*2) for b in B])
now = 0
f... |
class Solution(object):
def threeSumClosest(self, target, nums):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
final_list = None
diff = 10000000000000000000000000000
target.sort()
for i in range(len(target)):
... |
#Word break
def hasWord(s):
bag = ["mobile","samsung","sam","sung","man","mango",
"icecream","and","go","i","like","ice","cream"]
if s in bag:
return True
return False
def checkWords(s):
if len(s) == 0:
return True
for i in ... |
import sys, string, math
def find_max_sum(arr):
incl = 0
excl = 0
for i in arr:
new_excl = excl if excl > incl else incl
incl = excl + i
excl = new_excl
return (excl if excl > incl else incl)
n = int(input())
L = [ int(x) for x in input().split()]
print(find_max_sum(L))... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import Request
import urllib
import re
import datetime
class NewsmthCrawlerSpider(Spider):
name = 'newsmth_crawler'
allowed_domains = ['... |
# IPython log file
random.random()
import random
random.random()
random.random()
data = {i : random.random() for i in range(7)}
data = {i : random.random() for i in range(7)}
data = {i : random.random() for i in range(7)}
data
get_ipython().run_line_magic('logstart', '')
get_ipython().run_line_magic('logstor', '')
get... |
from torch.autograd import Variable
from skimage.transform import resize
from collections import defaultdict
from torchvision import models
import torch.optim as optim
from torch.optim import lr_scheduler
import torch.nn.functional as F
import torch.nn as nn
import os
import torch
import numpy as np
import scipy.misc ... |
import math
a = int(input("a) numero[22]: "))
b = int(input("b) numero[10]: "))
val = a + b
print("a + b =",val)
val = a - b
print("a - b =",val)
val = a * b
print("a * b =",val)
val = a ** b
print("a ^ b =",val)
val = math.sqrt(a+b)
print("sqrt(a + b) =",val)
|
import sys
''' sys kezeli ha fájl név után beírsz valamit '''
def main(argv):
if (len(argv)>0):
print("Hello "+' '.join(argv)+"!")
else:
print("Hello Wolrd!")
main(sys.argv[1:])
|
import sqlite3
def db_check():
conn = sqlite3.connect("db_rps.db")
cursor = conn.cursor()
cursor.execute("""SELECT * FROM statistics""")
row = cursor.fetchone()
# выводим список пользователей в цикле
while row is not None:
print(
f"| id: {str(row[0])} |/| dt_cr_us: {str(ro... |
# Question: https://www.hackerrank.com/challenges/equal/problem
t = int(raw_input())
subs = [5,2,1]
for i in range(t):
n = int(raw_input())
dist = list(map(int, raw_input().split()))
low = min(dist)
for j in range(n):
dist[j]-=low
ops=0
for j in range(n):
for k in range(3):
... |
import random
import matplotlib.pyplot as plt
from stats.descriptive_stats import mean, variance
def variance_bias(data):
"""无偏性方差"""
n = len(data)
if n <= 1:
return None
mean_value = mean(data)
return sum((e - mean_value) ** 2 for e in data) / n
def sample(num_of_samples, sample_sz, v... |
from django.db import models, connection
from sklearn.feature_extraction.text import CountVectorizer
class Upload(models.Model):
title = models.CharField(max_length=100)
upload = models.FileField(upload_to="media/")
def __str__(self):
return self.title
class URLUpload(models.Model):
title ... |
# Generated by Django 3.0.4 on 2020-06-27 12:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tour', '0009_auto_20200627_1259'),
('training', '0005_auto_20200627_1258'),
]
operations = [
migrations.AlterField(
mode... |
import cv2
imgcapture = cv2.VideoCapture(0)
result=True
while (result):
ret , frame =imgcapture.read()
cv2.imwrite("test.jpg",frame)
result=False
print("Image Capture.....")
imgcapture.release() |
""" PYTEST PAGE ELEMENT IDENTIFIERS GO HERE """
from selenium.webdriver.common.by import By
class LoginPageLocators(object):
USN_INPUT = (By.XPATH, 'sample_xpath')
PWD_INPUT = (By.XPATH, 'sample_xpath')
LOGIN_CTA = (By.XPATH, 'sample_xpath')
class LandingPageLocators(object):
SEARCH_CTA = (By.XPATH... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
from creational_patterns.prototype.framework.display import Display
# ˄
class FrameDisplay(Display):
# ˅
# ˄
def __init__(self, border_char):
self.__border_char = border_char
# ˅
pass
# ˄
def clone(self):
#... |
import time
from time import process_time, process_time_ns
from wiki.design_patterns.singleton import IsaacEdition
def duration_in_milliseconds_decorator(function):
def wrapper(*args, **kwargs):
start_time = time.time()
try:
function(*args, **kwargs)
except Exception as e:
... |
import os
from flask import Flask, request, redirect, url_for, jsonify, render_template
from werkzeug.utils import secure_filename
from eyedata.packData import *
import json
UPLOAD_FOLDER = 'static' + os.sep + 'Uploads'
ALLOWED_EXTENSIONS = set(['xlsx', 'xls'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLO... |
# Text stimulus
#
# Copyright (C) 2010-2013 Huang Xin
#
# See LICENSE.TXT that came with this file.
# Taget stimuli
#
# Copyright (C) 2010-2013 Huang Xin
#
# See LICENSE.TXT that came with this file.
from VisionEgg.Text import Text
from LightData import dictattr
from Core import Stimulus
class Hint(Stimulus):
... |
class Byte(object):
def __init__(self, pattern_string: str):
self.pattern_dict = {}
# So that 0 is the least significant bit
# and to allow bit twiddling, this is a dictionary
for index, char in enumerate(reversed(pattern_string)):
if char is '0':
self.pa... |
list1 = [1,6,4,8,1,3,13.5,123.0]
list2 = ["acd", "gmfdk", "abc"]
list1.sort()
print(list1)
list3 = [[1, 2, 3],
[4, 5, 6, 6, 4],
[7, 8, 9, 6]
]
list3.sort(key=len)
print(list3) |
import requests
def connect_google():
url="https://www.google.com.hk/"
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'
}
proxies = {"https": "http://127.0.0.1:1080"}
try:
... |
# -*- coding: utf-8 -*-
import re
import scrapy
from ..items import NewsLink
class VietnamNewsThanhnienSpider(scrapy.Spider):
name = 'vietnam_news_thanhnien'
allowed_domains = ['thanhnien.vn']
start_urls = [
# 'https://thanhnien.vn/thoi-su/trang-1.html',
# 'https://thanhnien.vn/the-gioi/tr... |
# O(log n)
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
assert len(nums) >= 1
if len(nums) == 1:
return nums[0]
lo = 0
hi = len(nums) - 1
if nums[lo] < nums[hi]:
# It is still sort... |
from django.apps import apps
from django import forms
#from .models import Listing, HousingUser
class HousingUserCreationForm(forms.ModelForm):
class Meta:
model = apps.get_model("listings", "HousingUser")
fields = ('user',)
class ListingForm(forms.ModelForm):
additional_lease_terms = forms.Ch... |
#soma hipotenusa
def inteiro(n):
return n % 1 == 0
def é_hipotenusa(x):
import math
i=1
hipotenusas=[]
while i < x:
j = 1
while j < x:
hipotenusa = math.sqrt(j*j + i*i)
if inteiro(hipotenusa):
hipotenusas.append(hipotenusa)
j += 1
i += 1
if x in hipotenusas:
return True
else:
return Fa... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'SET.ui'
#
# Created by: PyQt5 UI code generator 5.13.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow2(object):
def setupUi(self, MainWindow2):
... |
# TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge(lhs, rhs):
merged_list = []
# while the length of the rhs and the lhs remain
# above 0 - compare the first of each list and
# append them in ascending order to the new
# merged list
while len(lhs) > 0 and len(rhs) > 0... |
import pickle
import numpy as np
import matplotlib.pyplot as plt
# Gian is nice
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash(str(self))
def __... |
from django.contrib import admin
from wapipelines.models import Pipeline, Step, Result
admin.site.register(Pipeline)
admin.site.register(Step)
admin.site.register(Result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.