text stringlengths 38 1.54M |
|---|
import mysql.connector
def inject_data(data, user='root', database='restaurantwebsite'):
cnx = mysql.connector.connect(user=user, database=database)
cursor0 = cnx.cursor()
cursor1 = cnx.cursor()
cursor2 = cnx.cursor(prepared=True)
query0 = ("DROP TABLE IF EXISTS top10")
query1 = ("CREATE T... |
# coding: utf-8
import os
from .default import Config
class DevelopmentConfig(Config):
"""Base config class."""
# Flask app config
DEBUG = True
TESTING = False
SECRET_KEY = "sample_key"
# Db config
SQLALCHEMY_BINDS = {
'geo_pickups': 'mysql+pymysql://root:123qwe,./@10.0.11.91:188... |
import os
import datetime
import pymongo
from flask import Flask, flash, render_template, redirect, url_for, request
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
app = Flask(__name__)
app.config["MONGO_DBNAME"] = 'space_definitions'
app.config["MONGO_URI"] = os.environ.get('MONGO_URI')
# The fo... |
# Generated by Django 3.0.8 on 2020-11-08 05:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0017_auto_20201107_1239'),
('events', '0018_auto_20201107_1108'),
]
operations = [
]
|
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
from time import sleep
driver = Chrome(executable_path='/opt/WebDriver/bin/chromedriver')
# test link
driver.get("https://www.bhphotovideo.com/c/product/1561250-REG/fractal_design_fd_ca_mesh_c_bko_meshify_c_atx_matx_itx_blackout.html... |
#func to prin ladder based on input
def display_ladder(steps):
for count in range(steps):
print("| |\n***")
#func to get steps input
def create_ladder():
lad_steps = int(input("How many steps remain?\n"))
display_ladder(lad_steps)
#call func
create_ladder()
|
"""Methods often used to compare against to indicate baselines performance.
Many are based on [Raa16a]_.
"""
from dapper import *
@DA_Config
def EnCheat(**kwargs):
"""A baseline/reference method.
Should be implemented as part of Stats instead."""
def assimilator(stats,HMM,xx,yy): pass
return assimilator
@D... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 1 11:50:13 2016
@author: mads
#Make crops of images and annotations
History:
2017-05-23: Added support for keeping both original and cropped
2017-05-24: Fixed an error causing multiple threads to access same image when writing
"""
import os
import csv
import... |
from omega_pygame.core.pygame_api import pygame
def load_image(img_path):
return pygame.image.load(img_path)
def save_image(surface, img_path):
pygame.image.save(surface, img_path)
__all__ = ["load_image", "save_image"]
|
"""Tests for the entity blueprint"""
from json import dumps
import requests
from tentd.documents.entity import Follower
from tentd.tests import EntityTentdTestCase
from tentd.tests.mocking import MockFunction, MockResponse, patch
class FollowerTests(EntityTentdTestCase):
"""Tests relating to followers."""
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# coding=utf-8
"""
@author: Li Tian
@contact: litian_cup@163.com
@software: pycharm
@file: Caltools.py
@time: 2020/1/15 9:32
@desc: 小朋友计算小程序
【version 1.0】 20200115 实现基本功能
1. 输入数字a,计算a以内的加减法
"""
import random
class Caltool:
def __init__(self):
... |
"""
get user's id by m.ixigua.com
"""
# coding: utf-8
import requests
import json
import re
import sqlite3
from database import SqlXigua, AllUser
from config import XConfig, logging
from utilities import record_data
import time
from multiprocessing import Pool
from datetime import datetime
from user import User
# reg... |
import logging
from flask import Flask, jsonify, request
############ INIT ###########
app = Flask(__name__)
logging.basicConfig(filename='prl2016.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
class Tube:
def __init__(self, _id):
self.loaded = False
self.id = _id
... |
-*- coding: utf-8 -*-
"""
Created on Tue Feb 3 23:52:23 2015
@author: erostate
type can be "train", "validation"
can skip records on keep only some records if needed
will skip/keep last day on train/validation
command line format is:
$pypy csv_to_vwoneNamespacePerFeature.py filetoread filetowrite train
$pypy csv_... |
# http://bazel.io/
# vim: set ft=python sts=2 sw=2 et:
UNKNOWN_SRCS = [
"aes/aes_cbc.c",
"aes/aes_core.c",
"bf/bf_enc.c",
"bn/bn_asm.c",
"camellia/camellia.c",
"camellia/cmll_cbc.c",
"camellia/cmll_misc.c",
"des/des_enc.c",
"des/fcrypt_b.c",
"rc4/rc4_enc.c",
"rc4/rc4_skey.c"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import random
def md5_encryption(text):
'''
加密处理字符串
:param text:加密字符串
:return:
'''
md5 = hashlib.md5() # 实例化MD5加密对象
md5.update(text.encode('utf-8')) # 字符串必须转码
data = md5.hexdigest() # 获取加密数据
return data
... |
from wknn.models.units.sigmoid_neuron import Sigmoid_Neuron
from itertools import tee
def test_train_sigmoid_function():
from matplotlib import pyplot as plt
from wknn.utilities.output_fuctions import sigmoid_funct
p = Sigmoid_Neuron()
p.W = [5.5, 2.50, -2.01]
X = {
1: ([1.0, 1.5, -0.5], 0... |
#!/usr/bin/env python
"""
Generates the output for the /prism directory inside /_site.
Converts any .shtml files encountered to plain .html files.
Usage:
python _plugins/prism.py
"""
import os
import os.path
import shutil
import re
import sys
def main(args):
for (dirpath, dirnames, filenames) in os.walk('p... |
#!/usr/bin/env python
"""Translate quaternion orientation into heading angle.
Subscribes: imu/data (Imu)
Publishes: heading (Float32)
"""
from __future__ import division
import rospy
import tf
import math
from std_msgs.msg import Float32
from sensor_msgs.msg import Imu
class heading_processing(object):
def __i... |
# Copyright 2018 Google LLC
#
# 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, s... |
class Vehical:
def __init__(self,number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels, = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity
def drive(self):
... |
from django.conf.urls import url
from . import views
app_name = 'areas'
urlpatterns = [
url(r'^$', views.areacomum, name='areacomum'),
url(r'^apostar/$', views.apostar, name='apostar'),
url(r'^areapessoal/$', views.areapessoal, name='areapessoal'),
url(r'^carregarsaldo$', views.carregarsaldo, name='car... |
# import pandas as pd
# import re
# re.match
def ab(a, b):
"""a plus b"""
return a + b
c = ab(1, 2)
print(c)
import pandas as pd
pd.read_pickle
|
class Queue(object):
def __init__(self, alist):
self.alist = alist
def enqueue(self, param):
self.alist.append(param)
return param
def dequeue(self):
aparam = self.alist[0]
self.alist = self.alist[1:]
return aparam
alist = [5, 4, 8, 7]
queue = Queue(alist)... |
# Copyright (c) 2009-2010 Simon van Heeringen <s.vanheeringen@ncmls.ru.nl>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
""" Module to calculate ROC and MNCP scores """
# External imports
from... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
import datetime
import csv
import regex
import click
import csv_utf8
import HTMLParser
from pprint import pprint
import requests
from lxml import html
import logging
logger = logging.getLogger()
# Setting up logger
logger.setLevel(logging.INFO)... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import numpy as np
def mean_squared_error(y, label):
# y/label can be multi dimensional array
row_count = y.shape[0]
ret = 0.5 * np.sum((y - label) ** 2) / row_count
return ret # sum((y-t)**2) / row_count
def softmax(array):
tmp = array.copy() # a... |
import boto3
dynamodb = boto3.client('dynamodb')
def lambda_handler(event, context):
params = event['queryStringParameters']
if 'email' not in params or 'dropbox_oauth_token' not in params:
response = create_response(400, 'Missing info for registration.')
return response
email = params['em... |
class Node:
def __init__(self,data):
self.data = data;
self.next = None;
class Linked:
def printList(self):
temp = self.first
while temp:
print temp.data
temp = temp.next
def __init__(self):
self.first = None
if __name__ == '__main__':
list = Link... |
"""
Task database support module.
A database which react with the following JSON format data.
JSON Format:
{
'id': int, task id;
'desc': str, task description;
'data': dict, any data of specific task, e.g. sid, .sh file;
'time_stamp': dict with:
'create': str, time of task creation
'sta... |
from datetime import datetime, timedelta
from decimal import Decimal, InvalidOperation
from io import StringIO
import re
from django.core.exceptions import ValidationError
from django.core.management import call_command
from django.db import connection, transaction
from authentication import models as a_models
from m... |
# Contains various functions which are used for tasks which does not fit to any other python file.
import netTools as nt
import ipaddress
import netTools as net # tools for network connection
from subprocess import check_output
DISCOVERY_TIMEOUT_SEC = 1200 # secs within which all nodes should be reached ; if timeou... |
def car(x):
return x[0]
def cdr(x):
return x[1:]
def cons(x, y):
return [x] + y
def acharLugar(x, lista1):
if lista1 == []:
return cons(x, lista1)
elif x > car(lista1):
return cons(car(lista1), acharLugar(x, cdr(lista1)))
elif x <= car(lista1):
return cons(x,lista1)
d... |
from union_find import UnionFind
# Friend Circles
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
n = len(M)
uf = UnionFind(n)
for i in range(n):
for j in range(i + 1, n):
if M[i][j... |
import urllib2
response = urllib2.urlopen("https://raw.github.com/BenOut/PythonLogFileReader/master/dilemmas_new_users.py")
python_script_from_git = response.read()
exec python_script_from_git
raw_input("Press enter to close")
|
import discord
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, MissingPermissions
import discord.abc
import sys, traceback
import bot_config
import psutil
import os
import random
import re
import asyncio
from quickstart import *
spread = spread()
lbIDFile = "leaderboardmessag... |
#!/usr/bin/env python
''' Service Now ticket CLI '''
import argparse
import os
import json
from ticketutil.servicenow import ServiceNowTicket # pylint: disable=import-error
class ServiceNow(object):
"""SNOW object"""
def __init__(self):
"""Set object params"""
self.url = os.environ.get("sn... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 20 00:49:17 2014
@author: LeBronJames
"""
import MapReduce, sys
mr = MapReduce.MapReduce()
def mapper(record):
key = record[1]
value = record
mr.emit_intermediate(key, value)
def reducer(key, list_of_values):
order_records = filter(lambda x : x[0] == '... |
''' Solves problem #27 on https://projecteuler.net
Sergey Lisitsin. May 2019'''
def sequence(a,b):
n = 0
seq = 0
while seq == n:
# print ((n*(n+a))+b)
if isprime(n*(n+a)+b):
seq +=1
n += 1
return(seq)
def isprime(num):
for x in range(2,(abs(num)/... |
class Prime(object):
@classmethod
def main(cls, args):
print(cls.isPrime(50))
print(cls.isPrime(47))
@classmethod
def isPrime(self, n):
if( n > 1):
answer = True
else:
answer = False
i = 2
while(i*i <= n):
... |
from django.shortcuts import render, redirect, render_to_response
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404, JsonResponse
from django.db import transaction
from forms import *
from models import *
from accou... |
str = input("Enter the string value ")
result = ''
first = ''
last = ''
if len(str) < 2:
result = "Empty String"
else:
first = str[0:2]
last = str[-2:]
result = first+last
print(result)
|
# -*- coding: utf-8 -*-
from melange.exceptions import FragmentError
import json
import lxml.html
import UserDict
class MelangeFragment(object):
"""Single Melange Fragment
"""
def __init__(self, raw):
self._manifest = None
self.raw = raw
self.html = lxml.html.fromstring(raw)
... |
import turtle
import sys
from time import sleep
from easyTypeWriter import typeWriter
import winsound
#sound credit goes to harshnative on github
wn = turtle.Screen()
wn.setup(600,600)
sky =('sky.gif')
wn.bgpic(sky)
# message = "Hello"
obj = typeWriter.EasyInput()
words = "Hello! Welcome to our typing game! :P"
def c... |
import random
import math
import matplotlib.pyplot as plt
LEARNRATE = 0.05
def getRandom():
return random.random()*0.5
class Neuron:
def __init__(self,id,numInput):
self.id = id
self.error = 0
self.output = 0
self.input = []
self.weights = []
#Initialization ... |
#!usr/bin/python
n=int(raw_input("Enter the no. of elements :"))
a=[]
b=[]
print "Enter the elements :"
for i in xrange(n):
x=int(input())
a.append(x)
for i in xrange(n):
for j in range(i+1,n):
if a[i]==a[j]:
a[i]=a[j]=0
for i in xrange(n):
if not a[i]==0:
pri... |
import pandas as pd
from pandas import DataFrame
EXCEL_TYPES = ['xls', 'xlsx', 'xlsm', 'xlsb', 'odf', 'ods', 'odt']
NUMERICS = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
def return_numerical_columns(df: DataFrame, result_column: DataFrame, exclude: [] = None):
df_num = df.select_dtypes(include... |
# -*- coding: utf-8 -*-
from typing import List
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def mergeTwoKLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
... |
"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
from collections import deque
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not roo... |
# Sum of odd numbers
# https://www.codewars.com/kata/55fd2d567d94ac3bc9000064/train/python
# Instructions:
# Given the triangle of consecutive odd numbers:
# 1
# 3 5
# 7 9 11
# 13 15 17 19
# 21 23 25 27 29
# ...
# Calculate the row sums of this triangl... |
def main():
m,d = map(int, input().split())
for i in range(1,m):
if i == 1 or i == 3 or i == 5 or i == 7 or i ==8 or i == 10 or i ==12:
d += 31
elif i == 2:
d += 28
else:
d += 30
today = d % 7
print(switch(today))
def switch(to... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'mainHDlTlQ.ui'
##
## Created by: Qt User Interface Compiler version 5.14.1
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
###############... |
# -*- coding: utf-8 -*-
__author__ = "SadLin"
import sys
import urlparse
import optparse
from lib.calc_check import *
from lib.match_rule import match_type
from lib.load_plugins import load_plugins,show_waf_list
class checkWaf(object):
def __init__(self,RespDict):
self.respDict = RespDict
#... |
# Python3 program to count distinct
# divisors of a given number n
def SieveOfEratosthenes(n, prime, primesquare, a):
# Create a boolean array "prime[0..n]" and initialize all entries it as true.
# A value in prime[i] will finally be false if i is not a prime, else true.
for i in range(2, n + 1):
p... |
"""Take in any given and find best param
USAGE
-----
$ python mrec/model/grid_search.py
# Launch an mlflow tracking ui after model results to compare
$ mlflow ui
Add parameters via `model/make_classifiers.py` with its associated model
"""
# Standard Dist Imports
import logging
import os
import joblib
from pprint im... |
from golem import actions
from projects.golem_integration.pages import golem_steps
description = 'Verify step action'
def test(data):
actions.step('this is a step')
golem_steps.assert_last_step_message('this is a step')
|
from django.contrib import admin
from .models import (
GalleryProduct,
Product,
Color,
Size
)
class ImageProductInline(admin.StackedInline):
model = GalleryProduct
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_filter = ('status', 'gold_or_jewelry')
search... |
import os
import github3
from github3 import repos
from datetime import datetime
from tests.utils import (expect, BaseCase, load)
from mock import patch, mock_open
class TestRepository(BaseCase):
def __init__(self, methodName='runTest'):
super(TestRepository, self).__init__(methodName)
self.repo =... |
from data import *
from table import *
def getSize(vec):
sq_sum = 0
for i in vec:
sq_sum+= i**2
return round(np.sqrt(sq_sum),4)
#Define Billiard ball object
class Ball:
pos = np.array([0.0,0.0,0.0])
vel = np.array([0.0,0.0,0.0])
ang = np.array([0.0,0.0,0.0])
initial... |
import csv
from pathlib import Path
from datetime import datetime
import matplotlib.pyplot as plt
path = Path("weather_data/death_valley_2021_simple.csv")
lines = path.read_text().splitlines()
reader = csv.reader(lines)
header_row = next(reader)
# Extract dates and high temperatures.
dates, highs, lows = [], [], []... |
import collections
import numpy as np
import scipy.ndimage
import scipy.signal
from numba import njit
from scipy.special import logit, expit
def make_nondecreasing(x):
dx = np.diff(x)
dx[dx < 0] = 0
return x[0] + np.r_[0, np.cumsum(dx)]
def ceil_pow_2(k):
if bin(k).count('1') > 1:
k = 1 << k... |
#!/usr/bin/env python
"""
Author: Loic Dutrieux
Date: 2018-05-07
Purpose: Query the result of a classification and write the results to a vector
file on disk
"""
from madmex.management.base import AntaresBaseCommand
from madmex.models import Country, Region, PredictClassification
from madmex.util.spatial import f... |
"""
CALM
Copyright (c) 2021-present NAVER Corp.
MIT license
"""
__all__ = ['activation_map']
def activation_map(model, images, targets, score_map_process,
superclass=None, **kwargs):
cams = model(images, targets, superclass, return_cam=score_map_process)
return cams
|
import os
import cv2
from base_camera import BaseCamera
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
class Camera(BaseCamera):
video_source = 0
def __init__(self):
if os.environ.get('OPENCV_CAMERA_SOURCE'):
Camera.set_video_source(i... |
def myfunc(*args):
out = []
for num in args:
if num%2==0:
out.append(num)
return out
|
from bs4 import BeautifulSoup as bs
from cleantext import clean
from langdetect import detect
def form_elements(soup):
form_count = 0
input_count = 0
for form in soup.find_all("form"):
form_count += 1
for input_element in form.find_all("input"):
input_count += 1
return form_... |
# heavily inspired by https://github.com/mlflow/mlflow/blob/master/mlflow/projects/utils.py
import logging
import os
import platform
import re
import subprocess
import sys
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import click
import wandb
from wandb import util
from wandb.apis.internal impor... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import itertools
import re
import scrapy
from datetime import datetime
from functools import reduce
class HcdnSpider(scrapy.Spider):
name = "hcdn"
allowed_domains = ["http://www.hcdn.gob.ar/proyectos/proyectoTP.jsp?exp="]
... |
# practicing to scrape multiple pages on the web
import requests
from bs4 import BeautifulSoup
# picking our site
url = 'https://scrapingclub.com/exercise/list_basic/?page=1'
# getting the response
response = requests.get(url)
# picking our parser
soup = BeautifulSoup(response.text, 'lxml')
items = soup.find_all('d... |
import math
a = int(input("a 값? "))
b = int(input("b 값? "))
c = int(input("c 값? "))
판별식 = b**2 - 4*a*c
if 판별식 <0 :
print("해가 없습니다.")
elif 판별식 == 0 :
print("해가 1개 입니다.")
print("해 : %.2f" % (-b/2*a) )
elif 판별식 > 0 :
해1 = (-b + math.sqrt(판별식)) / (2*a)
해2 = (-b - math.sqrt(판별식)) / (2*a)
prin... |
class Solution:
def reverseBits(self, n: int) -> int:
count = 31
num = 0
while n > 0:
num = num + ((n&1) * 2**count)
n = n >> 1
count -= 1
return num |
class MathClock:
# hour = 0
# minuts = 0
def __init__(self, hour = 0, minuts = 0):
self.hour = hour
self.minuts = minuts
def __repr__(self):
return repr(self.hour+self.minuts)
def __add__(self, other):
return MathClock(self.minuts + other)
def __sub__(self, oth... |
import keras
from traitement_images import traitement_images
import time
model = keras.models.load_model("miniprojet_n_classes.h5")
from cv2 import VideoCapture, imwrite
# initialize the camera
cam = VideoCapture(0) # 0 -> index of camera
#cam = VideoCapture('http://192.168.1.36:4747/video')
while(1):
... |
#!/usr/bin/env python
from pru_speak import pru_speak
import socket
#Server on local host @ port 6060
TCP_IP = '127.0.0.1'
TCP_PORT = 6060
#The max size upto which is recieved at one go
BUFFER_SIZE = 1024 * 2
#create a passive socket and bind it to 127.0.0.1:6060
s = socket.socket(socket.AF_INET, socket.SOCK_STREA... |
import hardware, cpu, time
class ppu:
def __init__(self, nes):
self.DEBUG = 1
self.firstWrite = 0
self.mirroring = "vert"
#PPU 2000 register indexes
self.NMIOnVBlank = 0
self.ppuMasterSlave = 1
self.spriteSize = 2
self.backgroundPatternA... |
import pygame
import random
import math
from pygame import mixer
# initialization
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 620))
# background
background = pygame.image.load('background.png')
#bg sound
mixer.music.load('background.wav')
mixer.music.play(-1)
# title and icon
pygame.... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 1 00:15:25 2015
@author: hoseung
"""
from galaxymodule import galaxy
def get_center(x, y, z, m, method='default'):
"""
Determines the center of mass of given particles.
IDL version was to iteratively search for mass weighted mean position of
particles w... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('adm', '0157_auto_20171124_0921'),
]
operations = [
migrations.AlterModelOptions(
name='rut',
options... |
import couchdb
import schemas
from enum import Enum
class DB_Schema(Enum):
corey = 1
fang = 2
class Importer:
def __init__(self):
self.db_schemas = {
"stackoverflow_daily": DB_Schema.corey,
"stackoverflow_monthly": DB_Schema.fang,
"stackoverflow_monthly_2000": DB_Schema.fang
}
def getDataFromDB(... |
def validate_data(data, attrs=list()):
if not bool(data):
return False
response = True
for key, value in data.iteritems():
if key not in attrs:
response = False
break
return response
|
"""
이 경우 local_num 함수는 지역 변수 num이 존재하고
global_num 함수는 지역 변수 num이존재하지 않습니다.
그러므로 내부에서 return 할 때 num을 호출하지만 결과는 다르게 됩니다.
"""
num = 10
def local_num(a):
num = 100 # 지역변수 인식, 전역변수에는 영향 없음
return a + num
def global_num(a):
return a + num
val1 = local_num(100)
val2 = global_num(100)
print(val1) # 200
print... |
from django.db import models
class RegresionLineal(models.Model):
cantidad = models.IntegerField()
valor = models.FloatField()
x = models.FloatField()
p = models.FloatField()
def set_valor(self, valor):
self.valor = valor
def get_valor(self):
return self.valor
def se... |
# -*- coding: utf-8 -*-
import scrapy
from news_scrap.items import NewsScrapItem
from scrapy.linkextractors import LinkExtractor
import urlparse
from scrapy.spiders import CrawlSpider, Rule
from scrapy.http import Request
class BkkbizSpider(scrapy.Spider):
name = 'bkkbiz'
allowed_domains = ['www.bangkokbiznew... |
# coding=utf-8
from data_common.utils.file_util import FileUtil
from data_common.extract_common.template.template_analysis import TemplateAnalysis
from data_common.extract_common.sites.site_base import BaseSite
class Douban(BaseSite):
url_patterns = ['https://movie.douban.com']
def __init__(self):
s... |
{
'includes': [
'../gyp/common.gypi',
],
'targets': [
{ 'target_name': 'symlink_TEST_DATA',
'type': 'none',
'hard_dependency': 1,
'actions': [
{
'action_name': 'Symlink Fixture Directory',
'inputs': ['<!@(pwd)/../test'],
'outputs': ['<(PRODUCT_DIR)/T... |
from bs4 import BeautifulSoup
import wikipedia as wiki
from pathlib import Path
import re
def get_page(query):
"""
Returns a Wikipedia Page Object from a search term.
Assumes the page esists and the query is mostly spelled right
Args:
query: (Str) The title of wiki page to search for
Re... |
"""
data set will look like this
[[23], [56] ... ] <--- size going to be length of data set
when we first calculate the centroids
[[23], [56]...] <--- size is going to be k
clusters will look like
each sub list is a cluster
each element in cluster... is the original index of the actual data point
[[1, 2, 8], [9, 10, ... |
#!/usr/bin/python
import math
def prime(n):
if n < 4: return True
max = int(math.floor(math.sqrt(float(n))))
for i in xrange(max+1):
if i < 2: continue
if (n % i == 0): return False
return True
x = 600851475143
out = -1
max = int(math.floor(math.sqrt(x)))
best = -1
for i in xrange(1,m... |
from traits.api import Str, Int, Float, Bool, Enum
import enaml
from enaml.stdlib.sessions import show_simple_view
from Instrument import Instrument
class MicrowaveSource(Instrument):
address = Str('', desc='Address of unit as GPIB or I.P.')
power = Float(0.0, desc='Output power in dBm')
frequency = Floa... |
wow = str(raw_input('enter a word to do it twice: '))
def do_twice(f):
f()
f()
def print_wow():
print'wow'
def do_four(do_twice):
do_twice(print_wow)
do_twice(print_wow)
do_four(do_twice)
|
from django.shortcuts import render
def index(request):
return render(request, 'mainApp/index.html')
def contacts(request):
return render(request, 'mainApp/contacts.html')
def about(request):
return render(request, 'mainApp/about.html')
def wrong(request):
return render(request, 'feedback/wrong.html')
def thank... |
# Generated by Django 3.0.2 on 2020-01-26 07:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('subject', '0003_remove_subject_teacher'),
]
operations = [
migrations.AddField(
model_name='subject',
name='name',
... |
# In this assignment you must do a Twitter search on any term
# of your choice.
# Deliverables:
# 1) Print each tweet
# 2) Print the average subjectivity of the results
# 3) Print the average polarity of the results
# Be prepared to change the search term during demo.
import tweepy
from textblob import TextBlob
import... |
def test(a, b):
x = a // b
y = a % b
# 一般情况下,一个函数最多只会执行一个return语句
# 特殊情况(finally语句)下,一个函数可能会执行多个return语句,但是会存在覆盖的情况
# return x #return语句表示一个函数的结束
# return {'x':x,'y':y}
# return [x,y]
# return (x,y) #推荐使用
return x,y #返回的本质是一个元组
result = test(13, 5)
print("商是{},余数是{}".form... |
import pytest
import simplejson
from django.core.urlresolvers import reverse
from adserving.types import Decimal
@pytest.mark.parametrize('user_data, results', [
(('user_1', '123'), ('$30.00', '$30.00', 2)),
(('user_2', '123'), ('$0.00', None, 0)),
])
def test_billing_info_auth(client, billing_app, user_data... |
import sqlite3
Conexion = sqlite3.connect("Jugador")
Puntero = Conexion.cursor()
Jugadores = [
("Manu", "soymanu44", 15),
("Silvio", "manuputo", 15)
]
Puntero.executemany("INSERT INTO Jugadores VALUES(NULL, ?, ?, ?)", Jugadores)
Conexion.commit()
Conexion.close()
|
import pygame
from pygame.sprite import Group
import config
from .game_state import GameState
from states.ready import Ready
from .high_score import HighScore
from animation import StaticAnimation
from starfield import Starfield
import sounds
class Menu(GameState):
TitleSize = 64
MenuItemSize = 32
MenuIte... |
import sqlalchemy
class Database:
def __init__(self, username="root", password="", host="localhost", port=3306, database=None):
if database is None:
raise ValueError("Key database is required")
if type(database) is not str:
raise TypeError("The key database must be a string"... |
class TreeNode(object):
def __init__(self, init_data=None):
self.data = init_data
self.left = None
self.right = None
def __str__(self):
return str(self.data)
def traverse(root):
if not root:
return
traverse(root.left)
print(root, end=' ')
traverse(root.... |
import numpy as np
import math
class metronomo:
def __init__(self, nota, tempo, metrica):
self.nota = nota
self.tempo = tempo
self.metrica = metrica
self.tiempo = float(60/float(tempo))
def metrono(self):
array = []
note=0
if self.nota == 'c':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.