text stringlengths 38 1.54M |
|---|
from .distances import euclidean
from random import random
def kmeans(k, datapoints):
"""
Implementation of the k-Means algorithm.
Parameters
==========
k : int
The number of centers you want to position
datapoints : list<list>
A python list with the datapoints
"""
centers = [-1] * k
new_centers = []
f... |
#!/usr/bin/env python3
import os
import openpyxl
from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
#dir = os.getcwd()
#print(dir)
# Open workbook
wb = load_workbook(filename = 'BomList.xlsx') # similar to wb = openpyxl.lo... |
import os
import logging
from pathlib import Path
from urllib.parse import urlparse, parse_qs
from slack import RTMClient
from youtube import Youtube
filename = Path(__file__).name.split('.')[0]
logging.basicConfig(level='INFO')
logger = logging.getLogger(filename)
client_id = os.environ['YOUTUBE_CLIENT_ID']
client... |
from rouge import Rouge
a = ["我 am a student from xx school","i am a student from xx school"] # 预测摘要 (可以是列表也可以是句子)
b = ["i am a student from school on china","i am a student from xx school"] #真实摘要
rouge = Rouge()
rouge_score = rouge.get_scores(a, b)
print(rouge_score[0])
print(rouge_score[1])
print(a[0].split())
# pr... |
#!/usr/bin/python2.7
from Linearity import Neuron
import sys
import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
n = Neuron.load(sys.argv[1])
def findOnsetTime(trial, step=2., slide = 0.05, minOnset = 2., maxOnset = 50., initpValTolerance=0.5):
maxIndex = int(trial.F_sample*maxOnset*1e-3)
... |
import math
import os
import random
import re
import sys
import operator
# Complete the prims function below.
def prims(n, edges, start):
#build the graph
graph = {}
visited = set()
for edge in edges:
if edge[0] not in graph:
graph[edge[0]] = []
graph[edge[0]].append((edge[1... |
'''
Created on 03.06.2010
@author: valexl
'''
import sys
import os
import pickle
import subprocess
import shutil
from PyQt4 import QtGui,QtCore,QtSql
from RepoManager.SystemInfo import SystemInfo
from RepoManager.User import User
from EntityManager.EntityManager import EntityManager
from RepoManager.RepoManager im... |
import numpy as np
import matplotlib.pyplot as plt
from daomath.fields import VectorField
from daomath.du import *
from daomath.utility import *
class Force(VectorField):
def __init__(self,u,v,p=0,r=[-1,100]):
super().__init__(u,v,p,range=r)
class MaterialPoint():
def __init__(self,x0=0,y0=0,mass=1)... |
import os
import cv2
import torch
import numpy as np
from time import time
from multiprocessing import Pool, cpu_count
from functools import reduce
from pdb import set_trace
# ==============================================================================
# NOTE: Run all of the code from the ./code directory!
# =======... |
# Leftie solution
from threading import Semaphore, Thread
import time
from typing import Callable
def solution___at_least_one_leftie():
PHILOSOPHERS = 5
forks = [Semaphore(1) for _ in range(PHILOSOPHERS)]
def philosopher(i: int, leftie: bool, stop: Callable):
print(f'starting philosopher {i} |... |
'''MobileNetV1 in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from sp_conv import SpConvBlock, swish
__all__ = ['sp_mbnet']
class SpMbBlock(nn.Module):
'''Dept... |
#python 3.5环境,解释器在linux需要改变
# -*- encoding:utf-8 -*-
#Auth ChenJinPeng
from django import forms
from books import models
class BookForm(forms.Form):
name = forms.CharField(max_length=10)
publish_date = forms.DateField()
class ModelForm(forms.ModelForm):
class Meta:
model = models.Book
# fi... |
"""This plugin is for Lesson 5: Scene Changes; Project: GoldRush."""
from __future__ import print_function
from collections import Counter
from kelpplugin import KelpPlugin
from . import initializationViewer
import os
import sys
import kurt
BASE_PATH = './results'
class Plants(KelpPlugin):
def __init__(self):
... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
class GroupManage(object):
"""docstring for GroupManage"""
def __init__(self, conf):
super(GroupManage, self).__init__()
self.conf = conf
def send_message(self):
pass
def on_recv_message(self):
pass
def on_new_memb... |
from sklearn import datasets
class IrisDatasetLoader:
def __init__(self):
self.data = datasets.load_iris()
def load_data(self):
X = self.data.data
y = self.data.target
return X, y
class BostonDatasetLoader:
def __init__(self):
self.X = None
self.y = None
... |
#prints a string -sentence
print "Mary had a little lamb."
#prints a string by implementing a string into an embedded format character.
print "Its fleece was white as %s." % 'snow'
#prints a string - sentence
print "And everywhere that Mary went."
#prints ten periods together like this ...........
print "." * 10 # what... |
import util.Events as Events
from msn import CommandProcessor
import logging
log = logging.getLogger('msn.p.sb')
class MSNSwitchboard(Events.EventMixin, CommandProcessor):
events = Events.EventMixin.events | set ((
'on_buddy_join',
'on_buddy_leave',
'on_buddy_timeout',
'on_conn_... |
# -*- coding: utf-8 -*-
import sys, os, re, html, urllib
from os.path import dirname, basename, isdir, exists
from . import urlregexps
from . import utils
from . import localwebfn
from .utils import join, normpath
usage = """
Usage:
python3 -m idupree_websitepy.rrify path/to/dir/to/swizzle/
This swizzling looks for... |
# coding: utf-8
# In[1]:
import cv2
import numpy as np
# In[ ]:
cap = cv2.VideoCapture(0)
# In[12]:
while cap.isOpened():
ret, frame = cap.read() #reading the frame
ret,thresh1 = cv2.threshold(frame,127,255,cv2.THRESH_BINARY )
ret,thresh2 = cv2.threshold(frame,127,255,cv2.THRESH_BINARY_... |
'''
Aproximación de marea a partir de sus principales componentes
Requiere especificar el archivo con los datos
calcula las componentes usando fft
toma todas las que son mayores a un límite
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.text as mpltext
import datetime as dt
import sys
import m... |
# Generated by Django 2.0.8 on 2018-09-06 19:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0106_auto_20180906_1240'),
]
operations = [
migrations.AlterUniqueTogether(
name='panelist',
unique_together={('round... |
import os
from common_utils import log_change_single
from sklearn.linear_model import LinearRegression
class Pred_Info(object):
def __init__(self, stock, pred, target, actual, flag):
self.stock = stock
self.pred = pred
self.target = target
self.actual = actual
self.fla... |
from unittest import TestCase
from ......messaging.decorators.attach_decorator import AttachDecorator
from ..pres_format import V20PresFormat
CD_ID = "GMm4vMw8LLrLJjp81kRRLp:3:CL:12:tag"
INDY_PROOF_REQ = [
{
"name": "proof-req",
"version": "1.0",
"nonce": "12345",
"requested_attr... |
#! /usr/local/bin/python3
# _*_ coding:utf-8 _*_
"""
test for : str.encode()
bytes.decode()
"""
import os
CODEC = 'utf-8'
def main():
with open("text1","w") as f:
string_out = u"hello world"
print("string_type:",type(string_out))
bytes_out = string_out.encode(CODEC)
... |
'''
Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.
Since the answer may not fit in an integer data type, return the answer as a string.
If there is no answer return an empty string.
Input: digits = [8,1,9]
Output: "981... |
# test_message.py - unit tests for the sbclassifier.message module
#
# Copyright (C) 2002-2013 Python Software Foundation; All Rights Reserved
# Copyright 2014 Jeffrey Finkelstein.
#
# This file is part of sbclassifier, which is licensed under the Python
# Software Foundation License; for more information, see LICENSE.... |
#encoding=utf-8
'''
在python,值是靠引用来传递的,可以用id()查看一个
对象的引用是否相同,id是值保存在内存中那块内存地址
的标实
在调用对象过程中,实际传递的是对对象对引用
参数传递是通过引用来传递的
'''
# a = 1 #不可变类型 一旦确定,值改变会重新开辟一个新的内存空间
# def func(x):
# x=2 #此时地址已经发生了改变
# print('地址{}'.format(id(x))) #地址发生了变化
# pass
#
# print('地址{}'.format(id(a)))
# func(a... |
from django.urls import path
from bc import views as bc_views
app_name='handlers'
urlpatterns=[
path('',bc_views.IndexView.as_view(),name='home')
] |
import SuperPro_data as SP_data
import json
import argparse, sys, os
parser=argparse.ArgumentParser()
parser.add_argument('--path', help='this is the data file path')
parser.add_argument('--feedstock', choices=['corn_stover','sorghum'], help='Select your feedstock')
parser.add_argument('--fuel', choices=['ethanol','... |
from flask_babel import lazy_gettext as _
from flask_wtf import FlaskForm
from wtforms import BooleanField, StringField, TextAreaField, SubmitField, \
RadioField
from wtforms.ext.sqlalchemy.fields import QuerySelectMultipleField
from wtforms.validators import Optional
from app.forms.fields import CustomFormSelectF... |
# coding=utf-8
import subprocess
import time
import pyaudio
from gtts import gTTS
import flags
def say(text):
if not flags.debug:
PyAudio = pyaudio.PyAudio
RATE = 16000
data = ''
p = PyAudio()
stream = p.open(format=
p.get_format_from_width(1),
... |
"""
Bundling
https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc7/00000000001d3ff3
Problem
Pip has N strings. Each string consists only of letters from A to Z. Pip would like to bundle their strings into groups of size K. Each string must belong to exactly one group.
The score of a group is equa... |
# from django.urls import path
from django.conf.urls import include, url, i18n
from video.views import *
urlpatterns = [
url(r'^save_cache_str/$', saveCacheStr, name='save cache str'),
url(r'^quiz/(?P<course_name>\w+)/(?P<quiz_id>[0-9]+)/$', video_quiz, name='student quiz'),
] |
import networkx as nx
import facebook
import queue
import requests
import csv
import glob
import os
if __name__ == '__main__':
#tao graph networkx
g = nx.Graph()
#tao hang doi xep theo thu tu levels ten q
q = queue.PriorityQueue()
#tao graph de lay du lieu facebook
graph = facebook.GraphAPI(acc... |
from flask import Flask, render_template, request, redirect, session
app = Flask(__name__)
app.secret_key = 'keep it secret, keep it safe'
@app.route('/')
def info():
return render_template("index.html")
@app.route('/process', methods = ['POST'])
def user_info():
print(request.form)
session['name'] = requ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 15:17:48 2020
@author: kerstin
"""
class Config:
DATABASE='iobroker'
MOD_PORT=502
MOD_HOST="192.168.2.108"
INFLUX_PORT=8086
INFLUX_HOST='localhost'
PERIOD=2
PERIOD_STREAM=2
#definition of to be meassured item... |
def weirdTextEncoder(textNum):
totalBits = 32
lengthEachBit = 8
ascii_arr = []
## Conversion of the string into ASCII array
for s in textNum:
len_bit = len(bin(ord(s)).replace("0b",""))
if len_bit < lengthEachBit:
binValue = '0'*(lengthEachBit-len_bit)+bin(ord(... |
import sys
import traceback
def exception_handler(exctype, exception, tb):
error("" + exctype.__name__ + ": " + str(exception), exception)
sys.excepthook = exception_handler
# TODO: This should be changed to use Python standard logging
# mechanism and probably use a customized HTTPHandler:
# https://docs.python.... |
import pyautogui
import time
import sys
from vendas import moduloCadCliente
def login():
pyautogui.typewrite("1", interval=0.2)
pyautogui.press('enter', interval=0.2)
pyautogui.typewrite("ctr", interval=0.2)
pyautogui.typewrite("043244", interval=0.2)
pyautogui.press('enter', interval=0.2)
i =... |
from datetime import timedelta
import pandas as pd
import numpy as np
import plotly.graph_objects as go
class BaseModel:
use_dates = False
is_trained = False
is_predicted = False
record = ''
def __init__(self, x_train, y_train, predict_len=15, plot=True, plot_name='', start_date=None):
s... |
"""Constants for Snapcast."""
DATA_KEY = "snapcast"
GROUP_PREFIX = "snapcast_group_"
GROUP_SUFFIX = "Snapcast Group"
CLIENT_PREFIX = "snapcast_client_"
CLIENT_SUFFIX = "Snapcast Client"
SERVICE_SNAPSHOT = "snapshot"
SERVICE_RESTORE = "restore"
SERVICE_JOIN = "join"
SERVICE_UNJOIN = "unjoin"
SERVICE_SET_LATENCY = "se... |
# See if we have a special directory for the binaries (for developers)
import win32com
win32com.__PackageSupportBuildPath__(__path__)
|
# -*- coding: utf-8 -*-
import math
import calendar
import datetime
import codecs
import csv
import sys
import os
DAYSTART = '0300'
ROUNDDOWNTIME = 15
def option_parser():
usage = 'Usage: python {} [-i <input filename>] [-o <output filename>] [-d <period(yyyymm)>]'\
.format(__file__)
arguments = sys.... |
"""3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369."""
number = (input('Enter integer number (positive) '))
sum_number = int(number) + int(number + number) + int(number + number + number)
print(sum_number)
# method 2
sum_number = 0
... |
import os
import sys
import glob
import subprocess
import random
import fileinput
next_line = 0
lines = [line.strip() for line in fileinput.input()]
def get_line():
global next_line
i = next_line
next_line += 1
return lines[i]
cache = {}
def rev(s):
ans = ""
for i in range(len(s) - 1, -1, -... |
#!/usr/bin/env python
import pg, cgi
import auth_session
from db_functions import *
from cgi_functions import *
from navigation import *
from misc_functions import *
print "Content-type: text/html\n"
html = ""
feedbackHtml = ""
user_id = auth_session.session.getUserId()
# ------------------- Handle the submitted form... |
import logging
import random
import string
from collections import Counter
# from tqdm import tqdm
import sys
if sys.stderr.isatty():
from tqdm import tqdm
else:
def tqdm(iterable, **kwargs):
return iterable
from c2nl.objects import Code, Summary, AST
from c2nl.inputters.vocabulary import Vocabulary, U... |
"""Restaurant rating lister."""
def restaurant_ratings_list(filename):
restaurant_data = open(filename)
restaurant_dict = {}
for line in restaurant_data:
restaurant_name = line.rstrip().split(':')[0]
rating = line.rstrip().split(':')[1]
restaurant_dict[restaurant_name] = rating
... |
from django.contrib import admin
from django.db.models import QuerySet
from bots.models import Bot
@admin.register(Bot)
class BotAdmin(admin.ModelAdmin):
change_form_template = 'admin/change_bot_form.html'
actions = ['reset_webhook']
@admin.action(description="Re set webhook")
def reset_webhook(self... |
"""
CODE from https://github.com/mworchel/svbrdf-estimation
ADD CREDITS / REFERENCE BEFORE CODE RELEASE!!!
"""
import torch
import torch.nn as nn
import utils
from pytorch_svbrdf_renderer import Renderer, Config
class SVBRDFL1Loss(nn.Module):
def forward(self, input, target):
# Split the SVBRDF into it... |
import sys
test_cases = open(sys.argv[1], 'r')
i = 1;
first = True
for test in test_cases:
if (first):
first = False
continue
line = test.replace('\n', '').replace('\r', '')
# find zero
result = [];
index = line.find("Z")
while index != -1:
result.append(... |
import torch.nn.functional as F
import torch.nn as nn
from torchvision import models
from model_part import *
import functools
class UNet(nn.Module):
def __init__(self, input_nc=1, output_nc=1, bilinear=True):
super(UNet, self).__init__()
self.inc = DoubleConv(input_nc, 64)
self.... |
from transformation_1 import transformation_1
from transformation_2 import transformation_2
from environment import environment
def main():
project = environment['project']
dataset = environment['dataset']
table_prefix = environment['table_prefix']
transformation_1(project, dataset, table_prefix)
t... |
import sys
from uuid import uuid4
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from utils import createQrId
class AddStaff(QDialog):
def __init__(self, parent, cursor) -> None:
super().__init__(parent)
self.cursor = cursor
self.setupUi()
... |
# -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################
... |
# import numpy as np
from frospy.spectrum.app import check_input
from frospy.spectrum.spectrum_gui import set_defaults_init_main, print_gui
from frospy.spectrum import spectrum_gui
from frospy.spectrum.controllers import process_input
from frospy.core.spectrum.plot import init_plot_spectrum
from obspy.core import Attri... |
from django.urls import path
from . import views
urlpatterns = [
path('register/', views.register, name="register_pass"),
path('validate/', views.validate, name='validate'),
path('validate/check', views.get_guest_info, name="guest-info"),
path('', views.home, name="home"),
]
|
# Generated by Django 3.2.3 on 2021-05-25 09:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0013_alter_trades_quantity'),
]
operations = [
migrations.AddField(
model_name='trades',
name='test',
... |
#!/usr/bin/python
from six.moves import urllib
from six.moves.html_parser import HTMLParser
import os, re
SITE_URL = "http://codeforces.com"
SAVE_DIR = "submissions/"
download_count = 0
TERM_EMPTY = "\033[0m"
def print_yellow(msg):
TERM_YELLOW = "\033[1;33m"
print TERM_YELLOW + msg + TERM_EMPTY
def print_... |
import numpy as np
import matplotlib.pyplot as plt
from skimage.data import shepp_logan_phantom
from skimage.transform import radon, rescale
image = shepp_logan_phantom()
image = rescale(image, scale=0.4, mode='reflect', multichannel=False)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4.5))
ax1.set_title("Origi... |
#! /usr/bin/env python
'''Algorithms to process trajectories and moving objects'''
import moving
import numpy as np
def extractSpeeds(objects, zone):
speeds = {}
objectsNotInZone = []
import matplotlib.nxutils as nx
for o in objects:
inPolygon = nx.points_inside_poly(o.getPositions().asArray... |
__author__ = 'david_torrejon'
from extract_sentences import give_vocabulary, read_json_file, create_sentence_ds, build_glove_dictionary
from model_simple_rnn import paper_model
from shuffle_data import get_test_train_sets
from embeddings import create_embeddings
from tbir_project_data import load_data
import numpy as... |
class Variable:
'''
Elementary variable for a polynomial.
Attributes
----------
name : str
Name of the variable.
index : int (>= 0)
Index of the variable. If equal to 0, the variable will have no index.
_hash : int
Stored (and not computed on the fly) to accelerate c... |
import stud_tkdb as studb
import tkinter as tk
mainWindow = tk.Tk()
mainWindow.title("Student Database Management System")
heading_label = tk.Label(mainWindow, text ="Student Database Management")
heading_label.pack()
label1=tk.Label(mainWindow, text="Enter Name")
label1.pack()
entry1 = tk.Entry(mainWindow)
entry1.... |
# -- encoding:utf-8 --
import numpy as np
import cv2
labels=['dog','cat','panda']
np.random.seed(1)
W=np.random.randn(3,3072)
b=np.random.randn(3)
# print(W)
# print(b)
orig=cv2.imread('timg.jpg')
image=cv2.resize(orig,(32,32)).flatten()
print(image)
scores=W.dot(image)+b
print(scores)
for (label,score) in zip(lab... |
class Filter(object):
def __init__(self, filtered):
self._filtered = filtered
def __getattr__(self, attr):
if attr in ['tick', 'step'] + self.filtered_properties:
return self.brightness
return self._filtered.__getattr__(attr)
@property
def filtered_p... |
from PyObjCTools.TestSupport import TestCase, min_os_level
import NaturalLanguage
class TestNLTagScheme(TestCase):
def test_typed_enum(self):
self.assertIsTypedEnum(NaturalLanguage.NLTagScheme, str)
self.assertIsTypedEnum(NaturalLanguage.NLTag, str)
self.assertIsTypedEnum(NaturalLanguage.N... |
# coding: utf-8
PRICE_SUPPORT_TYPE = {
1: u'充值',
2: u'新购卡'
}
CARD_TYPE = {
1: u'次卡',
2: u'储值卡',
3: u'期限卡'
}
PAYMENT = {
1: u'现金支付',
2: u'刷卡支付',
3: u'转账支付',
4: u'支付宝二维码支付',
5: u'微信二维码支付'
}
|
from fonctions import sigmoide, tangente
class Reseau:
def __init__(self,name='Reseau_Simple',learn='sigmoide',error=0.001):
"""
# On init le réseau, avec pour paramètres :
- on met un nom à notre reseau
- on choisis la fonction d'activation qu... |
#coding:utf-8
from numpy import *
import operator
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
#数据提取预处理
def file2matrix(filename):
fr = open(filename)
arrayolines = fr.readlines() #一次性读取整个文件内容到一个迭代器以供我们遍历(读取到一个list中,以供使用,比较方便)
numberoflines = len(arrayolines)
returnmat = zeros((numb... |
from collections import deque
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from torch.autograd import Variable
from env_Tmaze import EnvTMaze
import numpy as np
import math
class ReplayMemory(object):
def __init__(self, max_epi_num=50, max_epi_len=300):
# c... |
'''
STAT 640 2016 Fall: Kaggle Competition
Team: LuckyCat
Members: Ruoxuan Tian, Ting Qi
'''
#################################################################
# Libraries
#################################################################
import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
import da... |
__author__ = 'Daoyuan'
from BaseSolution import *
class SingleNumberII(BaseSolution):
def __init__(self):
BaseSolution.__init__(self)
self.fuckinglevel = 8
self.push_test(
params = ([1,2,3,123,3,2,1,1,2,3],),
expects = 123
)
def solution(self, nums):
... |
#!/usr/bin/env python
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
class Read_Access:
def __init__(self):
self.reader = SimpleMFRC522()
self.id=None
self.text=""
def read_access_card(self):
try:
self.id, self.text = self.reader.read()
... |
import csv
heroes = open("education_abroad.csv")
reader = csv.DictReader(heroes, delimiter=";")
data = []
for d in reader:
data.append(d)
heroes.close()
country_set = set() #Hérna safna ég öllum nationalities í eitt set, því þetta er sér tafla
for d in data:
country_set.add(d['Country']) #adda því hér í s... |
#
# ld-script outputer
#
# Copyright (c) 2020, Arm Limited. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
from .. import outputs
from ..box import Memory
import io
import textwrap
import itertools as it
import collections as co
@outputs.output
class LdOutput(outputs.Output):
"""
Name of file ... |
from rest_framework import serializers
from users.models import UserProfile
from django.contrib.auth.models import User
class UserProfileSerializer(serializers.ModelSerializer):
# id = serializers.IntegerField(required=False)
# sub_cateory_name = serializers.SerializerMethodField()
class Meta:
m... |
#! /usr/bin/env python
"""
Get the list of IGSs with abundance across samples and # of IGSs with different
coverage spectrum
% scripts/seperate_IGS.py <spectrum file> <MAP file>
Use '-h' for parameter help.
There are two output files - *.IGS_abund and *.IGS
Firstly, get the number of different IGSs by dividing sum ... |
"""pyblog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
import datetime, random
import string
import sys
import helper
def get_random_string(length):
chars = "".join( [random.choice(string.letters) for i in xrange(length)] )
return chars
def get_random_url():
return "http://www." + get_random_string(6) + ".com"
num_users = int(sys.argv[1])
num_stories = int(sys.argv[2... |
from core import run_loop, Entity, style
def game(state, press):
mut_state = state
if press == "q":
mut_state["running"] = False
if press == "w":
mut_state["entities"]["player"].y -= 1
if press == "d":
mut_state["entities"]["player"].x += 1
if press == "s":
mut_state["entities"]["player"].y +=... |
from django.urls import path
from .views import PostListView,PostDetailView,PostCreateView,PostUpdateView,PostDeleteView,UserPostListView,QuestionListView,CityListView,SecretPostListView
from . import views
# from django.conf import settings
# from django.conf.urls.static import static
urlpatterns = [
path('', Pos... |
from datetime import datetime, timedelta
import gzip
import json
import logging
from queue import Queue, Empty
import random
import re
import struct
import time
from coapthon.messages.message import Message
from coapthon import defines
from coapthon.client.coap import CoAP
from coapthon.messages.request import Request... |
from flask import Flask, render_template, jsonify, request
import pymysql
from flask_restful import Resource, Api
from flask_mysqldb import MySQL,MySQLdb
import json
app = Flask(__name__)
app.secret_key = "gucciruable"
app.config ['MYSQL_HOST'] = 'localhost'
app.config ['MYSQL_USER'] = 'root'
app.config ['MYSQL_PA... |
import time
import onionGpio
sleepTime = 0.5
gpio0 = onionGpio.OnionGpio(0)
gpio0.setOutputDirection(0)
ledValue = 1
while 1:
print(ledValue)
gpio0.setValue(ledValue)
if ledValue == 1:
ledValue = 0
else:
ledValue = 1
time.sleep(sleepTime)
|
from src import app, db
from src.api.models.task import Task
from faker import Faker
import json
import unittest
class TaskView(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
self.faker = Faker()
self.base_url = 'http://localhost:5000/api/tasks'
self.task = {
'title': self.faker.se... |
# -*- coding:utf-8 -*-
from .trainer import Trainer
class LocalTrainer(Trainer):
"""
"""
def __init__(self, *args, **kargs):
Trainer.__init__(self, *args, **kargs)
def _variable_weights_init(self):
pass
def _optimizer_update(self):
self.optimzer.update()
|
#Importing Libraires
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from nltk.corpus import stopwords
import re
import string
import emoji
from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatizer
from sklearn.base import BaseEstimator,TransformerMixin
imp... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
import seaborn as sns
# %matplotlib inline
import statsmodels.api as sm
import statsmodels.stats.api as sms
from scipy.stats import boxcox
compas_... |
# Generated by Django 2.1 on 2018-09-07 11:07
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('mytest', '0005_auto_20180904_1538'),
]
operations = [
m... |
'''
Created on Sep 26, 2017
@author: riteshagarwal
'''
class failover_utils():
def compare_per_node_for_failovers_consistency(self, map1):
"""
Method to check uuid is consistent on active and replica new_vbucket_stats
"""
bucketMap = {}
for bucket in map1.keys():
... |
# ***** BEGIN GPL LICENSE BLOCK *****
#
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distribute... |
from django.contrib import admin
from sample.models import SamplePhoto, SampleAlbum
# Register your models here.
class PhotoInline(admin.StackedInline):
model = SamplePhoto
extra = 2
class SampleAlbumAdmin(admin.ModelAdmin):
inlines = [PhotoInline]
list_display = ('name', 'descriptio... |
from scrapy.crawler import CrawlerProcess
from muziekgebouweindhoven import MuziekGebouwSpider
process = CrawlerProcess(MuziekGebouwSpider)
process.start()
|
from gym_powerworld.envs.voltage_control_env import DiscreteVoltageControlEnv,\
GridMindEnv, GridMindHardEnv, GridMindContingenciesEnv, \
DiscreteVoltageControlSimple14BusEnv, \
DiscreteVoltageControlGenState14BusEnv, \
DiscreteVoltageControlBranchState14BusEnv, \
DiscreteVoltageControlBranchAndGenS... |
'''
Manager entity to launch, coordinate and notify all the results from data analysis tasks that could be involved for a given
electoral process
Created on 26/04/2015
@author: S41nz
'''
from engine.enums.engine_status import EngineStatus
from collection.rawfiles.csv_collector import CSVCollector
from collection.enums... |
import pygame
from pygame.locals import *
from define import WIDTH, HEIGHT
from textbox import TextBox
class PopupWindow:
def __init__(self, screen, text="", buttons=[], target=0, title=""):
self.screen = screen
# 枠線の色
self.outline_color = (50, 50, 50)
center_x, center_y = WIDTH //... |
import os
import logging
import datetime
from collections import defaultdict
from google.appengine.ext import ndb
from base_controller import LoggedInHandler
from consts.account_permissions import AccountPermissions
from consts.client_type import ClientType
from consts.model_type import ModelType
from consts.notifi... |
from django.shortcuts import render, redirect
from django.views import generic
from django.views.generic import ListView
from django.http import HttpResponse
from django.db.models import Q
from .models import *
from .forms import DonativoForm, PrestamoForm
def index(request):
return render(request,'index.html')
... |
# redact.py
# Author: Choong Huh
# Description:
# The program will read each line of the file given by ex.sh script.
# If sensitive information is found, the occurence is recorded in the audit file
# and the offending line is removed.
# Otherwise, the line is written to a new file which serves as the redacted copy.
im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.